commit 12a7825605f844f4fc14ffb89fbddd4b837b9a73 Author: Robert Karl Date: Sun Oct 4 12:55:44 2026 -0700 Import Strata at 6f32ec0 (upstream snapshot, unmodified) Source: https://github.com/Niko1221/Strata, commit 6f32ec070f23ced9f50e704d854d775da52591ab (engine 0.1.39, MIT). Every file is as upstream published it; later commits show exactly what this fork changes. Co-Authored-By: Claude Fable 5.1 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4f341af --- /dev/null +++ b/.dockerignore @@ -0,0 +1,27 @@ +# Keep the image to the source only: everything generated is re-created on +# first start (inside the container or on the /data volume). +.git + +# local Python environment (rebuilt in the image) +.venv/ +__pycache__/ +*.pyc +.pytest_cache/ + +# setup.py outputs and downloads (engine, packs, models, logs) +/engine/ +/build/ +/build*/ +/dist/ +/packs/ +/mtp/ +/models/ +/Strata-data/ +third_party/llama.cpp/ +third_party/*.zip +*.done +*.log +strata-*.json +strata-*.txt +run-*.sh +run-*.bat diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..466d97e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# Frozen prompts are hashed byte for byte (manifest sha256): never convert their line endings. +bench/prompts/** -text + +# launchers keep their platform line endings wherever the repository is cloned +*.sh text eol=lf +*.bat text eol=crlf + +# copies of real packs' native_experts.txt, parsed byte for byte by tests/core/expert_layout_test.cpp +tests/data/native_experts/** -text diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..35b26a9 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +buy_me_a_coffee: strataengine diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8bce537 --- /dev/null +++ b/.gitignore @@ -0,0 +1,58 @@ +# Generated, not source: deterministic build products of tools/ (see docs/). +# tiny-qwen4exp.gguf is ~113 MB, over GitHub's 100 MB file limit -- regenerate with +# python tools/make_tiny_model.py +bench/tiny-*.gguf +bench/wide-*.gguf +bench/micro/*.exe +bench/micro/*.obj +bench/micro/*.bin +bench/micro/*.dll +bench/micro/*.txt +*.log +build*/ +pack/ +logs/ +__pycache__/ +.pytest_cache/ +*.pyc + +# plan v0.3 P1 (repository hygiene, review E1): profiler captures and large diagnostic dumps stay out of git. +*.nsys-rep + +# Pi harness metadata (local session state, not project source) +*.sqlite +*.npz +*.occ1 +td.log + +# created by setup.py on the user's machine +/.venv/ +/build/ +/third_party/llama.cpp +/models/ +/packs/ +/mtp/ +/run-*.bat +/run-*.sh +/strata-*.json +/strata-*.log +/build-strata.bat +/build-strata-cuda12.bat +/build-cuda12/ +/.strata-mcp/ + +# image encoder (setup.py --vision): build output and the generated build script +build-vision*/ +build-vision.bat +build-vision-cuda12.bat + +# setup.py outputs (engine, downloads) and release builds +/engine/ +/engine-cuda12/ +/build-release*/ +/dist/ +*.done +/third_party/*.zip + +/.ccache/ +/.rocm-win/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..3bcf107 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,23 @@ +# AGENTS.md + +Strata runs the Qwen3.8-Flash-Next mixture-of-experts model (and its Coder, Swift 1.5 and Unsloth variants) on a +normal PC: one NVIDIA or AMD graphics card plus system RAM, on Windows or Linux. It has a C++/CUDA/HIP engine +(`src/`, `include/`), a Python server with an OpenAI- and Anthropic-compatible API and a web app (`serve/`), and a +one-click installer (`setup.py`, started by `START-HERE.bat` / `setup.sh`). + +## Installing Strata for a user + +Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**: check the PC, pick the model by RAM, run setup non-interactively, +start and verify the server, and connect the user's apps. Never expose the server beyond `127.0.0.1` without +`--api-key`. As an alternative to shell commands, Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md)) +offers the same steps as tools. + +## Working on the code + +- How the engine works, every measured number, the API and all settings: [docs/DETAILS.md](docs/DETAILS.md) and + the [paper](docs/paper/Strata-Paper.pdf). +- AMD (HIP) build and validation: [docs/AMD_HIP.md](docs/AMD_HIP.md); multi-GPU: [docs/MULTI_GPU.md](docs/MULTI_GPU.md). +- Setup's own tests run without a GPU or downloads: `python tools/test_setup_.py` (for example + `tools/test_setup_amd.py`, `tools/test_setup_choices.py`). +- Keep the docs' style: plain words, measured numbers with what they were measured on, no claims without a + measurement. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..0121bb0 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,1254 @@ +# 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) +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) + +# ---- 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) + # #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) + 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 (GPU, + # synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906) + if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) + add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu) + target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target}) + 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) + 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) + + 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) + + # 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() + if(STRATA_GGML_DIR) + add_subdirectory(${STRATA_GGML_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL) + else() + include(FetchContent) + FetchContent_Declare(strata_llamacpp + GIT_REPOSITORY https://github.com/ggml-org/llama.cpp.git + GIT_TAG 3cf03257f219afbe7334045ff7c6a06ac68c627d + GIT_SHALLOW FALSE) + FetchContent_GetProperties(strata_llamacpp) + if(NOT strata_llamacpp_POPULATED) + FetchContent_Populate(strata_llamacpp) + endif() + add_subdirectory(${strata_llamacpp_SOURCE_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL) + endif() + # 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) + set(_strata_mmq_cuda_types ${_strata_mmq_types}) + if(STRATA_MMQ_KQUANTS) + list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1) + endif() + foreach(_t IN LISTS _strata_mmq_cuda_types) + target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) + 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) + 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() + add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min) + # #290: the BF16 token embedding (--embd-gguf) gathered and dequantized bit for bit + add_test(NAME native_expert_parity_bf16_embd COMMAND native_expert_parity --bf16-embd) + # a pair without GPU kernels (Q6_K gate/up) is refused by native_expert_supported, not run + add_test(NAME native_expert_parity_refuses_q6_K COMMAND native_expert_parity --synthetic q6_K/q8_0) + set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE) + 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() diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6b62dae --- /dev/null +++ b/Dockerfile @@ -0,0 +1,115 @@ +# syntax=docker/dockerfile:1 +# +# Strata: Qwen3.8-Flash-Next on NVIDIA GPUs (RTX 30/40/50, 12+ GB VRAM; two or +# three cards can share one model, 8 GB each - docs/MULTI_GPU.md). +# +# The engine is compiled during docker build, so the first container start only +# downloads the model (~70 GB) and starts the server. docker build has no GPU, +# so the CUDA architectures are fixed here instead of read from nvidia-smi: the +# engine is a fat binary with a cubin per listed arch, and the runtime picks the +# one matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster +# build; a card outside the set needs a rebuild with its own arch. +# +# Build: +# docker build -t strata . +# docker build -t strata --build-arg CUDA_ARCHITECTURES=89 . # RTX 40 only +# +# Run (host needs an NVIDIA driver >= 580 and nvidia-container-toolkit): +# docker run --rm --gpus all \ +# -p 8080:8080 \ +# --ulimit memlock=-1 \ +# -v strata-data:/data \ +# -e MODEL=IQ2_XS \ +# strata +# +# Setup choices are env vars, read by docker-entrypoint.sh: FAMILY, MODEL, CONTEXT, +# VISION (no | yes | cpu), KV (int8 | q4_0 | k8v4), GPU (one card) or GPUS ("0,2" +# or "all", with LAYER_SPLIT), LOW_RAM (auto | on | off), HOST, PORT, API_KEY. +# +# Only the model files, the prepared pack, the MTP layer and the install config +# live in the /data volume; the engine is part of the image. Strata loads 32-62 GB +# into RAM, so a capped container needs -e LOW_RAM=on: setup.py reads the RAM from +# /proc/meminfo, which here is the host's total, not the container's limit. Add an +# API key before exposing the port to a network: -e API_KEY=. Pass +# -e REINSTALL=1 to change the model settings later. +# +# --gpus all on a host with two usable cards: setup takes both (the layer split is +# its recommended default). Pin one card with -e GPU=0, or name them with +# -e GPUS=0,2. A volume set up for one card switches to the pair on its first start +# on a two-card host unless GPU or GPUS pins it. LOW_RAM=on runs on one card. + +FROM nvidia/cuda:13.0.0-devel-ubuntu24.04 + +# STRATA_EXECV=1: setup.py replaces itself with the server, so the server is PID 1 +# and docker stop's SIGTERM reaches it (see setup.start). Normal Linux starts, which +# don't set it, keep spawning the server as a child. +ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 LANG=C.UTF-8 STRATA_EXECV=1 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential ca-certificates curl git libatomic1 libgomp1 \ + python3 python3-pip python3-venv unzip \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /opt/strata +COPY . . + +# RTX 20 (75), RTX 30 (86), RTX 40 (89), RTX 50 (120), plus 80 for A-series. CMakeLists +# refuses anything below 75. BUILD_VISION=0 skips the image encoder build. +ARG CUDA_ARCHITECTURES=75;80;86;89;120 +ARG BUILD_VISION=1 + +RUN python3 -m venv .venv \ + && .venv/bin/pip install --no-cache-dir --upgrade pip \ + && .venv/bin/pip install --no-cache-dir -r requirements.txt \ + && chmod +x setup.sh docker-entrypoint.sh + +# llama.cpp at the pinned commit, then the engine and the image encoder, built +# exactly the way setup.py builds them. BUILD.json is what setup.py reads to +# decide whether an engine is current: source=local with a matching src hash +# means the first start reuses it instead of recompiling. +RUN .venv/bin/python - <<'PYEOF' +import json, os, pathlib, shutil +import setup + +llama = setup.get_llama_cpp() +nvcc, _ = setup.find_nvcc() +arch = os.environ.get("CUDA_ARCHITECTURES", "75;80;86;89;120").strip().strip('"').replace(",", ";") +vision = "gpu" if os.environ.get("BUILD_VISION", "1") == "1" else "none" + +setup.cmake_build(setup.ROOT, setup.ROOT / "build", "strata", + ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", + f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}", + f"-DSTRATA_GGML_DIR={llama}"], None, "build-strata.bat") +if vision != "none": + setup.cmake_build(setup.ROOT / "tools" / "vision", setup.ROOT / "build-vision", "strata-vision", + [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=ON", + f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}"], None, "build-vision.bat") + +eng = setup.ROOT / "engine" +eng.mkdir(exist_ok=True) +shutil.copy2(setup.ROOT / "build" / setup.EXE, eng / setup.EXE) +if vision != "none": + shutil.copy2(setup.ROOT / "build-vision" / "bin" / setup.VEXE, eng / setup.VEXE) +bindir = pathlib.Path(nvcc).parent +meta = {"source": "local", "version": setup.source_version(), + "archs": [int(a.split("-")[0]) for a in arch.split(";") if a.split("-")[0].isdigit()], "vision": vision, + "cuda_dirs": [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()], + "src": setup.source_hash(setup.ENGINE_SOURCES), + "vision_src": setup.source_hash(setup.VISION_SOURCES) if vision != "none" else None} +(eng / "BUILD.json").write_text(json.dumps(meta, indent=1)) +PYEOF + +# the cmake trees are build-time only; the engine itself is what the container needs +RUN rm -rf build build-vision + +VOLUME ["/data"] +EXPOSE 8080 + +# /health is answered before the API key gate, so it works with or without one. +# The port only opens after the model loads (1-3 minutes, longer on a first run), +# so the start period is generous: a too short one marks a still-loading container +# unhealthy and a restart policy would kill it mid-download. +HEALTHCHECK --interval=30s --timeout=5s --start-period=600s --retries=3 \ + CMD curl -fs "http://127.0.0.1:${PORT:-8080}/health" || exit 1 + +ENTRYPOINT ["./docker-entrypoint.sh"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6687a42 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +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/README.de.md b/README.de.md new file mode 100644 index 0000000..e400395 --- /dev/null +++ b/README.de.md @@ -0,0 +1,221 @@ +

Strata

+ +[English](README.md) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · **Deutsch** · [Français](README.fr.md) · [Español](README.es.md) · [Português](README.pt-BR.md) + +

Ein KI-Modell mit 125 Milliarden Parametern auf deinem eigenen Gaming-PC
+NVIDIA- oder AMD-Grafikkarte (ab 12 GB) · Windows oder Linux · kostenlos und Open Source

+ +

Ein Voxel-Pagodengarten, den das Modell in Strata geschrieben hat, läuft im Browser
+Ein Voxel-Pagodengarten aus einem einzigen Prompt, auf einer RTX 5070 mit Strata (IQ3_S, 128K Kontext) · +ganzes Video (49 s)

+ +Strata lässt **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** auf einem normalen PC laufen. +Das ist ein großes, kluges KI-Modell, das sonst meist einen Server braucht. Es chattet, schreibt Code, versteht +Bilder und arbeitet mit deinen Apps und Coding-Agents zusammen. Nichts verlässt deinen PC. + +## Wie schnell ist es? + +Wir haben es auf zwei ganz normalen Gaming-PCs gemessen. Ein Token ist etwa ¾ eines Wortes. + +- **Schreibt Antworten:** wie schnell die Antwort in einem kurzen Chat erscheint. 60 Tokens pro Sekunde sind + schneller, als du lesen kannst. +- **Liest deinen Prompt:** wie schnell es aufnimmt, was du schickst (hier ein Dokument, Code oder Chatverlauf mit + 32K Tokens). + + + + +
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+ +| Größe | Schreibt Antworten | Liest deinen Prompt | +| --- | ---: | ---: | +| **Q2_0** | 94 Tokens/s | 2,650 Tokens/s | +| **IQ2_XS** | 79 Tokens/s | 2,090 Tokens/s | +| **IQ3_XXS** | 62 Tokens/s | 1,750 Tokens/s | +| **IQ3_S** | 53 Tokens/s | 1,620 Tokens/s | +| **Coder** | 55 Tokens/s | 2,180 Tokens/s | + + + +| Größe | Schreibt Antworten | Liest deinen Prompt | +| --- | ---: | ---: | +| **Q2_0** | 60 Tokens/s | 1,160 Tokens/s | +| **IQ2_XS** | 52 Tokens/s | 1,110 Tokens/s | +| **Coder** | 44 Tokens/s | 1,420 Tokens/s | + +
+ +NVIDIA: Q2_0 mit Engine 0.1.36, die anderen Zeilen mit 0.1.26 (4K Antworten, 32K Prompts). Die vollständigen +Tabellen stehen in [DETAILS.md](docs/DETAILS.md#speed-measured). Eine Karte mit mehr VRAM ist schneller: Eine +RTX 3090 (24 GB) sollte etwa 100-140 Tokens pro Sekunde schreiben. Lange Chats und andere Karten: +[Tempo jedes Modells](docs/MODELS.md#how-fast-is-each-size), [Ergebnisse aus der Community](docs/COMMUNITY_BENCHMARKS.md). + +

Buy Me A Coffee
+Strata ist kostenlos. Wenn es auf deinem PC gut läuft, hält ein Kaffee die Arbeit daran am Laufen.

+ +## Was du brauchst + +| | | +| --- | --- | +| **Grafikkarte** | **NVIDIA** GeForce RTX 20, 30, 40 oder 50 Serie, oder **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 oder RX 6800 / 6900 Serie. Sie braucht **12 GB VRAM oder mehr**. | +| **RAM** | 32 GB oder mehr. Dein RAM entscheidet, [welches Modell](#welches-modell-soll-ich-nehmen) passt. Mit 64 GB laufen alle Größen. | +| **Festplatte** | Etwa 80 GB frei. Nimm wenn möglich eine SSD: Der erste Start geht dann viel schneller. | +| **System** | Windows 10 / 11 oder Linux und ein aktueller Grafiktreiber von NVIDIA oder AMD. | + +Alles andere richtet der Installer ein. Zwei oder drei Karten können sich das Modell teilen ([Multi-GPU](docs/MULTI_GPU.md)). + +Experimentell, von Community-Mitgliedern auf ihren eigenen Rechnern geschrieben und getestet: + +- **Ältere Grafikkarten** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT): [Ältere GPUs](docs/OLDER_GPUS.md). +- **Intel Arc**, unter Linux aus dem Quellcode gebaut: [Intel Arc](docs/INTEL_ARC.md). +- **Ältere Prozessoren ohne AVX2**: Sie funktionieren, aber langsam. [Ältere CPUs](docs/INSTALL.md#older-cpus-experimental). + +Die vollständige Liste: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). + +## Installieren + +### Lass deine KI es einrichten + +Nutzt du einen KI-Coding-Assistenten (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Füge dort diesen Text ein: + +```text +Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +``` + +Er prüft deine Grafikkarte, deinen RAM und deine Festplatte und wählt das passende Modell. Dann installiert und +startet er es und sagt dir, wie du deine Apps verbindest. KI-Tools können Strata auch über seinen +[MCP-Server](docs/MCP_SERVER.md) installieren, starten und stoppen. + +### Oder mach es selbst + +[Lade Strata herunter](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) und entpacke es (oder nutze +`git clone`). **Windows:** Doppelklick auf **`START-HERE.bat`**. **Linux:** Führe im Strata-Ordner **`./setup.sh`** aus. + +Die Schritte sind für NVIDIA und AMD gleich. Der Installer erkennt deine Karte und richtet die passende Engine +dafür ein. Er stellt dir ein paar Fragen: + +- welches Modell und welche Größe, +- wie viel Kontext (wie viel Text sich das Modell merkt), +- ob es Bilder lesen soll. + +Drück jedes Mal Enter, um die empfohlene Antwort zu nehmen. Dann lädt er das Modell herunter (etwa 70 GB) und +startet es. Bricht der Download ab, starte ihn einfach neu: Er macht dort weiter, wo er aufgehört hat. Dein Browser +öffnet die Strata-App unter `http://127.0.0.1:8080`. + +> **Während das Modell startet, kann dein PC 1-3 Minuten langsam sein oder nicht reagieren** (beim ersten Mal am +> längsten). Strata lädt 35-55 GB in deinen RAM und reserviert einen Teil davon für die Grafikkarte. Das ist normal. +> Warte und schließ das Fenster nicht. Im Fenster siehst du, was Strata gerade tut. + +**Beim nächsten Mal** startest du wieder `START-HERE.bat` (oder `./setup.sh`). Es startet sofort und lädt nichts +doppelt herunter. Schließ das Fenster, um das Modell zu stoppen. `UPDATE.bat` (`./update.sh`) aktualisiert Strata, +ohne es zu starten. Updates, Docker, mehrere Karten, wo die Dateien landen und alle Optionen: +[docs/INSTALL.md](docs/INSTALL.md). + +## Welches Modell soll ich nehmen? + +Der Installer empfiehlt eins passend zu deinem RAM. Dasselbe Modell gibt es in mehreren Größen, mehr oder weniger +stark komprimiert. Kleinere Größen sind schneller. Größere sind etwas klüger. + +| Dein RAM | Nimm | Warum | +| --- | --- | --- | +| **32 GB** | **Coder** | passt in 32 GB und ist für Code gemacht (mit einer 24-GB-Karte laufen auch Q2_0 und IQ2_XS) | +| **48 GB** | **IQ2_XS** (oder Q2_0, das schnellste) | die größeren Größen passen nicht | +| **64 GB** | **IQ2_XS** (empfohlen) oder IQ3_XXS / IQ3_S | alle Größen passen; IQ3_S ist das beste und das langsamste | +| **96 GB oder mehr** | **IQ3_S** oder Unsloths UD-IQ4_XS (~4 Bit) | Platz für die größten Größen, auch wenn alles andere offen ist | + +- **[Coder](docs/MODELS.md#coder):** eine Version für Code, bei der die Hälfte der Experten entfernt wurde. Sie + erreicht 91 % des SWE-bench-Verified-Werts des vollen Modells (von ihren Autoren gemessen) und passt in 32 GB RAM. + Außerhalb von Code ist sie schwächer, auch bei chinesischem und anderem CJK-Text (#438). Nimm dafür Q2_0, IQ2_XS + oder IQ3_S, die alle Experten behalten. +- **[Swift 1.5](docs/MODELS.md#swift-15):** ein Fine-Tune, das viel kürzer nachdenkt, bevor es antwortet. Du + bekommst die Antwort früher, bei etwa gleicher Qualität. +- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** die ~4-Bit-Version von Unsloth, in der Qualität + zwischen IQ3_S und UD-Q4_K_XL. 94 GB Download. Mit weniger als ~80 GB RAM liest Strata einen Teil davon während + der Antwort von der SSD, dort ist es also langsamer (eine NVMe-SSD hilft). +- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)** (experimentell): am nächsten am vollen + Modell. Aber Strata liest das meiste davon während der Antwort von der SSD, deshalb schreibt es auf einem PC mit + 64 GB nur 7-8.5 Tokens/s. +- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** Das richtest du von Hand + ein. Es steht nicht im Menü des Installers. + +Größen, Downloads und was wohin passt: [docs/MODELS.md](docs/MODELS.md). Um später ein weiteres Modell +hinzuzufügen, starte `SETUP.bat` (Linux: `./setup.sh --setup`). + +## So benutzt du es + +

Der Monitor-Tab der Strata-App neben einem Coding-Agent
+Der Monitor der Strata-App (links), während ein Coding-Agent den Pagodengarten aus dem Video schreibt (rechts)

+ +- **Im Browser:** Öffne `http://127.0.0.1:8080`. Dort gibt es **Chat**, einen Live-**Monitor** für das Modell und + deine GPU/CPU/RAM und **About** mit den Einstellungen und Adressen. +- **Deine Apps und Coding-Agents:** Füge einen „OpenAI-kompatiblen“ Anbieter mit der Basis-URL + **`http://127.0.0.1:8080/v1`** hinzu. Jeder API-Key und jeder Modellname funktioniert. + - Apps, die die API von Anthropic nutzen: `http://127.0.0.1:8080/v1/messages` (Claude Code: + `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). + - Codex CLI und andere Apps, die die OpenAI Responses API nutzen: `/v1/responses` + ([Einrichtung](docs/DETAILS.md#the-responses-api-and-codex-cli)). +- **Nachdenken:** Wähle **aus, niedrig, mittel oder hoch** im Chat-Menü oder unter „Reasoning Effort“ in deiner + App. Aus ist am schnellsten. Hoch ist am besten für schwierige Fragen. +- **Bilder:** Antworte im Setup mit Ja auf „Images?“. Klick dann im Chat auf **Picture** oder hänge Bilder in deiner + App an. AMD-Karten lesen Bilder unter Linux über den Prozessor; unter Windows geht das noch nicht. +- **Vom Handy oder einem anderen PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Setz immer einen + Key. +- **Eine Anfrage nach der anderen:** Standardmäßig beantwortet Strata eine Anfrage, die anderen warten. Um mehrere + gleichzeitig zu beantworten, setz `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). Auf einer 12-GB-Karte wird + dadurch jede Antwort langsamer. +- **Lange Prompts:** Strata liest die erste Nachricht eines Chats komplett, etwa 1 Minute pro 30,000 Tokens. + Folgenachrichten starten in Sekunden. + +Mehr: [wo deine Chats gespeichert werden](docs/INSTALL.md#where-things-are-stored), [die API](docs/DETAILS.md#using-it). + +## Etwas ist schiefgelaufen? + +- **Mein PC ist beim ersten Start von Strata eingefroren.** Das ist normal, während das Modell lädt. Warte und + schließ das Fenster nicht. Nach 10 Minuten immer noch eingefroren? Starte den PC neu, schließ andere Programme und + versuch es noch einmal, oder nimm eine kleinere Größe. +- **Es hat beim Herunterladen oder Installieren aufgehört.** Starte `START-HERE.bat` (oder `./setup.sh`) noch + einmal. Es macht dort weiter, wo es aufgehört hat. +- **Es ist sehr langsam und die Festplattenlampe blinkt ständig, oder es meldet „the engine stopped + unexpectedly“.** Dein PC hat nicht genug freien RAM. Schließ andere Programme (Browser brauchen viel) oder nimm + eine kleinere Größe (Q2_0 oder IQ2_XS). +- **Es meldet, dass Port 8080 schon belegt ist.** Strata läuft bereits. Such nach seinem Fenster. + +Weitere Probleme und ihre Lösungen: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Kommst du nicht weiter? +Öffne ein [Issue](https://github.com/Niko1221/Strata/issues) und hänge `strata-.log` aus dem Strata-Ordner +an. Du hast ein Sicherheitsproblem gefunden? Melde es vertraulich: [SECURITY.md](SECURITY.md). + +## Wie funktioniert es? + +Modelle wie dieses laufen normalerweise auf Servern mit Hunderten Gigabyte Grafikspeicher. Deine Grafikkarte hat +12-24 GB. Strata bringt das Modell trotzdem unter, indem es **die Arbeit auf deinen ganzen PC verteilt**. Stell dir +eine Küche vor: Was du ständig brauchst, bleibt auf der Arbeitsfläche, der Rest wartet in der Vorratskammer. + +

Die 24,576 Experten des Modells: die meistgenutzten auf der Grafikkarte, alle im RAM, eine Nachschlagetabelle auf der SSD

+ +- **Das Modell ist ein Team aus 24,576 kleinen Spezialisten („Experten“).** Jedes Wort braucht nur 10 davon. +- **Deine Grafikkarte** hält die paar tausend Experten, die am häufigsten gebraucht werden. **Dein RAM** hält alle, + und **dein Prozessor** rechnet gleichzeitig am Rest. **Deine SSD** hält eine große Nachschlagetabelle. + +

Ein kleiner Helfer rät die nächsten Wörter; das große Modell prüft alle auf einmal und behält die richtigen

+ +- **Raten, dann prüfen:** Ein kleiner Helfer rät die nächsten paar Wörter. Das große Modell prüft sie alle auf + einmal. Du bekommst dieselbe Antwort, nur 1.6-1.8x schneller. +- **Lange Texte werden in großen Stücken gelesen** (bis zu 8,192 Tokens auf einmal), mit über 1,000 Tokens pro + Sekunde. + +Die längere Erklärung: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Jeder Teil und seine Zahlen: +[die Details](docs/DETAILS.md#how-it-works) und das [Paper](docs/paper/Strata-Paper.pdf). + +## Danksagung und Lizenz + +Das Modell ist [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) vom Qwen-Team. Komprimiert +wurde es von [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) +und Unsloth. Strata nutzt Teile von [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). Alle Danksagungen: +[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata ist Open Source unter der [MIT-Lizenz](LICENSE). Ein +paar Teile und alle Modelle haben eigene Lizenzen ([welche](docs/HOW_IT_WORKS.md#license)). + +## Strata unterstützen + +Strata ist kostenlos und Open Source. Wenn es dir nützt, kannst du die Entwicklung unterstützen: + +

Buy Me A Coffee

diff --git a/README.es.md b/README.es.md new file mode 100644 index 0000000..936c13d --- /dev/null +++ b/README.es.md @@ -0,0 +1,215 @@ +

Strata

+ +[English](README.md) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · **Español** · [Português](README.pt-BR.md) + +

Ejecuta un modelo de IA de 125 mil millones de parámetros en tu propio PC gaming
+Tarjeta gráfica NVIDIA o AMD (12 GB o más) · Windows o Linux · libre y de código abierto

+ +

Un jardín con una pagoda de vóxeles que escribió el modelo de Strata, funcionando en el navegador
+Un jardín con una pagoda de vóxeles, hecho con un solo prompt en una RTX 5070 con Strata (IQ3_S, contexto de 128K) · +vídeo completo (49 s)

+ +Strata ejecuta **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** en un PC normal. Es un +modelo de IA grande e inteligente que normalmente necesita un servidor. Conversa, escribe código, entiende imágenes +y funciona con tus aplicaciones y agentes de programación. Nada sale de tu PC. + +## ¿Qué velocidad tiene? + +Lo medimos en dos PC gaming normales. Un token equivale más o menos a ¾ de una palabra. + +- **Escribe respuestas:** lo rápido que aparece la respuesta en un chat corto. 60 tokens por segundo es más rápido de lo que puedes leer. +- **Lee tu prompt:** lo rápido que procesa lo que le envías (aquí, un documento, código o historial de chat de 32K tokens). + + + + +
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+ +| Tamaño | Escribe respuestas | Lee tu prompt | +| --- | ---: | ---: | +| **Q2_0** | 94 tokens/s | 2,650 tokens/s | +| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | +| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | +| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | +| **Coder** | 55 tokens/s | 2,180 tokens/s | + + + +| Tamaño | Escribe respuestas | Lee tu prompt | +| --- | ---: | ---: | +| **Q2_0** | 60 tokens/s | 1,160 tokens/s | +| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | +| **Coder** | 44 tokens/s | 1,420 tokens/s | + +
+ +NVIDIA: Q2_0 con el motor 0.1.36, las demás filas con 0.1.26 (respuestas de 4K, prompts de 32K). Las tablas +completas están en [DETAILS.md](docs/DETAILS.md#speed-measured). Una tarjeta con más VRAM es más rápida: una +RTX 3090 (24 GB) debería escribir unos 100-140 tokens por segundo. Chats largos y otras tarjetas: +[velocidad de cada modelo](docs/MODELS.md#how-fast-is-each-size), [resultados de la comunidad](docs/COMMUNITY_BENCHMARKS.md). + +

Buy Me A Coffee
+Strata es gratis. Si funciona bien en tu PC, un café ayuda a seguir trabajando en él.

+ +## Qué necesitas + +| | | +| --- | --- | +| **Tarjeta gráfica** | **NVIDIA** GeForce serie RTX 20, 30, 40 o 50, o **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 o serie RX 6800 / 6900. Necesita **12 GB de VRAM o más**. | +| **RAM** | 32 GB o más. Tu RAM decide [qué modelo](#qué-modelo-elijo) cabe. Con 64 GB funcionan todos los tamaños. | +| **Disco** | Unos 80 GB libres. Usa un SSD si puedes: el primer arranque es mucho más rápido. | +| **Sistema** | Windows 10 / 11 o Linux, y un controlador gráfico actual de NVIDIA o AMD. | + +El instalador prepara todo lo demás. Dos o tres tarjetas pueden repartirse el modelo ([multi-GPU](docs/MULTI_GPU.md)). + +Experimental, escrito y probado por miembros de la comunidad en sus propios equipos: + +- **Tarjetas gráficas antiguas** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT): [Older GPUs](docs/OLDER_GPUS.md). +- **Intel Arc**, compilado desde el código fuente en Linux: [Intel Arc](docs/INTEL_ARC.md). +- **Procesadores antiguos sin AVX2**: funcionan, pero despacio. [Older CPUs](docs/INSTALL.md#older-cpus-experimental). + +La lista completa: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). + +## Instalación + +### Deja que tu IA lo instale + +¿Usas un asistente de programación con IA (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Pega esto en él: + +```text +Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +``` + +Revisa tu tarjeta gráfica, tu RAM y tu disco, y elige el modelo que cabe. Luego lo instala, lo arranca y te explica +cómo conectar tus aplicaciones. Las herramientas de IA también pueden instalar, arrancar y detener Strata con su +[servidor MCP](docs/MCP_SERVER.md). + +### O hazlo tú mismo + +[Descarga Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) y descomprímelo (o usa `git clone`). +**Windows:** haz doble clic en **`START-HERE.bat`**. **Linux:** ejecuta **`./setup.sh`** en la carpeta de Strata. + +Los pasos son los mismos para NVIDIA y AMD. El instalador detecta tu tarjeta y prepara el motor adecuado para ella. +Te hace unas pocas preguntas: + +- qué modelo y qué tamaño, +- cuánto contexto (cuánto texto tiene presente el modelo), +- si debe entender imágenes. + +Pulsa Enter cada vez para usar la respuesta recomendada. Después descarga el modelo (unos 70 GB) y lo arranca. Si la +descarga se detiene, vuelve a ejecutarlo: sigue donde lo dejó. Tu navegador abre la aplicación de Strata en +`http://127.0.0.1:8080`. + +> **Mientras el modelo arranca, tu PC puede ir lento o dejar de responder durante 1-3 minutos** (más la primera vez). +> Strata carga 35-55 GB en tu RAM y reserva una parte para la tarjeta gráfica. Es normal. Espera y no cierres la +> ventana. La ventana muestra lo que está haciendo Strata. + +**La próxima vez**, vuelve a ejecutar `START-HERE.bat` (o `./setup.sh`). Arranca enseguida y no descarga nada dos +veces. Cierra su ventana para detener el modelo. `UPDATE.bat` (`./update.sh`) actualiza Strata sin arrancarlo. +Actualizaciones, Docker, varias tarjetas, dónde se guardan los archivos y todas las opciones: [docs/INSTALL.md](docs/INSTALL.md). + +## ¿Qué modelo elijo? + +El instalador te recomienda uno según tu RAM. El mismo modelo viene en varios tamaños, más o menos comprimidos. Los +tamaños pequeños son más rápidos. Los grandes son algo más inteligentes. + +| Tu RAM | Elige | Por qué | +| --- | --- | --- | +| **32 GB** | **Coder** | cabe en 32 GB y está hecho para programar (con una tarjeta de 24 GB también funcionan Q2_0 e IQ2_XS) | +| **48 GB** | **IQ2_XS** (o Q2_0, el más rápido) | los tamaños más grandes no caben | +| **64 GB** | **IQ2_XS** (recomendado), o IQ3_XXS / IQ3_S | caben todos los tamaños; IQ3_S es el mejor y el más lento | +| **96 GB o más** | **IQ3_S**, o el UD-IQ4_XS de Unsloth (~4 bits) | espacio para los tamaños más grandes con todo lo demás abierto | + +- **[Coder](docs/MODELS.md#coder):** una versión para programar a la que se le quitó la mitad de los expertos. Alcanza + el 91% de la puntuación SWE-bench Verified del modelo completo (medido por sus autores) y cabe en 32 GB de RAM. Es + más flojo fuera del código, también con chino y otros textos CJK (#438). Para eso, elige Q2_0, IQ2_XS o IQ3_S, que + conservan todos los expertos. +- **[Swift 1.5](docs/MODELS.md#swift-15):** un ajuste fino que piensa mucho menos tiempo antes de responder. Recibes + la respuesta antes, con más o menos la misma calidad. +- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** la versión de ~4 bits de Unsloth, entre IQ3_S y + UD-Q4_K_XL en calidad. Una descarga de 94 GB. Con menos de ~80 GB de RAM, Strata lee una parte desde el SSD + mientras responde, así que ahí es más lento (un SSD NVMe ayuda). +- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)** (experimental): el más parecido al modelo + completo. Pero Strata lee la mayor parte desde el SSD mientras responde, así que solo escribe 7-8.5 tokens/s en un + PC con 64 GB. +- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** se instala a mano. No está en + el menú del instalador. + +Tamaños, descargas y qué cabe dónde: [docs/MODELS.md](docs/MODELS.md). Para añadir otro modelo más adelante, ejecuta +`SETUP.bat` (Linux: `./setup.sh --setup`). + +## Cómo usarlo + +

La pestaña Monitor de la aplicación de Strata junto a un agente de programación
+El Monitor de la aplicación de Strata (izquierda) mientras un agente de programación escribe el jardín de la pagoda del vídeo (derecha)

+ +- **En el navegador:** abre `http://127.0.0.1:8080`. Tiene **Chat**, un **Monitor** en vivo del modelo y de tu + GPU/CPU/RAM, y **About** con los ajustes y las direcciones. +- **Tus aplicaciones y agentes de programación:** añade un proveedor "compatible con OpenAI" con la URL base + **`http://127.0.0.1:8080/v1`**. Sirve cualquier clave de API y cualquier nombre de modelo. + - Aplicaciones que usan la API de Anthropic: `http://127.0.0.1:8080/v1/messages` (Claude Code: + `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). + - Codex CLI y otras aplicaciones que usan la API Responses de OpenAI: `/v1/responses` + ([configuración](docs/DETAILS.md#the-responses-api-and-codex-cli)). +- **Razonamiento:** elige **off, low, medium o high** en el menú del chat o en el "reasoning effort" de tu aplicación. + Off es lo más rápido. High es lo mejor para preguntas difíciles. +- **Imágenes:** responde que sí a "Images?" en la instalación. Luego haz clic en **Picture** en el chat, o adjunta + imágenes en tu aplicación. Las tarjetas AMD leen imágenes en Linux a través del procesador; en Windows todavía no. +- **Desde tu móvil u otro PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Pon siempre una clave. +- **Una petición cada vez:** por defecto Strata responde una petición y las demás esperan. Para responder varias a la + vez, pon `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). En una tarjeta de 12 GB, cada respuesta va más lenta. +- **Prompts largos:** Strata lee entero el primer mensaje de un chat, más o menos 1 minuto por cada 30,000 tokens. Los + mensajes siguientes empiezan en segundos. + +Más: [dónde se guardan tus chats](docs/INSTALL.md#where-things-are-stored), [la API](docs/DETAILS.md#using-it). + +## ¿Algo salió mal? + +- **Mi PC se congeló la primera vez que arrancó Strata.** Es normal mientras carga el modelo. Espera y no cierres la + ventana. ¿Sigue congelado después de 10 minutos? Reinicia el PC, cierra otros programas y vuelve a intentarlo, o + elige un tamaño más pequeño. +- **Se detuvo durante la descarga o la instalación.** Vuelve a ejecutar `START-HERE.bat` (o `./setup.sh`). Sigue + donde se detuvo. +- **Va muy lento y la luz del disco no deja de parpadear, o dice "the engine stopped unexpectedly".** Tu PC no tiene + suficiente RAM libre. Cierra otros programas (los navegadores usan mucha), o elige un tamaño más pequeño (Q2_0 o + IQ2_XS). +- **Dice que el puerto 8080 ya está en uso.** Strata ya está en marcha. Busca su ventana. + +Más problemas y sus soluciones: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). ¿Sigues atascado? Abre un +[issue](https://github.com/Niko1221/Strata/issues) y adjunta `strata-.log` de la carpeta de Strata. ¿Has +encontrado un problema de seguridad? Infórmalo en privado: [SECURITY.md](SECURITY.md). + +## ¿Cómo funciona? + +Los modelos como este suelen funcionar en servidores con cientos de gigabytes de memoria gráfica. Tu tarjeta gráfica +tiene 12-24 GB. Strata hace que el modelo quepa **repartiendo el trabajo por todo tu PC**. Piensa en una cocina: lo +que usas todo el rato se queda en la encimera, y el resto espera en la despensa. + +

Los 24,576 expertos del modelo: los más usados en la tarjeta gráfica, todos en la RAM y una tabla de consulta en el SSD

+ +- **El modelo es un equipo de 24,576 pequeños especialistas ("expertos").** Cada palabra solo necesita 10 de ellos. +- **Tu tarjeta gráfica** guarda los pocos miles de expertos que más se usan. **Tu RAM** los tiene todos, y **tu + procesador** trabaja con el resto al mismo tiempo. **Tu SSD** guarda una gran tabla de consulta. + +

Un pequeño ayudante adivina las siguientes palabras; el modelo grande las comprueba todas a la vez y se queda con las correctas

+ +- **Adivinar y comprobar:** un pequeño ayudante adivina las siguientes palabras. El modelo grande las comprueba todas + a la vez. Recibes la misma respuesta, 1.6-1.8x antes. +- **Los textos largos se leen en trozos grandes** (hasta 8,192 tokens cada vez), a más de 1,000 tokens por segundo. + +La explicación larga: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Cada parte y sus números: +[los detalles](docs/DETAILS.md#how-it-works) y el [artículo](docs/paper/Strata-Paper.pdf). + +## Créditos y licencia + +El modelo es [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next), del equipo de Qwen. Lo +comprimieron [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) +y Unsloth. Strata usa partes de [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). Todos los créditos: +[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata es de código abierto con la [licencia MIT](LICENSE). +Algunas partes y cada modelo tienen sus propias licencias ([cuáles](docs/HOW_IT_WORKS.md#license)). + +## Apoya a Strata + +Strata es libre y de código abierto. Si te resulta útil, puedes apoyar su desarrollo: + +

Buy Me A Coffee

diff --git a/README.fr.md b/README.fr.md new file mode 100644 index 0000000..22faf7d --- /dev/null +++ b/README.fr.md @@ -0,0 +1,220 @@ +

Strata

+ +[English](README.md) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · [Deutsch](README.de.md) · **Français** · [Español](README.es.md) · [Português](README.pt-BR.md) + +

Faites tourner un modèle d'IA de 125 milliards de paramètres sur votre propre PC de jeu
+Carte graphique NVIDIA ou AMD (12 Go ou plus) · Windows ou Linux · gratuit et open source

+ +

Un jardin de pagode en voxels écrit par le modèle de Strata, qui tourne dans le navigateur
+Un jardin de pagode en voxels, généré en une seule requête sur une RTX 5070 avec Strata (IQ3_S, contexte de 128K) · +vidéo complète (49 s)

+ +Strata fait tourner **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** sur un PC normal. C'est +un grand modèle d'IA, très capable, qui demande d'habitude un serveur. Il discute, écrit du code, lit des images et +fonctionne avec vos applications et vos agents de code. Rien ne quitte votre PC. + +## Quelle est sa vitesse ? + +Nous l'avons mesurée sur deux PC de jeu ordinaires. Un token correspond à environ ¾ d'un mot. + +- **Écrit les réponses :** la vitesse à laquelle la réponse s'affiche dans une courte discussion. 60 tokens par seconde, c'est plus rapide que votre lecture. +- **Lit votre prompt :** la vitesse à laquelle il absorbe ce que vous envoyez (ici un document, du code ou un historique de discussion de 32K tokens). + + + + +
NVIDIA : RTX 5070 (12 Go), Ryzen 5 7600, 64 Go de RAMAMD : RX 9070 XT (16 Go), Ryzen 9 3900X, 47 Go de RAM
+ +| Taille | Écrit les réponses | Lit votre prompt | +| --- | ---: | ---: | +| **Q2_0** | 94 tokens/s | 2,650 tokens/s | +| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | +| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | +| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | +| **Coder** | 55 tokens/s | 2,180 tokens/s | + + + +| Taille | Écrit les réponses | Lit votre prompt | +| --- | ---: | ---: | +| **Q2_0** | 60 tokens/s | 1,160 tokens/s | +| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | +| **Coder** | 44 tokens/s | 1,420 tokens/s | + +
+ +NVIDIA : Q2_0 avec le moteur 0.1.36, les autres lignes avec 0.1.26 (réponses de 4K, prompts de 32K). Les tableaux +complets sont dans [DETAILS.md](docs/DETAILS.md#speed-measured). Une carte avec plus de VRAM va plus vite : une +RTX 3090 (24 Go) devrait écrire environ 100-140 tokens par seconde. Longues discussions et autres cartes : +[vitesse de chaque modèle](docs/MODELS.md#how-fast-is-each-size), [résultats de la communauté](docs/COMMUNITY_BENCHMARKS.md). + +

Buy Me A Coffee
+Strata est gratuit. S'il tourne bien sur votre PC, un café aide à poursuivre le travail.

+ +## Ce qu'il vous faut + +| | | +| --- | --- | +| **Carte graphique** | **NVIDIA** GeForce RTX série 20, 30, 40 ou 50, ou **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 ou série RX 6800 / 6900. Il faut **12 Go de VRAM ou plus**. | +| **RAM** | 32 Go ou plus. Votre RAM décide [quel modèle](#quel-modèle-choisir-) tient. Avec 64 Go, toutes les tailles tournent. | +| **Disque** | Environ 80 Go libres. Prenez un SSD si possible : le premier démarrage est bien plus rapide. | +| **Système** | Windows 10 / 11 ou Linux, avec un pilote graphique NVIDIA ou AMD à jour. | + +L'installateur s'occupe de tout le reste. Deux ou trois cartes peuvent se partager le modèle ([multi-GPU](docs/MULTI_GPU.md)). + +Expérimental, écrit et testé par des membres de la communauté sur leurs propres machines : + +- **Cartes graphiques plus anciennes** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT) : [Older GPUs](docs/OLDER_GPUS.md). +- **Intel Arc**, compilé depuis les sources sous Linux : [Intel Arc](docs/INTEL_ARC.md). +- **Processeurs plus anciens sans AVX2** : ça marche, mais lentement. [Older CPUs](docs/INSTALL.md#older-cpus-experimental). + +La liste complète : [docs/INSTALL.md](docs/INSTALL.md#what-you-need). + +## Installation + +### Laissez votre IA l'installer + +Vous utilisez un assistant de code IA (Claude Code, Cursor, Codex, GitHub Copilot, ...) ? Collez-lui ceci : + +```text +Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +``` + +Il vérifie votre carte graphique, votre RAM et votre disque, et choisit le modèle qui convient. Ensuite il l'installe, +le démarre et vous explique comment connecter vos applications. Les outils d'IA peuvent aussi installer, démarrer et +arrêter Strata grâce à son [serveur MCP](docs/MCP_SERVER.md). + +### Ou faites-le vous-même + +[Téléchargez Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) et décompressez-le (ou faites un `git clone`). +**Windows :** double-cliquez sur **`START-HERE.bat`**. **Linux :** lancez **`./setup.sh`** dans le dossier Strata. + +Les étapes sont les mêmes pour NVIDIA et AMD. L'installateur détecte votre carte et installe le bon moteur pour elle. +Il vous pose quelques questions : + +- quel modèle et quelle taille, +- combien de contexte (la quantité de texte que le modèle garde en tête), +- s'il doit lire les images. + +Appuyez sur Entrée à chaque fois pour garder la réponse recommandée. Ensuite il télécharge le modèle (environ 70 Go) +et le démarre. Si le téléchargement s'arrête, relancez-le : il reprend là où il s'était arrêté. Votre navigateur +ouvre l'application Strata à l'adresse `http://127.0.0.1:8080`. + +> **Pendant le démarrage du modèle, votre PC peut ralentir ou ne plus répondre pendant 1-3 minutes** (plus longtemps la première fois). +> Strata charge 35-55 Go dans votre RAM et en réserve une partie pour la carte graphique. C'est normal. Attendez, et +> ne fermez pas la fenêtre. La fenêtre montre ce que fait Strata. + +**La fois suivante**, relancez `START-HERE.bat` (ou `./setup.sh`). Il démarre tout de suite et ne télécharge rien +deux fois. Fermez sa fenêtre pour arrêter le modèle. `UPDATE.bat` (`./update.sh`) met Strata à jour sans le démarrer. +Mises à jour, Docker, plusieurs cartes, emplacement des fichiers et toutes les options : [docs/INSTALL.md](docs/INSTALL.md). + +## Quel modèle choisir ? + +L'installateur en recommande un selon votre RAM. Le même modèle existe en plusieurs tailles, plus ou moins +compressées. Les petites tailles sont plus rapides. Les grandes sont un peu plus intelligentes. + +| Votre RAM | Prenez | Pourquoi | +| --- | --- | --- | +| **32 Go** | **Coder** | il tient dans 32 Go et il est fait pour le code (avec une carte de 24 Go, Q2_0 et IQ2_XS tournent aussi) | +| **48 Go** | **IQ2_XS** (ou Q2_0, le plus rapide) | les plus grandes tailles ne tiennent pas | +| **64 Go** | **IQ2_XS** (recommandé), ou IQ3_XXS / IQ3_S | toutes les tailles tiennent ; IQ3_S est le meilleur et le plus lent | +| **96 Go ou plus** | **IQ3_S**, ou l'UD-IQ4_XS d'Unsloth (~4 bits) | de la place pour les plus grandes tailles, avec tout le reste ouvert | + +- **[Coder](docs/MODELS.md#coder) :** une version pour le code, avec la moitié des experts en moins. Elle atteint 91 % + du score SWE-bench Verified du modèle complet (mesuré par ses auteurs) et tient dans 32 Go de RAM. Elle est moins + bonne en dehors du code, y compris pour le chinois et les autres textes CJK (#438). Pour ces cas, prenez Q2_0, + IQ2_XS ou IQ3_S, qui gardent tous les experts. +- **[Swift 1.5](docs/MODELS.md#swift-15) :** un fine-tune qui réfléchit bien moins longtemps avant de répondre. Vous + avez la réponse plus tôt, avec à peu près la même qualité. +- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs)** : la version ~4 bits d'Unsloth, entre IQ3_S et + UD-Q4_K_XL en qualité. Un téléchargement de 94 Go. Avec moins de ~80 Go de RAM, Strata en lit une partie depuis + le SSD pendant qu'il répond, il y est donc plus lent (un SSD NVMe aide). +- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)** (expérimental) : le plus proche du modèle + complet. Mais Strata en lit la plus grande partie depuis le SSD pendant qu'il répond, donc il n'écrit que + 7-8.5 tokens/s sur un PC avec 64 Go. +- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs) :** vous l'installez à la main. + Il n'est pas dans le menu de l'installateur. + +Tailles, téléchargements et ce qui tient où : [docs/MODELS.md](docs/MODELS.md). Pour ajouter un autre modèle plus +tard, lancez `SETUP.bat` (Linux : `./setup.sh --setup`). + +## Utilisation + +

L'onglet Monitor de l'application Strata à côté d'un agent de code
+Le Monitor de l'application Strata (à gauche) pendant qu'un agent de code écrit le jardin de pagode de la vidéo (à droite)

+ +- **Dans le navigateur :** ouvrez `http://127.0.0.1:8080`. Vous y trouvez **Chat**, un **Monitor** en direct du + modèle et de votre GPU/CPU/RAM, et **About** avec les réglages et les adresses. +- **Vos applications et agents de code :** ajoutez un fournisseur « OpenAI-compatible » avec l'URL de base + **`http://127.0.0.1:8080/v1`**. N'importe quelle clé API et n'importe quel nom de modèle fonctionnent. + - Applications qui utilisent l'API d'Anthropic : `http://127.0.0.1:8080/v1/messages` (Claude Code : + `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). + - Codex CLI et les autres applications qui utilisent l'API OpenAI Responses : `/v1/responses` + ([configuration](docs/DETAILS.md#the-responses-api-and-codex-cli)). +- **Réflexion :** choisissez **off, low, medium ou high** dans le menu du chat ou dans le « reasoning effort » de + votre application. Off est le plus rapide. High est le meilleur pour les questions difficiles. +- **Images :** répondez oui à « Images? » pendant l'installation. Ensuite cliquez sur **Picture** dans le chat, ou + joignez des images dans votre application. Les cartes AMD lisent les images sous Linux via le processeur ; sous + Windows, pas encore. +- **Depuis votre téléphone ou un autre PC :** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Définissez + toujours une clé. +- **Une requête à la fois :** par défaut, Strata répond à une requête et les autres attendent. Pour répondre à + plusieurs en même temps, mettez `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). Sur une carte de 12 Go, chaque + réponse devient alors plus lente. +- **Longs prompts :** Strata lit en entier le premier message d'une discussion, environ 1 minute pour 30,000 tokens. + Les messages suivants démarrent en quelques secondes. + +Plus d'infos : [où sont stockées vos discussions](docs/INSTALL.md#where-things-are-stored), [l'API](docs/DETAILS.md#using-it). + +## Un problème ? + +- **Mon PC s'est figé au premier démarrage de Strata.** C'est normal pendant le chargement du modèle. Attendez, et ne + fermez pas la fenêtre. Toujours figé après 10 minutes ? Redémarrez le PC, fermez les autres programmes et + réessayez, ou choisissez une taille plus petite. +- **Il s'est arrêté pendant le téléchargement ou l'installation.** Relancez `START-HERE.bat` (ou `./setup.sh`). Il + reprend là où il s'était arrêté. +- **C'est très lent et le voyant du disque clignote sans arrêt, ou il affiche « the engine stopped unexpectedly ».** + Votre PC n'a pas assez de RAM libre. Fermez les autres programmes (les navigateurs en utilisent beaucoup), ou + choisissez une taille plus petite (Q2_0 ou IQ2_XS). +- **Il dit que le port 8080 est déjà utilisé.** Strata tourne déjà. Cherchez sa fenêtre. + +Autres problèmes et leurs solutions : [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Toujours bloqué ? Ouvrez une +[issue](https://github.com/Niko1221/Strata/issues) et joignez `strata-.log` depuis le dossier Strata. Vous +avez trouvé un problème de sécurité ? Signalez-le en privé : [SECURITY.md](SECURITY.md). + +## Comment ça marche ? + +Les modèles comme celui-ci tournent d'habitude sur des serveurs avec des centaines de gigaoctets de mémoire +graphique. Votre carte graphique a 12-24 Go. Strata fait tenir le modèle en **répartissant le travail sur tout votre +PC**. Pensez à une cuisine : ce que vous utilisez tout le temps reste sur le plan de travail, et le reste attend dans +le placard. + +

Les 24,576 experts du modèle : les plus sollicités sur la carte graphique, tous en RAM, une table de correspondance sur le SSD

+ +- **Le modèle est une équipe de 24,576 petits spécialistes (les « experts »).** Chaque mot n'en demande que 10. +- **Votre carte graphique** garde les quelques milliers d'experts les plus utilisés. **Votre RAM** les contient tous, + et **votre processeur** travaille sur les autres en même temps. **Votre SSD** contient une grande table de + correspondance. + +

Un petit assistant devine les mots suivants ; le grand modèle les vérifie tous d'un coup et garde les bons

+ +- **Deviner, puis vérifier :** un petit assistant devine les quelques mots suivants. Le grand modèle les vérifie + tous d'un coup. Vous obtenez la même réponse, 1.6-1.8x plus tôt. +- **Les longs textes sont lus par gros morceaux** (jusqu'à 8,192 tokens à la fois), à plus de 1,000 tokens par seconde. + +L'explication plus longue : [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Chaque partie et ses chiffres : +[les détails](docs/DETAILS.md#how-it-works) et l'[article](docs/paper/Strata-Paper.pdf). + +## Crédits et licence + +Le modèle est [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next), de l'équipe Qwen. Il a été +compressé par [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) +et Unsloth. Strata utilise des parties de [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). Tous les +crédits : [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata est open source sous [licence MIT](LICENSE). +Quelques parties et chaque modèle ont leur propre licence ([lesquelles](docs/HOW_IT_WORKS.md#license)). + +## Soutenir Strata + +Strata est gratuit et open source. S'il vous est utile, vous pouvez soutenir son développement : + +

Buy Me A Coffee

diff --git a/README.ja.md b/README.ja.md new file mode 100644 index 0000000..897322f --- /dev/null +++ b/README.ja.md @@ -0,0 +1,210 @@ +

Strata

+ +[English](README.md) · [简体中文](README.zh-CN.md) · **日本語** · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · [Português](README.pt-BR.md) + +

1,250 億パラメータの AI モデルを、手元のゲーミング PC で動かす
+NVIDIA または AMD のグラフィックカード(12 GB 以上) · Windows または Linux · 無料のオープンソース

+ +

Strata のモデルが書いたボクセルの五重塔の庭。ブラウザで動いている様子
+ボクセルの五重塔の庭。1 回のプロンプトで作成し、RTX 5070 上の Strata(IQ3_S、128K コンテキスト)で実行 · +動画全体(49 秒)

+ +Strata は **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** を普通の PC で動かします。 +これは大きくて賢い AI モデルで、ふつうはサーバーが必要です。チャットをしたり、コードを書いたり、画像を読んだりできます。 +アプリやコーディングエージェントとも連携します。データが PC の外に出ることはありません。 + +## どのくらい速い? + +ごく普通のゲーミング PC 2 台で測りました。1 トークンは英単語のおよそ ¾ です。 + +- **回答の書き出し:** 短いチャットで返答が表示される速さです。毎秒 60 トークンあれば、読むより速く表示されます。 +- **プロンプトの読み込み:** 送った内容を取り込む速さです(ここでは 32K トークンの文書、コード、またはチャット履歴)。 + + + + +
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+ +| サイズ | 回答の書き出し | プロンプトの読み込み | +| --- | ---: | ---: | +| **Q2_0** | 94 tokens/s | 2,650 tokens/s | +| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | +| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | +| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | +| **Coder** | 55 tokens/s | 2,180 tokens/s | + + + +| サイズ | 回答の書き出し | プロンプトの読み込み | +| --- | ---: | ---: | +| **Q2_0** | 60 tokens/s | 1,160 tokens/s | +| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | +| **Coder** | 44 tokens/s | 1,420 tokens/s | + +
+ +NVIDIA:Q2_0 はエンジン 0.1.36、ほかの行は 0.1.26 で測定(回答 4K、プロンプト 32K)。表の全体は +[DETAILS.md](docs/DETAILS.md#speed-measured) にあります。VRAM が多いカードほど速くなります。RTX 3090(24 GB)なら +毎秒およそ 100-140 トークンで書き出せるはずです。長いチャットやほかのカードについて:[モデルごとの速度](docs/MODELS.md#how-fast-is-each-size)、 +[コミュニティの測定結果](docs/COMMUNITY_BENCHMARKS.md)。 + +

Buy Me A Coffee
+Strata は無料です。あなたの PC でうまく動いたら、コーヒー 1 杯の支援が開発を続ける力になります。

+ +## 必要なもの + +| | | +| --- | --- | +| **グラフィックカード** | **NVIDIA** GeForce RTX 20、30、40、50 シリーズ、または **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 シリーズ。**VRAM 12 GB 以上**が必要です。 | +| **RAM** | 32 GB 以上。RAM の量で[使えるモデル](#どのモデルを選べばいい)が決まります。64 GB あればすべてのサイズが動きます。 | +| **ディスク** | 空き容量が約 80 GB。できれば SSD を使ってください。初回の起動がずっと速くなります。 | +| **OS** | Windows 10 / 11 または Linux。NVIDIA または AMD の最新のグラフィックドライバー。 | + +ほかに必要なものはすべてインストーラーが用意します。2 枚や 3 枚のカードでモデルを分担することもできます([マルチ GPU](docs/MULTI_GPU.md))。 + +試験的なサポート。コミュニティのメンバーが自分のマシンで書き、テストしたものです: + +- **古いグラフィックカード**(Tesla P40 / V100、GTX 10、Radeon VII / MI50、RX 6700 XT、RX 5500 XT):[Older GPUs](docs/OLDER_GPUS.md)。 +- **Intel Arc**(Linux でソースからビルド):[Intel Arc](docs/INTEL_ARC.md)。 +- **AVX2 のない古いプロセッサー**:動きますが、遅いです。[Older CPUs](docs/INSTALL.md#older-cpus-experimental)。 + +全リスト:[docs/INSTALL.md](docs/INSTALL.md#what-you-need)。 + +## インストール + +### AI にセットアップしてもらう + +AI コーディングアシスタント(Claude Code、Cursor、Codex、GitHub Copilot など)を使っていますか? これを貼り付けてください: + +```text +Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +``` + +AI がグラフィックカード、RAM、ディスクを調べて、合うモデルを選びます。それからインストールして起動し、 +アプリのつなぎ方を教えてくれます。AI ツールは Strata の [MCP サーバー](docs/MCP_SERVER.md) を通じて、 +Strata のインストール、起動、停止もできます。 + +### 自分でやる + +[Strata をダウンロード](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip)して展開します(または `git clone` します)。 +**Windows:** **`START-HERE.bat`** をダブルクリック。**Linux:** Strata フォルダーで **`./setup.sh`** を実行します。 + +手順は NVIDIA でも AMD でも同じです。インストーラーがカードを見つけて、それに合うエンジンを用意します。 +いくつか質問があります: + +- どのモデルを、どのサイズで使うか +- コンテキストをどのくらいにするか(モデルが覚えておけるテキストの量) +- 画像を読ませるかどうか + +毎回 Enter を押せば、おすすめの答えになります。そのあとモデル(約 70 GB)をダウンロードして起動します。 +ダウンロードが止まったら、もう一度実行してください。続きから再開します。ブラウザーで Strata アプリが +`http://127.0.0.1:8080` に開きます。 + +> **モデルの起動中、1-3 分ほど PC が重くなったり、反応しなくなったりすることがあります**(初回がいちばん長いです)。 +> Strata は 35-55 GB を RAM に読み込み、その一部をグラフィックカード用に固定します。これは正常です。 +> ウィンドウを閉じずに待ってください。Strata が何をしているかはウィンドウに表示されます。 + +**次回からは** `START-HERE.bat`(または `./setup.sh`)をもう一度実行します。すぐに起動し、同じものを 2 回ダウンロードすることはありません。 +モデルを止めるときはウィンドウを閉じます。`UPDATE.bat`(`./update.sh`)を使うと、Strata を起動せずに更新できます。 +更新、Docker、複数のカード、ファイルの保存場所、すべてのオプションについて:[docs/INSTALL.md](docs/INSTALL.md)。 + +## どのモデルを選べばいい + +インストーラーが RAM に合わせてひとつ勧めます。同じモデルにも、圧縮の強さが違う複数のサイズがあります。 +小さいサイズほど速く、大きいサイズほど少し賢くなります。 + +| RAM | 選ぶもの | 理由 | +| --- | --- | --- | +| **32 GB** | **Coder** | 32 GB に収まり、コード向けに作られている(24 GB のカードなら Q2_0 と IQ2_XS も動く) | +| **48 GB** | **IQ2_XS**(または最速の Q2_0) | 大きいサイズは収まらない | +| **64 GB** | **IQ2_XS**(おすすめ)、または IQ3_XXS / IQ3_S | すべてのサイズが収まる。IQ3_S がいちばん賢く、いちばん遅い | +| **96 GB 以上** | **IQ3_S**、または Unsloth の UD-IQ4_XS(約 4-bit) | ほかのものを全部開いたままでも、最大のサイズが入る余裕がある | + +- **[Coder](docs/MODELS.md#coder):** エキスパートを半分取り除いたコーディング向け版です。フルモデルの SWE-bench Verified スコアの + 91% に届き(作者による測定)、32 GB の RAM に収まります。コード以外では弱く、中国語などの CJK のテキストも苦手です(#438)。 + そうした用途には、すべてのエキスパートを残している Q2_0、IQ2_XS、IQ3_S を選んでください。 +- **[Swift 1.5](docs/MODELS.md#swift-15):** 答える前に考える時間がずっと短いファインチューン版です。 + ほぼ同じ品質のまま、答えが早く返ってきます。 +- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** Unsloth の約 4-bit 版で、品質は IQ3_S と UD-Q4_K_XL の間です。 + ダウンロードは 94 GB。RAM が約 80 GB 未満だと、答えている間に Strata がその一部を SSD から読むので遅くなります(NVMe SSD が有効です)。 +- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)**(試験的):フルモデルにいちばん近いものです。 + ただし答えている間、Strata はその大部分を SSD から読むので、64 GB の PC では毎秒 7-8.5 トークンしか書き出せません。 +- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** 手動でセットアップします。 + インストーラーのメニューにはありません。 + +サイズ、ダウンロード、どれがどこに収まるかについて:[docs/MODELS.md](docs/MODELS.md)。あとで別のモデルを追加するには +`SETUP.bat`(Linux:`./setup.sh --setup`)を実行します。 + +## 使い方 + +

Strata アプリの Monitor タブと、その横で動くコーディングエージェント
+Strata アプリの Monitor(左)。コーディングエージェントが動画の五重塔の庭を書いているところ(右)

+ +- **ブラウザーで:** `http://127.0.0.1:8080` を開きます。**Chat**、モデルと GPU/CPU/RAM の様子をリアルタイムで見る **Monitor**、 + 設定とアドレスが載った **About** があります。 +- **アプリやコーディングエージェントから:** 「OpenAI-compatible」プロバイダーを追加し、ベース URL に + **`http://127.0.0.1:8080/v1`** を指定します。API キーとモデル名は何でもかまいません。 + - Anthropic の API を使うアプリ:`http://127.0.0.1:8080/v1/messages`(Claude Code: + `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`)。 + - Codex CLI など OpenAI Responses API を使うアプリ:`/v1/responses` + ([設定方法](docs/DETAILS.md#the-responses-api-and-codex-cli))。 +- **思考(Thinking):** チャットのメニュー、またはアプリの「reasoning effort」で **off、low、medium、high** を選びます。 + off がいちばん速く、high は難しい質問に向いています。 +- **画像:** セットアップで「Images?」に yes と答えます。そのあとチャットで **Picture** をクリックするか、アプリで画像を添付します。 + AMD のカードは、Linux ではプロセッサーを使って画像を読みます。Windows ではまだ読めません。 +- **スマートフォンや別の PC から:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `。キーは必ず設定してください。 +- **リクエストは 1 つずつ:** 初期設定では Strata は 1 つのリクエストに答え、ほかは待ちます。複数に同時に答えるには + `"parallel": 2` を設定します([BATCHING.md](docs/BATCHING.md))。12 GB のカードでは、それぞれの回答が遅くなります。 +- **長いプロンプト:** Strata はチャットの最初のメッセージをすべて読みます。30,000 トークンあたり約 1 分かかります。 + 2 通目以降のメッセージは数秒で始まります。 + +詳しくは:[チャットの保存場所](docs/INSTALL.md#where-things-are-stored)、[API](docs/DETAILS.md#using-it)。 + +## うまくいかないとき + +- **Strata の初回起動で PC が固まった。** モデルの読み込み中はよくあることです。ウィンドウを閉じずに待ってください。 + 10 分たっても固まったまま? PC を再起動し、ほかのプログラムを閉じてもう一度試すか、小さいサイズを選んでください。 +- **ダウンロードやインストールの途中で止まった。** `START-HERE.bat`(または `./setup.sh`)をもう一度実行してください。 + 止まったところから続きます。 +- **とても遅く、ディスクのランプが点滅し続ける。または「the engine stopped unexpectedly」と表示される。** PC の空き RAM が + 足りません。ほかのプログラムを閉じるか(ブラウザーは多く使います)、小さいサイズ(Q2_0 または IQ2_XS)を選んでください。 +- **ポート 8080 がすでに使われていると表示される。** Strata はもう動いています。そのウィンドウを探してください。 + +ほかの問題と解決方法:[docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)。それでも解決しない場合は +[issue](https://github.com/Niko1221/Strata/issues) を作成し、Strata フォルダーにある `strata-.log` を添付してください。 +セキュリティの問題を見つけたら、非公開で報告してください:[SECURITY.md](SECURITY.md)。 + +## しくみ + +このようなモデルは、ふつう数百ギガバイトのグラフィックメモリを持つサーバーで動きます。あなたのグラフィックカードは +12-24 GB です。Strata は **PC 全体で作業を分担する** ことで、モデルを収めています。台所を思い浮かべてください。 +いつも使う道具は調理台に置き、残りは食料庫にしまっておきます。 + +

モデルの 24,576 個のエキスパート:よく使うものはグラフィックカードに、すべては RAM に、ルックアップテーブルは SSD に

+ +- **モデルは 24,576 個の小さな専門家(「エキスパート」)のチームです。** 1 語ごとに必要なのはそのうち 10 個だけです。 +- **グラフィックカード** は、よく使われる数千個のエキスパートを持ちます。**RAM** はすべてのエキスパートを持ち、 + **プロセッサー** が残りを同時に処理します。**SSD** は大きなルックアップテーブルを持ちます。 + +

小さなヘルパーが次の単語を予想し、大きなモデルがまとめて確認して正しいものを残す

+ +- **予想してから確認:** 小さなヘルパーが次の数語を予想します。大きなモデルがそれをまとめて確認します。 + 答えは同じまま、1.6-1.8x 早く返ってきます。 +- **長いテキストは大きなまとまりで読みます**(一度に最大 8,192 トークン)。速さは毎秒 1,000 トークン以上です。 + +もっと詳しい説明:[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md)。各部分とその数値: +[詳細](docs/DETAILS.md#how-it-works)と[論文](docs/paper/Strata-Paper.pdf)。 + +## クレジットとライセンス + +モデルは Qwen チームの [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) です。 +圧縮は [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF)、UkisAI(Swift 1.5)、 +Unsloth によるものです。Strata は [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) の一部を使っています。すべてのクレジット: +[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits)。Strata は [MIT License](LICENSE) のオープンソースです。一部のパーツと +すべてのモデルには、それぞれ独自のライセンスがあります([どれか](docs/HOW_IT_WORKS.md#license))。 + +## Strata を支援する + +Strata は無料のオープンソースです。役に立ったら、開発を支援していただけます: + +

Buy Me A Coffee

diff --git a/README.md b/README.md new file mode 100644 index 0000000..ae464b4 --- /dev/null +++ b/README.md @@ -0,0 +1,211 @@ +

Strata

+ +**English** · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · [Português](README.pt-BR.md) + +

Run a 125-billion-parameter AI model on your own gaming PC
+NVIDIA or AMD graphics card (12 GB or more) · Windows or Linux · free and open source

+ +

A voxel pagoda garden that Strata's model wrote, running in the browser
+A voxel pagoda garden, 1 shot prompt running on an RTX 5070 with Strata (IQ3_S, 128K context) · +full video (49 s)

+ +Strata runs **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** on a normal PC. This is a +large, smart AI model that usually needs a server. It chats, writes code, reads pictures and works with your apps +and coding agents. Nothing leaves your PC. + +## How fast is it? + +We measured it on two ordinary gaming PCs. A token is about ¾ of a word. + +- **Writes answers:** how fast the reply appears in a short chat. 60 tokens per second is faster than you can read. +- **Reads your prompt:** how fast it takes in what you send (here a 32K-token document, code or chat history). + + + + +
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+ +| Size | Writes answers | Reads your prompt | +| --- | ---: | ---: | +| **Q2_0** | 94 tokens/s | 2,650 tokens/s | +| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | +| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | +| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | +| **Coder** | 55 tokens/s | 2,180 tokens/s | + + + +| Size | Writes answers | Reads your prompt | +| --- | ---: | ---: | +| **Q2_0** | 60 tokens/s | 1,160 tokens/s | +| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | +| **Coder** | 44 tokens/s | 1,420 tokens/s | + +
+ +NVIDIA: Q2_0 with engine 0.1.36, the other rows with 0.1.26 (4K answers, 32K prompts). The full tables are in +[DETAILS.md](docs/DETAILS.md#speed-measured). A card with more VRAM is faster: an RTX 3090 (24 GB) should write +about 100-140 tokens per second. Long chats and other cards: [speed of each model](docs/MODELS.md#how-fast-is-each-size), +[community results](docs/COMMUNITY_BENCHMARKS.md). + +

Buy Me A Coffee
+Strata is free. If it runs well on your PC, a coffee keeps the work on it going.

+ +## What you need + +| | | +| --- | --- | +| **Graphics card** | **NVIDIA** GeForce RTX 20, 30, 40 or 50 series, or **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 or RX 6800 / 6900 series. It needs **12 GB of VRAM or more**. | +| **RAM** | 32 GB or more. Your RAM decides [which model](#which-model-should-i-pick) fits. 64 GB runs every size. | +| **Disk** | About 80 GB free. Use an SSD if you can: the first start is much faster. | +| **System** | Windows 10 / 11 or Linux, and a current graphics driver from NVIDIA or AMD. | + +The installer sets up everything else. Two or three cards can share the model ([multi-GPU](docs/MULTI_GPU.md)). + +Experimental, written and tested by community members on their own machines: + +- **Older graphics cards** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT): [Older GPUs](docs/OLDER_GPUS.md). +- **Intel Arc**, built from source on Linux: [Intel Arc](docs/INTEL_ARC.md). +- **Older processors without AVX2**: they work, but slowly. [Older CPUs](docs/INSTALL.md#older-cpus-experimental). + +The full list: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). + +## Install + +### Let your AI set it up + +Do you use an AI coding assistant (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Paste this into it: + +```text +Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +``` + +It checks your graphics card, RAM and disk and picks the model that fits. Then it installs and starts it and tells +you how to connect your apps. AI tools can also install, start and stop Strata through its +[MCP server](docs/MCP_SERVER.md). + +### Or do it yourself + +[Download Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) and unzip it (or `git clone` it). +**Windows:** double-click **`START-HERE.bat`**. **Linux:** run **`./setup.sh`** in the Strata folder. + +The steps are the same for NVIDIA and AMD. The installer finds your card and sets up the right engine for it. It +asks you a few questions: + +- which model and which size, +- how much context (how much text the model keeps in mind), +- whether it should read pictures. + +Press Enter each time for the recommended answer. Then it downloads the model (about 70 GB) and starts it. If the +download stops, run it again: it continues where it left off. Your browser opens the Strata app at +`http://127.0.0.1:8080`. + +> **While the model starts, your PC can be slow or stop responding for 1-3 minutes** (longest the first time). +> Strata loads 35-55 GB into your RAM and locks part of it for the graphics card. This is normal. Wait, and don't +> close the window. The window shows what Strata is doing. + +**Next time**, run `START-HERE.bat` (or `./setup.sh`) again. It starts right away and downloads nothing twice. Close +its window to stop the model. `UPDATE.bat` (`./update.sh`) updates Strata without starting it. Updating, Docker, +several cards, where the files go and every option: [docs/INSTALL.md](docs/INSTALL.md). + +## Which model should I pick? + +The installer recommends one for your RAM. The same model comes in several sizes, compressed more or less. Smaller +sizes are faster. Larger sizes are a bit smarter. + +| Your RAM | Take | Why | +| --- | --- | --- | +| **32 GB** | **Coder** | it fits 32 GB, and it is made for code (with a 24 GB card, Q2_0 and IQ2_XS run too) | +| **48 GB** | **IQ2_XS** (or Q2_0, the fastest) | the larger sizes do not fit | +| **64 GB** | **IQ2_XS** (recommended), or IQ3_XXS / IQ3_S | every size fits; IQ3_S is the best and the slowest | +| **96 GB or more** | **IQ3_S**, or Unsloth's UD-IQ4_XS (~4-bit) | room for the largest sizes with everything else open | + +- **[Coder](docs/MODELS.md#coder):** a coding version with half of the experts removed. It reaches 91% of the full + model's SWE-bench Verified score (measured by its authors) and fits 32 GB of RAM. It is weaker outside code, + including Chinese and other CJK text (#438). For those, take Q2_0, IQ2_XS or IQ3_S, which keep every expert. +- **[Swift 1.5](docs/MODELS.md#swift-15):** a fine-tune that thinks for a much shorter time before it answers. You + get the answer sooner, at about the same quality. +- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** Unsloth's ~4-bit version, between IQ3_S and + UD-Q4_K_XL in quality. A 94 GB download. With less than ~80 GB of RAM, Strata reads part of it from the SSD + while it answers, so it is slower there (an NVMe SSD helps). +- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)** (experimental): the closest to the full + model. But Strata reads most of it from the SSD while it answers, so it writes only 7-8.5 tokens/s on a 64 GB PC. +- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** you set it up by hand. It is + not in the installer's menu. + +Sizes, downloads and what fits where: [docs/MODELS.md](docs/MODELS.md). To add another model later, run +`SETUP.bat` (Linux: `./setup.sh --setup`). + +## Using it + +

The Strata app's Monitor tab next to a coding agent
+The Strata app's Monitor (left) while a coding agent writes the pagoda garden from the video (right)

+ +- **In the browser:** open `http://127.0.0.1:8080`. It has **Chat**, a live **Monitor** of the model and your + GPU/CPU/RAM, and **About** with the settings and addresses. +- **Your apps and coding agents:** add an "OpenAI-compatible" provider with the base URL + **`http://127.0.0.1:8080/v1`**. Any API key and any model name work. + - Apps that use Anthropic's API: `http://127.0.0.1:8080/v1/messages` (Claude Code: + `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). + - Codex CLI and other apps that use the OpenAI Responses API: `/v1/responses` + ([setup](docs/DETAILS.md#the-responses-api-and-codex-cli)). +- **Thinking:** choose **off, low, medium or high** in the chat menu or in your app's "reasoning effort". Off is the + fastest. High is best for hard questions. +- **Pictures:** say yes to "Images?" in setup. Then click **Picture** in the chat, or attach pictures in your app. + AMD cards read pictures on Linux through the processor; on Windows they can't yet. +- **From your phone or another PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Always set a key. +- **One request at a time:** by default Strata answers one request, and the others wait. To answer several at once, + set `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). On a 12 GB card this makes each answer slower. +- **Long prompts:** Strata reads the first message of a chat in full, about 1 minute per 30,000 tokens. Follow-up + messages start in seconds. + +More: [where your chats are stored](docs/INSTALL.md#where-things-are-stored), [the API](docs/DETAILS.md#using-it). + +## Something went wrong? + +- **My PC froze the first time Strata started.** This is normal while it loads the model. Wait, and don't close the + window. Still frozen after 10 minutes? Restart the PC, close other programs and try again, or pick a smaller size. +- **It stopped while downloading or installing.** Run `START-HERE.bat` (or `./setup.sh`) again. It continues where + it stopped. +- **It's very slow and the disk light keeps blinking, or it says "the engine stopped unexpectedly".** Your PC does + not have enough free RAM. Close other programs (browsers use a lot), or pick a smaller size (Q2_0 or IQ2_XS). +- **It says port 8080 is already in use.** Strata is already running. Look for its window. + +More problems and their fixes: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Still stuck? Open an +[issue](https://github.com/Niko1221/Strata/issues) and attach `strata-.log` from the Strata folder. Found a +security problem? Report it privately: [SECURITY.md](SECURITY.md). + +## How does it work? + +Models like this one usually run on servers with hundreds of gigabytes of graphics memory. Your graphics card has +12-24 GB. Strata makes the model fit by **sharing the work across your whole PC**. Think of a kitchen: the things +you use all the time stay on the counter, and the rest waits in the pantry. + +

The model's 24,576 experts: the busiest on the graphics card, all of them in RAM, a lookup table on the SSD

+ +- **The model is a team of 24,576 small specialists ("experts").** Each word needs only 10 of them. +- **Your graphics card** keeps the few thousand experts that are used most often. **Your RAM** holds all of them, + and **your processor** works on the rest at the same time. **Your SSD** holds a big lookup table. + +

A small helper guesses the next words; the big model checks them all at once and keeps the right ones

+ +- **Guess, then check:** a small helper guesses the next few words. The big model checks them all at once. You get + the same answer, 1.6-1.8x sooner. +- **Long texts are read in big pieces** (up to 8,192 tokens at a time), at over 1,000 tokens per second. + +The longer explanation: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Every part and its numbers: +[the details](docs/DETAILS.md#how-it-works) and the [paper](docs/paper/Strata-Paper.pdf). + +## Credits and license + +The model is [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team. It was +compressed by [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) +and Unsloth. Strata uses parts of [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). All credits: +[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata is open source under the [MIT License](LICENSE). A few +parts and every model have their own licenses ([which ones](docs/HOW_IT_WORKS.md#license)). + +## Support Strata + +Strata is free and open source. If it is useful to you, you can support its development: + +

Buy Me A Coffee

diff --git a/README.pt-BR.md b/README.pt-BR.md new file mode 100644 index 0000000..a34dbf2 --- /dev/null +++ b/README.pt-BR.md @@ -0,0 +1,216 @@ +

Strata

+ +[English](README.md) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · **Português** + +

Rode um modelo de IA de 125 bilhões de parâmetros no seu próprio PC gamer
+Placa de vídeo NVIDIA ou AMD (12 GB ou mais) · Windows ou Linux · gratuito e de código aberto

+ +

Um jardim com pagode em voxels que o modelo do Strata escreveu, rodando no navegador
+Um jardim com pagode em voxels, feito com um único prompt numa RTX 5070 com o Strata (IQ3_S, contexto de 128K) · +vídeo completo (49 s)

+ +O Strata roda o **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** num PC comum. É um modelo +de IA grande e inteligente que normalmente precisa de um servidor. Ele conversa, escreve código, entende imagens e +funciona com seus apps e agentes de programação. Nada sai do seu PC. + +## Qual é a velocidade? + +Medimos em dois PCs gamer comuns. Um token equivale a cerca de ¾ de uma palavra. + +- **Escreve respostas:** a velocidade com que a resposta aparece numa conversa curta. 60 tokens por segundo é mais rápido do que você consegue ler. +- **Lê seu prompt:** a velocidade com que ele absorve o que você envia (aqui, um documento, código ou histórico de conversa de 32K tokens). + + + + +
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB de RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB de RAM
+ +| Tamanho | Escreve respostas | Lê seu prompt | +| --- | ---: | ---: | +| **Q2_0** | 94 tokens/s | 2,650 tokens/s | +| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | +| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | +| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | +| **Coder** | 55 tokens/s | 2,180 tokens/s | + + + +| Tamanho | Escreve respostas | Lê seu prompt | +| --- | ---: | ---: | +| **Q2_0** | 60 tokens/s | 1,160 tokens/s | +| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | +| **Coder** | 44 tokens/s | 1,420 tokens/s | + +
+ +NVIDIA: Q2_0 com o engine 0.1.36, as outras linhas com 0.1.26 (respostas de 4K, prompts de 32K). As tabelas +completas estão em [DETAILS.md](docs/DETAILS.md#speed-measured). Uma placa com mais VRAM é mais rápida: uma +RTX 3090 (24 GB) deve escrever cerca de 100-140 tokens por segundo. Conversas longas e outras placas: +[velocidade de cada modelo](docs/MODELS.md#how-fast-is-each-size), [resultados da comunidade](docs/COMMUNITY_BENCHMARKS.md). + +

Buy Me A Coffee
+O Strata é gratuito. Se ele roda bem no seu PC, um café ajuda a manter o trabalho nele.

+ +## Do que você precisa + +| | | +| --- | --- | +| **Placa de vídeo** | **NVIDIA** GeForce RTX séries 20, 30, 40 ou 50, ou **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 ou séries RX 6800 / 6900. Ela precisa de **12 GB de VRAM ou mais**. | +| **RAM** | 32 GB ou mais. Sua RAM decide [qual modelo](#qual-modelo-devo-escolher) cabe. Com 64 GB, roda qualquer tamanho. | +| **Disco** | Cerca de 80 GB livres. Use um SSD se puder: a primeira inicialização fica bem mais rápida. | +| **Sistema** | Windows 10 / 11 ou Linux, e um driver de vídeo atualizado da NVIDIA ou da AMD. | + +O instalador cuida de todo o resto. Duas ou três placas podem dividir o modelo ([multi-GPU](docs/MULTI_GPU.md)). + +Experimental, escrito e testado por membros da comunidade nas próprias máquinas: + +- **Placas de vídeo mais antigas** (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT): [Older GPUs](docs/OLDER_GPUS.md). +- **Intel Arc**, compilado a partir do código-fonte no Linux: [Intel Arc](docs/INTEL_ARC.md). +- **Processadores mais antigos sem AVX2**: funcionam, mas devagar. [Older CPUs](docs/INSTALL.md#older-cpus-experimental). + +A lista completa: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). + +## Instalação + +### Deixe sua IA instalar + +Você usa um assistente de programação com IA (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Cole isto nele: + +```text +Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +``` + +Ele verifica sua placa de vídeo, RAM e disco e escolhe o modelo que cabe. Depois instala, inicia e explica como +conectar seus apps. Ferramentas de IA também podem instalar, iniciar e parar o Strata pelo +[servidor MCP](docs/MCP_SERVER.md) dele. + +### Ou faça você mesmo + +[Baixe o Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) e descompacte (ou use `git clone`). +**Windows:** clique duas vezes em **`START-HERE.bat`**. **Linux:** rode **`./setup.sh`** na pasta do Strata. + +Os passos são os mesmos para NVIDIA e AMD. O instalador encontra sua placa e configura o engine certo para ela. +Ele faz algumas perguntas: + +- qual modelo e qual tamanho, +- quanto contexto (quanto texto o modelo guarda na memória), +- se ele deve entender imagens. + +Aperte Enter em cada uma para usar a resposta recomendada. Depois ele baixa o modelo (cerca de 70 GB) e o inicia. +Se o download parar, rode de novo: ele continua de onde parou. Seu navegador abre o app do Strata em +`http://127.0.0.1:8080`. + +> **Enquanto o modelo inicia, seu PC pode ficar lento ou parar de responder por 1-3 minutos** (mais na primeira vez). +> O Strata carrega 35-55 GB na sua RAM e reserva parte dela para a placa de vídeo. Isso é normal. Espere e não +> feche a janela. A janela mostra o que o Strata está fazendo. + +**Da próxima vez**, rode `START-HERE.bat` (ou `./setup.sh`) de novo. Ele inicia na hora e não baixa nada duas +vezes. Feche a janela para parar o modelo. `UPDATE.bat` (`./update.sh`) atualiza o Strata sem iniciá-lo. +Atualização, Docker, várias placas, onde ficam os arquivos e todas as opções: [docs/INSTALL.md](docs/INSTALL.md). + +## Qual modelo devo escolher? + +O instalador recomenda um de acordo com sua RAM. O mesmo modelo vem em vários tamanhos, mais ou menos comprimidos. +Os tamanhos menores são mais rápidos. Os maiores são um pouco mais inteligentes. + +| Sua RAM | Escolha | Por quê | +| --- | --- | --- | +| **32 GB** | **Coder** | cabe em 32 GB e é feito para código (com uma placa de 24 GB, Q2_0 e IQ2_XS também rodam) | +| **48 GB** | **IQ2_XS** (ou Q2_0, o mais rápido) | os tamanhos maiores não cabem | +| **64 GB** | **IQ2_XS** (recomendado), ou IQ3_XXS / IQ3_S | todos os tamanhos cabem; IQ3_S é o melhor e o mais lento | +| **96 GB ou mais** | **IQ3_S**, ou o UD-IQ4_XS da Unsloth (~4-bit) | espaço para os maiores tamanhos com todo o resto aberto | + +- **[Coder](docs/MODELS.md#coder):** uma versão para programação com metade dos experts removida. Ela alcança 91% + da pontuação do modelo completo no SWE-bench Verified (medido pelos autores) e cabe em 32 GB de RAM. É mais fraca + fora do código, inclusive em chinês e outros textos CJK (#438). Para isso, escolha Q2_0, IQ2_XS ou IQ3_S, que + mantêm todos os experts. +- **[Swift 1.5](docs/MODELS.md#swift-15):** um fine-tune que pensa por bem menos tempo antes de responder. Você + recebe a resposta mais cedo, com quase a mesma qualidade. +- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** a versão de ~4 bits da Unsloth, entre IQ3_S e + UD-Q4_K_XL em qualidade. Um download de 94 GB. Com menos de ~80 GB de RAM, o Strata lê uma parte dele do SSD + enquanto responde, então ali ele fica mais lento (um SSD NVMe ajuda). +- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)** (experimental): o mais próximo do modelo + completo. Mas o Strata lê a maior parte dele do SSD enquanto responde, então ele escreve só 7-8.5 tokens/s num PC + com 64 GB. +- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** você configura à mão. Ele + não está no menu do instalador. + +Tamanhos, downloads e o que cabe onde: [docs/MODELS.md](docs/MODELS.md). Para adicionar outro modelo depois, rode +`SETUP.bat` (Linux: `./setup.sh --setup`). + +## Como usar + +

A aba Monitor do app Strata ao lado de um agente de programação
+O Monitor do app Strata (à esquerda) enquanto um agente de programação escreve o jardim com pagode do vídeo (à direita)

+ +- **No navegador:** abra `http://127.0.0.1:8080`. Lá tem o **Chat**, um **Monitor** ao vivo do modelo e da sua + GPU/CPU/RAM, e o **About** com as configurações e os endereços. +- **Seus apps e agentes de programação:** adicione um provedor "OpenAI-compatible" com a URL base + **`http://127.0.0.1:8080/v1`**. Qualquer chave de API e qualquer nome de modelo funcionam. + - Apps que usam a API da Anthropic: `http://127.0.0.1:8080/v1/messages` (Claude Code: + `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). + - Codex CLI e outros apps que usam a OpenAI Responses API: `/v1/responses` + ([configuração](docs/DETAILS.md#the-responses-api-and-codex-cli)). +- **Raciocínio:** escolha **off, low, medium ou high** no menu do chat ou no "reasoning effort" do seu app. Off é o + mais rápido. High é o melhor para perguntas difíceis. +- **Imagens:** responda sim para "Images?" na instalação. Depois clique em **Picture** no chat, ou anexe imagens no + seu app. Placas AMD entendem imagens no Linux usando o processador; no Windows, ainda não. +- **Do seu celular ou de outro PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `. Sempre defina uma chave. +- **Uma requisição por vez:** por padrão, o Strata responde uma requisição e as outras esperam. Para responder + várias ao mesmo tempo, defina `"parallel": 2` ([BATCHING.md](docs/BATCHING.md)). Numa placa de 12 GB, isso deixa + cada resposta mais lenta. +- **Prompts longos:** o Strata lê a primeira mensagem de uma conversa inteira, cerca de 1 minuto a cada 30,000 + tokens. As mensagens seguintes começam em segundos. + +Mais: [onde suas conversas ficam salvas](docs/INSTALL.md#where-things-are-stored), [a API](docs/DETAILS.md#using-it). + +## Algo deu errado? + +- **Meu PC travou na primeira vez que o Strata iniciou.** Isso é normal enquanto ele carrega o modelo. Espere e não + feche a janela. Ainda travado depois de 10 minutos? Reinicie o PC, feche outros programas e tente de novo, ou + escolha um tamanho menor. +- **Parou durante o download ou a instalação.** Rode `START-HERE.bat` (ou `./setup.sh`) de novo. Ele continua de + onde parou. +- **Está muito lento e a luz do disco não para de piscar, ou aparece "the engine stopped unexpectedly".** Seu PC + não tem RAM livre suficiente. Feche outros programas (navegadores usam muita), ou escolha um tamanho menor (Q2_0 + ou IQ2_XS). +- **Diz que a porta 8080 já está em uso.** O Strata já está rodando. Procure a janela dele. + +Mais problemas e como resolver: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Ainda sem solução? Abra uma +[issue](https://github.com/Niko1221/Strata/issues) e anexe o `strata-.log` da pasta do Strata. Encontrou um +problema de segurança? Informe em particular: [SECURITY.md](SECURITY.md). + +## Como funciona? + +Modelos como este normalmente rodam em servidores com centenas de gigabytes de memória de vídeo. Sua placa de vídeo +tem 12-24 GB. O Strata faz o modelo caber **dividindo o trabalho pelo PC inteiro**. Pense numa cozinha: o que você +usa o tempo todo fica na bancada, e o resto espera na despensa. + +

Os 24,576 experts do modelo: os mais usados na placa de vídeo, todos na RAM, uma tabela de consulta no SSD

+ +- **O modelo é uma equipe de 24,576 pequenos especialistas ("experts").** Cada palavra precisa de só 10 deles. +- **Sua placa de vídeo** guarda os poucos milhares de experts usados com mais frequência. **Sua RAM** guarda todos + eles, e **seu processador** trabalha no resto ao mesmo tempo. **Seu SSD** guarda uma grande tabela de consulta. + +

Um pequeno ajudante adivinha as próximas palavras; o modelo grande confere todas de uma vez e fica com as certas

+ +- **Adivinhar e conferir:** um pequeno ajudante adivinha as próximas palavras. O modelo grande confere todas de + uma vez. Você recebe a mesma resposta, 1.6-1.8x mais cedo. +- **Textos longos são lidos em grandes pedaços** (até 8,192 tokens por vez), a mais de 1,000 tokens por segundo. + +A explicação mais longa: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Cada parte e seus números: +[os detalhes](docs/DETAILS.md#how-it-works) e o [artigo](docs/paper/Strata-Paper.pdf). + +## Créditos e licença + +O modelo é o [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next), da equipe Qwen. Ele foi +comprimido por [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) +e Unsloth. O Strata usa partes do [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). Todos os créditos: +[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). O Strata é de código aberto sob a [MIT License](LICENSE). +Algumas partes e todos os modelos têm licenças próprias ([quais](docs/HOW_IT_WORKS.md#license)). + +## Apoie o Strata + +O Strata é gratuito e de código aberto. Se ele é útil para você, você pode apoiar o desenvolvimento: + +

Buy Me A Coffee

diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..6eb1220 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,199 @@ +

Strata

+ +[English](README.md) · **简体中文** · [日本語](README.ja.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · [Português](README.pt-BR.md) + +

在你自己的游戏电脑上运行 1250 亿参数的 AI 模型
+NVIDIA 或 AMD 显卡(12 GB 及以上)· Windows 或 Linux · 免费开源

+ +

Strata 的模型写出的体素宝塔花园,在浏览器中运行
+体素宝塔花园,一次提示生成,在 RTX 5070 上用 Strata 运行(IQ3_S,128K 上下文)· +完整视频(49 秒)

+ +Strata 能在普通电脑上运行 **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)**。这是一个又大又聪明的 +AI 模型,通常要用服务器才能跑。它能聊天、写代码、看图片,还能配合你的应用和编程智能体一起工作。所有数据都留在你的电脑上。 + +## 速度有多快? + +我们在两台普通的游戏电脑上做了测试。一个 token 大约相当于 ¾ 个英文单词。 + +- **写回答:** 短对话中回复出现的速度。每秒 60 个 token 已经比你的阅读速度还快。 +- **读提示:** 读入你发送内容的速度(这里是一份 32K token 的文档、代码或聊天记录)。 + + + + +
NVIDIA:RTX 5070(12 GB)、Ryzen 5 7600、64 GB 内存AMD:RX 9070 XT(16 GB)、Ryzen 9 3900X、47 GB 内存
+ +| 规格 | 写回答 | 读提示 | +| --- | ---: | ---: | +| **Q2_0** | 94 tokens/s | 2,650 tokens/s | +| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | +| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | +| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | +| **Coder** | 55 tokens/s | 2,180 tokens/s | + + + +| 规格 | 写回答 | 读提示 | +| --- | ---: | ---: | +| **Q2_0** | 60 tokens/s | 1,160 tokens/s | +| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | +| **Coder** | 44 tokens/s | 1,420 tokens/s | + +
+ +NVIDIA:Q2_0 用的是引擎 0.1.36,其他各行用的是 0.1.26(4K 回答,32K 提示)。完整表格见 +[DETAILS.md](docs/DETAILS.md#speed-measured)。显存越大的显卡越快:RTX 3090(24 GB)写回答应该能达到每秒约 +100-140 个 token。长对话和其他显卡的数据:[各模型的速度](docs/MODELS.md#how-fast-is-each-size)、 +[社区测试结果](docs/COMMUNITY_BENCHMARKS.md)。 + +

请我喝杯咖啡
+Strata 是免费的。如果它在你的电脑上跑得不错,请我喝杯咖啡,让这个项目继续下去。

+ +## 你需要什么 + +| | | +| --- | --- | +| **显卡** | **NVIDIA** GeForce RTX 20、30、40 或 50 系列,或 **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 系列。需要 **12 GB 或以上显存**。 | +| **内存** | 32 GB 或以上。内存大小决定能装下[哪个模型](#该选哪个模型)。64 GB 可以运行所有规格。 | +| **硬盘** | 约 80 GB 可用空间。尽量用 SSD:第一次启动会快很多。 | +| **系统** | Windows 10 / 11 或 Linux,以及 NVIDIA 或 AMD 的最新显卡驱动。 | + +其他的都由安装程序搞定。两到三张显卡可以分担同一个模型([多 GPU](docs/MULTI_GPU.md))。 + +实验性支持,由社区成员在自己的机器上编写和测试: + +- **较老的显卡**(Tesla P40 / V100、GTX 10、Radeon VII / MI50、RX 6700 XT、RX 5500 XT):[较老的 GPU](docs/OLDER_GPUS.md)。 +- **Intel Arc**,在 Linux 上从源码构建:[Intel Arc](docs/INTEL_ARC.md)。 +- **不支持 AVX2 的老处理器**:能用,但很慢。[较老的 CPU](docs/INSTALL.md#older-cpus-experimental)。 + +完整列表:[docs/INSTALL.md](docs/INSTALL.md#what-you-need)。 + +## 安装 + +### 让你的 AI 帮你装 + +你在用 AI 编程助手吗(Claude Code、Cursor、Codex、GitHub Copilot 等)?把下面这段粘贴给它: + +```text +Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +``` + +它会检查你的显卡、内存和硬盘,选出合适的模型。然后安装并启动它,再告诉你怎么连接你的应用。AI 工具也可以通过 +Strata 的 [MCP 服务器](docs/MCP_SERVER.md)来安装、启动和停止 Strata。 + +### 或者自己动手 + +[下载 Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) 并解压(或者用 `git clone`)。 +**Windows:** 双击 **`START-HERE.bat`**。**Linux:** 在 Strata 文件夹里运行 **`./setup.sh`**。 + +NVIDIA 和 AMD 的步骤完全一样。安装程序会识别你的显卡,并装好对应的引擎。它会问你几个问题: + +- 用哪个模型、哪个规格, +- 上下文多大(模型能记住多少文字), +- 是否要识别图片。 + +每次直接按回车就是推荐选项。之后它会下载模型(约 70 GB)并启动。如果下载中断了,再运行一次即可:它会从中断的地方继续。 +浏览器会打开 Strata 应用,地址是 `http://127.0.0.1:8080`。 + +> **模型启动时,你的电脑可能会变慢或卡住 1-3 分钟**(第一次最久)。 +> Strata 会把 35-55 GB 加载到内存,并为显卡锁定其中一部分。这是正常的。请耐心等待,不要关闭窗口。 +> 窗口里会显示 Strata 正在做什么。 + +**下次使用时**,再运行一次 `START-HERE.bat`(或 `./setup.sh`)。它会马上启动,已下载的东西不会重复下载。关闭它的窗口就能停止模型。 +`UPDATE.bat`(`./update.sh`)只更新 Strata,不启动。更新、Docker、多张显卡、文件存放位置以及所有选项: +[docs/INSTALL.md](docs/INSTALL.md)。 + +## 该选哪个模型 + +安装程序会根据你的内存推荐一个。同一个模型有几种规格,压缩程度不同。规格越小越快,越大越聪明一些。 + +| 你的内存 | 选择 | 原因 | +| --- | --- | --- | +| **32 GB** | **Coder** | 32 GB 装得下,而且专为代码打造(如果显卡是 24 GB,Q2_0 和 IQ2_XS 也能跑) | +| **48 GB** | **IQ2_XS**(或 Q2_0,最快) | 更大的规格装不下 | +| **64 GB** | **IQ2_XS**(推荐),或 IQ3_XXS / IQ3_S | 所有规格都装得下;IQ3_S 最好,也最慢 | +| **96 GB 或以上** | **IQ3_S**,或 Unsloth 的 UD-IQ4_XS(约 4-bit) | 开着其他程序也能放下最大的规格 | + +- **[Coder](docs/MODELS.md#coder):** 编程版本,去掉了一半专家。它达到完整模型 SWE-bench Verified 分数的 91%(由其作者测得), + 32 GB 内存就能装下。代码以外的能力较弱,包括中文和其他中日韩文本(#438)。这类用途请选 Q2_0、IQ2_XS 或 IQ3_S, + 它们保留了所有专家。 +- **[Swift 1.5](docs/MODELS.md#swift-15):** 一个微调版本,回答前思考的时间短得多。你能更早拿到答案,质量基本不变。 +- **[Unsloth UD-IQ4_XS](docs/MODELS.md#unsloth-ud-iq4_xs):** Unsloth 的约 4-bit 版本,质量介于 IQ3_S 和 UD-Q4_K_XL 之间。 + 下载 94 GB。内存少于约 80 GB 时,Strata 回答时要从 SSD 读取其中一部分,所以会更慢(NVMe SSD 有帮助)。 +- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)**(实验性):最接近完整模型。但 Strata + 回答时要从 SSD 读取其中大部分内容,所以在 64 GB 的电脑上每秒只能写 7-8.5 个 token。 +- **[OrcaRouter 的 Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs):** 需要手动设置,不在安装程序的菜单里。 + +规格、下载以及各配置能装下什么:[docs/MODELS.md](docs/MODELS.md)。以后想再添加模型,运行 +`SETUP.bat`(Linux:`./setup.sh --setup`)。 + +## 使用方法 + +

Strata 应用的 Monitor 标签页,旁边是一个编程智能体
+Strata 应用的 Monitor(左),编程智能体正在写视频里的宝塔花园(右)

+ +- **在浏览器里:** 打开 `http://127.0.0.1:8080`。里面有 **Chat**(聊天)、实时 **Monitor**(监控模型和你的 + GPU/CPU/内存),以及 **About**(设置和地址)。 +- **你的应用和编程智能体:** 添加一个“OpenAI 兼容”的提供商,base URL 填 **`http://127.0.0.1:8080/v1`**。 + API key 和模型名随便填都行。 + - 使用 Anthropic API 的应用:`http://127.0.0.1:8080/v1/messages`(Claude Code: + `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`)。 + - Codex CLI 和其他使用 OpenAI Responses API 的应用:`/v1/responses` + ([设置方法](docs/DETAILS.md#the-responses-api-and-codex-cli))。 +- **思考:** 在聊天菜单或应用的“reasoning effort”里选择 **off、low、medium 或 high**。off 最快, + high 最适合难题。 +- **图片:** 在安装时对“Images?”选是。然后在聊天里点 **Picture**,或在你的应用里附上图片。 + AMD 显卡在 Linux 上通过处理器识别图片;在 Windows 上暂时还不行。 +- **从手机或另一台电脑访问:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `。一定要设置 key。 +- **一次处理一个请求:** 默认情况下 Strata 一次只回答一个请求,其他请求排队等待。想同时回答多个, + 设置 `"parallel": 2`([BATCHING.md](docs/BATCHING.md))。在 12 GB 显卡上,这会让每个回答变慢。 +- **长提示:** Strata 会完整读入对话的第一条消息,大约每 30,000 个 token 需要 1 分钟。之后的消息几秒内就开始回答。 + +更多:[聊天记录存在哪里](docs/INSTALL.md#where-things-are-stored)、[API](docs/DETAILS.md#using-it)。 + +## 出问题了? + +- **Strata 第一次启动时电脑卡死了。** 加载模型时这是正常的。请耐心等待,不要关闭窗口。 + 10 分钟后还卡着?重启电脑,关掉其他程序再试一次,或者换一个更小的规格。 +- **下载或安装时中断了。** 再运行一次 `START-HERE.bat`(或 `./setup.sh`)。它会从中断的地方继续。 +- **非常慢,硬盘灯一直闪,或者提示“the engine stopped unexpectedly”。** 你的电脑可用内存不够。 + 关掉其他程序(浏览器很占内存),或者换一个更小的规格(Q2_0 或 IQ2_XS)。 +- **提示 8080 端口已被占用。** Strata 已经在运行了。找一下它的窗口。 + +更多问题和解决办法:[docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)。还是解决不了?提交一个 +[issue](https://github.com/Niko1221/Strata/issues),并附上 Strata 文件夹里的 `strata-.log`。发现了安全问题? +请私下报告:[SECURITY.md](SECURITY.md)。 + +## 它是怎么工作的? + +这类模型通常运行在拥有数百 GB 显存的服务器上。而你的显卡只有 12-24 GB。Strata 让模型装得下的办法是 +**把工作分摊到整台电脑上**。可以想象一个厨房:常用的东西放在台面上,其余的放在储藏室里。 + +

模型的 24,576 个专家:最常用的在显卡上,全部在内存里,一张查找表在 SSD 上

+ +- **这个模型是由 24,576 个小专家(“experts”)组成的团队。** 每个词只需要其中 10 个。 +- **你的显卡** 存放最常用的几千个专家。**你的内存** 存放全部专家, + **你的处理器** 同时处理其余的部分。**你的 SSD** 存放一张大查找表。 + +

一个小助手猜测接下来的几个词;大模型一次性全部检查,保留正确的

+ +- **先猜,再检查:** 一个小助手先猜接下来的几个词,大模型再一次性检查它们。答案完全一样,但快 1.6-1.8 倍。 +- **长文本分大块读入**(每次最多 8,192 个 token),速度超过每秒 1,000 个 token。 + +更详细的解释:[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md)。每个部分及其数据: +[详细说明](docs/DETAILS.md#how-it-works)和[论文](docs/paper/Strata-Paper.pdf)。 + +## 致谢与许可证 + +模型是 Qwen 团队的 [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)。它由 +[ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF)、UkisAI(Swift 1.5) +和 Unsloth 压缩。Strata 使用了 [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) 的部分代码。完整致谢: +[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits)。Strata 以 [MIT 许可证](LICENSE)开源。少数部分和每个模型 +有各自的许可证([具体是哪些](docs/HOW_IT_WORKS.md#license))。 + +## 支持 Strata + +Strata 免费且开源。如果它对你有用,欢迎支持它的开发: + +

请我喝杯咖啡

diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..94be4ea --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,44 @@ +# Security + +## Reporting a vulnerability + +Please report anything that should not be public until it is fixed **privately**, through GitHub's private +vulnerability reporting: the repository's **Security** tab, **Report a vulnerability** +([direct link](https://github.com/Niko1221/Strata/security/advisories/new)). Say what you found, how to reproduce it +(the request, the config keys involved, the Strata version), and what an attacker gains. We answer there, fix it in +a release, and credit you in the advisory unless you ask us not to. + +Ordinary hardening ideas and findings that are safe to discuss in public are welcome as an +[issue](https://github.com/Niko1221/Strata/issues) (#544 collects audit findings) or as a pull request, which we +review like our own code. + +Supported: the latest release. Fixes go into the next release, not into older ones. + +## What the server exposes + +Strata runs a model on your PC and serves it over HTTP (`serve/server.py`). Out of the box it is reachable from +this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAILS.md) ("From other devices", +"Host names", "Web pages without an API key", "Tools from MCP servers"). + +- **Where it listens.** `127.0.0.1` by default. `--host 0.0.0.0` (or `"host"` in `strata-.json`) opens it to + your network, and the server then warns when no API key is set. +- **API key.** `"api_key"` in the run config (or `STRATA_API_KEY`) is required on `/v1/*` and on every endpoint + that shows the model's state, requests or answers (`/status`, `/metrics`, `/settings`, `/mcp`, `/props`, `/slots`, + `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. Set one before you open the + server to your network or put a tunnel in front of it. +- **Host check (DNS rebinding, 0.1.38).** Without an API key the server answers only requests whose `Host` is a name + it knows (`localhost`, an IP address, the address it listens on and, when it listens beyond this PC, this PC's + name). Others get 403. `"allowed_hosts"` adds names; with an API key the key decides. +- **Origin check (0.1.38).** Without an API key, a browser `POST` to `/v1/*` from another web site's page (it carries + an `Origin` header) gets 403 unless that origin is Strata's own page, `localhost`, an allowed host, or listed in + `"trusted_origins"` / `"cors_origins"`. Changing settings (`/settings`, and `/config`: the few run config keys the + page's Model settings may change - never the network, key, MCP or program keys), `/load` and `/unload` and the + MCP tools are accepted only as JSON from Strata's own page (or `"trusted_origins"`), so a page elsewhere cannot + change settings or run tools. +- **CORS** is off unless `"cors_origins"` lists origins, and then only for `/v1/*`. +- **MCP tools** are opt-in: only the servers you put in the run config, only for requests from Strata's own page + that ask for them. They run with your user's rights, and the model decides when to call them. +- **The request monitor** (`/api-monitor`, which keeps the last prompts and answers in memory) is off unless + `"api_monitor": true` is set. + +Strata has not had an outside security audit yet. diff --git a/SETUP.bat b/SETUP.bat new file mode 100644 index 0000000..d2e6541 --- /dev/null +++ b/SETUP.bat @@ -0,0 +1,3 @@ +@echo off +rem Change settings or install another model (the same as START-HERE.bat --setup). +call "%~dp0START-HERE.bat" --setup %* diff --git a/START-HERE.bat b/START-HERE.bat new file mode 100644 index 0000000..dfb92fe --- /dev/null +++ b/START-HERE.bat @@ -0,0 +1,52 @@ +@echo off +rem Strata for Windows: the first run installs everything and starts the model; later runs just start it. +rem Needs only an NVIDIA or AMD graphics driver. Python is installed for your user account if it is missing (no admin needed). +setlocal +title Strata +cd /d "%~dp0" +if exist ".venv\Scripts\python.exe" goto run + +call :findpy +if defined PY goto venv +echo. +echo Python 3.10 or newer is not installed. Installing Python 3.12 for your user account ... +where winget >nul 2>nul +if errorlevel 1 goto pyorg +winget install -e --id Python.Python.3.12 --scope user --silent --source winget --accept-package-agreements --accept-source-agreements --disable-interactivity +call :findpy +if defined PY goto venv +:pyorg +echo Downloading the Python installer from python.org ... +powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol='Tls12'; Invoke-WebRequest -UseBasicParsing https://www.python.org/ftp/python/3.12.10/python-3.12.10-amd64.exe -OutFile \"$env:TEMP\strata-python-setup.exe\"" +if exist "%TEMP%\strata-python-setup.exe" "%TEMP%\strata-python-setup.exe" /quiet InstallAllUsers=0 PrependPath=1 Include_launcher=1 Include_test=0 +call :findpy +if defined PY goto venv +echo. +echo Python could not be installed automatically. +echo Install 64-bit Python 3.12 from https://www.python.org/downloads/ ("Add python.exe to PATH"), +echo then double-click START-HERE.bat again. +pause +exit /b 1 + +:venv +rem a private environment inside this folder, so nothing is installed into the system Python +%PY% -m venv .venv +if exist ".venv\Scripts\python.exe" goto run +echo Could not create the Python environment in .venv +pause +exit /b 1 + +:run +".venv\Scripts\python.exe" setup.py %* +if errorlevel 1 pause +exit /b + +:findpy +rem the py launcher first, then python on PATH (not the Microsoft Store stub), then the usual per-user folders +set "PY=" +py -3 -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) and sys.maxsize > 2**32 else 1)" >nul 2>nul +if not errorlevel 1 set "PY=py -3" & goto :eof +python -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) and sys.maxsize > 2**32 else 1)" >nul 2>nul +if not errorlevel 1 set "PY=python" & goto :eof +for %%V in (313 312 311 310) do if exist "%LOCALAPPDATA%\Programs\Python\Python%%V\python.exe" set "PY="%LOCALAPPDATA%\Programs\Python\Python%%V\python.exe"" & goto :eof +goto :eof diff --git a/UPDATE.bat b/UPDATE.bat new file mode 100644 index 0000000..7ee2901 --- /dev/null +++ b/UPDATE.bat @@ -0,0 +1,36 @@ +@echo off +rem Update Strata without starting the model (#475): the newest code (git pull, when this folder is a git clone), then +rem what START-HERE.bat does before a start - the engine (a new one when this version needs it), the Python packages, +rem each installed model's settings and draft subset. The model files are not touched. Start the model later with +rem START-HERE.bat. Options are passed on to setup.py. +setlocal +title Strata - update +cd /d "%~dp0" +rem All of it in one block: cmd reads a .bat file while it runs it, and the git pull can change this very file. +( + if exist ".git" ( + where git >nul 2>nul || ( + echo This folder is a git clone, but git is not on PATH: install Git for Windows ^(winget install Git.Git^) + echo or run "git pull" here yourself, then run UPDATE.bat again. + pause + exit /b 1 + ) + echo Getting the newest Strata ^(git pull^) ... + git pull --ff-only || ( + echo. + echo git pull did not succeed ^(the reason is above^): nothing was updated. Files you changed here can stop it: + echo "git status" lists them. + pause + exit /b 1 + ) + ) else ( + echo This copy of Strata was not made with git, so it cannot fetch new files itself. Download the newest one: + echo https://github.com/Niko1221/Strata/archive/refs/heads/main.zip + echo unzip it anywhere and run START-HERE.bat ^(or UPDATE.bat^) in it: it finds the model files in Strata-data + echo and sets itself up the same way - nothing big is downloaded again. + echo Checking this copy's engine and settings meanwhile ... + ) + call "%~dp0START-HERE.bat" --update %* + if not errorlevel 1 pause + exit /b +) diff --git a/bench/results/2026-09-24-final/estimates.json b/bench/results/2026-09-24-final/estimates.json new file mode 100644 index 0000000..0479ec4 --- /dev/null +++ b/bench/results/2026-09-24-final/estimates.json @@ -0,0 +1,461 @@ +[ + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "1k", + "slots": 4517, + "h": 0.747, + "decode": 88.7, + "prefill": 389.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "1k", + "slots": 7179, + "h": 0.826, + "decode": 80.5, + "prefill": 341.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "1k", + "slots": 12503, + "h": 0.93, + "decode": 127.5, + "prefill": 355.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "4k", + "slots": 4464, + "h": 0.722, + "decode": 94.6, + "prefill": 539.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "4k", + "slots": 7126, + "h": 0.809, + "decode": 87.4, + "prefill": 472.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "4k", + "slots": 12450, + "h": 0.923, + "decode": 140.0, + "prefill": 491.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "32k", + "slots": 4174, + "h": 0.674, + "decode": 87.5, + "prefill": 571.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "32k", + "slots": 6836, + "h": 0.774, + "decode": 81.3, + "prefill": 501.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "32k", + "slots": 12160, + "h": 0.907, + "decode": 130.0, + "prefill": 521.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "64k", + "slots": 3809, + "h": 0.625, + "decode": 76.4, + "prefill": 561.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "64k", + "slots": 6471, + "h": 0.74, + "decode": 71.6, + "prefill": 492.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "64k", + "slots": 11795, + "h": 0.892, + "decode": 115.3, + "prefill": 512.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "128k", + "slots": 3079, + "h": 0.571, + "decode": 65.1, + "prefill": 543.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "128k", + "slots": 5741, + "h": 0.702, + "decode": 61.8, + "prefill": 476.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "128k", + "slots": 11065, + "h": 0.873, + "decode": 100.0, + "prefill": 495.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "262k", + "slots": 1588, + "h": 0.526, + "decode": 56.3, + "prefill": 496.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "262k", + "slots": 4250, + "h": 0.668, + "decode": 52.9, + "prefill": 435.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "262k", + "slots": 9574, + "h": 0.849, + "decode": 84.6, + "prefill": 453.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "1k", + "slots": 4621, + "h": 0.799, + "decode": 82.0, + "prefill": 332.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "1k", + "slots": 7176, + "h": 0.86, + "decode": 79.6, + "prefill": 291.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "1k", + "slots": 12287, + "h": 0.941, + "decode": 131.1, + "prefill": 303.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "4k", + "slots": 4568, + "h": 0.785, + "decode": 78.1, + "prefill": 463.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "4k", + "slots": 7123, + "h": 0.85, + "decode": 76.9, + "prefill": 406.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "4k", + "slots": 12234, + "h": 0.937, + "decode": 127.7, + "prefill": 422.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "32k", + "slots": 4289, + "h": 0.783, + "decode": 65.3, + "prefill": 495.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "32k", + "slots": 6844, + "h": 0.848, + "decode": 62.9, + "prefill": 434.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "32k", + "slots": 11955, + "h": 0.935, + "decode": 102.9, + "prefill": 451.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "64k", + "slots": 3936, + "h": 0.759, + "decode": 63.7, + "prefill": 486.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "64k", + "slots": 6491, + "h": 0.83, + "decode": 62.0, + "prefill": 426.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "64k", + "slots": 11602, + "h": 0.927, + "decode": 102.2, + "prefill": 444.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "128k", + "slots": 3229, + "h": 0.695, + "decode": 52.0, + "prefill": 472.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "128k", + "slots": 5784, + "h": 0.784, + "decode": 51.3, + "prefill": 413.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "128k", + "slots": 10895, + "h": 0.905, + "decode": 85.0, + "prefill": 430.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "262k", + "slots": 1796, + "h": 0.627, + "decode": 48.1, + "prefill": 437.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "262k", + "slots": 4351, + "h": 0.735, + "decode": 47.3, + "prefill": 383.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "262k", + "slots": 9462, + "h": 0.876, + "decode": 77.5, + "prefill": 398.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "1k", + "slots": 3556, + "h": 0.638, + "decode": 64.6, + "prefill": 285.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "1k", + "slots": 5658, + "h": 0.728, + "decode": 65.8, + "prefill": 249.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "1k", + "slots": 9864, + "h": 0.858, + "decode": 106.5, + "prefill": 260.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "4k", + "slots": 3511, + "h": 0.712, + "decode": 65.6, + "prefill": 410.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "4k", + "slots": 5613, + "h": 0.784, + "decode": 64.7, + "prefill": 359.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "4k", + "slots": 9819, + "h": 0.887, + "decode": 103.0, + "prefill": 374.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "32k", + "slots": 3279, + "h": 0.696, + "decode": 57.3, + "prefill": 435.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "32k", + "slots": 5381, + "h": 0.772, + "decode": 56.3, + "prefill": 381.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "32k", + "slots": 9587, + "h": 0.879, + "decode": 89.0, + "prefill": 396.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "64k", + "slots": 2990, + "h": 0.677, + "decode": 54.4, + "prefill": 427.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "64k", + "slots": 5092, + "h": 0.757, + "decode": 53.7, + "prefill": 374.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "64k", + "slots": 9298, + "h": 0.87, + "decode": 85.1, + "prefill": 390.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "128k", + "slots": 2407, + "h": 0.57, + "decode": 44.8, + "prefill": 414.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "128k", + "slots": 4509, + "h": 0.675, + "decode": 44.6, + "prefill": 363.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "128k", + "slots": 8715, + "h": 0.824, + "decode": 70.8, + "prefill": 378.0 + } +] \ No newline at end of file diff --git a/bench/results/2026-09-24-final/estimates.md b/bench/results/2026-09-24-final/estimates.md new file mode 100644 index 0000000..66b88d2 --- /dev/null +++ b/bench/results/2026-09-24-final/estimates.md @@ -0,0 +1,27 @@ +### Output (decode) tok/s - estimated + +| Card | Model | 1k | 4k | 32k | 64k | 128k | 262k | +|---|---|---:|---:|---:|---:|---:|---:| +| RTX 5070 12GB (measured) | Q2_0 | ~89 | ~95 | ~88 | ~76 | ~65 | ~56 | +| RTX 5070 12GB (measured) | IQ2_XS | ~82 | ~78 | ~65 | ~64 | ~52 | ~48 | +| RTX 5070 12GB (measured) | IQ3_XXS | ~65 | ~66 | ~57 | ~54 | ~45 | - | +| RTX 5060 Ti 16GB | Q2_0 | ~80 | ~87 | ~81 | ~72 | ~62 | ~53 | +| RTX 5060 Ti 16GB | IQ2_XS | ~80 | ~77 | ~63 | ~62 | ~51 | ~47 | +| RTX 5060 Ti 16GB | IQ3_XXS | ~66 | ~65 | ~56 | ~54 | ~45 | - | +| RTX 3090 24GB | Q2_0 | ~128 | ~140 | ~130 | ~115 | ~100 | ~85 | +| RTX 3090 24GB | IQ2_XS | ~131 | ~128 | ~103 | ~102 | ~85 | ~78 | +| RTX 3090 24GB | IQ3_XXS | ~106 | ~103 | ~89 | ~85 | ~71 | - | + +### Prompt processing tok/s - estimated + +| Card | Model | 1k | 4k | 32k | 64k | 128k | 262k | +|---|---|---:|---:|---:|---:|---:|---:| +| RTX 5070 12GB (measured) | Q2_0 | ~389 | ~539 | ~571 | ~561 | ~543 | ~496 | +| RTX 5070 12GB (measured) | IQ2_XS | ~332 | ~463 | ~495 | ~486 | ~472 | ~437 | +| RTX 5070 12GB (measured) | IQ3_XXS | ~285 | ~410 | ~435 | ~427 | ~414 | - | +| RTX 5060 Ti 16GB | Q2_0 | ~341 | ~472 | ~501 | ~492 | ~476 | ~435 | +| RTX 5060 Ti 16GB | IQ2_XS | ~291 | ~406 | ~434 | ~426 | ~413 | ~383 | +| RTX 5060 Ti 16GB | IQ3_XXS | ~249 | ~359 | ~381 | ~374 | ~363 | - | +| RTX 3090 24GB | Q2_0 | ~355 | ~491 | ~521 | ~512 | ~495 | ~453 | +| RTX 3090 24GB | IQ2_XS | ~303 | ~422 | ~451 | ~444 | ~430 | ~398 | +| RTX 3090 24GB | IQ3_XXS | ~260 | ~374 | ~396 | ~390 | ~378 | - | diff --git a/bench/results/2026-09-24-final/matrix.json b/bench/results/2026-09-24-final/matrix.json new file mode 100644 index 0000000..260c833 --- /dev/null +++ b/bench/results/2026-09-24-final/matrix.json @@ -0,0 +1,240 @@ +[ + { + "model": "Q2_0", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 40.2, + "prefill_tok_s": 388.83, + "ttft_s": 2.68, + "decode_tok_s": 88.67, + "decoded": 256, + "spec_accept": 0.739, + "tokens_per_round": 2.71, + "vram_slots": 4517 + }, + { + "model": "Q2_0", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 44.6, + "prefill_tok_s": 538.75, + "ttft_s": 6.67, + "decode_tok_s": 94.59, + "decoded": 256, + "spec_accept": 0.846, + "tokens_per_round": 3.23, + "vram_slots": 4464 + }, + { + "model": "Q2_0", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 91.9, + "prefill_tok_s": 571.03, + "ttft_s": 55.34, + "decode_tok_s": 87.48, + "decoded": 256, + "spec_accept": 0.865, + "tokens_per_round": 3.11, + "vram_slots": 4174 + }, + { + "model": "Q2_0", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 151.5, + "prefill_tok_s": 561.16, + "ttft_s": 114.4, + "decode_tok_s": 76.38, + "decoded": 256, + "spec_accept": 0.781, + "tokens_per_round": 2.8, + "vram_slots": 3809 + }, + { + "model": "Q2_0", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 273.5, + "prefill_tok_s": 542.95, + "ttft_s": 236.7, + "decode_tok_s": 65.09, + "decoded": 256, + "spec_accept": 0.687, + "tokens_per_round": 2.65, + "vram_slots": 3079 + }, + { + "model": "Q2_0", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 562.5, + "prefill_tok_s": 496.33, + "ttft_s": 523.8, + "decode_tok_s": 56.26, + "decoded": 256, + "spec_accept": 0.659, + "tokens_per_round": 2.46, + "vram_slots": 1588 + }, + { + "model": "IQ2_XS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 42.3, + "prefill_tok_s": 332.19, + "ttft_s": 3.14, + "decode_tok_s": 81.97, + "decoded": 256, + "spec_accept": 0.84, + "tokens_per_round": 3.25, + "vram_slots": 4621 + }, + { + "model": "IQ2_XS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 47.4, + "prefill_tok_s": 462.95, + "ttft_s": 7.78, + "decode_tok_s": 78.05, + "decoded": 256, + "spec_accept": 0.856, + "tokens_per_round": 3.28, + "vram_slots": 4568 + }, + { + "model": "IQ2_XS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 102.3, + "prefill_tok_s": 495.14, + "ttft_s": 63.83, + "decode_tok_s": 65.32, + "decoded": 256, + "spec_accept": 0.706, + "tokens_per_round": 2.53, + "vram_slots": 4289 + }, + { + "model": "IQ2_XS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 170.8, + "prefill_tok_s": 486.42, + "ttft_s": 131.99, + "decode_tok_s": 63.66, + "decoded": 256, + "spec_accept": 0.701, + "tokens_per_round": 2.72, + "vram_slots": 3936 + }, + { + "model": "IQ2_XS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 312.7, + "prefill_tok_s": 471.61, + "ttft_s": 272.52, + "decode_tok_s": 52.04, + "decoded": 256, + "spec_accept": 0.602, + "tokens_per_round": 2.44, + "vram_slots": 3229 + }, + { + "model": "IQ2_XS", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 637.4, + "prefill_tok_s": 436.86, + "ttft_s": 595.11, + "decode_tok_s": 48.05, + "decoded": 256, + "spec_accept": 0.628, + "tokens_per_round": 2.42, + "vram_slots": 1796 + }, + { + "model": "IQ3_XXS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 43.8, + "prefill_tok_s": 284.64, + "ttft_s": 3.67, + "decode_tok_s": 64.58, + "decoded": 256, + "spec_accept": 0.912, + "tokens_per_round": 3.63, + "vram_slots": 3556 + }, + { + "model": "IQ3_XXS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 48.5, + "prefill_tok_s": 409.76, + "ttft_s": 8.78, + "decode_tok_s": 65.57, + "decoded": 256, + "spec_accept": 0.863, + "tokens_per_round": 3.24, + "vram_slots": 3511 + }, + { + "model": "IQ3_XXS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 112.6, + "prefill_tok_s": 434.75, + "ttft_s": 72.69, + "decode_tok_s": 57.3, + "decoded": 256, + "spec_accept": 0.752, + "tokens_per_round": 2.78, + "vram_slots": 3279 + }, + { + "model": "IQ3_XXS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 190.1, + "prefill_tok_s": 427.26, + "ttft_s": 150.25, + "decode_tok_s": 54.4, + "decoded": 256, + "spec_accept": 0.723, + "tokens_per_round": 2.88, + "vram_slots": 2990 + }, + { + "model": "IQ3_XXS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 351.1, + "prefill_tok_s": 414.43, + "ttft_s": 310.1, + "decode_tok_s": 44.81, + "decoded": 256, + "spec_accept": 0.648, + "tokens_per_round": 2.42, + "vram_slots": 2407 + } +] \ No newline at end of file diff --git a/bench/results/2026-09-24-final/matrix.md b/bench/results/2026-09-24-final/matrix.md new file mode 100644 index 0000000..b9b2cb9 --- /dev/null +++ b/bench/results/2026-09-24-final/matrix.md @@ -0,0 +1,15 @@ +### Prompt processing (tok/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +|---|---:|---:|---:|---:|---:|---:| +| Q2_0 | 389 | 539 | 571 | 561 | 543 | 496 | +| IQ2_XS | 332 | 463 | 495 | 486 | 472 | 437 | +| IQ3_XXS | 285 | 410 | 435 | 427 | 414 | - | + +### Output (tok/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +|---|---:|---:|---:|---:|---:|---:| +| Q2_0 | 88.7 | 94.6 | 87.5 | 76.4 | 65.1 | 56.3 | +| IQ2_XS | 82.0 | 78.0 | 65.3 | 63.7 | 52.0 | 48.0 | +| IQ3_XXS | 64.6 | 65.6 | 57.3 | 54.4 | 44.8 | - | diff --git a/bench/results/2026-09-24-vision/vision.json b/bench/results/2026-09-24-vision/vision.json new file mode 100644 index 0000000..5150dc2 --- /dev/null +++ b/bench/results/2026-09-24-vision/vision.json @@ -0,0 +1,53 @@ +[ + { + "model": "Q2_0", + "off": { + "prefill_tok_s": 541.31, + "decode_tok_s": 90.74, + "vram_slots": 4464, + "spec_accept": 0.846 + }, + "on": { + "prefill_tok_s": 530.64, + "decode_tok_s": 86.92, + "vram_slots": 3402, + "spec_accept": 0.858 + }, + "flag_identical": true, + "on_identical": false + }, + { + "model": "IQ2_XS", + "off": { + "prefill_tok_s": 468.17, + "decode_tok_s": 77.14, + "vram_slots": 4568, + "spec_accept": 0.856 + }, + "on": { + "prefill_tok_s": 457.61, + "decode_tok_s": 73.96, + "vram_slots": 3542, + "spec_accept": 0.866 + }, + "flag_identical": true, + "on_identical": false + }, + { + "model": "IQ3_XXS", + "off": { + "prefill_tok_s": 411.3, + "decode_tok_s": 64.7, + "vram_slots": 3511, + "spec_accept": 0.863 + }, + "on": { + "prefill_tok_s": 401.48, + "decode_tok_s": 59.46, + "vram_slots": 2662, + "spec_accept": 0.868 + }, + "flag_identical": true, + "on_identical": true + } +] \ No newline at end of file diff --git a/bench/results/2026-09-24-vision/vision.md b/bench/results/2026-09-24-vision/vision.md new file mode 100644 index 0000000..c30d299 --- /dev/null +++ b/bench/results/2026-09-24-vision/vision.md @@ -0,0 +1,5 @@ +| Model | Prompt tok/s (vision off) | Prompt tok/s (vision on) | Output tok/s (vision off) | Output tok/s (vision on) | VRAM expert slots off / on | --vision alone: same tokens | +|---|---:|---:|---:|---:|---:|---| +| Q2_0 | 541 | 531 | 90.7 | 86.9 | 4464 / 3402 | yes | +| IQ2_XS | 468 | 458 | 77.1 | 74.0 | 4568 / 3542 | yes | +| IQ3_XXS | 411 | 401 | 64.7 | 59.5 | 3511 / 2662 | yes | diff --git a/bench/results/2026-09-27-cache-parity/README.md b/bench/results/2026-09-27-cache-parity/README.md new file mode 100644 index 0000000..10f1d19 --- /dev/null +++ b/bench/results/2026-09-27-cache-parity/README.md @@ -0,0 +1,29 @@ +# 2026-09-27: expert cache on vs off (issue #23) + +Question: the engine used to warn at start that "the GPU hit path is NOT CORRECT ... any OUTPUT from it is not". Does +the expert cache make the output worse? + +Method: teacher-forced. `strata --dump-logits` runs a text one token at a time and writes the logits at every +position, so both runs see the same text and each position's next-token prediction can be compared: +- cache off: no `--expert-cache`, every routed expert computed by the CPU pool; +- cache on: `--expert-profile pack/profile-decode-8k.bin --expert-cache auto`, 5,130 of the most-used experts on the GPU. + +Q2_0, RTX 5070, the first 512 or 1,024 tokens of three frozen prompts. + +| Text | Same top-1 | Median KL | Perplexity off | Perplexity on | On - off (nats per token) | +|---|---:|---:|---:|---:|---:| +| Code agent (512) | 97.7% | 3.0e-04 | 2.672 | 2.630 | -0.016 +- 0.019 | +| Long document (1,024) | 96.2% | 4.5e-03 | 29.844 | 29.843 | -0.000 +- 0.005 | +| Chat (1,024) | 95.0% | 4.4e-03 | 18.380 | 18.301 | -0.004 +- 0.006 | +| **All 2,557 tokens** | | | | | **-0.005 +- 0.005** | + +Reading: +- The cache changes which of two nearly equal candidates wins at 2-5% of positions. Most of the flips have a top-2 + margin under 0.5 logits (`logits-compare.txt`). +- Neither side is more accurate: the perplexity of the actual text is the same, within 1 standard error. +- A GPU expert and the CPU compute the same quantized expert with a different floating-point order. Both are an + equally good approximation of the model. + +The start-up warning dates from round 328, when the GPU hit path had a real fault (divergence from token 0). That fault +was fixed long ago and is covered by `expert_parity`, `native_expert_parity` and the grouped kernels' tests. Since +engine 0.1.8 the warning is replaced by one accurate line. diff --git a/bench/results/2026-09-27-esp/README.md b/bench/results/2026-09-27-esp/README.md new file mode 100644 index 0000000..19ff778 --- /dev/null +++ b/bench/results/2026-09-27-esp/README.md @@ -0,0 +1,36 @@ +# 2026-09-27: the experimental-speed-projection control vector + +The package's `Qwen3.8-Flash-Next-experimental-speed-projection.gguf` (47 unit directions of 2,560, one per layer), +applied as `--control-vector-scaled FILE:1.0 --control-vector-layer-range 4 44 --cvec-mode project --cvec-dir +per-layer`: after layers 4-44, every hyper-connection stream `h -= (h . v) v`. The package describes it as a +refusal-direction projection. Q2_0, RTX 5070, fixed experts (`--expert-cache 4000 --pcie-frac 0 --adapt-swaps 0`). + +## Kernel (`cvec_parity`) + +Project and add against a double-precision reference (max error 5e-7); with the switch off, the kernel's pending +residual write is bitwise the fused hyper-connection read's own, so a loaded-but-off vector is the stock engine. + +## Teacher-forced, stock vs projection (`esp_kl.py`, per-token path) + +| Text | Tokens | Same top-1 | Mean KL | p99 KL | Perplexity stock | With the vector | +|---|---:|---:|---:|---:|---:|---:| +| Code | 511 | 92.8% | 0.098 | 1.69 | 2.594 | 2.982 | +| Document | 1,023 | 89.8% | 0.058 | 0.84 | 30.299 | 30.984 | +| Chat | 1,023 | 89.6% | 0.050 | 0.33 | 18.409 | 18.485 | +| **All** | 2,557 | | **0.063** (max 4.10) | 1.00 | | | + +The package reports a mean KL of 0.186 on its own neutral text with UD-Q2_K_XL in llama.cpp. + +Cost on the same tokens: 44.34 -> 44.26, 46.74 -> 46.56, 47.02 -> 46.83 tok/s (0.2-0.4%). + +## Serve (`esp_serve.py`) + +- Loaded and switched off (`cvec=0`) vs an engine without it: 65 / 65 first tokens after prefixes (verify windows + and the batched prompt path) and three 256-token generations **token-identical**. +- On, off, on again: identical (the switch drops the conversation cache, so nothing computed one way is reused the + other way). +- The prompt paths steer like the per-token path: served-with-vector first tokens agree with the per-token path's + teacher-forced argmax with the vector 62 / 65, and with the stock one 57 / 65 (stock served: 64 / 65 and 57 / 65). +- Decode tok/s of 3 x 256-token generations: stock 66.4, on 76.7 / 81.2. **Not a like-for-like comparison:** the + model writes different text with it on (on the code prompt it copied a long stretch of the source, which prompt + lookup drafts at 91% acceptance, where stock stopped after 78 tokens). On the same tokens it is 0.2-0.4% slower. diff --git a/bench/results/2026-09-27-esp/esp_kl.py b/bench/results/2026-09-27-esp/esp_kl.py new file mode 100644 index 0000000..5ec6d3a --- /dev/null +++ b/bench/results/2026-09-27-esp/esp_kl.py @@ -0,0 +1,85 @@ +"""Teacher-forced logits, stock vs the experimental-speed-projection vector, on the same texts and fixed experts. + + python esp_kl.py run # the dumps (per-token path) + python esp_kl.py compare # same top-1, mean/median KL(stock || projection), perplexities +""" +import json +import os +import subprocess +import sys + +import numpy as np + +S = os.path.dirname(os.path.abspath(__file__)) +E = r"C:\Users\AI-Server\Desktop\Strata\Public\Engine" +EXE = E + r"\build-dev\strata.exe" +VEC = r"C:\Users\AI-Server\Desktop\Strata\experimental-speed-projection\Qwen3.8-Flash-Next-experimental-speed-projection.gguf" +TEXTS = {"code": S + r"\p512.ids", "doc": S + r"\4k-02-long-doc-1k.ids", "chat": S + r"\4k-04-chat-1k.ids"} +OUT = S + r"\esp-kl" +ARMS = {"stock": [], + "proj": ["--control-vector-scaled", VEC + ":1.0", "--control-vector-layer-range", "4", "44", + "--cvec-mode", "project", "--cvec-dir", "per-layer"]} + + +def base_args(): + c = json.load(open(S + r"\cfg-rel.json")) + a = list(c["args"]) + i = a.index("--expert-cache") + a[i + 1] = "4000" + j = a.index("--prefill") # the prompt one token at a time: a logits row per position + del a[j:j + 2] + return a + ["--pcie-frac", "0", "--adapt-swaps", "0"], c + + +def run(): + os.makedirs(OUT, exist_ok=True) + args, c = base_args() + env = dict(os.environ) + env["PATH"] = os.pathsep.join(c["lib_dirs"]) + os.pathsep + env["PATH"] + for name, path in TEXTS.items(): + for arm, extra in ARMS.items(): + out = f"{OUT}\\{name}-{arm}.bin" + if os.path.exists(out): + continue + cmd = [EXE, *args, *extra, "--tokens-file", path, "--max-new", "1", "--dump-logits", out] + with open(f"{OUT}\\{name}-{arm}.log", "w") as log: + r = subprocess.run(cmd, cwd=c["cwd"], stdout=log, stderr=subprocess.STDOUT, env=env) + print(name, arm, "exit", r.returncode, flush=True) + + +def load(p): + h = np.fromfile(p, dtype=np.int32, count=2) + return np.memmap(p, dtype=np.float32, mode="r", offset=8, shape=(int(h[1]), int(h[0]))) + + +def lsm(x): + x = x.astype(np.float64) + m = x.max(axis=-1, keepdims=True) + return x - (m + np.log(np.exp(x - m).sum(axis=-1, keepdims=True))) + + +def compare(): + print(f"{'text':<6}{'tokens':>7}{'same top-1':>11}{'mean KL':>9}{'median KL':>11}{'p99 KL':>8}{'ppl stock':>10}{'ppl proj':>9}") + allkl = [] + for name, path in TEXTS.items(): + ids = [int(x) for x in open(path).read().replace(",", " ").split()] + a, b = load(f"{OUT}\\{name}-stock.bin"), load(f"{OUT}\\{name}-proj.bin") + n = min(a.shape[0], b.shape[0], len(ids) - 1) + kl, same, la, lb = [], 0, [], [] + for r in range(0, n, 64): + pa, pb = lsm(a[r:min(n, r + 64)]), lsm(b[r:min(n, r + 64)]) + kl += list((np.exp(pa) * (pa - pb)).sum(axis=1)) + same += int((pa.argmax(1) == pb.argmax(1)).sum()) + nxt = np.array(ids[r + 1:min(n, r + 64) + 1]) + la += list(pa[np.arange(len(nxt)), nxt]) + lb += list(pb[np.arange(len(nxt)), nxt]) + kl = np.array(kl) + allkl += list(kl) + print(f"{name:<6}{n:>7}{100 * same / n:>10.1f}%{kl.mean():>9.3f}{np.median(kl):>11.4f}{np.percentile(kl, 99):>8.2f}" + f"{np.exp(-np.mean(la)):>10.3f}{np.exp(-np.mean(lb)):>9.3f}") + allkl = np.array(allkl) + print(f"all {len(allkl)} tokens: mean KL {allkl.mean():.3f}, max {allkl.max():.2f}, p99 {np.percentile(allkl, 99):.2f}") + + +if __name__ == "__main__": + {"run": run, "compare": compare}[sys.argv[1]]() diff --git a/bench/results/2026-09-27-esp/esp_serve.py b/bench/results/2026-09-27-esp/esp_serve.py new file mode 100644 index 0000000..4ec2005 --- /dev/null +++ b/bench/results/2026-09-27-esp/esp_serve.py @@ -0,0 +1,129 @@ +"""Serve-mode checks of the experimental-speed-projection vector (exact mode: fixed experts, no PCIe share). + + python esp_serve.py run ARM # ARM = stock | vec; writes esp-serve/.json + python esp_serve.py compare + +Per arm: the first greedy token after many prefixes of three texts (short ones go through the verify windows, long +ones through the batched prompt path; the conversation cache reuses the earlier prefix), and three 256-token greedy +generations. The vec arm runs everything with cvec=1, then cvec=0, then cvec=1 again. +""" +import json +import os +import sys +import threading + +S = os.path.dirname(os.path.abspath(__file__)) +E = r"C:\Users\AI-Server\Desktop\Strata\Public\Engine" +sys.path.insert(0, E) +from serve.server import StrataEngine # noqa: E402 + +EXE = E + r"\build-dev\strata.exe" +VEC = r"C:\Users\AI-Server\Desktop\Strata\experimental-speed-projection\Qwen3.8-Flash-Next-experimental-speed-projection.gguf" +TEXTS = {"code": S + r"\p512.ids", "doc": S + r"\4k-02-long-doc-1k.ids", "chat": S + r"\4k-04-chat-1k.ids"} +OUT = S + r"\esp-serve" +VEC_ARGS = ["--control-vector-scaled", VEC + ":1.0", "--control-vector-layer-range", "4", "44", + "--cvec-mode", "project", "--cvec-dir", "per-layer"] + + +def ids_of(name): + return [int(x) for x in open(TEXTS[name]).read().replace(",", " ").split()] + + +def engine(extra): + c = json.load(open(S + r"\cfg-rel.json")) + a = list(c["args"]) + a[a.index("--expert-cache") + 1] = "4000" + env = dict(os.environ) + env["PATH"] = os.pathsep.join(c["lib_dirs"]) + os.pathsep + env["PATH"] + return StrataEngine(EXE, a + ["--pcie-frac", "0", "--adapt-swaps", "0"] + extra, cwd=c["cwd"], + log=OUT + r"\engine.log", env=env) + + +def gen(eng, ids, n, sampling): + toks = [t for t in eng.generate(ids, n, sampling, threading.Event()) if t is not None] + return toks, dict(eng.last) + + +def suite(eng, sampling): + out = {"first": {}, "long": {}} + for name in TEXTS: + ids = ids_of(name) + # short prefixes growing by 4 (each continues the live session through the verify windows), then long ones + # SHRINKING (no cached prefix, so each is read from 0 by the batched prompt path) + lens = list(range(32, 72, 4)) + list(range(min(len(ids) - 1, 700), 95, -48)) + out["first"][name] = {L: gen(eng, ids[:L], 1, sampling)[0][0] for L in lens} + for name in TEXTS: + toks, last = gen(eng, ids_of(name)[:300], 256, sampling) + out["long"][name] = {"tokens": toks, "last": last} + return out + + +def run(arm): + os.makedirs(OUT, exist_ok=True) + eng = engine(VEC_ARGS if arm == "vec" else []) + res = {"info": eng.info} + if arm == "stock": + res["stock"] = suite(eng, {}) + else: + res["on"] = suite(eng, {"experimental_speed_projection": True}) + res["off"] = suite(eng, {"experimental_speed_projection": False}) + res["on2"] = suite(eng, {"experimental_speed_projection": True}) + eng.close() + json.dump(res, open(f"{OUT}\\{arm}.json", "w")) + print(arm, "done", eng.info, flush=True) + + +def compare(): + import numpy as np + sys.path.insert(0, S) + from esp_kl import load, OUT as KL + st = json.load(open(OUT + r"\stock.json")) + ve = json.load(open(OUT + r"\vec.json")) + print("engine INFO (vec):", ve["info"]) + + def eq_first(a, b): + tot = same = 0 + for name in a: + for L, t in a[name].items(): + tot += 1 + same += int(b[name][L] == t) + return same, tot + + def eq_long(a, b): + return all(a[n]["tokens"] == b[n]["tokens"] for n in a), \ + [(n, next((i for i, (x, y) in enumerate(zip(a[n]["tokens"], b[n]["tokens"])) if x != y), None)) for n in a] + + print("1. vector loaded, switched off == no vector") + print(" first tokens: %d / %d identical" % eq_first(st["stock"]["first"], ve["off"]["first"])) + print(" 256-token generations identical:", *eq_long(st["stock"]["long"], ve["off"]["long"])) + print("2. repeatable: on, off, on again") + print(" first tokens: %d / %d identical" % eq_first(ve["on"]["first"], ve["on2"]["first"])) + print(" 256-token generations identical:", *eq_long(ve["on"]["long"], ve["on2"]["long"])) + print("3. the prompt paths against the per-token path's teacher-forced argmax (row L-1 predicts token L)") + for arm, first in (("stock", st["stock"]["first"]), ("on", ve["on"]["first"])): + for ref in ("stock", "proj"): + agree = tot = 0 + for name in first: + d = load(f"{KL}\\{name}-{ref}.bin") + for L, t in first[name].items(): + L = int(L) + if L - 1 < d.shape[0]: + tot += 1 + agree += int(int(np.argmax(d[L - 1])) == t) + print(f" served {arm:<5} vs per-token {ref:<5}: {agree} / {tot}") + print("4. how different the text is: 256-token generations, on vs stock, first difference") + print(" ", eq_long(st["stock"]["long"], ve["on"]["long"])[1]) + print("5. decode speed (exact mode: fixed experts, no PCIe share - not the normal setup)") + for label, r in (("stock", st["stock"]), ("vec off", ve["off"]), ("vec on", ve["on"]), ("vec on 2", ve["on2"])): + g = sum(v["last"]["generated"] for v in r["long"].values()) + ms = sum(v["last"]["decode_ms"] for v in r["long"].values()) + acc = sum(v["last"].get("drafts_accepted", 0) for v in r["long"].values()) + off = sum(v["last"].get("drafts_offered", 0) for v in r["long"].values()) + print(f" {label:<9} {g / ms * 1000:6.1f} tok/s drafts accepted {acc}/{off}") + + +if __name__ == "__main__": + if sys.argv[1] == "run": + run(sys.argv[2]) + else: + compare() diff --git a/bench/results/2026-09-27-esp/serve-checks.txt b/bench/results/2026-09-27-esp/serve-checks.txt new file mode 100644 index 0000000..23219a3 --- /dev/null +++ b/bench/results/2026-09-27-esp/serve-checks.txt @@ -0,0 +1,20 @@ +1. vector loaded, switched off == no vector + first tokens: 65 / 65 identical + 256-token generations identical: True [('code', None), ('doc', None), ('chat', None)] +2. repeatable: on, off, on again + first tokens: 65 / 65 identical + 256-token generations identical: True [('code', None), ('doc', None), ('chat', None)] +3. the prompt paths against the per-token path's teacher-forced argmax (row L-1 predicts token L) + served stock vs per-token stock: 64 / 65 + served stock vs per-token proj : 57 / 65 + served on vs per-token stock: 57 / 65 + served on vs per-token proj : 62 / 65 +4. how different the text is: 256-token generations, on vs stock, first difference + [('code', 11), ('doc', 6), ('chat', 3)] +5. decode speed (exact mode: fixed experts, no PCIe share - not the normal setup) + stock 66.4 tok/s drafts accepted 256/309 + vec off 65.7 tok/s drafts accepted 251/318 + vec on 76.7 tok/s drafts accepted 366/425 + vec on 2 81.2 tok/s drafts accepted 366/423 + +[exited with code 0] diff --git a/bench/results/2026-09-27-esp/teacher-forced.txt b/bench/results/2026-09-27-esp/teacher-forced.txt new file mode 100644 index 0000000..5beb4b8 --- /dev/null +++ b/bench/results/2026-09-27-esp/teacher-forced.txt @@ -0,0 +1,6 @@ +text tokens same top-1 mean KL median KL p99 KL ppl stock ppl proj +code 511 92.8% 0.098 0.0031 1.69 2.594 2.982 +doc 1023 89.8% 0.058 0.0271 0.84 30.299 30.984 +chat 1023 89.6% 0.050 0.0265 0.33 18.409 18.485 +all 2557 tokens: mean KL 0.063, max 4.10, p99 1.00 + diff --git a/bench/results/2026-09-27-kv-q4/README.md b/bench/results/2026-09-27-kv-q4/README.md new file mode 100644 index 0000000..7cfa891 --- /dev/null +++ b/bench/results/2026-09-27-kv-q4/README.md @@ -0,0 +1,60 @@ +# 2026-09-27: Q4_0 KV with Hadamard rotation (PR #21, `--kv q4_0`) + +PR #21 (code-martin) adds a 4-bit K/V format: an orthonormal 256-point Walsh-Hadamard rotation of K, V and Q, then +ggml `q4_0` blocks (576 B per cell and layer, vs 1,056 B in int8). + +## Integration fixes made on merge + +- **Q4 + KV streaming (`--kv-resident`).** The PR had no host copy for Q4 and skipped the staging, so with streaming + on, the prompt path wrote K/V through the residency map's -1 entries (out-of-bounds writes). + - Q4 is now a third format in `kv_stream`: host copy, block residency, prompt-path staging, MTP ring and STATE_HASH. + - `kv_stream_parity` checks it bitwise, streamed vs resident, with ring restore. +- **Duplicate attention.** The per-token decode path ran attention twice, the first time before the selection's + blocks were made resident; it now runs once. +- **Tie-break.** The group maximum's tie-break is now deterministic across lanes: equal |x| with opposite signs + could give one block two scales. +- **Unrelated changes dropped:** duplicate path fixes (already in 0.1.7), personal `.gitignore` entries, and a + re-encoded CMakeLists. + +`kv_q4_parity` (the PR's test) and all 70 ctest tests pass. + +## Quality (teacher-forced, `tools/kv_precision_compare.py`) + +Same text, same fixed expert set (Q2_0, 3,000 slots, `--adapt-swaps 0`); only `--kv` differs. fp16 is the reference. + +| Text | KV | Same top-1 as fp16 | Mean KL | Perplexity | vs fp16 (nats/token) | +|---|---|---:|---:|---:|---:| +| code agent (512) | int8 | 98.4% | 0.014 | 2.649 | -0.011 +- 0.006 | +| | q4_0 | 95.7% | 0.030 | 2.598 | -0.031 +- 0.014 | +| document (1,024) | int8 | 95.6% | 0.009 | 30.18 | +0.012 +- 0.005 | +| | q4_0 | 91.3% | 0.039 | 32.26 | **+0.078 +- 0.011** | +| chat (1,024) | int8 | 95.5% | 0.009 | 18.24 | -0.003 +- 0.005 | +| | q4_0 | 90.7% | 0.028 | 18.52 | +0.012 +- 0.008 | +| document, 8K (every 8th position) | int8 | 92.3% | 0.114 | 7.63 | -0.013 +- 0.020 | +| | q4_0 | 88.0% | 0.297 | 8.65 | **+0.112 +- 0.037** | + +- **int8 is indistinguishable from fp16** (within about 2 standard errors everywhere). +- **q4_0 costs measurable precision, and more as the context grows:** + - document perplexity +8% at 1K and +12% at 8K; + - the KL from fp16 is 2.6-4.2x int8's; + - code and chat are near-neutral. +- **Needles with `--kv q4_0 --kv-resident 32768`: 5/5** (1K, 32K, 128K at 10% and 90% depth, 262K; + `needles-q4.*`). Retrieval holds. + +## Speed and memory (Q2_0, 128K, matrix bench, `--kv-resident 32768`) + +| KV | Expert slots | Decode tok/s | Tokens/round | Rounds/s | K/V in RAM | +|---|---:|---:|---:|---:|---:| +| int8 (`kv-stream/matrix-stream`) | 4,044 | 62.4 | 2.52 | 24.8 | 1.52 GiB | +| q4_0 (`matrix-q4`) | 4,190 | 67.4 | 2.62 | 25.7 (+3.7%) | 0.83 GiB | + +Without streaming (contexts up to 64K, or too little RAM for it) q4_0 halves the whole KV cache in VRAM instead. + +## Decision + +`--kv q4_0` is a user option: +- `START-HERE.bat --kv q4_0`, or the question setup asks above 8K context; +- or `--kv q4_0` in a `strata-*.json`. + +int8 stays the default: every published quality number was measured with it, and q4_0's precision cost is real, +though it passes the needles. diff --git a/bench/results/2026-09-28-coder/README.md b/bench/results/2026-09-28-coder/README.md new file mode 100644 index 0000000..4afc192 --- /dev/null +++ b/bench/results/2026-09-28-coder/README.md @@ -0,0 +1,44 @@ +# The GSQ-RCO Coder (256 of 512 experts) on Strata + +RTX 5070 12 GB, Ryzen 5 7600, 64 GB DDR5-5200, Windows 10. Engine 0.1.15 + PR #54 (the expert count from the model +file), the settings setup writes (`--prefill auto`, 8-bit KV above 4K, KV streaming from 64K, MTP, greedy, 256 tokens), +`data/expert-profile-coder.bin`, the same code-agent prompts as `2026-09-28-speed-0114`. + +| | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Prompt, tokens/s | 599 | 1,152 | 1,298 | 1,350 | 1,266 | 1,034 | +| Output, tokens/s | 53.3 | 50.6 | 53.3 | 50.8 | 44.0 | 42.8 | +| Draft acceptance | 0.720 | 0.707 | 0.785 | 0.696 | 0.619 | 0.684 | +| Experts in VRAM | 2,570 | 2,615 | 2,418 | 2,382 | 2,326 | 2,208 | + +Every run in [`matrix.json`](matrix.json). The 128K and 262K answers were read: coherent (they list and discuss the +files of the prompt). + +## Why it is fast + +The kept experts are stored like IQ3_S's (IQ2_S / IQ3_XXS / IQ3_S / IQ4_XS gate and up, IQ4_NL / Q2_0 down; "IQ1_M" is +the release's name for 1.89 bits per *original* parameter), so a token costs about what IQ3_S costs where the expert is +on the CPU. But there are half as many experts: the 23 GB of them pin completely (`cudaHostRegister` of the whole +arena), a 12 GB card holds ~20% of them instead of ~10%, and the prompt path streams half as many. + +## The expert profile + +`data/expert-profile-coder.bin` (48 x 256, all 12,288 pairs ranked): the shipped 48 x 512 ranking, each pair mapped to +its kept expert's new index through section 2 of the release's `tensor-allocation/*.rco-allocation.txt` (the kept +experts in their original order; gate, up and down agree on which were kept), pruned pairs dropped. 5,492 of the +shipped top 8,000 survive (as PR #54 found). With 2,537 slots on the 12 GB card, 72% of the expert reads of a 4K code +prompt hit the GPU - a wrong index mapping would give about the slot share, 21%. + +## Images + +The Coder ships the original's vision encoder (the same file). With `--vision` on the GPU it described a Strata +Monitor screenshot correctly, windows, labels and the numbers of the dashboard and the requests table (1,079 prompt +tokens with the image, 2,012 generated at ~50 tokens/s). + +## The experimental speed projection + +The vector was made from the full model's activations; the Coder has the same residual stream. On the Coder it loads +(41 layers steered), costs no measurable speed (47.7-55.7 tokens/s with it on or off), and both settings write correct +answers to three coding prompts. What it is for - fewer refusals - was not measured. (Two runs of the same prompt with +it off also differ after ~130-200 characters in serve mode, so this check cannot show how far it moves ordinary text; +the teacher-forced method of `2026-09-27-esp` needs the token-by-token prompt path, which native packs do not run.) diff --git a/bench/results/2026-09-28-coder/matrix.json b/bench/results/2026-09-28-coder/matrix.json new file mode 100644 index 0000000..2614ebc --- /dev/null +++ b/bench/results/2026-09-28-coder/matrix.json @@ -0,0 +1,86 @@ +[ + { + "model": "CODER", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 18.0, + "prefill_tok_s": 599.05, + "ttft_s": 2.54, + "decode_tok_s": 53.33, + "decoded": 256, + "spec_accept": 0.72, + "tokens_per_round": 2.86, + "vram_slots": 2570 + }, + { + "model": "CODER", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 19.6, + "prefill_tok_s": 1152.17, + "ttft_s": 3.94, + "decode_tok_s": 50.6, + "decoded": 256, + "spec_accept": 0.707, + "tokens_per_round": 2.88, + "vram_slots": 2615 + }, + { + "model": "CODER", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 40.7, + "prefill_tok_s": 1297.8, + "ttft_s": 25.17, + "decode_tok_s": 53.34, + "decoded": 256, + "spec_accept": 0.785, + "tokens_per_round": 3.02, + "vram_slots": 2418 + }, + { + "model": "CODER", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 75.5, + "prefill_tok_s": 1350.09, + "ttft_s": 49.01, + "decode_tok_s": 50.84, + "decoded": 256, + "spec_accept": 0.696, + "tokens_per_round": 2.61, + "vram_slots": 2382 + }, + { + "model": "CODER", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 121.5, + "prefill_tok_s": 1266.31, + "ttft_s": 102.95, + "decode_tok_s": 44.03, + "decoded": 256, + "spec_accept": 0.619, + "tokens_per_round": 2.33, + "vram_slots": 2326 + }, + { + "model": "CODER", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 280.7, + "prefill_tok_s": 1033.91, + "ttft_s": 252.92, + "decode_tok_s": 42.8, + "decoded": 256, + "spec_accept": 0.684, + "tokens_per_round": 2.6, + "vram_slots": 2208 + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-prefill-speed/README.md b/bench/results/2026-09-28-prefill-speed/README.md new file mode 100644 index 0000000..91d4278 --- /dev/null +++ b/bench/results/2026-09-28-prefill-speed/README.md @@ -0,0 +1,47 @@ +# Faster prompt reading (engine 0.1.13) + +RTX 5070 12 GB, Ryzen 5 7600, 64 GB DDR5. 32K-token prompt (`bench/prompts/long/32k-01-code-agent.ids`), one-shot +engine, `--expert-cache auto`, greedy. Numbers are prompt tokens/s. + +## What changed, step by step + +| Step | What | Result | +|---|---|---| +| Buffers | The attention half and the MoE half of a layer share one scratch region (~260 KB less per prompt token) | bit-identical; chunk 4096 borrows 1.78 GiB instead of 2.84 | +| PLE rows | The next chunk's PLE rows are read from the model file on a thread while the GPU works | bit-identical; 762 -> 790 at chunk 4096 | +| Chunk size | `--prefill auto`: the largest of 8192 / 6144 / 4096 / ... whose buffers fit in the cache slots it may borrow; a request borrows only what its own prompt needs | Q2_0: 4096 791, 6144 878, 8192 973 | +| Host copies | Experts the arena could not pin are copied to pinned buffers by helper threads instead of the launching thread | bit-identical; IQ3_S at 4096: 551 -> 652 | +| PLE block | Computed for the whole chunk (two GEMMs) instead of token by token | Q2_0 981 -> 1053, IQ3_S 831 -> 940 | +| Experts | llama.cpp's MMQ kernels (weights stay quantized, int8 tensor cores) instead of dequantize-to-FP16 + cuBLAS | Q2_0 1052 -> 1130, IQ3_S (8192) 932 -> 1014 | +| Streaming | At chunks of 2048+ every non-resident expert streams in a fixed order through a ring, so the next layer's arrive while the current layer's attention runs | bit-identical; Q2_0 1130 -> 1290, IQ3_S -> 1208 | + +Tried and dropped: cuBLAS grouped GEMMs for the experts (faster in isolation, slower inside the engine: 770 vs 790). + +## Before and after + +| | engine 0.1.12 (`--prefill 2048`) | engine 0.1.13 (`--prefill auto`) | +|---|---:|---:| +| Q2_0, 32K prompt | 572 | 1,290 | +| IQ3_S, 32K prompt | 383 | 1,208 | +| Server, Q2_0, 128K context, 999-token prompt | 353 | 438 | +| Server, 6,927-token prompt | 529 | 1,077 | +| Server, 28,584-token prompt | 584 | 1,249 | + +Output speed is unchanged (the decode path is the same). Short prompts (a few hundred tokens) go through the verify +windows as before. + +## Quality + +- "Bit-identical" steps were checked with the GDN state hash after the 32K prompt (all 36 recurrent layers). +- The steps that change rounding (the batched PLE block, MMQ's 8-bit activations) were compared teacher-forced: the + 32K prompt is read by the prompt path up to its last 256 tokens, those go through the token path with their logits + dumped. At 32K every rounding change moves the predictions about this much - even a different chunk size of the + unchanged engine - so that is the yardstick: + +| Against the 8192-chunk FP16 path | Same top-1 | Mean KL | Perplexity (reference 9.21) | +|---|---:|---:|---:| +| Chunk 6144, same code (the yardstick) | 89.8% | 0.33 | 9.18 | +| MMQ experts | 85.9% | 0.38 | 8.63 | + +- Needles (the answer hidden at a given depth): 5 of 5 at 1K, 32K, 128K (two depths) and 262K, Q2_0, KV streaming. +- A rerun of the same configuration is bit-identical. diff --git a/bench/results/2026-09-28-rope-scaling/README.md b/bench/results/2026-09-28-rope-scaling/README.md new file mode 100644 index 0000000..1624f43 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/README.md @@ -0,0 +1,49 @@ +# Rope scaling: needle recall past the trained 262K + +The feature (PR #84, experimental): `--rope-scaling none|linear|yarn` extends the context past the model's +trained 262,144 positions by rescaling the rotary angles - llama.cpp's types, ggml's `rope_yarn` +arithmetic, one process config applied at the cos/sin table (default path) and as kernel constants +(`--native-rope`, the native indexer, prefill). The three tables here are the first end-to-end check +that a scaled run actually recalls past the trained end. + +**Hardware:** RTX 4070 Ti SUPER 16 GB, Ryzen 9 5900X (no AVX-512 - the IQ3_XXS native pack runs its +expert kernels on AVX-2), 125 GB RAM, Linux. **Engine:** this branch built from source (the log records +`rope scaling ... --max-context ... against a trained context of 262144` at startup). The runs below +were taken on the rope tree built over the 0.1.17-era base; the branch then rebased onto main (engine +0.1.20) - the drift touches none of the rope files - and the rebase was re-validated: `rope_parity` +green, a 64-token greedy run token-identical to the plain 0.1.20 build, and the yarn 262k probe +repeated green (see the last table row). Baseline arm A also re-checked the default is the stock +model: a 64-token greedy run produces the same token ids as the ready-made 0.1.17 engine, and +`rope_parity` holds the `none` table bit-identical to the pre-scaling builder. +**Method:** `tools/needle_bench.py` against a running server (launch recipes in `config-*.json`), +`temperature 0`, thinking off, depth 50%, one probe per length. + +| Arm | Scaling | Context | Probe | Prompt tokens | Result | Probe time | +| --- | --- | --- | --- | --- | --- | --- | +| A | none | 262,144 | 1k @ 50% | 1,442 | FOUND | 4 s | +| A | none | 262,144 | 32k @ 50% | 31,763 | FOUND | 27 s | +| A | none | 262,144 | 128k @ 50% | 128,328 | FOUND | 86 s | +| B | linear, factor 2 | 560,000 | 262k @ 50% | 274,222 | FOUND | 232 s | +| B | linear, factor 2 | 560,000 | 512k @ 50% | 527,051 | FOUND | 619 s | +| C | yarn, factor 2 | 560,000 | 262k @ 50% | 274,215 | FOUND | 236 s | +| C | yarn, factor 2 | 560,000 | 512k @ 50% | 526,988 | FOUND | 615 s | +| C | yarn, factor 2 | 560,000 | 262k @ 50% (the rebase re-check) | 273,708 | FOUND | 235 s | + +All 8 of 8 probes found the needle; JSON per arm: `needle-A-none.json`, `needle-B-linear2.json`, +`needle-B-linear2-512k.json`, `needle-C-yarn2.json` (+ the rebase re-check in +`needle-C-yarn2-rebased.json`); server and engine logs alongside. + +What this establishes, and what it does not: + +- **Past the trained end the model still reads.** 512k probes are 2.01x the trained 262,144 - position + interpolation (B) and YaRN (C) both hold a mid-context lookup there. +- **Scaled runs within the trained range are a slightly different model.** `yarn`'s mscale applies at + every position (a 64-token greedy prompt diverges from the stock run after ~19 tokens); arm A is the + stock model, arms B/C are not, by design. +- **One depth, one needle, one machine.** A single probe per (length, arm) at depth 50% says "recall + works there", not "no degradation anywhere" - a full depth sweep and a longer-length ladder (768K, + 1M) on the bench machine (64 GB RAM there vs 125 GB here, so 262K IQ3_XXS fits either way) is the + natural follow-up. 512K prompts prefill at ~850-950 tokens/s on this card; the probe time is almost + entirely prefill. +- **The `560,000` context** in arms B/C is headroom for the needle harness's tokenizer overshoot + (a "512k" probe tokenizes to ~527k); 524,288 exactly would refuse the probe. diff --git a/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json b/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json new file mode 100644 index 0000000..528fc9f --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json @@ -0,0 +1,38 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "262144" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-A-none-262144.log" +} \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/config-B-linear2.json b/bench/results/2026-09-28-rope-scaling/config-B-linear2.json new file mode 100644 index 0000000..30b31d7 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/config-B-linear2.json @@ -0,0 +1,42 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "560000", + "--rope-scaling", + "linear", + "--rope-scale", + "2" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-B-linear2-524288.log" +} \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json b/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json new file mode 100644 index 0000000..6172a63 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json @@ -0,0 +1,42 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "560000", + "--rope-scaling", + "yarn", + "--rope-scale", + "2" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-C-yarn2-524288.log" +} \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json b/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json new file mode 100644 index 0000000..526b751 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json @@ -0,0 +1,121 @@ +[ + { + "length": "128k", + "round": 0, + "kind": "decode", + "prompt_tok": 128401, + "read": 52, + "gen": 357, + "read_tok_s": 79.2, + "gen_tok_s": 56.3, + "drafts_ok": 182, + "drafts_all": 305, + "seg_blocks": 3284340, + "seg_mib": 370.0, + "seg_misses": 91744, + "seg_hit_pct": 97.207, + "kib_per_token": 1061.29 + }, + { + "length": "128k", + "round": 1, + "kind": "read", + "prompt_tok": 128357, + "read": 128357, + "gen": 24, + "read_tok_s": 1389.2, + "gen_tok_s": 41.7, + "drafts_ok": 11, + "drafts_all": 23, + "seg_blocks": -3253560, + "seg_mib": -391.7, + "seg_misses": -97147, + "seg_hit_pct": 97.014, + "kib_per_token": -3.12 + }, + { + "length": "128k", + "round": 1, + "kind": "decode", + "prompt_tok": 128402, + "read": 52, + "gen": 388, + "read_tok_s": 76.5, + "gen_tok_s": 54.6, + "drafts_ok": 195, + "drafts_all": 363, + "seg_blocks": 3752616, + "seg_mib": 463.5, + "seg_misses": 114911, + "seg_hit_pct": 96.938, + "kib_per_token": 1223.26 + }, + { + "length": "512k", + "round": 0, + "kind": "read", + "prompt_tok": 522983, + "read": 522983, + "gen": 24, + "read_tok_s": 868.4, + "gen_tok_s": 42.4, + "drafts_ok": 13, + "drafts_all": 16, + "seg_blocks": -3808056, + "seg_mib": -387.8, + "seg_misses": -96113, + "seg_hit_pct": 97.476, + "kib_per_token": -0.76 + }, + { + "length": "512k", + "round": 0, + "kind": "decode", + "prompt_tok": 523028, + "read": 52, + "gen": 402, + "read_tok_s": 63.3, + "gen_tok_s": 48.4, + "drafts_ok": 221, + "drafts_all": 348, + "seg_blocks": 3580056, + "seg_mib": 920.4, + "seg_misses": 228658, + "seg_hit_pct": 93.613, + "kib_per_token": 2344.5 + }, + { + "length": "512k", + "round": 1, + "kind": "read", + "prompt_tok": 522984, + "read": 522984, + "gen": 24, + "read_tok_s": 857.1, + "gen_tok_s": 35.5, + "drafts_ok": 9, + "drafts_all": 18, + "seg_blocks": -3555408, + "seg_mib": -905.8, + "seg_misses": -225016, + "seg_hit_pct": 93.671, + "kib_per_token": -1.77 + }, + { + "length": "512k", + "round": 1, + "kind": "decode", + "prompt_tok": 523029, + "read": 52, + "gen": 402, + "read_tok_s": 61.3, + "gen_tok_s": 42.8, + "drafts_ok": 192, + "drafts_all": 388, + "seg_blocks": 4005216, + "seg_mib": 1079.9, + "seg_misses": 268221, + "seg_hit_pct": 93.303, + "kib_per_token": 2750.79 + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-A-none.json b/bench/results/2026-09-28-rope-scaling/needle-A-none.json new file mode 100644 index 0000000..099bd36 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-A-none.json @@ -0,0 +1,29 @@ +[ + { + "length": "1k", + "depth": 50, + "prompt_tokens": 1442, + "seconds": 3.7, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "32k", + "depth": 50, + "prompt_tokens": 31763, + "seconds": 27.5, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + }, + { + "length": "128k", + "depth": 50, + "prompt_tokens": 128328, + "seconds": 86.1, + "found": true, + "word": "willow-cobalt-696", + "answer": "willow-cobalt-696" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json b/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json new file mode 100644 index 0000000..e93f21d --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json @@ -0,0 +1,11 @@ +[ + { + "length": "512k", + "depth": 50, + "prompt_tokens": 527051, + "seconds": 619.0, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json b/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json new file mode 100644 index 0000000..7a98787 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json @@ -0,0 +1,16 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 274222, + "seconds": 232.2, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "512k", + "depth": 50, + "error": "HTTP Error 400: Bad Request" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json new file mode 100644 index 0000000..659f51a --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json @@ -0,0 +1,11 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 273708, + "seconds": 234.8, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json new file mode 100644 index 0000000..2dfa146 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json @@ -0,0 +1,20 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 274215, + "seconds": 235.5, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "512k", + "depth": 50, + "prompt_tokens": 526988, + "seconds": 615.0, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-speed-0114/README.md b/bench/results/2026-09-28-speed-0114/README.md new file mode 100644 index 0000000..f6c1aba --- /dev/null +++ b/bench/results/2026-09-28-speed-0114/README.md @@ -0,0 +1,32 @@ +# Speed with engine 0.1.14 + +RTX 5070 12 GB (PCIe 5.0 x16), Ryzen 5 7600, 64 GB DDR5-5200, Windows 10. The ready-made 0.1.14 engine, one-shot runs +with what setup writes: `--prefill auto`, the shipped expert profile, `--expert-cache auto`, 8-bit KV above 4K, KV +streaming (`--kv-resident 32768`) from 64K, MTP (`--spec 4 --spec-min-p 0.5`), greedy, 256 generated tokens. One +code-agent prompt per length (`bench/prompts/*/…-code-agent.ids`, the same prompts as `2026-09-24-final`). + +The tables: [`matrix.md`](matrix.md) (prompt and output speed, draft acceptance, experts in VRAM); every run in +[`matrix.json`](matrix.json). + +- **IQ2_XS** was measured with Swift 1.5's IQ2_XS (the original's file was not on the machine; the two run at the same + speed: 4K 465 vs 467 prompt tokens/s in `2026-09-24`). +- **IQ3_S at 128K** comes from a first pass during which a large download was running (the clean rerun of that row + was stopped when Windows ran short of memory); the other rows are from runs on an otherwise idle machine. +- **IQ3_XXS and IQ3_S at 262K** are not measured: with 43 / 50 GB of experts, a 260K context exceeds 64 GB of RAM. + +## Against 0.1.12 + +Prompts are 1.2x (1K) to 2.4x (32K-128K) faster: the 0.1.13 prompt path (chunks of up to 8,192 tokens, MMQ experts, +streamed expert copies; see `2026-09-28-prefill-speed`). + +Output speed moves with the text: speculative decoding is faster when more drafts are accepted, and the new prompt +path's rounding changes the answer, so the same prompt can land a few percent either way (Q2_0 32K: acceptance 0.865 +then, 0.709 now). The engine itself is not slower: on the 4K prompt, run back to back on the same machine state, +0.1.14 writes 88.5 tokens/s and 0.1.12 85.7 (3 runs each, same free VRAM). + +## Found on the way + +IQ3_XXS at 64K and 128K ended with `out of memory: cudaFuncSetAttribute` in the MMQ launch: CUDA loads a kernel's code +when it is first used, and mid-prompt there was no VRAM left for it. Loading every kernel at start +(`CUDA_MODULE_LOADING=EAGER`, which the engine now sets itself) fixes it for ~30 MB of VRAM; the IQ3_XXS 64K/128K rows +were measured with that fix. diff --git a/bench/results/2026-09-28-speed-0114/matrix.json b/bench/results/2026-09-28-speed-0114/matrix.json new file mode 100644 index 0000000..ca9501e --- /dev/null +++ b/bench/results/2026-09-28-speed-0114/matrix.json @@ -0,0 +1,322 @@ +[ + { + "model": "Q2_0", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 41.0, + "prefill_tok_s": 494.43, + "ttft_s": 3.55, + "decode_tok_s": 84.26, + "decoded": 256, + "spec_accept": 0.709, + "tokens_per_round": 2.72, + "vram_slots": 4176 + }, + { + "model": "Q2_0", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 41.2, + "prefill_tok_s": 1006.63, + "ttft_s": 5.05, + "decode_tok_s": 90.26, + "decoded": 256, + "spec_accept": 0.846, + "tokens_per_round": 3.23, + "vram_slots": 4123 + }, + { + "model": "Q2_0", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 63.1, + "prefill_tok_s": 1307.6, + "ttft_s": 25.63, + "decode_tok_s": 73.61, + "decoded": 256, + "spec_accept": 0.709, + "tokens_per_round": 2.68, + "vram_slots": 3833 + }, + { + "model": "Q2_0", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 89.0, + "prefill_tok_s": 1293.5, + "ttft_s": 51.12, + "decode_tok_s": 69.02, + "decoded": 256, + "spec_accept": 0.679, + "tokens_per_round": 2.62, + "vram_slots": 3780 + }, + { + "model": "Q2_0", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 147.4, + "prefill_tok_s": 1208.46, + "ttft_s": 107.81, + "decode_tok_s": 67.21, + "decoded": 256, + "spec_accept": 0.691, + "tokens_per_round": 2.64, + "vram_slots": 3697 + }, + { + "model": "Q2_0", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 309.8, + "prefill_tok_s": 966.84, + "ttft_s": 270.35, + "decode_tok_s": 60.3, + "decoded": 256, + "spec_accept": 0.623, + "tokens_per_round": 2.43, + "vram_slots": 3525 + }, + { + "model": "IQ2_XS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 40.4, + "prefill_tok_s": 461.28, + "ttft_s": 2.28, + "decode_tok_s": 74.38, + "decoded": 256, + "spec_accept": 0.772, + "tokens_per_round": 2.84, + "vram_slots": 4386, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 41.8, + "prefill_tok_s": 810.71, + "ttft_s": 4.48, + "decode_tok_s": 73.84, + "decoded": 256, + "spec_accept": 0.79, + "tokens_per_round": 3.24, + "vram_slots": 4336, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 65.0, + "prefill_tok_s": 1237.98, + "ttft_s": 25.59, + "decode_tok_s": 71.49, + "decoded": 256, + "spec_accept": 0.856, + "tokens_per_round": 3.28, + "vram_slots": 4057, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 97.1, + "prefill_tok_s": 1135.63, + "ttft_s": 56.59, + "decode_tok_s": 64.29, + "decoded": 256, + "spec_accept": 0.707, + "tokens_per_round": 2.76, + "vram_slots": 4005, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 158.0, + "prefill_tok_s": 1070.61, + "ttft_s": 120.1, + "decode_tok_s": 59.76, + "decoded": 256, + "spec_accept": 0.726, + "tokens_per_round": 2.69, + "vram_slots": 3923, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 332.4, + "prefill_tok_s": 886.2, + "ttft_s": 293.43, + "decode_tok_s": 52.83, + "decoded": 256, + "spec_accept": 0.628, + "tokens_per_round": 2.53, + "vram_slots": 3565, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 44.1, + "prefill_tok_s": 414.55, + "ttft_s": 2.54, + "decode_tok_s": 60.26, + "decoded": 256, + "spec_accept": 0.864, + "tokens_per_round": 3.52, + "vram_slots": 3304, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 45.8, + "prefill_tok_s": 769.57, + "ttft_s": 4.73, + "decode_tok_s": 62.07, + "decoded": 256, + "spec_accept": 0.855, + "tokens_per_round": 3.24, + "vram_slots": 3263, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 69.7, + "prefill_tok_s": 1107.75, + "ttft_s": 28.61, + "decode_tok_s": 51.4, + "decoded": 256, + "spec_accept": 0.678, + "tokens_per_round": 2.6, + "vram_slots": 3031, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 104.9, + "prefill_tok_s": 1065.31, + "ttft_s": 61.77, + "decode_tok_s": 49.95, + "decoded": 256, + "spec_accept": 0.741, + "tokens_per_round": 2.94, + "vram_slots": 2965, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 172.1, + "prefill_tok_s": 1015.11, + "ttft_s": 128.12, + "decode_tok_s": 45.78, + "decoded": 256, + "spec_accept": 0.665, + "tokens_per_round": 2.35, + "vram_slots": 2901, + "note": "first pass" + }, + { + "model": "IQ3_S", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 56.2, + "prefill_tok_s": 396.13, + "ttft_s": 4.14, + "decode_tok_s": 51.52, + "decoded": 256, + "spec_accept": 0.826, + "tokens_per_round": 3.12, + "vram_slots": 2617 + }, + { + "model": "IQ3_S", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 57.5, + "prefill_tok_s": 736.9, + "ttft_s": 6.35, + "decode_tok_s": 51.6, + "decoded": 256, + "spec_accept": 0.747, + "tokens_per_round": 2.89, + "vram_slots": 2580 + }, + { + "model": "IQ3_S", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 82.5, + "prefill_tok_s": 1069.83, + "ttft_s": 31.33, + "decode_tok_s": 48.19, + "decoded": 256, + "spec_accept": 0.772, + "tokens_per_round": 2.94, + "vram_slots": 2383 + }, + { + "model": "IQ3_S", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 115.0, + "prefill_tok_s": 1069.8, + "ttft_s": 61.47, + "decode_tok_s": 48.75, + "decoded": 256, + "spec_accept": 0.786, + "tokens_per_round": 2.9, + "vram_slots": 2347 + }, + { + "model": "IQ3_S", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 191.8, + "prefill_tok_s": 931.09, + "ttft_s": 138.11, + "decode_tok_s": 40.48, + "decoded": 256, + "spec_accept": 0.661, + "tokens_per_round": 2.71, + "vram_slots": 2310, + "note": "first pass (a download was running)" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-speed-0114/matrix.md b/bench/results/2026-09-28-speed-0114/matrix.md new file mode 100644 index 0000000..5a92ac6 --- /dev/null +++ b/bench/results/2026-09-28-speed-0114/matrix.md @@ -0,0 +1,35 @@ +### Prompt processing (tok/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Q2_0 | 494 | 1,007 | 1,308 | 1,294 | 1,208 | 967 | +| IQ2_XS | 461 | 811 | 1,238 | 1,136 | 1,071 | 886 | +| IQ3_XXS | 415 | 770 | 1,108 | 1,065 | 1,015 | - | +| IQ3_S | 396 | 737 | 1,070 | 1,070 | 931 | - | + +### Output (tok/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Q2_0 | 84.3 | 90.3 | 73.6 | 69.0 | 67.2 | 60.3 | +| IQ2_XS | 74.4 | 73.8 | 71.5 | 64.3 | 59.8 | 52.8 | +| IQ3_XXS | 60.3 | 62.1 | 51.4 | 50.0 | 45.8 | - | +| IQ3_S | 51.5 | 51.6 | 48.2 | 48.8 | 40.5 | - | + +### Draft acceptance + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Q2_0 | 0.709 | 0.846 | 0.709 | 0.679 | 0.691 | 0.623 | +| IQ2_XS | 0.772 | 0.790 | 0.856 | 0.707 | 0.726 | 0.628 | +| IQ3_XXS | 0.864 | 0.855 | 0.678 | 0.741 | 0.665 | - | +| IQ3_S | 0.826 | 0.747 | 0.772 | 0.786 | 0.661 | - | + +### Experts in VRAM + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Q2_0 | 4,176 | 4,123 | 3,833 | 3,780 | 3,697 | 3,525 | +| IQ2_XS | 4,386 | 4,336 | 4,057 | 4,005 | 3,923 | 3,565 | +| IQ3_XXS | 3,304 | 3,263 | 3,031 | 2,965 | 2,901 | - | +| IQ3_S | 2,617 | 2,580 | 2,383 | 2,347 | 2,310 | - | diff --git a/bench/results/2026-09-29-layer-split-limits/README.md b/bench/results/2026-09-29-layer-split-limits/README.md new file mode 100644 index 0000000..017c9d4 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/README.md @@ -0,0 +1,59 @@ +# Layer split: the features that were off across GPUs (2026-09-29) + +**Setup:** +- **Rig:** RIBPC. RTX 5080 16 GB (CUDA0) + RTX 3090 24 GB; RTX 2080 Ti 22 GB as a helper card. Ryzen 9 9950X3D, + 62 GB RAM, Windows 11. +- **Model:** the Coder (IQ1_M native pack). +- **Build:** branch `mg/limits`, sm_75 + sm_86 + sm_120. +- **Correctness runs:** `rib_norepeat.py`, with a fixed cache, no swaps, no PCIe share and no suffix drafts where two + runs are compared byte for byte. +- **Speed runs:** `rib_pp.py`. +- Raw results are in `data/`. + +## Correctness + +| Check | Result | +|---|---| +| One GPU, this branch vs the 0.1.21-equivalent run (fixed cache) | 10/10 byte-identical | +| Speed projection (control vector), one GPU vs the split on the same GPU (K=24) | 10/10 byte-identical | +| KV streaming (128K context, 32K resident), one GPU vs the split on the same GPU | 10/10 byte-identical | +| Images, one GPU vs the split on the same GPU (three questions about a test picture) | identical answers | +| Speed projection / KV streaming / plain, 5080 + 3090 (K=24): no-repeat under presence 100, the 144 sanity case | all pass, 0 repeats | +| The vector acts across GPUs: 5080 + 3090 with vs without the vector | 8 of 10 answers differ (as on one GPU: 7 of 10) | +| Images, 5080 + 3090 (K=24): "What color is the circle?" / "What number?" / describe | "Red" / "42" / "A red circle, the number 42, and a blue square are displayed on a white background" | +| Mid-prompt checkpoint (every 16,384 tokens): a 19.5K prompt, then another sharing its first 18,600 tokens | one GPU and 5080 + 3090: reused 16,384, answer right | +| 5080 + 3090 (K=30) + a 2080 Ti helper holding 3,000 experts | all pass | +| `--mmap-experts` with the Coder (a native pack) | a clear start-up error: it needs a canonical pack's `experts.bin` (with or without a split) | + +Across GPUs the text is not byte-identical to one GPU: experts that one card leaves to the CPU run on a GPU in the +split, and the two round differently. + +## Speed + +| Run | Prompt 16K / 28K / 60K tok/s | Decode story / code tok/s | Hits | +|---|---|---|---| +| KV streaming (128K), 5080 alone | 1,487 / 1,801 / 1,837 | 66.6 / 74.0 | 59-71% | +| KV streaming (128K), 5080 + 3090 auto | 1,685 / 1,957 / 1,968 | 75.8 / 97.0 | 96-97% | +| Speed projection, 5080 + 3090 auto | 1,813 / 2,053 / - | 77.0 / 103.6 | 96-97% | +| 5080 + 3090 (K=30), no helper | - | 62.5 / 85.2 | | +| 5080 + 3090 (K=30) + 2080 Ti helper | - | 43.0 / 63.7 | | + +**The helper card makes it slower,** as it did without a split (bench/results/2026-09-29-layer-split). Its per-layer +round trip costs more than the CPU pool needs for the few experts it would take over. It stays supported: the +helpers take the visible GPUs no stage runs on and hold only experts no stage's cache holds. But it isn't +recommended. + +## What changed + +- **Per-device tables:** the image-position (mrope) table and the control vector's tables are now kept per device; + every stage's rope and steering kernels read their own device's copy. `cvec_set_enabled` switches the vector on + every device. +- **KV streaming:** each stage's session streams its own KV host copy (pinned, portable). The split no longer forces + it off. +- **Mid-prompt checkpoints:** `Prefill::on_stage_chunk` lets each stage save its part of a checkpoint when it has + read the chunk. The last stage assembles the parts: the earlier ones are a chunk ahead by then. +- **Helpers (`--expert-cache-remote`) with a split:** they take the visible devices after the stages, skip every + pair a stage's cache holds, and preflight and open on those devices. +- **Explicit `--expert-cache` with a split:** it is capped so CUDA0 keeps room for the prompt path's own buffers. + Without the cap, the first prompt failed with "device buffers ... do not fit". +- **`--mmap-experts`:** refused at start for a native pack, with the reason. diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-same24-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-same24-coder-iq1_m.json new file mode 100644 index 0000000..d36b8ba --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-same24-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 102, + "drafts_offered": 166, + "tok_s": 66.7, + "text": "The wind didn\u2019t just howl; it screamed. It tore through the iron gallery of the Blackwood Point Light, rattling the glass panes like a prisoner testing the bars of a cell.\n\nElias Thorne was not a man who feared the dark. He was a man who feared the silence.\n\nFor forty years, he had lived in the shadow of the Fresnel lens, a rotating eye of glass and brass that swept the Atlantic with a beam of pure, unyielding light. His job was simple: keep the light burning. Keep the logbook current. Keep the foghorn sounding when the mist rolled in, thick as wool.\n\nBut Elias knew something else. He knew that the light was not just for ships. It was for the lost.\n\nIt was November 14th, 1982. The storm was a Category 5, a monster that had swallowed the horizon. The waves were mountains of black water, crashing against the granite" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 134, + "drafts_offered": 180, + "tok_s": 80.8, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 72.5, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.6, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 104, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 92, + "tok_s": 45.4, + "text": "Aardvark \nAlbatross \n\nAlligator \nAnaconda \nAntelope \nBaboon \nBadger \nBat \nBear \nBeaver \nBirds of Paradise (Manucode) \nBoa Constrictor \n\nBuffalo \nCamel \nCapybara \nCat \nChameleon\nCheetah\n\nChicken\n\n\nCrocodile \nDeer \n\nDingo \nDog \nDonkey \nDragonfly \n\nElephant \nEmu \nFalcon \nFerret \nFlamingo \nFox<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 72, + "repeats": 0, + "drafts_accepted": 15, + "drafts_offered": 70, + "tok_s": 46.1, + "text": "The wind didn\u2019t just howl; it screamed against the glass of Lantern House 42, demanding entry into every crack and crevice that had been sealed with tar in previous years but now wept like old wounds on an open sore skin\u2014like a wound left unhealed by time. Elias knew this rhythm better than he remembered his own name<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 76, + "tok_s": 49.3, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in my teeth, searching for something to break its rhythm against stone that refused be broken by anything less than God himself had forged into being willing and able withstand eternity\u2019s cruelty without complaint or mercy from start finish until now forevermore if any such concept even existed within human comprehension let alone divine authority which we all knew did not exist but wished it would because wishful thinking is always easier to imagine hopelessly impossible truths as probable lies than vice versa.\n\nElias Thorne was eighty-three years old today, exactly one hundred and forty-seven days since his last heart attack had been logged by Dr Armitage who himself retired seven months ago after receiving a subpoena from the county clerk indicating he might have overstayed professional courtesy boundaries" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 94, + "repeats": 0, + "drafts_accepted": 27, + "drafts_offered": 56, + "tok_s": 46.7, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippo \nRhino \nCheetah \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nElk \nMoose \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nBull \nOx \nPig \nBoar \nRabbit \nSquirrel <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 62.4, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 148, + "tok_s": 56.4, + "text": "The phrase \"the History Of The Sea\" is inherently ambiguous, as it could refer to several distinct historical narratives: geological formation (how oceans came into existence), maritime navigation and exploration by humans throughout human civilization; or perhaps more specifically in modern times refers often used metaphorically for economic trends like stock market fluctuations (\"sea change\"). However given your request likely intends an academic-style comprehensive overview covering both natural science aspects AND cultural significance through time periods\u2014especially since this kind question appears frequently on exams asking students write essays discussing evolution from primordial origins up present-day impacts including environmental changes due climate crisis etc.\u2014I will craft such broad yet structured piece combining geology + anthropology/ecological impact together while maintaining coherent flow suitable high-level educational context without overly technical jargon but still accurate enough scientifically grounded facts where appropriate within reasonable scope limits typical school assignments expect (~80\u201312% word count range implied implicitly though not stated explicitly here we aim moderate length ~65 words? Wait no user said \u201clong\u201d so probably >3k+ characters minimum safe bet around 7-9 paragraphs total approximating maybe close-to-full-page standard double-spaced equivalent which translates roughly \u22654K chars safely acceptable). Let me proceed accordingly ensuring clarity structure intro body conclusion style formal tone neutral informative balanced perspective acknowledging uncertainties if any minor ones exist e.g exact dates vary depending sources hence use hedging language sparingly only when necessary avoid overclaiming certainty especially regarding speculative theories vs established consensus knowledge base current mainstream understanding circa early-mid" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-single-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-single-coder-iq1_m.json new file mode 100644 index 0000000..503a7a2 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-single-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 102, + "drafts_offered": 166, + "tok_s": 67.1, + "text": "The wind didn\u2019t just howl; it screamed. It tore through the iron gallery of the Blackwood Point Light, rattling the glass panes like a prisoner testing the bars of a cell.\n\nElias Thorne was not a man who feared the dark. He was a man who feared the silence.\n\nFor forty years, he had lived in the shadow of the Fresnel lens, a rotating eye of glass and brass that swept the Atlantic with a beam of pure, unyielding light. His job was simple: keep the light burning. Keep the logbook current. Keep the foghorn sounding when the mist rolled in, thick as wool.\n\nBut Elias knew something else. He knew that the light was not just for ships. It was for the lost.\n\nIt was November 14th, 1982. The storm was a Category 5, a monster that had swallowed the horizon. The waves were mountains of black water, crashing against the granite" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 134, + "drafts_offered": 180, + "tok_s": 81.0, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 62.4, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 73.4, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 104, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 92, + "tok_s": 43.5, + "text": "Aardvark \nAlbatross \n\nAlligator \nAnaconda \nAntelope \nBaboon \nBadger \nBat \nBear \nBeaver \nBirds of Paradise (Manucode) \nBoa Constrictor \n\nBuffalo \nCamel \nCapybara \nCat \nChameleon\nCheetah\n\nChicken\n\n\nCrocodile \nDeer \n\nDingo \nDog \nDonkey \nDragonfly \n\nElephant \nEmu \nFalcon \nFerret \nFlamingo \nFox<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 72, + "repeats": 0, + "drafts_accepted": 15, + "drafts_offered": 70, + "tok_s": 46.1, + "text": "The wind didn\u2019t just howl; it screamed against the glass of Lantern House 42, demanding entry into every crack and crevice that had been sealed with tar in previous years but now wept like old wounds on an open sore skin\u2014like a wound left unhealed by time. Elias knew this rhythm better than he remembered his own name<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 76, + "tok_s": 48.9, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in my teeth, searching for something to break its rhythm against stone that refused be broken by anything less than God himself had forged into being willing and able withstand eternity\u2019s cruelty without complaint or mercy from start finish until now forevermore if any such concept even existed within human comprehension let alone divine authority which we all knew did not exist but wished it would because wishful thinking is always easier to imagine hopelessly impossible truths as probable lies than vice versa.\n\nElias Thorne was eighty-three years old today, exactly one hundred and forty-seven days since his last heart attack had been logged by Dr Armitage who himself retired seven months ago after receiving a subpoena from the county clerk indicating he might have overstayed professional courtesy boundaries" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 94, + "repeats": 0, + "drafts_accepted": 27, + "drafts_offered": 56, + "tok_s": 46.8, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippo \nRhino \nCheetah \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nElk \nMoose \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nBull \nOx \nPig \nBoar \nRabbit \nSquirrel <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 63.1, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 148, + "tok_s": 56.6, + "text": "The phrase \"the History Of The Sea\" is inherently ambiguous, as it could refer to several distinct historical narratives: geological formation (how oceans came into existence), maritime navigation and exploration by humans throughout human civilization; or perhaps more specifically in modern times refers often used metaphorically for economic trends like stock market fluctuations (\"sea change\"). However given your request likely intends an academic-style comprehensive overview covering both natural science aspects AND cultural significance through time periods\u2014especially since this kind question appears frequently on exams asking students write essays discussing evolution from primordial origins up present-day impacts including environmental changes due climate crisis etc.\u2014I will craft such broad yet structured piece combining geology + anthropology/ecological impact together while maintaining coherent flow suitable high-level educational context without overly technical jargon but still accurate enough scientifically grounded facts where appropriate within reasonable scope limits typical school assignments expect (~80\u201312% word count range implied implicitly though not stated explicitly here we aim moderate length ~65 words? Wait no user said \u201clong\u201d so probably >3k+ characters minimum safe bet around 7-9 paragraphs total approximating maybe close-to-full-page standard double-spaced equivalent which translates roughly \u22654K chars safely acceptable). Let me proceed accordingly ensuring clarity structure intro body conclusion style formal tone neutral informative balanced perspective acknowledging uncertainties if any minor ones exist e.g exact dates vary depending sources hence use hedging language sparingly only when necessary avoid overclaiming certainty especially regarding speculative theories vs established consensus knowledge base current mainstream understanding circa early-mid" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-x2-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-x2-coder-iq1_m.json new file mode 100644 index 0000000..3599ae8 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-x2-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 85, + "drafts_offered": 172, + "tok_s": 36.6, + "text": "The wind didn\u2019t just howl; it screamed. It tore through the gaps in the iron railing of the Lantern Room, carrying the scent of brine and rotting kelp. Elias pulled his woolen collar up to his chin, his fingers numb and clumsy inside thick leather gloves.\n\nHe was the last man on the island. The automated systems had failed three winters ago, a glitch in the solar-powered backup that no engineer had been able to fix before the supply boat stopped coming. Now, it was just him, the light, and the sea.\n\nElias climbed the spiral stairs, his boots heavy with salt spray. The iron steps groaned under his weight, a sound that seemed to mock the storm outside. He reached the top, the glass walls vibrating with the force of the gale. Outside, the world was a blur of black and white. The ocean was invisible; it was only a presence, a weight pressing against the stone foundation of the tower.\n\nHe" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 173, + "tok_s": 96.8, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 88.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 94.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 104, + "repeats": 0, + "drafts_accepted": 30, + "drafts_offered": 96, + "tok_s": 55.9, + "text": "Aardvark \nAlbatross \n\nAlligator \nAnaconda \nAntelope \nBaboon \nBadger \nBat \nBear \nBeaver \nBirds of Paradise (Manucode) \nBoa Constrictor \n\nBuffalo \nCamel \nCapybara \nCat \nChameleon\nCheetah\n\nChicken\n\n\nCrocodile \nDeer \n\nDingo \nDog \nDonkey \nDragonfly \n\nElephant \nEmu \nFalcon \nFerret \nFlamingo \nFox<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 114, + "tok_s": 55.4, + "text": "The wind didn\u2019t just howl; it screamed against the glass of Lantern House 42, demanding entry into every crack and crevice that had been sealed with tar in previous years but now wept like old wounds at this one\u2019s age: forty-three winters since its construction. My name was Elias Thorne\u2014no middle initial\u2014and I kept no logbook for visitors because there were none; only ships passed by, their hulls cutting through the black water as if they too feared what lay beneath it more than above or beside them in fog so thick that even my own reflection vanished from sight when looked upon directly.\n\nI climbed each morning not to greet dawn but check whether light still lived within me\u2014the bulb\u2019s heart had failed twice before, once during a storm named *Harrow*," + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 110, + "tok_s": 52.2, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in my teeth, searching for something to hold onto until I died.\u201d said Elias Thorne as he adjusted his collar against November\u2019s bite.** He was not merely complaining of cold weather but articulating a poetic metaphor: that even after death (metaphorically), there would be no relief from this relentless gale.\n\nElias had been the last human keeper on any significant stretch coast since automation became standard practice, yet here he stood , stubbornly refusing to let technology replace his vigilance . His cottage perched atop a crumbling granite foundation was more than just shelter; it housed centuries of handwritten logs detailing every ship\u2019s name and cargo load that passed within sight.\n\nOn most nights Elias tended the light mechanically\u2014" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 91, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 69, + "tok_s": 58.7, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippopotamus \nRhinoceros \nLeopard \nCheetah \nPanther \nWolf \nFox \nBear \nDeer \nElk \nMoose \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nBull \nOx \nPig \nDog \nCat<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 12, + "repeats": 0, + "drafts_accepted": 4, + "drafts_offered": 17, + "tok_s": 60.3, + "text": "1 2,3456789<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 41, + "drafts_offered": 168, + "tok_s": 59.9, + "text": "The phrase \"the History Of The Sea\" is inherently ambiguous, as it could refer to several distinct historical narratives: geological formation (how oceans came into existence), maritime navigation and exploration histories (\"history at/over/across/on/in/of/to/from/toward/off by means around above below through under upon alongside against among between within without throughout despite during after before since until while when where who whom whose which what how why whether\"), or perhaps even metaphorical interpretations involving human interaction with water bodies over time periods like ages eras epochs generations centuries decades years months days hours minutes seconds moments instants times occasions instances events episodes incidents occurrences situations circumstances conditions states phases stages steps processes procedures sequences series chains cycles loops repetitions iterations continuations progressions developments evolutions transformations changes alterations modifications adjustments corrections revisions amendments updates upgrades improvements enhancements refinements optimizations perfecting completing finishing concluding ending terminating ceasing stopping halting pausing resuming continuing proceeding advancing progressing moving shifting translating rotating reflecting mirroring flipping turning twisting bending curving arches spirals helix coils twists turns rotations reflections mirrors flips inversions reversings reversion backtracking retracing reversing undo redo do again repeat repeats repeated repeatedly repetition repetitive repetitiveness repete repeater repeatingly recurrent recurrence recurring recurs recur recurred recursion recursive recursively recurse recessed recessionary regress regression regressed retrograde reverse reversed reversal revert reverted reverberate resonated echo echoed echoing echoes echolocation sonar radar radio telecommunication communication communications communicate communicated communicating communicative comms comm chatter chat chats chatting chatted talk talks talked" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp0-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp0-coder-iq1_m.json new file mode 100644 index 0000000..c8e5f09 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp0-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 171, + "tok_s": 62.5, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from broken glass and rusted iron, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, ensuring the rotation was smooth, silent, and precise. *Tick. Tick. Tick.* The sound was the heartbeat of the coast." + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 184, + "tok_s": 85.2, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 78.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 80.5, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 59, + "repeats": 0, + "drafts_accepted": 13, + "drafts_offered": 48, + "tok_s": 46.6, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBuffalo \n\nCat \nCheetah \n\nChimpanzee \nClam \n\n\nCrocodile \n\n\n\nDolphin \n\n\n\n\nDonkey <|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 30, + "drafts_offered": 101, + "tok_s": 51.3, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots smelled faintly brine and old coffee as he climbed spiral stairs worn smooth by decades feet his hands were calloused from gripping iron railings that had been polished to a dull shine\n\nElias was not merely keeping light alive; He kept order intact. Every night, at precisely 18:07 hours local time\u2014adjusted for leap seconds and magnetic drift\u2014he wound the clockwork mechanism inside brass housing behind Fresnel lens This wasn\u2019t vanity It\u2019s necessity The rotation speed must remain constant or ships lose their bearing in fog where compasses fail\n\nHe spoke softly to himself while working, murmuring numbers aloud because silence made him" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 67, + "repeats": 0, + "drafts_accepted": 14, + "drafts_offered": 68, + "tok_s": 41.2, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, like he had no mouth to hold back its fury anymore that night.\u201d Elara pulled her wool coat tighter around herself as she climbed spiral staircase of **Blackrock Lighthouse**. Her boots were slick with salt spray from previous days.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 91, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 54, + "tok_s": 48.8, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nHippopotamus \nRhinoceros \nCamel \nCheetah \nLeopard \nJaguar \nBear \nWolf \nFox \nDog \nCat \nMouse \nRat \nSquirrel \nDeer \n\nAntelope \n\nBuffalo \n\n\nBison \n\n\n\nElk \n\n\n\n\nMoose <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 11, + "tok_s": 68.8, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 32, + "drafts_offered": 107, + "tok_s": 52.3, + "text": "The ocean is not merely water; it has been, and remains to this day one giant storybook that weaves together geology with biology as wellas human culture into an epic narrative spanning billions years from its earliest beginnings in primordial times through modern-day ecological crises The vast expanse covers more than seventy percent Earth\u2019s surface area making up nearly all life support systems on our planet yet despite being so large humans have only explored less five thousand square kilometers out total 361 million km\u00b2 which means over ninety-nine point nine eight six per cent unexplored territory This makes oceans arguably larger unknown territories compared space exploration where NASA estimates they\u2019ve mapped roughly ten billion stars versus current marine surveys covering just two hundred fifty-six species documented globally against estimated millions undiscovered organisms including deep-sea creatures like anglerfish or vampire squid whose existence was first recorded centuries ago but still remain poorly understood due extreme pressures depths exceeding eleven miles below Pacific Trenches Mariana located near Guam island chain reaching maximum depth known today at approximately thirty-seven feet under pressure equivalent atmospheric levels causing structural collapse if unprotected by specialized vessels capable handling such conditions without failure mechanisms designed specifically for submersible operations operating within these zones require titanium hulls rated withstand forces greater gravity acting upon objects falling vertically downward acceleration rates calculated using Newtonian physics principles applied universally across gravitational fields regardless medium density variations present throughout different layers stratosphere troposphere mesospheres thermoclines etceterally speaking however when discussing aquatic environments instead air masses replace gases dissolved oxygen nitrogen arg" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp1-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp1-coder-iq1_m.json new file mode 100644 index 0000000..d8fb5e0 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp1-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 94, + "drafts_offered": 169, + "tok_s": 43.0, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and he had been the keeper of the Blackwood Point Light for forty of those years. The other thirty-three had been spent in a small, drafty cottage that smelled perpetually of kerosene and damp wood.\n\nFor decades, Elias had tended the great Fresnel lens, polishing the glass prisms until they gleamed like diamonds, winding the clockwork mechanism that turned the beam, and trimming the wick of the oil lamp. It was a job of patience, of precision, of silence. The light was his charge. The sea was his neighbor.\n\nBut this morning, the sea was not his neighbor. It was his enemy.\n\nThe storm had been forecasted for three days, but it had arrived in one. The barometric pressure had dropped so sharply that Elias\u2019s ears popped." + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 178, + "tok_s": 63.7, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 56.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 57.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 94, + "repeats": 0, + "drafts_accepted": 24, + "drafts_offered": 49, + "tok_s": 43.3, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nHippopotamus \nRhinoceros \nCheetah \nLeopard \nJaguar \nPuma \nWolf \nFox \nBear \nDeer \nElk \nMoose \nAntelope \nBison \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nDog \nCat \nRabbit \nMouse \nHamster \nGuinea Pig<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 35, + "drafts_offered": 108, + "tok_s": 41.4, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots smelled faintly brine and old coffee as he climbed spiral stairs worn smooth by decades feet his hands were calloused from gripping iron railings that had been polished to a dull shine.\n\nElias wasn\u2019t just keeping light; was guarding silence the beam swept across black water every seven seconds cutting through fog so thick it swallowed sound entirely for three nights straight no ships answered its signal not even fishing trawlers seeking shelter they\u2019d long abandoned this stretch of coast where currents shifted unpredictably pulling debris from sunken wrecks into tangled heaps that snagged anchors and tore hulls open like wounds.\n\nHe remembered the last time someone had" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 59, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 46, + "tok_s": 33.7, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, trying to pry them apart like loose planks of weathered oak outside your own mouth again and then you are going away from home is fine but for now let me write a proper story.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 60, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 48, + "tok_s": 43.2, + "text": "Aardvark \nAntelope allonax (Oryx) \u2013 *Note: Using standard names for clarity* \n\nLet me provide a clean list of exactly **1** animal name on each single physical text file/terminal output stream with no other characters except the newline (\\n).<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 11, + "tok_s": 48.9, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 27, + "drafts_offered": 105, + "tok_s": 40.2, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element\u2014it became civilization itself through its capacity as both barrier (to land) but also conduit between lands\u2014and thus gave rise directly from being part nature\u2019s own evolutionary engine into becoming humanity's greatest historical actor across all time scales since first emergence until now present-day future projections still ongoing today within our current era context window limits allowed here by system constraints set above threshold levels required before output generation begins below line break marker inserted immediately after final punctuation mark ending entire preceding paragraph block structure defined earlier during initial drafting phase prior execution stage completed successfully without errors detected internally via internal validation routines executed automatically upon completion cycle termination signal received end-of-file condition triggered correctly according standard protocol specifications followed strictly adhered-to throughout process flow control logic implemented using structured programming constructs compatible with target runtime environment configuration parameters specified herein explicitly declared beforehand at top-level scope declaration section located near beginning source code file header comments included inline documentation style guidelines observed consistently applied uniformly everywhere else similarly formatted sections appearing later down document body text area scrolling vertically downward directionally aligned left margin justified right edge wrapped around fixed-width column boundaries determined dynamically based available screen real estate measured pixel-per-unit scaling factor adjusted responsively depending viewport dimensions reported back client-side rendering pipeline components responsible" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-same24-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-same24-coder-iq1_m.json new file mode 100644 index 0000000..c2e69fe --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-same24-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 94, + "drafts_offered": 167, + "tok_s": 62.7, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to hold the chaos of the ocean at bay. The beam swept out, a blade of pure, concentrated light cutting through the rain and sleet, illuminating the jagged teeth of the reef below.\n\n" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 179, + "tok_s": 81.3, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 71.0, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 71.9, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 52, + "tok_s": 47.9, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFalcon <|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 122, + "tok_s": 47.4, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach his post at dawn every morning for thirty years. His name was written on a brass plaque by door: **Elias Thorne**.\n\nHe wasn\u2019t just keeping light; He kept time, weathered hands gripping the cold iron railing until knuckles turned white against frostbite and windburn that never healed fully because they were always there waiting to be felt again when he stepped outside into storm or calm alike. The lens above him was a Fresnel giant\u2019s eye made of hand-ground crystal prisms each one polished daily with chamois cloth soaked in whale" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 65, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 58, + "tok_s": 42.6, + "text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they slammed against their hinges every night for eleven months of winter and summer alike.\u201d I had never seen calm water here\u2014only gray churning seas that swallowed ships smaller than themselves<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 101, + "repeats": 0, + "drafts_accepted": 32, + "drafts_offered": 53, + "tok_s": 49.4, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nCheetah \nHippopotamus \nRhinoceros \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nOtter \nBeaver \nBadger \nMongoose \nMeerkat \nHyena \nJackal \nAntelope \nBison \nElk \nCaribou \nLlama \nAlpace <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 12, + "tok_s": 64.7, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 52, + "drafts_offered": 148, + "tok_s": 49.9, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by hundreds millions years yet continues shaping every aspect from climate regulation through evolutionary biology down even into modern industrial logistics today's global supply chains depend upon them directly indirectly via atmospheric pressure systems weather patterns migration routes food webs carbon cycles oxygen generation thermal buffering tidal forces salinity gradients depth stratification light attenuation currents circulation gyres upwelling zones thermoclines halothermics bathymetric features continental shelves abyssal plains trenching ridges volcanic arcs island formations atoll structures seamounts submarine canons canyon walls cliff faces overhang ledge platforms reef flats fore-reef back-lagoon inner-shelf outer-slope drop-offs pinnacle pinnacles spires columns arches tunnels caves grottos swim-through passages chimney vents blowholes fissures cracks crevices joints faults fractures breaks gaps holes openings void spaces hollow chambers cavernous interiors subterranean networks underground rivers lakes pools springs wells shaft pits sinks drains sewers pipes conduits tubes channels gutters ditches furrows grooves rills runnels streams brooks rivulets creeks tributaries branches forks splits divergences con" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-single-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-single-coder-iq1_m.json new file mode 100644 index 0000000..cd49d8c --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-single-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 94, + "drafts_offered": 167, + "tok_s": 49.2, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to hold the chaos of the ocean at bay. The beam swept out, a blade of pure, concentrated light cutting through the rain and sleet, illuminating the jagged teeth of the reef below.\n\n" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 179, + "tok_s": 76.2, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 73.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 73.4, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 52, + "tok_s": 47.1, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFalcon <|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 122, + "tok_s": 47.0, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach his post at dawn every morning for thirty years. His name was written on a brass plaque by door: **Elias Thorne**.\n\nHe wasn\u2019t just keeping light; He kept time, weathered hands gripping the cold iron railing until knuckles turned white against frostbite and windburn that never healed fully because they were always there waiting to be felt again when he stepped outside into storm or calm alike. The lens above him was a Fresnel giant\u2019s eye made of hand-ground crystal prisms each one polished daily with chamois cloth soaked in whale" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 65, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 58, + "tok_s": 42.3, + "text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they slammed against their hinges every night for eleven months of winter and summer alike.\u201d I had never seen calm water here\u2014only gray churning seas that swallowed ships smaller than themselves<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 101, + "repeats": 0, + "drafts_accepted": 32, + "drafts_offered": 53, + "tok_s": 50.0, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nCheetah \nHippopotamus \nRhinoceros \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nOtter \nBeaver \nBadger \nMongoose \nMeerkat \nHyena \nJackal \nAntelope \nBison \nElk \nCaribou \nLlama \nAlpace <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 12, + "tok_s": 64.6, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 52, + "drafts_offered": 148, + "tok_s": 49.8, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by hundreds millions years yet continues shaping every aspect from climate regulation through evolutionary biology down even into modern industrial logistics today's global supply chains depend upon them directly indirectly via atmospheric pressure systems weather patterns migration routes food webs carbon cycles oxygen generation thermal buffering tidal forces salinity gradients depth stratification light attenuation currents circulation gyres upwelling zones thermoclines halothermics bathymetric features continental shelves abyssal plains trenching ridges volcanic arcs island formations atoll structures seamounts submarine canons canyon walls cliff faces overhang ledge platforms reef flats fore-reef back-lagoon inner-shelf outer-slope drop-offs pinnacle pinnacles spires columns arches tunnels caves grottos swim-through passages chimney vents blowholes fissures cracks crevices joints faults fractures breaks gaps holes openings void spaces hollow chambers cavernous interiors subterranean networks underground rivers lakes pools springs wells shaft pits sinks drains sewers pipes conduits tubes channels gutters ditches furrows grooves rills runnels streams brooks rivulets creeks tributaries branches forks splits divergences con" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-x2-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-x2-coder-iq1_m.json new file mode 100644 index 0000000..2f058f4 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-x2-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 97, + "drafts_offered": 176, + "tok_s": 73.0, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was the last of the line, the only man left on the jagged spine of Widow\u2019s Rock. For forty years, he had tended the light. For forty years, he had listened to the ocean\u2019s endless, hungry whisper.\n\nTonight was different. The storm wasn\u2019t just a storm; it was a *tempest*. The waves didn\u2019t crash; they *shattered*. They threw themselves against the granite base of the lighthouse with the force of a battering ram, sending tremors up through the soles of Elias\u2019s boots.\n\nHe climbed the spiral stairs, one hundred and twelve steps of iron and rust. His hand, calloused and scarred from decades of polishing the brass railing, found the familiar groove in the metal. He didn\u2019t look up. He didn\u2019t look down. He looked *forward*." + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 176, + "tok_s": 102.5, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 90.9, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 91.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 118, + "repeats": 0, + "drafts_accepted": 38, + "drafts_offered": 103, + "tok_s": 62.8, + "text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 58, + "repeats": 0, + "drafts_accepted": 9, + "drafts_offered": 63, + "tok_s": 50.4, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty jail cell below sea level three hundred feet down to where Elias kept his boots dry and ready for emergencies when he had no time even think about changing them.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 140, + "repeats": 0, + "drafts_accepted": 22, + "drafts_offered": 90, + "tok_s": 50.1, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, demanding entry into every crack and crevice of Stone Harbor Lighthous eKeepers have always been solitary figures against isolation\u2019s greatest adversary: time itself Elias Thorne knew this intimately. For thirty years he had kept watch over one hundred thousand ships each night scanning for lights that might signal disaster or hope\n\nHis job was simple but deadly serious He checked weather logs every day without fail The foghorn echoed through the tower three times before dawn Each morning at 4:02 AM Elias would climb eighty-two steps to reach his office where coffee cooled beside a single candle flickering in drafts from below<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 96, + "repeats": 0, + "drafts_accepted": 31, + "drafts_offered": 69, + "tok_s": 58.9, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippo \nRhino \nCheetah \nLeopard \nJaguar \nPanther \nCougar \nBear \nWolf \nFox \nDeer \nElk \nMoose \nBison \nBuffalo \nAntelope \nCamel \nDonkey \nGoat \nSheep \nCow \nPig \nHorse <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 71.2, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 119, + "tok_s": 61.3, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth\u2019s surface.\u201d \u2014 *This quote by Rachel Carson serves as an apt introduction.* The story we tell today begins with that first drop falling into primordial pools billions years ago\u2014but what follows next? What happens when those drops become oceans themselves\u2014when they begin moving across continents carrying sediment from mountains down rivers until finally reaching their final resting place at last\u2014the deep abyssal plains where sunlight cannot reach nor pressure crushes everything else alive there below depths greater than six kilometers beneath waves crashing against shores above them all around world forever changing shape over time due plate tectonics shifting landmass slowly apart together again repeatedly throughout geological epochs spanning hundreds millions or even thousands million+ yrs since formation early Hadean era through Archeozoic eons onward present Holocene epoch still ongoing now right here under current conditions observed via satellites monitoring global climate patterns affecting currents temperatures salinity levels biodiversity distribution human impacts altering ecosystems directly indirectly causing extinction events locally globally recently historically prehistorically anciently mythologically culturally spiritually philosoph scientifically mathematically physically chem biol geo astro cosmological sociopolitical economic environmental ecological evolutionary genetic linguistic literary artistic musical cinematic theatrical photographic journalistic digital analog virtual real tangible intangible metaphysical ontosemantic semiotic symbolic allegorical narrative descriptive analytical interpretive evaluative critical reflective introspective contemplatory ponderous thoughtful considerate attentive observant perceptive insightful intelligent knowledgeable informed educated literati learned skilled capable" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-nocv-x2-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-nocv-x2-coder-iq1_m.json new file mode 100644 index 0000000..0e44612 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-nocv-x2-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 87, + "drafts_offered": 170, + "tok_s": 71.4, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and green.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from rope burns and broken glass, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, listening for the faint, rhythmic *tick-tick-tick* that signaled the rotation was true. If the rhythm faltered, ships" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 178, + "tok_s": 104.1, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 90.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 94.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 76, + "repeats": 0, + "drafts_accepted": 20, + "drafts_offered": 64, + "tok_s": 61.6, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBuffalo \nButterfly \nCamel \nCat \nCaterpillar \n\nCentipede \n\nChameleon \n\nCheetah \n\nChicken \n\nCricket \n\nCrocodile \n\n\nDolphin \n\n\n\nDonkey \n\n\n\n\nDragon<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 21, + "drafts_offered": 90, + "tok_s": 59.2, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty jail cell below sea level to above cloud height at once\u2014no matter how high you climbed or deep into its foundations down through rock and saltwater. It was November again when Elias first noticed that his logbook had begun recording entries he hadn\u2019t written yet: *Storm surge expected Tuesday, but the sky is clear.*\n\nHe stopped writing for a moment to listen\u2014not with ears alone\u2014but by pressing both palms flat against cold iron walls where condensation formed in slow spirals like fingerprints left behind after touching something invisible. The metal hummed faintly beneath his skin as if remembering old storms long past their dates on paper calendars torn from newspapers dated three years ahead of today" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 63, + "tok_s": 52.6, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, trying to get inside where he had spent thirty years refusing entry except for family and friends like him who were old enough too know better than young men ever could be again about what safety meant. It was November 2014 when Elias Thorne first stepped onto that spiral staircase with only one boot on because his other foot hurt after walking from the harbor office all morning long before anyone else thought he needed shoes off there for work even if nobody saw them do it but everyone knew why so they did not ask him anymore once this happened already twice last winter near same season now here again today too soon then tomorrow maybe never will come back unless someone sends message tonight via radio signal code Morse dot dash pattern" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 94, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 60, + "tok_s": 58.8, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nKangaroo \nPanda \nKoala \nCheetah \nWolf \nFox \nBear \nMonkey \nDolphin \nWhale \nShark \nOctopus \nJellyfish \nCrab \nSpider \nRabbit \nCat \nDog \nHorse \nCow \nSheep \nGoat \nChicken \nRooster \nTurkey \nEagle \nFalcon <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 71.8, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 52, + "drafts_offered": 148, + "tok_s": 61.8, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\u201d \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \u201cthe Sea\u201d or \"Ocean\" (terms often used interchangeably but distinct geographically) was never just an element within our planet\u2019s geography\u2014it became its engine itself\u2014a living system whose evolution shaped everything else around us from climate patterns down through evolutionary biology right up into modern civilization's economic structures cultural identities political boundaries ecological systems scientific understanding technological capabilities philosophical frameworks psychological experiences artistic expressions literary metaphors cinematic narratives musical compositions architectural designs urban planning strategies agricultural practices industrial processes medical discoveries legal precedents educational curricula religious traditions spiritual beliefs mythological stories folkloric tales poetic verses dramatic scripts visual arts photographic images digital media social networks behavioral norms emotional responses cognitive models decision-making algorithms predictive analytics statistical probabilities probabilistic reasoning causal inference counterfactual thinking hypothetical scenarios normative ethics deontal logic modal semantics temporal dynamics spatial relations topographical features hydrological cycles meteor phenomena atmospheric chemistry geological formations tectonic shifts volcanic eruptions seismic events tsunamis hurricanes cyclones monsoons typhoons droughts floods storms winds currents waves swells breakers surf foam spray mist fog rain snow ice glaciers berg floes drift pack-ice brine salinity pH alkalines acidity hardness softness temperature pressure depth light darkness color hue saturation brightness contrast luminance chroma tone value shade tint reflection" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-reg-coder-iq1_m.json b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-reg-coder-iq1_m.json new file mode 100644 index 0000000..99bd379 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-reg-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 187, + "tok_s": 58.7, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 179, + "tok_s": 80.7, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 71.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 73.0, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 19, + "drafts_offered": 49, + "tok_s": 49.1, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 80, + "repeats": 0, + "drafts_accepted": 6, + "drafts_offered": 52, + "tok_s": 46.2, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 83, + "tok_s": 43.9, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 62, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 31, + "tok_s": 49.1, + "text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 62.7, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 47, + "drafts_offered": 153, + "tok_s": 52.2, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/pp-lim-cv-pp-x2.json b/bench/results/2026-09-29-layer-split-limits/data/pp-lim-cv-pp-x2.json new file mode 100644 index 0000000..9c6a2a0 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/pp-lim-cv-pp-x2.json @@ -0,0 +1,84 @@ +{ + "label": "lim-cv-pp-x2", + "extra": [ + "--layer-split", + "auto", + "--control-vector-scaled", + "C:\\Users\\ribbon\\strata-test\\Strata\\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" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 15925, + "prompt_ms": 8783.1, + "pp_tok_s": 1813.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27474, + "prompt_ms": 13379.7, + "pp_tok_s": 2053.4, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3652.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 246.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 77.0, + "reps": [ + 77.0 + ], + "hit_rate": 0.9718150054476462, + "text": "The wind didn\u2019t just howl; it screamed. It tore through the gaps in the iron railing of the Lantern Room, carrying the scent of brine and rotting kelp. Elias pulled his woolen collar up to his chin, his fingers numb and clumsy inside thick leather gloves.\n\nHe was the last man on the island. The automated systems had failed three winters ago, a glitch in the solar panel array that no engineer had been able to fix before the supply boat stopped running. Now, it was just him, the light, and the sea.\n\nElias climbed the spiral stairs, his boots heavy with salt spray. The iron steps groaned under his weight, a sound that seemed to mock the storm outside. He reached the top, the glass walls vibrating with the force of the gale.\n\nInside the lantern room, the great Fresnel lens sat like a dormant eye. It was cold, dark, and waiting.\n\nElias moved to the control panel. His" + }, + { + "name": "code", + "tok_s": 103.6, + "reps": [ + 103.6 + ], + "hit_rate": 0.957731667226356, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False" + } + ], + "stage_timing": [], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.30 GiB for experts", + "strata generate: layer split auto: CUDA1 82 SMs at 1.86 GHz -> 0.48 ms per layer, 14.14 GiB for experts", + "strata generate: layer split auto: K=22 - predicted 19.7 ms per decode window; the caches hold 11298 of 12288 profiled pairs (~99.7% of the routed mass)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 3479 slots, 6.22 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 91.6% (5554 hits / 6062 lookups)", + "strata serve: decode expert cache hit rate: 95.3% (3592 hits / 3771 lookups)", + "strata serve: decode expert cache hit rate: 96.5% (3650 hits / 3782 lookups)", + "strata serve: decode expert cache hit rate: 96.3% (25027 hits / 25980 lookups)", + "strata serve: decode expert cache hit rate: 96.5% (3201 hits / 3318 lookups)", + "strata serve: decode expert cache hit rate: 97.2% (129334 hits / 133085 lookups)", + "strata serve: decode expert cache hit rate: 95.8% (108375 hits / 113158 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-single.json b/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-single.json new file mode 100644 index 0000000..5316f9a --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-single.json @@ -0,0 +1,76 @@ +{ + "label": "lim-kv-pp-single", + "extra": [ + "--max-context", + "131072", + "--kv-resident", + "32768" + ], + "gpus": "0", + "needles": [ + { + "tokens": 15925, + "prompt_ms": 10706.3, + "pp_tok_s": 1487.4, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27474, + "prompt_ms": 15256.7, + "pp_tok_s": 1800.8, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 59725, + "prompt_ms": 32515.5, + "pp_tok_s": 1836.8, + "found": true, + "answer": "falcon-174<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4006.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 276.2, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 66.6, + "reps": [ + 66.6 + ], + "hit_rate": 0.7101864314556545, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to sync with his own heartbeat. He had been doing this for forty years. His hands were mapped with scars from rope burns and broken glass, his eyes permanently squinted against the glare of the bulb." + }, + { + "name": "code", + "tok_s": 74.0, + "reps": [ + 74.0 + ], + "hit_rate": 0.5873783774988882, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [], + "engine_lines": [ + "strata generate: expert cache auto: 8.99 GiB free, 700 MiB reserved -> 3349 slots", + "strata generate: expert cache 2434 slots, 4.67 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 1944 cache slots (3.72 GiB)", + "strata serve: decode expert cache hit rate: 41.8% (1746 hits / 4176 lookups)", + "strata serve: decode expert cache hit rate: 50.4% (1512 hits / 3000 lookups)", + "strata serve: decode expert cache hit rate: 54.9% (1689 hits / 3077 lookups)", + "strata serve: decode expert cache hit rate: 60.3% (1938 hits / 3213 lookups)", + "strata serve: decode expert cache hit rate: 58.3% (11146 hits / 19121 lookups)", + "strata serve: decode expert cache hit rate: 66.1% (2201 hits / 3331 lookups)", + "strata serve: decode expert cache hit rate: 71.0% (74397 hits / 104757 lookups)", + "strata serve: decode expert cache hit rate: 58.7% (54151 hits / 92191 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-x2.json b/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-x2.json new file mode 100644 index 0000000..275e63f --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-x2.json @@ -0,0 +1,87 @@ +{ + "label": "lim-kv-pp-x2", + "extra": [ + "--max-context", + "131072", + "--kv-resident", + "32768", + "--layer-split", + "auto" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 15925, + "prompt_ms": 9452.6, + "pp_tok_s": 1684.7, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27474, + "prompt_ms": 14042.4, + "pp_tok_s": 1956.5, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 59725, + "prompt_ms": 30345.9, + "pp_tok_s": 1968.1, + "found": true, + "answer": "falcon-174<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3806.1, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 245.6, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 75.8, + "reps": [ + 75.8 + ], + "hit_rate": 0.9698055042592483, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined Elias\u2019s life for thirty years. He stood before the great Fresnel lens, a cathedral of glass and brass that caught the light of the single, powerful bulb and fractured it into a thousand beams.\n\nHe checked the clock. 11:42 PM. The rotation was smooth, silent, a hypnotic sweep that painted the darkness with a slow, rhythmic pulse. *Flash. Dark. Flash. Dark.*\n\nE" + }, + { + "name": "code", + "tok_s": 97.0, + "reps": [ + 97.0 + ], + "hit_rate": 0.9562207324057541, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 17.96 GiB free", + "strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.13 GiB for experts", + "strata generate: layer split auto: CUDA1 82 SMs at 1.86 GHz -> 0.48 ms per layer, 13.98 GiB for experts", + "strata generate: layer split auto: K=22 - predicted 19.7 ms per decode window; the caches hold 11199 of 12288 profiled pairs (~99.7% of the routed mass)", + "strata generate: expert cache auto: 10.30 GiB free, 700 MiB reserved -> 3277 slots", + "strata generate: expert cache 3409 slots, 6.09 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 91.3% (5098 hits / 5585 lookups)", + "strata serve: decode expert cache hit rate: 94.7% (4000 hits / 4225 lookups)", + "strata serve: decode expert cache hit rate: 96.5% (4095 hits / 4245 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (4183 hits / 4278 lookups)", + "strata serve: decode expert cache hit rate: 96.2% (27177 hits / 28250 lookups)", + "strata serve: decode expert cache hit rate: 97.6% (4177 hits / 4281 lookups)", + "strata serve: decode expert cache hit rate: 97.0% (130241 hits / 134296 lookups)", + "strata serve: decode expert cache hit rate: 95.6% (113534 hits / 118732 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split-limits/data/vision.json b/bench/results/2026-09-29-layer-split-limits/data/vision.json new file mode 100644 index 0000000..ed935b5 --- /dev/null +++ b/bench/results/2026-09-29-layer-split-limits/data/vision.json @@ -0,0 +1,24 @@ +{ + "answers": { + "single": [ + " Red", + "42", + "A red circle, the number 42, and a blue square are arranged on a white background." + ], + "same24": [ + " Red", + "42", + "A red circle, the number 42, and a blue square are arranged on a white background." + ], + "x2": [ + " Red", + "42", + "A red circle, the number 42, and a blue square are displayed on a white background." + ] + }, + "correct": { + "single": true, + "same24": true, + "x2": true + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/README.md b/bench/results/2026-09-29-layer-split/README.md new file mode 100644 index 0000000..363b1a1 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/README.md @@ -0,0 +1,84 @@ +# Layer split across GPUs (2026-09-29) + +**Rig (a community member's PC, "RIBPC"):** +- Ryzen 9 9950X3D, 62 GB DDR5, Windows 11, CUDA 13.1. +- RTX 5080 16 GB (x16), RTX 3090 24 GB (x4 gen4, ~6 GB/s), RTX 2080 Ti 22 GB (x4 gen3, Turing sm_75; the + experimental `STRATA_EXPERIMENTAL_SM75` build). + +**Model:** the Coder (GSQ-RCO IQ1_M, 48 layers x 256 experts = 12,288 expert pairs, ~23 GB of experts), 32K +context, int8 KV, `--prefill auto`, `--spec 4`. It is the only model that fits the rig's RAM and disk. + +**Tools:** `rib_pp.py` (needle prompts at 2.7K/8K/16K/28K tokens with a code word at 50% depth, a 2-turn chat that +must reuse its checkpoint, greedy decode of a story and a code prompt) and `rib_norepeat.py` (the Phase A +no-repeat and sanity cases). Raw results are in `data/`. + +## Correctness + +| Check | Result | +|---|---| +| This branch vs the 0.1.20 release, one GPU (5080), fixed cache, all 10 cases | **10/10 byte-identical** | +| This branch, one GPU vs the split on the same GPU (K=24, `--split-device 0`) | **10/10 byte-identical**: the hand-off is exact | +| 5080 + 3090 (auto) and 5080 + 2080 Ti + 3090 (auto): no-repeat under presence 100 (greedy and sampled), 144 sanity | all pass, 0 repeats | +| Needles at 2.7K-28K tokens, every configuration | all found | +| 2-turn chat (the checkpoint restored on every GPU) | reused 6,631-6,632 of 6,660 tokens, answer right | + +Across GPUs the text is not byte-identical to one GPU: experts the CPU computed on one card run on a GPU in the split, +and they round differently (the same effect as `--expert-cache`, bench/results/2026-09-27-cache-parity). + +## Speed + +**Prompt tok/s** at 16K / 28K tokens, and **decode tok/s** for story / code (greedy; three repeats averaged +in the K sweep): + +| Configuration | Split | Prompt 16K | Prompt 28K | Decode story | Decode code | Decode hits | +|---|---|---|---|---|---|---| +| 0.1.20, 5080 alone | - | 2,045 | 2,005 | 83.2 | 88.2 | 70-84% | +| this branch, 5080 alone | - | 2,017 | 1,974 | 83.1 | 88.0 | 70-84% | +| this branch, 5080 alone, 3 repeats (adaptive swaps learn the prompt) | - | 1,726 | 1,970 | 86.7 | 105.2 | 91-92% | +| 3090 alone | - | 1,253 | 1,211 | 71.7 | 92.9 | 86-93% | +| 5080 + 3090 | K=18 | 1,547 | 1,694 | 77.2 | 103.8 | 99.9% | +| 5080 + 3090 | K=22 | 1,840 | 2,074 | 80.2 | 106.4 | 99.8% | +| 5080 + 3090 | K=24 | 1,978 | 2,258 | 83.5 | 109.5 | 99.5% | +| **5080 + 3090** | **K=26** | **2,039** | **2,357** | **83.8** | **109.7** | 99.3% | +| 5080 + 3090 | K=28 | 2,011 | 2,287 | 83.5 | 112.5 | 99.0% | +| 5080 + 3090 | K=30 | 1,935 | 2,218 | 81.1 | 109.6 | 98% | +| 5080 + 3090 | K=32 | 1,818 | 2,063 | 83.0 | 108.7 | 98% | +| 5080 + 3090 | auto (K=22) | 2,037 | 2,073 | 79.5 | 108.9 | 99.7% | +| 3090 + 5080 | auto (K=30) | 1,672 | 1,876 | 90.3 | 105.1 | 99.4% | +| 5080 + 2080 Ti + 3090 | auto (22, 23) | 1,687 | 1,847 | 67.6 | 89.6 | 99.7% | +| 5080 + 3090 + 2080 Ti | first auto (12, 33) | 1,148 | 1,144 | 51.9 | 69.7 | 100% | +| 5080 + 2080 Ti | first auto | 914 | 906 | 45.5 | 58.0 | 97% | + +What decides it: + +- **The best two-GPU split for the Coder is K=26-28.** Prompts run +18-20% over the 5080 alone at 16-28K; + decode is on par for story and +4-7% for code. +- **Residency saturates quickly: the per-layer GPU speed decides.** From K=18 up, both caches hold 98-100% of + the routed experts. Moving layers to the faster card is what helps: the 3090 costs 0.50 ms per layer per + window, the 5080 0.33 (`STRATA_SPLIT_TIMING`, the "wait for the GPU" per stage). +- **Decode is bounded by that GPU time.** One 5080 with its cache adapted spends 16.3 ms waiting for its GPU and + 5.5 ms in the CPU pool per window. The split removes the pool (0.8-1.0 ms) but adds the slower card's layers: + 7.9 + 12.1 ms at K=24. The per-layer GPU half (kernels plus the host round trip that publishes each layer's + expert plan) is the next thing to cut, for one GPU as well (perf-review-plan E-6). +- **A third, slower card costs more than it holds.** The 2080 Ti's one-layer stage took 3.1 ms per window. + For a model that already fits two cards, leave it out. It pays only when the two faster cards cannot hold most + of the routed experts (a bigger model; not testable on this rig's 62 GB of RAM). +- **Prompt chunk:** 1024 instead of 2048 frees ~0.7 GB per card, but prompts read 7-12% slower. + +## Auto placement + +`--layer-split auto` predicts one decode window's time for every placement (every placement up to three GPUs) and +keeps the fastest: + +- **per-layer time** from SMs x clock (0.33 ms for an RTX 5080); +- **cache contents:** each card's layers' profiled pairs, hottest first, as the fill does; +- **routed mass** of rank r taken as (r+1)^-1.2 (fits the sweep's hit rates within 0.1-1%); +- **missed mass** costing 190 ms per unit (fitted to the sweep's best K; `STRATA_SPLIT_MISS_MS` overrides). + +It picked K=22 on the 5080 + 3090: within 0-12% of the best fixed split on prompts and on par on decode. It gives +a slow third card a single layer. + +## Reproduce + +On a rig: the `strata-remote` tools, then `rib_matrix.bat`, `rib_ksweep.bat`, `rib_validate.bat` (in the dev +notes, not in this repository). diff --git a/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x2-auto-coder-iq1_m.json b/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x2-auto-coder-iq1_m.json new file mode 100644 index 0000000..a5169b0 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x2-auto-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 193, + "tok_s": 74.6, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, gripped the iron railing as he ascended the final flight of steps to the lantern room.\n\nBelow him, the Atlantic churned in a frenzy, whitecaps exploding against the black rocks like fireworks. Above, the sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen.\n\nElias checked the clock. 11:42 PM. The light was due.\n\nHe didn\u2019t flip a switch. He didn\u2019t press a button. He reached for the heavy brass lever that had worn smooth by his palm over the years. With a grunt that matched the strain of his aging muscles, he pulled it down.\n\n*Clunk.*\n\nThe" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 181, + "tok_s": 105.5, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 85.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 94.3, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 118, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 105, + "tok_s": 67.9, + "text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 147, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 103, + "tok_s": 63.2, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to that date and time for context because you asked me about a lighthouse keeper but gave no specifics beyond \u201cshort story,\u201d so let\u2019s set it: isolated coastal station off the Oregon coast during winter storm season, 1987.\n\nMy name is Elias Vane (I made this fictional; real keepers often kept journals signed with initials only), and I\u2019m writing from memory because my logbook got waterlogged when a rogue wave breached lower storage room at dawn\u2014so here\u2019s what happened:<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 109, + "repeats": 0, + "drafts_accepted": 13, + "drafts_offered": 56, + "tok_s": 54.1, + "text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they settled into silence with every storm break out of three hundred days here being storms that broke something else again but mostly kept me warm because I burned coal and wood whenever we had any left over from last winter when even then if you\u2019re lucky enough to get through it all without freezing yourself so hard your own thoughts become ice too\n\nBut Elias knew better than anyone: fear was useful only until dawn<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 92, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 48, + "tok_s": 64.7, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nHippopotamus \nRhinoceros \nCamel \nCheetah \nLeopard \nPanther \nJaguar \nBison \nElk \nDeer \nFox \nWolf \nBear \nLlama \nDonkey \nGoat \nSheep \nCow \nPig \nRabbit \nCat \nDog<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 14, + "tok_s": 71.7, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 53, + "drafts_offered": 134, + "tok_s": 66.1, + "text": "The ocean is not merely water; it has been, and continues to be one with humanity\u2019s most profound narrative arc in human civilization: **the story we tell ourselves through our relationship** between landmasses separated by vast expansiveness that defines both isolation from other worlds (and thus their own unique evolutionary paths) as well than connection across them via currents wind patterns tides depth pressure temperature salinity biodiversity geology climate change economic trade routes ecological systems cultural exchange political boundaries scientific discovery technological advancement environmental degradation conservation efforts maritime archaeography historical cartographic evolution legal frameworks international law enforcement mechanisms insurance liability regimes regulatory compliance standards safety protocols navigation aids communication networks emergency response strategies search-and-rescue operations salvage rights ownership disputes heritage protection zones sustainable harvesting practices aquaculture development infrastructure engineering projects coastal management policies urban planning regulations zoning ordinances building codes architectural design guidelines aesthetic considerations functional requirements accessibility provisions energy efficiency measures thermal insulation techniques moisture control methods ventilation optimization lighting solutions acoustic soundproofing structural integrity assessments seismic resistance evaluations flood mitigation plans storm surge barriers levee construction seawall reinforcement breakwater installation harbor dredging channel maintenance buoy placement lighthouse automation radar monitoring sonar mapping bathymetric surveys hydrographic charts nautical almanacs tide tables current predictions weather forecasts marine meteorological models satellite imagery remote sensing data assimilation numerical simulations computational fluid dynamics finite element analysis partial differential equations tensor calculus linear algebra probability theory statistics stochastic processes Markov chains Bayesian inference machine learning artificial neural network deep convolutional recurrent transformer attention heads generative adversarial diffusion transformers large language model tokenization" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x3-auto-coder-iq1_m.json b/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x3-auto-coder-iq1_m.json new file mode 100644 index 0000000..54c8c52 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x3-auto-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 193, + "tok_s": 68.2, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, gripped the iron railing as he ascended the final flight of steps to the lantern room.\n\nBelow him, the Atlantic churned in a frenzy, whitecaps exploding against the black rocks like fireworks. Above, the sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen.\n\nElias checked the clock. 11:42 PM. The light was due.\n\nHe didn\u2019t flip a switch. He didn\u2019t press a button. He reached for the heavy brass lever that had worn smooth by his palm over the years. With a grunt that matched the strain of his aging muscles, he pulled it down.\n\n*Clunk.*\n\nThe" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 181, + "tok_s": 99.4, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.5, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 76.3, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 118, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 105, + "tok_s": 65.2, + "text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 147, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 103, + "tok_s": 45.7, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to that date and time for context because you asked me about a lighthouse keeper but gave no specifics beyond \u201cshort story,\u201d so let\u2019s set it: isolated coastal station off the Oregon coast during winter storm season, 1987.\n\nMy name is Elias Vane (I made this fictional; real keepers often kept journals signed with initials only), and I\u2019m writing from memory because my logbook got waterlogged when a rogue wave breached lower storage room at dawn\u2014so here\u2019s what happened:<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 109, + "repeats": 0, + "drafts_accepted": 13, + "drafts_offered": 56, + "tok_s": 42.1, + "text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they settled into silence with every storm break out of three hundred days here being storms that broke something else again but mostly kept me warm because I burned coal and wood whenever we had any left over from last winter when even then if you\u2019re lucky enough to get through it all without freezing yourself so hard your own thoughts become ice too\n\nBut Elias knew better than anyone: fear was useful only until dawn<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 92, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 48, + "tok_s": 43.9, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nHippopotamus \nRhinoceros \nCamel \nCheetah \nLeopard \nPanther \nJaguar \nBison \nElk \nDeer \nFox \nWolf \nBear \nLlama \nDonkey \nGoat \nSheep \nCow \nPig \nRabbit \nCat \nDog<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 14, + "tok_s": 61.4, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 53, + "drafts_offered": 134, + "tok_s": 51.9, + "text": "The ocean is not merely water; it has been, and continues to be one with humanity\u2019s most profound narrative arc in human civilization: **the story we tell ourselves through our relationship** between landmasses separated by vast expansiveness that defines both isolation from other worlds (and thus their own unique evolutionary paths) as well than connection across them via currents wind patterns tides depth pressure temperature salinity biodiversity geology climate change economic trade routes ecological systems cultural exchange political boundaries scientific discovery technological advancement environmental degradation conservation efforts maritime archaeography historical cartographic evolution legal frameworks international law enforcement mechanisms insurance liability regimes regulatory compliance standards safety protocols navigation aids communication networks emergency response strategies search-and-rescue operations salvage rights ownership disputes heritage protection zones sustainable harvesting practices aquaculture development infrastructure engineering projects coastal management policies urban planning regulations zoning ordinances building codes architectural design guidelines aesthetic considerations functional requirements accessibility provisions energy efficiency measures thermal insulation techniques moisture control methods ventilation optimization lighting solutions acoustic soundproofing structural integrity assessments seismic resistance evaluations flood mitigation plans storm surge barriers levee construction seawall reinforcement breakwater installation harbor dredging channel maintenance buoy placement lighthouse automation radar monitoring sonar mapping bathymetric surveys hydrographic charts nautical almanacs tide tables current predictions weather forecasts marine meteorological models satellite imagery remote sensing data assimilation numerical simulations computational fluid dynamics finite element analysis partial differential equations tensor calculus linear algebra probability theory statistics stochastic processes Markov chains Bayesian inference machine learning artificial neural network deep convolutional recurrent transformer attention heads generative adversarial diffusion transformers large language model tokenization" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/norepeat-nr-x2-auto-coder-iq1_m.json b/bench/results/2026-09-29-layer-split/data/norepeat-nr-x2-auto-coder-iq1_m.json new file mode 100644 index 0000000..537523b --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/norepeat-nr-x2-auto-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 91, + "drafts_offered": 190, + "tok_s": 74.0, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, knew every bolt, every lever, and every creak in the iron bones of the tower.\n\nFor forty years, Elias had been the guardian of the Point. Not just of the light, but of the silence between the waves.\n\nIt was November. The sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that shook the floorboards beneath Elias\u2019s boots.\n\nHe climbed the stairs. One hundred and twelve steps. He counted them by feel, his left hand trailing along the cold iron railing. At the top, the air was" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 137, + "drafts_offered": 178, + "tok_s": 103.4, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 91.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 70.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 118, + "repeats": 0, + "drafts_accepted": 38, + "drafts_offered": 108, + "tok_s": 65.4, + "text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 57, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 61, + "tok_s": 57.1, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach top room where his world began again.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 58, + "repeats": 0, + "drafts_accepted": 14, + "drafts_offered": 54, + "tok_s": 52.9, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in stone and steel, carrying with them spray from three miles out into churning black water that no longer resembled an ocean so much as abyssal chaos waiting for its prey to surface beneath waves of salt.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 59, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 47, + "tok_s": 51.7, + "text": "Lion \nTiger \n\nElephant\\nGiraffe\\Zebra\\rHippopotamus\\tRhinoceros\\vCrocodile\\fAlligator\\bSnake\\aSpider\\u2615CoffeeCup\u2615\ufe0fTeaTime\ud83d\udc09DragonFishWhaleDolph<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 12, + "tok_s": 73.5, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 43, + "drafts_offered": 126, + "tok_s": 63.4, + "text": "The ocean is not merely water; it has been, and continues to be one with humanity\u2019s most profound narrative arc in human civilization: **the story told by waves**. It serves as both witness (through sedimentary layers)and participant( through currents that carry messages across continents). Its \"history\" spans geological epochs where life first emerged from primordial pools into complex ecosystems today\u2014and cultural histories shaped entirely around its roleas connector between distant lands or barrier separating them forever depending on perspective taken at different times throughout millennia since ancient civilizations began building boats outof logs carved using stone tools until modern container ships carrying billions tons cargo daily cross Atlantic routes once navigated onlyby stars alone under moonlight during nights when sailors feared monsters lurking beneath hulls made fragile against storms they could barely predict even now despite advanced meteorology systems developed over past century after industrial revolution transformed maritime trade patterns globally due economic pressures driving demand for faster logistics chains linking factories producing electronics manufactured inside cities located far inland near rivers feeding estuaries opening directly onto open seas connected via canals engineered centuries ago like Suez Canal built originallyfor military purposes later adapted commercial use post-World War II era reshaping global supply networks dramatically because geopolitical shifts altered which ports remained accessible politically versus physically blocked temporarily then reopened permanently following treaty agreements signed among nations agreeing upon shared responsibilities regarding environmental stewardship including coral reef restoration efforts funded jointly international organizations coordinating scientific research conducted aboard vessels specifically designed deep-sea exploration equipped robotic submersibles capable descending trenches deeper than any previous technology allowed" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/norepeat-nr-x3-auto-coder-iq1_m.json b/bench/results/2026-09-29-layer-split/data/norepeat-nr-x3-auto-coder-iq1_m.json new file mode 100644 index 0000000..d72d1b2 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/norepeat-nr-x3-auto-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 98, + "drafts_offered": 166, + "tok_s": 54.4, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that made the floorboards tremble. Elias stood by the lantern room, his hands wrapped around a mug of coffee that had gone cold hours ago. He wasn\u2019t drinking it. He was holding it for warmth." + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 137, + "drafts_offered": 163, + "tok_s": 70.7, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_basic():\n \"\"\"Test basic CSV parsing with simple data.\"\"\"\n import tempfile\n import os\n \n # Create a temporary CSV" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 56.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 57.6, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 59, + "repeats": 0, + "drafts_accepted": 13, + "drafts_offered": 47, + "tok_s": 39.7, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBuffalo \n\nCat \nCheetah \n\nChimpanzee \nClam \n\n\nCrocodile \n\n\n\nDolphin \n\n\n\n\nDonkey <|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 57, + "repeats": 0, + "drafts_accepted": 12, + "drafts_offered": 58, + "tok_s": 39.9, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach topmost gallery where his world began.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 30, + "drafts_offered": 111, + "tok_s": 34.7, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his stone cottage like an angry ghost trying to get inside, yet finding no door left unlocked because Elias never let one stay that way for more than three seconds after entering or leaving during storm season. He had been doing this since 1987\u2014since before he even knew why\u2014and now it was muscle memory so deep into his bones and fingers\u2019 calloused skin texture patterns worn thin by years of gripping the same iron railing at midnight watch that if you asked him what time exactly, down to quarter-hour increments when fog rolled in thick enough where light beams bent around itself like old rope coiling tight on a winch drum spooling out slowly from below deck floor level storage locker number seven under stairs leading" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 96, + "repeats": 0, + "drafts_accepted": 31, + "drafts_offered": 48, + "tok_s": 42.3, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nCheetah \nHippopotamus \nRhinoceros \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nOtter \nBeaver \nBadger \nMongoose \nMeerkat \nChimpanzee \nGorilla \nOrangetutan \nAntelope \nBison \nElk <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 43.0, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 127, + "tok_s": 37.6, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\u201d \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \u201cthe Sea\u201d or \"Ocean\" (terms often used interchangeably but distinct geographically) was never just an element within our planet\u2019s geography\u2014it became its engine itself\u2014a living system whose existence predates humanity by billions years yet continues shaping us today through climate regulation oxygen production food supply trade routes cultural identity ecological resilience economic development political boundaries scientific discovery technological innovation environmental crisis conservation efforts historical memory philosophical reflection poetic metaphor musical composition cinematic storytelling literary narrative visual art architectural inspiration culinary tradition spiritual symbolism psychological influence sociological transformation educational foundation medical necessity agricultural dependency industrial revolution urban planning infrastructural engineering legal framework regulatory policy international cooperation global governance planetary stewardship existential risk mitigation sustainable practice ethical consideration moral imperative social justice democratic participation civic engagement public health community welfare individual responsibility personal accountability collective action shared experience common understanding mutual respect reciprocal trust collaborative effort cooperative endeavor joint venture unified mission integrated strategy coordinated plan synchronized schedule aligned timeline concurrent execution simultaneous operation parallel processing sequential progression iterative refinement recursive improvement continuous adaptation dynamic adjustment flexible response adaptive behavior responsive conduct proactive initiative anticipatory foresight predictive modeling probabilistic assessment statistical analysis empirical observation experimental verification theoretical hypothesis conceptual abstraction logical deduction rational inference critical evaluation analytical reasoning systematic investigation methodical inquiry structured exploration comprehensive examination detailed scrutiny meticulous inspection thorough review exhaustive audit complete survey full census total enumeration absolute" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/norepeat-reg-dev-coder-iq1_m.json b/bench/results/2026-09-29-layer-split/data/norepeat-reg-dev-coder-iq1_m.json new file mode 100644 index 0000000..99cf299 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/norepeat-reg-dev-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 187, + "tok_s": 59.2, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 179, + "tok_s": 81.6, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.9, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.3, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 19, + "drafts_offered": 49, + "tok_s": 49.6, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 80, + "repeats": 0, + "drafts_accepted": 6, + "drafts_offered": 52, + "tok_s": 44.9, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 83, + "tok_s": 44.1, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 62, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 31, + "tok_s": 49.5, + "text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 65.2, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 47, + "drafts_offered": 153, + "tok_s": 52.5, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/norepeat-reg-rel-coder-iq1_m.json b/bench/results/2026-09-29-layer-split/data/norepeat-reg-rel-coder-iq1_m.json new file mode 100644 index 0000000..85cdf6e --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/norepeat-reg-rel-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 187, + "tok_s": 58.4, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 179, + "tok_s": 80.6, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 75.2, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.2, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 19, + "drafts_offered": 49, + "tok_s": 48.5, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 80, + "repeats": 0, + "drafts_accepted": 6, + "drafts_offered": 52, + "tok_s": 46.4, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 83, + "tok_s": 43.3, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 62, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 31, + "tok_s": 49.8, + "text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 62.5, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 47, + "drafts_offered": 153, + "tok_s": 52.6, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/norepeat-reg-same24-coder-iq1_m.json b/bench/results/2026-09-29-layer-split/data/norepeat-reg-same24-coder-iq1_m.json new file mode 100644 index 0000000..e0473e7 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/norepeat-reg-same24-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 187, + "tok_s": 58.4, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 179, + "tok_s": 80.5, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.5, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 76.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 19, + "drafts_offered": 49, + "tok_s": 49.6, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 80, + "repeats": 0, + "drafts_accepted": 6, + "drafts_offered": 52, + "tok_s": 46.7, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 83, + "tok_s": 44.3, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 62, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 31, + "tok_s": 50.0, + "text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 62.0, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 47, + "drafts_offered": 153, + "tok_s": 52.1, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-dev-3090.json b/bench/results/2026-09-29-layer-split/data/pp-dev-3090.json new file mode 100644 index 0000000..acfe0b3 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-dev-3090.json @@ -0,0 +1,72 @@ +{ + "label": "dev-3090", + "extra": [], + "gpus": "2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 3424.8, + "pp_tok_s": 796.0, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 8617.9, + "pp_tok_s": 972.3, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 12820.1, + "pp_tok_s": 1253.2, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 22901.1, + "pp_tok_s": 1211.4, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 5657.8, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 238.7, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 71.7, + "hit_rate": 0.9266798230257504, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning black void, punctuated by whitecaps that looked like teeth.\n\nHe climbed the spiral stairs, his knees protesting with every step. The iron rungs were cold, slick with condensation that had leaked through the hairline cracks in the masonry. At the top, the lantern room hummed with the low, steady thrum of the rotating lens. It was a sound Elias had learned to sleep with, a heartbeat of the house.\n\nHe checked the clock. 11:42 PM. The light swept across the water, a slow, hypnotic arc. *Flash. Darkness. Flash. Darkness.*\n\nFor a moment, the beam caught something that wasn\u2019t water. A shape" + }, + { + "name": "code", + "tok_s": 92.9, + "hit_rate": 0.8636411400016346, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header row\n and values from the corresponding row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n```<|im_end|>" + } + ], + "engine_lines": [ + "strata generate: expert cache auto: 17.31 GiB free, 700 MiB reserved -> 6704 slots", + "strata generate: expert cache 8730 slots, 16.62 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2315 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 86.6% (4986 hits / 5756 lookups)", + "strata serve: decode expert cache hit rate: 87.1% (3757 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 88.7% (3827 hits / 4314 lookups)", + "strata serve: decode expert cache hit rate: 92.1% (3975 hits / 4318 lookups)", + "strata serve: decode expert cache hit rate: 95.5% (4124 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 94.3% (25793 hits / 27360 lookups)", + "strata serve: decode expert cache hit rate: 94.6% (4088 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 92.7% (116454 hits / 125668 lookups)", + "strata serve: decode expert cache hit rate: 86.4% (73970 hits / 85649 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-dev-5080.json b/bench/results/2026-09-29-layer-split/data/pp-dev-5080.json new file mode 100644 index 0000000..e7b3d31 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-dev-5080.json @@ -0,0 +1,72 @@ +{ + "label": "dev-5080", + "extra": [], + "gpus": "0", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2129.8, + "pp_tok_s": 1279.9, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5057.2, + "pp_tok_s": 1656.8, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 7964.7, + "pp_tok_s": 2017.2, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 14053.6, + "pp_tok_s": 1974.1, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3366.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 197.3, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.1, + "hit_rate": 0.8418683557684931, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. *Click. Click. Click.* The gears engaged, and the massive Fresnel lens began its slow" + }, + { + "name": "code", + "tok_s": 88.0, + "hit_rate": 0.7011385968111186, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)", + "strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)", + "strata serve: decode expert cache hit rate: 72.5% (2539 hits / 3504 lookups)", + "strata serve: decode expert cache hit rate: 77.3% (2817 hits / 3642 lookups)", + "strata serve: decode expert cache hit rate: 75.3% (16500 hits / 21916 lookups)", + "strata serve: decode expert cache hit rate: 80.0% (2978 hits / 3723 lookups)", + "strata serve: decode expert cache hit rate: 84.2% (98752 hits / 117301 lookups)", + "strata serve: decode expert cache hit rate: 70.1% (69215 hits / 98718 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k18.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k18.json new file mode 100644 index 0000000..16251eb --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k18.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k18", + "extra": [ + "--layer-split", + "18" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 10383.7, + "pp_tok_s": 1547.2, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 16371.9, + "pp_tok_s": 1694.5, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4308.0, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 239.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 77.2, + "reps": [ + 74.6, + 78.1, + 79.0 + ], + "hit_rate": 0.9985378787878788, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias climbed the spiral stairs, his hand gripping the cold iron railing. His knees ached, not from age, but from the constant vibration of the floor beneath his feet. He reached the lantern room, the heart of the lighthouse, and checked the clockwork mechanism. The great lens, a prism of Fresnel glass, rotated with a steady, hypnotic *whirrr-click, whirrr-click*. It was the only sound that mattered. The light swept out into the black void, cutting through" + }, + { + "name": "code", + "tok_s": 103.8, + "reps": [ + 97.6, + 106.4, + 107.3 + ], + "hit_rate": 0.9984863945578232, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 524 windows; per window: wait for the GPU 6.456 ms, pool + plan 0.181 ms, host staging 0.581 ms, commit 0.206 ms", + "strata serve: stage 1: 524 windows; per window: wait for the GPU 14.872 ms, pool + plan 0.501 ms, host staging 0.000 ms, commit 0.387 ms", + "strata serve: stage 0: 593 windows; per window: wait for the GPU 6.479 ms, pool + plan 0.185 ms, host staging 0.515 ms, commit 0.207 ms", + "strata serve: stage 1: 593 windows; per window: wait for the GPU 15.053 ms, pool + plan 0.496 ms, host staging 0.000 ms, commit 0.390 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 18)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4608 slots, 8.24 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 18-47, expert cache 7152 slots (14.14 GiB), 7152 of its 7680 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-17", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-17 (CUDA0), 18-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.7% (6159 hits / 6240 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (3796 hits / 3840 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (3811 hits / 3840 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (27723 hits / 27840 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (3807 hits / 3840 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (142002 hits / 143040 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (139882 hits / 140160 lookups)", + "strata serve: decode expert cache hit rate: 99.9% (131807 hits / 132000 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (119278 hits / 120480 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (117410 hits / 117600 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (117422 hits / 117600 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k19.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k19.json new file mode 100644 index 0000000..7628eac --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k19.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k19", + "extra": [ + "--layer-split", + "19" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9875.2, + "pp_tok_s": 1626.9, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 15498.0, + "pp_tok_s": 1790.1, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4085.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 238.7, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 79.3, + "reps": [ + 74.8, + 85.6, + 77.4 + ], + "hit_rate": 0.9977757017660928, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias stood at the top of the spiral staircase, his hand resting on the cold iron railing. He was not afraid. Fear was for the tourists who came in summer, wide-eyed and clutching their cameras. Elias was a keeper. He was a guardian.\n\nHe checked the logbook. The entry for the night was simple: *Wind, 60 knots. Visibility, zero. Light, operational.*\n\nHe walked down the stairs, his boots heavy on the metal grating. The smell of salt" + }, + { + "name": "code", + "tok_s": 107.4, + "reps": [ + 98.9, + 111.3, + 112.1 + ], + "hit_rate": 0.9986286196529353, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header row\n and values from the corresponding row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with" + } + ], + "stage_timing": [ + "strata serve: stage 0: 533 windows; per window: wait for the GPU 6.226 ms, pool + plan 0.294 ms, host staging 0.561 ms, commit 0.225 ms", + "strata serve: stage 1: 533 windows; per window: wait for the GPU 14.156 ms, pool + plan 0.373 ms, host staging 0.000 ms, commit 0.371 ms", + "strata serve: stage 0: 599 windows; per window: wait for the GPU 6.314 ms, pool + plan 0.292 ms, host staging 0.501 ms, commit 0.225 ms", + "strata serve: stage 1: 599 windows; per window: wait for the GPU 14.366 ms, pool + plan 0.375 ms, host staging 0.000 ms, commit 0.374 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 19)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.5% (6141 hits / 6234 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (3797 hits / 3836 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (3814 hits / 3837 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (28659 hits / 28795 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (3814 hits / 3839 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (141378 hits / 142508 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (124963 hits / 125273 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (134574 hits / 134874 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (121132 hits / 122322 lookups)", + "strata serve: decode expert cache hit rate: 99.9% (114073 hits / 114235 lookups)", + "strata serve: decode expert cache hit rate: 99.9% (113598 hits / 113754 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k20.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k20.json new file mode 100644 index 0000000..494c08b --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k20.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k20", + "extra": [ + "--layer-split", + "20" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9044.3, + "pp_tok_s": 1776.4, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13928.7, + "pp_tok_s": 1991.8, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3743.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 236.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 76.4, + "reps": [ + 74.2, + 78.4, + 76.7 + ], + "hit_rate": 0.9979911611088791, + "text": "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry it from the bedrock, and it howled through the narrow slits of the lantern room glass.\n\nElias Thorne was seventy years old, but he moved with the grace of a man who had spent fifty years listening to the sea. He knew the rhythm of the waves against the rocks below\u2014the *thud, thud, crash*\u2014and he knew when that rhythm changed. When the sea grew too quiet, or too violent, he knew a storm was coming, or a ship was in trouble.\n\nTonight, the storm was a Category 4. The rain lashed against the windows like gravel thrown by a giant. Elias stood in the center of the lantern room, his hand resting on the cold brass railing. He wasn\u2019t afraid. He was a guardian.\n\nHe checked the clockwork mechanism. It was old, a relic from 1" + }, + { + "name": "code", + "tok_s": 105.9, + "reps": [ + 103.2, + 106.8, + 107.7 + ], + "hit_rate": 0.9981849807154201, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 537 windows; per window: wait for the GPU 6.685 ms, pool + plan 0.403 ms, host staging 0.593 ms, commit 0.215 ms", + "strata serve: stage 1: 537 windows; per window: wait for the GPU 13.928 ms, pool + plan 0.282 ms, host staging 0.000 ms, commit 0.359 ms", + "strata serve: stage 0: 606 windows; per window: wait for the GPU 6.764 ms, pool + plan 0.399 ms, host staging 0.528 ms, commit 0.216 ms", + "strata serve: stage 1: 606 windows; per window: wait for the GPU 14.108 ms, pool + plan 0.288 ms, host staging 0.000 ms, commit 0.362 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 20)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 20-47, expert cache 7142 slots (14.14 GiB), 7142 of its 7168 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-19", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.9% (6162 hits / 6230 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (3803 hits / 3835 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (3810 hits / 3836 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (27185 hits / 27330 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (3807 hits / 3835 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (139825 hits / 140938 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (142122 hits / 142524 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (146556 hits / 146851 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (118026 hits / 119233 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (118729 hits / 118997 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (118791 hits / 119007 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k21.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k21.json new file mode 100644 index 0000000..8e7bcc9 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k21.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k21", + "extra": [ + "--layer-split", + "21" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8880.5, + "pp_tok_s": 1809.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13654.6, + "pp_tok_s": 2031.8, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3680.6, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 235.4, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 77.4, + "reps": [ + 80.2, + 80.8, + 71.2 + ], + "hit_rate": 0.9973622550922132, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from rope burns and broken glass, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, ensuring the rotation was smooth, silent, and steady. *Tick. Tick. Tick.* The sound was the heartbeat of the coast.\n\n" + }, + { + "name": "code", + "tok_s": 106.7, + "reps": [ + 100.6, + 110.5, + 109.0 + ], + "hit_rate": 0.998218711927068, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 527 windows; per window: wait for the GPU 6.934 ms, pool + plan 0.620 ms, host staging 0.530 ms, commit 0.245 ms", + "strata serve: stage 1: 527 windows; per window: wait for the GPU 13.912 ms, pool + plan 0.365 ms, host staging 0.000 ms, commit 0.359 ms", + "strata serve: stage 0: 595 windows; per window: wait for the GPU 7.031 ms, pool + plan 0.595 ms, host staging 0.472 ms, commit 0.245 ms", + "strata serve: stage 1: 595 windows; per window: wait for the GPU 14.051 ms, pool + plan 0.361 ms, host staging 0.000 ms, commit 0.361 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 21)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4627 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 21-47, expert cache 6912 slots (13.78 GiB), 6912 of its 6912 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-20", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-20 (CUDA0), 21-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.7% (5672 hits / 5748 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4287 hits / 4314 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4287 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (29024 hits / 29229 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4278 hits / 4316 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (131499 hits / 133085 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (130974 hits / 131451 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (138767 hits / 139134 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (121454 hits / 122932 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (116809 hits / 117079 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (118803 hits / 119015 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k22.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k22.json new file mode 100644 index 0000000..e139ea5 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k22.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k22", + "extra": [ + "--layer-split", + "22" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8730.9, + "pp_tok_s": 1840.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13375.4, + "pp_tok_s": 2074.2, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3611.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 234.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 80.2, + "reps": [ + 78.4, + 80.9, + 81.5 + ], + "hit_rate": 0.9977764197412695, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and he had been the keeper of the Blackwood Point Light for forty of those years. The other thirty-three had been spent in a small, drafty cottage on the mainland, waiting for the day when the sea would finally claim him.\n\nTonight, the storm was a Category 4. The waves weren\u2019t just crashing; they were climbing. They reached the gallery railing, ten feet above the base of the tower, spraying a fine mist of brine that coated Elias\u2019s glasses.\n\nHe climbed the spiral stairs, his knees protesting with every step. The iron steps were cold, slick with condensation. At the top, in the lantern room, the air was thin and sharp. The great Fresnel lens, a cathedral of glass and brass, stood silent. It was time to wake it.\n\n" + }, + { + "name": "code", + "tok_s": 106.4, + "reps": [ + 100.7, + 110.3, + 108.1 + ], + "hit_rate": 0.9971798370756316, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 529 windows; per window: wait for the GPU 7.229 ms, pool + plan 0.561 ms, host staging 0.529 ms, commit 0.233 ms", + "strata serve: stage 1: 529 windows; per window: wait for the GPU 13.058 ms, pool + plan 0.253 ms, host staging 0.000 ms, commit 0.334 ms", + "strata serve: stage 0: 598 windows; per window: wait for the GPU 7.325 ms, pool + plan 0.552 ms, host staging 0.469 ms, commit 0.235 ms", + "strata serve: stage 1: 598 windows; per window: wait for the GPU 13.238 ms, pool + plan 0.260 ms, host staging 0.000 ms, commit 0.337 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)", + "strata serve: decode expert cache hit rate: 98.7% (4256 hits / 4310 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4278 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (27008 hits / 27289 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (4260 hits / 4313 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (135183 hits / 137274 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (136132 hits / 136708 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (135515 hits / 135817 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (121287 hits / 123280 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (117658 hits / 118026 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (120574 hits / 120915 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k23.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k23.json new file mode 100644 index 0000000..b0b5827 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k23.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k23", + "extra": [ + "--layer-split", + "23" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8742.6, + "pp_tok_s": 1837.7, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13084.2, + "pp_tok_s": 2120.3, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3566.1, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 238.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 81.0, + "reps": [ + 76.8, + 85.2, + 81.1 + ], + "hit_rate": 0.9961302681992337, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning black void, swallowing the horizon, throwing white foam against the granite base like a tantrum.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his wool trousers, the fabric stiff with salt and grease. He checked the clockwork mechanism that turned the lens. It was a beast of a thing, a Fresnel lens of eight feet in diameter, a cathedral of glass and crystal that focused the beam of the lamp into a single, piercing needle of light.\n\nHe wound the weights. *Click, click, click.* The gears engaged. The massive lens began its slow, hypnotic rotation.\n\nFor a moment, the" + }, + { + "name": "code", + "tok_s": 108.4, + "reps": [ + 105.1, + 109.0, + 111.1 + ], + "hit_rate": 0.9961698810290479, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 537 windows; per window: wait for the GPU 7.423 ms, pool + plan 0.953 ms, host staging 0.542 ms, commit 0.237 ms", + "strata serve: stage 1: 537 windows; per window: wait for the GPU 12.223 ms, pool + plan 0.236 ms, host staging 0.000 ms, commit 0.324 ms", + "strata serve: stage 0: 606 windows; per window: wait for the GPU 7.519 ms, pool + plan 0.904 ms, host staging 0.483 ms, commit 0.239 ms", + "strata serve: stage 1: 606 windows; per window: wait for the GPU 12.395 ms, pool + plan 0.242 ms, host staging 0.000 ms, commit 0.326 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 23)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4609 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 23-47, expert cache 6400 slots (12.82 GiB), 6400 of its 6400 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-22", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-22 (CUDA0), 23-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 96.8% (5528 hits / 5709 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (4235 hits / 4303 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (4260 hits / 4308 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (30643 hits / 31089 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (4248 hits / 4309 lookups)", + "strata serve: decode expert cache hit rate: 98.3% (134776 hits / 137143 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (133024 hits / 133766 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (129995 hits / 130500 lookups)", + "strata serve: decode expert cache hit rate: 97.9% (115782 hits / 118287 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (117953 hits / 118464 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (117560 hits / 118012 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k24.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k24.json new file mode 100644 index 0000000..0d5baf6 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k24.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k24", + "extra": [ + "--layer-split", + "24" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8122.5, + "pp_tok_s": 1978.0, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 12285.8, + "pp_tok_s": 2258.1, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3407.0, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 234.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.5, + "reps": [ + 84.9, + 83.3, + 82.3 + ], + "hit_rate": 0.9949381327334084, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined Elias\u2019s life for thirty years. He was not merely a keeper; he was a guardian of silence.\n\nHe checked the clock. 11:42 PM. The rotation of the great Fresnel lens was due. With a practiced hand, he engaged the brake on the clockwork mechanism. The heavy brass gears groaned, then began their slow, rhythmic turn. *Tick. Tick. Tick.* It was a heartbeat" + }, + { + "name": "code", + "tok_s": 109.5, + "reps": [ + 104.9, + 111.0, + 112.6 + ], + "hit_rate": 0.9953796671318199, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 519 windows; per window: wait for the GPU 7.835 ms, pool + plan 0.767 ms, host staging 0.557 ms, commit 0.244 ms", + "strata serve: stage 1: 519 windows; per window: wait for the GPU 11.922 ms, pool + plan 0.232 ms, host staging 0.000 ms, commit 0.325 ms", + "strata serve: stage 0: 587 windows; per window: wait for the GPU 7.943 ms, pool + plan 0.744 ms, host staging 0.497 ms, commit 0.246 ms", + "strata serve: stage 1: 587 windows; per window: wait for the GPU 12.073 ms, pool + plan 0.238 ms, host staging 0.000 ms, commit 0.326 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 24)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 24-47, expert cache 6144 slots (12.35 GiB), 6144 of its 6144 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-23", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-23 (CUDA0), 24-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 95.9% (5916 hits / 6171 lookups)", + "strata serve: decode expert cache hit rate: 97.4% (3717 hits / 3815 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (3761 hits / 3823 lookups)", + "strata serve: decode expert cache hit rate: 98.1% (27138 hits / 27664 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (3742 hits / 3826 lookups)", + "strata serve: decode expert cache hit rate: 97.9% (126114 hits / 128875 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (133626 hits / 134658 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (132675 hits / 133350 lookups)", + "strata serve: decode expert cache hit rate: 96.8% (113593 hits / 117399 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (118372 hits / 118949 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (116981 hits / 117524 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k26.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k26.json new file mode 100644 index 0000000..a7b95c1 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k26.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k26", + "extra": [ + "--layer-split", + "26" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 7880.9, + "pp_tok_s": 2038.6, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 11771.9, + "pp_tok_s": 2356.7, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3323.9, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 231.5, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.8, + "reps": [ + 85.9, + 83.1, + 82.4 + ], + "hit_rate": 0.9933966961830739, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and green.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined Elias\u2019s life for thirty years. He was a keeper of the light, but more importantly, he was a keeper of time.\n\nHe checked his pocket watch. 11:42 PM. The rotation of the great Fresnel lens was due. With a practiced, rhythmic *clunk-clunk-clunk*, he wound the clockwork mechanism. The massive lens began its slow, hypnotic turn, sweeping its beam across" + }, + { + "name": "code", + "tok_s": 109.7, + "reps": [ + 104.4, + 112.7, + 111.9 + ], + "hit_rate": 0.9938670271352759, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 519 windows; per window: wait for the GPU 8.376 ms, pool + plan 1.030 ms, host staging 0.566 ms, commit 0.273 ms", + "strata serve: stage 1: 519 windows; per window: wait for the GPU 10.886 ms, pool + plan 0.214 ms, host staging 0.000 ms, commit 0.297 ms", + "strata serve: stage 0: 588 windows; per window: wait for the GPU 8.506 ms, pool + plan 0.985 ms, host staging 0.505 ms, commit 0.274 ms", + "strata serve: stage 1: 588 windows; per window: wait for the GPU 11.036 ms, pool + plan 0.219 ms, host staging 0.000 ms, commit 0.298 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 26)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4568 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 26-47, expert cache 5632 slots (11.32 GiB), 5632 of its 5632 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-25", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-25 (CUDA0), 26-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 92.8% (5259 hits / 5665 lookups)", + "strata serve: decode expert cache hit rate: 95.2% (4056 hits / 4259 lookups)", + "strata serve: decode expert cache hit rate: 97.2% (4164 hits / 4285 lookups)", + "strata serve: decode expert cache hit rate: 97.1% (27690 hits / 28510 lookups)", + "strata serve: decode expert cache hit rate: 97.5% (4184 hits / 4293 lookups)", + "strata serve: decode expert cache hit rate: 96.9% (121839 hits / 125724 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (132165 hits / 133648 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (137652 hits / 138567 lookups)", + "strata serve: decode expert cache hit rate: 95.3% (111307 hits / 116822 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (118436 hits / 119329 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (119109 hits / 119844 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k28.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k28.json new file mode 100644 index 0000000..8e81120 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k28.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k28", + "extra": [ + "--layer-split", + "28" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 7989.3, + "pp_tok_s": 2010.9, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 12132.9, + "pp_tok_s": 2286.6, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3433.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 228.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.5, + "reps": [ + 83.7, + 82.4, + 84.5 + ], + "hit_rate": 0.9900441970361987, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias climbed the spiral stairs, his hand gripping the cold iron railing. His knees ached, not from age, but from the constant vibration of the floor beneath his feet. He reached the lantern room, the heart of the lighthouse, and checked the clockwork mechanism. The great lens, a prism of Fresnel glass, rotated with a steady, hypnotic *whirrr-click, whirrr-click*. It was the only sound that mattered. The light swept out into the black void, cutting through" + }, + { + "name": "code", + "tok_s": 112.5, + "reps": [ + 101.4, + 112.1, + 124.1 + ], + "hit_rate": 0.9896636587366694, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n```<|im_end|>" + } + ], + "stage_timing": [ + "strata serve: stage 0: 527 windows; per window: wait for the GPU 8.765 ms, pool + plan 1.401 ms, host staging 0.593 ms, commit 0.281 ms", + "strata serve: stage 1: 527 windows; per window: wait for the GPU 9.893 ms, pool + plan 0.195 ms, host staging 0.000 ms, commit 0.276 ms", + "strata serve: stage 0: 578 windows; per window: wait for the GPU 8.908 ms, pool + plan 1.359 ms, host staging 0.559 ms, commit 0.284 ms", + "strata serve: stage 1: 578 windows; per window: wait for the GPU 10.025 ms, pool + plan 0.200 ms, host staging 0.000 ms, commit 0.278 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 28)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4537 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 28-47, expert cache 5120 slots (10.30 GiB), 5120 of its 5120 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-27", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-27 (CUDA0), 28-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 88.8% (5405 hits / 6086 lookups)", + "strata serve: decode expert cache hit rate: 93.8% (3539 hits / 3773 lookups)", + "strata serve: decode expert cache hit rate: 94.2% (3560 hits / 3781 lookups)", + "strata serve: decode expert cache hit rate: 95.7% (26702 hits / 27899 lookups)", + "strata serve: decode expert cache hit rate: 95.9% (3647 hits / 3804 lookups)", + "strata serve: decode expert cache hit rate: 95.7% (122618 hits / 128160 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (135035 hits / 136884 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (129476 hits / 130778 lookups)", + "strata serve: decode expert cache hit rate: 93.9% (111037 hits / 118290 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (118829 hits / 120140 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (90480 hits / 91425 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k30.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k30.json new file mode 100644 index 0000000..8ce08cd --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k30.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k30", + "extra": [ + "--layer-split", + "30" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8301.3, + "pp_tok_s": 1935.4, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 12507.6, + "pp_tok_s": 2218.1, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3448.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 229.4, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 81.1, + "reps": [ + 78.0, + 84.4, + 81.0 + ], + "hit_rate": 0.9798126997277784, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias stood at the top of the spiral staircase, his hand resting on the cold iron railing. He was not afraid. Fear was for the tourists who came in summer, wide-eyed and clutching their cameras. Elias was a keeper. He was a guardian.\n\nHe checked the logbook. The entry for the night was simple: *Wind, 60 knots. Visibility, zero. Light, operational.*\n\nHe walked down the stairs, his boots heavy on the metal grating. The smell of salt" + }, + { + "name": "code", + "tok_s": 109.6, + "reps": [ + 100.7, + 114.1, + 114.1 + ], + "hit_rate": 0.9825370343977666, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 540 windows; per window: wait for the GPU 9.206 ms, pool + plan 1.794 ms, host staging 0.525 ms, commit 0.298 ms", + "strata serve: stage 1: 540 windows; per window: wait for the GPU 8.767 ms, pool + plan 0.173 ms, host staging 0.000 ms, commit 0.242 ms", + "strata serve: stage 0: 608 windows; per window: wait for the GPU 9.390 ms, pool + plan 1.733 ms, host staging 0.471 ms, commit 0.301 ms", + "strata serve: stage 1: 608 windows; per window: wait for the GPU 8.910 ms, pool + plan 0.178 ms, host staging 0.000 ms, commit 0.244 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 30)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4479 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 30-47, expert cache 4608 slots (9.19 GiB), 4608 of its 4608 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-29", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-29 (CUDA0), 30-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 84.6% (5099 hits / 6028 lookups)", + "strata serve: decode expert cache hit rate: 90.7% (3403 hits / 3751 lookups)", + "strata serve: decode expert cache hit rate: 91.1% (3415 hits / 3747 lookups)", + "strata serve: decode expert cache hit rate: 94.1% (26108 hits / 27737 lookups)", + "strata serve: decode expert cache hit rate: 93.4% (3534 hits / 3784 lookups)", + "strata serve: decode expert cache hit rate: 94.6% (127532 hits / 134866 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (135828 hits / 137786 lookups)", + "strata serve: decode expert cache hit rate: 98.0% (132455 hits / 135184 lookups)", + "strata serve: decode expert cache hit rate: 91.0% (106351 hits / 116917 lookups)", + "strata serve: decode expert cache hit rate: 97.9% (115791 hits / 118246 lookups)", + "strata serve: decode expert cache hit rate: 98.3% (117198 hits / 119281 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-k32.json b/bench/results/2026-09-29-layer-split/data/pp-ks-k32.json new file mode 100644 index 0000000..bf23985 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-k32.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k32", + "extra": [ + "--layer-split", + "32" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8837.1, + "pp_tok_s": 1818.0, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13449.8, + "pp_tok_s": 2062.7, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3565.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 227.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.0, + "reps": [ + 75.0, + 86.1, + 87.8 + ], + "hit_rate": 0.9796934433020751, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. *Click. Click. Click.* The gears engaged, and the massive Fresnel lens began its slow" + }, + { + "name": "code", + "tok_s": 108.7, + "reps": [ + 98.8, + 112.2, + 115.1 + ], + "hit_rate": 0.9777186846317358, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 533 windows; per window: wait for the GPU 9.839 ms, pool + plan 2.192 ms, host staging 0.585 ms, commit 0.318 ms", + "strata serve: stage 1: 533 windows; per window: wait for the GPU 8.014 ms, pool + plan 0.156 ms, host staging 0.000 ms, commit 0.231 ms", + "strata serve: stage 0: 602 windows; per window: wait for the GPU 10.014 ms, pool + plan 2.111 ms, host staging 0.520 ms, commit 0.321 ms", + "strata serve: stage 1: 602 windows; per window: wait for the GPU 8.094 ms, pool + plan 0.160 ms, host staging 0.000 ms, commit 0.232 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 32)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4488 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 32-47, expert cache 4096 slots (8.26 GiB), 4096 of its 4096 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-31", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-31 (CUDA0), 32-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 81.3% (4889 hits / 6010 lookups)", + "strata serve: decode expert cache hit rate: 87.7% (3272 hits / 3733 lookups)", + "strata serve: decode expert cache hit rate: 87.9% (3280 hits / 3733 lookups)", + "strata serve: decode expert cache hit rate: 92.3% (24238 hits / 26254 lookups)", + "strata serve: decode expert cache hit rate: 91.5% (3457 hits / 3778 lookups)", + "strata serve: decode expert cache hit rate: 93.7% (133254 hits / 142240 lookups)", + "strata serve: decode expert cache hit rate: 98.0% (130112 hits / 132812 lookups)", + "strata serve: decode expert cache hit rate: 98.0% (130069 hits / 132765 lookups)", + "strata serve: decode expert cache hit rate: 89.1% (105263 hits / 118190 lookups)", + "strata serve: decode expert cache hit rate: 97.2% (116970 hits / 120309 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (115450 hits / 118081 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-ks-single.json b/bench/results/2026-09-29-layer-split/data/pp-ks-single.json new file mode 100644 index 0000000..d4fe9d7 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-ks-single.json @@ -0,0 +1,76 @@ +{ + "label": "ks-single", + "extra": [], + "gpus": "0", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9310.4, + "pp_tok_s": 1725.6, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 14085.4, + "pp_tok_s": 1969.6, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3388.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 200.7, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 86.7, + "reps": [ + 78.2, + 91.4, + 90.4 + ], + "hit_rate": 0.921882148773369, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and his hands were a map of the coastline he had guarded for fifty years. The knuckles were swollen, the skin cracked like dry earth, but they moved with a precision that no machine could replicate.\n\nHe stood on the gallery of the *Harrow Point* lighthouse, the iron railing cold against his palms. Below, the Atlantic churned in a frenzy, whitecaps exploding against the black rocks like fireworks. Above, the sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen.\n\nElias checked the clock. 11:42 PM. The light was due.\n\nHe didn\u2019t look at the gauge. He didn\u2019t check the fuel levels. He knew. He always knew. The rhythm of the ocean, the pressure of the air, the subtle vibration" + }, + { + "name": "code", + "tok_s": 105.2, + "reps": [ + 87.8, + 113.5, + 114.2 + ], + "hit_rate": 0.9109811738648947, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 382 windows; per window: wait for the GPU 15.155 ms, pool + plan 4.331 ms, host staging 0.656 ms, commit 0.458 ms", + "strata serve: stage 0: 455 windows; per window: wait for the GPU 15.790 ms, pool + plan 5.552 ms, host staging 0.688 ms, commit 0.467 ms", + "strata serve: stage 0: 524 windows; per window: wait for the GPU 16.064 ms, pool + plan 5.529 ms, host staging 0.606 ms, commit 0.472 ms", + "strata serve: stage 0: 593 windows; per window: wait for the GPU 16.305 ms, pool + plan 5.462 ms, host staging 0.540 ms, commit 0.475 ms" + ], + "engine_lines": [ + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 67.8% (2299 hits / 3391 lookups)", + "strata serve: decode expert cache hit rate: 68.5% (2345 hits / 3424 lookups)", + "strata serve: decode expert cache hit rate: 75.6% (16605 hits / 21959 lookups)", + "strata serve: decode expert cache hit rate: 73.3% (2608 hits / 3558 lookups)", + "strata serve: decode expert cache hit rate: 83.7% (104878 hits / 125346 lookups)", + "strata serve: decode expert cache hit rate: 92.7% (119739 hits / 129184 lookups)", + "strata serve: decode expert cache hit rate: 92.2% (116867 hits / 126770 lookups)", + "strata serve: decode expert cache hit rate: 68.1% (64111 hits / 94116 lookups)", + "strata serve: decode expert cache hit rate: 89.0% (96370 hits / 108259 lookups)", + "strata serve: decode expert cache hit rate: 91.1% (102827 hits / 112875 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-rel-5080.json b/bench/results/2026-09-29-layer-split/data/pp-rel-5080.json new file mode 100644 index 0000000..e078384 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-rel-5080.json @@ -0,0 +1,72 @@ +{ + "label": "rel-5080", + "extra": [], + "gpus": "0", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2132.8, + "pp_tok_s": 1278.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5008.9, + "pp_tok_s": 1672.8, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 7855.4, + "pp_tok_s": 2045.2, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13833.9, + "pp_tok_s": 2005.4, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3298.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 197.9, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.2, + "hit_rate": 0.8418683557684931, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. *Click. Click. Click.* The gears engaged, and the massive Fresnel lens began its slow" + }, + { + "name": "code", + "tok_s": 88.2, + "hit_rate": 0.7011385968111186, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)", + "strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)", + "strata serve: decode expert cache hit rate: 72.5% (2539 hits / 3504 lookups)", + "strata serve: decode expert cache hit rate: 77.3% (2817 hits / 3642 lookups)", + "strata serve: decode expert cache hit rate: 75.3% (16500 hits / 21916 lookups)", + "strata serve: decode expert cache hit rate: 80.0% (2978 hits / 3723 lookups)", + "strata serve: decode expert cache hit rate: 84.2% (98752 hits / 117301 lookups)", + "strata serve: decode expert cache hit rate: 70.1% (69215 hits / 98718 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-t75-5080.json b/bench/results/2026-09-29-layer-split/data/pp-t75-5080.json new file mode 100644 index 0000000..a339822 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-t75-5080.json @@ -0,0 +1,78 @@ +{ + "label": "t75-5080", + "extra": [], + "gpus": "0", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2158.8, + "pp_tok_s": 1262.7, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5060.0, + "pp_tok_s": 1655.9, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3389.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 213.5, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 80.4, + "reps": [ + 80.4 + ], + "hit_rate": 0.855538332528651, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning black void, punctuated by whitecaps that looked like teeth.\n\nHe climbed the spiral stairs, his boots heavy with salt and exhaustion. The iron steps groaned under his weight, a sound that had become so familiar to him that he could sleep to it. But tonight, he wasn\u2019t sleeping. He was working.\n\nThe lens was the heart of the lighthouse. A massive, rotating Fresnel lens, a cathedral of glass and brass that turned with a mechanical hum. Elias checked the clockwork mechanism. It was smooth, rhythmic, a heartbeat in the dark. But the light itself was failing.\n\nHe climbed higher, into the lantern room. The wind battered the glass panes," + }, + { + "name": "code", + "tok_s": 87.5, + "reps": [ + 87.5 + ], + "hit_rate": 0.7075461363025227, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 39 windows; per window: wait for the GPU 17.252 ms, pool + plan 8.473 ms, host staging 0.611 ms, commit 0.525 ms", + "strata serve: stage 0: 47 windows; per window: wait for the GPU 18.018 ms, pool + plan 8.616 ms, host staging 0.607 ms, commit 0.534 ms", + "strata serve: stage 0: 169 windows; per window: wait for the GPU 15.223 ms, pool + plan 5.717 ms, host staging 0.688 ms, commit 0.467 ms", + "strata serve: stage 0: 243 windows; per window: wait for the GPU 16.500 ms, pool + plan 7.316 ms, host staging 0.742 ms, commit 0.481 ms" + ], + "engine_lines": [ + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4294 slots, 8.18 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)", + "strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)", + "strata serve: decode expert cache hit rate: 75.5% (16316 hits / 21602 lookups)", + "strata serve: decode expert cache hit rate: 74.4% (2660 hits / 3573 lookups)", + "strata serve: decode expert cache hit rate: 83.4% (92664 hits / 111086 lookups)", + "strata serve: decode expert cache hit rate: 72.0% (70946 hits / 98601 lookups)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)", + "strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)", + "strata serve: decode expert cache hit rate: 75.5% (16316 hits / 21602 lookups)", + "strata serve: decode expert cache hit rate: 74.4% (2659 hits / 3572 lookups)", + "strata serve: decode expert cache hit rate: 85.6% (101004 hits / 118059 lookups)", + "strata serve: decode expert cache hit rate: 70.8% (71044 hits / 100409 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-v-x2-auto.json b/bench/results/2026-09-29-layer-split/data/pp-v-x2-auto.json new file mode 100644 index 0000000..4b02eec --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-v-x2-auto.json @@ -0,0 +1,103 @@ +{ + "label": "v-x2-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2577.0, + "pp_tok_s": 1057.8, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 4433.5, + "pp_tok_s": 1889.9, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 7885.8, + "pp_tok_s": 2037.3, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13384.6, + "pp_tok_s": 2072.8, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3667.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 253.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 79.5, + "reps": [ + 78.9, + 79.0, + 80.7 + ], + "hit_rate": 0.9969903443250137, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from rope burns and broken glass, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, listening for the faint, rhythmic *tick-tick-tick* that signaled the rotation was true. If the rhythm faltered, ships" + }, + { + "name": "code", + "tok_s": 108.9, + "reps": [ + 103.3, + 113.7, + 109.5 + ], + "hit_rate": 0.9971795386830036, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 542 windows; per window: wait for the GPU 7.167 ms, pool + plan 0.572 ms, host staging 0.550 ms, commit 0.232 ms", + "strata serve: stage 1: 542 windows; per window: wait for the GPU 12.855 ms, pool + plan 0.250 ms, host staging 0.000 ms, commit 0.334 ms", + "strata serve: stage 0: 610 windows; per window: wait for the GPU 7.276 ms, pool + plan 0.559 ms, host staging 0.493 ms, commit 0.234 ms", + "strata serve: stage 1: 610 windows; per window: wait for the GPU 13.048 ms, pool + plan 0.258 ms, host staging 0.000 ms, commit 0.337 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.30 GiB for experts", + "strata generate: layer split auto: CUDA1 82 SMs at 1.86 GHz -> 0.48 ms per layer, 14.14 GiB for experts", + "strata generate: layer split auto: K=22 - predicted 19.7 ms per decode window; the caches hold 11298 of 12288 profiled pairs (~99.7% of the routed mass)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (4241 hits / 4306 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (4262 hits / 4309 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4290 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (4303 hits / 4319 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (28379 hits / 28721 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (4285 hits / 4314 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (136232 hits / 138256 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (135540 hits / 136216 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (136812 hits / 137225 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (118437 hits / 120406 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (112836 hits / 113230 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-v-x2r-auto.json b/bench/results/2026-09-29-layer-split/data/pp-v-x2r-auto.json new file mode 100644 index 0000000..786a117 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-v-x2r-auto.json @@ -0,0 +1,88 @@ +{ + "label": "v-x2r-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "2,0", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9610.0, + "pp_tok_s": 1671.8, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 14786.1, + "pp_tok_s": 1876.3, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3850.8, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 245.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 90.3, + "reps": [ + 91.0, + 97.0, + 82.8 + ], + "hit_rate": 0.993905472636816, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak of the spiral staircase, every draft that slipped under the door, and every shift in the barometric pressure that preceded a storm. He was not merely a worker; he was the heartbeat of the coast.\n\nIt was November, the month of grey seas and shorter days. The fog had rolled in thick, a wall of white so dense that even the beam of the Fresnel lens seemed to struggle against it. Elias stood in the lantern room, his hands roughened by salt and rope, adjusting the rotation mechanism. The great lens, a cathedral of glass and brass, began its slow, rhythmic sweep. *Flash. Dark. Flash. Dark.*\n\nHe checked the log" + }, + { + "name": "code", + "tok_s": 105.1, + "reps": [ + 98.4, + 109.9, + 107.0 + ], + "hit_rate": 0.9949900793650793, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 492 windows; per window: wait for the GPU 15.016 ms, pool + plan 0.297 ms, host staging 0.517 ms, commit 0.404 ms", + "strata serve: stage 1: 492 windows; per window: wait for the GPU 5.775 ms, pool + plan 0.854 ms, host staging 0.001 ms, commit 0.210 ms", + "strata serve: stage 0: 561 windows; per window: wait for the GPU 15.257 ms, pool + plan 0.306 ms, host staging 0.455 ms, commit 0.408 ms", + "strata serve: stage 1: 561 windows; per window: wait for the GPU 5.852 ms, pool + plan 0.820 ms, host staging 0.001 ms, commit 0.210 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 57.7 GB/s -> pcie_frac 0.55", + "strata generate: layer split: CUDA1 holds its weights, session and head; 9.98 GiB free", + "strata generate: layer split auto: CUDA0 82 SMs at 1.86 GHz -> 0.48 ms per layer, 16.45 GiB for experts", + "strata generate: layer split auto: CUDA1 84 SMs at 2.81 GHz -> 0.31 ms per layer, 5.99 GiB for experts", + "strata generate: layer split auto: K=30 - predicted 20.8 ms per decode window; the caches hold 10684 of 12288 profiled pairs (~99.5% of the routed mass)", + "strata generate: expert cache auto: 18.62 GiB free, 700 MiB reserved -> 6634 slots", + "strata generate: expert cache 7680 slots, 14.23 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 30-47, expert cache 3004 slots (5.98 GiB), 3004 of its 4608 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-29", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-29 (CUDA0), 30-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 93.2% (5367 hits / 5760 lookups)", + "strata serve: decode expert cache hit rate: 93.7% (4049 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 96.7% (4178 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 97.7% (26272 hits / 26880 lookups)", + "strata serve: decode expert cache hit rate: 97.1% (4194 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (110748 hits / 113280 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (113787 hits / 114240 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (127856 hits / 128640 lookups)", + "strata serve: decode expert cache hit rate: 96.3% (116528 hits / 120960 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (116423 hits / 117120 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (120354 hits / 120960 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-v-x3-auto.json b/bench/results/2026-09-29-layer-split/data/pp-v-x3-auto.json new file mode 100644 index 0000000..70510ae --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-v-x3-auto.json @@ -0,0 +1,89 @@ +{ + "label": "v-x3-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,1,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9525.4, + "pp_tok_s": 1686.6, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 15017.1, + "pp_tok_s": 1847.4, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4039.6, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 360.2, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 67.6, + "reps": [ + 59.8, + 83.1, + 59.9 + ], + "hit_rate": 0.9967581085879247, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with the force of a battering ram. Elias stood in the lantern room, his hands rough as sandpaper, adjusting the massive Fresnel lens. The rotation mechanism groaned, a sound like a ship\u2019s anchor chain being h" + }, + { + "name": "code", + "tok_s": 89.6, + "reps": [ + 81.0, + 104.8, + 83.0 + ], + "hit_rate": 0.9975041387598007, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 2: 522 windows; per window: wait for the GPU 12.405 ms, pool + plan 0.242 ms, host staging 0.006 ms, commit 0.375 ms", + "strata serve: stage 0: 590 windows; per window: wait for the GPU 7.387 ms, pool + plan 0.549 ms, host staging 0.517 ms, commit 0.248 ms", + "strata serve: stage 1: 590 windows; per window: wait for the GPU 3.071 ms, pool + plan 0.011 ms, host staging 0.000 ms, commit 0.606 ms", + "strata serve: stage 2: 590 windows; per window: wait for the GPU 12.592 ms, pool + plan 0.250 ms, host staging 0.006 ms, commit 0.377 ms" + ], + "engine_lines": [ + "strata generate: layer split across 3 GPUs: CUDA0, then CUDA1,2 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA1 holds its weights, session; 16.67 GiB free", + "strata generate: layer split: CUDA2 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA2 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.30 GiB for experts", + "strata generate: layer split auto: CUDA1 68 SMs at 1.54 GHz -> 0.69 ms per layer, 13.50 GiB for experts", + "strata generate: layer split auto: CUDA2 82 SMs at 1.86 GHz -> 0.48 ms per layer, 14.14 GiB for experts", + "strata generate: layer split auto: K=22,23 - predicted 19.9 ms per decode window; the caches hold 11298 of 12288 profiled pairs (~99.7% of the routed mass)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-22, expert cache 256 slots (0.52 GiB), 256 of its 256 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA2 runs layers 23-47, expert cache 6400 slots (12.82 GiB), 6400 of its 6400 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-22 (CUDA1), 23-47 (CUDA2), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)", + "strata serve: decode expert cache hit rate: 98.7% (4256 hits / 4310 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4278 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (29862 hits / 30170 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (4264 hits / 4313 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (134418 hits / 136339 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (116986 hits / 117525 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (129134 hits / 129554 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-x2-auto-c1024.json b/bench/results/2026-09-29-layer-split/data/pp-x2-auto-c1024.json new file mode 100644 index 0000000..9bc24c3 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-x2-auto-c1024.json @@ -0,0 +1,84 @@ +{ + "label": "x2-auto-c1024", + "extra": [ + "--layer-split", + "auto", + "--prefill", + "1024" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2648.7, + "pp_tok_s": 1029.2, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5547.0, + "pp_tok_s": 1510.5, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 10123.3, + "pp_tok_s": 1587.0, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 17652.0, + "pp_tok_s": 1571.7, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4379.9, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 235.5, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 82.7, + "hit_rate": 1.0, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that made the floorboards tremble. Elias stood by the lantern room, his hands wrapped around a mug of coffee that had gone cold hours ago. He wasn\u2019t drinking it. He was holding it for warmth." + }, + { + "name": "code", + "tok_s": 111.1, + "hit_rate": 1.0, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_basic():\n \"\"\"Test basic CSV parsing with simple data.\"\"\"\n import tempfile\n import os\n \n # Create a temporary CSV" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: K=19 - the caches hold 12288 of 12288 profiled pairs (fullest device 99%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3613 slots", + "strata generate: expert cache 4864 slots, 8.76 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7424 slots (14.66 GiB), 7424 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 100.0% (5760 hits / 5760 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (26400 hits / 26400 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (130080 hits / 130080 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (110400 hits / 110400 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-x2-auto.json b/bench/results/2026-09-29-layer-split/data/pp-x2-auto.json new file mode 100644 index 0000000..280c63e --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-x2-auto.json @@ -0,0 +1,82 @@ +{ + "label": "x2-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2711.7, + "pp_tok_s": 1005.3, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5010.3, + "pp_tok_s": 1672.4, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 8994.8, + "pp_tok_s": 1786.1, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 15497.2, + "pp_tok_s": 1790.2, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4050.3, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 249.7, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.0, + "hit_rate": 0.9920220447608565, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. The massive Fresnel lens, a cathedral of glass and crystal, began its slow, hypnotic sweep" + }, + { + "name": "code", + "tok_s": 101.8, + "hit_rate": 0.991767530342175, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: K=19 - the caches hold 11767 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.5% (6141 hits / 6234 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (3797 hits / 3838 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (3804 hits / 3838 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (3816 hits / 3839 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (3825 hits / 3839 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (27693 hits / 27832 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (3815 hits / 3839 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (127081 hits / 128103 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (119386 hits / 120377 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-x2-k16.json b/bench/results/2026-09-29-layer-split/data/pp-x2-k16.json new file mode 100644 index 0000000..cca7bcf --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-x2-k16.json @@ -0,0 +1,81 @@ +{ + "label": "x2-k16", + "extra": [ + "--layer-split", + "16" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2987.1, + "pp_tok_s": 912.6, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5908.6, + "pp_tok_s": 1418.1, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 10655.8, + "pp_tok_s": 1507.7, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 18484.6, + "pp_tok_s": 1500.9, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4790.8, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 243.3, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 71.4, + "hit_rate": 0.9814261642156863, + "text": "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry the lighthouse from its bedrock. Inside, however, the air was still, smelling faintly of kerosene and old paper.\n\nElias had been the keeper of the Point for thirty-two years. He knew every creak in the floorboards, every draft that slipped through the window seals, and exactly how much oil the great Fresnel lens needed to turn its slow, hypnotic rotation.\n\nIt was 2:00 AM. The storm was at its peak. The sea was a chaotic black mirror, whipped into whitecaps that looked like jagged teeth.\n\nElias climbed the spiral stairs, his hand gripping the cold iron railing. His boots, heavy with salt and wear, thumped a steady rhythm against the stone. *Thump. Thump. Thump.*\n\nAt the top, the lantern room hummed with the vibration of" + }, + { + "name": "code", + "tok_s": 86.4, + "hit_rate": 0.9798276439089693, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 16)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4096 slots, 7.17 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 16-47, expert cache 7124 slots (14.14 GiB), 7124 of its 8192 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-15", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-15 (CUDA0), 16-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5626 hits / 5760 lookups)", + "strata serve: decode expert cache hit rate: 98.1% (4237 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (4269 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4279 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (4298 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (28471 hits / 28800 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4282 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 98.1% (128135 hits / 130560 lookups)", + "strata serve: decode expert cache hit rate: 98.0% (117109 hits / 119520 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-x2-k22.json b/bench/results/2026-09-29-layer-split/data/pp-x2-k22.json new file mode 100644 index 0000000..765880e --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-x2-k22.json @@ -0,0 +1,81 @@ +{ + "label": "x2-k22", + "extra": [ + "--layer-split", + "22" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2537.7, + "pp_tok_s": 1074.2, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 4440.0, + "pp_tok_s": 1887.2, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 7872.5, + "pp_tok_s": 2040.8, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13405.0, + "pp_tok_s": 2069.6, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3610.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 236.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 78.1, + "hit_rate": 0.9851122208995093, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and he had been the keeper of the Blackwood Point Light for forty of those years. The other thirty-three had been spent in a hospital bed, waiting for the end.\n\nEvery night, Elias climbed the one hundred and twelve steps of the spiral staircase. His knees, worn smooth by the friction of his own boots over decades, protested with a sharp ache. He counted them. *One, two, three\u2026* The rhythm was his heartbeat. If he lost the count, he lost the light.\n\nAt the top, the lantern room hummed with the low, electric thrum of the Fresnel lens. It was a cathedral of glass and brass, a machine that had never failed him. Not once. Not in four decades.\n\nHe polished the brass railing with a rag that smelled of lemon and" + }, + { + "name": "code", + "tok_s": 104.3, + "hit_rate": 0.9842543225870746, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (4241 hits / 4306 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (4262 hits / 4309 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4290 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (4303 hits / 4319 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (28379 hits / 28721 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (4285 hits / 4314 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (135713 hits / 137764 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (118518 hits / 120414 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-x2r-auto.json b/bench/results/2026-09-29-layer-split/data/pp-x2r-auto.json new file mode 100644 index 0000000..acc5c98 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-x2r-auto.json @@ -0,0 +1,82 @@ +{ + "label": "x2r-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "2,0", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2804.2, + "pp_tok_s": 972.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5641.7, + "pp_tok_s": 1485.2, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 10643.4, + "pp_tok_s": 1509.5, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 18363.5, + "pp_tok_s": 1510.8, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4517.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 245.6, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 78.9, + "hit_rate": 0.9913117283950618, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to sync with his own heartbeat. He had been doing this for forty years. His hands were mapped with scars from rope burns and broken glass, his eyes permanently squinted against the glare of the bulb." + }, + { + "name": "code", + "tok_s": 93.4, + "hit_rate": 0.990286044973545, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 57.7 GB/s -> pcie_frac 0.55", + "strata generate: layer split: CUDA1 holds its weights, session and head; 9.98 GiB free", + "strata generate: layer split auto: K=36 - the caches hold 11775 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 18.62 GiB free, 700 MiB reserved -> 6634 slots", + "strata generate: expert cache 8828 slots, 16.45 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 36-47, expert cache 2945 slots (5.99 GiB), 2945 of its 3072 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-35", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-35 (CUDA0), 36-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.6% (5678 hits / 5760 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4283 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (4285 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (4303 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (4306 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (27700 hits / 27840 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4295 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (128474 hits / 129600 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (119785 hits / 120960 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-x2t-auto.json b/bench/results/2026-09-29-layer-split/data/pp-x2t-auto.json new file mode 100644 index 0000000..9c14111 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-x2t-auto.json @@ -0,0 +1,99 @@ +{ + "label": "x2t-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,1", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 4201.1, + "pp_tok_s": 648.9, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 9655.6, + "pp_tok_s": 867.8, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 17573.8, + "pp_tok_s": 914.2, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 30615.6, + "pp_tok_s": 906.2, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 7864.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 366.9, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 45.5, + "reps": [ + 45.5 + ], + "hit_rate": 0.9703345151405784, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, knew every bolt, every lever, and every creak in the iron bones of the tower.\n\nFor forty years, Elias had been the guardian of the Point. Not just of the light, but of the silence between the waves.\n\nIt was November. The sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that shook the floorboards beneath Elias\u2019s boots.\n\nHe climbed the stairs. One hundred and twelve steps. He counted them by feel, his left hand trailing along the cold iron railing. At the top, the air was" + }, + { + "name": "code", + "tok_s": 58.0, + "reps": [ + 58.0 + ], + "hit_rate": 0.9700542735219787, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 168 windows; per window: wait for the GPU 9.683 ms, pool + plan 0.509 ms, host staging 0.714 ms, commit 0.320 ms", + "strata serve: stage 1: 168 windows; per window: wait for the GPU 25.253 ms, pool + plan 0.881 ms, host staging 0.000 ms, commit 0.559 ms", + "strata serve: stage 0: 242 windows; per window: wait for the GPU 9.860 ms, pool + plan 0.550 ms, host staging 0.750 ms, commit 0.328 ms", + "strata serve: stage 1: 242 windows; per window: wait for the GPU 26.029 ms, pool + plan 0.980 ms, host staging 0.000 ms, commit 0.571 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA1 holds its weights, session and head; 16.18 GiB free", + "strata generate: layer split auto: K=20 - the caches hold 10761 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 20-47, expert cache 6157 slots (12.19 GiB), 6157 of its 7168 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-19", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window", + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA1 holds its weights, session and head; 16.18 GiB free", + "strata generate: layer split auto: K=20 - the caches hold 10761 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 20-47, expert cache 6157 slots (12.19 GiB), 6157 of its 7168 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-19", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 96.6% (5559 hits / 5754 lookups)", + "strata serve: decode expert cache hit rate: 97.5% (4205 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (4217 hits / 4312 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (4257 hits / 4318 lookups)" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/pp-x3-auto.json b/bench/results/2026-09-29-layer-split/data/pp-x3-auto.json new file mode 100644 index 0000000..14cd5a5 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/pp-x3-auto.json @@ -0,0 +1,99 @@ +{ + "label": "x3-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,2,1", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 3657.4, + "pp_tok_s": 745.3, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 7594.1, + "pp_tok_s": 1103.4, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 13996.4, + "pp_tok_s": 1147.9, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 24255.2, + "pp_tok_s": 1143.8, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 6104.9, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 393.4, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 51.9, + "reps": [ + 51.9 + ], + "hit_rate": 1.0, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that made the floorboards tremble. Elias stood by the lantern room, his hands wrapped around a mug of coffee that had gone cold hours ago. He wasn\u2019t drinking it. He was holding it for warmth." + }, + { + "name": "code", + "tok_s": 69.7, + "reps": [ + 69.7 + ], + "hit_rate": 1.0, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_basic():\n \"\"\"Test basic CSV parsing with simple data.\"\"\"\n import tempfile\n import os\n \n # Create a temporary CSV" + } + ], + "stage_timing": [ + "strata serve: stage 2: 165 windows; per window: wait for the GPU 13.452 ms, pool + plan 0.162 ms, host staging 0.000 ms, commit 0.328 ms", + "strata serve: stage 0: 234 windows; per window: wait for the GPU 6.235 ms, pool + plan 0.145 ms, host staging 0.704 ms, commit 0.214 ms", + "strata serve: stage 1: 234 windows; per window: wait for the GPU 15.592 ms, pool + plan 0.246 ms, host staging 0.000 ms, commit 0.657 ms", + "strata serve: stage 2: 234 windows; per window: wait for the GPU 13.916 ms, pool + plan 0.177 ms, host staging 0.000 ms, commit 0.335 ms" + ], + "engine_lines": [ + "strata generate: layer split across 3 GPUs: CUDA0, then CUDA1,2 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session; 18.62 GiB free", + "strata generate: layer split: CUDA2 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA2 holds its weights, session and head; 16.18 GiB free", + "strata generate: layer split auto: K=12,33 - the caches hold 12288 of 12288 profiled pairs (fullest device 66%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3072 slots", + "strata generate: expert cache 3072 slots, 5.41 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 12-32, expert cache 5376 slots (10.22 GiB), 5376 of its 5376 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA2 runs layers 33-47, expert cache 3840 slots (7.79 GiB), 3840 of its 3840 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-11", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-11 (CUDA0), 12-32 (CUDA1), 33-47 (CUDA2), one hand-off per window", + "strata generate: layer split across 3 GPUs: CUDA0, then CUDA1,2 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session; 18.62 GiB free", + "strata generate: layer split: CUDA2 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA2 holds its weights, session and head; 16.18 GiB free", + "strata generate: layer split auto: K=12,33 - the caches hold 12288 of 12288 profiled pairs (fullest device 66%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3072 slots", + "strata generate: expert cache 3072 slots, 5.41 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 12-32, expert cache 5376 slots (10.22 GiB), 5376 of its 5376 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA2 runs layers 33-47, expert cache 3840 slots (7.79 GiB), 3840 of its 3840 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-11" + ] +} \ No newline at end of file diff --git a/bench/results/2026-09-29-layer-split/data/summary-all.json b/bench/results/2026-09-29-layer-split/data/summary-all.json new file mode 100644 index 0000000..75bcd84 --- /dev/null +++ b/bench/results/2026-09-29-layer-split/data/summary-all.json @@ -0,0 +1,1083 @@ +{ + "regression": { + "release_vs_dev_identical": [ + 10, + 10 + ], + "speed_release": { + "greedy story 200": 58.4, + "greedy code 200": 80.6, + "greedy sanity": 75.2, + "greedy, no penalty (sanity)": 74.2, + "greedy presence=100 last_n=64": 48.5, + "greedy presence=100 last_n=64 story": 46.4, + "sampled presence=100 last_n=64 seed 3": 43.3, + "sampled presence=100 last_n=64 seed 11": 49.8, + "greedy frequency=100 last_n=16": 62.5, + "greedy presence=100 last_n=4096 (8-row windows)": 52.6 + }, + "speed_dev": { + "greedy story 200": 59.2, + "greedy code 200": 81.6, + "greedy sanity": 74.9, + "greedy, no penalty (sanity)": 74.3, + "greedy presence=100 last_n=64": 49.6, + "greedy presence=100 last_n=64 story": 44.9, + "sampled presence=100 last_n=64 seed 3": 44.1, + "sampled presence=100 last_n=64 seed 11": 49.5, + "greedy frequency=100 last_n=16": 65.2, + "greedy presence=100 last_n=4096 (8-row windows)": 52.5 + }, + "dev_vs_same_gpu_split_identical": [ + 10, + 10 + ] + }, + "correctness": { + "reg-rel": { + "cases": 10, + "repeats": 0, + "sanity_144": true, + "tok_s": { + "greedy story 200": 58.4, + "greedy code 200": 80.6, + "greedy sanity": 75.2, + "greedy, no penalty (sanity)": 74.2, + "greedy presence=100 last_n=64": 48.5, + "greedy presence=100 last_n=64 story": 46.4, + "sampled presence=100 last_n=64 seed 3": 43.3, + "sampled presence=100 last_n=64 seed 11": 49.8, + "greedy frequency=100 last_n=16": 62.5, + "greedy presence=100 last_n=4096 (8-row windows)": 52.6 + } + }, + "reg-dev": { + "cases": 10, + "repeats": 0, + "sanity_144": true, + "tok_s": { + "greedy story 200": 59.2, + "greedy code 200": 81.6, + "greedy sanity": 74.9, + "greedy, no penalty (sanity)": 74.3, + "greedy presence=100 last_n=64": 49.6, + "greedy presence=100 last_n=64 story": 44.9, + "sampled presence=100 last_n=64 seed 3": 44.1, + "sampled presence=100 last_n=64 seed 11": 49.5, + "greedy frequency=100 last_n=16": 65.2, + "greedy presence=100 last_n=4096 (8-row windows)": 52.5 + } + }, + "reg-same24": { + "cases": 10, + "repeats": 0, + "sanity_144": true, + "tok_s": { + "greedy story 200": 58.4, + "greedy code 200": 80.5, + "greedy sanity": 74.5, + "greedy, no penalty (sanity)": 76.8, + "greedy presence=100 last_n=64": 49.6, + "greedy presence=100 last_n=64 story": 46.7, + "sampled presence=100 last_n=64 seed 3": 44.3, + "sampled presence=100 last_n=64 seed 11": 50.0, + "greedy frequency=100 last_n=16": 62.0, + "greedy presence=100 last_n=4096 (8-row windows)": 52.1 + } + }, + "nr-x2-auto": { + "cases": 10, + "repeats": 0, + "sanity_144": true, + "tok_s": { + "greedy story 200": 74.0, + "greedy code 200": 103.4, + "greedy sanity": 91.1, + "greedy, no penalty (sanity)": 70.7, + "greedy presence=100 last_n=64": 65.4, + "greedy presence=100 last_n=64 story": 57.1, + "sampled presence=100 last_n=64 seed 3": 52.9, + "sampled presence=100 last_n=64 seed 11": 51.7, + "greedy frequency=100 last_n=16": 73.5, + "greedy presence=100 last_n=4096 (8-row windows)": 63.4 + } + } + }, + "runs": { + "dev-3090": { + "gpus": "2", + "extra": "", + "pp": [ + [ + 2726, + 796.0, + true + ], + [ + 8379, + 972.3, + true + ], + [ + 16066, + 1253.2, + true + ], + [ + 27743, + 1211.4, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 5657.8, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 238.7, + "ok": true + }, + "decode": [ + [ + "story", + 71.7, + 0.927 + ], + [ + "code", + 92.9, + 0.864 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n P", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 6.4 GB/s host->device -> pcie_frac 0.14 (default 0.55)", + "strata generate: expert cache auto: 17.31 GiB free, 700 MiB reserved -> 6704 slots", + "strata generate: expert cache 8730 slots, 16.62 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "dev-5080": { + "gpus": "0", + "extra": "", + "pp": [ + [ + 2726, + 1279.9, + true + ], + [ + 8379, + 1656.8, + true + ], + [ + 16066, + 2017.2, + true + ], + [ + 27743, + 1974.1, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3366.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 197.3, + "ok": true + }, + "decode": [ + [ + "story", + 83.1, + 0.842 + ], + [ + "code", + 88.0, + 0.701 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "ks-k18": { + "gpus": "0,2", + "extra": "--layer-split 18", + "pp": [ + [ + 16066, + 1547.2, + true + ], + [ + 27743, + 1694.5, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4308.0, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 239.8, + "ok": true + }, + "decode": [ + [ + "story", + 77.2, + 0.999 + ], + [ + "code", + 103.8, + 0.998 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 18)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4608 slots, 8.24 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 18-47, expert cache 7152 slots (14.14 GiB), 7152 of its 7680 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-17", + "strata serve: layer split: layers 0-17 (CUDA0), 18-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k19": { + "gpus": "0,2", + "extra": "--layer-split 19", + "pp": [ + [ + 16066, + 1626.9, + true + ], + [ + 27743, + 1790.1, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4085.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 238.7, + "ok": true + }, + "decode": [ + [ + "story", + 79.3, + 0.998 + ], + [ + "code", + 107.4, + 0.999 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 19)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k20": { + "gpus": "0,2", + "extra": "--layer-split 20", + "pp": [ + [ + 16066, + 1776.4, + true + ], + [ + 27743, + 1991.8, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3743.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 236.8, + "ok": true + }, + "decode": [ + [ + "story", + 76.4, + 0.998 + ], + [ + "code", + 105.9, + 0.998 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry it from the bedrock, a", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 20)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 20-47, expert cache 7142 slots (14.14 GiB), 7142 of its 7168 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-19", + "strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k21": { + "gpus": "0,2", + "extra": "--layer-split 21", + "pp": [ + [ + 16066, + 1809.1, + true + ], + [ + 27743, + 2031.8, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3680.6, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 235.4, + "ok": true + }, + "decode": [ + [ + "story", + 77.4, + 0.997 + ], + [ + "code", + 106.7, + 0.998 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching agai", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 21)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4627 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 21-47, expert cache 6912 slots (13.78 GiB), 6912 of its 6912 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-20", + "strata serve: layer split: layers 0-20 (CUDA0), 21-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k22": { + "gpus": "0,2", + "extra": "--layer-split 22", + "pp": [ + [ + 16066, + 1840.1, + true + ], + [ + 27743, + 2074.2, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3611.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 234.8, + "ok": true + }, + "decode": [ + [ + "story", + 80.2, + 0.998 + ], + [ + "code", + 106.4, + 0.997 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with ", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k23": { + "gpus": "0,2", + "extra": "--layer-split 23", + "pp": [ + [ + 16066, + 1837.7, + true + ], + [ + 27743, + 2120.3, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3566.1, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 238.0, + "ok": true + }, + "decode": [ + [ + "story", + 81.0, + 0.996 + ], + [ + "code", + 108.4, + 0.996 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 23)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4609 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 23-47, expert cache 6400 slots (12.82 GiB), 6400 of its 6400 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-22", + "strata serve: layer split: layers 0-22 (CUDA0), 23-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k24": { + "gpus": "0,2", + "extra": "--layer-split 24", + "pp": [ + [ + 16066, + 1978.0, + true + ], + [ + 27743, + 2258.1, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3407.0, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 234.0, + "ok": true + }, + "decode": [ + [ + "story", + 83.5, + 0.995 + ], + [ + "code", + 109.5, + 0.995 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching agai", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 24)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 24-47, expert cache 6144 slots (12.35 GiB), 6144 of its 6144 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-23", + "strata serve: layer split: layers 0-23 (CUDA0), 24-47 (CUDA1), one hand-off per window" + ] + }, + "ks-single": { + "gpus": "0", + "extra": "", + "pp": [ + [ + 16066, + 1725.6, + true + ], + [ + 27743, + 1969.6, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3388.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 200.7, + "ok": true + }, + "decode": [ + [ + "story", + 86.7, + 0.922 + ], + [ + "code", + 105.2, + 0.911 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with ", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "rel-5080": { + "gpus": "0", + "extra": "", + "pp": [ + [ + 2726, + 1278.1, + true + ], + [ + 8379, + 1672.8, + true + ], + [ + 16066, + 2045.2, + true + ], + [ + 27743, + 2005.4, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3298.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 197.9, + "ok": true + }, + "decode": [ + [ + "story", + 83.2, + 0.842 + ], + [ + "code", + 88.2, + 0.701 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "t75-5080": { + "gpus": "0", + "extra": "", + "pp": [ + [ + 2726, + 1262.9, + true + ], + [ + 8379, + 1658.6, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3385.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 212.5, + "ok": true + }, + "decode": [ + [ + "story", + 86.7, + 0.834 + ], + [ + "code", + 90.1, + 0.72 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 57.8 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4294 slots, 8.18 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "x2-auto-c1024": { + "gpus": "0,2", + "extra": "--layer-split auto --prefill 1024", + "pp": [ + [ + 2726, + 1029.2, + true + ], + [ + 8379, + 1510.5, + true + ], + [ + 16066, + 1587.0, + true + ], + [ + 27743, + 1571.7, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4379.9, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 235.5, + "ok": true + }, + "decode": [ + [ + "story", + 82.7, + 1.0 + ], + [ + "code", + 111.1, + 1.0 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: PCIe probe: 57.8 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: K=19 - the caches hold 12288 of 12288 profiled pairs (fullest device 99%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3613 slots", + "strata generate: expert cache 4864 slots, 8.76 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7424 slots (14.66 GiB), 7424 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window" + ] + }, + "x2-auto": { + "gpus": "0,2", + "extra": "--layer-split auto", + "pp": [ + [ + 2726, + 1005.3, + true + ], + [ + 8379, + 1672.4, + true + ], + [ + 16066, + 1786.1, + true + ], + [ + 27743, + 1790.2, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4050.3, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 249.7, + "ok": true + }, + "decode": [ + [ + "story", + 83.0, + 0.992 + ], + [ + "code", + 101.8, + 0.992 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: K=19 - the caches hold 11767 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window" + ] + }, + "x2-k16": { + "gpus": "0,2", + "extra": "--layer-split 16", + "pp": [ + [ + 2726, + 912.6, + true + ], + [ + 8379, + 1418.1, + true + ], + [ + 16066, + 1507.7, + true + ], + [ + 27743, + 1500.9, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4790.8, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 243.3, + "ok": true + }, + "decode": [ + [ + "story", + 71.4, + 0.981 + ], + [ + "code", + 86.4, + 0.98 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry the lighthouse from it", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 16)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4096 slots, 7.17 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 16-47, expert cache 7124 slots (14.14 GiB), 7124 of its 8192 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-15", + "strata serve: layer split: layers 0-15 (CUDA0), 16-47 (CUDA1), one hand-off per window" + ] + }, + "x2-k22": { + "gpus": "0,2", + "extra": "--layer-split 22", + "pp": [ + [ + 2726, + 1074.2, + true + ], + [ + 8379, + 1887.2, + true + ], + [ + 16066, + 2040.8, + true + ], + [ + 27743, + 2069.6, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3610.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 236.0, + "ok": true + }, + "decode": [ + [ + "story", + 78.1, + 0.985 + ], + [ + "code", + 104.3, + 0.984 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with ", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window" + ] + }, + "x2r-auto": { + "gpus": "2,0", + "extra": "--layer-split auto", + "pp": [ + [ + 2726, + 972.1, + true + ], + [ + 8379, + 1485.2, + true + ], + [ + 16066, + 1509.5, + true + ], + [ + 27743, + 1510.8, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4517.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 245.6, + "ok": true + }, + "decode": [ + [ + "story", + 78.9, + 0.991 + ], + [ + "code", + 93.4, + 0.99 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and i", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: PCIe probe: 6.4 GB/s host->device -> pcie_frac 0.14 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 57.7 GB/s -> pcie_frac 0.55", + "strata generate: layer split: CUDA1 holds its weights, session and head; 9.98 GiB free", + "strata generate: layer split auto: K=36 - the caches hold 11775 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 18.62 GiB free, 700 MiB reserved -> 6634 slots", + "strata generate: expert cache 8828 slots, 16.45 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 36-47, expert cache 2945 slots (5.99 GiB), 2945 of its 3072 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-35", + "strata serve: layer split: layers 0-35 (CUDA0), 36-47 (CUDA1), one hand-off per window" + ] + } + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/README.md b/bench/results/2026-09-29-rtx3090-epyc-milan/README.md new file mode 100644 index 0000000..05e346e --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/README.md @@ -0,0 +1,46 @@ +# Preliminary native RTX 3090 / EPYC 7453 results + +Issue: [#165](https://github.com/Niko1221/Strata/issues/165) +Engine: Strata v0.1.26, source build at `ac8b251` +Status: preliminary; prompt set and harness guidance requested upstream. + +## Hardware + +| Component | Guest-visible details | +|---|---| +| CPU | AMD EPYC 7453, 20 vCPU, AVX2; AVX-512 not exposed | +| RAM | 165 GiB visible to Ubuntu 24.04.5 KVM guest; physical DIMM layout and bandwidth not verified | +| GPUs | 2x RTX 3090 24 GB; PCIe Gen4 x16 maximum reported per card; driver 595.91.07 | +| Power limit | 280 W configured on each GPU; defaults are 350 W / 420 W, max-adjustable limits 366 W / 450 W | +| Storage | 541 GiB ext4 guest data disk; host storage layout not verified | + +The power values above are configured caps, not measured workload draw. Idle draw during the hardware capture was approximately 35 W / 29 W. + +## Method + +Native Linux setup, local build from v0.1.26, `--prefill auto`, shipped expert profile, automatic expert cache, int8 KV, MTP on, images off, experimental speed projection off. The GPU power limit was 280 W per card. Native runs used a systemd service with `LimitMEMLOCK=infinity`; other llama-swap model containers were stopped. + +The local API harness used the public Strata source tree as its prompt corpus, with generated tasks, `temperature: 0`, `reasoning_effort: none`, and `max_tokens: 256`. It is not the upstream code-agent prompt set or harness. Runs use unique request IDs and no conversation reuse in speed mode. Three runs per speed cell are summarized by medians; actual `usage.prompt_tokens` are recorded because nominal context labels can drift. The first decode run is also shown. Several requests ended early on EOS, so actual generated counts are in the raw JSON. + +No calibration comparison, upstream prompt comparison, `STRATA_SPLIT_TIMING` stage timing, or under-load power-draw capture has been done. Treat all prompt/decode comparisons with upstream as indicative only until the requested upstream method is available. + +## Results + +See [`matrix.md`](matrix.md) for summary tables and [`matrix.json`](matrix.json) for all successful run records. Per-run source JSON, logs, the local harness, and scrubbed hardware facts are in [`data/`](data/). + +Highlights: + +- IQ3_XXS on one 3090: 1K–262K cells, three runs each; 262K prompts were 232,183 / 259,589 / 261,068 tokens and fit within the 262,144 context. +- Coder IQ1_M at 32K: single-GPU median decode 66.8 tok/s; dual-GPU auto (K=19) median 98.6 tok/s. +- Fixed Coder K sweep: K=22 was the highest observed three-run median (103.3 tok/s); independently generated prompts mean this is not a paired ranking. +- IQ3_XXS and IQ3_S dual-GPU auto both selected K=24 at 32K. +- IQ3_XXS and IQ3_S needles passed 3/3 at 8K / 16K / 28K on the tested single/dual configurations; two-turn checkpoint reuse passed for both. + +## Limits and follow-up + +- Upstream prompts/harness are not yet available; all current speed data uses a local source-tree corpus. +- The guest exposes one NUMA node and 165 GiB RAM, but physical DIMM topology and memory bandwidth are unknown. +- PCIe x16 is the reported maximum link width; the engine probes were about 23–26 GB/s. Verify PCIe generation/width under sustained load before claiming a direct x16-vs-x4 comparison. +- Coder dual-GPU needle/two-turn checks and dual-GPU timing breakdowns are not run yet. +- K=18 has one successful run at 83.1 tok/s; a repeated startup failed while uploading a dense weight with an out-of-memory error, so it is not a three-run median. +- Calibration/default comparisons and IQ3_S single-GPU results remain outstanding. diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-1.json new file mode 100644 index 0000000..9aaa778 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-1.json @@ -0,0 +1,360 @@ +{ + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "6c1252339f83", + "corpus_repeated": false, + "time": "2026-09-29T21:11:07", + "prompt_tokens": 28317, + "completion_tokens": 48, + "ttft_s": 12.868, + "e2e_s": 13.739, + "api_prompt_tps": 2200.5, + "api_decode_tps": 54.0, + "engine_prompt_tps": 2229.2, + "engine_decode_tps": 52.7, + "log_lines": [ + "strata serve: prompt 28317 tokens = 0 reused + 28317 read in 12703 ms (2229.2 tok/s), 48 generated in 911 ms (52.7 tok/s), drafts accepted 31 of 38, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (25001 hits / 25956 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 8973, + "expert_cache_mib": 17503, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 369, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716268.10927, + "duration_s": 13.6, + "finish": "stop", + "prompt_tokens": 28317, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 12702.6, + "decode_ms": 910.6, + "decode_tok_s": 52.7, + "hit_rate": 0.963 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790716256.7391467, + "requests": 1, + "prompt_tokens": 28317, + "reused": 0, + "output_tokens": 48, + "prompt_ms": 12702.6, + "decode_ms": 910.6 + }, + "hardware": { + "gpu_util": 88, + "gpu_mem_used": 25531711488, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 220.362, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.28515625, + "gpu_pcie_tx_mb": 0.4287109375, + "cpu": 81.3, + "ram_used": 43964985344, + "ram_total": 177175990272, + "disk_read_mb": 2.9148478336133063, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 100, + 96, + 100, + 99, + 100, + 99, + 99, + 100, + 100, + 88 + ], + "gpu_mem_used": [ + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25407979520, + 25418465280, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25531711488 + ], + "gpu_temp": [ + 43, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46 + ], + "gpu_power": [ + 148.8, + 140.48, + 132.59, + 119.03, + 118.99, + 119.03, + 119.04, + 119.03, + 119.12, + 119.17, + 119.16, + 119.15, + 119.26, + 191.57, + 276.49, + 276.88, + 275.95, + 277.04, + 277.35, + 267.91, + 275.37, + 276.16, + 278.28, + 279.07, + 220.36 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.29, + 0.33, + 0.29, + 0.33, + 0.29, + 385.14, + 19.88, + 1892.23, + 13280.39, + 85.45, + 16838.55, + 680.06, + 1060.72, + 13.45, + 15.74, + 5013.75, + 1194.52, + 0.29 + ], + "cpu": [ + 0.0, + 0.7, + 7.3, + 15.7, + 7.1, + 2.0, + 1.2, + 2.0, + 2.1, + 1.6, + 1.9, + 7.4, + 13.9, + 18.3, + 6.1, + 6.0, + 16.7, + 24.9, + 13.2, + 12.0, + 7.1, + 6.2, + 6.0, + 8.8, + 81.3 + ], + "ram_used": [ + 43381886976, + 43381694464, + 43410796544, + 43434872832, + 43483377664, + 43485900800, + 43484897280, + 43481210880, + 43469135872, + 43462295552, + 43458363392, + 43496140800, + 43624353792, + 43648593920, + 43633405952, + 43641139200, + 43635249152, + 43689267200, + 43846070272, + 43924541440, + 43924467712, + 43918565376, + 43883311104, + 44002877440, + 43964985344 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 25.43, + 204.93, + 214.14, + 7.41, + 0.22, + 184.19, + 135.03, + 0.0, + 101.27, + 0.0, + 0.0, + 0.0, + 0.78, + 2.91 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790716282.234284 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-2.json new file mode 100644 index 0000000..fce0548 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-2.json @@ -0,0 +1,491 @@ +{ + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "894af0ad69b7", + "corpus_repeated": false, + "time": "2026-09-29T21:11:22", + "prompt_tokens": 31630, + "completion_tokens": 26, + "ttft_s": 12.792, + "e2e_s": 13.164, + "api_prompt_tps": 2472.7, + "api_decode_tps": 67.3, + "engine_prompt_tps": 2506.6, + "engine_decode_tps": 66.8, + "log_lines": [ + "strata serve: prompt 31630 tokens = 0 reused + 31630 read in 12619 ms (2506.6 tok/s), 26 generated in 389 ms (66.8 tok/s), drafts accepted 12 of 21, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (16646 hits / 16791 lookups)" + ], + "answer_head": "I don't see any file content in the conversation above. Could you please share the file you'd like me to analyze?", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 8973, + "expert_cache_mib": 17503, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 369, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716282.3818104, + "duration_s": 13.0, + "finish": "stop", + "prompt_tokens": 31630, + "reused": 0, + "output_tokens": 26, + "engine_generated": 26, + "prompt_ms": 12618.8, + "decode_ms": 389.0, + "decode_tok_s": 66.8, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790716268.10927, + "duration_s": 13.6, + "finish": "stop", + "prompt_tokens": 28317, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 12702.6, + "decode_ms": 910.6, + "decode_tok_s": 52.7, + "hit_rate": 0.963 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790716256.7391467, + "requests": 2, + "prompt_tokens": 59947, + "reused": 0, + "output_tokens": 74, + "prompt_ms": 25321.4, + "decode_ms": 1299.6 + }, + "hardware": { + "gpu_util": 81, + "gpu_mem_used": 25531711488, + "gpu_mem_total": 25769803776, + "gpu_temp": 45, + "gpu_power": 256.109, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 9.7744140625, + "gpu_pcie_tx_mb": 25.1767578125, + "cpu": 46.1, + "ram_used": 43872071680, + "ram_total": 177175990272, + "disk_read_mb": 1.6222807345356267, + "disk_write_mb": 0.018689870213544086, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 100, + 96, + 100, + 99, + 100, + 99, + 99, + 100, + 100, + 88, + 0, + 100, + 99, + 100, + 99, + 100, + 98, + 99, + 99, + 100, + 99, + 100, + 81 + ], + "gpu_mem_used": [ + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25407979520, + 25418465280, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488 + ], + "gpu_temp": [ + 43, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 44, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 48, + 47, + 45 + ], + "gpu_power": [ + 148.8, + 140.48, + 132.59, + 119.03, + 118.99, + 119.03, + 119.04, + 119.03, + 119.12, + 119.17, + 119.16, + 119.15, + 119.26, + 191.57, + 276.49, + 276.88, + 275.95, + 277.04, + 277.35, + 267.91, + 275.37, + 276.16, + 278.28, + 279.07, + 220.36, + 189.89, + 258.72, + 276.75, + 276.67, + 277.52, + 275.34, + 268.93, + 277.69, + 277.77, + 276.91, + 278.53, + 278.56, + 256.11 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.29, + 0.33, + 0.29, + 0.33, + 0.29, + 385.14, + 19.88, + 1892.23, + 13280.39, + 85.45, + 16838.55, + 680.06, + 1060.72, + 13.45, + 15.74, + 5013.75, + 1194.52, + 0.29, + 2531.19, + 14.02, + 3715.09, + 10.68, + 13440.37, + 8568.48, + 14.92, + 15.31, + 15.69, + 6486.56, + 17.31, + 9674.45, + 9.77 + ], + "cpu": [ + 0.0, + 0.7, + 7.3, + 15.7, + 7.1, + 2.0, + 1.2, + 2.0, + 2.1, + 1.6, + 1.9, + 7.4, + 13.9, + 18.3, + 6.1, + 6.0, + 16.7, + 24.9, + 13.2, + 12.0, + 7.1, + 6.2, + 6.0, + 8.8, + 81.3, + 4.2, + 6.8, + 6.4, + 7.6, + 5.5, + 6.0, + 20.6, + 12.9, + 6.2, + 7.0, + 5.7, + 5.9, + 46.1 + ], + "ram_used": [ + 43381886976, + 43381694464, + 43410796544, + 43434872832, + 43483377664, + 43485900800, + 43484897280, + 43481210880, + 43469135872, + 43462295552, + 43458363392, + 43496140800, + 43624353792, + 43648593920, + 43633405952, + 43641139200, + 43635249152, + 43689267200, + 43846070272, + 43924541440, + 43924467712, + 43918565376, + 43883311104, + 44002877440, + 43964985344, + 43959267328, + 43943862272, + 43937861632, + 43930320896, + 43922284544, + 43915001856, + 43817238528, + 43819147264, + 43818729472, + 43828027392, + 43824201728, + 43825434624, + 43872071680 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 25.43, + 204.93, + 214.14, + 7.41, + 0.22, + 184.19, + 135.03, + 0.0, + 101.27, + 0.0, + 0.0, + 0.0, + 0.78, + 2.91, + 0.61, + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 79.64, + 41.92, + 0.0, + 0.0, + 0.0, + 0.0, + 1.62 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790716295.9009006 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-3.json new file mode 100644 index 0000000..c94b836 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-3.json @@ -0,0 +1,622 @@ +{ + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "a4c63bd599ab", + "corpus_repeated": false, + "time": "2026-09-29T21:11:35", + "prompt_tokens": 31601, + "completion_tokens": 45, + "ttft_s": 12.796, + "e2e_s": 13.243, + "api_prompt_tps": 2469.6, + "api_decode_tps": 98.5, + "engine_prompt_tps": 2502.4, + "engine_decode_tps": 97.4, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 12628 ms (2502.4 tok/s), 45 generated in 462 ms (97.4 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.6% (23985 hits / 24333 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 8973, + "expert_cache_mib": 17503, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 369, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716296.0458817, + "duration_s": 13.1, + "finish": "stop", + "prompt_tokens": 31601, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 12628.3, + "decode_ms": 461.9, + "decode_tok_s": 97.4, + "hit_rate": 0.986 + }, + { + "projection": null, + "time": 1790716282.3818104, + "duration_s": 13.0, + "finish": "stop", + "prompt_tokens": 31630, + "reused": 0, + "output_tokens": 26, + "engine_generated": 26, + "prompt_ms": 12618.8, + "decode_ms": 389.0, + "decode_tok_s": 66.8, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790716268.10927, + "duration_s": 13.6, + "finish": "stop", + "prompt_tokens": 28317, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 12702.6, + "decode_ms": 910.6, + "decode_tok_s": 52.7, + "hit_rate": 0.963 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790716256.7391467, + "requests": 3, + "prompt_tokens": 91548, + "reused": 0, + "output_tokens": 119, + "prompt_ms": 37949.7, + "decode_ms": 1761.5 + }, + "hardware": { + "gpu_util": 96, + "gpu_mem_used": 25531711488, + "gpu_mem_total": 25769803776, + "gpu_temp": 47, + "gpu_power": 245.399, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 414.037109375, + "gpu_pcie_tx_mb": 303.36328125, + "cpu": 35.1, + "ram_used": 43772702720, + "ram_total": 177175990272, + "disk_read_mb": 0.6087260569540994, + "disk_write_mb": 0.20539836277592313, + "tok_s": 97.29124144311484, + "tok_s_mean": 96.62332449971758 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 100, + 96, + 100, + 99, + 100, + 99, + 99, + 100, + 100, + 88, + 0, + 100, + 99, + 100, + 99, + 100, + 98, + 99, + 99, + 100, + 99, + 100, + 81, + 99, + 100, + 100, + 99, + 100, + 99, + 17, + 99, + 100, + 99, + 99, + 99, + 96 + ], + "gpu_mem_used": [ + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25407979520, + 25418465280, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488 + ], + "gpu_temp": [ + 43, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 44, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 48, + 47, + 45, + 47, + 47, + 47, + 48, + 48, + 48, + 46, + 47, + 48, + 48, + 48, + 48, + 47 + ], + "gpu_power": [ + 148.8, + 140.48, + 132.59, + 119.03, + 118.99, + 119.03, + 119.04, + 119.03, + 119.12, + 119.17, + 119.16, + 119.15, + 119.26, + 191.57, + 276.49, + 276.88, + 275.95, + 277.04, + 277.35, + 267.91, + 275.37, + 276.16, + 278.28, + 279.07, + 220.36, + 189.89, + 258.72, + 276.75, + 276.67, + 277.52, + 275.34, + 268.93, + 277.69, + 277.77, + 276.91, + 278.53, + 278.56, + 256.11, + 199.6, + 275.35, + 275.49, + 276.31, + 275.46, + 277.78, + 266.35, + 267.73, + 276.71, + 276.41, + 275.34, + 278.17, + 245.4 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.29, + 0.33, + 0.29, + 0.33, + 0.29, + 385.14, + 19.88, + 1892.23, + 13280.39, + 85.45, + 16838.55, + 680.06, + 1060.72, + 13.45, + 15.74, + 5013.75, + 1194.52, + 0.29, + 2531.19, + 14.02, + 3715.09, + 10.68, + 13440.37, + 8568.48, + 14.92, + 15.31, + 15.69, + 6486.56, + 17.31, + 9674.45, + 9.77, + 2795.22, + 4473.69, + 14.5, + 12.97, + 14.92, + 7716.66, + 2819.78, + 4278.33, + 12009.48, + 17.07, + 9916.78, + 8518.17, + 414.04 + ], + "cpu": [ + 0.0, + 0.7, + 7.3, + 15.7, + 7.1, + 2.0, + 1.2, + 2.0, + 2.1, + 1.6, + 1.9, + 7.4, + 13.9, + 18.3, + 6.1, + 6.0, + 16.7, + 24.9, + 13.2, + 12.0, + 7.1, + 6.2, + 6.0, + 8.8, + 81.3, + 4.2, + 6.8, + 6.4, + 7.6, + 5.5, + 6.0, + 20.6, + 12.9, + 6.2, + 7.0, + 5.7, + 5.9, + 46.1, + 4.0, + 6.9, + 5.7, + 6.2, + 7.1, + 5.5, + 5.6, + 9.9, + 13.7, + 8.4, + 7.7, + 6.4, + 35.1 + ], + "ram_used": [ + 43381886976, + 43381694464, + 43410796544, + 43434872832, + 43483377664, + 43485900800, + 43484897280, + 43481210880, + 43469135872, + 43462295552, + 43458363392, + 43496140800, + 43624353792, + 43648593920, + 43633405952, + 43641139200, + 43635249152, + 43689267200, + 43846070272, + 43924541440, + 43924467712, + 43918565376, + 43883311104, + 44002877440, + 43964985344, + 43959267328, + 43943862272, + 43937861632, + 43930320896, + 43922284544, + 43915001856, + 43817238528, + 43819147264, + 43818729472, + 43828027392, + 43824201728, + 43825434624, + 43872071680, + 43734614016, + 43728027648, + 43719413760, + 43703148544, + 43695366144, + 43687342080, + 43744829440, + 43791024128, + 43789787136, + 43766198272, + 43761831936, + 43750072320, + 43772702720 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 25.43, + 204.93, + 214.14, + 7.41, + 0.22, + 184.19, + 135.03, + 0.0, + 101.27, + 0.0, + 0.0, + 0.0, + 0.78, + 2.91, + 0.61, + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 79.64, + 41.92, + 0.0, + 0.0, + 0.0, + 0.0, + 1.62, + 0.72, + 0.0, + 0.0, + 0.05, + 0.0, + 0.0, + 0.18, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.61 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.29 + ] + }, + "time": 1790716309.6464093 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K18/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K18/speed-32k-1.json new file mode 100644 index 0000000..3f6e910 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K18/speed-32k-1.json @@ -0,0 +1,423 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K18", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "052cbcbb7af7", + "corpus_repeated": false, + "time": "2026-09-29T21:21:48", + "prompt_tokens": 28313, + "completion_tokens": 57, + "ttft_s": 12.346, + "e2e_s": 12.991, + "api_prompt_tps": 2293.3, + "api_decode_tps": 86.9, + "engine_prompt_tps": 2324.6, + "engine_decode_tps": 83.1, + "log_lines": [ + "strata serve: prompt 28313 tokens = 0 reused + 28313 read in 12180 ms (2324.6 tok/s), 57 generated in 686 ms (83.1 tok/s), drafts accepted 39 of 41, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.7% (28717 hits / 28800 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 4608, + "expert_cache_mib": 8437, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 9557, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716909.0337873, + "duration_s": 12.9, + "finish": "stop", + "prompt_tokens": 28313, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 12179.9, + "decode_ms": 685.7, + "decode_tok_s": 83.1, + "hit_rate": 0.997 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790716889.8200681, + "requests": 1, + "prompt_tokens": 28313, + "reused": 0, + "output_tokens": 57, + "prompt_ms": 12179.9, + "decode_ms": 685.7 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 0, + "mem_used": 15823994880, + "mem_total": 25769803776, + "temp": 44, + "power": 161.267 + }, + { + "index": 1, + "util": 90, + "mem_used": 24208408576, + "mem_total": 25769803776, + "temp": 51, + "power": 278.413 + } + ], + "gpu_util": 45.0, + "gpu_mem_used": 40032403456, + "gpu_mem_total": 51539607552, + "gpu_temp": 51, + "gpu_power": 439.68, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5.33984375, + "gpu_pcie_tx_mb": 18.5009765625, + "cpu": 16.1, + "ram_used": 44574941184, + "ram_total": 177175990272, + "disk_read_mb": 0.9737281407762519, + "disk_write_mb": 0.11497896865254635, + "tok_s": 36.0, + "tok_s_mean": 64.01736582189179 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 41.5, + 68.0, + 50.0, + 73.0, + 87.5, + 41.5, + 47.0, + 50.0, + 78.0, + 50.5, + 45.0 + ], + "gpu_mem_used": [ + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 40032403456 + ], + "gpu_temp": [ + 45, + 44, + 44, + 44, + 44, + 44, + 45, + 44, + 44, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 42, + 41, + 41, + 47, + 50, + 51, + 51, + 51, + 52, + 51, + 52, + 51, + 52, + 51 + ], + "gpu_power": [ + 255.0, + 240.14, + 239.41, + 239.38, + 239.55, + 239.75, + 239.74, + 239.65, + 239.56, + 239.63, + 239.71, + 239.58, + 239.49, + 239.62, + 239.83, + 239.9, + 200.58, + 138.26, + 69.98, + 230.69, + 516.11, + 485.77, + 500.33, + 518.82, + 491.98, + 467.22, + 490.75, + 506.65, + 510.68, + 439.68 + ], + "gpu_pcie_rx_mb": [ + 0.71, + 0.62, + 0.67, + 0.67, + 0.67, + 0.57, + 0.71, + 0.62, + 0.62, + 0.57, + 0.67, + 0.62, + 0.71, + 0.67, + 0.67, + 0.62, + 0.76, + 0.86, + 0.71, + 1243.59, + 45.3, + 2454.38, + 77.06, + 3382.78, + 1099.87, + 47.06, + 2677.87, + 79.25, + 1143.26, + 5.34 + ], + "cpu": [ + 0.0, + 1.0, + 2.8, + 3.4, + 1.0, + 1.6, + 1.6, + 1.0, + 1.4, + 0.7, + 3.6, + 8.3, + 1.0, + 8.2, + 5.7, + 2.6, + 3.4, + 1.4, + 10.1, + 12.9, + 8.2, + 10.3, + 10.7, + 11.6, + 27.0, + 14.9, + 11.2, + 18.3, + 15.0, + 16.1 + ], + "ram_used": [ + 43962929152, + 43965493248, + 43981484032, + 43968327680, + 43968602112, + 43968954368, + 43964538880, + 43964022784, + 43964801024, + 43964657664, + 43961843712, + 43958075392, + 43958878208, + 43967004672, + 43967807488, + 43951247360, + 43945017344, + 43945320448, + 43971616768, + 44103409664, + 44112924672, + 44112818176, + 43979321344, + 43978510336, + 44145692672, + 44276580352, + 44275351552, + 44327723008, + 44296556544, + 44574941184 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 64.21, + 105.78, + 24.45, + 89.11, + 67.32, + 92.34, + 145.4, + 79.43, + 98.92, + 75.23, + 0.0, + 0.97 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 36.0 + ] + }, + "time": 1790716922.4098496 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-1.json new file mode 100644 index 0000000..063ae12 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-1.json @@ -0,0 +1,270 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "69d919ce1297", + "corpus_repeated": false, + "time": "2026-09-29T21:32:53", + "prompt_tokens": 28316, + "completion_tokens": 57, + "ttft_s": 10.575, + "e2e_s": 11.256, + "api_prompt_tps": 2677.7, + "api_decode_tps": 82.2, + "engine_prompt_tps": 2718.9, + "engine_decode_tps": 79.8, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 10414 ms (2718.9 tok/s), 57 generated in 715 ms (79.8 tok/s), drafts accepted 37 of 48, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34080 hits / 34080 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 5632, + "expert_cache_mib": 10325, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 7669, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717573.1737459, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10414.4, + "decode_ms": 714.5, + "decode_tok_s": 79.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717571.262619, + "requests": 1, + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "prompt_ms": 10414.4, + "decode_ms": 714.5 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 34, + "mem_used": 17822580736, + "mem_total": 25769803776, + "temp": 49, + "power": 184.581 + }, + { + "index": 1, + "util": 54, + "mem_used": 22828482560, + "mem_total": 25769803776, + "temp": 52, + "power": 232.993 + } + ], + "gpu_util": 44.0, + "gpu_mem_used": 40651063296, + "gpu_mem_total": 51539607552, + "gpu_temp": 52, + "gpu_power": 417.57399999999996, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.953125, + "cpu": 6.2, + "ram_used": 44281556992, + "ram_total": 177175990272, + "disk_read_mb": 3.421090719626586, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 73.5, + 58.5, + 96.0, + 57.5, + 95.5, + 47.5, + 93.0, + 58.5, + 50.0, + 44.0 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40651063296 + ], + "gpu_temp": [ + 48, + 47, + 47, + 50, + 53, + 53, + 54, + 53, + 54, + 54, + 54, + 54, + 52 + ], + "gpu_power": [ + 256.98, + 244.54, + 244.03, + 340.49, + 532.78, + 528.1, + 525.31, + 536.01, + 504.78, + 526.85, + 529.86, + 484.8, + 417.57 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.67, + 78.72, + 82.54, + 76.1, + 85.97, + 55.17, + 62.23, + 87.12, + 83.54, + 85.83, + 0.67 + ], + "cpu": [ + 0.0, + 1.2, + 5.4, + 10.7, + 10.0, + 9.8, + 14.0, + 18.3, + 17.8, + 18.6, + 9.0, + 5.8, + 6.2 + ], + "ram_used": [ + 43564908544, + 43556737024, + 43564126208, + 43739512832, + 43734302720, + 43734560768, + 43735560192, + 43898122240, + 44013469696, + 43991674880, + 43978436608, + 43974189056, + 44281556992 + ], + "disk_read_mb": [ + null, + 0.0, + 73.94, + 96.25, + 39.8, + 73.77, + 144.08, + 110.85, + 127.27, + 131.68, + 42.81, + 0.0, + 3.42 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717584.813652 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-2.json new file mode 100644 index 0000000..44d74e8 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-2.json @@ -0,0 +1,383 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "8506420b91e1", + "corpus_repeated": false, + "time": "2026-09-29T21:33:04", + "prompt_tokens": 31633, + "completion_tokens": 45, + "ttft_s": 10.85, + "e2e_s": 11.271, + "api_prompt_tps": 2915.4, + "api_decode_tps": 104.6, + "engine_prompt_tps": 2962.7, + "engine_decode_tps": 103.3, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 10677 ms (2962.7 tok/s), 45 generated in 436 ms (103.3 tok/s), drafts accepted 32 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24960 hits / 24960 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what the last file does.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 5632, + "expert_cache_mib": 10325, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 7669, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717584.9637764, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10677.2, + "decode_ms": 435.6, + "decode_tok_s": 103.3, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717573.1737459, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10414.4, + "decode_ms": 714.5, + "decode_tok_s": 79.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717571.262619, + "requests": 2, + "prompt_tokens": 59949, + "reused": 0, + "output_tokens": 102, + "prompt_ms": 21091.6, + "decode_ms": 1150.1 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 37, + "mem_used": 17822580736, + "mem_total": 25769803776, + "temp": 49, + "power": 187.064 + }, + { + "index": 1, + "util": 60, + "mem_used": 22828482560, + "mem_total": 25769803776, + "temp": 53, + "power": 243.674 + } + ], + "gpu_util": 48.5, + "gpu_mem_used": 40651063296, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 430.738, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.6181640625, + "gpu_pcie_tx_mb": 1.0, + "cpu": 6.1, + "ram_used": 44308209664, + "ram_total": 177175990272, + "disk_read_mb": 0.7959400039611647, + "disk_write_mb": 0.24130307812397303, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 73.5, + 58.5, + 96.0, + 57.5, + 95.5, + 47.5, + 93.0, + 58.5, + 50.0, + 44.0, + 18.0, + 52.0, + 95.5, + 50.0, + 97.0, + 24.5, + 95.5, + 82.0, + 96.5, + 50.0, + 48.5 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296 + ], + "gpu_temp": [ + 48, + 47, + 47, + 50, + 53, + 53, + 54, + 53, + 54, + 54, + 54, + 54, + 52, + 49, + 54, + 54, + 54, + 54, + 52, + 54, + 54, + 54, + 54, + 53 + ], + "gpu_power": [ + 256.98, + 244.54, + 244.03, + 340.49, + 532.78, + 528.1, + 525.31, + 536.01, + 504.78, + 526.85, + 529.86, + 484.8, + 417.57, + 353.2, + 539.11, + 526.73, + 525.83, + 531.55, + 507.76, + 523.24, + 527.24, + 526.07, + 501.32, + 430.74 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.67, + 78.72, + 82.54, + 76.1, + 85.97, + 55.17, + 62.23, + 87.12, + 83.54, + 85.83, + 0.67, + 1765.25, + 83.88, + 85.4, + 85.07, + 88.59, + 82.35, + 78.3, + 85.16, + 61.94, + 46.3, + 0.62 + ], + "cpu": [ + 0.0, + 1.2, + 5.4, + 10.7, + 10.0, + 9.8, + 14.0, + 18.3, + 17.8, + 18.6, + 9.0, + 5.8, + 6.2, + 4.4, + 6.6, + 6.4, + 5.8, + 6.1, + 7.4, + 5.9, + 6.8, + 19.8, + 14.2, + 6.1 + ], + "ram_used": [ + 43564908544, + 43556737024, + 43564126208, + 43739512832, + 43734302720, + 43734560768, + 43735560192, + 43898122240, + 44013469696, + 43991674880, + 43978436608, + 43974189056, + 44281556992, + 44278607872, + 44263776256, + 44251099136, + 44242841600, + 44235354112, + 44232339456, + 44218642432, + 44210057216, + 44216344576, + 44288196608, + 44308209664 + ], + "disk_read_mb": [ + null, + 0.0, + 73.94, + 96.25, + 39.8, + 73.77, + 144.08, + 110.85, + 127.27, + 131.68, + 42.81, + 0.0, + 3.42, + 0.48, + 0.01, + 0.04, + 0.06, + 0.02, + 0.02, + 0.02, + 12.53, + 104.78, + 0.0, + 0.8 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717596.5877995 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-3.json new file mode 100644 index 0000000..905e9d9 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-3.json @@ -0,0 +1,496 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "831d87a1dacc", + "corpus_repeated": false, + "time": "2026-09-29T21:33:16", + "prompt_tokens": 31601, + "completion_tokens": 60, + "ttft_s": 10.877, + "e2e_s": 11.43, + "api_prompt_tps": 2905.4, + "api_decode_tps": 106.7, + "engine_prompt_tps": 2951.6, + "engine_decode_tps": 105.7, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 10706 ms (2951.6 tok/s), 60 generated in 568 ms (105.7 tok/s), drafts accepted 41 of 46, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (31680 hits / 31680 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file does.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 5632, + "expert_cache_mib": 10325, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 7669, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717596.735188, + "duration_s": 11.3, + "finish": "stop", + "prompt_tokens": 31601, + "reused": 0, + "output_tokens": 60, + "engine_generated": 60, + "prompt_ms": 10706.3, + "decode_ms": 567.6, + "decode_tok_s": 105.7, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717584.9637764, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10677.2, + "decode_ms": 435.6, + "decode_tok_s": 103.3, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717573.1737459, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10414.4, + "decode_ms": 714.5, + "decode_tok_s": 79.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717571.262619, + "requests": 3, + "prompt_tokens": 91550, + "reused": 0, + "output_tokens": 162, + "prompt_ms": 31797.899999999998, + "decode_ms": 1717.6999999999998 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 25, + "mem_used": 17822580736, + "mem_total": 25769803776, + "temp": 50, + "power": 201.214 + }, + { + "index": 1, + "util": 61, + "mem_used": 22828482560, + "mem_total": 25769803776, + "temp": 53, + "power": 238.993 + } + ], + "gpu_util": 43.0, + "gpu_mem_used": 40651063296, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 440.207, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 4.4, + "ram_used": 44291919872, + "ram_total": 177175990272, + "disk_read_mb": 0.7281688058408962, + "disk_write_mb": 0.01802398034259644, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 73.5, + 58.5, + 96.0, + 57.5, + 95.5, + 47.5, + 93.0, + 58.5, + 50.0, + 44.0, + 18.0, + 52.0, + 95.5, + 50.0, + 97.0, + 24.5, + 95.5, + 82.0, + 96.5, + 50.0, + 48.5, + 49.5, + 96.0, + 48.0, + 96.0, + 47.5, + 94.5, + 61.0, + 97.5, + 47.5, + 49.5, + 43.0 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296 + ], + "gpu_temp": [ + 48, + 47, + 47, + 50, + 53, + 53, + 54, + 53, + 54, + 54, + 54, + 54, + 52, + 49, + 54, + 54, + 54, + 54, + 52, + 54, + 54, + 54, + 54, + 53, + 50, + 54, + 54, + 54, + 55, + 54, + 54, + 54, + 55, + 55, + 53 + ], + "gpu_power": [ + 256.98, + 244.54, + 244.03, + 340.49, + 532.78, + 528.1, + 525.31, + 536.01, + 504.78, + 526.85, + 529.86, + 484.8, + 417.57, + 353.2, + 539.11, + 526.73, + 525.83, + 531.55, + 507.76, + 523.24, + 527.24, + 526.07, + 501.32, + 430.74, + 359.38, + 510.67, + 527.45, + 526.85, + 532.56, + 501.47, + 534.58, + 526.16, + 522.92, + 475.95, + 440.21 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.67, + 78.72, + 82.54, + 76.1, + 85.97, + 55.17, + 62.23, + 87.12, + 83.54, + 85.83, + 0.67, + 1765.25, + 83.88, + 85.4, + 85.07, + 88.59, + 82.35, + 78.3, + 85.16, + 61.94, + 46.3, + 0.62, + 87.45, + 41.53, + 89.07, + 84.21, + 76.25, + 52.17, + 78.29, + 83.59, + 51.45, + 47.92, + 0.67 + ], + "cpu": [ + 0.0, + 1.2, + 5.4, + 10.7, + 10.0, + 9.8, + 14.0, + 18.3, + 17.8, + 18.6, + 9.0, + 5.8, + 6.2, + 4.4, + 6.6, + 6.4, + 5.8, + 6.1, + 7.4, + 5.9, + 6.8, + 19.8, + 14.2, + 6.1, + 7.3, + 6.6, + 6.3, + 5.7, + 6.0, + 6.2, + 6.3, + 6.1, + 7.3, + 6.4, + 4.4 + ], + "ram_used": [ + 43564908544, + 43556737024, + 43564126208, + 43739512832, + 43734302720, + 43734560768, + 43735560192, + 43898122240, + 44013469696, + 43991674880, + 43978436608, + 43974189056, + 44281556992, + 44278607872, + 44263776256, + 44251099136, + 44242841600, + 44235354112, + 44232339456, + 44218642432, + 44210057216, + 44216344576, + 44288196608, + 44308209664, + 44011671552, + 43989819392, + 43978940416, + 43970682880, + 43962933248, + 44045533184, + 44039798784, + 44039798784, + 44047568896, + 44044705792, + 44291919872 + ], + "disk_read_mb": [ + null, + 0.0, + 73.94, + 96.25, + 39.8, + 73.77, + 144.08, + 110.85, + 127.27, + 131.68, + 42.81, + 0.0, + 3.42, + 0.48, + 0.01, + 0.04, + 0.06, + 0.02, + 0.02, + 0.02, + 12.53, + 104.78, + 0.0, + 0.8, + 0.61, + 0.05, + 0.03, + 0.09, + 0.08, + 0.04, + 0.05, + 0.04, + 0.15, + 0.0, + 0.73 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717608.5200934 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-1.json new file mode 100644 index 0000000..e087261 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-1.json @@ -0,0 +1,279 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "87af67edfd2d", + "corpus_repeated": false, + "time": "2026-09-29T21:34:02", + "prompt_tokens": 28314, + "completion_tokens": 256, + "ttft_s": 10.029, + "e2e_s": 12.977, + "api_prompt_tps": 2823.1, + "api_decode_tps": 86.5, + "engine_prompt_tps": 2871.1, + "engine_decode_tps": 85.9, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 9862 ms (2871.1 tok/s), 256 generated in 2981 ms (85.9 tok/s), drafts accepted 143 of 193, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (147360 hits / 147360 lookups)" + ], + "answer_head": "Looking at the last file above, `docs/AMD_HIP_PERFORMANCE.md`, it documents the performance evidence and correctness limits for the experimental AMD HIP backend targeting gfx1100 (RX 7900 XTX). It records:\n\n- The exact build/runtime configuration used for the benchmark (env vars, CLI flags, model pa", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6144, + "expert_cache_mib": 11337, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 6657, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717642.434618, + "duration_s": 12.9, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 9861.8, + "decode_ms": 2981.5, + "decode_tok_s": 85.9, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717640.7776525, + "requests": 1, + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "prompt_ms": 9861.8, + "decode_ms": 2981.5 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 43, + "mem_used": 18898419712, + "mem_total": 25769803776, + "temp": 50, + "power": 244.874 + }, + { + "index": 1, + "util": 57, + "mem_used": 21758935040, + "mem_total": 25769803776, + "temp": 54, + "power": 254.71 + } + ], + "gpu_util": 50.0, + "gpu_mem_used": 40657354752, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 499.584, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5.38671875, + "gpu_pcie_tx_mb": 87.7373046875, + "cpu": 11.7, + "ram_used": 44619116544, + "ram_total": 177175990272, + "disk_read_mb": 4.515214018548113, + "disk_write_mb": 0.17657261525048487, + "tok_s": 107.09643367230112, + "tok_s_mean": 83.26979350665239 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 1.0, + 93.0, + 94.0, + 64.0, + 94.5, + 88.5, + 95.5, + 92.5, + 48.5, + 32.0, + 48.0, + 50.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40476999680, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40657354752, + 40657354752, + 40657354752 + ], + "gpu_temp": [ + 49, + 49, + 49, + 53, + 54, + 54, + 55, + 54, + 55, + 55, + 55, + 52, + 54, + 54 + ], + "gpu_power": [ + 259.59, + 247.18, + 245.88, + 414.53, + 546.71, + 547.76, + 546.95, + 533.57, + 531.41, + 545.46, + 539.14, + 402.04, + 486.67, + 499.58 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 247.86, + 81.11, + 78.2, + 80.92, + 83.88, + 57.6, + 82.87, + 79.92, + 40.29, + 5.39, + 9.77, + 5.39 + ], + "cpu": [ + 0.0, + 1.9, + 9.1, + 8.8, + 9.5, + 10.7, + 13.9, + 10.5, + 13.9, + 11.8, + 6.0, + 6.3, + 12.4, + 11.7 + ], + "ram_used": [ + 43887411200, + 43859918848, + 43956232192, + 44034678784, + 44030210048, + 44028076032, + 44015280128, + 44252610560, + 44247789568, + 44243210240, + 44230340608, + 44558966784, + 44619108352, + 44619116544 + ], + "disk_read_mb": [ + null, + 0.0, + 126.09, + 44.05, + 80.0, + 93.94, + 138.6, + 104.01, + 156.43, + 97.38, + 0.0, + 1.76, + 4.66, + 4.52 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.74, + 81.4, + 107.1 + ] + }, + "time": 1790717655.7892108 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-2.json new file mode 100644 index 0000000..290da92 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-2.json @@ -0,0 +1,392 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "b38394f620b3", + "corpus_repeated": false, + "time": "2026-09-29T21:34:15", + "prompt_tokens": 31635, + "completion_tokens": 45, + "ttft_s": 10.269, + "e2e_s": 10.686, + "api_prompt_tps": 3080.5, + "api_decode_tps": 105.5, + "engine_prompt_tps": 3130.4, + "engine_decode_tps": 104.2, + "log_lines": [ + "strata serve: prompt 31635 tokens = 0 reused + 31635 read in 10106 ms (3130.4 tok/s), 45 generated in 432 ms (104.2 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24480 hits / 24480 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6144, + "expert_cache_mib": 11337, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 6657, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717655.9301767, + "duration_s": 10.5, + "finish": "stop", + "prompt_tokens": 31635, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10105.9, + "decode_ms": 431.8, + "decode_tok_s": 104.2, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717642.434618, + "duration_s": 12.9, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 9861.8, + "decode_ms": 2981.5, + "decode_tok_s": 85.9, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717640.7776525, + "requests": 2, + "prompt_tokens": 59949, + "reused": 0, + "output_tokens": 301, + "prompt_ms": 19967.699999999997, + "decode_ms": 3413.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 20, + "mem_used": 18898419712, + "mem_total": 25769803776, + "temp": 50, + "power": 191.174 + }, + { + "index": 1, + "util": 53, + "mem_used": 21758935040, + "mem_total": 25769803776, + "temp": 54, + "power": 238.032 + } + ], + "gpu_util": 36.5, + "gpu_mem_used": 40657354752, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 429.206, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.6181640625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 5.3, + "ram_used": 44575621120, + "ram_total": 177175990272, + "disk_read_mb": 2.4688909410966033, + "disk_write_mb": 0.23427432287777988, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 1.0, + 93.0, + 94.0, + 64.0, + 94.5, + 88.5, + 95.5, + 92.5, + 48.5, + 32.0, + 48.0, + 50.0, + 0.0, + 84.5, + 96.0, + 95.5, + 79.0, + 97.5, + 97.0, + 95.5, + 96.0, + 50.0, + 36.5 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40476999680, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752 + ], + "gpu_temp": [ + 49, + 49, + 49, + 53, + 54, + 54, + 55, + 54, + 55, + 55, + 55, + 52, + 54, + 54, + 50, + 54, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 54 + ], + "gpu_power": [ + 259.59, + 247.18, + 245.88, + 414.53, + 546.71, + 547.76, + 546.95, + 533.57, + 531.41, + 545.46, + 539.14, + 402.04, + 486.67, + 499.58, + 409.59, + 480.21, + 551.08, + 548.0, + 547.82, + 539.97, + 537.72, + 548.44, + 548.33, + 513.55, + 429.21 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 247.86, + 81.11, + 78.2, + 80.92, + 83.88, + 57.6, + 82.87, + 79.92, + 40.29, + 5.39, + 9.77, + 5.39, + 45.78, + 64.8, + 1284.55, + 129.94, + 83.06, + 82.63, + 84.78, + 73.15, + 82.44, + 0.57, + 0.62 + ], + "cpu": [ + 0.0, + 1.9, + 9.1, + 8.8, + 9.5, + 10.7, + 13.9, + 10.5, + 13.9, + 11.8, + 6.0, + 6.3, + 12.4, + 11.7, + 6.7, + 8.3, + 6.5, + 7.2, + 6.1, + 6.0, + 6.1, + 6.5, + 11.2, + 8.0, + 5.3 + ], + "ram_used": [ + 43887411200, + 43859918848, + 43956232192, + 44034678784, + 44030210048, + 44028076032, + 44015280128, + 44252610560, + 44247789568, + 44243210240, + 44230340608, + 44558966784, + 44619108352, + 44619116544, + 44154675200, + 44152926208, + 44151242752, + 44149854208, + 44145594368, + 44375150592, + 44366180352, + 44365656064, + 44362940416, + 44400578560, + 44575621120 + ], + "disk_read_mb": [ + null, + 0.0, + 126.09, + 44.05, + 80.0, + 93.94, + 138.6, + 104.01, + 156.43, + 97.38, + 0.0, + 1.76, + 4.66, + 4.52, + 0.63, + 0.02, + 0.04, + 0.03, + 0.05, + 0.03, + 0.02, + 13.87, + 103.6, + 0.0, + 2.47 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.74, + 81.4, + 107.1, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717666.9788535 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-3.json new file mode 100644 index 0000000..7ef8005 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-3.json @@ -0,0 +1,496 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "3bee1c1e482a", + "corpus_repeated": false, + "time": "2026-09-29T21:34:26", + "prompt_tokens": 31602, + "completion_tokens": 60, + "ttft_s": 10.281, + "e2e_s": 10.865, + "api_prompt_tps": 3073.8, + "api_decode_tps": 101.0, + "engine_prompt_tps": 3123.2, + "engine_decode_tps": 100.2, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10118 ms (3123.2 tok/s), 60 generated in 599 ms (100.2 tok/s), drafts accepted 40 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34560 hits / 34560 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file does.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6144, + "expert_cache_mib": 11337, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 6657, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717667.1193056, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 60, + "engine_generated": 60, + "prompt_ms": 10118.5, + "decode_ms": 599.0, + "decode_tok_s": 100.2, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717655.9301767, + "duration_s": 10.5, + "finish": "stop", + "prompt_tokens": 31635, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10105.9, + "decode_ms": 431.8, + "decode_tok_s": 104.2, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717642.434618, + "duration_s": 12.9, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 9861.8, + "decode_ms": 2981.5, + "decode_tok_s": 85.9, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717640.7776525, + "requests": 3, + "prompt_tokens": 91551, + "reused": 0, + "output_tokens": 361, + "prompt_ms": 30086.199999999997, + "decode_ms": 4012.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 43, + "mem_used": 18898419712, + "mem_total": 25769803776, + "temp": 51, + "power": 178.691 + }, + { + "index": 1, + "util": 51, + "mem_used": 21758935040, + "mem_total": 25769803776, + "temp": 54, + "power": 244.501 + } + ], + "gpu_util": 47.0, + "gpu_mem_used": 40657354752, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 423.192, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5.1962890625, + "gpu_pcie_tx_mb": 103.138671875, + "cpu": 6.6, + "ram_used": 44596383744, + "ram_total": 177175990272, + "disk_read_mb": 1.1207609014346964, + "disk_write_mb": 0.0288298624163266, + "tok_s": 110.47676922161895, + "tok_s_mean": 99.0096070780873 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 1.0, + 93.0, + 94.0, + 64.0, + 94.5, + 88.5, + 95.5, + 92.5, + 48.5, + 32.0, + 48.0, + 50.0, + 0.0, + 84.5, + 96.0, + 95.5, + 79.0, + 97.5, + 97.0, + 95.5, + 96.0, + 50.0, + 36.5, + 49.5, + 96.5, + 61.0, + 94.5, + 91.0, + 97.0, + 95.5, + 98.5, + 47.5, + 47.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40476999680, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752 + ], + "gpu_temp": [ + 49, + 49, + 49, + 53, + 54, + 54, + 55, + 54, + 55, + 55, + 55, + 52, + 54, + 54, + 50, + 54, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 54, + 52, + 55, + 55, + 55, + 55, + 56, + 56, + 55, + 56, + 54 + ], + "gpu_power": [ + 259.59, + 247.18, + 245.88, + 414.53, + 546.71, + 547.76, + 546.95, + 533.57, + 531.41, + 545.46, + 539.14, + 402.04, + 486.67, + 499.58, + 409.59, + 480.21, + 551.08, + 548.0, + 547.82, + 539.97, + 537.72, + 548.44, + 548.33, + 513.55, + 429.21, + 354.61, + 553.75, + 546.57, + 547.59, + 532.21, + 535.5, + 547.28, + 548.49, + 534.02, + 423.19 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 247.86, + 81.11, + 78.2, + 80.92, + 83.88, + 57.6, + 82.87, + 79.92, + 40.29, + 5.39, + 9.77, + 5.39, + 45.78, + 64.8, + 1284.55, + 129.94, + 83.06, + 82.63, + 84.78, + 73.15, + 82.44, + 0.57, + 0.62, + 81.82, + 83.45, + 75.34, + 84.16, + 82.11, + 81.49, + 70.95, + 73.91, + 52.55, + 5.2 + ], + "cpu": [ + 0.0, + 1.9, + 9.1, + 8.8, + 9.5, + 10.7, + 13.9, + 10.5, + 13.9, + 11.8, + 6.0, + 6.3, + 12.4, + 11.7, + 6.7, + 8.3, + 6.5, + 7.2, + 6.1, + 6.0, + 6.1, + 6.5, + 11.2, + 8.0, + 5.3, + 6.7, + 12.7, + 10.0, + 5.9, + 6.4, + 6.0, + 7.1, + 5.7, + 6.8, + 6.6 + ], + "ram_used": [ + 43887411200, + 43859918848, + 43956232192, + 44034678784, + 44030210048, + 44028076032, + 44015280128, + 44252610560, + 44247789568, + 44243210240, + 44230340608, + 44558966784, + 44619108352, + 44619116544, + 44154675200, + 44152926208, + 44151242752, + 44149854208, + 44145594368, + 44375150592, + 44366180352, + 44365656064, + 44362940416, + 44400578560, + 44575621120, + 44112637952, + 44134821888, + 44114948096, + 44112486400, + 44240445440, + 44343197696, + 44341800960, + 44344549376, + 44344029184, + 44596383744 + ], + "disk_read_mb": [ + null, + 0.0, + 126.09, + 44.05, + 80.0, + 93.94, + 138.6, + 104.01, + 156.43, + 97.38, + 0.0, + 1.76, + 4.66, + 4.52, + 0.63, + 0.02, + 0.04, + 0.03, + 0.05, + 0.03, + 0.02, + 13.87, + 103.6, + 0.0, + 2.47, + 0.63, + 0.05, + 0.08, + 0.08, + 0.04, + 0.07, + 0.04, + 0.17, + 0.0, + 1.12 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.74, + 81.4, + 107.1, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 110.48 + ] + }, + "time": 1790717678.3471994 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-1.json new file mode 100644 index 0000000..2e492f8 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-1.json @@ -0,0 +1,261 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "5ca39dba7489", + "corpus_repeated": false, + "time": "2026-09-29T21:35:22", + "prompt_tokens": 28314, + "completion_tokens": 48, + "ttft_s": 9.79, + "e2e_s": 10.297, + "api_prompt_tps": 2892.2, + "api_decode_tps": 92.7, + "engine_prompt_tps": 2940.2, + "engine_decode_tps": 88.8, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 9630 ms (2940.2 tok/s), 48 generated in 540 ms (88.8 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25920 hits / 25920 lookups)" + ], + "answer_head": "I'll first look at the repository structure to understand what files exist and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6656, + "expert_cache_mib": 12387, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 5607, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717722.129571, + "duration_s": 10.2, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 9630.1, + "decode_ms": 540.5, + "decode_tok_s": 88.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717720.412441, + "requests": 1, + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "prompt_ms": 9630.1, + "decode_ms": 540.5 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 47, + "mem_used": 19980550144, + "mem_total": 25769803776, + "temp": 51, + "power": 179.665 + }, + { + "index": 1, + "util": 28, + "mem_used": 20641153024, + "mem_total": 25769803776, + "temp": 53, + "power": 236.004 + } + ], + "gpu_util": 37.5, + "gpu_mem_used": 40621703168, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 415.669, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 6.0, + "ram_used": 44539072512, + "ram_total": 177175990272, + "disk_read_mb": 2.97776661958663, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.5, + 71.0, + 95.5, + 96.0, + 91.5, + 66.5, + 95.5, + 90.5, + 84.5, + 37.5 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40472805376, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40621703168 + ], + "gpu_temp": [ + 50, + 50, + 50, + 52, + 55, + 55, + 56, + 56, + 56, + 55, + 56, + 53 + ], + "gpu_power": [ + 261.03, + 248.02, + 247.5, + 351.95, + 548.48, + 553.77, + 555.05, + 536.77, + 531.38, + 552.37, + 551.57, + 415.67 + ], + "gpu_pcie_rx_mb": [ + 0.76, + 0.62, + 224.64, + 86.02, + 83.16, + 75.62, + 86.69, + 102.66, + 65.66, + 83.97, + 38.86, + 0.67 + ], + "cpu": [ + 0.0, + 1.1, + 8.1, + 9.1, + 9.3, + 12.2, + 12.6, + 12.6, + 23.5, + 14.7, + 5.9, + 6.0 + ], + "ram_used": [ + 43871281152, + 43867545600, + 43958726656, + 44040531968, + 44041007104, + 44033200128, + 44032602112, + 44244361216, + 44250234880, + 44236812288, + 44233678848, + 44539072512 + ], + "disk_read_mb": [ + null, + 0.0, + 122.8, + 47.19, + 79.99, + 100.77, + 127.09, + 108.72, + 156.54, + 97.45, + 0.0, + 2.98 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717732.8116624 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-2.json new file mode 100644 index 0000000..85ea212 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-2.json @@ -0,0 +1,365 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "14c7210ce0e9", + "corpus_repeated": false, + "time": "2026-09-29T21:35:32", + "prompt_tokens": 31635, + "completion_tokens": 45, + "ttft_s": 10.029, + "e2e_s": 10.496, + "api_prompt_tps": 3154.3, + "api_decode_tps": 94.3, + "engine_prompt_tps": 3205.2, + "engine_decode_tps": 93.5, + "log_lines": [ + "strata serve: prompt 31635 tokens = 0 reused + 31635 read in 9870 ms (3205.2 tok/s), 45 generated in 481 ms (93.5 tok/s), drafts accepted 31 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25440 hits / 25440 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what the last file does.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6656, + "expert_cache_mib": 12387, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 5607, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717732.947479, + "duration_s": 10.4, + "finish": "stop", + "prompt_tokens": 31635, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9870.0, + "decode_ms": 481.3, + "decode_tok_s": 93.5, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717722.129571, + "duration_s": 10.2, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 9630.1, + "decode_ms": 540.5, + "decode_tok_s": 88.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717720.412441, + "requests": 2, + "prompt_tokens": 59949, + "reused": 0, + "output_tokens": 93, + "prompt_ms": 19500.1, + "decode_ms": 1021.8 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 51, + "mem_used": 19991035904, + "mem_total": 25769803776, + "temp": 51, + "power": 190.866 + }, + { + "index": 1, + "util": 56, + "mem_used": 20653735936, + "mem_total": 25769803776, + "temp": 55, + "power": 249.813 + } + ], + "gpu_util": 53.5, + "gpu_mem_used": 40644771840, + "gpu_mem_total": 51539607552, + "gpu_temp": 55, + "gpu_power": 440.679, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 16.44921875, + "gpu_pcie_tx_mb": 82.0625, + "cpu": 6.0, + "ram_used": 44553875456, + "ram_total": 177175990272, + "disk_read_mb": 0.6053434938228842, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.5, + 71.0, + 95.5, + 96.0, + 91.5, + 66.5, + 95.5, + 90.5, + 84.5, + 37.5, + 1.5, + 97.0, + 96.0, + 81.0, + 86.5, + 95.5, + 95.0, + 96.5, + 95.0, + 53.5 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40472805376, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40644771840 + ], + "gpu_temp": [ + 50, + 50, + 50, + 52, + 55, + 55, + 56, + 56, + 56, + 55, + 56, + 53, + 51, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 55 + ], + "gpu_power": [ + 261.03, + 248.02, + 247.5, + 351.95, + 548.48, + 553.77, + 555.05, + 536.77, + 531.38, + 552.37, + 551.57, + 415.67, + 326.37, + 532.86, + 555.24, + 552.15, + 555.12, + 507.8, + 554.85, + 554.0, + 554.13, + 440.68 + ], + "gpu_pcie_rx_mb": [ + 0.76, + 0.62, + 224.64, + 86.02, + 83.16, + 75.62, + 86.69, + 102.66, + 65.66, + 83.97, + 38.86, + 0.67, + 3698.35, + 132.46, + 131.89, + 82.06, + 85.92, + 83.02, + 1279.88, + 50.4, + 86.21, + 16.45 + ], + "cpu": [ + 0.0, + 1.1, + 8.1, + 9.1, + 9.3, + 12.2, + 12.6, + 12.6, + 23.5, + 14.7, + 5.9, + 6.0, + 4.5, + 6.1, + 6.0, + 6.4, + 6.7, + 5.9, + 6.7, + 9.9, + 7.4, + 6.0 + ], + "ram_used": [ + 43871281152, + 43867545600, + 43958726656, + 44040531968, + 44041007104, + 44033200128, + 44032602112, + 44244361216, + 44250234880, + 44236812288, + 44233678848, + 44539072512, + 44064968704, + 44058497024, + 44058497024, + 44058501120, + 44175929344, + 44294356992, + 44294352896, + 44295569408, + 44291391488, + 44553875456 + ], + "disk_read_mb": [ + null, + 0.0, + 122.8, + 47.19, + 79.99, + 100.77, + 127.09, + 108.72, + 156.54, + 97.45, + 0.0, + 2.98, + 0.47, + 0.01, + 0.04, + 0.06, + 0.03, + 0.03, + 12.57, + 71.85, + 33.12, + 0.61 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717743.8106396 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-3.json new file mode 100644 index 0000000..6030458 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-3.json @@ -0,0 +1,469 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "3f243fdb63ee", + "corpus_repeated": false, + "time": "2026-09-29T21:35:43", + "prompt_tokens": 31601, + "completion_tokens": 60, + "ttft_s": 10.026, + "e2e_s": 10.61, + "api_prompt_tps": 3151.9, + "api_decode_tps": 101.0, + "engine_prompt_tps": 3208.3, + "engine_decode_tps": 100.2, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 9850 ms (3208.3 tok/s), 60 generated in 599 ms (100.2 tok/s), drafts accepted 40 of 50, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34080 hits / 34080 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file is.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6656, + "expert_cache_mib": 12387, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 5607, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717743.964174, + "duration_s": 10.5, + "finish": "stop", + "prompt_tokens": 31601, + "reused": 0, + "output_tokens": 60, + "engine_generated": 60, + "prompt_ms": 9849.9, + "decode_ms": 598.9, + "decode_tok_s": 100.2, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717732.947479, + "duration_s": 10.4, + "finish": "stop", + "prompt_tokens": 31635, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9870.0, + "decode_ms": 481.3, + "decode_tok_s": 93.5, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717722.129571, + "duration_s": 10.2, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 9630.1, + "decode_ms": 540.5, + "decode_tok_s": 88.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717720.412441, + "requests": 3, + "prompt_tokens": 91550, + "reused": 0, + "output_tokens": 153, + "prompt_ms": 29350.0, + "decode_ms": 1620.6999999999998 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 46, + "mem_used": 19991035904, + "mem_total": 25769803776, + "temp": 52, + "power": 189.922 + }, + { + "index": 1, + "util": 52, + "mem_used": 20653735936, + "mem_total": 25769803776, + "temp": 55, + "power": 246.398 + } + ], + "gpu_util": 49.0, + "gpu_mem_used": 40644771840, + "gpu_mem_total": 51539607552, + "gpu_temp": 55, + "gpu_power": 436.32, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 17.8330078125, + "gpu_pcie_tx_mb": 43.1533203125, + "cpu": 6.0, + "ram_used": 44614168576, + "ram_total": 177175990272, + "disk_read_mb": 0.4973320821900814, + "disk_write_mb": 0.05405783502066102, + "tok_s": 99.26679787882165, + "tok_s_mean": 97.997900113756 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.5, + 71.0, + 95.5, + 96.0, + 91.5, + 66.5, + 95.5, + 90.5, + 84.5, + 37.5, + 1.5, + 97.0, + 96.0, + 81.0, + 86.5, + 95.5, + 95.0, + 96.5, + 95.0, + 53.5, + 0.0, + 95.0, + 95.5, + 82.0, + 94.5, + 93.0, + 88.5, + 96.0, + 97.0, + 49.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40472805376, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840 + ], + "gpu_temp": [ + 50, + 50, + 50, + 52, + 55, + 55, + 56, + 56, + 56, + 55, + 56, + 53, + 51, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 55, + 52, + 55, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 55 + ], + "gpu_power": [ + 261.03, + 248.02, + 247.5, + 351.95, + 548.48, + 553.77, + 555.05, + 536.77, + 531.38, + 552.37, + 551.57, + 415.67, + 326.37, + 532.86, + 555.24, + 552.15, + 555.12, + 507.8, + 554.85, + 554.0, + 554.13, + 440.68, + 363.75, + 474.54, + 552.72, + 554.16, + 554.3, + 509.24, + 555.11, + 555.88, + 555.36, + 436.32 + ], + "gpu_pcie_rx_mb": [ + 0.76, + 0.62, + 224.64, + 86.02, + 83.16, + 75.62, + 86.69, + 102.66, + 65.66, + 83.97, + 38.86, + 0.67, + 3698.35, + 132.46, + 131.89, + 82.06, + 85.92, + 83.02, + 1279.88, + 50.4, + 86.21, + 16.45, + 38.96, + 81.63, + 83.25, + 84.4, + 72.53, + 127.22, + 48.4, + 96.51, + 100.71, + 17.83 + ], + "cpu": [ + 0.0, + 1.1, + 8.1, + 9.1, + 9.3, + 12.2, + 12.6, + 12.6, + 23.5, + 14.7, + 5.9, + 6.0, + 4.5, + 6.1, + 6.0, + 6.4, + 6.7, + 5.9, + 6.7, + 9.9, + 7.4, + 6.0, + 11.7, + 10.8, + 6.2, + 11.4, + 7.0, + 6.7, + 5.6, + 5.4, + 6.0, + 6.0 + ], + "ram_used": [ + 43871281152, + 43867545600, + 43958726656, + 44040531968, + 44041007104, + 44033200128, + 44032602112, + 44244361216, + 44250234880, + 44236812288, + 44233678848, + 44539072512, + 44064968704, + 44058497024, + 44058497024, + 44058501120, + 44175929344, + 44294356992, + 44294352896, + 44295569408, + 44291391488, + 44553875456, + 44129808384, + 44180946944, + 44184666112, + 44182659072, + 44296114176, + 44404658176, + 44394999808, + 44386783232, + 44374441984, + 44614168576 + ], + "disk_read_mb": [ + null, + 0.0, + 122.8, + 47.19, + 79.99, + 100.77, + 127.09, + 108.72, + 156.54, + 97.45, + 0.0, + 2.98, + 0.47, + 0.01, + 0.04, + 0.06, + 0.03, + 0.03, + 12.57, + 71.85, + 33.12, + 0.61, + 0.53, + 0.06, + 0.06, + 0.09, + 0.08, + 0.04, + 0.04, + 0.04, + 0.15, + 0.5 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 99.27 + ] + }, + "time": 1790717754.9239163 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-1.json new file mode 100644 index 0000000..65c1407 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-1.json @@ -0,0 +1,261 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "0796a1ce12e4", + "corpus_repeated": false, + "time": "2026-09-29T21:36:29", + "prompt_tokens": 28316, + "completion_tokens": 57, + "ttft_s": 10.285, + "e2e_s": 10.86, + "api_prompt_tps": 2753.1, + "api_decode_tps": 97.4, + "engine_prompt_tps": 2798.5, + "engine_decode_tps": 93.7, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 10118 ms (2798.5 tok/s), 57 generated in 608 ms (93.7 tok/s), drafts accepted 40 of 42, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (28800 hits / 28800 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7168, + "expert_cache_mib": 13437, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 4557, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717789.1846194, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10118.2, + "decode_ms": 608.0, + "decode_tok_s": 93.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717787.625935, + "requests": 1, + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "prompt_ms": 10118.2, + "decode_ms": 608.0 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 41, + "mem_used": 21104623616, + "mem_total": 25769803776, + "temp": 52, + "power": 189.832 + }, + { + "index": 1, + "util": 42, + "mem_used": 19548536832, + "mem_total": 25769803776, + "temp": 54, + "power": 230.563 + } + ], + "gpu_util": 41.5, + "gpu_mem_used": 40653160448, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 420.395, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 17.1650390625, + "gpu_pcie_tx_mb": 53.119140625, + "cpu": 6.1, + "ram_used": 44503613440, + "ram_total": 177175990272, + "disk_read_mb": 1.946188226381293, + "disk_write_mb": 0.0036040522710764685, + "tok_s": 81.42212134334822, + "tok_s_mean": 78.79383849818437 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 46.5, + 96.0, + 72.5, + 93.0, + 90.0, + 95.5, + 93.5, + 97.5, + 41.5 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40495874048, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40653160448 + ], + "gpu_temp": [ + 51, + 50, + 50, + 52, + 55, + 54, + 56, + 54, + 56, + 56, + 57, + 54 + ], + "gpu_power": [ + 261.46, + 249.04, + 248.59, + 342.07, + 531.07, + 533.47, + 545.68, + 511.29, + 533.34, + 534.58, + 541.51, + 420.39 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 182.48, + 55.88, + 87.02, + 80.58, + 57.5, + 78.87, + 83.88, + 1294.42, + 46.78, + 17.17 + ], + "cpu": [ + 0.0, + 6.6, + 18.0, + 11.3, + 10.5, + 9.8, + 11.5, + 13.9, + 11.4, + 12.9, + 7.4, + 6.1 + ], + "ram_used": [ + 43799613440, + 43777974272, + 43950305280, + 43962880000, + 43939622912, + 43930345472, + 43932086272, + 44071780352, + 44183257088, + 44182880256, + 44179062784, + 44503613440 + ], + "disk_read_mb": [ + null, + 0.0, + 129.59, + 40.83, + 79.94, + 84.92, + 115.02, + 136.42, + 117.79, + 106.04, + 29.9, + 1.95 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 81.42 + ] + }, + "time": 1790717800.421838 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-2.json new file mode 100644 index 0000000..bd33217 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-2.json @@ -0,0 +1,374 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "3d5bf2c2aa6f", + "corpus_repeated": false, + "time": "2026-09-29T21:36:40", + "prompt_tokens": 31631, + "completion_tokens": 45, + "ttft_s": 10.58, + "e2e_s": 10.972, + "api_prompt_tps": 2989.7, + "api_decode_tps": 112.3, + "engine_prompt_tps": 3034.9, + "engine_decode_tps": 110.6, + "log_lines": [ + "strata serve: prompt 31631 tokens = 0 reused + 31631 read in 10423 ms (3034.9 tok/s), 45 generated in 407 ms (110.6 tok/s), drafts accepted 33 of 34, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (23040 hits / 23040 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7168, + "expert_cache_mib": 13437, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 4557, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717800.5571585, + "duration_s": 10.8, + "finish": "stop", + "prompt_tokens": 31631, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10422.5, + "decode_ms": 406.8, + "decode_tok_s": 110.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717789.1846194, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10118.2, + "decode_ms": 608.0, + "decode_tok_s": 93.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717787.625935, + "requests": 2, + "prompt_tokens": 59947, + "reused": 0, + "output_tokens": 102, + "prompt_ms": 20540.7, + "decode_ms": 1014.8 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 46, + "mem_used": 21104623616, + "mem_total": 25769803776, + "temp": 51, + "power": 204.027 + }, + { + "index": 1, + "util": 12, + "mem_used": 19548536832, + "mem_total": 25769803776, + "temp": 54, + "power": 226.431 + } + ], + "gpu_util": 29.0, + "gpu_mem_used": 40653160448, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 430.45799999999997, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.6181640625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 4.3, + "ram_used": 44573519872, + "ram_total": 177175990272, + "disk_read_mb": 0.9768799607845553, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 46.5, + 96.0, + 72.5, + 93.0, + 90.0, + 95.5, + 93.5, + 97.5, + 41.5, + 0.0, + 96.0, + 93.0, + 97.5, + 94.5, + 97.0, + 95.0, + 97.0, + 93.5, + 67.0, + 29.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40495874048, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448 + ], + "gpu_temp": [ + 51, + 50, + 50, + 52, + 55, + 54, + 56, + 54, + 56, + 56, + 57, + 54, + 52, + 55, + 54, + 56, + 56, + 56, + 56, + 57, + 57, + 56, + 54 + ], + "gpu_power": [ + 261.46, + 249.04, + 248.59, + 342.07, + 531.07, + 533.47, + 545.68, + 511.29, + 533.34, + 534.58, + 541.51, + 420.39, + 375.37, + 452.84, + 528.99, + 547.53, + 532.29, + 524.3, + 518.92, + 543.34, + 532.25, + 534.03, + 430.46 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 182.48, + 55.88, + 87.02, + 80.58, + 57.5, + 78.87, + 83.88, + 1294.42, + 46.78, + 17.17, + 42.15, + 1288.27, + 41.05, + 75.34, + 70.76, + 44.15, + 79.87, + 61.61, + 75.63, + 42.06, + 0.62 + ], + "cpu": [ + 0.0, + 6.6, + 18.0, + 11.3, + 10.5, + 9.8, + 11.5, + 13.9, + 11.4, + 12.9, + 7.4, + 6.1, + 4.2, + 6.4, + 6.0, + 12.9, + 11.2, + 6.1, + 8.2, + 8.8, + 14.0, + 6.4, + 4.3 + ], + "ram_used": [ + 43799613440, + 43777974272, + 43950305280, + 43962880000, + 43939622912, + 43930345472, + 43932086272, + 44071780352, + 44183257088, + 44182880256, + 44179062784, + 44503613440, + 44015304704, + 44019281920, + 44021350400, + 44034875392, + 44111585280, + 44348657664, + 44344815616, + 44359872512, + 44334280704, + 44327985152, + 44573519872 + ], + "disk_read_mb": [ + null, + 0.0, + 129.59, + 40.83, + 79.94, + 84.92, + 115.02, + 136.42, + 117.79, + 106.04, + 29.9, + 1.95, + 1.72, + 0.02, + 0.02, + 0.05, + 0.06, + 0.01, + 0.03, + 12.6, + 101.64, + 2.94, + 0.98 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 81.42, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717811.896799 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-3.json new file mode 100644 index 0000000..9897615 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-3.json @@ -0,0 +1,487 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "d22ca9d8c7b8", + "corpus_repeated": false, + "time": "2026-09-29T21:36:51", + "prompt_tokens": 31602, + "completion_tokens": 59, + "ttft_s": 10.575, + "e2e_s": 11.17, + "api_prompt_tps": 2988.5, + "api_decode_tps": 97.4, + "engine_prompt_tps": 3037.5, + "engine_decode_tps": 96.6, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10404 ms (3037.5 tok/s), 59 generated in 611 ms (96.6 tok/s), drafts accepted 41 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (35040 hits / 35040 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7168, + "expert_cache_mib": 13437, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 4557, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717812.0454123, + "duration_s": 11.0, + "finish": "stop", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 59, + "engine_generated": 59, + "prompt_ms": 10404.1, + "decode_ms": 610.6, + "decode_tok_s": 96.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717800.5571585, + "duration_s": 10.8, + "finish": "stop", + "prompt_tokens": 31631, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10422.5, + "decode_ms": 406.8, + "decode_tok_s": 110.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717789.1846194, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10118.2, + "decode_ms": 608.0, + "decode_tok_s": 93.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717787.625935, + "requests": 3, + "prompt_tokens": 91549, + "reused": 0, + "output_tokens": 161, + "prompt_ms": 30944.800000000003, + "decode_ms": 1625.4 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 48, + "mem_used": 21104623616, + "mem_total": 25769803776, + "temp": 53, + "power": 214.931 + }, + { + "index": 1, + "util": 0, + "mem_used": 19548536832, + "mem_total": 25769803776, + "temp": 53, + "power": 199.379 + } + ], + "gpu_util": 24.0, + "gpu_mem_used": 40653160448, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 414.31, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 3.6, + "ram_used": 44545851392, + "ram_total": 177175990272, + "disk_read_mb": 0.7062443272525659, + "disk_write_mb": 0.11530519628613321, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 46.5, + 96.0, + 72.5, + 93.0, + 90.0, + 95.5, + 93.5, + 97.5, + 41.5, + 0.0, + 96.0, + 93.0, + 97.5, + 94.5, + 97.0, + 95.0, + 97.0, + 93.5, + 67.0, + 29.0, + 50.0, + 96.5, + 47.5, + 95.5, + 96.5, + 95.5, + 62.5, + 96.5, + 95.5, + 50.0, + 24.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40495874048, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448 + ], + "gpu_temp": [ + 51, + 50, + 50, + 52, + 55, + 54, + 56, + 54, + 56, + 56, + 57, + 54, + 52, + 55, + 54, + 56, + 56, + 56, + 56, + 57, + 57, + 56, + 54, + 53, + 56, + 54, + 57, + 57, + 57, + 56, + 57, + 56, + 57, + 53 + ], + "gpu_power": [ + 261.46, + 249.04, + 248.59, + 342.07, + 531.07, + 533.47, + 545.68, + 511.29, + 533.34, + 534.58, + 541.51, + 420.39, + 375.37, + 452.84, + 528.99, + 547.53, + 532.29, + 524.3, + 518.92, + 543.34, + 532.25, + 534.03, + 430.46, + 354.3, + 519.1, + 530.52, + 534.81, + 532.5, + 512.45, + 532.86, + 540.0, + 532.72, + 513.31, + 414.31 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 182.48, + 55.88, + 87.02, + 80.58, + 57.5, + 78.87, + 83.88, + 1294.42, + 46.78, + 17.17, + 42.15, + 1288.27, + 41.05, + 75.34, + 70.76, + 44.15, + 79.87, + 61.61, + 75.63, + 42.06, + 0.62, + 84.64, + 74.34, + 85.5, + 81.54, + 0.67, + 75.72, + 81.82, + 82.83, + 28.8, + 17.74, + 0.67 + ], + "cpu": [ + 0.0, + 6.6, + 18.0, + 11.3, + 10.5, + 9.8, + 11.5, + 13.9, + 11.4, + 12.9, + 7.4, + 6.1, + 4.2, + 6.4, + 6.0, + 12.9, + 11.2, + 6.1, + 8.2, + 8.8, + 14.0, + 6.4, + 4.3, + 4.2, + 6.6, + 6.0, + 17.8, + 8.5, + 6.2, + 15.1, + 14.3, + 6.7, + 6.9, + 3.6 + ], + "ram_used": [ + 43799613440, + 43777974272, + 43950305280, + 43962880000, + 43939622912, + 43930345472, + 43932086272, + 44071780352, + 44183257088, + 44182880256, + 44179062784, + 44503613440, + 44015304704, + 44019281920, + 44021350400, + 44034875392, + 44111585280, + 44348657664, + 44344815616, + 44359872512, + 44334280704, + 44327985152, + 44573519872, + 44103626752, + 44105744384, + 44105732096, + 44159885312, + 44275363840, + 44375539712, + 44373200896, + 44318019584, + 44307988480, + 44545863680, + 44545851392 + ], + "disk_read_mb": [ + null, + 0.0, + 129.59, + 40.83, + 79.94, + 84.92, + 115.02, + 136.42, + 117.79, + 106.04, + 29.9, + 1.95, + 1.72, + 0.02, + 0.02, + 0.05, + 0.06, + 0.01, + 0.03, + 12.6, + 101.64, + 2.94, + 0.98, + 0.74, + 0.02, + 0.06, + 0.32, + 0.08, + 0.04, + 0.05, + 0.04, + 0.1, + 0.0, + 0.71 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 81.42, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717823.5700235 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-1.json new file mode 100644 index 0000000..a0d750a --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-1.json @@ -0,0 +1,608 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "b4895f87f439", + "corpus_repeated": false, + "time": "2026-09-29T21:28:38", + "prompt_tokens": 28316, + "completion_tokens": 45, + "ttft_s": 9.936, + "e2e_s": 10.4, + "api_prompt_tps": 2849.8, + "api_decode_tps": 94.9, + "engine_prompt_tps": 2892.0, + "engine_decode_tps": 94.1, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 9791 ms (2892.0 tok/s), 45 generated in 478 ms (94.1 tok/s), drafts accepted 31 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25440 hits / 25440 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7680, + "expert_cache_mib": 14575, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 3419, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717318.4067442, + "duration_s": 10.3, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9791.3, + "decode_ms": 478.1, + "decode_tok_s": 94.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717288.2692974, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 10484.4, + "decode_ms": 636.0, + "decode_tok_s": 88.1, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717276.5105639, + "requests": 2, + "prompt_tokens": 56632, + "reused": 0, + "output_tokens": 101, + "prompt_ms": 20275.699999999997, + "decode_ms": 1114.1 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 53, + "mem_used": 22306291712, + "mem_total": 25769803776, + "temp": 51, + "power": 200.427 + }, + { + "index": 1, + "util": 46, + "mem_used": 18353160192, + "mem_total": 25769803776, + "temp": 53, + "power": 223.879 + } + ], + "gpu_util": 49.5, + "gpu_mem_used": 40659451904, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 424.306, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5.8642578125, + "gpu_pcie_tx_mb": 107.4306640625, + "cpu": 6.9, + "ram_used": 44604223488, + "ram_total": 177175990272, + "disk_read_mb": 1.1417042620069329, + "disk_write_mb": 0.04682067951447989, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 50.0, + 94.0, + 63.0, + 95.0, + 50.0, + 92.0, + 95.0, + 82.5, + 97.0, + 35.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.5, + 97.5, + 49.0, + 94.5, + 50.0, + 96.5, + 53.0, + 94.5, + 97.0, + 49.5 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40659451904 + ], + "gpu_temp": [ + 49, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 50, + 52, + 53, + 53, + 53, + 52, + 54, + 51, + 54, + 52, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 49, + 48, + 48, + 48, + 49, + 49, + 49, + 49, + 46, + 46, + 53, + 52, + 54, + 52, + 54, + 52, + 54, + 54, + 53 + ], + "gpu_power": [ + 257.9, + 244.84, + 244.4, + 244.1, + 244.29, + 244.43, + 244.32, + 244.0, + 243.79, + 243.86, + 244.04, + 244.43, + 304.5, + 504.99, + 527.59, + 513.34, + 519.55, + 489.82, + 537.3, + 515.01, + 534.71, + 416.26, + 390.46, + 299.77, + 260.05, + 241.54, + 241.56, + 241.75, + 241.63, + 241.51, + 241.46, + 241.4, + 241.29, + 241.13, + 241.31, + 241.69, + 241.72, + 221.92, + 136.12, + 67.69, + 469.97, + 521.96, + 512.77, + 514.47, + 496.64, + 522.43, + 513.55, + 532.56, + 424.31 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.67, + 0.62, + 0.62, + 0.62, + 0.62, + 0.67, + 1.62, + 0.67, + 0.62, + 0.62, + 0.62, + 4319.14, + 134.51, + 87.31, + 96.37, + 111.91, + 79.87, + 41.53, + 80.25, + 44.15, + 15.88, + 0.67, + 0.57, + 0.57, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.81, + 0.81, + 44.34, + 97.08, + 1308.87, + 41.25, + 84.97, + 155.3, + 46.68, + 84.26, + 3604.32, + 5.86 + ], + "cpu": [ + 0.0, + 1.4, + 4.7, + 7.8, + 13.7, + 1.8, + 1.4, + 1.9, + 1.6, + 1.4, + 1.5, + 9.7, + 13.3, + 10.3, + 10.0, + 9.4, + 23.0, + 17.6, + 10.6, + 13.1, + 6.5, + 6.2, + 1.3, + 8.4, + 5.4, + 1.3, + 1.2, + 1.8, + 1.6, + 0.9, + 10.0, + 4.2, + 0.8, + 1.8, + 1.6, + 2.2, + 2.6, + 1.9, + 2.8, + 7.4, + 8.7, + 7.1, + 5.6, + 6.2, + 14.3, + 8.5, + 5.8, + 9.0, + 6.9 + ], + "ram_used": [ + 43796508672, + 43800592384, + 43805933568, + 43809234944, + 43832729600, + 43832090624, + 43837464576, + 43835621376, + 43830910976, + 43829395456, + 43825078272, + 43852685312, + 44052480000, + 44036640768, + 44033179648, + 44028084224, + 44053590016, + 44291584000, + 44290129920, + 44269481984, + 44257243136, + 44556734464, + 44502183936, + 44524433408, + 44526993408, + 44523057152, + 44523831296, + 44519899136, + 44508749824, + 44508250112, + 44527558656, + 44529721344, + 44527198208, + 44529672192, + 44530278400, + 44537171968, + 44538560512, + 44524920832, + 44552687616, + 44075163648, + 44090421248, + 44086198272, + 44085055488, + 44084731904, + 44364992512, + 44360019968, + 44359946240, + 44359090176, + 44604223488 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 56.63, + 73.79, + 64.08, + 89.26, + 71.49, + 160.33, + 111.7, + 115.85, + 97.53, + 0.0, + 3.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.56, + 0.02, + 0.04, + 0.03, + 0.05, + 0.01, + 0.03, + 0.01, + 0.0, + 1.14 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717329.186504 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-2.json new file mode 100644 index 0000000..d886504 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-2.json @@ -0,0 +1,721 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "f81947893a8b", + "corpus_repeated": false, + "time": "2026-09-29T21:28:49", + "prompt_tokens": 31632, + "completion_tokens": 48, + "ttft_s": 11.011, + "e2e_s": 11.496, + "api_prompt_tps": 2872.7, + "api_decode_tps": 97.0, + "engine_prompt_tps": 2926.4, + "engine_decode_tps": 96.1, + "log_lines": [ + "strata serve: prompt 31632 tokens = 0 reused + 31632 read in 10809 ms (2926.4 tok/s), 48 generated in 499 ms (96.1 tok/s), drafts accepted 32 of 38, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (27360 hits / 27360 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7680, + "expert_cache_mib": 14575, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 3419, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717329.364414, + "duration_s": 11.3, + "finish": "stop", + "prompt_tokens": 31632, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 10809.3, + "decode_ms": 499.4, + "decode_tok_s": 96.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717318.4067442, + "duration_s": 10.3, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9791.3, + "decode_ms": 478.1, + "decode_tok_s": 94.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717288.2692974, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 10484.4, + "decode_ms": 636.0, + "decode_tok_s": 88.1, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717276.5105639, + "requests": 3, + "prompt_tokens": 88264, + "reused": 0, + "output_tokens": 149, + "prompt_ms": 31084.999999999996, + "decode_ms": 1613.5 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 48, + "mem_used": 22306291712, + "mem_total": 25769803776, + "temp": 51, + "power": 211.949 + }, + { + "index": 1, + "util": 41, + "mem_used": 18353160192, + "mem_total": 25769803776, + "temp": 54, + "power": 238.158 + } + ], + "gpu_util": 44.5, + "gpu_mem_used": 40659451904, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 450.10699999999997, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 16.3544921875, + "gpu_pcie_tx_mb": 94.6513671875, + "cpu": 12.9, + "ram_used": 44387663872, + "ram_total": 177175990272, + "disk_read_mb": 0.417992184024029, + "disk_write_mb": 0.0972912842124895, + "tok_s": 101.46942145535564, + "tok_s_mean": 93.06246895838419 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 50.0, + 94.0, + 63.0, + 95.0, + 50.0, + 92.0, + 95.0, + 82.5, + 97.0, + 35.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.5, + 97.5, + 49.0, + 94.5, + 50.0, + 96.5, + 53.0, + 94.5, + 97.0, + 49.5, + 50.0, + 97.5, + 97.0, + 98.5, + 68.5, + 96.0, + 49.5, + 96.0, + 68.5, + 97.0, + 44.5 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904 + ], + "gpu_temp": [ + 49, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 50, + 52, + 53, + 53, + 53, + 52, + 54, + 51, + 54, + 52, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 49, + 48, + 48, + 48, + 49, + 49, + 49, + 49, + 46, + 46, + 53, + 52, + 54, + 52, + 54, + 52, + 54, + 54, + 53, + 50, + 54, + 54, + 55, + 54, + 55, + 52, + 55, + 54, + 55, + 54 + ], + "gpu_power": [ + 257.9, + 244.84, + 244.4, + 244.1, + 244.29, + 244.43, + 244.32, + 244.0, + 243.79, + 243.86, + 244.04, + 244.43, + 304.5, + 504.99, + 527.59, + 513.34, + 519.55, + 489.82, + 537.3, + 515.01, + 534.71, + 416.26, + 390.46, + 299.77, + 260.05, + 241.54, + 241.56, + 241.75, + 241.63, + 241.51, + 241.46, + 241.4, + 241.29, + 241.13, + 241.31, + 241.69, + 241.72, + 221.92, + 136.12, + 67.69, + 469.97, + 521.96, + 512.77, + 514.47, + 496.64, + 522.43, + 513.55, + 532.56, + 424.31, + 362.71, + 481.71, + 508.96, + 525.74, + 511.3, + 510.79, + 506.4, + 523.98, + 513.03, + 516.57, + 450.11 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.67, + 0.62, + 0.62, + 0.62, + 0.62, + 0.67, + 1.62, + 0.67, + 0.62, + 0.62, + 0.62, + 4319.14, + 134.51, + 87.31, + 96.37, + 111.91, + 79.87, + 41.53, + 80.25, + 44.15, + 15.88, + 0.67, + 0.57, + 0.57, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.81, + 0.81, + 44.34, + 97.08, + 1308.87, + 41.25, + 84.97, + 155.3, + 46.68, + 84.26, + 3604.32, + 5.86, + 45.25, + 84.11, + 42.39, + 128.98, + 67.52, + 42.77, + 92.46, + 81.82, + 43.3, + 95.32, + 16.35 + ], + "cpu": [ + 0.0, + 1.4, + 4.7, + 7.8, + 13.7, + 1.8, + 1.4, + 1.9, + 1.6, + 1.4, + 1.5, + 9.7, + 13.3, + 10.3, + 10.0, + 9.4, + 23.0, + 17.6, + 10.6, + 13.1, + 6.5, + 6.2, + 1.3, + 8.4, + 5.4, + 1.3, + 1.2, + 1.8, + 1.6, + 0.9, + 10.0, + 4.2, + 0.8, + 1.8, + 1.6, + 2.2, + 2.6, + 1.9, + 2.8, + 7.4, + 8.7, + 7.1, + 5.6, + 6.2, + 14.3, + 8.5, + 5.8, + 9.0, + 6.9, + 3.9, + 5.5, + 5.8, + 5.9, + 6.4, + 7.5, + 6.6, + 6.1, + 8.7, + 17.4, + 12.9 + ], + "ram_used": [ + 43796508672, + 43800592384, + 43805933568, + 43809234944, + 43832729600, + 43832090624, + 43837464576, + 43835621376, + 43830910976, + 43829395456, + 43825078272, + 43852685312, + 44052480000, + 44036640768, + 44033179648, + 44028084224, + 44053590016, + 44291584000, + 44290129920, + 44269481984, + 44257243136, + 44556734464, + 44502183936, + 44524433408, + 44526993408, + 44523057152, + 44523831296, + 44519899136, + 44508749824, + 44508250112, + 44527558656, + 44529721344, + 44527198208, + 44529672192, + 44530278400, + 44537171968, + 44538560512, + 44524920832, + 44552687616, + 44075163648, + 44090421248, + 44086198272, + 44085055488, + 44084731904, + 44364992512, + 44360019968, + 44359946240, + 44359090176, + 44604223488, + 44141965312, + 44142555136, + 44129452032, + 44121694208, + 44121939968, + 44354928640, + 44349378560, + 44349894656, + 44349890560, + 44144226304, + 44387663872 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 56.63, + 73.79, + 64.08, + 89.26, + 71.49, + 160.33, + 111.7, + 115.85, + 97.53, + 0.0, + 3.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.56, + 0.02, + 0.04, + 0.03, + 0.05, + 0.01, + 0.03, + 0.01, + 0.0, + 1.14, + 0.4, + 0.01, + 0.0, + 0.03, + 0.04, + 0.01, + 0.03, + 12.58, + 71.94, + 32.9, + 0.42 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 101.47 + ] + }, + "time": 1790717341.185252 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-3.json new file mode 100644 index 0000000..714c5df --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-3.json @@ -0,0 +1,735 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "cb947708c5cc", + "corpus_repeated": false, + "time": "2026-09-29T21:29:01", + "prompt_tokens": 31602, + "completion_tokens": 45, + "ttft_s": 10.976, + "e2e_s": 11.378, + "api_prompt_tps": 2879.2, + "api_decode_tps": 109.6, + "engine_prompt_tps": 2920.6, + "engine_decode_tps": 108.0, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10820 ms (2920.6 tok/s), 45 generated in 417 ms (108.0 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24480 hits / 24480 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7680, + "expert_cache_mib": 14575, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 3419, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717341.3189692, + "duration_s": 11.2, + "finish": "stop", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10820.3, + "decode_ms": 416.8, + "decode_tok_s": 108.0, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717329.364414, + "duration_s": 11.3, + "finish": "stop", + "prompt_tokens": 31632, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 10809.3, + "decode_ms": 499.4, + "decode_tok_s": 96.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717318.4067442, + "duration_s": 10.3, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9791.3, + "decode_ms": 478.1, + "decode_tok_s": 94.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717288.2692974, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 10484.4, + "decode_ms": 636.0, + "decode_tok_s": 88.1, + "hit_rate": 1.0 + } + ], + "requests_kept": 4, + "totals": { + "since": 1790717276.5105639, + "requests": 4, + "prompt_tokens": 119866, + "reused": 0, + "output_tokens": 194, + "prompt_ms": 41905.299999999996, + "decode_ms": 2030.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 5, + "mem_used": 22306291712, + "mem_total": 25769803776, + "temp": 49, + "power": 227.165 + }, + { + "index": 1, + "util": 42, + "mem_used": 18353160192, + "mem_total": 25769803776, + "temp": 54, + "power": 235.691 + } + ], + "gpu_util": 23.5, + "gpu_mem_used": 40659451904, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 462.856, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 17.0703125, + "gpu_pcie_tx_mb": 56.361328125, + "cpu": 5.5, + "ram_used": 44383059968, + "ram_total": 177175990272, + "disk_read_mb": 0.38547172180233397, + "disk_write_mb": 0.09366602585851105, + "tok_s": 121.26075785511577, + "tok_s_mean": 112.03069063875886 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 50.0, + 94.0, + 63.0, + 95.0, + 50.0, + 92.0, + 95.0, + 82.5, + 97.0, + 35.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.5, + 97.5, + 49.0, + 94.5, + 50.0, + 96.5, + 53.0, + 94.5, + 97.0, + 49.5, + 50.0, + 97.5, + 97.0, + 98.5, + 68.5, + 96.0, + 49.5, + 96.0, + 68.5, + 97.0, + 44.5, + 50.0, + 85.5, + 94.5, + 73.0, + 79.0, + 96.0, + 48.0, + 95.0, + 72.5, + 95.5, + 23.5 + ], + "gpu_mem_used": [ + 40449736704, + 40542011392, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904 + ], + "gpu_temp": [ + 48, + 50, + 52, + 53, + 53, + 53, + 52, + 54, + 51, + 54, + 52, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 49, + 48, + 48, + 48, + 49, + 49, + 49, + 49, + 46, + 46, + 53, + 52, + 54, + 52, + 54, + 52, + 54, + 54, + 53, + 50, + 54, + 54, + 55, + 54, + 55, + 52, + 55, + 54, + 55, + 54, + 51, + 53, + 54, + 53, + 54, + 55, + 54, + 55, + 55, + 55, + 54 + ], + "gpu_power": [ + 244.43, + 304.5, + 504.99, + 527.59, + 513.34, + 519.55, + 489.82, + 537.3, + 515.01, + 534.71, + 416.26, + 390.46, + 299.77, + 260.05, + 241.54, + 241.56, + 241.75, + 241.63, + 241.51, + 241.46, + 241.4, + 241.29, + 241.13, + 241.31, + 241.69, + 241.72, + 221.92, + 136.12, + 67.69, + 469.97, + 521.96, + 512.77, + 514.47, + 496.64, + 522.43, + 513.55, + 532.56, + 424.31, + 362.71, + 481.71, + 508.96, + 525.74, + 511.3, + 510.79, + 506.4, + 523.98, + 513.03, + 516.57, + 450.11, + 369.53, + 481.25, + 509.29, + 527.58, + 511.62, + 510.74, + 510.07, + 527.16, + 513.42, + 533.96, + 462.86 + ], + "gpu_pcie_rx_mb": [ + 0.62, + 4319.14, + 134.51, + 87.31, + 96.37, + 111.91, + 79.87, + 41.53, + 80.25, + 44.15, + 15.88, + 0.67, + 0.57, + 0.57, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.81, + 0.81, + 44.34, + 97.08, + 1308.87, + 41.25, + 84.97, + 155.3, + 46.68, + 84.26, + 3604.32, + 5.86, + 45.25, + 84.11, + 42.39, + 128.98, + 67.52, + 42.77, + 92.46, + 81.82, + 43.3, + 95.32, + 16.35, + 43.1, + 79.92, + 41.63, + 65.23, + 80.39, + 37.1, + 81.92, + 1273.96, + 41.01, + 79.15, + 17.07 + ], + "cpu": [ + 9.7, + 13.3, + 10.3, + 10.0, + 9.4, + 23.0, + 17.6, + 10.6, + 13.1, + 6.5, + 6.2, + 1.3, + 8.4, + 5.4, + 1.3, + 1.2, + 1.8, + 1.6, + 0.9, + 10.0, + 4.2, + 0.8, + 1.8, + 1.6, + 2.2, + 2.6, + 1.9, + 2.8, + 7.4, + 8.7, + 7.1, + 5.6, + 6.2, + 14.3, + 8.5, + 5.8, + 9.0, + 6.9, + 3.9, + 5.5, + 5.8, + 5.9, + 6.4, + 7.5, + 6.6, + 6.1, + 8.7, + 17.4, + 12.9, + 4.0, + 6.3, + 7.4, + 6.1, + 5.4, + 6.6, + 5.7, + 6.7, + 9.3, + 6.7, + 5.5 + ], + "ram_used": [ + 43852685312, + 44052480000, + 44036640768, + 44033179648, + 44028084224, + 44053590016, + 44291584000, + 44290129920, + 44269481984, + 44257243136, + 44556734464, + 44502183936, + 44524433408, + 44526993408, + 44523057152, + 44523831296, + 44519899136, + 44508749824, + 44508250112, + 44527558656, + 44529721344, + 44527198208, + 44529672192, + 44530278400, + 44537171968, + 44538560512, + 44524920832, + 44552687616, + 44075163648, + 44090421248, + 44086198272, + 44085055488, + 44084731904, + 44364992512, + 44360019968, + 44359946240, + 44359090176, + 44604223488, + 44141965312, + 44142555136, + 44129452032, + 44121694208, + 44121939968, + 44354928640, + 44349378560, + 44349894656, + 44349890560, + 44144226304, + 44387663872, + 44206063616, + 44194983936, + 44169220096, + 44150177792, + 44142342144, + 44137152512, + 44138057728, + 44126892032, + 44160794624, + 44161884160, + 44383059968 + ], + "disk_read_mb": [ + 56.63, + 73.79, + 64.08, + 89.26, + 71.49, + 160.33, + 111.7, + 115.85, + 97.53, + 0.0, + 3.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.56, + 0.02, + 0.04, + 0.03, + 0.05, + 0.01, + 0.03, + 0.01, + 0.0, + 1.14, + 0.4, + 0.01, + 0.0, + 0.03, + 0.04, + 0.01, + 0.03, + 12.58, + 71.94, + 32.9, + 0.42, + 0.53, + 0.06, + 0.03, + 0.08, + 0.09, + 0.04, + 0.08, + 0.03, + 0.02, + 0.22, + 0.39 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 101.47, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 121.26 + ] + }, + "time": 1790717353.0661266 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-1.json new file mode 100644 index 0000000..ef3f5dd --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-1.json @@ -0,0 +1,585 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "3e44ccd7ec28", + "corpus_repeated": false, + "time": "2026-09-29T21:18:00", + "prompt_tokens": 28314, + "completion_tokens": 48, + "ttft_s": 11.385, + "e2e_s": 11.891, + "api_prompt_tps": 2486.9, + "api_decode_tps": 93.0, + "engine_prompt_tps": 2524.7, + "engine_decode_tps": 88.5, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 11215 ms (2524.7 tok/s), 48 generated in 542 ms (88.5 tok/s), drafts accepted 34 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24958 hits / 24960 lookups)" + ], + "answer_head": "I'll first look at the repository structure to understand what files exist and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 4864, + "expert_cache_mib": 8968, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 9025, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716680.7795944, + "duration_s": 11.8, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 11214.6, + "decode_ms": 542.2, + "decode_tok_s": 88.5, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790716641.243247, + "requests": 1, + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "prompt_ms": 11214.6, + "decode_ms": 542.2 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 2, + "mem_used": 16383934464, + "mem_total": 25769803776, + "temp": 43, + "power": 147.336 + }, + { + "index": 1, + "util": 7, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 48, + "power": 266.007 + } + ], + "gpu_util": 4.5, + "gpu_mem_used": 40611217408, + "gpu_mem_total": 51539607552, + "gpu_temp": 48, + "gpu_power": 413.343, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 16.8310546875, + "gpu_pcie_tx_mb": 71.810546875, + "cpu": 8.4, + "ram_used": 44637356032, + "ram_total": 177175990272, + "disk_read_mb": 2.277384309569965, + "disk_write_mb": 0.07927603609262536, + "tok_s": 96.0473472439008, + "tok_s_mean": 90.3424282028167 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 48.0, + 91.5, + 69.0, + 77.0, + 91.0, + 93.0, + 49.5, + 94.0, + 50.0, + 4.5 + ], + "gpu_mem_used": [ + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40489582592, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40611217408 + ], + "gpu_temp": [ + 44, + 43, + 43, + 43, + 43, + 43, + 44, + 44, + 43, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 43, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 51, + 51, + 48 + ], + "gpu_power": [ + 253.73, + 239.29, + 238.99, + 238.62, + 238.58, + 238.53, + 238.39, + 238.34, + 238.4, + 238.51, + 238.61, + 238.53, + 238.49, + 238.83, + 238.96, + 238.97, + 226.8, + 148.88, + 73.97, + 64.38, + 63.94, + 63.69, + 63.56, + 63.75, + 63.53, + 63.8, + 63.68, + 63.62, + 63.84, + 63.74, + 63.81, + 64.11, + 63.92, + 63.72, + 63.85, + 63.64, + 63.78, + 139.81, + 418.68, + 508.54, + 520.36, + 495.57, + 522.4, + 506.1, + 501.02, + 508.77, + 509.32, + 413.34 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.67, + 0.71, + 0.57, + 0.62, + 0.57, + 0.67, + 0.57, + 0.67, + 0.62, + 0.57, + 0.67, + 0.62, + 0.57, + 1.05, + 0.57, + 0.76, + 0.81, + 0.81, + 0.81, + 0.76, + 0.76, + 0.81, + 0.86, + 1.43, + 0.81, + 0.81, + 0.76, + 0.86, + 0.81, + 0.76, + 0.95, + 0.86, + 0.86, + 0.76, + 0.86, + 0.86, + 70.24, + 68.14, + 64.66, + 75.24, + 42.29, + 84.73, + 70.48, + 75.05, + 54.45, + 44.44, + 16.83 + ], + "cpu": [ + 0.0, + 0.6, + 1.0, + 1.6, + 2.5, + 1.0, + 3.1, + 8.1, + 6.5, + 1.2, + 1.9, + 2.1, + 1.5, + 3.2, + 2.4, + 1.3, + 2.0, + 1.4, + 1.3, + 0.9, + 0.9, + 14.0, + 6.6, + 2.5, + 2.7, + 1.7, + 1.2, + 0.6, + 1.1, + 1.2, + 1.7, + 1.3, + 1.4, + 2.7, + 4.4, + 12.3, + 12.4, + 11.4, + 12.5, + 10.3, + 9.0, + 12.2, + 12.1, + 12.5, + 11.3, + 10.4, + 5.8, + 8.4 + ], + "ram_used": [ + 43649658880, + 43652177920, + 43664764928, + 43666993152, + 43672375296, + 43665145856, + 43695276032, + 43759751168, + 43760455680, + 43757346816, + 43754053632, + 43711803392, + 43717255168, + 43692584960, + 43693260800, + 43687956480, + 43682111488, + 43635728384, + 43632320512, + 43636883456, + 43633815552, + 43735252992, + 43881848832, + 43881005056, + 43875524608, + 43879301120, + 43878330368, + 43866976256, + 43862958080, + 43863728128, + 43854176256, + 43855548416, + 43854200832, + 43859615744, + 43895934976, + 43929411584, + 43962118144, + 44169498624, + 44107767808, + 44110077952, + 44109590528, + 44111515648, + 44233150464, + 44346421248, + 44340047872, + 44335108096, + 44329865216, + 44637356032 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 129.56, + 55.21, + 65.53, + 55.86, + 128.68, + 113.77, + 117.74, + 106.28, + 68.13, + 0.0, + 2.28 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 96.05 + ] + }, + "time": 1790716693.048385 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-2.json new file mode 100644 index 0000000..62fded2 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-2.json @@ -0,0 +1,707 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "0b6b57dfa6a4", + "corpus_repeated": false, + "time": "2026-09-29T21:18:13", + "prompt_tokens": 31634, + "completion_tokens": 55, + "ttft_s": 11.855, + "e2e_s": 12.398, + "api_prompt_tps": 2668.4, + "api_decode_tps": 99.4, + "engine_prompt_tps": 2704.3, + "engine_decode_tps": 98.6, + "log_lines": [ + "strata serve: prompt 31634 tokens = 0 reused + 31634 read in 11698 ms (2704.3 tok/s), 55 generated in 558 ms (98.6 tok/s), drafts accepted 38 of 44, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (29759 hits / 29760 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 4864, + "expert_cache_mib": 8968, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 9025, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716693.1835682, + "duration_s": 12.3, + "finish": "stop", + "prompt_tokens": 31634, + "reused": 0, + "output_tokens": 55, + "engine_generated": 55, + "prompt_ms": 11697.7, + "decode_ms": 557.8, + "decode_tok_s": 98.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790716680.7795944, + "duration_s": 11.8, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 11214.6, + "decode_ms": 542.2, + "decode_tok_s": 88.5, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790716641.243247, + "requests": 2, + "prompt_tokens": 59948, + "reused": 0, + "output_tokens": 103, + "prompt_ms": 22912.300000000003, + "decode_ms": 1100.0 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 30, + "mem_used": 16392323072, + "mem_total": 25769803776, + "temp": 45, + "power": 154.497 + }, + { + "index": 1, + "util": 0, + "mem_used": 24241963008, + "mem_total": 25769803776, + "temp": 47, + "power": 250.412 + } + ], + "gpu_util": 15.0, + "gpu_mem_used": 40634286080, + "gpu_mem_total": 51539607552, + "gpu_temp": 47, + "gpu_power": 404.909, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 19.310546875, + "gpu_pcie_tx_mb": 48.8271484375, + "cpu": 8.6, + "ram_used": 44481728512, + "ram_total": 177175990272, + "disk_read_mb": 1.583864660002197, + "disk_write_mb": 0.12238954190926069, + "tok_s": 112.53532236859756, + "tok_s_mean": 97.92814776699883 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 48.0, + 91.5, + 69.0, + 77.0, + 91.0, + 93.0, + 49.5, + 94.0, + 50.0, + 4.5, + 0.5, + 94.5, + 73.5, + 72.5, + 96.5, + 49.0, + 97.5, + 97.5, + 48.5, + 94.0, + 48.5, + 15.0 + ], + "gpu_mem_used": [ + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40489582592, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40634286080 + ], + "gpu_temp": [ + 44, + 43, + 43, + 43, + 43, + 43, + 44, + 44, + 43, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 43, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 51, + 51, + 48, + 45, + 51, + 51, + 50, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 47 + ], + "gpu_power": [ + 253.73, + 239.29, + 238.99, + 238.62, + 238.58, + 238.53, + 238.39, + 238.34, + 238.4, + 238.51, + 238.61, + 238.53, + 238.49, + 238.83, + 238.96, + 238.97, + 226.8, + 148.88, + 73.97, + 64.38, + 63.94, + 63.69, + 63.56, + 63.75, + 63.53, + 63.8, + 63.68, + 63.62, + 63.84, + 63.74, + 63.81, + 64.11, + 63.92, + 63.72, + 63.85, + 63.64, + 63.78, + 139.81, + 418.68, + 508.54, + 520.36, + 495.57, + 522.4, + 506.1, + 501.02, + 508.77, + 509.32, + 413.34, + 344.59, + 491.91, + 520.34, + 491.14, + 524.22, + 495.09, + 489.28, + 512.02, + 509.99, + 497.54, + 503.94, + 404.91 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.67, + 0.71, + 0.57, + 0.62, + 0.57, + 0.67, + 0.57, + 0.67, + 0.62, + 0.57, + 0.67, + 0.62, + 0.57, + 1.05, + 0.57, + 0.76, + 0.81, + 0.81, + 0.81, + 0.76, + 0.76, + 0.81, + 0.86, + 1.43, + 0.81, + 0.81, + 0.76, + 0.86, + 0.81, + 0.76, + 0.95, + 0.86, + 0.86, + 0.76, + 0.86, + 0.86, + 70.24, + 68.14, + 64.66, + 75.24, + 42.29, + 84.73, + 70.48, + 75.05, + 54.45, + 44.44, + 16.83, + 43.1, + 73.43, + 85.92, + 85.16, + 1285.6, + 83.21, + 5496.41, + 73.67, + 83.68, + 89.36, + 52.83, + 19.31 + ], + "cpu": [ + 0.0, + 0.6, + 1.0, + 1.6, + 2.5, + 1.0, + 3.1, + 8.1, + 6.5, + 1.2, + 1.9, + 2.1, + 1.5, + 3.2, + 2.4, + 1.3, + 2.0, + 1.4, + 1.3, + 0.9, + 0.9, + 14.0, + 6.6, + 2.5, + 2.7, + 1.7, + 1.2, + 0.6, + 1.1, + 1.2, + 1.7, + 1.3, + 1.4, + 2.7, + 4.4, + 12.3, + 12.4, + 11.4, + 12.5, + 10.3, + 9.0, + 12.2, + 12.1, + 12.5, + 11.3, + 10.4, + 5.8, + 8.4, + 5.5, + 16.9, + 8.9, + 8.2, + 6.7, + 6.4, + 6.4, + 5.5, + 7.3, + 10.1, + 6.1, + 8.6 + ], + "ram_used": [ + 43649658880, + 43652177920, + 43664764928, + 43666993152, + 43672375296, + 43665145856, + 43695276032, + 43759751168, + 43760455680, + 43757346816, + 43754053632, + 43711803392, + 43717255168, + 43692584960, + 43693260800, + 43687956480, + 43682111488, + 43635728384, + 43632320512, + 43636883456, + 43633815552, + 43735252992, + 43881848832, + 43881005056, + 43875524608, + 43879301120, + 43878330368, + 43866976256, + 43862958080, + 43863728128, + 43854176256, + 43855548416, + 43854200832, + 43859615744, + 43895934976, + 43929411584, + 43962118144, + 44169498624, + 44107767808, + 44110077952, + 44109590528, + 44111515648, + 44233150464, + 44346421248, + 44340047872, + 44335108096, + 44329865216, + 44637356032, + 44551315456, + 44588969984, + 44562165760, + 44546224128, + 44540850176, + 44543295488, + 44547391488, + 44375429120, + 44370026496, + 44363567104, + 44368113664, + 44481728512 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 129.56, + 55.21, + 65.53, + 55.86, + 128.68, + 113.77, + 117.74, + 106.28, + 68.13, + 0.0, + 2.28, + 1.11, + 0.12, + 0.02, + 0.05, + 0.05, + 0.01, + 0.03, + 0.0, + 25.35, + 92.15, + 0.01, + 1.58 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 96.05, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 112.54 + ] + }, + "time": 1790716705.9498026 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-3.json new file mode 100644 index 0000000..2c111c3 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-3.json @@ -0,0 +1,721 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "caa0b992dd74", + "corpus_repeated": false, + "time": "2026-09-29T21:18:25", + "prompt_tokens": 31601, + "completion_tokens": 45, + "ttft_s": 11.847, + "e2e_s": 12.249, + "api_prompt_tps": 2667.3, + "api_decode_tps": 109.5, + "engine_prompt_tps": 2704.5, + "engine_decode_tps": 108.1, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 11684 ms (2704.5 tok/s), 45 generated in 416 ms (108.1 tok/s), drafts accepted 33 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24000 hits / 24000 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 4864, + "expert_cache_mib": 8968, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 9025, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716706.0904436, + "duration_s": 12.1, + "finish": "stop", + "prompt_tokens": 31601, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 11684.5, + "decode_ms": 416.2, + "decode_tok_s": 108.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790716693.1835682, + "duration_s": 12.3, + "finish": "stop", + "prompt_tokens": 31634, + "reused": 0, + "output_tokens": 55, + "engine_generated": 55, + "prompt_ms": 11697.7, + "decode_ms": 557.8, + "decode_tok_s": 98.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790716680.7795944, + "duration_s": 11.8, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 11214.6, + "decode_ms": 542.2, + "decode_tok_s": 88.5, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790716641.243247, + "requests": 3, + "prompt_tokens": 91549, + "reused": 0, + "output_tokens": 148, + "prompt_ms": 34596.8, + "decode_ms": 1516.2 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 30, + "mem_used": 16392323072, + "mem_total": 25769803776, + "temp": 46, + "power": 161.526 + }, + { + "index": 1, + "util": 0, + "mem_used": 24241963008, + "mem_total": 25769803776, + "temp": 48, + "power": 223.689 + } + ], + "gpu_util": 15.0, + "gpu_mem_used": 40634286080, + "gpu_mem_total": 51539607552, + "gpu_temp": 48, + "gpu_power": 385.21500000000003, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.5703125, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 6.1, + "ram_used": 44274470912, + "ram_total": 177175990272, + "disk_read_mb": 0.14419269932051038, + "disk_write_mb": 0.2595468587769187, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 48.0, + 91.5, + 69.0, + 77.0, + 91.0, + 93.0, + 49.5, + 94.0, + 50.0, + 4.5, + 0.5, + 94.5, + 73.5, + 72.5, + 96.5, + 49.0, + 97.5, + 97.5, + 48.5, + 94.0, + 48.5, + 15.0, + 0.0, + 97.5, + 49.0, + 93.5, + 72.5, + 70.5, + 97.0, + 95.5, + 50.0, + 96.0, + 50.0, + 15.0 + ], + "gpu_mem_used": [ + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40489582592, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080 + ], + "gpu_temp": [ + 44, + 44, + 44, + 44, + 44, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 43, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 51, + 51, + 48, + 45, + 51, + 51, + 50, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 47, + 45, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 52, + 52, + 48 + ], + "gpu_power": [ + 238.49, + 238.83, + 238.96, + 238.97, + 226.8, + 148.88, + 73.97, + 64.38, + 63.94, + 63.69, + 63.56, + 63.75, + 63.53, + 63.8, + 63.68, + 63.62, + 63.84, + 63.74, + 63.81, + 64.11, + 63.92, + 63.72, + 63.85, + 63.64, + 63.78, + 139.81, + 418.68, + 508.54, + 520.36, + 495.57, + 522.4, + 506.1, + 501.02, + 508.77, + 509.32, + 413.34, + 344.59, + 491.91, + 520.34, + 491.14, + 524.22, + 495.09, + 489.28, + 512.02, + 509.99, + 497.54, + 503.94, + 404.91, + 336.42, + 502.95, + 510.85, + 498.42, + 519.36, + 492.86, + 501.0, + 522.94, + 497.46, + 508.62, + 494.37, + 385.22 + ], + "gpu_pcie_rx_mb": [ + 0.62, + 0.57, + 1.05, + 0.57, + 0.76, + 0.81, + 0.81, + 0.81, + 0.76, + 0.76, + 0.81, + 0.86, + 1.43, + 0.81, + 0.81, + 0.76, + 0.86, + 0.81, + 0.76, + 0.95, + 0.86, + 0.86, + 0.76, + 0.86, + 0.86, + 70.24, + 68.14, + 64.66, + 75.24, + 42.29, + 84.73, + 70.48, + 75.05, + 54.45, + 44.44, + 16.83, + 43.1, + 73.43, + 85.92, + 85.16, + 1285.6, + 83.21, + 5496.41, + 73.67, + 83.68, + 89.36, + 52.83, + 19.31, + 45.11, + 82.73, + 85.31, + 43.06, + 94.36, + 41.63, + 73.48, + 42.01, + 87.26, + 45.92, + 121.97, + 0.57 + ], + "cpu": [ + 1.5, + 3.2, + 2.4, + 1.3, + 2.0, + 1.4, + 1.3, + 0.9, + 0.9, + 14.0, + 6.6, + 2.5, + 2.7, + 1.7, + 1.2, + 0.6, + 1.1, + 1.2, + 1.7, + 1.3, + 1.4, + 2.7, + 4.4, + 12.3, + 12.4, + 11.4, + 12.5, + 10.3, + 9.0, + 12.2, + 12.1, + 12.5, + 11.3, + 10.4, + 5.8, + 8.4, + 5.5, + 16.9, + 8.9, + 8.2, + 6.7, + 6.4, + 6.4, + 5.5, + 7.3, + 10.1, + 6.1, + 8.6, + 3.1, + 6.2, + 9.6, + 17.9, + 6.1, + 7.4, + 6.0, + 6.4, + 6.4, + 5.7, + 5.9, + 6.1 + ], + "ram_used": [ + 43717255168, + 43692584960, + 43693260800, + 43687956480, + 43682111488, + 43635728384, + 43632320512, + 43636883456, + 43633815552, + 43735252992, + 43881848832, + 43881005056, + 43875524608, + 43879301120, + 43878330368, + 43866976256, + 43862958080, + 43863728128, + 43854176256, + 43855548416, + 43854200832, + 43859615744, + 43895934976, + 43929411584, + 43962118144, + 44169498624, + 44107767808, + 44110077952, + 44109590528, + 44111515648, + 44233150464, + 44346421248, + 44340047872, + 44335108096, + 44329865216, + 44637356032, + 44551315456, + 44588969984, + 44562165760, + 44546224128, + 44540850176, + 44543295488, + 44547391488, + 44375429120, + 44370026496, + 44363567104, + 44368113664, + 44481728512, + 44224720896, + 44216463360, + 44188299264, + 44025966592, + 44017278976, + 44014284800, + 44060004352, + 44042358784, + 44044165120, + 44044423168, + 44044165120, + 44274470912 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 129.56, + 55.21, + 65.53, + 55.86, + 128.68, + 113.77, + 117.74, + 106.28, + 68.13, + 0.0, + 2.28, + 1.11, + 0.12, + 0.02, + 0.05, + 0.05, + 0.01, + 0.03, + 0.0, + 25.35, + 92.15, + 0.01, + 1.58, + 0.57, + 0.06, + 0.06, + 0.05, + 0.08, + 0.04, + 0.07, + 0.01, + 0.04, + 0.15, + 0.0, + 0.14 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 96.05, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 112.54, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790716718.7022452 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-16k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-16k-1.json new file mode 100644 index 0000000..420ad09 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-16k-1.json @@ -0,0 +1,750 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "1e52cb484c7f", + "corpus_repeated": false, + "time": "2026-09-29T21:55:17", + "prompt_tokens": 17345, + "completion_tokens": 8, + "ttft_s": 23.389, + "e2e_s": 23.454, + "api_prompt_tps": 741.6, + "api_decode_tps": 106.6, + "engine_prompt_tps": 744.7, + "engine_decode_tps": 101.7, + "log_lines": [ + "strata serve: prompt 17345 tokens = 0 reused + 17345 read in 23292 ms (744.7 tok/s), 8 generated in 79 ms (101.7 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (4159 hits / 4317 lookups)" + ], + "answer_head": "A466BDE8", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718917.8830457, + "duration_s": 23.4, + "finish": "stop", + "prompt_tokens": 17345, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 23292.2, + "decode_ms": 78.7, + "decode_tok_s": 101.7, + "hit_rate": 0.963 + }, + { + "projection": null, + "time": 1790718906.5660036, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 7491, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 10625.3, + "decode_ms": 109.4, + "decode_tok_s": 73.1, + "hit_rate": 0.902 + }, + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 5, + "totals": { + "since": 1790718725.4039552, + "requests": 5, + "prompt_tokens": 116388, + "reused": 0, + "output_tokens": 237, + "prompt_ms": 157531.5, + "decode_ms": 2436.8 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 5, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 46, + "power": 125.093 + }, + { + "index": 1, + "util": 0, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 51, + "power": 215.964 + } + ], + "gpu_util": 2.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 51, + "gpu_power": 341.057, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 16.5, + "ram_used": 70477971456, + "ram_total": 177175990272, + "disk_read_mb": 0.17303348536954039, + "disk_write_mb": 0.0036048642785320916, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 37.0, + 28.0, + 22.5, + 30.0, + 37.0, + 18.0, + 29.0, + 22.0, + 21.0, + 0.5, + 50.0, + 34.5, + 25.0, + 60.5, + 31.5, + 26.0, + 33.5, + 46.5, + 25.0, + 31.5, + 21.0, + 30.0, + 35.0, + 37.0, + 32.5, + 22.0, + 26.5, + 19.5, + 49.5, + 26.5, + 21.0, + 2.5 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 45, + 45, + 45, + 45, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 50, + 49, + 51, + 51, + 51, + 51, + 50, + 51, + 52, + 50, + 49, + 49, + 51, + 52, + 50, + 52, + 51, + 51, + 51, + 51, + 52, + 51, + 52, + 51, + 51, + 52, + 52, + 51, + 52, + 52, + 53, + 51 + ], + "gpu_power": [ + 242.53, + 242.44, + 242.38, + 242.52, + 242.49, + 242.46, + 242.59, + 242.37, + 242.36, + 242.5, + 242.54, + 140.5, + 84.6, + 65.59, + 65.03, + 64.81, + 64.81, + 64.9, + 64.51, + 64.65, + 64.87, + 64.67, + 64.8, + 64.5, + 64.56, + 64.64, + 64.52, + 64.48, + 252.37, + 388.02, + 363.78, + 375.15, + 399.66, + 368.5, + 396.75, + 362.75, + 365.62, + 336.59, + 296.73, + 407.69, + 367.08, + 376.76, + 397.12, + 384.8, + 382.99, + 408.25, + 371.72, + 397.41, + 373.98, + 388.78, + 413.99, + 362.47, + 402.46, + 358.68, + 403.34, + 387.12, + 369.06, + 426.5, + 375.9, + 341.06 + ], + "gpu_pcie_rx_mb": [ + 0.62, + 0.62, + 0.67, + 0.67, + 0.67, + 0.62, + 0.62, + 0.57, + 0.62, + 0.67, + 0.71, + 0.81, + 0.81, + 0.86, + 0.81, + 0.86, + 0.81, + 0.86, + 0.76, + 0.81, + 0.86, + 0.81, + 0.95, + 0.81, + 0.86, + 0.86, + 0.86, + 0.71, + 7078.07, + 5438.42, + 7891.61, + 5618.71, + 5824.99, + 6656.5, + 6553.84, + 1295.8, + 3929.76, + 0.67, + 7089.76, + 6013.73, + 7916.07, + 5803.39, + 5749.08, + 4295.01, + 6229.4, + 7158.52, + 6448.94, + 8972.07, + 4133.89, + 5762.81, + 4218.58, + 7081.13, + 5446.96, + 19399.45, + 7164.1, + 6657.41, + 4340.22, + 8272.65, + 7551.43, + 0.67 + ], + "cpu": [ + 1.4, + 3.7, + 2.4, + 2.6, + 2.2, + 1.6, + 7.0, + 7.8, + 0.8, + 3.8, + 6.2, + 1.4, + 1.5, + 1.3, + 0.5, + 0.8, + 1.4, + 1.7, + 1.4, + 1.5, + 8.2, + 9.2, + 2.9, + 5.7, + 1.3, + 5.6, + 1.2, + 7.3, + 6.3, + 9.1, + 6.4, + 7.4, + 6.7, + 6.4, + 16.3, + 9.8, + 6.3, + 19.7, + 4.9, + 6.7, + 5.5, + 6.3, + 6.2, + 6.4, + 7.1, + 6.3, + 6.6, + 6.4, + 16.7, + 8.7, + 6.4, + 6.7, + 6.7, + 6.4, + 6.1, + 7.1, + 5.5, + 9.0, + 6.7, + 16.5 + ], + "ram_used": [ + 70616137728, + 70634639360, + 70632943616, + 70619291648, + 70622433280, + 70624546816, + 70651342848, + 70754201600, + 70754394112, + 70772871168, + 70811869184, + 70806048768, + 70788648960, + 70775001088, + 70770065408, + 70761766912, + 70762528768, + 70758371328, + 70767398912, + 70768398336, + 70723190784, + 70684524544, + 70713102336, + 70694293504, + 70656102400, + 70685872128, + 70679355392, + 70251024384, + 70250827776, + 70240993280, + 70217400320, + 70216302592, + 70220156928, + 70211788800, + 70218944512, + 70240178176, + 70232375296, + 70472826880, + 70432313344, + 70401486848, + 70392971264, + 70382305280, + 70365552640, + 70356713472, + 70348333056, + 70341337088, + 70134956032, + 70120873984, + 70109106176, + 70101512192, + 70084435968, + 70076407808, + 70066089984, + 70059646976, + 70027522048, + 70087983104, + 70087725056, + 70115901440, + 70239928320, + 70477971456 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.04, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.46, + 0.01, + 0.0, + 0.0, + 0.82, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.2, + 0.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.59, + 0.0, + 0.0, + 0.02, + 0.0, + 0.04, + 0.0, + 0.0, + 0.05, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.17 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790718941.76262 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-28k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-28k-1.json new file mode 100644 index 0000000..fca49d3 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-28k-1.json @@ -0,0 +1,764 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "c61aafff2d90", + "corpus_repeated": false, + "time": "2026-09-29T21:55:41", + "prompt_tokens": 29827, + "completion_tokens": 8, + "ttft_s": 39.958, + "e2e_s": 40.036, + "api_prompt_tps": 746.5, + "api_decode_tps": 89.7, + "engine_prompt_tps": 749.2, + "engine_decode_tps": 85.9, + "log_lines": [ + "strata serve: prompt 29827 tokens = 0 reused + 29827 read in 39812 ms (749.2 tok/s), 8 generated in 93 ms (85.9 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.2% (4154 hits / 4318 lookups)" + ], + "answer_head": "7BDBA3C1", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718941.8879943, + "duration_s": 39.9, + "finish": "stop", + "prompt_tokens": 29827, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 39812.1, + "decode_ms": 93.1, + "decode_tok_s": 85.9, + "hit_rate": 0.962 + }, + { + "projection": null, + "time": 1790718917.8830457, + "duration_s": 23.4, + "finish": "stop", + "prompt_tokens": 17345, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 23292.2, + "decode_ms": 78.7, + "decode_tok_s": 101.7, + "hit_rate": 0.963 + }, + { + "projection": null, + "time": 1790718906.5660036, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 7491, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 10625.3, + "decode_ms": 109.4, + "decode_tok_s": 73.1, + "hit_rate": 0.902 + }, + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 6, + "totals": { + "since": 1790718725.4039552, + "requests": 6, + "prompt_tokens": 146215, + "reused": 0, + "output_tokens": 245, + "prompt_ms": 197343.6, + "decode_ms": 2529.9 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 0, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 47, + "power": 130.942 + }, + { + "index": 1, + "util": 42, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 53, + "power": 227.639 + } + ], + "gpu_util": 21.0, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 358.581, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 6.3, + "ram_used": 70479159296, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.014414807554752778, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 50.0, + 34.5, + 25.0, + 60.5, + 31.5, + 26.0, + 33.5, + 46.5, + 25.0, + 31.5, + 21.0, + 30.0, + 35.0, + 37.0, + 32.5, + 22.0, + 26.5, + 19.5, + 49.5, + 26.5, + 21.0, + 2.5, + 50.5, + 42.0, + 43.0, + 38.0, + 32.0, + 21.5, + 29.0, + 34.0, + 13.5, + 36.0, + 23.0, + 30.0, + 11.0, + 77.5, + 34.5, + 23.5, + 29.0, + 17.5, + 69.0, + 34.5, + 23.5, + 32.5, + 24.5, + 57.5, + 32.0, + 26.0, + 33.5, + 25.0, + 32.0, + 32.5, + 22.5, + 36.0, + 37.0, + 36.5, + 28.5, + 42.5, + 21.0 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 50, + 49, + 49, + 51, + 52, + 50, + 52, + 51, + 51, + 51, + 51, + 52, + 51, + 52, + 51, + 51, + 52, + 52, + 51, + 52, + 52, + 53, + 51, + 50, + 50, + 51, + 53, + 51, + 52, + 52, + 51, + 52, + 51, + 52, + 52, + 52, + 53, + 52, + 52, + 51, + 51, + 53, + 52, + 52, + 52, + 52, + 52, + 51, + 53, + 52, + 52, + 52, + 52, + 53, + 52, + 53, + 52, + 53, + 52, + 53 + ], + "gpu_power": [ + 336.59, + 296.73, + 407.69, + 367.08, + 376.76, + 397.12, + 384.8, + 382.99, + 408.25, + 371.72, + 397.41, + 373.98, + 388.78, + 413.99, + 362.47, + 402.46, + 358.68, + 403.34, + 387.12, + 369.06, + 426.5, + 375.9, + 341.06, + 316.12, + 396.45, + 370.14, + 378.61, + 411.6, + 381.87, + 383.44, + 399.03, + 378.32, + 399.6, + 372.43, + 400.43, + 390.19, + 384.29, + 405.22, + 398.65, + 405.33, + 377.77, + 347.82, + 408.44, + 395.16, + 399.76, + 391.18, + 383.68, + 395.97, + 381.79, + 371.58, + 387.34, + 367.36, + 390.18, + 377.99, + 404.54, + 406.77, + 371.21, + 404.91, + 389.57, + 358.58 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 7089.76, + 6013.73, + 7916.07, + 5803.39, + 5749.08, + 4295.01, + 6229.4, + 7158.52, + 6448.94, + 8972.07, + 4133.89, + 5762.81, + 4218.58, + 7081.13, + 5446.96, + 19399.45, + 7164.1, + 6657.41, + 4340.22, + 8272.65, + 7551.43, + 0.67, + 5912.64, + 6668.66, + 4836.32, + 15187.07, + 6919.96, + 7012.13, + 4668.04, + 8340.98, + 5615.52, + 6986.24, + 8358.29, + 8231.35, + 7154.13, + 6558.46, + 5322.65, + 14744.81, + 6437.3, + 7645.75, + 4067.04, + 5734.82, + 1.62, + 5507.04, + 5994.7, + 5715.7, + 6093.12, + 89.88, + 6215.57, + 4331.35, + 6045.63, + 5971.19, + 6178.04, + 5846.59, + 7484.53, + 5744.65, + 5095.67, + 7809.07, + 0.67 + ], + "cpu": [ + 19.7, + 4.9, + 6.7, + 5.5, + 6.3, + 6.2, + 6.4, + 7.1, + 6.3, + 6.6, + 6.4, + 16.7, + 8.7, + 6.4, + 6.7, + 6.7, + 6.4, + 6.1, + 7.1, + 5.5, + 9.0, + 6.7, + 16.5, + 4.3, + 8.5, + 17.0, + 10.5, + 8.0, + 8.5, + 6.2, + 6.8, + 6.0, + 6.0, + 5.6, + 6.4, + 7.1, + 5.6, + 6.3, + 11.3, + 13.8, + 13.6, + 7.0, + 5.8, + 6.1, + 6.1, + 6.3, + 6.2, + 6.0, + 9.3, + 6.5, + 6.1, + 6.0, + 14.5, + 11.7, + 5.6, + 8.6, + 7.7, + 6.1, + 6.7, + 6.3 + ], + "ram_used": [ + 70472826880, + 70432313344, + 70401486848, + 70392971264, + 70382305280, + 70365552640, + 70356713472, + 70348333056, + 70341337088, + 70134956032, + 70120873984, + 70109106176, + 70101512192, + 70084435968, + 70076407808, + 70066089984, + 70059646976, + 70027522048, + 70087983104, + 70087725056, + 70115901440, + 70239928320, + 70477971456, + 70343557120, + 70337265664, + 70309584896, + 70434922496, + 70428250112, + 70420987904, + 70412926976, + 70409207808, + 70400454656, + 70391336960, + 70383079424, + 70374731776, + 70367465472, + 70359465984, + 70354010112, + 70334316544, + 70343401472, + 70345613312, + 70344155136, + 70340018176, + 70356168704, + 70375772160, + 70372450304, + 70371860480, + 70366474240, + 70373842944, + 70374035456, + 70365605888, + 70363926528, + 70340509696, + 70341251072, + 70340546560, + 70343122944, + 70346379264, + 70347120640, + 70345048064, + 70479159296 + ], + "disk_read_mb": [ + 0.2, + 0.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.59, + 0.0, + 0.0, + 0.02, + 0.0, + 0.04, + 0.0, + 0.0, + 0.05, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.17, + 0.53, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.6, + 0.0, + 0.03, + 0.0, + 0.0, + 0.05, + 0.0, + 0.0, + 0.05, + 0.0, + 0.05, + 0.0, + 0.0, + 0.03, + 0.0, + 0.04, + 0.0, + 0.0, + 0.18, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790718982.302463 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-8k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-8k-1.json new file mode 100644 index 0000000..e510b11 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-8k-1.json @@ -0,0 +1,736 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "7c040dd4c6d7", + "corpus_repeated": false, + "time": "2026-09-29T21:55:06", + "prompt_tokens": 7491, + "completion_tokens": 8, + "ttft_s": 10.682, + "e2e_s": 10.776, + "api_prompt_tps": 701.3, + "api_decode_tps": 74.7, + "engine_prompt_tps": 705.0, + "engine_decode_tps": 73.1, + "log_lines": [ + "strata serve: prompt 7491 tokens = 0 reused + 7491 read in 10625 ms (705.0 tok/s), 8 generated in 109 ms (73.1 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 90.2% (3891 hits / 4313 lookups)" + ], + "answer_head": "C43C98BD", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718906.5660036, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 7491, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 10625.3, + "decode_ms": 109.4, + "decode_tok_s": 73.1, + "hit_rate": 0.902 + }, + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 4, + "totals": { + "since": 1790718725.4039552, + "requests": 4, + "prompt_tokens": 99043, + "reused": 0, + "output_tokens": 229, + "prompt_ms": 134239.3, + "decode_ms": 2358.1000000000004 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 1, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 46, + "power": 122.865 + }, + { + "index": 1, + "util": 0, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 50, + "power": 213.727 + } + ], + "gpu_util": 0.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 50, + "gpu_power": 336.592, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 19.7, + "ram_used": 70472826880, + "ram_total": 177175990272, + "disk_read_mb": 0.2018157842351215, + "disk_write_mb": 0.28470440990311785, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 25.0, + 33.5, + 47.0, + 15.5, + 32.5, + 24.0, + 32.5, + 29.0, + 55.0, + 34.0, + 48.0, + 33.0, + 22.5, + 31.5, + 24.5, + 20.0, + 20.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 37.0, + 28.0, + 22.5, + 30.0, + 37.0, + 18.0, + 29.0, + 22.0, + 21.0, + 0.5 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 51, + 50, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 50, + 52, + 52, + 52, + 51, + 52, + 52, + 50, + 49, + 49, + 49, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 45, + 45, + 45, + 45, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 50, + 49, + 51, + 51, + 51, + 51, + 50, + 51, + 52, + 50 + ], + "gpu_power": [ + 380.19, + 386.69, + 409.76, + 359.41, + 400.68, + 368.54, + 396.07, + 393.99, + 371.52, + 407.92, + 367.65, + 416.33, + 386.19, + 394.79, + 409.75, + 373.56, + 329.84, + 371.48, + 309.69, + 279.06, + 254.32, + 242.47, + 242.53, + 242.44, + 242.38, + 242.52, + 242.49, + 242.46, + 242.59, + 242.37, + 242.36, + 242.5, + 242.54, + 140.5, + 84.6, + 65.59, + 65.03, + 64.81, + 64.81, + 64.9, + 64.51, + 64.65, + 64.87, + 64.67, + 64.8, + 64.5, + 64.56, + 64.64, + 64.52, + 64.48, + 252.37, + 388.02, + 363.78, + 375.15, + 399.66, + 368.5, + 396.75, + 362.75, + 365.62, + 336.59 + ], + "gpu_pcie_rx_mb": [ + 5368.61, + 7806.78, + 7675.93, + 8469.58, + 5669.88, + 14723.06, + 5790.85, + 6188.01, + 6980.23, + 7332.23, + 12898.87, + 6754.21, + 6340.74, + 6000.61, + 6420.09, + 4455.66, + 19.74, + 0.62, + 0.62, + 0.57, + 0.67, + 0.62, + 0.62, + 0.62, + 0.67, + 0.67, + 0.67, + 0.62, + 0.62, + 0.57, + 0.62, + 0.67, + 0.71, + 0.81, + 0.81, + 0.86, + 0.81, + 0.86, + 0.81, + 0.86, + 0.76, + 0.81, + 0.86, + 0.81, + 0.95, + 0.81, + 0.86, + 0.86, + 0.86, + 0.71, + 7078.07, + 5438.42, + 7891.61, + 5618.71, + 5824.99, + 6656.5, + 6553.84, + 1295.8, + 3929.76, + 0.67 + ], + "cpu": [ + 7.3, + 17.5, + 8.0, + 7.9, + 6.6, + 6.2, + 6.2, + 6.1, + 6.6, + 5.7, + 6.8, + 7.1, + 7.8, + 6.2, + 9.8, + 15.0, + 32.2, + 20.2, + 4.3, + 11.3, + 2.0, + 1.5, + 1.4, + 3.7, + 2.4, + 2.6, + 2.2, + 1.6, + 7.0, + 7.8, + 0.8, + 3.8, + 6.2, + 1.4, + 1.5, + 1.3, + 0.5, + 0.8, + 1.4, + 1.7, + 1.4, + 1.5, + 8.2, + 9.2, + 2.9, + 5.7, + 1.3, + 5.6, + 1.2, + 7.3, + 6.3, + 9.1, + 6.4, + 7.4, + 6.7, + 6.4, + 16.3, + 9.8, + 6.3, + 19.7 + ], + "ram_used": [ + 70159552512, + 70270476288, + 70270668800, + 70271184896, + 70263926784, + 70264184832, + 70264291328, + 70265167872, + 70267035648, + 70267035648, + 70264389632, + 70261067776, + 70265782272, + 70268100608, + 70275043328, + 70091866112, + 70312075264, + 70311395328, + 70465576960, + 70613889024, + 70610006016, + 70609461248, + 70616137728, + 70634639360, + 70632943616, + 70619291648, + 70622433280, + 70624546816, + 70651342848, + 70754201600, + 70754394112, + 70772871168, + 70811869184, + 70806048768, + 70788648960, + 70775001088, + 70770065408, + 70761766912, + 70762528768, + 70758371328, + 70767398912, + 70768398336, + 70723190784, + 70684524544, + 70713102336, + 70694293504, + 70656102400, + 70685872128, + 70679355392, + 70251024384, + 70250827776, + 70240993280, + 70217400320, + 70216302592, + 70220156928, + 70211788800, + 70218944512, + 70240178176, + 70232375296, + 70472826880 + ], + "disk_read_mb": [ + 0.0, + 0.04, + 0.0, + 0.01, + 0.0, + 0.02, + 0.0, + 0.0, + 0.01, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.09, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.04, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.46, + 0.01, + 0.0, + 0.0, + 0.82, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.2 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.75, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790718917.804988 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-two-turn/two-turn-16k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-two-turn/two-turn-16k-1.json new file mode 100644 index 0000000..49166bd --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-two-turn/two-turn-16k-1.json @@ -0,0 +1,797 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "2fd93144a29a", + "corpus_repeated": false, + "time": "2026-09-29T21:56:47", + "prompt_tokens": 15639, + "completion_tokens": 83, + "ttft_s": 21.242, + "e2e_s": 22.071, + "api_prompt_tps": 736.2, + "api_decode_tps": 98.8, + "engine_prompt_tps": 739.4, + "engine_decode_tps": 98.3, + "log_lines": [ + "strata serve: prompt 15639 tokens = 0 reused + 15639 read in 21151 ms (739.4 tok/s), 83 generated in 844 ms (98.3 tok/s), drafts accepted 53 of 73, 1 checkpoints", + "strata serve: decode expert cache hit rate: 98.5% (48689 hits / 49415 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there.", + "turn2_ttft_s": 0.627, + "turn2_prompt_tokens": 15676, + "turn2_log_lines": [ + "strata serve: prompt 15676 tokens = 15632 reused + 44 read in 521 ms (84.4 tok/s), 64 generated in 739 ms (86.6 tok/s), drafts accepted 37 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.1% (36768 hits / 37868 lookups)" + ], + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719030.332211, + "duration_s": 1.3, + "finish": "length", + "prompt_tokens": 15676, + "reused": 15632, + "output_tokens": 64, + "engine_generated": 64, + "prompt_ms": 521.0, + "decode_ms": 739.1, + "decode_tok_s": 86.6, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790719007.7458334, + "duration_s": 22.0, + "finish": "stop", + "prompt_tokens": 15639, + "reused": 0, + "output_tokens": 83, + "engine_generated": 83, + "prompt_ms": 21150.9, + "decode_ms": 844.3, + "decode_tok_s": 98.3, + "hit_rate": 0.985 + }, + { + "projection": null, + "time": 1790718941.8879943, + "duration_s": 39.9, + "finish": "stop", + "prompt_tokens": 29827, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 39812.1, + "decode_ms": 93.1, + "decode_tok_s": 85.9, + "hit_rate": 0.962 + }, + { + "projection": null, + "time": 1790718917.8830457, + "duration_s": 23.4, + "finish": "stop", + "prompt_tokens": 17345, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 23292.2, + "decode_ms": 78.7, + "decode_tok_s": 101.7, + "hit_rate": 0.963 + }, + { + "projection": null, + "time": 1790718906.5660036, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 7491, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 10625.3, + "decode_ms": 109.4, + "decode_tok_s": 73.1, + "hit_rate": 0.902 + }, + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 8, + "totals": { + "since": 1790718725.4039552, + "requests": 8, + "prompt_tokens": 177530, + "reused": 15632, + "output_tokens": 392, + "prompt_ms": 219015.5, + "decode_ms": 4113.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 41, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 50, + "power": 209.466 + }, + { + "index": 1, + "util": 49, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 53, + "power": 186.867 + } + ], + "gpu_util": 45.0, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 396.33299999999997, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 2090.7392578125, + "gpu_pcie_tx_mb": 103.1865234375, + "cpu": 82.0, + "ram_used": 70765735936, + "ram_total": 177175990272, + "disk_read_mb": 3.548661248401337, + "disk_write_mb": 0.003595401467478558, + "tok_s": 85.02069488627261, + "tok_s_mean": 85.60127593635436 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 57.5, + 32.0, + 26.0, + 33.5, + 25.0, + 32.0, + 32.5, + 22.5, + 36.0, + 37.0, + 36.5, + 28.5, + 42.5, + 21.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 32.0, + 30.5, + 25.5, + 63.5, + 34.5, + 24.5, + 36.0, + 38.0, + 28.0, + 33.0, + 21.5, + 25.0, + 41.5, + 33.0, + 30.0, + 22.0, + 29.5, + 19.5, + 23.5, + 48.0, + 0.0, + 45.0 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 52, + 51, + 53, + 52, + 52, + 52, + 52, + 53, + 52, + 53, + 52, + 53, + 52, + 53, + 51, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 47, + 46, + 46, + 46, + 46, + 45, + 45, + 45, + 51, + 51, + 51, + 52, + 51, + 53, + 52, + 53, + 52, + 52, + 53, + 52, + 53, + 52, + 52, + 53, + 53, + 53, + 53, + 53, + 51, + 53 + ], + "gpu_power": [ + 383.68, + 395.97, + 381.79, + 371.58, + 387.34, + 367.36, + 390.18, + 377.99, + 404.54, + 406.77, + 371.21, + 404.91, + 389.57, + 358.58, + 310.16, + 278.39, + 242.88, + 242.69, + 242.56, + 242.41, + 242.25, + 242.45, + 242.44, + 242.38, + 242.25, + 242.18, + 242.52, + 242.57, + 242.25, + 242.23, + 197.61, + 110.58, + 65.55, + 65.12, + 65.0, + 65.02, + 65.01, + 64.82, + 155.28, + 410.36, + 361.72, + 382.57, + 404.0, + 377.89, + 389.35, + 407.89, + 389.48, + 386.49, + 371.41, + 379.85, + 411.79, + 387.4, + 395.89, + 369.99, + 400.03, + 390.77, + 393.61, + 354.25, + 413.98, + 396.33 + ], + "gpu_pcie_rx_mb": [ + 5715.7, + 6093.12, + 89.88, + 6215.57, + 4331.35, + 6045.63, + 5971.19, + 6178.04, + 5846.59, + 7484.53, + 5744.65, + 5095.67, + 7809.07, + 0.67, + 0.71, + 0.57, + 0.67, + 0.62, + 0.62, + 0.57, + 0.71, + 0.62, + 0.57, + 0.67, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 0.71, + 0.91, + 0.81, + 0.76, + 0.81, + 0.76, + 0.81, + 0.86, + 0.86, + 6219.24, + 5437.52, + 6447.08, + 6610.58, + 6506.2, + 88.93, + 6106.14, + 6218.53, + 5297.85, + 8021.88, + 67.85, + 4886.82, + 6395.77, + 5794.95, + 5961.99, + 92.79, + 4561.42, + 5886.93, + 4115.39, + 15.07, + 6036.38, + 2090.74 + ], + "cpu": [ + 6.2, + 6.0, + 9.3, + 6.5, + 6.1, + 6.0, + 14.5, + 11.7, + 5.6, + 8.6, + 7.7, + 6.1, + 6.7, + 6.3, + 15.2, + 4.0, + 11.7, + 1.7, + 0.8, + 1.6, + 10.1, + 8.8, + 1.8, + 3.0, + 2.0, + 1.1, + 3.9, + 2.5, + 1.2, + 1.0, + 4.4, + 2.2, + 2.1, + 1.1, + 9.2, + 4.0, + 0.7, + 12.8, + 6.2, + 7.1, + 6.6, + 6.1, + 5.7, + 6.8, + 7.9, + 5.9, + 6.1, + 7.1, + 16.6, + 14.8, + 6.4, + 6.7, + 6.6, + 7.0, + 6.5, + 7.1, + 6.4, + 44.5, + 46.9, + 82.0 + ], + "ram_used": [ + 70371860480, + 70366474240, + 70373842944, + 70374035456, + 70365605888, + 70363926528, + 70340509696, + 70341251072, + 70340546560, + 70343122944, + 70346379264, + 70347120640, + 70345048064, + 70479159296, + 70572703744, + 70652428288, + 70736793600, + 70729584640, + 70733873152, + 70729728000, + 70753632256, + 70894960640, + 70882795520, + 70887088128, + 70877409280, + 70896922624, + 70917816320, + 70944993280, + 70949908480, + 70948433920, + 70969233408, + 70968532992, + 70973911040, + 70965530624, + 70981591040, + 70982193152, + 70979321856, + 71007891456, + 70533447680, + 70536957952, + 70444630016, + 70438658048, + 70435995648, + 70428848128, + 70422986752, + 70424240128, + 70404268032, + 70411444224, + 70518763520, + 70541369344, + 70539395072, + 70538240000, + 70528540672, + 70514954240, + 70316679168, + 70304641024, + 70310481920, + 70539440128, + 70546964480, + 70765735936 + ], + "disk_read_mb": [ + 0.05, + 0.0, + 0.0, + 0.03, + 0.0, + 0.04, + 0.0, + 0.0, + 0.18, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.48, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.02, + 0.0, + 0.01, + 0.0, + 0.03, + 0.0, + 0.0, + 0.21, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.21, + 0.47, + 3.55 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 106.42, + 0.0, + 85.02 + ] + }, + "time": 1790719032.1000419 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-1.json new file mode 100644 index 0000000..443e522 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-1.json @@ -0,0 +1,648 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "e13c9cdd6797", + "corpus_repeated": false, + "time": "2026-09-29T21:52:23", + "prompt_tokens": 28315, + "completion_tokens": 84, + "ttft_s": 39.45, + "e2e_s": 40.422, + "api_prompt_tps": 717.7, + "api_decode_tps": 85.4, + "engine_prompt_tps": 720.7, + "engine_decode_tps": 83.1, + "log_lines": [ + "strata serve: prompt 28315 tokens = 0 reused + 28315 read in 39287 ms (720.7 tok/s), 84 generated in 1011 ms (83.1 tok/s), drafts accepted 56 of 67, 2 checkpoints", + "strata serve: decode expert cache hit rate: 94.9% (43073 hits / 45377 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context and find the relevant files.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790718725.4039552, + "requests": 1, + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 39, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 45, + "power": 141.739 + }, + { + "index": 1, + "util": 48, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 50, + "power": 205.268 + } + ], + "gpu_util": 43.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 50, + "gpu_power": 347.007, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 6170.3671875, + "gpu_pcie_tx_mb": 126.7900390625, + "cpu": 85.9, + "ram_used": 70739390464, + "ram_total": 177175990272, + "disk_read_mb": 3.315986845192439, + "disk_write_mb": 0.09340808014626588, + "tok_s": 93.51552437654362, + "tok_s_mean": 85.24938371584437 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 57.0, + 32.5, + 23.5, + 25.0, + 22.0, + 51.0, + 35.5, + 33.0, + 27.5, + 26.0, + 41.0, + 33.0, + 23.5, + 29.5, + 27.5, + 71.0, + 31.5, + 21.5, + 64.0, + 36.5, + 20.5, + 32.5, + 30.5, + 22.0, + 29.0, + 24.5, + 30.0, + 17.5, + 76.0, + 25.0, + 20.5, + 30.0, + 23.0, + 19.0, + 24.0, + 43.5 + ], + "gpu_mem_used": [ + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49316495360, + 49326981120, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49440227328 + ], + "gpu_temp": [ + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 42, + 44, + 47, + 46, + 49, + 47, + 49, + 49, + 49, + 49, + 48, + 49, + 48, + 48, + 49, + 48, + 48, + 50, + 48, + 48, + 48, + 48, + 49, + 48, + 48, + 49, + 48, + 50, + 49, + 49, + 51, + 48, + 50, + 48, + 49, + 50, + 50, + 50 + ], + "gpu_power": [ + 239.92, + 240.19, + 239.81, + 239.35, + 239.3, + 239.28, + 239.24, + 239.29, + 239.41, + 239.46, + 239.45, + 239.36, + 239.21, + 239.26, + 239.32, + 239.37, + 225.06, + 145.42, + 158.12, + 371.86, + 384.05, + 358.93, + 405.61, + 381.25, + 384.16, + 389.93, + 395.3, + 399.41, + 384.35, + 363.41, + 386.79, + 392.7, + 344.05, + 389.76, + 383.66, + 397.8, + 373.05, + 366.9, + 391.72, + 366.3, + 381.76, + 387.41, + 366.67, + 395.88, + 403.84, + 386.94, + 392.83, + 352.42, + 402.48, + 392.8, + 357.94, + 383.58, + 359.24, + 350.73, + 347.01 + ], + "gpu_pcie_rx_mb": [ + 0.62, + 0.67, + 0.67, + 0.62, + 0.62, + 0.57, + 0.57, + 0.57, + 0.62, + 0.67, + 0.67, + 0.62, + 0.62, + 0.62, + 0.62, + 0.62, + 0.76, + 14.92, + 6198.41, + 7236.0, + 8724.26, + 3654.86, + 5959.32, + 6449.94, + 6329.34, + 7285.26, + 4763.84, + 6812.52, + 7321.69, + 6494.14, + 5619.86, + 6789.97, + 5793.67, + 5562.64, + 2331.69, + 6177.52, + 8354.0, + 7435.75, + 4811.38, + 1.43, + 7506.18, + 7562.16, + 2886.44, + 7184.17, + 6752.54, + 7546.95, + 7499.69, + 4610.3, + 6852.1, + 6167.22, + 5107.31, + 7326.55, + 4237.65, + 0.67, + 6170.37 + ], + "cpu": [ + 100.0, + 1.4, + 1.1, + 0.9, + 1.2, + 2.3, + 0.9, + 1.3, + 9.5, + 5.4, + 6.6, + 4.7, + 1.3, + 1.2, + 1.8, + 2.0, + 0.8, + 11.3, + 10.6, + 10.4, + 5.7, + 6.8, + 17.0, + 10.2, + 8.1, + 7.1, + 6.9, + 7.6, + 9.8, + 9.9, + 5.8, + 6.7, + 11.0, + 6.0, + 9.4, + 6.2, + 15.2, + 12.9, + 8.4, + 7.2, + 10.2, + 6.1, + 10.5, + 6.4, + 6.0, + 9.0, + 7.4, + 8.9, + 6.9, + 8.7, + 15.6, + 12.0, + 6.3, + 6.8, + 85.9 + ], + "ram_used": [ + 70239571968, + 70088245248, + 70096302080, + 70097154048, + 70103457792, + 70078648320, + 70084857856, + 70088122368, + 70148214784, + 70162341888, + 70191161344, + 70190673920, + 70184566784, + 70184079360, + 70179979264, + 70173462528, + 70171906048, + 70119723008, + 70266146816, + 70263320576, + 70263308288, + 70262693888, + 70372823040, + 70378594304, + 70380400640, + 70383910912, + 70389587968, + 70366543872, + 70385344512, + 70382903296, + 70379986944, + 70372298752, + 70358667264, + 70367678464, + 70356070400, + 70353756160, + 70321405952, + 70284603392, + 70262280192, + 70387703808, + 70314864640, + 70312120320, + 70299967488, + 70299987968, + 70294355968, + 70301368320, + 70293327872, + 70290792448, + 70280925184, + 70300200960, + 70377836544, + 70448394240, + 70448910336, + 70574612480, + 70739390464 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 4.75, + 124.76, + 40.78, + 0.0, + 7.5, + 16.84, + 0.0, + 55.72, + 0.0, + 13.03, + 20.5, + 0.0, + 67.32, + 0.0, + 0.0, + 83.74, + 0.0, + 80.89, + 0.0, + 0.0, + 71.3, + 0.0, + 0.0, + 79.43, + 0.0, + 72.4, + 4.53, + 0.0, + 54.62, + 0.0, + 42.73, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 3.32 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 93.52 + ] + }, + "time": 1790718784.6773934 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-2.json new file mode 100644 index 0000000..719fcb2 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-2.json @@ -0,0 +1,707 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "f953f67441b4", + "corpus_repeated": false, + "time": "2026-09-29T21:53:04", + "prompt_tokens": 31633, + "completion_tokens": 88, + "ttft_s": 42.403, + "e2e_s": 43.165, + "api_prompt_tps": 746.0, + "api_decode_tps": 114.2, + "engine_prompt_tps": 749.3, + "engine_decode_tps": 113.3, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 42217 ms (749.3 tok/s), 88 generated in 777 ms (113.3 tok/s), drafts accepted 61 of 69, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.8% (45031 hits / 46048 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the \"last file\" being referenced.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790718725.4039552, + "requests": 2, + "prompt_tokens": 59948, + "reused": 0, + "output_tokens": 172, + "prompt_ms": 81503.2, + "decode_ms": 1787.8000000000002 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 43, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 46, + "power": 127.404 + }, + { + "index": 1, + "util": 22, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 50, + "power": 202.736 + } + ], + "gpu_util": 32.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 50, + "gpu_power": 330.14, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 50.97265625, + "gpu_pcie_tx_mb": 74.43359375, + "cpu": 47.4, + "ram_used": 70762872832, + "ram_total": 177175990272, + "disk_read_mb": 0.9085358249169909, + "disk_write_mb": 0.21546304148229034, + "tok_s": 110.51273259801776, + "tok_s_mean": 104.51731108020398 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 31.5, + 21.5, + 64.0, + 36.5, + 20.5, + 32.5, + 30.5, + 22.0, + 29.0, + 24.5, + 30.0, + 17.5, + 76.0, + 25.0, + 20.5, + 30.0, + 23.0, + 19.0, + 24.0, + 43.5, + 0.0, + 41.5, + 33.5, + 27.5, + 34.0, + 22.0, + 61.5, + 37.0, + 23.5, + 24.5, + 28.5, + 54.0, + 41.5, + 89.5, + 30.5, + 21.0, + 32.0, + 33.5, + 24.5, + 26.0, + 25.5, + 38.5, + 31.5, + 24.5, + 30.0, + 26.0, + 31.5, + 19.0, + 86.5, + 28.0, + 22.5, + 32.0, + 26.0, + 77.5, + 22.5, + 22.5, + 34.0, + 26.0, + 20.5, + 32.5 + ], + "gpu_mem_used": [ + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 49, + 48, + 48, + 49, + 48, + 50, + 49, + 49, + 51, + 48, + 50, + 48, + 49, + 50, + 50, + 50, + 47, + 48, + 48, + 50, + 49, + 50, + 49, + 49, + 50, + 49, + 50, + 49, + 50, + 51, + 49, + 50, + 50, + 49, + 50, + 50, + 51, + 50, + 49, + 50, + 49, + 51, + 49, + 50, + 51, + 49, + 50, + 50, + 51, + 52, + 50, + 50, + 50, + 51, + 52, + 50 + ], + "gpu_power": [ + 397.8, + 373.05, + 366.9, + 391.72, + 366.3, + 381.76, + 387.41, + 366.67, + 395.88, + 403.84, + 386.94, + 392.83, + 352.42, + 402.48, + 392.8, + 357.94, + 383.58, + 359.24, + 350.73, + 347.01, + 325.66, + 372.55, + 370.97, + 352.05, + 397.27, + 391.66, + 343.17, + 403.13, + 366.16, + 402.14, + 390.68, + 396.82, + 401.28, + 360.7, + 398.3, + 366.48, + 382.49, + 395.03, + 366.16, + 401.29, + 385.57, + 368.88, + 396.03, + 374.4, + 393.23, + 385.24, + 406.68, + 391.86, + 364.28, + 409.58, + 388.38, + 389.1, + 390.65, + 372.81, + 415.25, + 390.44, + 384.85, + 382.05, + 377.98, + 330.14 + ], + "gpu_pcie_rx_mb": [ + 6177.52, + 8354.0, + 7435.75, + 4811.38, + 1.43, + 7506.18, + 7562.16, + 2886.44, + 7184.17, + 6752.54, + 7546.95, + 7499.69, + 4610.3, + 6852.1, + 6167.22, + 5107.31, + 7326.55, + 4237.65, + 0.67, + 6170.37, + 5107.54, + 5192.28, + 6336.26, + 3422.45, + 4911.8, + 7759.14, + 6146.0, + 4671.1, + 9668.92, + 5712.17, + 6061.89, + 4888.06, + 5886.08, + 9090.42, + 5683.33, + 6294.68, + 7625.39, + 4995.82, + 12979.6, + 4392.43, + 6062.41, + 5581.95, + 5691.53, + 8234.83, + 8344.89, + 7880.73, + 6094.07, + 8294.58, + 5858.85, + 5465.17, + 6922.82, + 4432.29, + 6296.59, + 5837.44, + 7103.97, + 7604.84, + 4756.35, + 4899.02, + 5517.96, + 50.97 + ], + "cpu": [ + 6.2, + 15.2, + 12.9, + 8.4, + 7.2, + 10.2, + 6.1, + 10.5, + 6.4, + 6.0, + 9.0, + 7.4, + 8.9, + 6.9, + 8.7, + 15.6, + 12.0, + 6.3, + 6.8, + 85.9, + 9.8, + 9.7, + 6.7, + 6.6, + 6.8, + 7.4, + 7.1, + 7.1, + 12.2, + 13.8, + 6.7, + 8.5, + 6.5, + 6.1, + 6.4, + 6.5, + 6.1, + 7.2, + 6.6, + 7.4, + 6.1, + 6.8, + 12.8, + 11.1, + 6.2, + 6.4, + 6.4, + 6.1, + 6.3, + 8.7, + 7.4, + 9.4, + 6.3, + 7.9, + 6.5, + 6.4, + 15.4, + 9.4, + 6.3, + 47.4 + ], + "ram_used": [ + 70353756160, + 70321405952, + 70284603392, + 70262280192, + 70387703808, + 70314864640, + 70312120320, + 70299967488, + 70299987968, + 70294355968, + 70301368320, + 70293327872, + 70290792448, + 70280925184, + 70300200960, + 70377836544, + 70448394240, + 70448910336, + 70574612480, + 70739390464, + 70512533504, + 70533234688, + 70513684480, + 70496215040, + 70484873216, + 70469386240, + 70452416512, + 70445555712, + 70424002560, + 70434533376, + 70424702976, + 70408409088, + 70395523072, + 70388035584, + 70353256448, + 70333558784, + 70326820864, + 70357315584, + 70361923584, + 70355750912, + 70357520384, + 70490038272, + 70530985984, + 70524338176, + 70524243968, + 70525259776, + 70528827392, + 70526148608, + 70526631936, + 70541975552, + 70541778944, + 70536822784, + 70537621504, + 70537134080, + 70534877184, + 70532685824, + 70529556480, + 70530998272, + 70534545408, + 70762872832 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 71.3, + 0.0, + 0.0, + 79.43, + 0.0, + 72.4, + 4.53, + 0.0, + 54.62, + 0.0, + 42.73, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 3.32, + 0.6, + 0.01, + 0.0, + 0.01, + 0.0, + 0.0, + 0.02, + 0.0, + 0.02, + 0.0, + 0.0, + 0.03, + 0.0, + 0.03, + 0.0, + 0.0, + 0.73, + 0.0, + 0.01, + 0.0, + 0.0, + 0.01, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 12.58, + 0.0, + 0.0, + 71.88, + 0.0, + 33.04, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.91 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 93.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 110.51 + ] + }, + "time": 1790718828.3451 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-3.json new file mode 100644 index 0000000..8acc53d --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-3.json @@ -0,0 +1,721 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "4e71f26e7fd8", + "corpus_repeated": false, + "time": "2026-09-29T21:53:48", + "prompt_tokens": 31604, + "completion_tokens": 49, + "ttft_s": 42.269, + "e2e_s": 42.716, + "api_prompt_tps": 747.7, + "api_decode_tps": 107.5, + "engine_prompt_tps": 750.5, + "engine_decode_tps": 106.3, + "log_lines": [ + "strata serve: prompt 31604 tokens = 0 reused + 31604 read in 42111 ms (750.5 tok/s), 49 generated in 461 ms (106.3 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (26163 hits / 26396 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the \"last file\" being referenced.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790718725.4039552, + "requests": 3, + "prompt_tokens": 91552, + "reused": 0, + "output_tokens": 221, + "prompt_ms": 123614.0, + "decode_ms": 2248.7000000000003 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 39, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 47, + "power": 127.526 + }, + { + "index": 1, + "util": 2, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 50, + "power": 202.315 + } + ], + "gpu_util": 20.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 50, + "gpu_power": 329.841, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 19.740234375, + "gpu_pcie_tx_mb": 54.21484375, + "cpu": 32.2, + "ram_used": 70312075264, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.09328657441898458, + "tok_s": 97.74566314411967, + "tok_s_mean": 97.74268443960047 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 25.5, + 38.5, + 31.5, + 24.5, + 30.0, + 26.0, + 31.5, + 19.0, + 86.5, + 28.0, + 22.5, + 32.0, + 26.0, + 77.5, + 22.5, + 22.5, + 34.0, + 26.0, + 20.5, + 32.5, + 0.0, + 36.5, + 37.0, + 26.0, + 32.0, + 37.0, + 24.0, + 32.5, + 20.5, + 29.0, + 25.0, + 27.5, + 30.5, + 24.0, + 35.0, + 28.5, + 29.0, + 30.0, + 29.5, + 33.5, + 44.5, + 55.5, + 36.0, + 25.0, + 33.5, + 47.0, + 15.5, + 32.5, + 24.0, + 32.5, + 29.0, + 55.0, + 34.0, + 48.0, + 33.0, + 22.5, + 31.5, + 24.5, + 20.0, + 20.5 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 51, + 50, + 49, + 50, + 49, + 51, + 49, + 50, + 51, + 49, + 50, + 50, + 51, + 52, + 50, + 50, + 50, + 51, + 52, + 50, + 49, + 49, + 49, + 51, + 50, + 50, + 50, + 50, + 51, + 50, + 50, + 51, + 50, + 51, + 50, + 51, + 51, + 50, + 52, + 50, + 51, + 50, + 50, + 51, + 50, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 50, + 52, + 52, + 52, + 51, + 52, + 52, + 50 + ], + "gpu_power": [ + 385.57, + 368.88, + 396.03, + 374.4, + 393.23, + 385.24, + 406.68, + 391.86, + 364.28, + 409.58, + 388.38, + 389.1, + 390.65, + 372.81, + 415.25, + 390.44, + 384.85, + 382.05, + 377.98, + 330.14, + 415.76, + 348.22, + 407.06, + 354.03, + 392.05, + 392.72, + 370.96, + 399.97, + 402.84, + 387.68, + 394.33, + 359.55, + 419.05, + 403.04, + 384.68, + 390.64, + 393.93, + 389.6, + 362.93, + 373.48, + 405.22, + 378.6, + 399.07, + 380.19, + 386.69, + 409.76, + 359.41, + 400.68, + 368.54, + 396.07, + 393.99, + 371.52, + 407.92, + 367.65, + 416.33, + 386.19, + 394.79, + 409.75, + 373.56, + 329.84 + ], + "gpu_pcie_rx_mb": [ + 6062.41, + 5581.95, + 5691.53, + 8234.83, + 8344.89, + 7880.73, + 6094.07, + 8294.58, + 5858.85, + 5465.17, + 6922.82, + 4432.29, + 6296.59, + 5837.44, + 7103.97, + 7604.84, + 4756.35, + 4899.02, + 5517.96, + 50.97, + 0.67, + 11557.34, + 5125.33, + 6536.1, + 6042.86, + 7341.43, + 5299.47, + 6137.51, + 6431.72, + 5859.47, + 4887.1, + 5919.46, + 5763.62, + 94.17, + 6438.59, + 7535.84, + 6171.89, + 7355.36, + 4306.32, + 5857.37, + 4681.59, + 5568.03, + 5823.33, + 5368.61, + 7806.78, + 7675.93, + 8469.58, + 5669.88, + 14723.06, + 5790.85, + 6188.01, + 6980.23, + 7332.23, + 12898.87, + 6754.21, + 6340.74, + 6000.61, + 6420.09, + 4455.66, + 19.74 + ], + "cpu": [ + 6.1, + 6.8, + 12.8, + 11.1, + 6.2, + 6.4, + 6.4, + 6.1, + 6.3, + 8.7, + 7.4, + 9.4, + 6.3, + 7.9, + 6.5, + 6.4, + 15.4, + 9.4, + 6.3, + 47.4, + 36.1, + 6.3, + 6.7, + 6.6, + 5.7, + 7.4, + 6.2, + 7.4, + 6.0, + 6.6, + 15.5, + 14.6, + 5.8, + 6.4, + 6.5, + 6.2, + 11.6, + 8.8, + 7.8, + 6.2, + 6.9, + 6.0, + 5.5, + 7.3, + 17.5, + 8.0, + 7.9, + 6.6, + 6.2, + 6.2, + 6.1, + 6.6, + 5.7, + 6.8, + 7.1, + 7.8, + 6.2, + 9.8, + 15.0, + 32.2 + ], + "ram_used": [ + 70357520384, + 70490038272, + 70530985984, + 70524338176, + 70524243968, + 70525259776, + 70528827392, + 70526148608, + 70526631936, + 70541975552, + 70541778944, + 70536822784, + 70537621504, + 70537134080, + 70534877184, + 70532685824, + 70529556480, + 70530998272, + 70534545408, + 70762872832, + 70460293120, + 70452703232, + 70444961792, + 70428729344, + 70420193280, + 70418821120, + 70406471680, + 70396342272, + 70389112832, + 70380965888, + 70312722432, + 70348423168, + 70338981888, + 70328791040, + 70326034432, + 70312820736, + 70085947392, + 69987848192, + 70072119296, + 70060589056, + 70056861696, + 70179471360, + 70176550912, + 70159552512, + 70270476288, + 70270668800, + 70271184896, + 70263926784, + 70264184832, + 70264291328, + 70265167872, + 70267035648, + 70267035648, + 70264389632, + 70261067776, + 70265782272, + 70268100608, + 70275043328, + 70091866112, + 70312075264 + ], + "disk_read_mb": [ + 0.0, + 0.01, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 12.58, + 0.0, + 0.0, + 71.88, + 0.0, + 33.04, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.91, + 0.83, + 0.04, + 0.0, + 0.0, + 0.01, + 0.0, + 0.03, + 0.0, + 0.0, + 0.03, + 0.0, + 0.05, + 0.0, + 0.0, + 0.04, + 0.0, + 0.04, + 0.0, + 0.04, + 0.0, + 0.0, + 0.04, + 0.0, + 0.0, + 0.04, + 0.0, + 0.01, + 0.0, + 0.02, + 0.0, + 0.0, + 0.01, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 110.51, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.75 + ] + }, + "time": 1790718871.5639336 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-16k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-16k-1.json new file mode 100644 index 0000000..2a76a65 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-16k-1.json @@ -0,0 +1,830 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "e39790e5649d", + "corpus_repeated": false, + "time": "2026-09-29T20:47:57", + "prompt_tokens": 17346, + "completion_tokens": 8, + "ttft_s": 9.075, + "e2e_s": 9.178, + "api_prompt_tps": 1911.3, + "api_decode_tps": 68.2, + "engine_prompt_tps": 1933.6, + "engine_decode_tps": 67.4, + "log_lines": [ + "strata serve: prompt 17346 tokens = 0 reused + 17346 read in 8971 ms (1933.6 tok/s), 8 generated in 119 ms (67.4 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 80.6% (3014 hits / 3740 lookups)" + ], + "answer_head": "37E3DB14", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714877.4157934, + "duration_s": 9.1, + "finish": "stop", + "prompt_tokens": 17346, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 8971.0, + "decode_ms": 118.7, + "decode_tok_s": 67.4, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714872.57582, + "duration_s": 4.3, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 4124.7, + "decode_ms": 123.2, + "decode_tok_s": 64.9, + "hit_rate": 0.748 + }, + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + } + ], + "requests_kept": 24, + "totals": { + "since": 1790713882.6043305, + "requests": 24, + "prompt_tokens": 631825, + "reused": 0, + "output_tokens": 4662, + "prompt_ms": 302982.9, + "decode_ms": 55029.19999999998 + }, + "hardware": { + "gpu_util": 100, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 49, + "gpu_power": 265.798, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 22367.23828125, + "gpu_pcie_tx_mb": 80.8232421875, + "cpu": 6.2, + "ram_used": 63624777728, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.31474488451743216, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 99, + 100, + 0, + 100, + 99, + 99, + 100, + 100, + 99, + 90, + 100 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 46, + 45, + 45, + 44, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 42, + 42, + 42, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 47, + 48, + 49, + 49, + 46, + 49, + 49, + 48, + 49, + 49, + 49, + 48, + 49 + ], + "gpu_power": [ + 162.82, + 148.08, + 135.02, + 121.86, + 121.63, + 121.78, + 121.51, + 121.24, + 121.16, + 121.27, + 121.24, + 121.23, + 121.05, + 121.06, + 121.26, + 121.23, + 101.81, + 59.35, + 35.84, + 35.18, + 35.01, + 35.2, + 35.0, + 34.94, + 35.11, + 35.02, + 35.03, + 35.11, + 34.94, + 34.9, + 35.04, + 35.01, + 35.02, + 35.13, + 34.98, + 34.93, + 35.03, + 34.9, + 34.91, + 35.06, + 34.94, + 34.94, + 35.11, + 35.01, + 35.09, + 34.99, + 34.98, + 69.69, + 278.48, + 278.38, + 276.27, + 201.82, + 237.39, + 277.05, + 276.41, + 278.18, + 277.05, + 276.73, + 274.45, + 265.8 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.38, + 0.33, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.43, + 0.43, + 0.43, + 0.43, + 0.48, + 0.52, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.57, + 0.43, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.48, + 0.43, + 0.43, + 0.67, + 0.43, + 0.43, + 0.43, + 0.43, + 12932.54, + 9.63, + 46.83, + 24945.45, + 2343.61, + 13238.91, + 26700.59, + 116.78, + 454.76, + 16.55, + 25179.15, + 16555.31, + 22367.24 + ], + "cpu": [ + 1.7, + 6.8, + 2.8, + 2.2, + 1.5, + 0.9, + 1.8, + 5.2, + 2.3, + 5.5, + 8.8, + 1.8, + 3.7, + 1.8, + 2.8, + 1.4, + 3.7, + 3.3, + 1.7, + 1.3, + 4.2, + 1.2, + 1.6, + 1.7, + 9.9, + 2.6, + 0.5, + 2.0, + 1.8, + 2.4, + 1.5, + 0.8, + 1.6, + 1.2, + 0.7, + 1.6, + 1.6, + 2.3, + 9.4, + 4.7, + 1.1, + 3.5, + 10.5, + 1.6, + 1.2, + 1.3, + 4.9, + 9.2, + 6.2, + 7.5, + 8.5, + 22.5, + 12.5, + 14.4, + 12.6, + 8.8, + 6.5, + 7.5, + 6.4, + 6.2 + ], + "ram_used": [ + 64108949504, + 64264835072, + 64269873152, + 64217538560, + 64220250112, + 64209580032, + 64204328960, + 64140402688, + 64131928064, + 64163700736, + 64240553984, + 64240898048, + 64248393728, + 64243052544, + 64234790912, + 64233521152, + 64232390656, + 64308101120, + 64309403648, + 64297762816, + 64329601024, + 64305721344, + 64307060736, + 64304783360, + 64363835392, + 64356347904, + 64354099200, + 64356909056, + 64359067648, + 64329744384, + 64330743808, + 64332496896, + 64325115904, + 64319610880, + 64320966656, + 64320552960, + 64315297792, + 64318357504, + 64285126656, + 64085762048, + 64088686592, + 64091111424, + 64247578624, + 64251699200, + 64241737728, + 64244289536, + 64283144192, + 63581208576, + 63583793152, + 63583657984, + 63716282368, + 63680327680, + 63688806400, + 63692079104, + 63653728256, + 63611449344, + 63604965376, + 63573368832, + 63636836352, + 63624777728 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 59.38, + 0.0, + 0.0, + 0.0, + 34.69, + 51.95, + 0.0, + 0.0, + 11.38, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790714887.0144231 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-28k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-28k-1.json new file mode 100644 index 0000000..507bd18 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-28k-1.json @@ -0,0 +1,830 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "94aa92e58ada", + "corpus_repeated": false, + "time": "2026-09-29T20:48:07", + "prompt_tokens": 29820, + "completion_tokens": 8, + "ttft_s": 14.138, + "e2e_s": 14.241, + "api_prompt_tps": 2109.2, + "api_decode_tps": 68.2, + "engine_prompt_tps": 2134.7, + "engine_decode_tps": 66.5, + "log_lines": [ + "strata serve: prompt 29820 tokens = 0 reused + 29820 read in 13969 ms (2134.7 tok/s), 8 generated in 120 ms (66.5 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 80.6% (3033 hits / 3764 lookups)" + ], + "answer_head": "64EC0999", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714887.1579242, + "duration_s": 14.1, + "finish": "stop", + "prompt_tokens": 29820, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 13969.3, + "decode_ms": 120.3, + "decode_tok_s": 66.5, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714877.4157934, + "duration_s": 9.1, + "finish": "stop", + "prompt_tokens": 17346, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 8971.0, + "decode_ms": 118.7, + "decode_tok_s": 67.4, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714872.57582, + "duration_s": 4.3, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 4124.7, + "decode_ms": 123.2, + "decode_tok_s": 64.9, + "hit_rate": 0.748 + }, + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + } + ], + "requests_kept": 25, + "totals": { + "since": 1790713882.6043305, + "requests": 25, + "prompt_tokens": 661645, + "reused": 0, + "output_tokens": 4670, + "prompt_ms": 316952.2, + "decode_ms": 55149.499999999985 + }, + "hardware": { + "gpu_util": 99, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 49, + "gpu_power": 278.531, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 86.068359375, + "gpu_pcie_tx_mb": 76.1982421875, + "cpu": 6.7, + "ram_used": 63515471872, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.08241686128693117, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 99, + 100, + 0, + 100, + 99, + 99, + 100, + 100, + 99, + 90, + 100, + 0, + 99, + 99, + 100, + 96, + 100, + 99, + 99, + 99, + 100, + 99, + 100, + 99, + 99 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 44, + 44, + 42, + 42, + 42, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 47, + 48, + 49, + 49, + 46, + 49, + 49, + 48, + 49, + 49, + 49, + 48, + 49, + 46, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49 + ], + "gpu_power": [ + 121.26, + 121.23, + 101.81, + 59.35, + 35.84, + 35.18, + 35.01, + 35.2, + 35.0, + 34.94, + 35.11, + 35.02, + 35.03, + 35.11, + 34.94, + 34.9, + 35.04, + 35.01, + 35.02, + 35.13, + 34.98, + 34.93, + 35.03, + 34.9, + 34.91, + 35.06, + 34.94, + 34.94, + 35.11, + 35.01, + 35.09, + 34.99, + 34.98, + 69.69, + 278.48, + 278.38, + 276.27, + 201.82, + 237.39, + 277.05, + 276.41, + 278.18, + 277.05, + 276.73, + 274.45, + 265.8, + 225.08, + 215.47, + 277.53, + 277.2, + 277.77, + 276.7, + 277.63, + 275.8, + 266.11, + 275.21, + 277.53, + 275.92, + 279.07, + 278.53 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.43, + 0.43, + 0.43, + 0.43, + 0.48, + 0.52, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.57, + 0.43, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.48, + 0.43, + 0.43, + 0.67, + 0.43, + 0.43, + 0.43, + 0.43, + 12932.54, + 9.63, + 46.83, + 24945.45, + 2343.61, + 13238.91, + 26700.59, + 116.78, + 454.76, + 16.55, + 25179.15, + 16555.31, + 22367.24, + 0.29, + 6039.81, + 15.31, + 2050.78, + 8.77, + 51.02, + 14.83, + 11.11, + 14.88, + 25541.35, + 21966.98, + 22781.28, + 20080.71, + 86.07 + ], + "cpu": [ + 2.8, + 1.4, + 3.7, + 3.3, + 1.7, + 1.3, + 4.2, + 1.2, + 1.6, + 1.7, + 9.9, + 2.6, + 0.5, + 2.0, + 1.8, + 2.4, + 1.5, + 0.8, + 1.6, + 1.2, + 0.7, + 1.6, + 1.6, + 2.3, + 9.4, + 4.7, + 1.1, + 3.5, + 10.5, + 1.6, + 1.2, + 1.3, + 4.9, + 9.2, + 6.2, + 7.5, + 8.5, + 22.5, + 12.5, + 14.4, + 12.6, + 8.8, + 6.5, + 7.5, + 6.4, + 6.2, + 20.7, + 7.5, + 5.6, + 6.7, + 10.9, + 6.4, + 7.2, + 16.4, + 12.9, + 5.7, + 8.2, + 6.5, + 6.1, + 6.7 + ], + "ram_used": [ + 64234790912, + 64233521152, + 64232390656, + 64308101120, + 64309403648, + 64297762816, + 64329601024, + 64305721344, + 64307060736, + 64304783360, + 64363835392, + 64356347904, + 64354099200, + 64356909056, + 64359067648, + 64329744384, + 64330743808, + 64332496896, + 64325115904, + 64319610880, + 64320966656, + 64320552960, + 64315297792, + 64318357504, + 64285126656, + 64085762048, + 64088686592, + 64091111424, + 64247578624, + 64251699200, + 64241737728, + 64244289536, + 64283144192, + 63581208576, + 63583793152, + 63583657984, + 63716282368, + 63680327680, + 63688806400, + 63692079104, + 63653728256, + 63611449344, + 63604965376, + 63573368832, + 63636836352, + 63624777728, + 63754727424, + 63698673664, + 63690715136, + 63681667072, + 63675179008, + 63536058368, + 63521837056, + 63517446144, + 63523024896, + 63518388224, + 63517155328, + 63521734656, + 63516585984, + 63515471872 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 59.38, + 0.0, + 0.0, + 0.0, + 34.69, + 51.95, + 0.0, + 0.0, + 11.38, + 0.0, + 0.0, + 0.0, + 0.0, + 0.11, + 4.58, + 0.0, + 0.0, + 97.16, + 0.0, + 0.0, + 0.0, + 52.31, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790714901.7591343 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-8k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-8k-1.json new file mode 100644 index 0000000..844f1d0 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-8k-1.json @@ -0,0 +1,830 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "3c83d69c2581", + "corpus_repeated": false, + "time": "2026-09-29T20:47:52", + "prompt_tokens": 7493, + "completion_tokens": 8, + "ttft_s": 4.2, + "e2e_s": 4.307, + "api_prompt_tps": 1783.9, + "api_decode_tps": 65.8, + "engine_prompt_tps": 1816.6, + "engine_decode_tps": 64.9, + "log_lines": [ + "strata serve: prompt 7493 tokens = 0 reused + 7493 read in 4125 ms (1816.6 tok/s), 8 generated in 123 ms (64.9 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 74.8% (2704 hits / 3615 lookups)" + ], + "answer_head": "0E6415FF", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714872.57582, + "duration_s": 4.3, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 4124.7, + "decode_ms": 123.2, + "decode_tok_s": 64.9, + "hit_rate": 0.748 + }, + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + } + ], + "requests_kept": 23, + "totals": { + "since": 1790713882.6043305, + "requests": 23, + "prompt_tokens": 614479, + "reused": 0, + "output_tokens": 4654, + "prompt_ms": 294011.9, + "decode_ms": 54910.499999999985 + }, + "hardware": { + "gpu_util": 100, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 49, + "gpu_power": 276.273, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 24945.44921875, + "gpu_pcie_tx_mb": 2986.287109375, + "cpu": 8.5, + "ram_used": 63716282368, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 100, + 99, + 100, + 99, + 99, + 85, + 91, + 96, + 95, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 99, + 100 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 46, + 45, + 45, + 44, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 42, + 42, + 42, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 47, + 48, + 49, + 49 + ], + "gpu_power": [ + 277.85, + 276.09, + 278.51, + 279.06, + 278.13, + 239.73, + 262.71, + 270.73, + 273.54, + 162.82, + 148.08, + 135.02, + 121.86, + 121.63, + 121.78, + 121.51, + 121.24, + 121.16, + 121.27, + 121.24, + 121.23, + 121.05, + 121.06, + 121.26, + 121.23, + 101.81, + 59.35, + 35.84, + 35.18, + 35.01, + 35.2, + 35.0, + 34.94, + 35.11, + 35.02, + 35.03, + 35.11, + 34.94, + 34.9, + 35.04, + 35.01, + 35.02, + 35.13, + 34.98, + 34.93, + 35.03, + 34.9, + 34.91, + 35.06, + 34.94, + 34.94, + 35.11, + 35.01, + 35.09, + 34.99, + 34.98, + 69.69, + 278.48, + 278.38, + 276.27 + ], + "gpu_pcie_rx_mb": [ + 12025.83, + 22118.66, + 18928.05, + 18.36, + 86.12, + 284.24, + 9240.67, + 7805.97, + 0.29, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.38, + 0.33, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.43, + 0.43, + 0.43, + 0.43, + 0.48, + 0.52, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.57, + 0.43, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.48, + 0.43, + 0.43, + 0.67, + 0.43, + 0.43, + 0.43, + 0.43, + 12932.54, + 9.63, + 46.83, + 24945.45 + ], + "cpu": [ + 8.2, + 6.7, + 6.2, + 6.0, + 13.2, + 64.5, + 99.9, + 99.0, + 86.8, + 1.7, + 6.8, + 2.8, + 2.2, + 1.5, + 0.9, + 1.8, + 5.2, + 2.3, + 5.5, + 8.8, + 1.8, + 3.7, + 1.8, + 2.8, + 1.4, + 3.7, + 3.3, + 1.7, + 1.3, + 4.2, + 1.2, + 1.6, + 1.7, + 9.9, + 2.6, + 0.5, + 2.0, + 1.8, + 2.4, + 1.5, + 0.8, + 1.6, + 1.2, + 0.7, + 1.6, + 1.6, + 2.3, + 9.4, + 4.7, + 1.1, + 3.5, + 10.5, + 1.6, + 1.2, + 1.3, + 4.9, + 9.2, + 6.2, + 7.5, + 8.5 + ], + "ram_used": [ + 64100171776, + 64087904256, + 64069447680, + 64067096576, + 64095731712, + 64224346112, + 64185745408, + 64170352640, + 64157536256, + 64108949504, + 64264835072, + 64269873152, + 64217538560, + 64220250112, + 64209580032, + 64204328960, + 64140402688, + 64131928064, + 64163700736, + 64240553984, + 64240898048, + 64248393728, + 64243052544, + 64234790912, + 64233521152, + 64232390656, + 64308101120, + 64309403648, + 64297762816, + 64329601024, + 64305721344, + 64307060736, + 64304783360, + 64363835392, + 64356347904, + 64354099200, + 64356909056, + 64359067648, + 64329744384, + 64330743808, + 64332496896, + 64325115904, + 64319610880, + 64320966656, + 64320552960, + 64315297792, + 64318357504, + 64285126656, + 64085762048, + 64088686592, + 64091111424, + 64247578624, + 64251699200, + 64241737728, + 64244289536, + 64283144192, + 63581208576, + 63583793152, + 63583657984, + 63716282368 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.89, + 2.52, + 3.25, + 2.83, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 59.38, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 61.23, + 76.01, + 95.36, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790714877.3325372 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-two-turn/two-turn-16k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-two-turn/two-turn-16k-1.json new file mode 100644 index 0000000..2b88fb6 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-two-turn/two-turn-16k-1.json @@ -0,0 +1,835 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "7aed17dd03cd", + "corpus_repeated": false, + "time": "2026-09-29T20:48:48", + "prompt_tokens": 15636, + "completion_tokens": 256, + "ttft_s": 7.488, + "e2e_s": 10.882, + "api_prompt_tps": 2088.0, + "api_decode_tps": 75.1, + "engine_prompt_tps": 2114.8, + "engine_decode_tps": 75.1, + "log_lines": [ + "strata serve: prompt 15636 tokens = 0 reused + 15636 read in 7394 ms (2114.8 tok/s), 256 generated in 3410 ms (75.1 tok/s), drafts accepted 152 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 93.0% (136865 hits / 147168 lookups)" + ], + "answer_head": "## What `README.md` does\n\n`README.md` is the project's landing page and primary user-facing documentation. It serves several purposes:\n\n1. **Marketing/overview** \u2014 Opens with a headline claim (\"Run a 125-billion-parameter AI model on a normal gaming PC\") and a visual demo (the pagoda video) to immed", + "turn2_ttft_s": 0.438, + "turn2_prompt_tokens": 15915, + "turn2_log_lines": [ + "strata serve: prompt 15915 tokens = 15892 reused + 23 read in 332 ms (69.3 tok/s), 46 generated in 661 ms (69.6 tok/s), drafts accepted 27 of 44, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.4% (29047 hits / 30124 lookups)" + ], + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714939.7647502, + "duration_s": 1.0, + "finish": "stop", + "prompt_tokens": 15915, + "reused": 15892, + "output_tokens": 46, + "engine_generated": 46, + "prompt_ms": 331.9, + "decode_ms": 660.8, + "decode_tok_s": 69.6, + "hit_rate": 0.964 + }, + { + "projection": null, + "time": 1790714928.3706348, + "duration_s": 10.8, + "finish": "length", + "prompt_tokens": 15636, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 7393.6, + "decode_ms": 3409.5, + "decode_tok_s": 75.1, + "hit_rate": 0.93 + }, + { + "projection": null, + "time": 1790714887.1579242, + "duration_s": 14.1, + "finish": "stop", + "prompt_tokens": 29820, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 13969.3, + "decode_ms": 120.3, + "decode_tok_s": 66.5, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714877.4157934, + "duration_s": 9.1, + "finish": "stop", + "prompt_tokens": 17346, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 8971.0, + "decode_ms": 118.7, + "decode_tok_s": 67.4, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714872.57582, + "duration_s": 4.3, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 4124.7, + "decode_ms": 123.2, + "decode_tok_s": 64.9, + "hit_rate": 0.748 + }, + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + } + ], + "requests_kept": 27, + "totals": { + "since": 1790713882.6043305, + "requests": 27, + "prompt_tokens": 693196, + "reused": 15892, + "output_tokens": 4972, + "prompt_ms": 324677.7, + "decode_ms": 59219.79999999999 + }, + "hardware": { + "gpu_util": 94, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 48, + "gpu_power": 197.275, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 822.3525390625, + "gpu_pcie_tx_mb": 183.15234375, + "cpu": 52.4, + "ram_used": 63860678656, + "ram_total": 177175990272, + "disk_read_mb": 1.1632307226246328, + "disk_write_mb": 0.2954830452969325, + "tok_s": 50.58164583911189, + "tok_s_mean": 50.57911214220715 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 100, + 99, + 99, + 100, + 100, + 99, + 90, + 100, + 0, + 99, + 99, + 100, + 96, + 100, + 99, + 99, + 99, + 100, + 99, + 100, + 99, + 99, + 96, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 99, + 100, + 99, + 99, + 100, + 100, + 100, + 95, + 97, + 93, + 94 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 49, + 49, + 48, + 49, + 49, + 49, + 48, + 49, + 46, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 46, + 45, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 42, + 42, + 42, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 47, + 49, + 49, + 49, + 49, + 49, + 49, + 47, + 48, + 49, + 49, + 48 + ], + "gpu_power": [ + 237.39, + 277.05, + 276.41, + 278.18, + 277.05, + 276.73, + 274.45, + 265.8, + 225.08, + 215.47, + 277.53, + 277.2, + 277.77, + 276.7, + 277.63, + 275.8, + 266.11, + 275.21, + 277.53, + 275.92, + 279.07, + 278.53, + 241.13, + 171.76, + 147.92, + 134.65, + 121.43, + 121.4, + 121.36, + 121.31, + 121.11, + 121.03, + 121.2, + 121.14, + 120.8, + 121.02, + 121.17, + 121.22, + 102.94, + 60.93, + 36.12, + 35.26, + 35.35, + 35.31, + 35.23, + 35.08, + 35.09, + 35.22, + 69.73, + 277.07, + 276.87, + 276.87, + 278.61, + 277.22, + 278.12, + 247.41, + 259.45, + 271.65, + 275.28, + 197.28 + ], + "gpu_pcie_rx_mb": [ + 13238.91, + 26700.59, + 116.78, + 454.76, + 16.55, + 25179.15, + 16555.31, + 22367.24, + 0.29, + 6039.81, + 15.31, + 2050.78, + 8.77, + 51.02, + 14.83, + 11.11, + 14.88, + 25541.35, + 21966.98, + 22781.28, + 20080.71, + 86.07, + 0.33, + 0.29, + 0.29, + 0.33, + 0.33, + 0.29, + 0.33, + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.43, + 0.33, + 0.33, + 0.29, + 0.33, + 0.38, + 0.43, + 0.38, + 0.43, + 0.38, + 0.43, + 0.43, + 0.38, + 0.43, + 7494.78, + 15213.11, + 13.83, + 86.31, + 6.25, + 4.48, + 7.34, + 1956.56, + 3779.22, + 10756.4, + 0.33, + 822.35 + ], + "cpu": [ + 12.5, + 14.4, + 12.6, + 8.8, + 6.5, + 7.5, + 6.4, + 6.2, + 20.7, + 7.5, + 5.6, + 6.7, + 10.9, + 6.4, + 7.2, + 16.4, + 12.9, + 5.7, + 8.2, + 6.5, + 6.1, + 6.7, + 20.8, + 2.1, + 8.1, + 1.0, + 2.4, + 4.3, + 1.2, + 15.4, + 6.0, + 0.7, + 1.7, + 1.9, + 1.9, + 1.8, + 1.1, + 2.0, + 2.0, + 1.3, + 1.6, + 1.5, + 3.7, + 3.2, + 9.8, + 1.4, + 4.8, + 1.6, + 8.9, + 6.6, + 7.0, + 5.9, + 5.6, + 7.0, + 10.7, + 49.0, + 100.0, + 99.6, + 87.8, + 52.4 + ], + "ram_used": [ + 63688806400, + 63692079104, + 63653728256, + 63611449344, + 63604965376, + 63573368832, + 63636836352, + 63624777728, + 63754727424, + 63698673664, + 63690715136, + 63681667072, + 63675179008, + 63536058368, + 63521837056, + 63517446144, + 63523024896, + 63518388224, + 63517155328, + 63521734656, + 63516585984, + 63515471872, + 63598735360, + 63575552000, + 63746940928, + 63743287296, + 63744950272, + 63746498560, + 63748960256, + 63781244928, + 63777951744, + 63778541568, + 63778627584, + 63784894464, + 63788924928, + 63789916160, + 63785603072, + 63778463744, + 63786168320, + 63781711872, + 63785504768, + 63775502336, + 63798136832, + 63833931776, + 63825649664, + 63827275776, + 63826427904, + 63833698304, + 63620595712, + 63618826240, + 63602626560, + 63602855936, + 63603830784, + 63609753600, + 63610949632, + 63683670016, + 63692382208, + 63679488000, + 63682031616, + 63860678656 + ], + "disk_read_mb": [ + 51.95, + 0.0, + 0.0, + 11.38, + 0.0, + 0.0, + 0.0, + 0.0, + 0.11, + 4.58, + 0.0, + 0.0, + 97.16, + 0.0, + 0.0, + 0.0, + 52.31, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.41, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.29, + 3.18, + 2.31, + 2.73, + 1.16 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 68.59, + 62.69, + 101.15, + 0.0, + 50.58 + ] + }, + "time": 1790714941.2661076 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-1.json new file mode 100644 index 0000000..ffcfe8e --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-1.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 1, + "run_id": "183f9c0b2a25", + "corpus_repeated": false, + "time": "2026-09-29T20:43:56", + "prompt_tokens": 119256, + "completion_tokens": 256, + "ttft_s": 55.136, + "e2e_s": 58.347, + "api_prompt_tps": 2162.9, + "api_decode_tps": 79.4, + "engine_prompt_tps": 2185.1, + "engine_decode_tps": 79.3, + "log_lines": [ + "strata serve: prompt 119256 tokens = 0 reused + 119256 read in 54577 ms (2185.1 tok/s), 256 generated in 3230 ms (79.3 tok/s), drafts accepted 151 of 208, 6 checkpoints", + "strata serve: decode expert cache hit rate: 95.5% (140181 hits / 146787 lookups)" + ], + "answer_head": "The last file shown is `include/strata/kernels/cpu/pool.hpp`. It declares the CPU expert pool (`ExpertPool`), which is the engine's mechanism for computing the routed MoE experts that do not fit in VRAM.\n\n**What it does:**\n\n1. **Thread Management:** It creates a pool of worker threads pinned to phy", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + } + ], + "requests_kept": 20, + "totals": { + "since": 1790713882.6043305, + "requests": 20, + "prompt_tokens": 346713, + "reused": 0, + "output_tokens": 4134, + "prompt_ms": 170012.5, + "decode_ms": 48004.89999999999 + }, + "hardware": { + "gpu_util": 0, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 45, + "gpu_power": 245.728, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.3330078125, + "gpu_pcie_tx_mb": 0.4765625, + "cpu": 55.3, + "ram_used": 63994736640, + "ram_total": 177175990272, + "disk_read_mb": 2.173699813344069, + "disk_write_mb": 0.07870292427625078, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 100, + 99, + 99, + 100, + 99, + 97, + 96, + 99, + 99, + 99, + 100, + 100, + 97, + 100, + 100, + 99, + 97, + 99, + 100, + 100, + 99, + 99, + 98, + 99, + 99, + 99, + 98, + 100, + 100, + 99, + 99, + 100, + 100, + 100, + 99, + 99, + 99, + 97, + 100, + 100, + 100, + 4, + 100, + 100, + 89, + 94, + 95, + 0 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 38, + 38, + 38, + 38, + 45, + 46, + 46, + 46, + 46, + 46, + 46, + 47, + 47, + 47, + 47, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 46, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 47, + 47, + 46, + 47, + 47, + 45 + ], + "gpu_power": [ + 34.95, + 35.05, + 34.94, + 34.95, + 146.71, + 278.26, + 278.02, + 277.13, + 278.38, + 277.26, + 277.39, + 265.55, + 278.37, + 277.81, + 278.33, + 277.55, + 276.64, + 268.76, + 278.4, + 278.09, + 279.44, + 277.89, + 278.06, + 278.94, + 266.27, + 278.02, + 278.54, + 277.25, + 277.61, + 278.51, + 277.09, + 267.68, + 277.75, + 277.97, + 277.81, + 277.03, + 277.2, + 278.97, + 266.74, + 277.84, + 277.04, + 277.08, + 277.19, + 277.7, + 278.99, + 275.31, + 278.3, + 278.49, + 277.62, + 278.02, + 276.32, + 276.96, + 277.41, + 263.19, + 267.16, + 277.12, + 240.24, + 275.77, + 278.35, + 245.73 + ], + "gpu_pcie_rx_mb": [ + 0.43, + 0.38, + 0.43, + 0.62, + 11.06, + 10427.81, + 2646.73, + 383.9, + 8262.3, + 11.68, + 24650.05, + 893.64, + 18094.54, + 8958.05, + 12.25, + 6881.52, + 17403.6, + 4113.72, + 25011.21, + 21669.05, + 15617.75, + 11.78, + 26451.63, + 0.33, + 5449.25, + 2654.98, + 14.88, + 22.22, + 15.59, + 7.49, + 1.29, + 17076.97, + 2352.29, + 26573.8, + 19.55, + 15.45, + 3977.3, + 0.29, + 16.07, + 3622.44, + 16839.27, + 13.49, + 13131.9, + 19713.45, + 26861.86, + 17424.06, + 12115.96, + 5297.42, + 26787.19, + 12211.47, + 5737.21, + 18827.01, + 8191.39, + 15610.6, + 18543.15, + 81.97, + 3906.87, + 3778.6, + 4665.28, + 0.33 + ], + "cpu": [ + 1.5, + 6.0, + 1.8, + 7.9, + 6.4, + 6.6, + 16.7, + 12.8, + 7.5, + 6.4, + 5.6, + 6.5, + 6.9, + 6.6, + 17.4, + 5.9, + 5.5, + 14.4, + 12.9, + 6.6, + 19.0, + 17.6, + 6.4, + 7.6, + 15.3, + 10.6, + 6.2, + 15.5, + 14.7, + 6.1, + 5.9, + 17.4, + 8.8, + 6.2, + 15.9, + 21.5, + 7.2, + 7.4, + 16.6, + 7.1, + 6.6, + 8.9, + 14.9, + 6.1, + 5.8, + 10.7, + 14.6, + 6.8, + 5.9, + 19.6, + 12.3, + 6.2, + 7.7, + 6.1, + 5.9, + 6.3, + 64.3, + 100.0, + 100.0, + 55.3 + ], + "ram_used": [ + 63599173632, + 63581626368, + 63584313344, + 63628144640, + 63383064576, + 63385989120, + 63410585600, + 63420211200, + 63412383744, + 63414505472, + 63524802560, + 63511179264, + 63497076736, + 63495684096, + 63489646592, + 63487651840, + 63472156672, + 63594835968, + 63578550272, + 63580782592, + 63599607808, + 63609155584, + 63609020416, + 63658397696, + 63611748352, + 63599493120, + 63591612416, + 63610773504, + 63607812096, + 63605293056, + 63719862272, + 63720685568, + 63714033664, + 63716544512, + 63707664384, + 63700750336, + 63700516864, + 63791661056, + 63808417792, + 63809699840, + 63813054464, + 63809191936, + 63809736704, + 63785721856, + 63788429312, + 63899906048, + 63903354880, + 63885254656, + 63887302656, + 63919407104, + 63917928448, + 63921512448, + 63919017984, + 64030937088, + 64033521664, + 64022724608, + 64014991360, + 64020590592, + 64011530240, + 63994736640 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.59, + 0.0, + 0.0, + 0.18, + 0.0, + 0.0, + 0.31, + 0.0, + 0.0, + 5.59, + 188.01, + 0.0, + 0.0, + 123.58, + 109.11, + 0.0, + 61.11, + 110.87, + 0.0, + 0.0, + 173.38, + 90.91, + 0.0, + 90.3, + 151.87, + 0.0, + 0.0, + 198.92, + 33.71, + 0.0, + 100.92, + 100.99, + 0.0, + 0.0, + 190.6, + 21.65, + 0.0, + 46.97, + 157.79, + 0.0, + 0.0, + 54.2, + 150.86, + 0.0, + 0.0, + 89.37, + 16.55, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.57, + 4.0, + 4.88, + 2.17 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 80.35, + 77.04, + 74.05, + 0.0 + ] + }, + "time": 1790714694.882821 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-2.json new file mode 100644 index 0000000..27d398a --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-2.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 2, + "run_id": "815c67976126", + "corpus_repeated": false, + "time": "2026-09-29T20:44:54", + "prompt_tokens": 130360, + "completion_tokens": 256, + "ttft_s": 60.567, + "e2e_s": 63.777, + "api_prompt_tps": 2152.3, + "api_decode_tps": 79.4, + "engine_prompt_tps": 2173.6, + "engine_decode_tps": 79.4, + "log_lines": [ + "strata serve: prompt 130360 tokens = 0 reused + 130360 read in 59974 ms (2173.6 tok/s), 256 generated in 3226 ms (79.4 tok/s), drafts accepted 158 of 225, 6 checkpoints", + "strata serve: decode expert cache hit rate: 94.5% (142001 hits / 150326 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing.\n\n## What `include/strata/kernels/gdn.hpp` does\n\nThis header declares the **non-projection parts of the Gated Delta-Net (GDN) layer** \u2014 the \"mixer\" used in 36 of the model's 48 layers (the other 12 are QSA full-attention layers). It is the C++ cou", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + } + ], + "requests_kept": 21, + "totals": { + "since": 1790713882.6043305, + "requests": 21, + "prompt_tokens": 477073, + "reused": 0, + "output_tokens": 4390, + "prompt_ms": 229986.4, + "decode_ms": 51230.999999999985 + }, + "hardware": { + "gpu_util": 95, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 48, + "gpu_power": 278.59, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 1822.99609375, + "gpu_pcie_tx_mb": 282.4296875, + "cpu": 100.0, + "ram_used": 63968800768, + "ram_total": 177175990272, + "disk_read_mb": 3.7524610679737007, + "disk_write_mb": 0.06727519842980738, + "tok_s": 75.51795929153683, + "tok_s_mean": 78.52742680374247 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 99, + 100, + 97, + 99, + 100, + 3, + 99, + 100, + 98, + 100, + 99, + 100, + 100, + 99, + 99, + 98, + 100, + 100, + 15, + 99, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 100, + 99, + 98, + 99, + 100, + 11, + 99, + 99, + 100, + 100, + 99, + 99, + 99, + 99, + 100, + 99, + 100, + 100, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 100, + 100, + 100, + 49, + 97, + 93, + 95 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 47, + 47, + 48, + 48, + 48, + 47, + 46, + 47, + 47, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 47, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 46, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 47, + 48, + 48, + 48 + ], + "gpu_power": [ + 242.39, + 277.2, + 277.34, + 277.65, + 278.23, + 277.3, + 263.86, + 266.5, + 276.0, + 277.29, + 276.57, + 277.42, + 277.59, + 268.12, + 277.51, + 276.99, + 278.25, + 276.6, + 278.17, + 261.67, + 270.19, + 277.42, + 278.17, + 277.12, + 278.28, + 277.75, + 275.69, + 267.25, + 277.04, + 278.86, + 278.14, + 276.63, + 278.3, + 265.62, + 266.61, + 278.07, + 276.73, + 277.66, + 277.57, + 279.3, + 278.07, + 267.14, + 278.22, + 278.47, + 276.15, + 278.64, + 278.86, + 277.69, + 275.4, + 267.11, + 276.68, + 277.32, + 278.12, + 277.19, + 277.93, + 278.16, + 257.52, + 253.15, + 278.1, + 278.59 + ], + "gpu_pcie_rx_mb": [ + 5309.2, + 958.97, + 17058.94, + 14.64, + 4.05, + 3010.03, + 8.39, + 15.12, + 15999.51, + 15.07, + 10772.8, + 7160.47, + 71.72, + 850.39, + 14.26, + 26414.87, + 26332.33, + 24917.6, + 18346.6, + 6700.37, + 20833.01, + 48.73, + 15.64, + 11585.24, + 10728.5, + 4552.75, + 22.55, + 13.78, + 18.55, + 13.88, + 3975.96, + 21618.6, + 14728.83, + 12107.04, + 17.45, + 2833.51, + 11.78, + 14105.51, + 21939.33, + 26894.86, + 0.33, + 21545.12, + 4351.66, + 13.54, + 21.36, + 50.16, + 22.7, + 14.26, + 24800.11, + 17.12, + 405.07, + 24.65, + 15145.21, + 16473.29, + 23109.39, + 24054.19, + 24291.28, + 1098.68, + 2094.22, + 1823.0 + ], + "cpu": [ + 12.7, + 5.7, + 13.2, + 17.8, + 11.5, + 8.3, + 10.6, + 6.0, + 6.7, + 8.3, + 8.0, + 5.8, + 5.5, + 10.0, + 7.2, + 6.7, + 11.2, + 15.8, + 7.1, + 9.4, + 8.7, + 6.2, + 6.3, + 10.1, + 6.6, + 8.2, + 8.6, + 6.9, + 6.0, + 6.4, + 9.0, + 16.5, + 8.5, + 8.3, + 8.3, + 6.3, + 6.1, + 9.9, + 6.0, + 7.2, + 6.1, + 8.2, + 11.3, + 7.1, + 7.3, + 16.3, + 11.9, + 6.5, + 8.4, + 17.1, + 6.1, + 6.2, + 6.3, + 6.4, + 6.8, + 7.5, + 7.9, + 100.0, + 100.0, + 100.0 + ], + "ram_used": [ + 63257399296, + 63250329600, + 63299825664, + 63294885888, + 63299862528, + 63298265088, + 63372304384, + 63374991360, + 63367077888, + 63366172672, + 63358062592, + 63355240448, + 63368228864, + 63471902720, + 63463698432, + 63469293568, + 63458623488, + 63534329856, + 63535923200, + 63653580800, + 63646789632, + 63642984448, + 63647580160, + 63642767360, + 63650861056, + 63672475648, + 63778967552, + 63777734656, + 63777472512, + 63771406336, + 63775264768, + 63864942592, + 63851782144, + 63977308160, + 63971295232, + 63971143680, + 63971721216, + 63963795456, + 63959093248, + 63937032192, + 64053448704, + 64054136832, + 63885062144, + 63887245312, + 63892475904, + 63940841472, + 63943122944, + 63941619712, + 64051613696, + 64039284736, + 64037093376, + 64025649152, + 64001216512, + 63998476288, + 63988797440, + 63985102848, + 64024535040, + 64006193152, + 63985057792, + 63968800768 + ], + "disk_read_mb": [ + 82.45, + 0.0, + 0.0, + 104.98, + 0.0, + 0.15, + 86.65, + 0.0, + 0.0, + 49.16, + 30.63, + 0.0, + 0.0, + 66.33, + 0.0, + 0.0, + 49.25, + 0.0, + 0.0, + 19.87, + 53.0, + 0.0, + 0.0, + 65.63, + 0.0, + 0.0, + 49.27, + 11.94, + 0.0, + 0.0, + 53.35, + 0.0, + 0.0, + 40.85, + 14.45, + 0.0, + 0.0, + 52.4, + 0.0, + 0.0, + 0.0, + 51.78, + 0.0, + 0.0, + 14.03, + 110.69, + 0.0, + 0.0, + 0.19, + 189.89, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 2.91, + 2.72, + 3.75 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 80.44, + 97.1, + 75.52 + ] + }, + "time": 1790714759.167411 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-3.json new file mode 100644 index 0000000..ab96da0 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-3.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 3, + "run_id": "317fbfabc24a", + "corpus_repeated": false, + "time": "2026-09-29T20:45:59", + "prompt_tokens": 129913, + "completion_tokens": 256, + "ttft_s": 60.534, + "e2e_s": 64.056, + "api_prompt_tps": 2146.1, + "api_decode_tps": 72.4, + "engine_prompt_tps": 2168.8, + "engine_decode_tps": 72.0, + "log_lines": [ + "strata serve: prompt 129913 tokens = 0 reused + 129913 read in 59901 ms (2168.8 tok/s), 256 generated in 3556 ms (72.0 tok/s), drafts accepted 148 of 200, 6 checkpoints", + "strata serve: decode expert cache hit rate: 95.6% (138618 hits / 145073 lookups)" + ], + "answer_head": "The last file is `include/strata/kernels/gdn.hpp`. It declares the non-projection parts of the gated delta-net (GDN) layer used by 36 of the model's 48 layers. It defines `GdnShapes` (S=128, h_k=16, h_v=48) and declares `gdn_step`, which performs one in-place step of the delta-rule recurrence: it de", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + } + ], + "requests_kept": 22, + "totals": { + "since": 1790713882.6043305, + "requests": 22, + "prompt_tokens": 606986, + "reused": 0, + "output_tokens": 4646, + "prompt_ms": 289887.2, + "decode_ms": 54787.29999999999 + }, + "hardware": { + "gpu_util": 95, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 49, + "gpu_power": 273.544, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.28515625, + "gpu_pcie_tx_mb": 0.4765625, + "cpu": 86.8, + "ram_used": 64157536256, + "ram_total": 177175990272, + "disk_read_mb": 2.8283858363947703, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 99, + 99, + 99, + 100, + 100, + 99, + 99, + 100, + 97, + 99, + 100, + 98, + 100, + 100, + 100, + 100, + 99, + 100, + 99, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 100, + 100, + 99, + 100, + 97, + 100, + 100, + 100, + 99, + 99, + 99, + 99, + 100, + 100, + 100, + 97, + 99, + 99, + 100, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 85, + 91, + 96, + 95 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 49, + 48, + 49, + 49, + 49, + 49, + 48, + 49, + 49, + 49, + 49, + 48, + 48, + 49, + 48, + 49, + 49, + 49, + 49, + 48, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49 + ], + "gpu_power": [ + 277.4, + 277.63, + 276.55, + 277.24, + 277.6, + 277.7, + 267.41, + 277.71, + 277.73, + 277.11, + 277.47, + 278.48, + 265.62, + 277.65, + 278.51, + 277.16, + 277.8, + 278.42, + 276.76, + 264.34, + 277.83, + 278.79, + 277.39, + 278.33, + 279.04, + 277.09, + 266.43, + 277.15, + 279.09, + 277.12, + 278.21, + 279.11, + 276.87, + 266.5, + 277.59, + 276.92, + 277.76, + 277.37, + 277.95, + 278.05, + 266.15, + 281.14, + 276.88, + 277.27, + 277.03, + 278.78, + 277.01, + 276.66, + 264.08, + 276.78, + 278.41, + 277.85, + 276.09, + 278.51, + 279.06, + 278.13, + 239.73, + 262.71, + 270.73, + 273.54 + ], + "gpu_pcie_rx_mb": [ + 11.44, + 11737.44, + 1061.11, + 1303.05, + 10.78, + 20755.48, + 892.69, + 12802.27, + 17290.83, + 13.02, + 669.76, + 9859.75, + 15.88, + 26970.96, + 27538.78, + 8595.9, + 10.82, + 22491.22, + 20098.16, + 7703.26, + 2655.31, + 1810.74, + 21.84, + 656.7, + 7.82, + 17247.68, + 12383.65, + 14706.95, + 18027.4, + 14.64, + 51.02, + 23.94, + 21140.67, + 19852.11, + 18272.88, + 11345.43, + 10748.2, + 23.08, + 3973.67, + 14.35, + 15.45, + 12245.37, + 13872.91, + 2994.2, + 10277.84, + 51.35, + 26547.62, + 4842.76, + 13126.71, + 6178.52, + 14.73, + 12025.83, + 22118.66, + 18928.05, + 18.36, + 86.12, + 284.24, + 9240.67, + 7805.97, + 0.29 + ], + "cpu": [ + 7.6, + 6.7, + 9.9, + 8.5, + 6.7, + 6.2, + 11.3, + 5.7, + 6.1, + 11.0, + 7.2, + 6.5, + 20.9, + 10.8, + 5.8, + 8.9, + 8.5, + 6.7, + 6.4, + 11.1, + 6.7, + 5.6, + 11.4, + 8.9, + 6.1, + 6.0, + 17.0, + 11.4, + 6.6, + 10.0, + 7.3, + 6.2, + 6.6, + 10.7, + 6.4, + 6.2, + 6.7, + 9.0, + 6.2, + 7.0, + 9.7, + 17.6, + 7.3, + 7.5, + 10.4, + 6.7, + 6.4, + 6.7, + 8.5, + 6.3, + 5.8, + 8.2, + 6.7, + 6.2, + 6.0, + 13.2, + 64.5, + 99.9, + 99.0, + 86.8 + ], + "ram_used": [ + 63275466752, + 63276769280, + 63271755776, + 63272300544, + 63263879168, + 63359676416, + 63357374464, + 63357542400, + 63358373888, + 63359791104, + 63361323008, + 63363457024, + 63494107136, + 63494156288, + 63489257472, + 63490707456, + 63488667648, + 63458295808, + 63462985728, + 63580164096, + 63581151232, + 63584616448, + 63609655296, + 63608074240, + 63610007552, + 63607758848, + 63749599232, + 63745466368, + 63718805504, + 63722086400, + 63728562176, + 63731232768, + 63729074176, + 63842201600, + 63847124992, + 63850708992, + 63853719552, + 63846064128, + 63846113280, + 63848321024, + 63970734080, + 63991717888, + 63989817344, + 63985319936, + 63983939584, + 63975882752, + 63976255488, + 63973568512, + 64091373568, + 64083685376, + 64078811136, + 64100171776, + 64087904256, + 64069447680, + 64067096576, + 64095731712, + 64224346112, + 64185745408, + 64170352640, + 64157536256 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 71.01, + 35.58, + 0.0, + 2.93, + 89.18, + 0.0, + 0.0, + 92.41, + 0.0, + 0.0, + 76.71, + 3.39, + 0.0, + 12.48, + 48.82, + 0.0, + 0.0, + 92.22, + 0.0, + 0.0, + 44.7, + 41.48, + 0.0, + 0.0, + 83.51, + 0.0, + 0.0, + 52.65, + 20.67, + 0.0, + 0.0, + 77.14, + 0.0, + 0.0, + 21.58, + 52.7, + 0.0, + 0.0, + 74.56, + 0.0, + 0.0, + 0.0, + 65.27, + 0.0, + 0.0, + 0.0, + 48.73, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.89, + 2.52, + 3.25, + 2.83 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 61.23, + 76.01, + 95.36, + 0.0 + ] + }, + "time": 1790714823.7293081 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-1.json new file mode 100644 index 0000000..b46da85 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-1.json @@ -0,0 +1,815 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 1, + "run_id": "56b3dec5f002", + "corpus_repeated": false, + "time": "2026-09-29T20:40:39", + "prompt_tokens": 1092, + "completion_tokens": 256, + "ttft_s": 1.378, + "e2e_s": 4.115, + "api_prompt_tps": 792.3, + "api_decode_tps": 93.2, + "engine_prompt_tps": 808.1, + "engine_decode_tps": 93.0, + "log_lines": [ + "strata serve: prompt 1092 tokens = 0 reused + 1092 read in 1351 ms (808.1 tok/s), 256 generated in 2753 ms (93.0 tok/s), drafts accepted 159 of 210, 1 checkpoints", + "strata serve: decode expert cache hit rate: 95.4% (137036 hits / 143638 lookups)" + ], + "answer_head": "Based on the content of `CMakeLists.txt`, here is an explanation of its function and a proposed improvement.\n\n### Explanation of `CMakeLists.txt`\n\nThis file serves as the top-level build configuration for the **Strata Engine** (version 0.1.26). Its primary responsibilities are:\n\n1. **Project Defini", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714290.8242896, + "duration_s": 1.8, + "finish": "stop", + "prompt_tokens": 1147, + "reused": 0, + "output_tokens": 40, + "engine_generated": 40, + "prompt_ms": 1304.0, + "decode_ms": 456.3, + "decode_tok_s": 87.7, + "hit_rate": 0.916 + }, + { + "projection": null, + "time": 1790714285.3293037, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 1094, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1899.7, + "decode_ms": 3080.2, + "decode_tok_s": 83.1, + "hit_rate": 0.946 + }, + { + "projection": null, + "time": 1790713900.001974, + "duration_s": 0.7, + "finish": "stop", + "prompt_tokens": 22, + "reused": 0, + "output_tokens": 7, + "engine_generated": 7, + "prompt_ms": 482.2, + "decode_ms": 197.4, + "decode_tok_s": 35.5, + "hit_rate": 0.707 + } + ], + "requests_kept": 11, + "totals": { + "since": 1790713882.6043305, + "requests": 11, + "prompt_tokens": 114775, + "reused": 0, + "output_tokens": 1944, + "prompt_ms": 60083.00000000001, + "decode_ms": 23035.299999999996 + }, + "hardware": { + "gpu_util": 94, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 45, + "gpu_power": 276.526, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.3330078125, + "gpu_pcie_tx_mb": 0.4765625, + "cpu": 87.0, + "ram_used": 63534440448, + "ram_total": 177175990272, + "disk_read_mb": 3.2598935177561885, + "disk_write_mb": 0.003747004043397918, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 99, + 99, + 42, + 99, + 99, + 100, + 99, + 99, + 99, + 94, + 99, + 95, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 44, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 42, + 42, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45 + ], + "gpu_power": [ + 277.8, + 276.98, + 276.99, + 264.47, + 274.0, + 276.95, + 276.96, + 277.85, + 278.23, + 277.83, + 242.91, + 278.73, + 277.1, + 247.26, + 164.95, + 142.09, + 130.43, + 119.16, + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53 + ], + "gpu_pcie_rx_mb": [ + 20099.78, + 18385.74, + 52.36, + 17363.88, + 9102.54, + 10.44, + 87.17, + 12174.99, + 8.39, + 78.63, + 439.12, + 1555.01, + 511.84, + 0.33, + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33 + ], + "cpu": [ + 6.7, + 5.9, + 12.5, + 10.7, + 6.6, + 10.7, + 6.2, + 7.2, + 6.5, + 5.9, + 52.8, + 100.0, + 100.0, + 46.0, + 2.5, + 9.7, + 2.8, + 11.4, + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0 + ], + "ram_used": [ + 63341527040, + 63336820736, + 63366373376, + 63501127680, + 63474081792, + 63398842368, + 63397171200, + 63396274176, + 63387021312, + 63380054016, + 63501307904, + 63504547840, + 63499546624, + 63490957312, + 63502053376, + 63600914432, + 63612030976, + 63779962880, + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448 + ], + "disk_read_mb": [ + 0.2, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.41, + 2.29, + 3.94, + 1.13, + 0.0, + 0.0, + 0.0, + 0.0, + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 91.56, + 92.69, + 83.62, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0 + ] + }, + "time": 1790714443.884817 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-2.json new file mode 100644 index 0000000..299ed2b --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-2.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 2, + "run_id": "5da89525cd83", + "corpus_repeated": false, + "time": "2026-09-29T20:40:43", + "prompt_tokens": 1149, + "completion_tokens": 256, + "ttft_s": 1.323, + "e2e_s": 4.156, + "api_prompt_tps": 868.4, + "api_decode_tps": 90.0, + "engine_prompt_tps": 885.5, + "engine_decode_tps": 89.9, + "log_lines": [ + "strata serve: prompt 1149 tokens = 0 reused + 1149 read in 1298 ms (885.5 tok/s), 256 generated in 2847 ms (89.9 tok/s), drafts accepted 156 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.1% (144603 hits / 148933 lookups)" + ], + "answer_head": "Based on the content provided, here is an explanation of the `CMakeLists.txt` file and a proposed improvement.\n\n### Explanation of `CMakeLists.txt`\n\nThis file is the top-level build configuration for the **Strata Engine** (specifically Phase 1, Step 1). Its primary responsibilities are:\n\n1. **Proje", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714290.8242896, + "duration_s": 1.8, + "finish": "stop", + "prompt_tokens": 1147, + "reused": 0, + "output_tokens": 40, + "engine_generated": 40, + "prompt_ms": 1304.0, + "decode_ms": 456.3, + "decode_tok_s": 87.7, + "hit_rate": 0.916 + }, + { + "projection": null, + "time": 1790714285.3293037, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 1094, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1899.7, + "decode_ms": 3080.2, + "decode_tok_s": 83.1, + "hit_rate": 0.946 + }, + { + "projection": null, + "time": 1790713900.001974, + "duration_s": 0.7, + "finish": "stop", + "prompt_tokens": 22, + "reused": 0, + "output_tokens": 7, + "engine_generated": 7, + "prompt_ms": 482.2, + "decode_ms": 197.4, + "decode_tok_s": 35.5, + "hit_rate": 0.707 + } + ], + "requests_kept": 12, + "totals": { + "since": 1790713882.6043305, + "requests": 12, + "prompt_tokens": 115924, + "reused": 0, + "output_tokens": 2200, + "prompt_ms": 61380.600000000006, + "decode_ms": 25882.799999999996 + }, + "hardware": { + "gpu_util": 95, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 45, + "gpu_power": 273.597, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 1249.6943359375, + "gpu_pcie_tx_mb": 212.6689453125, + "cpu": 97.9, + "ram_used": 63536766976, + "ram_total": 177175990272, + "disk_read_mb": 2.8181744035205307, + "disk_write_mb": 0.014930725316665065, + "tok_s": 76.9743768862725, + "tok_s_mean": 90.24600065341676 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 99, + 100, + 99, + 99, + 99, + 94, + 99, + 95, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 42, + 42, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45 + ], + "gpu_power": [ + 274.0, + 276.95, + 276.96, + 277.85, + 278.23, + 277.83, + 242.91, + 278.73, + 277.1, + 247.26, + 164.95, + 142.09, + 130.43, + 119.16, + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6 + ], + "gpu_pcie_rx_mb": [ + 9102.54, + 10.44, + 87.17, + 12174.99, + 8.39, + 78.63, + 439.12, + 1555.01, + 511.84, + 0.33, + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69 + ], + "cpu": [ + 6.6, + 10.7, + 6.2, + 7.2, + 6.5, + 5.9, + 52.8, + 100.0, + 100.0, + 46.0, + 2.5, + 9.7, + 2.8, + 11.4, + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9 + ], + "ram_used": [ + 63474081792, + 63398842368, + 63397171200, + 63396274176, + 63387021312, + 63380054016, + 63501307904, + 63504547840, + 63499546624, + 63490957312, + 63502053376, + 63600914432, + 63612030976, + 63779962880, + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.41, + 2.29, + 3.94, + 1.13, + 0.0, + 0.0, + 0.0, + 0.0, + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 91.56, + 92.69, + 83.62, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97 + ] + }, + "time": 1790714448.544591 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-3.json new file mode 100644 index 0000000..e56ebe6 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-3.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 3, + "run_id": "3ad6050d1d4c", + "corpus_repeated": false, + "time": "2026-09-29T20:40:48", + "prompt_tokens": 1135, + "completion_tokens": 256, + "ttft_s": 1.33, + "e2e_s": 4.007, + "api_prompt_tps": 853.1, + "api_decode_tps": 95.3, + "engine_prompt_tps": 869.7, + "engine_decode_tps": 95.1, + "log_lines": [ + "strata serve: prompt 1135 tokens = 0 reused + 1135 read in 1305 ms (869.7 tok/s), 256 generated in 2691 ms (95.1 tok/s), drafts accepted 159 of 217, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.2% (145229 hits / 149472 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file defines the top-level build configuration for the **Strata Engine** project. Its primary responsibilities include:\n\n1. **Project Definition**: Sets the project name (`strata`), version (`0.1.26`), and language standard (C++20).\n2. **Target Management**: Conditionally adds", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714290.8242896, + "duration_s": 1.8, + "finish": "stop", + "prompt_tokens": 1147, + "reused": 0, + "output_tokens": 40, + "engine_generated": 40, + "prompt_ms": 1304.0, + "decode_ms": 456.3, + "decode_tok_s": 87.7, + "hit_rate": 0.916 + }, + { + "projection": null, + "time": 1790714285.3293037, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 1094, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1899.7, + "decode_ms": 3080.2, + "decode_tok_s": 83.1, + "hit_rate": 0.946 + } + ], + "requests_kept": 13, + "totals": { + "since": 1790713882.6043305, + "requests": 13, + "prompt_tokens": 117059, + "reused": 0, + "output_tokens": 2456, + "prompt_ms": 62685.700000000004, + "decode_ms": 28573.599999999995 + }, + "hardware": { + "gpu_util": 21, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 43, + "gpu_power": 268.452, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.28515625, + "gpu_pcie_tx_mb": 0.4287109375, + "cpu": 63.3, + "ram_used": 63492075520, + "ram_total": 177175990272, + "disk_read_mb": 1.6601509757982635, + "disk_write_mb": 0.022485114796364742, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 94, + 99, + 95, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 45, + 45, + 45, + 45, + 42, + 42, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43 + ], + "gpu_power": [ + 277.83, + 242.91, + 278.73, + 277.1, + 247.26, + 164.95, + 142.09, + 130.43, + 119.16, + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45 + ], + "gpu_pcie_rx_mb": [ + 78.63, + 439.12, + 1555.01, + 511.84, + 0.33, + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29 + ], + "cpu": [ + 5.9, + 52.8, + 100.0, + 100.0, + 46.0, + 2.5, + 9.7, + 2.8, + 11.4, + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3 + ], + "ram_used": [ + 63380054016, + 63501307904, + 63504547840, + 63499546624, + 63490957312, + 63502053376, + 63600914432, + 63612030976, + 63779962880, + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520 + ], + "disk_read_mb": [ + 0.0, + 1.41, + 2.29, + 3.94, + 1.13, + 0.0, + 0.0, + 0.0, + 0.0, + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66 + ], + "tok_s": [ + 0.0, + 91.56, + 92.69, + 83.62, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0 + ] + }, + "time": 1790714453.0546403 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-1.json new file mode 100644 index 0000000..d2005e3 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-1.json @@ -0,0 +1,675 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 1, + "run_id": "459ef0e5c155", + "corpus_repeated": false, + "time": "2026-09-29T20:52:28", + "prompt_tokens": 232183, + "completion_tokens": 256, + "ttft_s": 131.32, + "e2e_s": 135.339, + "api_prompt_tps": 1768.1, + "api_decode_tps": 63.4, + "engine_prompt_tps": 1784.6, + "engine_decode_tps": 63.0, + "log_lines": [ + "strata serve: prompt 232183 tokens = 0 reused + 232183 read in 130101 ms (1784.6 tok/s), 256 generated in 4061 ms (63.0 tok/s), drafts accepted 150 of 240, 6 checkpoints", + "strata serve: decode expert cache hit rate: 93.7% (149829 hits / 159942 lookups)" + ], + "answer_head": "The last file is `serve/server.py` (the listing is truncated at the very end, in the `main()` function where it assigns `svc.gpu_index`).\n\n## What it does\n\nIt is the HTTP API layer of Strata: a pure-Python bridge between OpenAI/Anthropic-style clients and the C++ engine. Concretely:\n\n- **Engine adap", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 262144, + "images": false, + "version": "0.1.26", + "context": 262144, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10451, + "expert_cache_mib": 17355, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 385, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790715149.1813676, + "duration_s": 134.2, + "finish": "length", + "prompt_tokens": 232183, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 130101.1, + "decode_ms": 4061.2, + "decode_tok_s": 63.0, + "hit_rate": 0.937 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790715131.4670517, + "requests": 1, + "prompt_tokens": 232183, + "reused": 0, + "output_tokens": 256, + "prompt_ms": 130101.1, + "decode_ms": 4061.2 + }, + "hardware": { + "gpu_util": 93, + "gpu_mem_used": 25512837120, + "gpu_mem_total": 25769803776, + "gpu_temp": 50, + "gpu_power": 278.227, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 1220.75, + "gpu_pcie_tx_mb": 478.41015625, + "cpu": 100.0, + "ram_used": 65694810112, + "ram_total": 177175990272, + "disk_read_mb": 3.754966568441275, + "disk_write_mb": 0.0, + "tok_s": 74.58045953935934, + "tok_s_mean": 62.37130450720771 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 100, + 99, + 100, + 99, + 100, + 98, + 100, + 100, + 100, + 100, + 100, + 99, + 99, + 100, + 99, + 99, + 100, + 99, + 100, + 100, + 98, + 100, + 100, + 100, + 97, + 100, + 100, + 99, + 99, + 98, + 97, + 100, + 100, + 100, + 99, + 100, + 100, + 99, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 3, + 100, + 100, + 93, + 94, + 96, + 93 + ], + "gpu_mem_used": [ + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25512837120, + 25512837120, + 25512837120, + 25512837120 + ], + "gpu_temp": [ + 49, + 49, + 49, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 50, + 49, + 49, + 49, + 49, + 50, + 50, + 49, + 49, + 50, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 49, + 50, + 50, + 50, + 51, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 50, + 50, + 47, + 50, + 50, + 50 + ], + "gpu_power": [ + 279.11, + 266.12, + 276.9, + 277.46, + 279.35, + 277.6, + 278.96, + 278.2, + 276.29, + 279.45, + 275.58, + 268.64, + 275.16, + 277.98, + 275.78, + 278.17, + 279.67, + 276.04, + 279.46, + 275.1, + 265.27, + 279.22, + 280.54, + 276.07, + 280.55, + 278.32, + 274.82, + 275.85, + 280.08, + 279.93, + 266.81, + 277.79, + 274.52, + 274.38, + 279.74, + 277.72, + 274.64, + 279.65, + 280.34, + 278.34, + 277.27, + 274.99, + 265.64, + 277.06, + 278.38, + 279.64, + 279.6, + 273.86, + 273.12, + 273.61, + 275.7, + 275.96, + 276.36, + 266.12, + 265.34, + 275.53, + 242.04, + 256.98, + 274.43, + 278.23 + ], + "gpu_pcie_rx_mb": [ + 28.08, + 16676.85, + 27.75, + 7942.58, + 15.78, + 16.36, + 19454.0, + 15911.58, + 26.8, + 41.1, + 28.75, + 15.21, + 24.79, + 15.5, + 12903.17, + 15722.66, + 13615.27, + 5212.5, + 21571.11, + 9259.8, + 29.85, + 15.5, + 9701.01, + 153.35, + 15.64, + 30.23, + 25023.46, + 14.5, + 29.71, + 26217.94, + 17128.85, + 9320.26, + 28.28, + 28.94, + 13.54, + 87.12, + 1377.34, + 10125.25, + 29.04, + 30.52, + 15905.0, + 8753.63, + 7850.26, + 26.85, + 27.04, + 15.31, + 3817.42, + 27.99, + 26.89, + 26269.48, + 26779.27, + 20418.6, + 6900.17, + 6532.96, + 1637.36, + 26114.94, + 1472.71, + 1607.46, + 3050.8, + 1220.75 + ], + "cpu": [ + 6.4, + 10.7, + 11.7, + 16.5, + 8.6, + 6.3, + 18.6, + 6.0, + 5.9, + 5.7, + 8.8, + 12.7, + 5.6, + 5.9, + 6.6, + 12.9, + 11.3, + 13.4, + 13.0, + 9.8, + 14.3, + 23.4, + 6.3, + 5.9, + 7.9, + 13.4, + 9.7, + 6.5, + 6.7, + 5.9, + 10.3, + 17.8, + 14.9, + 7.1, + 8.8, + 5.8, + 16.3, + 7.3, + 5.7, + 7.3, + 5.7, + 8.0, + 14.4, + 7.4, + 6.6, + 5.9, + 15.4, + 12.5, + 6.2, + 6.9, + 7.8, + 7.2, + 6.8, + 7.1, + 5.7, + 6.0, + 44.6, + 99.9, + 99.9, + 100.0 + ], + "ram_used": [ + 65760505856, + 65825771520, + 65805475840, + 65899847680, + 65884385280, + 65881726976, + 65877250048, + 65865695232, + 65856700416, + 65843732480, + 65918058496, + 65911185408, + 65901252608, + 65896804352, + 65888411648, + 65880047616, + 65859633152, + 65903091712, + 65906130944, + 65929789440, + 65996169216, + 65697763328, + 65680461824, + 65660788736, + 65639858176, + 65624662016, + 65614233600, + 65604620288, + 65594793984, + 65589379072, + 65666322432, + 65661911040, + 65706741760, + 65701203968, + 65697587200, + 65691623424, + 65677221888, + 65665282048, + 65657679872, + 65628098560, + 65621381120, + 65695760384, + 65678503936, + 65672011776, + 65665482752, + 65658216448, + 65673232384, + 65655951360, + 65646583808, + 65641152512, + 65659457536, + 65656025088, + 65651355648, + 65716195328, + 65703702528, + 65693274112, + 65702584320, + 65687781376, + 65690525696, + 65694810112 + ], + "disk_read_mb": [ + 0.0, + 84.11, + 102.3, + 0.0, + 0.0, + 0.0, + 175.14, + 0.0, + 0.0, + 0.0, + 43.72, + 150.32, + 0.0, + 0.0, + 0.0, + 118.91, + 69.66, + 0.0, + 0.0, + 0.0, + 128.82, + 137.4, + 0.0, + 0.0, + 0.0, + 143.2, + 89.93, + 0.0, + 0.0, + 0.0, + 81.49, + 154.61, + 0.0, + 0.0, + 0.0, + 0.0, + 196.96, + 31.0, + 0.0, + 0.0, + 0.0, + 22.35, + 158.36, + 0.0, + 0.0, + 0.0, + 0.0, + 63.48, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.53, + 4.38, + 2.32, + 3.75 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 41.84, + 65.33, + 69.08, + 74.58 + ] + }, + "time": 1790715283.9323688 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-2.json new file mode 100644 index 0000000..bfc81ee --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-2.json @@ -0,0 +1,689 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 2, + "run_id": "fbabd65a593d", + "corpus_repeated": false, + "time": "2026-09-29T20:54:43", + "prompt_tokens": 259589, + "completion_tokens": 92, + "ttft_s": 152.099, + "e2e_s": 153.446, + "api_prompt_tps": 1706.7, + "api_decode_tps": 67.5, + "engine_prompt_tps": 1721.6, + "engine_decode_tps": 67.3, + "log_lines": [ + "strata serve: prompt 259589 tokens = 0 reused + 259589 read in 150784 ms (1721.6 tok/s), 92 generated in 1367 ms (67.3 tok/s), drafts accepted 61 of 75, 6 checkpoints", + "strata serve: decode expert cache hit rate: 90.0% (43983 hits / 48863 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the codebase and the last file in detail.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 262144, + "images": false, + "version": "0.1.26", + "context": 262144, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10451, + "expert_cache_mib": 17355, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 385, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790715285.1507986, + "duration_s": 152.2, + "finish": "stop", + "prompt_tokens": 259589, + "reused": 0, + "output_tokens": 92, + "engine_generated": 92, + "prompt_ms": 150783.8, + "decode_ms": 1366.8, + "decode_tok_s": 67.3, + "hit_rate": 0.9 + }, + { + "projection": null, + "time": 1790715149.1813676, + "duration_s": 134.2, + "finish": "length", + "prompt_tokens": 232183, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 130101.1, + "decode_ms": 4061.2, + "decode_tok_s": 63.0, + "hit_rate": 0.937 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790715131.4670517, + "requests": 2, + "prompt_tokens": 491772, + "reused": 0, + "output_tokens": 348, + "prompt_ms": 280884.9, + "decode_ms": 5428.0 + }, + "hardware": { + "gpu_util": 96, + "gpu_mem_used": 25512837120, + "gpu_mem_total": 25769803776, + "gpu_temp": 52, + "gpu_power": 277.319, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5709.8388671875, + "gpu_pcie_tx_mb": 1049.041015625, + "cpu": 99.9, + "ram_used": 65638817792, + "ram_total": 177175990272, + "disk_read_mb": 3.1622365794124767, + "disk_write_mb": 0.03737868297177868, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 100, + 100, + 99, + 100, + 100, + 100, + 99, + 100, + 100, + 99, + 99, + 97, + 100, + 100, + 100, + 99, + 99, + 97, + 100, + 100, + 100, + 100, + 60, + 100, + 100, + 99, + 99, + 100, + 98, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 98, + 100, + 100, + 99, + 99, + 100, + 98, + 100, + 99, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 99, + 96, + 96 + ], + "gpu_mem_used": [ + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120 + ], + "gpu_temp": [ + 51, + 52, + 52, + 51, + 51, + 52, + 51, + 50, + 51, + 52, + 51, + 51, + 51, + 51, + 51, + 52, + 51, + 51, + 51, + 51, + 51, + 51, + 52, + 50, + 52, + 51, + 52, + 52, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 52, + 52, + 52, + 52, + 52, + 52, + 51, + 51, + 51, + 52, + 51, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 51, + 52 + ], + "gpu_power": [ + 280.1, + 277.72, + 269.31, + 279.51, + 276.6, + 277.19, + 280.46, + 278.19, + 275.14, + 276.45, + 280.49, + 278.01, + 265.6, + 274.96, + 274.76, + 278.94, + 279.21, + 278.77, + 277.22, + 274.11, + 273.93, + 275.55, + 279.88, + 274.53, + 278.22, + 280.08, + 279.56, + 277.48, + 275.9, + 276.58, + 275.74, + 275.62, + 274.27, + 272.69, + 272.53, + 276.33, + 279.54, + 279.3, + 279.1, + 279.0, + 278.24, + 279.57, + 276.45, + 276.52, + 276.57, + 276.89, + 273.45, + 267.54, + 275.91, + 275.91, + 277.91, + 276.31, + 276.26, + 279.97, + 276.73, + 278.79, + 274.29, + 278.64, + 241.5, + 277.32 + ], + "gpu_pcie_rx_mb": [ + 24.6, + 11576.41, + 14790.49, + 31.66, + 20927.76, + 28.32, + 23015.64, + 14269.26, + 27.42, + 9814.79, + 27090.45, + 28.08, + 29.28, + 30.8, + 22511.15, + 22487.21, + 30.47, + 74.67, + 20330.0, + 20889.04, + 27.89, + 31.8, + 55.55, + 14868.74, + 15.35, + 20128.63, + 27.13, + 26.56, + 53.21, + 24118.71, + 16327.71, + 9496.97, + 20100.59, + 27.75, + 15.97, + 14788.58, + 13.49, + 13957.07, + 26.13, + 27.75, + 26181.89, + 48.68, + 16340.3, + 5056.67, + 25172.95, + 16.36, + 87.55, + 33.81, + 31.28, + 31.66, + 35.0, + 35.09, + 8309.17, + 6276.99, + 31.14, + 13669.87, + 18489.17, + 29.47, + 2057.6, + 5709.84 + ], + "cpu": [ + 6.6, + 7.6, + 11.4, + 12.8, + 6.6, + 6.0, + 6.6, + 11.6, + 10.6, + 6.8, + 5.6, + 6.1, + 9.8, + 25.0, + 9.1, + 5.9, + 6.8, + 6.1, + 16.7, + 7.0, + 8.8, + 6.9, + 5.9, + 12.8, + 11.2, + 5.6, + 6.5, + 14.2, + 10.7, + 16.4, + 8.1, + 7.0, + 6.2, + 5.9, + 7.4, + 13.8, + 6.0, + 5.7, + 7.0, + 6.1, + 6.2, + 15.3, + 15.5, + 12.5, + 6.3, + 6.3, + 6.0, + 14.9, + 7.3, + 9.6, + 6.6, + 6.1, + 6.6, + 8.6, + 5.9, + 6.2, + 16.0, + 9.9, + 42.7, + 99.9 + ], + "ram_used": [ + 65829687296, + 65809809408, + 65878708224, + 65862221824, + 65854197760, + 65848958976, + 65840418816, + 65838673920, + 65828872192, + 65821380608, + 65813520384, + 65804607488, + 65870708736, + 65884573696, + 65869344768, + 65860734976, + 65835606016, + 65825009664, + 65818324992, + 65817894912, + 65821642752, + 65816698880, + 65812000768, + 65862680576, + 65843482624, + 65833279488, + 65827409920, + 65838510080, + 65830367232, + 65803018240, + 65796870144, + 65792782336, + 65785704448, + 65781006336, + 65859014656, + 65839325184, + 65832935424, + 65818849280, + 65813626880, + 65805553664, + 65796202496, + 65790906368, + 65792847872, + 65822486528, + 65813880832, + 65796804608, + 65786474496, + 65854476288, + 65841573888, + 65829576704, + 65816891392, + 65810354176, + 65800015872, + 65793110016, + 65783308288, + 65776508928, + 65580986368, + 65575313408, + 65644572672, + 65638817792 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 99.27, + 135.95, + 0.0, + 0.0, + 0.0, + 113.06, + 91.94, + 0.0, + 0.0, + 0.0, + 46.52, + 161.04, + 0.0, + 0.0, + 0.0, + 0.0, + 199.72, + 0.0, + 0.0, + 0.0, + 0.0, + 91.5, + 66.56, + 0.0, + 0.0, + 0.0, + 0.0, + 191.98, + 0.0, + 0.0, + 0.0, + 0.0, + 13.73, + 127.69, + 0.0, + 0.0, + 0.0, + 0.0, + 1.52, + 125.36, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 171.54, + 7.82, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.75, + 3.16 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 69.44, + 0.0 + ] + }, + "time": 1790715437.8967788 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-3.json new file mode 100644 index 0000000..b42bd7f --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-3.json @@ -0,0 +1,703 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 3, + "run_id": "40a721fd9a17", + "corpus_repeated": false, + "time": "2026-09-29T20:57:17", + "prompt_tokens": 261068, + "completion_tokens": 256, + "ttft_s": 152.605, + "e2e_s": 156.279, + "api_prompt_tps": 1710.7, + "api_decode_tps": 69.4, + "engine_prompt_tps": 1725.6, + "engine_decode_tps": 69.3, + "log_lines": [ + "strata serve: prompt 261068 tokens = 0 reused + 261068 read in 151288 ms (1725.6 tok/s), 256 generated in 3693 ms (69.3 tok/s), drafts accepted 151 of 231, 6 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (153481 hits / 159304 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing and then propose a concrete improvement.\n\n## What `serve/web/app.js` does\n\nThis file is the **entire client-side logic of the Strata web application** \u2014 a framework-free, single-file JavaScript app that talks only to the local Strata server. It po", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 262144, + "images": false, + "version": "0.1.26", + "context": 262144, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10451, + "expert_cache_mib": 17355, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 385, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790715439.1095636, + "duration_s": 155.1, + "finish": "length", + "prompt_tokens": 261068, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 151288.5, + "decode_ms": 3693.0, + "decode_tok_s": 69.3, + "hit_rate": 0.963 + }, + { + "projection": null, + "time": 1790715285.1507986, + "duration_s": 152.2, + "finish": "stop", + "prompt_tokens": 259589, + "reused": 0, + "output_tokens": 92, + "engine_generated": 92, + "prompt_ms": 150783.8, + "decode_ms": 1366.8, + "decode_tok_s": 67.3, + "hit_rate": 0.9 + }, + { + "projection": null, + "time": 1790715149.1813676, + "duration_s": 134.2, + "finish": "length", + "prompt_tokens": 232183, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 130101.1, + "decode_ms": 4061.2, + "decode_tok_s": 63.0, + "hit_rate": 0.937 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790715131.4670517, + "requests": 3, + "prompt_tokens": 752840, + "reused": 0, + "output_tokens": 604, + "prompt_ms": 432173.4, + "decode_ms": 9121.0 + }, + "hardware": { + "gpu_util": 92, + "gpu_mem_used": 25512837120, + "gpu_mem_total": 25769803776, + "gpu_temp": 53, + "gpu_power": 277.576, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 3810.1669921875, + "gpu_pcie_tx_mb": 299.7392578125, + "cpu": 100.0, + "ram_used": 65843089408, + "ram_total": 177175990272, + "disk_read_mb": 4.922097648659462, + "disk_write_mb": 0.0, + "tok_s": 68.55526509763148, + "tok_s_mean": 69.76955378630859 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 100, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 98, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 98, + 100, + 100, + 100, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 88, + 100, + 100, + 100, + 99, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 97, + 95, + 95, + 92 + ], + "gpu_mem_used": [ + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120 + ], + "gpu_temp": [ + 53, + 52, + 53, + 52, + 52, + 52, + 53, + 53, + 52, + 52, + 53, + 53, + 53, + 52, + 52, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 52, + 52, + 53, + 53, + 53, + 53, + 53, + 53, + 52, + 52, + 52, + 52, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 52, + 53, + 53, + 52, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53 + ], + "gpu_power": [ + 279.28, + 276.25, + 280.52, + 280.21, + 276.32, + 278.64, + 280.39, + 275.19, + 275.3, + 267.01, + 278.7, + 279.27, + 280.07, + 277.82, + 274.89, + 273.96, + 277.23, + 280.24, + 279.4, + 277.21, + 266.21, + 276.82, + 277.27, + 274.7, + 272.68, + 273.87, + 273.33, + 275.44, + 276.56, + 276.53, + 276.52, + 263.9, + 276.06, + 275.76, + 276.06, + 275.68, + 275.74, + 273.79, + 276.62, + 276.84, + 276.88, + 276.17, + 275.71, + 273.17, + 265.54, + 275.78, + 273.31, + 275.66, + 275.72, + 276.2, + 275.38, + 273.99, + 273.72, + 275.56, + 276.07, + 276.57, + 245.75, + 278.73, + 277.86, + 277.58 + ], + "gpu_pcie_rx_mb": [ + 4135.46, + 6890.58, + 13.64, + 3437.09, + 30.71, + 20378.88, + 15.64, + 30.99, + 20391.65, + 19570.21, + 4926.97, + 27.94, + 28.08, + 26564.6, + 4245.0, + 29.13, + 28.94, + 7148.27, + 17857.03, + 28.51, + 11700.44, + 28.28, + 27.51, + 26015.42, + 14.3, + 16.36, + 11904.38, + 29.71, + 29.99, + 33.33, + 14.83, + 30.04, + 28.8, + 28.18, + 26.08, + 17.07, + 26755.14, + 31.04, + 30.14, + 30.8, + 29.04, + 30.8, + 33.24, + 27187.54, + 19414.33, + 9223.17, + 54.17, + 12.68, + 24.32, + 33.43, + 12868.02, + 32.04, + 29.66, + 34.62, + 20107.13, + 84.11, + 1655.15, + 10931.06, + 1614.47, + 3810.17 + ], + "cpu": [ + 12.6, + 5.5, + 6.4, + 6.8, + 13.7, + 9.3, + 10.4, + 12.8, + 12.2, + 11.8, + 13.0, + 6.1, + 6.4, + 6.3, + 8.4, + 15.9, + 9.1, + 6.5, + 7.0, + 5.8, + 13.8, + 18.7, + 8.2, + 6.0, + 7.7, + 8.1, + 14.9, + 5.8, + 6.5, + 6.5, + 5.9, + 9.5, + 9.8, + 6.4, + 6.2, + 13.8, + 11.5, + 9.4, + 9.4, + 6.0, + 7.2, + 5.8, + 6.6, + 6.5, + 15.9, + 8.9, + 7.4, + 6.0, + 6.1, + 9.0, + 13.9, + 6.6, + 8.0, + 6.2, + 6.0, + 7.2, + 56.6, + 100.0, + 100.0, + 100.0 + ], + "ram_used": [ + 65659777024, + 65650483200, + 65649508352, + 65644490752, + 65632600064, + 65621151744, + 65675010048, + 65661538304, + 65681547264, + 65747542016, + 65735454720, + 65723609088, + 65715372032, + 65702187008, + 65677402112, + 65653993472, + 65667379200, + 65663696896, + 65657884672, + 65648963584, + 65722257408, + 65791442944, + 65798762496, + 65787301888, + 65781350400, + 65659375616, + 65646817280, + 65635090432, + 65627262976, + 65615314944, + 65606516736, + 65678639104, + 65669410816, + 65663270912, + 65656647680, + 65739636736, + 65798643712, + 65792847872, + 65780387840, + 65772281856, + 65774555136, + 65768087552, + 65765552128, + 65838772224, + 65833267200, + 65850757120, + 65824538624, + 65812451328, + 65801834496, + 65796722688, + 65808052224, + 65799196672, + 65796362240, + 65791713280, + 65787756544, + 65798152192, + 65876860928, + 65866027008, + 65852674048, + 65843089408 + ], + "disk_read_mb": [ + 116.54, + 0.0, + 0.0, + 0.0, + 150.82, + 68.05, + 0.0, + 0.0, + 0.0, + 84.44, + 137.56, + 0.0, + 0.0, + 0.0, + 19.83, + 193.88, + 0.0, + 0.0, + 0.0, + 0.0, + 143.92, + 24.87, + 0.0, + 0.0, + 0.0, + 25.89, + 153.9, + 0.0, + 0.0, + 0.0, + 0.0, + 69.98, + 56.36, + 0.0, + 0.0, + 0.0, + 0.0, + 48.96, + 64.15, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 206.65, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.78, + 4.65, + 4.44, + 4.92 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 74.98, + 63.75, + 72.35, + 68.56 + ] + }, + "time": 1790715594.6843412 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-1.json new file mode 100644 index 0000000..deb941f --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-1.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "563f1c703ebe", + "corpus_repeated": false, + "time": "2026-09-29T20:41:08", + "prompt_tokens": 34932, + "completion_tokens": 256, + "ttft_s": 16.748, + "e2e_s": 19.56, + "api_prompt_tps": 2085.7, + "api_decode_tps": 90.7, + "engine_prompt_tps": 2110.2, + "engine_decode_tps": 90.6, + "log_lines": [ + "strata serve: prompt 34932 tokens = 0 reused + 34932 read in 16554 ms (2110.2 tok/s), 256 generated in 2827 ms (90.6 tok/s), drafts accepted 167 of 216, 3 checkpoints", + "strata serve: decode expert cache hit rate: 94.1% (133137 hits / 141416 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing and propose an improvement.\n\n## What `docs/DETAILS.md` does\n\nThis is the comprehensive technical documentation file for the Strata project. It serves as the single source of truth for:\n\n1. **Performance benchmarks** \u2014 Detailed tables of prompt-pro", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + } + ], + "requests_kept": 17, + "totals": { + "since": 1790713882.6043305, + "requests": 17, + "prompt_tokens": 164273, + "reused": 0, + "output_tokens": 3366, + "prompt_ms": 86199.0, + "decode_ms": 38719.19999999999 + }, + "hardware": { + "gpu_util": 97, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 278.81, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5630.111328125, + "gpu_pcie_tx_mb": 76.2939453125, + "cpu": 100.0, + "ram_used": 63789760512, + "ram_total": 177175990272, + "disk_read_mb": 2.3587450688100042, + "disk_write_mb": 0.1268945131954749, + "tok_s": 96.52070218780436, + "tok_s_mean": 91.25774344883004 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97, + 0, + 98, + 99, + 98, + 0, + 99, + 100, + 99, + 96, + 96, + 0, + 100, + 99, + 100, + 100, + 99, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 99, + 100, + 98, + 99, + 97 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46, + 42, + 46, + 45, + 46, + 42, + 45, + 45, + 45, + 46, + 46, + 42, + 46, + 46, + 46, + 46, + 46, + 45, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46 + ], + "gpu_power": [ + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79, + 215.59, + 278.37, + 251.8, + 276.73, + 219.4, + 271.43, + 276.62, + 251.66, + 277.46, + 278.06, + 194.1, + 265.98, + 277.8, + 274.38, + 278.56, + 277.99, + 277.15, + 264.89, + 276.96, + 277.37, + 277.24, + 276.83, + 276.94, + 278.15, + 264.71, + 273.73, + 243.99, + 277.71, + 278.81 + ], + "gpu_pcie_rx_mb": [ + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33, + 3342.49, + 34.05, + 7461.5, + 4551.6, + 6961.73, + 24513.15, + 26324.56, + 679.21, + 426.48, + 0.33, + 10.87, + 10442.35, + 23162.22, + 22324.94, + 24878.6, + 26870.2, + 14619.68, + 11419.68, + 893.4, + 13515.52, + 20953.08, + 7.87, + 14.59, + 23972.7, + 9329.51, + 82.11, + 7527.59, + 4538.68, + 5630.11 + ], + "cpu": [ + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8, + 14.8, + 15.8, + 37.5, + 100.0, + 32.6, + 6.8, + 6.6, + 96.7, + 100.0, + 83.5, + 5.1, + 7.7, + 6.8, + 5.8, + 11.1, + 14.6, + 9.1, + 8.4, + 7.3, + 7.4, + 7.0, + 7.1, + 6.5, + 5.9, + 6.0, + 6.9, + 72.2, + 100.0, + 100.0 + ], + "ram_used": [ + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816, + 63401848832, + 63554486272, + 63453114368, + 63441051648, + 63399321600, + 63389306880, + 63427080192, + 63418408960, + 63417094144, + 63416299520, + 63358083072, + 63351615488, + 63342723072, + 63336611840, + 63371808768, + 63426170880, + 63504416768, + 63594704896, + 63611879424, + 63612047360, + 63599980544, + 63573508096, + 63570501632, + 63568433152, + 63702056960, + 63700324352, + 63800950784, + 63801184256, + 63789760512 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66, + 0.64, + 0.0, + 0.21, + 2.1, + 1.17, + 0.0, + 0.0, + 1.29, + 3.73, + 2.96, + 0.82, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.0, + 0.23, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.7, + 0.31, + 2.36 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0, + 0.0, + 0.0, + 89.96, + 98.26, + 0.0, + 0.0, + 0.0, + 93.47, + 116.21, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.18, + 97.71, + 96.52 + ] + }, + "time": 1790714488.9946597 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-2.json new file mode 100644 index 0000000..449462f --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-2.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "283cb867e188", + "corpus_repeated": false, + "time": "2026-09-29T20:41:28", + "prompt_tokens": 31582, + "completion_tokens": 256, + "ttft_s": 14.807, + "e2e_s": 18.058, + "api_prompt_tps": 2132.9, + "api_decode_tps": 78.4, + "engine_prompt_tps": 2160.4, + "engine_decode_tps": 78.3, + "log_lines": [ + "strata serve: prompt 31582 tokens = 0 reused + 31582 read in 14619 ms (2160.4 tok/s), 256 generated in 3271 ms (78.3 tok/s), drafts accepted 161 of 240, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.0% (151459 hits / 157708 lookups)" + ], + "answer_head": "The last file in the provided list is `docs/DETAILS.md`.\n\n### What it does\nThis file serves as the **comprehensive technical manual and reference guide** for the Strata engine. While the `README.md` focuses on quick installation and high-level marketing, `DETAILS.md` provides the deep technical spec", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + } + ], + "requests_kept": 18, + "totals": { + "since": 1790713882.6043305, + "requests": 18, + "prompt_tokens": 195855, + "reused": 0, + "output_tokens": 3622, + "prompt_ms": 100817.7, + "decode_ms": 41989.89999999999 + }, + "hardware": { + "gpu_util": 94, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 47, + "gpu_power": 276.188, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.380859375, + "gpu_pcie_tx_mb": 0.4287109375, + "cpu": 84.0, + "ram_used": 63683891200, + "ram_total": 177175990272, + "disk_read_mb": 2.12697518787369, + "disk_write_mb": 0.05242544477153462, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97, + 0, + 98, + 99, + 98, + 0, + 99, + 100, + 99, + 96, + 96, + 0, + 100, + 99, + 100, + 100, + 99, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 99, + 100, + 98, + 99, + 97, + 0, + 99, + 99, + 99, + 99, + 99, + 99, + 98, + 100, + 99, + 100, + 99, + 99, + 99, + 73, + 98, + 97, + 94 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46, + 42, + 46, + 45, + 46, + 42, + 45, + 45, + 45, + 46, + 46, + 42, + 46, + 46, + 46, + 46, + 46, + 45, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 43, + 46, + 47, + 46, + 46, + 46, + 47, + 46, + 47, + 46, + 47, + 46, + 46, + 46, + 44, + 46, + 46, + 47 + ], + "gpu_power": [ + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79, + 215.59, + 278.37, + 251.8, + 276.73, + 219.4, + 271.43, + 276.62, + 251.66, + 277.46, + 278.06, + 194.1, + 265.98, + 277.8, + 274.38, + 278.56, + 277.99, + 277.15, + 264.89, + 276.96, + 277.37, + 277.24, + 276.83, + 276.94, + 278.15, + 264.71, + 273.73, + 243.99, + 277.71, + 278.81, + 203.42, + 258.01, + 277.13, + 277.38, + 277.05, + 276.55, + 275.55, + 267.16, + 280.52, + 277.94, + 278.68, + 277.45, + 276.52, + 278.47, + 255.06, + 250.07, + 273.21, + 276.19 + ], + "gpu_pcie_rx_mb": [ + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33, + 3342.49, + 34.05, + 7461.5, + 4551.6, + 6961.73, + 24513.15, + 26324.56, + 679.21, + 426.48, + 0.33, + 10.87, + 10442.35, + 23162.22, + 22324.94, + 24878.6, + 26870.2, + 14619.68, + 11419.68, + 893.4, + 13515.52, + 20953.08, + 7.87, + 14.59, + 23972.7, + 9329.51, + 82.11, + 7527.59, + 4538.68, + 5630.11, + 6.67, + 11788.08, + 773.91, + 87.02, + 13.59, + 4.53, + 50.21, + 7.15, + 6744.72, + 14.45, + 115.11, + 2575.49, + 26114.03, + 3364.04, + 3375.15, + 957.73, + 2766.08, + 0.38 + ], + "cpu": [ + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8, + 14.8, + 15.8, + 37.5, + 100.0, + 32.6, + 6.8, + 6.6, + 96.7, + 100.0, + 83.5, + 5.1, + 7.7, + 6.8, + 5.8, + 11.1, + 14.6, + 9.1, + 8.4, + 7.3, + 7.4, + 7.0, + 7.1, + 6.5, + 5.9, + 6.0, + 6.9, + 72.2, + 100.0, + 100.0, + 19.3, + 8.8, + 6.1, + 7.1, + 6.6, + 7.1, + 6.0, + 6.8, + 5.6, + 5.5, + 6.6, + 7.8, + 6.1, + 6.2, + 41.1, + 99.9, + 99.4, + 84.0 + ], + "ram_used": [ + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816, + 63401848832, + 63554486272, + 63453114368, + 63441051648, + 63399321600, + 63389306880, + 63427080192, + 63418408960, + 63417094144, + 63416299520, + 63358083072, + 63351615488, + 63342723072, + 63336611840, + 63371808768, + 63426170880, + 63504416768, + 63594704896, + 63611879424, + 63612047360, + 63599980544, + 63573508096, + 63570501632, + 63568433152, + 63702056960, + 63700324352, + 63800950784, + 63801184256, + 63789760512, + 63567470592, + 63559606272, + 63544537088, + 63536496640, + 63529500672, + 63515496448, + 63496245248, + 63530811392, + 63529254912, + 63530737664, + 63536521216, + 63543078912, + 63537020928, + 63539232768, + 63659114496, + 63677952000, + 63679279104, + 63683891200 + ], + "disk_read_mb": [ + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66, + 0.64, + 0.0, + 0.21, + 2.1, + 1.17, + 0.0, + 0.0, + 1.29, + 3.73, + 2.96, + 0.82, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.0, + 0.23, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.7, + 0.31, + 2.36, + 0.74, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.34, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 1.22, + 1.87, + 2.13 + ], + "tok_s": [ + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0, + 0.0, + 0.0, + 89.96, + 98.26, + 0.0, + 0.0, + 0.0, + 93.47, + 116.21, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.18, + 97.71, + 96.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 80.68, + 75.74, + 112.93, + 0.0 + ] + }, + "time": 1790714507.5571826 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-3.json new file mode 100644 index 0000000..f12d32e --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-3.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "1aba3d88be7a", + "corpus_repeated": false, + "time": "2026-09-29T20:41:47", + "prompt_tokens": 31602, + "completion_tokens": 256, + "ttft_s": 14.833, + "e2e_s": 17.604, + "api_prompt_tps": 2130.5, + "api_decode_tps": 92.0, + "engine_prompt_tps": 2161.9, + "engine_decode_tps": 91.9, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 14618 ms (2161.9 tok/s), 256 generated in 2785 ms (91.9 tok/s), drafts accepted 160 of 207, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.5% (137828 hits / 142765 lookups)" + ], + "answer_head": "The last file in the provided list is `docs/DETAILS.md`.\n\n### What it does\nThis file serves as the comprehensive technical documentation and user manual for the \"Strata\" engine. It bridges the gap between the high-level marketing pitch in `README.md` and the raw source code. Specifically, it:\n\n1. *", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + } + ], + "requests_kept": 19, + "totals": { + "since": 1790713882.6043305, + "requests": 19, + "prompt_tokens": 227457, + "reused": 0, + "output_tokens": 3878, + "prompt_ms": 115435.4, + "decode_ms": 44775.099999999984 + }, + "hardware": { + "gpu_util": 94, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 47, + "gpu_power": 277.644, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 3986.787109375, + "gpu_pcie_tx_mb": 397.443359375, + "cpu": 99.9, + "ram_used": 63539171328, + "ram_total": 177175990272, + "disk_read_mb": 3.5686025775501298, + "disk_write_mb": 0.3811491758221081, + "tok_s": 96.24470767975828, + "tok_s_mean": 94.09593644569512 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 99, + 100, + 99, + 96, + 96, + 0, + 100, + 99, + 100, + 100, + 99, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 99, + 100, + 98, + 99, + 97, + 0, + 99, + 99, + 99, + 99, + 99, + 99, + 98, + 100, + 99, + 100, + 99, + 99, + 99, + 73, + 98, + 97, + 94, + 100, + 100, + 99, + 99, + 99, + 99, + 99, + 100, + 99, + 100, + 100, + 100, + 99, + 99, + 97, + 97, + 94 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 42, + 45, + 45, + 45, + 46, + 46, + 42, + 46, + 46, + 46, + 46, + 46, + 45, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 43, + 46, + 47, + 46, + 46, + 46, + 47, + 46, + 47, + 46, + 47, + 46, + 46, + 46, + 44, + 46, + 46, + 47, + 46, + 46, + 47, + 46, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 47, + 47 + ], + "gpu_power": [ + 219.4, + 271.43, + 276.62, + 251.66, + 277.46, + 278.06, + 194.1, + 265.98, + 277.8, + 274.38, + 278.56, + 277.99, + 277.15, + 264.89, + 276.96, + 277.37, + 277.24, + 276.83, + 276.94, + 278.15, + 264.71, + 273.73, + 243.99, + 277.71, + 278.81, + 203.42, + 258.01, + 277.13, + 277.38, + 277.05, + 276.55, + 275.55, + 267.16, + 280.52, + 277.94, + 278.68, + 277.45, + 276.52, + 278.47, + 255.06, + 250.07, + 273.21, + 276.19, + 200.05, + 276.81, + 276.45, + 275.4, + 277.81, + 277.45, + 277.14, + 266.34, + 281.85, + 279.13, + 278.52, + 278.21, + 279.47, + 278.62, + 244.74, + 278.38, + 277.64 + ], + "gpu_pcie_rx_mb": [ + 6961.73, + 24513.15, + 26324.56, + 679.21, + 426.48, + 0.33, + 10.87, + 10442.35, + 23162.22, + 22324.94, + 24878.6, + 26870.2, + 14619.68, + 11419.68, + 893.4, + 13515.52, + 20953.08, + 7.87, + 14.59, + 23972.7, + 9329.51, + 82.11, + 7527.59, + 4538.68, + 5630.11, + 6.67, + 11788.08, + 773.91, + 87.02, + 13.59, + 4.53, + 50.21, + 7.15, + 6744.72, + 14.45, + 115.11, + 2575.49, + 26114.03, + 3364.04, + 3375.15, + 957.73, + 2766.08, + 0.38, + 16.21, + 26374.96, + 15489.62, + 25149.82, + 11.68, + 14.21, + 14.21, + 5900.76, + 15.35, + 3692.53, + 87.59, + 8.2, + 25347.8, + 80.63, + 5132.53, + 22.03, + 3986.79 + ], + "cpu": [ + 32.6, + 6.8, + 6.6, + 96.7, + 100.0, + 83.5, + 5.1, + 7.7, + 6.8, + 5.8, + 11.1, + 14.6, + 9.1, + 8.4, + 7.3, + 7.4, + 7.0, + 7.1, + 6.5, + 5.9, + 6.0, + 6.9, + 72.2, + 100.0, + 100.0, + 19.3, + 8.8, + 6.1, + 7.1, + 6.6, + 7.1, + 6.0, + 6.8, + 5.6, + 5.5, + 6.6, + 7.8, + 6.1, + 6.2, + 41.1, + 99.9, + 99.4, + 84.0, + 4.7, + 8.8, + 7.4, + 6.1, + 6.1, + 5.7, + 6.3, + 7.3, + 6.8, + 5.8, + 8.4, + 15.2, + 18.1, + 6.8, + 56.4, + 100.0, + 99.9 + ], + "ram_used": [ + 63399321600, + 63389306880, + 63427080192, + 63418408960, + 63417094144, + 63416299520, + 63358083072, + 63351615488, + 63342723072, + 63336611840, + 63371808768, + 63426170880, + 63504416768, + 63594704896, + 63611879424, + 63612047360, + 63599980544, + 63573508096, + 63570501632, + 63568433152, + 63702056960, + 63700324352, + 63800950784, + 63801184256, + 63789760512, + 63567470592, + 63559606272, + 63544537088, + 63536496640, + 63529500672, + 63515496448, + 63496245248, + 63530811392, + 63529254912, + 63530737664, + 63536521216, + 63543078912, + 63537020928, + 63539232768, + 63659114496, + 63677952000, + 63679279104, + 63683891200, + 63526555648, + 63547674624, + 63533957120, + 63515795456, + 63502536704, + 63493373952, + 63485927424, + 63556431872, + 63548153856, + 63549214720, + 63593517056, + 63649341440, + 63479009280, + 63476772864, + 63577780224, + 63546908672, + 63539171328 + ], + "disk_read_mb": [ + 1.17, + 0.0, + 0.0, + 1.29, + 3.73, + 2.96, + 0.82, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.0, + 0.23, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.7, + 0.31, + 2.36, + 0.74, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.34, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 1.22, + 1.87, + 2.13, + 0.67, + 0.0, + 0.0, + 0.27, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.45, + 0.74, + 3.57 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 93.47, + 116.21, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.18, + 97.71, + 96.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 80.68, + 75.74, + 112.93, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 108.5, + 87.33, + 96.24 + ] + }, + "time": 1790714525.664817 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-1.json new file mode 100644 index 0000000..24ec0dc --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-1.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 1, + "run_id": "6c6e9cb15bc9", + "corpus_repeated": false, + "time": "2026-09-29T20:40:53", + "prompt_tokens": 3881, + "completion_tokens": 256, + "ttft_s": 2.267, + "e2e_s": 5.041, + "api_prompt_tps": 1711.6, + "api_decode_tps": 91.9, + "engine_prompt_tps": 1745.2, + "engine_decode_tps": 91.7, + "log_lines": [ + "strata serve: prompt 3881 tokens = 0 reused + 3881 read in 2224 ms (1745.2 tok/s), 256 generated in 2791 ms (91.7 tok/s), drafts accepted 155 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.3% (146401 hits / 150495 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file is the top-level build configuration for the **Strata Engine**. It orchestrates the compilation of the project, handling complex dependencies between CPU-only components, GPU kernels (CUDA/HIP), and testing infrastructure.\n\n### What the file does:\n\n1. **Project Configurati", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714290.8242896, + "duration_s": 1.8, + "finish": "stop", + "prompt_tokens": 1147, + "reused": 0, + "output_tokens": 40, + "engine_generated": 40, + "prompt_ms": 1304.0, + "decode_ms": 456.3, + "decode_tok_s": 87.7, + "hit_rate": 0.916 + } + ], + "requests_kept": 14, + "totals": { + "since": 1790713882.6043305, + "requests": 14, + "prompt_tokens": 120940, + "reused": 0, + "output_tokens": 2712, + "prompt_ms": 64909.50000000001, + "decode_ms": 31364.099999999995 + }, + "hardware": { + "gpu_util": 97, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 278.792, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.3330078125, + "gpu_pcie_tx_mb": 0.5244140625, + "cpu": 93.8, + "ram_used": 63471906816, + "ram_total": 177175990272, + "disk_read_mb": 2.6609869128828647, + "disk_write_mb": 0.0037478688913843163, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 42, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46 + ], + "gpu_power": [ + 164.95, + 142.09, + 130.43, + 119.16, + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79 + ], + "gpu_pcie_rx_mb": [ + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33 + ], + "cpu": [ + 2.5, + 9.7, + 2.8, + 11.4, + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8 + ], + "ram_used": [ + 63502053376, + 63600914432, + 63612030976, + 63779962880, + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0 + ] + }, + "time": 1790714458.598403 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-2.json new file mode 100644 index 0000000..fea0fec --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-2.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 2, + "run_id": "1df8c923675b", + "corpus_repeated": false, + "time": "2026-09-29T20:40:58", + "prompt_tokens": 4200, + "completion_tokens": 142, + "ttft_s": 2.418, + "e2e_s": 4.063, + "api_prompt_tps": 1736.7, + "api_decode_tps": 85.7, + "engine_prompt_tps": 1772.2, + "engine_decode_tps": 85.5, + "log_lines": [ + "strata serve: prompt 4200 tokens = 0 reused + 4200 read in 2370 ms (1772.2 tok/s), 142 generated in 1660 ms (85.5 tok/s), drafts accepted 96 of 114, 1 checkpoints", + "strata serve: decode expert cache hit rate: 89.6% (64163 hits / 71608 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context better.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + } + ], + "requests_kept": 15, + "totals": { + "since": 1790713882.6043305, + "requests": 15, + "prompt_tokens": 125140, + "reused": 0, + "output_tokens": 2854, + "prompt_ms": 67279.5, + "decode_ms": 33024.09999999999 + }, + "hardware": { + "gpu_util": 98, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 276.727, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 4551.6005859375, + "gpu_pcie_tx_mb": 1681.041015625, + "cpu": 100.0, + "ram_used": 63441051648, + "ram_total": 177175990272, + "disk_read_mb": 2.097570021071815, + "disk_write_mb": 0.10077293695540748, + "tok_s": 98.25687730909294, + "tok_s_mean": 85.16861474502441 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97, + 0, + 98, + 99, + 98 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46, + 42, + 46, + 45, + 46 + ], + "gpu_power": [ + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79, + 215.59, + 278.37, + 251.8, + 276.73 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33, + 3342.49, + 34.05, + 7461.5, + 4551.6 + ], + "cpu": [ + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8, + 14.8, + 15.8, + 37.5, + 100.0 + ], + "ram_used": [ + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816, + 63401848832, + 63554486272, + 63453114368, + 63441051648 + ], + "disk_read_mb": [ + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66, + 0.64, + 0.0, + 0.21, + 2.1 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0, + 0.0, + 0.0, + 89.96, + 98.26 + ] + }, + "time": 1790714463.1652913 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-3.json new file mode 100644 index 0000000..bcaa4df --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-3.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 3, + "run_id": "777f84f22df4", + "corpus_repeated": false, + "time": "2026-09-29T20:41:03", + "prompt_tokens": 4201, + "completion_tokens": 256, + "ttft_s": 2.409, + "e2e_s": 5.262, + "api_prompt_tps": 1744.1, + "api_decode_tps": 89.4, + "engine_prompt_tps": 1775.8, + "engine_decode_tps": 89.2, + "log_lines": [ + "strata serve: prompt 4201 tokens = 0 reused + 4201 read in 2366 ms (1775.8 tok/s), 256 generated in 2868 ms (89.2 tok/s), drafts accepted 161 of 222, 1 checkpoints", + "strata serve: decode expert cache hit rate: 96.0% (144002 hits / 149996 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file is the top-level build configuration for the **Strata Engine**. Its primary responsibilities are:\n\n1. **Project Definition**: Sets up the project name (`strata`), version (`0.1.26`), and C++20 standard.\n2. **Backend Selection**: Manages mutually exclusive GPU backends (CU", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + } + ], + "requests_kept": 16, + "totals": { + "since": 1790713882.6043305, + "requests": 16, + "prompt_tokens": 129341, + "reused": 0, + "output_tokens": 3110, + "prompt_ms": 69645.1, + "decode_ms": 35892.49999999999 + }, + "hardware": { + "gpu_util": 96, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 278.057, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.3330078125, + "gpu_pcie_tx_mb": 0.4287109375, + "cpu": 83.5, + "ram_used": 63416299520, + "ram_total": 177175990272, + "disk_read_mb": 2.956676951508761, + "disk_write_mb": 0.16488439273306146, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97, + 0, + 98, + 99, + 98, + 0, + 99, + 100, + 99, + 96, + 96 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46, + 42, + 46, + 45, + 46, + 42, + 45, + 45, + 45, + 46, + 46 + ], + "gpu_power": [ + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79, + 215.59, + 278.37, + 251.8, + 276.73, + 219.4, + 271.43, + 276.62, + 251.66, + 277.46, + 278.06 + ], + "gpu_pcie_rx_mb": [ + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33, + 3342.49, + 34.05, + 7461.5, + 4551.6, + 6961.73, + 24513.15, + 26324.56, + 679.21, + 426.48, + 0.33 + ], + "cpu": [ + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8, + 14.8, + 15.8, + 37.5, + 100.0, + 32.6, + 6.8, + 6.6, + 96.7, + 100.0, + 83.5 + ], + "ram_used": [ + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816, + 63401848832, + 63554486272, + 63453114368, + 63441051648, + 63399321600, + 63389306880, + 63427080192, + 63418408960, + 63417094144, + 63416299520 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66, + 0.64, + 0.0, + 0.21, + 2.1, + 1.17, + 0.0, + 0.0, + 1.29, + 3.73, + 2.96 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0, + 0.0, + 0.0, + 89.96, + 98.26, + 0.0, + 0.0, + 0.0, + 93.47, + 116.21, + 0.0 + ] + }, + "time": 1790714468.9308503 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-16k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-16k-1.json new file mode 100644 index 0000000..f42f93d --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-16k-1.json @@ -0,0 +1,501 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "8f89dfed9af3", + "corpus_repeated": false, + "time": "2026-09-29T22:00:26", + "prompt_tokens": 17344, + "completion_tokens": 8, + "ttft_s": 15.582, + "e2e_s": 15.663, + "api_prompt_tps": 1113.1, + "api_decode_tps": 86.5, + "engine_prompt_tps": 1119.9, + "engine_decode_tps": 83.8, + "log_lines": [ + "strata serve: prompt 17344 tokens = 0 reused + 17344 read in 15487 ms (1119.9 tok/s), 8 generated in 96 ms (83.8 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.3% (4205 hits / 4320 lookups)" + ], + "answer_head": "05449BFC", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719226.530526, + "duration_s": 15.6, + "finish": "stop", + "prompt_tokens": 17344, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 15486.8, + "decode_ms": 95.5, + "decode_tok_s": 83.8, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790719217.9333243, + "duration_s": 8.0, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7, + "decode_tok_s": 58.6, + "hit_rate": 0.94 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790719202.7795203, + "requests": 2, + "prompt_tokens": 24837, + "reused": 0, + "output_tokens": 17, + "prompt_ms": 23348.3, + "decode_ms": 249.2 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 0, + "mem_used": 25171001344, + "mem_total": 25769803776, + "temp": 47, + "power": 148.05 + }, + { + "index": 1, + "util": 40, + "mem_used": 24185339904, + "mem_total": 25769803776, + "temp": 54, + "power": 237.219 + } + ], + "gpu_util": 20.0, + "gpu_mem_used": 49356341248, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 385.269, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 1.7626953125, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 9.1, + "ram_used": 62596341760, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 73.5, + 23.5, + 31.0, + 56.5, + 23.5, + 20.5, + 0.5, + 70.5, + 22.5, + 26.5, + 56.0, + 29.0, + 77.0, + 11.0, + 28.5, + 59.5, + 28.5, + 19.5, + 17.0, + 27.0, + 20.0 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49274552320, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 51, + 53, + 52, + 52, + 52, + 53, + 49, + 51, + 52, + 52, + 53, + 53, + 53, + 52, + 53, + 51, + 53, + 53, + 53, + 53, + 54 + ], + "gpu_power": [ + 257.56, + 245.14, + 244.59, + 244.41, + 244.51, + 244.45, + 244.36, + 244.36, + 244.26, + 244.16, + 244.27, + 244.18, + 244.09, + 243.92, + 243.88, + 245.24, + 443.06, + 409.13, + 432.67, + 433.1, + 400.92, + 389.08, + 278.03, + 383.36, + 392.74, + 440.94, + 403.62, + 421.29, + 427.09, + 407.67, + 422.11, + 423.13, + 417.76, + 440.15, + 377.19, + 403.8, + 385.27 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.57, + 0.62, + 0.67, + 0.57, + 0.62, + 0.62, + 0.67, + 0.62, + 0.62, + 0.67, + 0.62, + 0.57, + 0.62, + 2169.46, + 6179.19, + 3838.3, + 4927.82, + 4008.2, + 7314.58, + 0.95, + 1338.19, + 7892.51, + 3024.72, + 5741.74, + 2921.96, + 5454.83, + 5667.49, + 3768.87, + 6803.13, + 8164.64, + 2711.1, + 5725.29, + 6417.89, + 0.67, + 1.76 + ], + "cpu": [ + 0.0, + 15.8, + 15.7, + 6.4, + 8.0, + 8.1, + 4.7, + 6.7, + 0.9, + 1.5, + 5.3, + 12.5, + 1.6, + 3.2, + 8.4, + 14.2, + 13.2, + 10.5, + 10.5, + 13.4, + 9.0, + 12.2, + 23.9, + 8.1, + 16.5, + 13.0, + 13.0, + 9.0, + 9.7, + 12.8, + 8.6, + 12.9, + 10.4, + 8.6, + 9.0, + 9.4, + 9.1 + ], + "ram_used": [ + 61827047424, + 61871300608, + 61941383168, + 61960540160, + 61978361856, + 61977542656, + 61984432128, + 61992636416, + 61992636416, + 62000824320, + 62002450432, + 62005186560, + 62006108160, + 62014894080, + 62023741440, + 62230065152, + 62246010880, + 62250319872, + 62234144768, + 62227582976, + 62226890752, + 62392664064, + 62490071040, + 62486704128, + 62515294208, + 62517342208, + 62467452928, + 62510080000, + 62495842304, + 62471684096, + 62463819776, + 62459879424, + 62443171840, + 62374465536, + 62303469568, + 62390607872, + 62596341760 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 28.33, + 101.36, + 41.6, + 10.77, + 0.0, + 0.01, + 0.0, + 0.0, + 1.06, + 0.0, + 14.72, + 0.0, + 56.04, + 0.0, + 33.79, + 66.18, + 16.29, + 83.86, + 33.38, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790719242.619913 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-28k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-28k-1.json new file mode 100644 index 0000000..edaf300 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-28k-1.json @@ -0,0 +1,722 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "93a9a0e32114", + "corpus_repeated": false, + "time": "2026-09-29T22:00:42", + "prompt_tokens": 29825, + "completion_tokens": 9, + "ttft_s": 26.19, + "e2e_s": 26.262, + "api_prompt_tps": 1138.8, + "api_decode_tps": 110.5, + "engine_prompt_tps": 1146.7, + "engine_decode_tps": 103.9, + "log_lines": [ + "strata serve: prompt 29825 tokens = 0 reused + 29825 read in 26009 ms (1146.7 tok/s), 9 generated in 87 ms (103.9 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.2% (4241 hits / 4320 lookups)" + ], + "answer_head": "98C00B03", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719242.7790127, + "duration_s": 26.1, + "finish": "stop", + "prompt_tokens": 29825, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 26008.5, + "decode_ms": 86.6, + "decode_tok_s": 103.9, + "hit_rate": 0.982 + }, + { + "projection": null, + "time": 1790719226.530526, + "duration_s": 15.6, + "finish": "stop", + "prompt_tokens": 17344, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 15486.8, + "decode_ms": 95.5, + "decode_tok_s": 83.8, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790719217.9333243, + "duration_s": 8.0, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7, + "decode_tok_s": 58.6, + "hit_rate": 0.94 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790719202.7795203, + "requests": 3, + "prompt_tokens": 54662, + "reused": 0, + "output_tokens": 26, + "prompt_ms": 49356.8, + "decode_ms": 335.79999999999995 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 6, + "mem_used": 25171001344, + "mem_total": 25769803776, + "temp": 47, + "power": 141.832 + }, + { + "index": 1, + "util": 20, + "mem_used": 24185339904, + "mem_total": 25769803776, + "temp": 52, + "power": 243.782 + } + ], + "gpu_util": 13.0, + "gpu_mem_used": 49356341248, + "gpu_mem_total": 51539607552, + "gpu_temp": 52, + "gpu_power": 385.61400000000003, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 16.6, + "ram_used": 62951010304, + "ram_total": 177175990272, + "disk_read_mb": 0.08651659039933747, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 73.5, + 23.5, + 31.0, + 56.5, + 23.5, + 20.5, + 0.5, + 70.5, + 22.5, + 26.5, + 56.0, + 29.0, + 77.0, + 11.0, + 28.5, + 59.5, + 28.5, + 19.5, + 17.0, + 27.0, + 20.0, + 0.0, + 60.5, + 25.5, + 71.0, + 67.0, + 26.5, + 26.5, + 85.0, + 26.0, + 73.5, + 49.5, + 25.0, + 48.0, + 32.0, + 76.5, + 9.0, + 27.5, + 47.5, + 30.0, + 62.5, + 15.5, + 31.5, + 29.0, + 39.5, + 13.0 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49274552320, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 51, + 53, + 52, + 52, + 52, + 53, + 49, + 51, + 52, + 52, + 53, + 53, + 53, + 52, + 53, + 51, + 53, + 53, + 53, + 53, + 54, + 50, + 51, + 53, + 53, + 52, + 54, + 52, + 52, + 53, + 53, + 53, + 53, + 52, + 53, + 54, + 52, + 53, + 52, + 53, + 52, + 52, + 54, + 53, + 54, + 52 + ], + "gpu_power": [ + 244.59, + 244.41, + 244.51, + 244.45, + 244.36, + 244.36, + 244.26, + 244.16, + 244.27, + 244.18, + 244.09, + 243.92, + 243.88, + 245.24, + 443.06, + 409.13, + 432.67, + 433.1, + 400.92, + 389.08, + 278.03, + 383.36, + 392.74, + 440.94, + 403.62, + 421.29, + 427.09, + 407.67, + 422.11, + 423.13, + 417.76, + 440.15, + 377.19, + 403.8, + 385.27, + 299.57, + 398.78, + 401.71, + 449.87, + 430.87, + 402.83, + 439.43, + 401.46, + 455.62, + 425.18, + 404.39, + 417.35, + 406.87, + 423.67, + 422.86, + 404.6, + 421.5, + 402.4, + 422.71, + 432.67, + 398.05, + 455.72, + 434.46, + 403.83, + 385.61 + ], + "gpu_pcie_rx_mb": [ + 0.57, + 0.62, + 0.67, + 0.57, + 0.62, + 0.62, + 0.67, + 0.62, + 0.62, + 0.67, + 0.62, + 0.57, + 0.62, + 2169.46, + 6179.19, + 3838.3, + 4927.82, + 4008.2, + 7314.58, + 0.95, + 1338.19, + 7892.51, + 3024.72, + 5741.74, + 2921.96, + 5454.83, + 5667.49, + 3768.87, + 6803.13, + 8164.64, + 2711.1, + 5725.29, + 6417.89, + 0.67, + 1.76, + 1343.92, + 7796.67, + 10809.8, + 5598.92, + 3013.99, + 91.89, + 4693.79, + 5621.38, + 5381.87, + 7487.25, + 2228.12, + 7344.77, + 3943.44, + 0.81, + 5476.19, + 2437.4, + 6693.74, + 3836.63, + 7843.59, + 5638.65, + 2853.11, + 8215.43, + 8500.96, + 4445.79, + 0.67 + ], + "cpu": [ + 15.7, + 6.4, + 8.0, + 8.1, + 4.7, + 6.7, + 0.9, + 1.5, + 5.3, + 12.5, + 1.6, + 3.2, + 8.4, + 14.2, + 13.2, + 10.5, + 10.5, + 13.4, + 9.0, + 12.2, + 23.9, + 8.1, + 16.5, + 13.0, + 13.0, + 9.0, + 9.7, + 12.8, + 8.6, + 12.9, + 10.4, + 8.6, + 9.0, + 9.4, + 9.1, + 16.9, + 17.1, + 22.7, + 7.5, + 10.8, + 8.9, + 7.3, + 7.3, + 8.3, + 7.7, + 9.8, + 6.9, + 12.4, + 6.4, + 12.2, + 20.6, + 19.9, + 11.0, + 8.1, + 10.3, + 9.8, + 7.6, + 8.1, + 7.3, + 16.6 + ], + "ram_used": [ + 61941383168, + 61960540160, + 61978361856, + 61977542656, + 61984432128, + 61992636416, + 61992636416, + 62000824320, + 62002450432, + 62005186560, + 62006108160, + 62014894080, + 62023741440, + 62230065152, + 62246010880, + 62250319872, + 62234144768, + 62227582976, + 62226890752, + 62392664064, + 62490071040, + 62486704128, + 62515294208, + 62517342208, + 62467452928, + 62510080000, + 62495842304, + 62471684096, + 62463819776, + 62459879424, + 62443171840, + 62374465536, + 62303469568, + 62390607872, + 62596341760, + 62489825280, + 62562496512, + 62577270784, + 62577836032, + 62576951296, + 62564986880, + 62553812992, + 62539886592, + 62533107712, + 62521810944, + 62503256064, + 62503677952, + 62490673152, + 62492131328, + 62495432704, + 62503706624, + 62769029120, + 62766465024, + 62765707264, + 62747688960, + 62726733824, + 62717767680, + 62722011136, + 62728314880, + 62951010304 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 28.33, + 101.36, + 41.6, + 10.77, + 0.0, + 0.01, + 0.0, + 0.0, + 1.06, + 0.0, + 14.72, + 0.0, + 56.04, + 0.0, + 33.79, + 66.18, + 16.29, + 83.86, + 33.38, + 0.0, + 0.0, + 0.0, + 0.0, + 0.73, + 0.0, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.14, + 0.0, + 0.53, + 47.85, + 0.0, + 71.37, + 0.0, + 78.98, + 55.42, + 22.25, + 53.69, + 0.0, + 54.32, + 39.07, + 0.0, + 0.0, + 0.0, + 0.09 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790719269.3852785 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-8k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-8k-1.json new file mode 100644 index 0000000..f2df03e --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-8k-1.json @@ -0,0 +1,352 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "d1d745f05911", + "corpus_repeated": false, + "time": "2026-09-29T22:00:17", + "prompt_tokens": 7493, + "completion_tokens": 9, + "ttft_s": 7.948, + "e2e_s": 8.057, + "api_prompt_tps": 942.8, + "api_decode_tps": 73.4, + "engine_prompt_tps": 953.1, + "engine_decode_tps": 58.6, + "log_lines": [ + "strata serve: prompt 7493 tokens = 0 reused + 7493 read in 7861 ms (953.1 tok/s), 9 generated in 154 ms (58.6 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 94.0% (4062 hits / 4320 lookups)" + ], + "answer_head": "69231569", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719217.9333243, + "duration_s": 8.0, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7, + "decode_tok_s": 58.6, + "hit_rate": 0.94 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790719202.7795203, + "requests": 1, + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 0, + "mem_used": 25139544064, + "mem_total": 25769803776, + "temp": 46, + "power": 145.526 + }, + { + "index": 1, + "util": 41, + "mem_used": 24151785472, + "mem_total": 25769803776, + "temp": 53, + "power": 243.553 + } + ], + "gpu_util": 20.5, + "gpu_mem_used": 49291329536, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 389.079, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.9521484375, + "gpu_pcie_tx_mb": 4154.1572265625, + "cpu": 12.2, + "ram_used": 62392664064, + "ram_total": 177175990272, + "disk_read_mb": 0.0036010722333241606, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 73.5, + 23.5, + 31.0, + 56.5, + 23.5, + 20.5 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49274552320, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 51, + 53, + 52, + 52, + 52, + 53 + ], + "gpu_power": [ + 257.56, + 245.14, + 244.59, + 244.41, + 244.51, + 244.45, + 244.36, + 244.36, + 244.26, + 244.16, + 244.27, + 244.18, + 244.09, + 243.92, + 243.88, + 245.24, + 443.06, + 409.13, + 432.67, + 433.1, + 400.92, + 389.08 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.57, + 0.62, + 0.67, + 0.57, + 0.62, + 0.62, + 0.67, + 0.62, + 0.62, + 0.67, + 0.62, + 0.57, + 0.62, + 2169.46, + 6179.19, + 3838.3, + 4927.82, + 4008.2, + 7314.58, + 0.95 + ], + "cpu": [ + 0.0, + 15.8, + 15.7, + 6.4, + 8.0, + 8.1, + 4.7, + 6.7, + 0.9, + 1.5, + 5.3, + 12.5, + 1.6, + 3.2, + 8.4, + 14.2, + 13.2, + 10.5, + 10.5, + 13.4, + 9.0, + 12.2 + ], + "ram_used": [ + 61827047424, + 61871300608, + 61941383168, + 61960540160, + 61978361856, + 61977542656, + 61984432128, + 61992636416, + 61992636416, + 62000824320, + 62002450432, + 62005186560, + 62006108160, + 62014894080, + 62023741440, + 62230065152, + 62246010880, + 62250319872, + 62234144768, + 62227582976, + 62226890752, + 62392664064 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 28.33, + 101.36, + 41.6, + 10.77, + 0.0, + 0.01, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790719226.4537745 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn/two-turn-16k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn/two-turn-16k-1.json new file mode 100644 index 0000000..96504d4 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn/two-turn-16k-1.json @@ -0,0 +1,755 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "dedda4f9d6be", + "corpus_repeated": false, + "time": "2026-09-29T22:01:09", + "prompt_tokens": 15635, + "completion_tokens": 44, + "ttft_s": 13.63, + "e2e_s": 14.13, + "api_prompt_tps": 1147.1, + "api_decode_tps": 86.1, + "engine_prompt_tps": 1154.6, + "engine_decode_tps": 85.6, + "log_lines": [ + "strata serve: prompt 15635 tokens = 0 reused + 15635 read in 13541 ms (1154.6 tok/s), 44 generated in 514 ms (85.6 tok/s), drafts accepted 30 of 36, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.9% (24433 hits / 24957 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context better.", + "turn2_ttft_s": 0.577, + "turn2_prompt_tokens": 15672, + "turn2_log_lines": [ + "strata serve: prompt 15672 tokens = 15628 reused + 44 read in 490 ms (89.8 tok/s), 48 generated in 567 ms (84.6 tok/s), drafts accepted 28 of 43, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.6% (31236 hits / 31679 lookups)" + ], + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719284.681533, + "duration_s": 1.1, + "finish": "stop", + "prompt_tokens": 15672, + "reused": 15628, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 490.1, + "decode_ms": 567.1, + "decode_tok_s": 84.6, + "hit_rate": 0.986 + }, + { + "projection": null, + "time": 1790719270.0522854, + "duration_s": 14.1, + "finish": "stop", + "prompt_tokens": 15635, + "reused": 0, + "output_tokens": 44, + "engine_generated": 44, + "prompt_ms": 13541.4, + "decode_ms": 513.7, + "decode_tok_s": 85.7, + "hit_rate": 0.979 + }, + { + "projection": null, + "time": 1790719242.7790127, + "duration_s": 26.1, + "finish": "stop", + "prompt_tokens": 29825, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 26008.5, + "decode_ms": 86.6, + "decode_tok_s": 103.9, + "hit_rate": 0.982 + }, + { + "projection": null, + "time": 1790719226.530526, + "duration_s": 15.6, + "finish": "stop", + "prompt_tokens": 17344, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 15486.8, + "decode_ms": 95.5, + "decode_tok_s": 83.8, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790719217.9333243, + "duration_s": 8.0, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7, + "decode_tok_s": 58.6, + "hit_rate": 0.94 + } + ], + "requests_kept": 5, + "totals": { + "since": 1790719202.7795203, + "requests": 5, + "prompt_tokens": 85969, + "reused": 15628, + "output_tokens": 118, + "prompt_ms": 63388.3, + "decode_ms": 1416.6 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 15, + "mem_used": 25191972864, + "mem_total": 25769803776, + "temp": 48, + "power": 148.771 + }, + { + "index": 1, + "util": 0, + "mem_used": 24206311424, + "mem_total": 25769803776, + "temp": 51, + "power": 169.566 + } + ], + "gpu_util": 7.5, + "gpu_mem_used": 49398284288, + "gpu_mem_total": 51539607552, + "gpu_temp": 51, + "gpu_power": 318.337, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 26.1298828125, + "gpu_pcie_tx_mb": 56.265625, + "cpu": 39.7, + "ram_used": 63088369664, + "ram_total": 177175990272, + "disk_read_mb": 1.2843527404984159, + "disk_write_mb": 0.0035875774874257423, + "tok_s": 52.0, + "tok_s_mean": 89.37171592337687 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 23.5, + 31.0, + 56.5, + 23.5, + 20.5, + 0.5, + 70.5, + 22.5, + 26.5, + 56.0, + 29.0, + 77.0, + 11.0, + 28.5, + 59.5, + 28.5, + 19.5, + 17.0, + 27.0, + 20.0, + 0.0, + 60.5, + 25.5, + 71.0, + 67.0, + 26.5, + 26.5, + 85.0, + 26.0, + 73.5, + 49.5, + 25.0, + 48.0, + 32.0, + 76.5, + 9.0, + 27.5, + 47.5, + 30.0, + 62.5, + 15.5, + 31.5, + 29.0, + 39.5, + 13.0, + 0.0, + 69.5, + 24.0, + 30.5, + 61.5, + 27.0, + 62.5, + 17.0, + 26.5, + 53.5, + 23.5, + 29.5, + 29.0, + 41.0, + 7.5 + ], + "gpu_mem_used": [ + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49398284288, + 49398284288 + ], + "gpu_temp": [ + 53, + 52, + 52, + 52, + 53, + 49, + 51, + 52, + 52, + 53, + 53, + 53, + 52, + 53, + 51, + 53, + 53, + 53, + 53, + 54, + 50, + 51, + 53, + 53, + 52, + 54, + 52, + 52, + 53, + 53, + 53, + 53, + 52, + 53, + 54, + 52, + 53, + 52, + 53, + 52, + 52, + 54, + 53, + 54, + 52, + 50, + 51, + 53, + 54, + 52, + 54, + 53, + 53, + 54, + 53, + 53, + 54, + 55, + 53, + 51 + ], + "gpu_power": [ + 409.13, + 432.67, + 433.1, + 400.92, + 389.08, + 278.03, + 383.36, + 392.74, + 440.94, + 403.62, + 421.29, + 427.09, + 407.67, + 422.11, + 423.13, + 417.76, + 440.15, + 377.19, + 403.8, + 385.27, + 299.57, + 398.78, + 401.71, + 449.87, + 430.87, + 402.83, + 439.43, + 401.46, + 455.62, + 425.18, + 404.39, + 417.35, + 406.87, + 423.67, + 422.86, + 404.6, + 421.5, + 402.4, + 422.71, + 432.67, + 398.05, + 455.72, + 434.46, + 403.83, + 385.61, + 282.41, + 360.22, + 446.82, + 449.66, + 410.55, + 427.9, + 441.96, + 389.46, + 451.44, + 439.2, + 402.13, + 441.82, + 408.98, + 365.37, + 318.34 + ], + "gpu_pcie_rx_mb": [ + 3838.3, + 4927.82, + 4008.2, + 7314.58, + 0.95, + 1338.19, + 7892.51, + 3024.72, + 5741.74, + 2921.96, + 5454.83, + 5667.49, + 3768.87, + 6803.13, + 8164.64, + 2711.1, + 5725.29, + 6417.89, + 0.67, + 1.76, + 1343.92, + 7796.67, + 10809.8, + 5598.92, + 3013.99, + 91.89, + 4693.79, + 5621.38, + 5381.87, + 7487.25, + 2228.12, + 7344.77, + 3943.44, + 0.81, + 5476.19, + 2437.4, + 6693.74, + 3836.63, + 7843.59, + 5638.65, + 2853.11, + 8215.43, + 8500.96, + 4445.79, + 0.67, + 0.62, + 4431.82, + 4655.12, + 7505.13, + 4915.86, + 7990.69, + 6352.23, + 3326.13, + 3696.82, + 7077.12, + 4858.06, + 5613.99, + 7732.68, + 0.67, + 26.13 + ], + "cpu": [ + 10.5, + 10.5, + 13.4, + 9.0, + 12.2, + 23.9, + 8.1, + 16.5, + 13.0, + 13.0, + 9.0, + 9.7, + 12.8, + 8.6, + 12.9, + 10.4, + 8.6, + 9.0, + 9.4, + 9.1, + 16.9, + 17.1, + 22.7, + 7.5, + 10.8, + 8.9, + 7.3, + 7.3, + 8.3, + 7.7, + 9.8, + 6.9, + 12.4, + 6.4, + 12.2, + 20.6, + 19.9, + 11.0, + 8.1, + 10.3, + 9.8, + 7.6, + 8.1, + 7.3, + 16.6, + 7.1, + 8.3, + 7.7, + 7.5, + 19.7, + 13.3, + 9.8, + 12.2, + 12.2, + 11.3, + 11.1, + 11.3, + 11.7, + 49.6, + 39.7 + ], + "ram_used": [ + 62250319872, + 62234144768, + 62227582976, + 62226890752, + 62392664064, + 62490071040, + 62486704128, + 62515294208, + 62517342208, + 62467452928, + 62510080000, + 62495842304, + 62471684096, + 62463819776, + 62459879424, + 62443171840, + 62374465536, + 62303469568, + 62390607872, + 62596341760, + 62489825280, + 62562496512, + 62577270784, + 62577836032, + 62576951296, + 62564986880, + 62553812992, + 62539886592, + 62533107712, + 62521810944, + 62503256064, + 62503677952, + 62490673152, + 62492131328, + 62495432704, + 62503706624, + 62769029120, + 62766465024, + 62765707264, + 62747688960, + 62726733824, + 62717767680, + 62722011136, + 62728314880, + 62951010304, + 62691995648, + 62677225472, + 62661165056, + 62640271360, + 62636351488, + 62633791488, + 62731657216, + 62747160576, + 62744502272, + 62746267648, + 62732316672, + 62762123264, + 62711451648, + 62861885440, + 63088369664 + ], + "disk_read_mb": [ + 10.77, + 0.0, + 0.01, + 0.0, + 0.0, + 1.06, + 0.0, + 14.72, + 0.0, + 56.04, + 0.0, + 33.79, + 66.18, + 16.29, + 83.86, + 33.38, + 0.0, + 0.0, + 0.0, + 0.0, + 0.73, + 0.0, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.14, + 0.0, + 0.53, + 47.85, + 0.0, + 71.37, + 0.0, + 78.98, + 55.42, + 22.25, + 53.69, + 0.0, + 54.32, + 39.07, + 0.0, + 0.0, + 0.0, + 0.09, + 0.58, + 0.02, + 0.01, + 0.0, + 0.03, + 0.0, + 2.6, + 6.44, + 7.35, + 8.08, + 4.14, + 2.09, + 0.01, + 2.47, + 1.28 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 52.0 + ] + }, + "time": 1790719286.2452984 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-1.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-1.json new file mode 100644 index 0000000..f92ffc7 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-1.json @@ -0,0 +1,612 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "cfa75b59eb61", + "corpus_repeated": false, + "time": "2026-09-29T21:39:52", + "prompt_tokens": 28314, + "completion_tokens": 256, + "ttft_s": 26.573, + "e2e_s": 29.595, + "api_prompt_tps": 1065.5, + "api_decode_tps": 84.4, + "engine_prompt_tps": 1071.8, + "engine_decode_tps": 83.7, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 26417 ms (1071.8 tok/s), 256 generated in 3058 ms (83.7 tok/s), drafts accepted 147 of 251, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.9% (171443 hits / 173268 lookups)" + ], + "answer_head": "The last file in the repository listing is `docs/DETAILS.md`.\n\n### What `docs/DETAILS.md` does\n\nIt is the comprehensive technical documentation and reference manual for the Strata engine. While the `README.md` focuses on quick installation and high-level usage, `DETAILS.md` provides the deep technic", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717992.6885722, + "duration_s": 29.5, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26416.6, + "decode_ms": 3057.9, + "decode_tok_s": 83.7, + "hit_rate": 0.989 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717968.2500567, + "requests": 1, + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "prompt_ms": 26416.6, + "decode_ms": 3057.9 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 44, + "mem_used": 25196167168, + "mem_total": 25769803776, + "temp": 52, + "power": 244.795 + }, + { + "index": 1, + "util": 0, + "mem_used": 24208408576, + "mem_total": 25769803776, + "temp": 52, + "power": 218.413 + } + ], + "gpu_util": 22.0, + "gpu_mem_used": 49404575744, + "gpu_mem_total": 51539607552, + "gpu_temp": 52, + "gpu_power": 463.20799999999997, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 60.1, + "ram_used": 62328995840, + "ram_total": 177175990272, + "disk_read_mb": 3.420667733965059, + "disk_write_mb": 0.02523147959721329, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 49.5, + 21.5, + 58.5, + 25.5, + 31.5, + 24.0, + 25.0, + 35.0, + 27.0, + 64.5, + 29.0, + 24.5, + 24.5, + 27.0, + 16.0, + 26.0, + 59.5, + 24.5, + 28.5, + 48.0, + 26.5, + 29.0, + 31.0, + 3.0, + 46.0, + 46.0, + 22.0 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49205346304, + 49278746624, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49383604224, + 49404575744, + 49404575744, + 49404575744 + ], + "gpu_temp": [ + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 50, + 49, + 46, + 46, + 46, + 46, + 46, + 46, + 48, + 52, + 53, + 53, + 53, + 53, + 54, + 54, + 53, + 54, + 53, + 53, + 54, + 54, + 54, + 52, + 55, + 53, + 54, + 55, + 54, + 54, + 54, + 55, + 53, + 55, + 55, + 52 + ], + "gpu_power": [ + 260.95, + 248.93, + 247.54, + 246.62, + 246.82, + 246.65, + 246.9, + 246.83, + 246.8, + 246.68, + 246.72, + 246.75, + 246.63, + 246.53, + 246.57, + 246.83, + 236.89, + 159.99, + 79.32, + 65.35, + 64.71, + 64.62, + 64.91, + 91.65, + 314.3, + 428.65, + 367.67, + 455.67, + 441.66, + 390.44, + 440.16, + 375.92, + 453.54, + 370.98, + 401.8, + 438.74, + 379.04, + 440.69, + 353.57, + 419.67, + 435.26, + 406.67, + 447.91, + 390.07, + 459.5, + 448.73, + 405.61, + 374.45, + 407.02, + 468.77, + 463.21 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.62, + 0.67, + 0.57, + 7.87, + 0.62, + 0.62, + 0.67, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 1.38, + 0.57, + 0.76, + 0.86, + 0.91, + 0.81, + 0.86, + 0.86, + 0.81, + 539.92, + 4704.14, + 5432.94, + 3021.19, + 4790.88, + 4142.71, + 2301.69, + 8161.88, + 3244.83, + 5099.68, + 7126.09, + 2825.64, + 6742.29, + 2064.18, + 5534.93, + 4369.31, + 7614.9, + 4834.13, + 2332.54, + 7141.88, + 4942.8, + 3514.62, + 5720.52, + 6970.74, + 14.21, + 15.78, + 30.52, + 0.67 + ], + "cpu": [ + 0.0, + 14.3, + 2.7, + 0.9, + 1.7, + 1.5, + 2.1, + 1.3, + 1.5, + 1.3, + 1.2, + 2.2, + 1.2, + 0.9, + 1.2, + 19.1, + 3.1, + 3.2, + 2.2, + 1.9, + 2.8, + 2.0, + 4.5, + 12.1, + 9.2, + 7.1, + 7.5, + 5.5, + 13.3, + 15.7, + 18.9, + 15.5, + 7.4, + 9.3, + 7.1, + 10.1, + 9.1, + 6.1, + 9.7, + 7.4, + 9.1, + 9.2, + 13.5, + 15.4, + 6.6, + 8.7, + 6.0, + 28.4, + 94.8, + 99.5, + 60.1 + ], + "ram_used": [ + 61824409600, + 61846106112, + 61853241344, + 61854605312, + 61855711232, + 61855694848, + 61853442048, + 61858058240, + 61861154816, + 61861928960, + 61862432768, + 61867282432, + 61861072896, + 61856456704, + 61880406016, + 61890236416, + 61890191360, + 61887963136, + 61887766528, + 61882646528, + 61870043136, + 61879148544, + 61934235648, + 61984825344, + 62089637888, + 62090121216, + 62098157568, + 62098403328, + 62088568832, + 62106021888, + 61750501376, + 61766746112, + 61776080896, + 61778165760, + 61779779584, + 61908017152, + 61907206144, + 61910032384, + 62031020032, + 62033805312, + 62032531456, + 61967249408, + 61974036480, + 61990858752, + 61985890304, + 61979660288, + 61980233728, + 62277226496, + 62302523392, + 62302191616, + 62328995840 + ], + "disk_read_mb": [ + null, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.38, + 66.8, + 0.0, + 24.38, + 0.0, + 55.65, + 33.54, + 0.11, + 67.43, + 0.0, + 83.76, + 1.78, + 79.2, + 71.21, + 0.0, + 79.44, + 0.0, + 77.02, + 53.81, + 0.7, + 42.73, + 0.0, + 0.0, + 0.0, + 1.02, + 5.65, + 4.98, + 3.42 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 48.0, + 86.94, + 102.06, + 0.0 + ] + }, + "time": 1790718022.6741135 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-2.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-2.json new file mode 100644 index 0000000..e7b146c --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-2.json @@ -0,0 +1,707 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "c27c8adc0b65", + "corpus_repeated": false, + "time": "2026-09-29T21:40:22", + "prompt_tokens": 31633, + "completion_tokens": 256, + "ttft_s": 26.904, + "e2e_s": 29.536, + "api_prompt_tps": 1175.8, + "api_decode_tps": 96.9, + "engine_prompt_tps": 1185.2, + "engine_decode_tps": 96.7, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 26691 ms (1185.2 tok/s), 256 generated in 2648 ms (96.7 tok/s), drafts accepted 160 of 214, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (147426 hits / 148799 lookups)" + ], + "answer_head": "I cannot analyze the last file because the provided repository content is truncated. The `docs/DETAILS.md` file cuts off mid-sentence in the \"Using it\" section (`...if y`), and no subsequent files are shown.\n\nHowever, I can analyze the **`chat.py`** file, which is the last *complete* file provided i", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718022.860633, + "duration_s": 29.4, + "finish": "length", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26690.6, + "decode_ms": 2648.4, + "decode_tok_s": 96.7, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790717992.6885722, + "duration_s": 29.5, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26416.6, + "decode_ms": 3057.9, + "decode_tok_s": 83.7, + "hit_rate": 0.989 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717968.2500567, + "requests": 2, + "prompt_tokens": 59947, + "reused": 0, + "output_tokens": 512, + "prompt_ms": 53107.2, + "decode_ms": 5706.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 37, + "mem_used": 25196167168, + "mem_total": 25769803776, + "temp": 51, + "power": 209.254 + }, + { + "index": 1, + "util": 55, + "mem_used": 24208408576, + "mem_total": 25769803776, + "temp": 55, + "power": 248.664 + } + ], + "gpu_util": 46.0, + "gpu_mem_used": 49404575744, + "gpu_mem_total": 51539607552, + "gpu_temp": 55, + "gpu_power": 457.918, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 30.46875, + "gpu_pcie_tx_mb": 164.2216796875, + "cpu": 97.1, + "ram_used": 62326792192, + "ram_total": 177175990272, + "disk_read_mb": 4.657722192080744, + "disk_write_mb": 0.11106875996500236, + "tok_s": 102.58306863780025, + "tok_s_mean": 98.12574884260572 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 49.5, + 21.5, + 58.5, + 25.5, + 31.5, + 24.0, + 25.0, + 35.0, + 27.0, + 64.5, + 29.0, + 24.5, + 24.5, + 27.0, + 16.0, + 26.0, + 59.5, + 24.5, + 28.5, + 48.0, + 26.5, + 29.0, + 31.0, + 3.0, + 46.0, + 46.0, + 22.0, + 59.5, + 29.0, + 60.0, + 26.0, + 31.5, + 71.0, + 32.5, + 28.0, + 66.0, + 23.5, + 24.5, + 18.5, + 29.0, + 28.0, + 78.0, + 30.0, + 73.5, + 16.0, + 28.0, + 25.0, + 28.0, + 29.0, + 66.0, + 26.5, + 18.5, + 43.5, + 46.0 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49205346304, + 49278746624, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49383604224, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744 + ], + "gpu_temp": [ + 46, + 46, + 46, + 46, + 46, + 48, + 52, + 53, + 53, + 53, + 53, + 54, + 54, + 53, + 54, + 53, + 53, + 54, + 54, + 54, + 52, + 55, + 53, + 54, + 55, + 54, + 54, + 54, + 55, + 53, + 55, + 55, + 52, + 52, + 54, + 54, + 54, + 55, + 55, + 55, + 54, + 54, + 54, + 54, + 54, + 54, + 54, + 55, + 55, + 55, + 54, + 55, + 54, + 55, + 55, + 55, + 55, + 53, + 55, + 55 + ], + "gpu_power": [ + 79.32, + 65.35, + 64.71, + 64.62, + 64.91, + 91.65, + 314.3, + 428.65, + 367.67, + 455.67, + 441.66, + 390.44, + 440.16, + 375.92, + 453.54, + 370.98, + 401.8, + 438.74, + 379.04, + 440.69, + 353.57, + 419.67, + 435.26, + 406.67, + 447.91, + 390.07, + 459.5, + 448.73, + 405.61, + 374.45, + 407.02, + 468.77, + 463.21, + 376.39, + 436.62, + 444.21, + 398.6, + 447.75, + 406.3, + 391.79, + 452.85, + 427.37, + 418.5, + 444.64, + 378.02, + 407.95, + 435.96, + 404.27, + 456.87, + 440.61, + 401.93, + 421.84, + 438.49, + 398.65, + 446.07, + 421.03, + 422.3, + 368.39, + 434.33, + 457.92 + ], + "gpu_pcie_rx_mb": [ + 0.91, + 0.81, + 0.86, + 0.86, + 0.81, + 539.92, + 4704.14, + 5432.94, + 3021.19, + 4790.88, + 4142.71, + 2301.69, + 8161.88, + 3244.83, + 5099.68, + 7126.09, + 2825.64, + 6742.29, + 2064.18, + 5534.93, + 4369.31, + 7614.9, + 4834.13, + 2332.54, + 7141.88, + 4942.8, + 3514.62, + 5720.52, + 6970.74, + 14.21, + 15.78, + 30.52, + 0.67, + 4175.19, + 7742.45, + 4905.89, + 4411.55, + 4744.0, + 6063.36, + 4488.9, + 7846.78, + 7336.33, + 4790.3, + 4790.26, + 4959.82, + 3664.44, + 6053.92, + 4708.72, + 5601.93, + 6957.58, + 5201.77, + 7840.16, + 7413.0, + 3656.91, + 7095.34, + 5569.93, + 6273.89, + 9.44, + 21.46, + 30.47 + ], + "cpu": [ + 2.2, + 1.9, + 2.8, + 2.0, + 4.5, + 12.1, + 9.2, + 7.1, + 7.5, + 5.5, + 13.3, + 15.7, + 18.9, + 15.5, + 7.4, + 9.3, + 7.1, + 10.1, + 9.1, + 6.1, + 9.7, + 7.4, + 9.1, + 9.2, + 13.5, + 15.4, + 6.6, + 8.7, + 6.0, + 28.4, + 94.8, + 99.5, + 60.1, + 6.9, + 5.7, + 6.7, + 6.1, + 6.3, + 13.9, + 10.0, + 6.4, + 7.2, + 5.7, + 6.4, + 6.6, + 6.1, + 5.5, + 6.3, + 6.6, + 7.5, + 6.5, + 6.4, + 17.9, + 10.2, + 6.4, + 7.9, + 6.6, + 24.8, + 93.3, + 97.1 + ], + "ram_used": [ + 61887766528, + 61882646528, + 61870043136, + 61879148544, + 61934235648, + 61984825344, + 62089637888, + 62090121216, + 62098157568, + 62098403328, + 62088568832, + 62106021888, + 61750501376, + 61766746112, + 61776080896, + 61778165760, + 61779779584, + 61908017152, + 61907206144, + 61910032384, + 62031020032, + 62033805312, + 62032531456, + 61967249408, + 61974036480, + 61990858752, + 61985890304, + 61979660288, + 61980233728, + 62277226496, + 62302523392, + 62302191616, + 62328995840, + 62040481792, + 62030888960, + 62024949760, + 62010191872, + 62003638272, + 62026113024, + 62011977728, + 61980151808, + 61970239488, + 61954445312, + 61954318336, + 61948420096, + 61997678592, + 62080253952, + 62075203584, + 62075965440, + 62076403712, + 62076399616, + 62070407168, + 62091988992, + 62091988992, + 62093479936, + 62097862656, + 62095917056, + 62331494400, + 62325518336, + 62326792192 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.38, + 66.8, + 0.0, + 24.38, + 0.0, + 55.65, + 33.54, + 0.11, + 67.43, + 0.0, + 83.76, + 1.78, + 79.2, + 71.21, + 0.0, + 79.44, + 0.0, + 77.02, + 53.81, + 0.7, + 42.73, + 0.0, + 0.0, + 0.0, + 1.02, + 5.65, + 4.98, + 3.42, + 0.54, + 0.0, + 0.01, + 0.02, + 0.0, + 0.02, + 0.03, + 0.0, + 0.03, + 0.02, + 0.0, + 0.01, + 0.0, + 0.01, + 0.02, + 0.0, + 0.0, + 12.64, + 0.0, + 71.65, + 32.97, + 0.0, + 0.0, + 0.0, + 0.99, + 5.21, + 4.66 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 48.0, + 86.94, + 102.06, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 56.0, + 103.48, + 102.58 + ] + }, + "time": 1790718052.712857 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-3.json b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-3.json new file mode 100644 index 0000000..af133b7 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-3.json @@ -0,0 +1,721 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "60c6cbe1b14a", + "corpus_repeated": false, + "time": "2026-09-29T21:40:52", + "prompt_tokens": 31603, + "completion_tokens": 256, + "ttft_s": 27.476, + "e2e_s": 30.102, + "api_prompt_tps": 1150.2, + "api_decode_tps": 97.1, + "engine_prompt_tps": 1158.9, + "engine_decode_tps": 96.9, + "log_lines": [ + "strata serve: prompt 31603 tokens = 0 reused + 31603 read in 27271 ms (1158.9 tok/s), 256 generated in 2641 ms (96.9 tok/s), drafts accepted 154 of 209, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.6% (148622 hits / 149275 lookups)" + ], + "answer_head": "An analysis of the last file (`docs/DETAILS.md`) and a proposed improvement follows.\n\n### What the file does\n\n`docs/DETAILS.md` serves as the comprehensive technical manual for the Strata engine. It bridges the gap between the high-level marketing in the `README.md` and the raw source code. Specific", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718052.8930452, + "duration_s": 29.9, + "finish": "length", + "prompt_tokens": 31603, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 27270.7, + "decode_ms": 2641.1, + "decode_tok_s": 96.9, + "hit_rate": 0.996 + }, + { + "projection": null, + "time": 1790718022.860633, + "duration_s": 29.4, + "finish": "length", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26690.6, + "decode_ms": 2648.4, + "decode_tok_s": 96.7, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790717992.6885722, + "duration_s": 29.5, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26416.6, + "decode_ms": 3057.9, + "decode_tok_s": 83.7, + "hit_rate": 0.989 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717968.2500567, + "requests": 3, + "prompt_tokens": 91550, + "reused": 0, + "output_tokens": 768, + "prompt_ms": 80377.9, + "decode_ms": 8347.4 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 43, + "mem_used": 25196167168, + "mem_total": 25769803776, + "temp": 52, + "power": 242.95 + }, + { + "index": 1, + "util": 65, + "mem_used": 24208408576, + "mem_total": 25769803776, + "temp": 55, + "power": 253.875 + } + ], + "gpu_util": 54.0, + "gpu_mem_used": 49404575744, + "gpu_mem_total": 51539607552, + "gpu_temp": 55, + "gpu_power": 496.825, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 11.77734375, + "gpu_pcie_tx_mb": 120.830078125, + "cpu": 85.4, + "ram_used": 62122582016, + "ram_total": 177175990272, + "disk_read_mb": 2.9330443322466575, + "disk_write_mb": 0.08616042102070966, + "tok_s": 82.32972941826796, + "tok_s_mean": 95.05553044960695 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 31.0, + 3.0, + 46.0, + 46.0, + 22.0, + 59.5, + 29.0, + 60.0, + 26.0, + 31.5, + 71.0, + 32.5, + 28.0, + 66.0, + 23.5, + 24.5, + 18.5, + 29.0, + 28.0, + 78.0, + 30.0, + 73.5, + 16.0, + 28.0, + 25.0, + 28.0, + 29.0, + 66.0, + 26.5, + 18.5, + 43.5, + 46.0, + 0.0, + 64.5, + 26.0, + 23.0, + 72.5, + 27.0, + 66.0, + 24.5, + 76.5, + 60.5, + 27.5, + 57.5, + 24.5, + 32.0, + 66.5, + 26.0, + 27.0, + 64.5, + 29.5, + 52.5, + 65.5, + 24.0, + 23.5, + 85.0, + 30.5, + 9.5, + 46.0, + 54.0 + ], + "gpu_mem_used": [ + 49295523840, + 49383604224, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744 + ], + "gpu_temp": [ + 55, + 53, + 55, + 55, + 52, + 52, + 54, + 54, + 54, + 55, + 55, + 55, + 54, + 54, + 54, + 54, + 54, + 54, + 54, + 55, + 55, + 55, + 54, + 55, + 54, + 55, + 55, + 55, + 55, + 53, + 55, + 55, + 53, + 54, + 55, + 55, + 54, + 55, + 55, + 55, + 56, + 54, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 54, + 55, + 55, + 55, + 55, + 56, + 55, + 56, + 54, + 56, + 55 + ], + "gpu_power": [ + 405.61, + 374.45, + 407.02, + 468.77, + 463.21, + 376.39, + 436.62, + 444.21, + 398.6, + 447.75, + 406.3, + 391.79, + 452.85, + 427.37, + 418.5, + 444.64, + 378.02, + 407.95, + 435.96, + 404.27, + 456.87, + 440.61, + 401.93, + 421.84, + 438.49, + 398.65, + 446.07, + 421.03, + 422.3, + 368.39, + 434.33, + 457.92, + 400.91, + 379.28, + 435.92, + 440.53, + 380.92, + 451.07, + 408.21, + 436.33, + 435.94, + 414.69, + 425.45, + 442.33, + 389.05, + 457.45, + 433.14, + 411.6, + 454.98, + 417.2, + 434.56, + 447.81, + 430.75, + 413.26, + 446.25, + 404.97, + 437.77, + 402.11, + 426.81, + 496.82 + ], + "gpu_pcie_rx_mb": [ + 6970.74, + 14.21, + 15.78, + 30.52, + 0.67, + 4175.19, + 7742.45, + 4905.89, + 4411.55, + 4744.0, + 6063.36, + 4488.9, + 7846.78, + 7336.33, + 4790.3, + 4790.26, + 4959.82, + 3664.44, + 6053.92, + 4708.72, + 5601.93, + 6957.58, + 5201.77, + 7840.16, + 7413.0, + 3656.91, + 7095.34, + 5569.93, + 6273.89, + 9.44, + 21.46, + 30.47, + 0.67, + 4040.72, + 6771.71, + 4774.76, + 3710.08, + 6013.11, + 4218.43, + 89.64, + 5065.25, + 4264.21, + 7538.94, + 3521.39, + 1962.57, + 7673.88, + 4194.59, + 12185.76, + 7580.33, + 5805.73, + 5337.71, + 5530.07, + 5019.52, + 94.17, + 4176.62, + 7140.59, + 4804.28, + 0.62, + 11.11, + 11.78 + ], + "cpu": [ + 6.0, + 28.4, + 94.8, + 99.5, + 60.1, + 6.9, + 5.7, + 6.7, + 6.1, + 6.3, + 13.9, + 10.0, + 6.4, + 7.2, + 5.7, + 6.4, + 6.6, + 6.1, + 5.5, + 6.3, + 6.6, + 7.5, + 6.5, + 6.4, + 17.9, + 10.2, + 6.4, + 7.9, + 6.6, + 24.8, + 93.3, + 97.1, + 28.6, + 7.9, + 6.3, + 6.6, + 5.7, + 7.6, + 16.1, + 12.3, + 6.8, + 6.9, + 6.2, + 7.1, + 5.6, + 6.4, + 6.7, + 5.7, + 7.5, + 6.5, + 6.0, + 8.4, + 15.8, + 7.4, + 8.5, + 6.1, + 5.7, + 7.0, + 74.1, + 85.4 + ], + "ram_used": [ + 61980233728, + 62277226496, + 62302523392, + 62302191616, + 62328995840, + 62040481792, + 62030888960, + 62024949760, + 62010191872, + 62003638272, + 62026113024, + 62011977728, + 61980151808, + 61970239488, + 61954445312, + 61954318336, + 61948420096, + 61997678592, + 62080253952, + 62075203584, + 62075965440, + 62076403712, + 62076399616, + 62070407168, + 62091988992, + 62091988992, + 62093479936, + 62097862656, + 62095917056, + 62331494400, + 62325518336, + 62326792192, + 62020993024, + 62018838528, + 62010839040, + 62003871744, + 61990277120, + 61970149376, + 61773103104, + 61820641280, + 61810376704, + 61790760960, + 61782196224, + 61814075392, + 61809737728, + 61808422912, + 61930074112, + 61927755776, + 61912608768, + 61800587264, + 61798178816, + 61793333248, + 61882507264, + 61882978304, + 61885661184, + 61886173184, + 61886357504, + 62129778688, + 62122844160, + 62122582016 + ], + "disk_read_mb": [ + 0.0, + 1.02, + 5.65, + 4.98, + 3.42, + 0.54, + 0.0, + 0.01, + 0.02, + 0.0, + 0.02, + 0.03, + 0.0, + 0.03, + 0.02, + 0.0, + 0.01, + 0.0, + 0.01, + 0.02, + 0.0, + 0.0, + 12.64, + 0.0, + 71.65, + 32.97, + 0.0, + 0.0, + 0.0, + 0.99, + 5.21, + 4.66, + 2.02, + 0.04, + 0.0, + 0.02, + 0.04, + 0.0, + 0.04, + 0.0, + 0.05, + 0.05, + 0.0, + 0.05, + 0.04, + 0.0, + 0.04, + 0.04, + 0.0, + 0.02, + 0.03, + 0.0, + 0.01, + 0.0, + 0.16, + 0.0, + 0.0, + 0.0, + 3.86, + 2.93 + ], + "tok_s": [ + 0.0, + 48.0, + 86.94, + 102.06, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 56.0, + 103.48, + 102.58, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 114.9, + 82.33 + ] + }, + "time": 1790718083.3185816 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/data/strata-bench.py b/bench/results/2026-09-29-rtx3090-epyc-milan/data/strata-bench.py new file mode 100644 index 0000000..ed92ede --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/data/strata-bench.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +"""Strata benchmark harness (contribution plan, PR 1 step 1.2). + +Follows the upstream method (bench/results/2026-09-28-speed-0114): one code-agent prompt per +length, greedy, 256 generated tokens, MTP as configured by setup. Every run gets a unique +prefix, so conversation checkpoints cannot skip the prompt. Numbers come from the engine log +lines the owner asks for in issue #74. /metrics and API timing are stored as cross-checks. + +Stdlib only. Examples: + ./strata-bench.py --label IQ3_XXS-1x3090 --log ./strata-iq3_xxs.log + ./strata-bench.py --label Coder-2x3090-auto --contexts 16k,28k --mode needle + ./strata-bench.py --url http://127.0.0.1:9292 --model flash-next-strata --label via-llama-swap +""" + +import argparse +import json +import os +import re +import statistics +import sys +import time +import urllib.error +import urllib.request +import uuid +from datetime import datetime +from pathlib import Path + +NOMINAL = {"1k": 1024, "2.7k": 2765, "4k": 4096, "8k": 8192, "16k": 16384, "28k": 28672, + "32k": 32768, "64k": 65536, "128k": 131072, "262k": 262144} +CODE_EXT = {".py", ".cpp", ".cc", ".h", ".hpp", ".cu", ".cuh", ".js", ".md", ".txt", ".cmake"} +SKIP_DIRS = {".git", ".venv", "build", "engine", "third_party", "node_modules", "models", + "packs", "mtp", "bench", "data", "__pycache__", "Strata-data"} +LOG_PATTERNS = [ + re.compile(r"decode expert cache hit rate", re.I), + re.compile(r"\bPCIe\b"), + re.compile(r"prompt .*tok/s.*generated .*tok/s", re.I), + re.compile(r"reus|checkpoint", re.I), + re.compile(r"layer split", re.I), +] +TOKS_PER_S = re.compile(r"([\d][\d,]*(?:\.\d+)?)\s*tok(?:ens)?/s", re.I) + + +def load_corpus(dirs): + parts = [] + for d in dirs: + root = Path(d) + for p in sorted(root.rglob("*")): + if p.suffix.lower() not in CODE_EXT or not p.is_file(): + continue + if any(s in SKIP_DIRS for s in p.relative_to(root).parts[:-1]): + continue + text = p.read_text(encoding="utf-8", errors="ignore") + if text.strip(): + parts.append(f"### {p.relative_to(root).as_posix()}\n```\n{text}\n```\n") + if not parts: + sys.exit(f"no source files found in {dirs}") + return parts + + +def build_text(parts, n_chars): + out, size, i, repeated = [], 0, 0, False + while size < n_chars: + if i and i % len(parts) == 0: + repeated = True + chunk = parts[i % len(parts)] + out.append(chunk) + size += len(chunk) + i += 1 + return "".join(out)[:n_chars], repeated + + +def post_stream(url, payload, api_key, timeout): + req = urllib.request.Request( + f"{url}/v1/chat/completions", data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json", "Authorization": f"Bearer {api_key or 'none'}"}) + t0 = time.perf_counter() + t_first, text, reasoning, usage, chunks = None, [], [], {}, 0 + with urllib.request.urlopen(req, timeout=timeout) as resp: + for raw in resp: + line = raw.decode("utf-8", errors="ignore").strip() + if not line.startswith("data:"): + continue + data = line[5:].strip() + if data == "[DONE]": + break + try: + chunk = json.loads(data) + except json.JSONDecodeError: + continue + if chunk.get("usage"): + usage = chunk["usage"] + for ch in chunk.get("choices") or []: + delta = ch.get("delta") or {} + piece = delta.get("content") or "" + rpiece = delta.get("reasoning_content") or "" + if (piece or rpiece) and t_first is None: + t_first = time.perf_counter() + if piece or rpiece: + chunks += 1 + text.append(piece) + reasoning.append(rpiece) + t_end = time.perf_counter() + return {"t_start": t0, "t_first": t_first or t_end, "t_end": t_end, "text": "".join(text), + "reasoning": "".join(reasoning), "usage": usage, "chunks": chunks} + + +def get_json(url, path, api_key, timeout=10): + try: + req = urllib.request.Request(f"{url}{path}", headers={"Authorization": f"Bearer {api_key or 'none'}"}) + with urllib.request.urlopen(req, timeout=timeout) as r: + body = r.read().decode("utf-8", errors="ignore") + try: + return json.loads(body) + except json.JSONDecodeError: + return body + except (urllib.error.URLError, TimeoutError) as e: + return {"error": str(e)} + + +def wait_healthy(url, api_key, timeout): + deadline = time.time() + timeout + while time.time() < deadline: + h = get_json(url, "/health", api_key, timeout=5) + if not (isinstance(h, dict) and "error" in h): + return True + time.sleep(5) + return False + + +def log_offset(log): + return log.stat().st_size if log and log.exists() else 0 + + +def log_lines_since(log, offset): + if not log or not log.exists(): + return [] + time.sleep(0.5) + with log.open("r", encoding="utf-8", errors="ignore") as f: + f.seek(offset) + new = f.read().splitlines() + return [ln for ln in new if any(p.search(ln) for p in LOG_PATTERNS)] + + +def engine_numbers(lines): + """Best effort: the last 'prompt ... tok/s ... generated ... tok/s' line -> (prompt, decode).""" + for ln in reversed(lines): + if LOG_PATTERNS[2].search(ln): + vals = [float(v.replace(",", "")) for v in TOKS_PER_S.findall(ln)] + if len(vals) >= 2: + return vals[0], vals[1] + return None, None + + +def target_tokens(key, max_tokens): + n = NOMINAL[key] + # leave room for the answer, like upstream's 259,943-token "262K" prompt + return n - max_tokens - 1024 if n >= 32768 else n + + +def make_messages(mode, parts, n_chars, run_id): + body, repeated = build_text(parts, n_chars) + system = f"[bench run {run_id}] You are a coding agent working in the repository shown below." + if mode == "needle": + word = uuid.uuid4().hex[:8].upper() + mid = len(body) // 2 + body = f"{body[:mid]}\n# NOTE: the secret code word is {word}.\n{body[mid:]}" + task = "What is the secret code word mentioned in the files above? Answer with the word only." + else: + word = None + task = ("Task: explain what the last file above does, then propose one concrete improvement " + "as a unified diff.") + msgs = [{"role": "system", "content": system}, + {"role": "user", "content": f"Repository files:\n\n{body}\n\n{task}"}] + return msgs, word, repeated + + +def run_once(a, parts, key, run, cpt): + tgt = target_tokens(key, a.max_tokens) + run_id = uuid.uuid4().hex[:12] + msgs, word, repeated = make_messages(a.mode, parts, int(tgt * cpt), run_id) + payload = {"model": a.model, "messages": msgs, "max_tokens": a.max_tokens, "stream": True, + "stream_options": {"include_usage": True}, "temperature": 0, + "reasoning_effort": a.reasoning_effort} + off = log_offset(a.log) + rec = {"label": a.label, "mode": a.mode, "ctx": key, "target_tokens": tgt, "run": run, + "run_id": run_id, "corpus_repeated": repeated, "time": datetime.now().isoformat(timespec="seconds")} + try: + r = post_stream(a.url, payload, a.api_key, a.timeout) + except Exception as e: # noqa: BLE001 - record and continue with the next cell + rec["error"] = str(e)[:300] + return rec, cpt + pt = r["usage"].get("prompt_tokens") + ct = r["usage"].get("completion_tokens") or r["chunks"] + ttft = r["t_first"] - r["t_start"] + dec_t = r["t_end"] - r["t_first"] + lines = log_lines_since(a.log, off) + e_prompt, e_decode = engine_numbers(lines) + rec.update({ + "prompt_tokens": pt, "completion_tokens": ct, + "ttft_s": round(ttft, 3), "e2e_s": round(r["t_end"] - r["t_start"], 3), + "api_prompt_tps": round(pt / ttft, 1) if pt and ttft > 0 else None, + "api_decode_tps": round((ct - 1) / dec_t, 1) if ct and ct > 1 and dec_t > 0 else None, + "engine_prompt_tps": e_prompt, "engine_decode_tps": e_decode, + "log_lines": lines, "answer_head": r["text"][:300], + }) + if word: + rec["needle_found"] = word in r["text"].upper() or word in r["reasoning"].upper() + if a.mode == "two-turn": + follow = msgs + [{"role": "assistant", "content": r["text"]}, + {"role": "user", "content": "Summarize your answer in one sentence."}] + off2 = log_offset(a.log) + r2 = post_stream(a.url, {**payload, "messages": follow, "max_tokens": 64}, a.api_key, a.timeout) + rec["turn2_ttft_s"] = round(r2["t_first"] - r2["t_start"], 3) + rec["turn2_prompt_tokens"] = r2["usage"].get("prompt_tokens") + rec["turn2_log_lines"] = log_lines_since(a.log, off2) + if pt: + cpt = (int(tgt * cpt) + 400) / pt # refine chars per token for the next cells + return rec, cpt + + +def write_md(path, recs, label): + def med(vals): + vals = [v for v in vals if v is not None] + return round(statistics.median(vals), 1) if vals else None + + rows = ["| ctx | prompt tokens | runs | TTFT s (med) | prompt tok/s engine / API (med) " + "| decode tok/s engine / API (run 1) | decode tok/s engine / API (med) | needle |", + "|---|---|---|---|---|---|---|---|"] + for key in dict.fromkeys(r["ctx"] for r in recs): + rs = [r for r in recs if r["ctx"] == key and "error" not in r] + errs = sum(1 for r in recs if r["ctx"] == key and "error" in r) + if not rs: + rows.append(f"| {key} | - | 0 ({errs} errors) | | | | | |") + continue + first = rs[0] + needle = "" if rs[0].get("needle_found") is None else f"{sum(r['needle_found'] for r in rs)}/{len(rs)}" + rows.append( + f"| {key} | {rs[0]['prompt_tokens']} | {len(rs)}{f' ({errs} err)' if errs else ''} " + f"| {med(r['ttft_s'] for r in rs)} " + f"| {med(r['engine_prompt_tps'] for r in rs)} / {med(r['api_prompt_tps'] for r in rs)} " + f"| {first['engine_decode_tps']} / {first['api_decode_tps']} " + f"| {med(r['engine_decode_tps'] for r in rs)} / {med(r['api_decode_tps'] for r in rs)} | {needle} |") + path.write_text(f"# {label}\n\n" + "\n".join(rows) + "\n", encoding="utf-8") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--url", default="http://127.0.0.1:8090") + ap.add_argument("--model", default="strata", help="model name sent (llama-swap: the model id)") + ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", "")) + ap.add_argument("--label", required=True, help="e.g. IQ3_XXS-1x3090-calibrated") + ap.add_argument("--contexts", default="1k,4k,32k,128k", help=f"comma list of {','.join(NOMINAL)}") + ap.add_argument("--repeats", type=int, default=3) + ap.add_argument("--max-tokens", type=int, default=256) + ap.add_argument("--reasoning-effort", default="none") + ap.add_argument("--mode", choices=["speed", "needle", "two-turn"], default="speed") + ap.add_argument("--source-dir", action="append", default=None, + help="code corpus for the prompts (default: current directory, the Strata repo)") + ap.add_argument("--log", type=Path, default=None, + help="engine log, e.g. ./strata-iq3_xxs.log") + ap.add_argument("--out", type=Path, default=Path(f"./benchmark-output/{datetime.now():%Y-%m-%d}")) + ap.add_argument("--timeout", type=float, default=1800, help="per request, seconds (262K prefill takes minutes)") + ap.add_argument("--chars-per-token", type=float, default=3.4, help="start value, refined after each run") + a = ap.parse_args() + + keys = [k.strip().lower() for k in a.contexts.split(",") if k.strip()] + bad = [k for k in keys if k not in NOMINAL] + if bad: + sys.exit(f"unknown context(s): {bad}") + parts = load_corpus(a.source_dir or ["."]) + if a.log and not a.log.exists(): + print(f"warning: log {a.log} not found; engine numbers will be empty", file=sys.stderr) + if not wait_healthy(a.url, a.api_key, 900): + sys.exit(f"{a.url}/health not reachable") + + out = a.out / a.label + (out / "data").mkdir(parents=True, exist_ok=True) + recs, cpt = [], a.chars_per_token + for key in keys: + for run in range(1, a.repeats + 1): + rec, cpt = run_once(a, parts, key, run, cpt) + rec["metrics_after"] = get_json(a.url, "/metrics", a.api_key) + recs.append(rec) + (out / "data" / f"{a.mode}-{key}-{run}.json").write_text(json.dumps(rec, indent=1), encoding="utf-8") + status = rec.get("error") or (f"prompt {rec['prompt_tokens']} tok, TTFT {rec['ttft_s']} s, " + f"decode engine {rec['engine_decode_tps']} / API {rec['api_decode_tps']} tok/s") + print(f"[{a.label}] {a.mode} {key} run {run}: {status}", flush=True) + + matrix_path = out / "matrix.json" + merged = {} + if matrix_path.exists(): + for record in json.loads(matrix_path.read_text(encoding="utf-8")): + merged[(record["mode"], record["ctx"], record["run"])] = record + for record in recs: + key = (record["mode"], record["ctx"], record["run"]) + merged[key] = {k: v for k, v in record.items() if k != "metrics_after"} + combined = list(merged.values()) + matrix_path.write_text(json.dumps(combined, indent=1), encoding="utf-8") + write_md(out / "matrix.md", combined, f"{a.label} ({a.mode})") + print(f"written: {out}/matrix.md, matrix.json, data/") + + +if __name__ == "__main__": + main() diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/hw.txt b/bench/results/2026-09-29-rtx3090-epyc-milan/hw.txt new file mode 100644 index 0000000..843efcf --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/hw.txt @@ -0,0 +1,86 @@ + +## date (UTC) +2026-09-29T22:07:24Z + +## strata version +v0.1.26 + +## os +PRETTY_NAME="Ubuntu 24.04.5 LTS" +VERSION_ID="24.04" +6.8.0-139-generic + +## virtualization +kvm + +## cpu +CPU(s): 20 +Model name: AMD EPYC 7453 28-Core Processor +Thread(s) per core: 1 +Core(s) per socket: 20 +Socket(s): 1 +L3 cache: 320 MiB (20 instances) +NUMA node(s): 1 + +## cpu flags (relevant) +avx2 f16c fma + +## numa +available: 1 nodes (0) +node 0 cpus: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 +node 0 size: 168968 MB +node 0 free: 47460 MB +node distances: +node 0 + 0: 10 + +## memory + total used free shared buff/cache available +Mem: 165 14 46 0 105 150 +Swap: 0 0 0 + +## dimms +run as root for dmidecode +(in a VM these are virtual DIMMs: fill in the host section below by hand) + +## memlock limit +21627928 + +## gpu +index, name, driver_version, memory.total [MiB], pcie.link.gen.current, pcie.link.gen.max, pcie.link.width.current, pcie.link.width.max, power.limit [W], power.default_limit [W], power.max_limit [W], power.draw [W], clocks.max.sm [MHz] +0, NVIDIA GeForce RTX 3090, 595.91.07, 24576 MiB, 1, 4, 16, 16, 280.00 W, 350.00 W, 366.00 W, 35.23 W, 2130 MHz +1, NVIDIA GeForce RTX 3090, 595.91.07, 24576 MiB, 1, 4, 16, 16, 280.00 W, 420.00 W, 450.00 W, 28.60 W, 2100 MHz + +## gpu topology + GPU0 GPU1 CPU Affinity NUMA Affinity GPU NUMA ID +GPU0 X PHB 0-19 0 N/A +GPU1 PHB X 0-19 0 N/A + +Legend: + + X = Self + SYS = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI) + NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node + PHB = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU) + PXB = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge) + PIX = Connection traversing at most a single PCIe bridge + NV# = Connection traversing a bonded set of # NVLinks + +## gpu processes (must be empty before benchmarking) +pid, process_name, used_gpu_memory [MiB] + +## docker +Docker version 29.8.1, build 4a63305 +NVIDIA Container Toolkit CLI version 1.18.1 + +## disk (model data) +Filesystem Size Used Avail Use% Mounted on +/dev/sdb1 541G 409G 106G 80% + +## host (fill in manually) +- Hypervisor: Proxmox VE (KVM guest; host version not visible inside the VM) +- CPU: AMD EPYC 7453 28-Core Processor (Milan); 20 vCPU exposed, AVX2, no AVX-512 visible +- RAM: 165 GiB visible to the guest; physical DIMM layout and bandwidth not measured +- VM: 20 vCPU, 1 socket x 20 cores x 1 thread, 1 NUMA node; ballooning and pinning not verified +- GPUs: 2x RTX 3090 24 GB; PCIe Gen4 x16 maximum reported for each (current idle link generation varies); configured power limit 280 W each +- Storage: ext4 guest data disk, 541 GiB; host storage layout not verified from the guest diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.json b/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.json new file mode 100644 index 0000000..4cc74c5 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.json @@ -0,0 +1,1294 @@ +[ + { + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "6c1252339f83", + "corpus_repeated": false, + "time": "2026-09-29T21:11:07", + "prompt_tokens": 28317, + "completion_tokens": 48, + "ttft_s": 12.868, + "e2e_s": 13.739, + "api_prompt_tps": 2200.5, + "api_decode_tps": 54.0, + "engine_prompt_tps": 2229.2, + "engine_decode_tps": 52.7, + "log_lines": [ + "strata serve: prompt 28317 tokens = 0 reused + 28317 read in 12703 ms (2229.2 tok/s), 48 generated in 911 ms (52.7 tok/s), drafts accepted 31 of 38, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (25001 hits / 25956 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "894af0ad69b7", + "corpus_repeated": false, + "time": "2026-09-29T21:11:22", + "prompt_tokens": 31630, + "completion_tokens": 26, + "ttft_s": 12.792, + "e2e_s": 13.164, + "api_prompt_tps": 2472.7, + "api_decode_tps": 67.3, + "engine_prompt_tps": 2506.6, + "engine_decode_tps": 66.8, + "log_lines": [ + "strata serve: prompt 31630 tokens = 0 reused + 31630 read in 12619 ms (2506.6 tok/s), 26 generated in 389 ms (66.8 tok/s), drafts accepted 12 of 21, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (16646 hits / 16791 lookups)" + ], + "answer_head": "I don't see any file content in the conversation above. Could you please share the file you'd like me to analyze?" + }, + { + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "a4c63bd599ab", + "corpus_repeated": false, + "time": "2026-09-29T21:11:35", + "prompt_tokens": 31601, + "completion_tokens": 45, + "ttft_s": 12.796, + "e2e_s": 13.243, + "api_prompt_tps": 2469.6, + "api_decode_tps": 98.5, + "engine_prompt_tps": 2502.4, + "engine_decode_tps": 97.4, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 12628 ms (2502.4 tok/s), 45 generated in 462 ms (97.4 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.6% (23985 hits / 24333 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K18", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "052cbcbb7af7", + "corpus_repeated": false, + "time": "2026-09-29T21:21:48", + "prompt_tokens": 28313, + "completion_tokens": 57, + "ttft_s": 12.346, + "e2e_s": 12.991, + "api_prompt_tps": 2293.3, + "api_decode_tps": 86.9, + "engine_prompt_tps": 2324.6, + "engine_decode_tps": 83.1, + "log_lines": [ + "strata serve: prompt 28313 tokens = 0 reused + 28313 read in 12180 ms (2324.6 tok/s), 57 generated in 686 ms (83.1 tok/s), drafts accepted 39 of 41, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.7% (28717 hits / 28800 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "69d919ce1297", + "corpus_repeated": false, + "time": "2026-09-29T21:32:53", + "prompt_tokens": 28316, + "completion_tokens": 57, + "ttft_s": 10.575, + "e2e_s": 11.256, + "api_prompt_tps": 2677.7, + "api_decode_tps": 82.2, + "engine_prompt_tps": 2718.9, + "engine_decode_tps": 79.8, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 10414 ms (2718.9 tok/s), 57 generated in 715 ms (79.8 tok/s), drafts accepted 37 of 48, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34080 hits / 34080 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "8506420b91e1", + "corpus_repeated": false, + "time": "2026-09-29T21:33:04", + "prompt_tokens": 31633, + "completion_tokens": 45, + "ttft_s": 10.85, + "e2e_s": 11.271, + "api_prompt_tps": 2915.4, + "api_decode_tps": 104.6, + "engine_prompt_tps": 2962.7, + "engine_decode_tps": 103.3, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 10677 ms (2962.7 tok/s), 45 generated in 436 ms (103.3 tok/s), drafts accepted 32 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24960 hits / 24960 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what the last file does." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "831d87a1dacc", + "corpus_repeated": false, + "time": "2026-09-29T21:33:16", + "prompt_tokens": 31601, + "completion_tokens": 60, + "ttft_s": 10.877, + "e2e_s": 11.43, + "api_prompt_tps": 2905.4, + "api_decode_tps": 106.7, + "engine_prompt_tps": 2951.6, + "engine_decode_tps": 105.7, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 10706 ms (2951.6 tok/s), 60 generated in 568 ms (105.7 tok/s), drafts accepted 41 of 46, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (31680 hits / 31680 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file does." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "87af67edfd2d", + "corpus_repeated": false, + "time": "2026-09-29T21:34:02", + "prompt_tokens": 28314, + "completion_tokens": 256, + "ttft_s": 10.029, + "e2e_s": 12.977, + "api_prompt_tps": 2823.1, + "api_decode_tps": 86.5, + "engine_prompt_tps": 2871.1, + "engine_decode_tps": 85.9, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 9862 ms (2871.1 tok/s), 256 generated in 2981 ms (85.9 tok/s), drafts accepted 143 of 193, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (147360 hits / 147360 lookups)" + ], + "answer_head": "Looking at the last file above, `docs/AMD_HIP_PERFORMANCE.md`, it documents the performance evidence and correctness limits for the experimental AMD HIP backend targeting gfx1100 (RX 7900 XTX). It records:\n\n- The exact build/runtime configuration used for the benchmark (env vars, CLI flags, model pa" + }, + { + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "b38394f620b3", + "corpus_repeated": false, + "time": "2026-09-29T21:34:15", + "prompt_tokens": 31635, + "completion_tokens": 45, + "ttft_s": 10.269, + "e2e_s": 10.686, + "api_prompt_tps": 3080.5, + "api_decode_tps": 105.5, + "engine_prompt_tps": 3130.4, + "engine_decode_tps": 104.2, + "log_lines": [ + "strata serve: prompt 31635 tokens = 0 reused + 31635 read in 10106 ms (3130.4 tok/s), 45 generated in 432 ms (104.2 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24480 hits / 24480 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "3bee1c1e482a", + "corpus_repeated": false, + "time": "2026-09-29T21:34:26", + "prompt_tokens": 31602, + "completion_tokens": 60, + "ttft_s": 10.281, + "e2e_s": 10.865, + "api_prompt_tps": 3073.8, + "api_decode_tps": 101.0, + "engine_prompt_tps": 3123.2, + "engine_decode_tps": 100.2, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10118 ms (3123.2 tok/s), 60 generated in 599 ms (100.2 tok/s), drafts accepted 40 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34560 hits / 34560 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file does." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "5ca39dba7489", + "corpus_repeated": false, + "time": "2026-09-29T21:35:22", + "prompt_tokens": 28314, + "completion_tokens": 48, + "ttft_s": 9.79, + "e2e_s": 10.297, + "api_prompt_tps": 2892.2, + "api_decode_tps": 92.7, + "engine_prompt_tps": 2940.2, + "engine_decode_tps": 88.8, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 9630 ms (2940.2 tok/s), 48 generated in 540 ms (88.8 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25920 hits / 25920 lookups)" + ], + "answer_head": "I'll first look at the repository structure to understand what files exist and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "14c7210ce0e9", + "corpus_repeated": false, + "time": "2026-09-29T21:35:32", + "prompt_tokens": 31635, + "completion_tokens": 45, + "ttft_s": 10.029, + "e2e_s": 10.496, + "api_prompt_tps": 3154.3, + "api_decode_tps": 94.3, + "engine_prompt_tps": 3205.2, + "engine_decode_tps": 93.5, + "log_lines": [ + "strata serve: prompt 31635 tokens = 0 reused + 31635 read in 9870 ms (3205.2 tok/s), 45 generated in 481 ms (93.5 tok/s), drafts accepted 31 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25440 hits / 25440 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what the last file does." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "3f243fdb63ee", + "corpus_repeated": false, + "time": "2026-09-29T21:35:43", + "prompt_tokens": 31601, + "completion_tokens": 60, + "ttft_s": 10.026, + "e2e_s": 10.61, + "api_prompt_tps": 3151.9, + "api_decode_tps": 101.0, + "engine_prompt_tps": 3208.3, + "engine_decode_tps": 100.2, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 9850 ms (3208.3 tok/s), 60 generated in 599 ms (100.2 tok/s), drafts accepted 40 of 50, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34080 hits / 34080 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file is." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "0796a1ce12e4", + "corpus_repeated": false, + "time": "2026-09-29T21:36:29", + "prompt_tokens": 28316, + "completion_tokens": 57, + "ttft_s": 10.285, + "e2e_s": 10.86, + "api_prompt_tps": 2753.1, + "api_decode_tps": 97.4, + "engine_prompt_tps": 2798.5, + "engine_decode_tps": 93.7, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 10118 ms (2798.5 tok/s), 57 generated in 608 ms (93.7 tok/s), drafts accepted 40 of 42, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (28800 hits / 28800 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "3d5bf2c2aa6f", + "corpus_repeated": false, + "time": "2026-09-29T21:36:40", + "prompt_tokens": 31631, + "completion_tokens": 45, + "ttft_s": 10.58, + "e2e_s": 10.972, + "api_prompt_tps": 2989.7, + "api_decode_tps": 112.3, + "engine_prompt_tps": 3034.9, + "engine_decode_tps": 110.6, + "log_lines": [ + "strata serve: prompt 31631 tokens = 0 reused + 31631 read in 10423 ms (3034.9 tok/s), 45 generated in 407 ms (110.6 tok/s), drafts accepted 33 of 34, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (23040 hits / 23040 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "d22ca9d8c7b8", + "corpus_repeated": false, + "time": "2026-09-29T21:36:51", + "prompt_tokens": 31602, + "completion_tokens": 59, + "ttft_s": 10.575, + "e2e_s": 11.17, + "api_prompt_tps": 2988.5, + "api_decode_tps": 97.4, + "engine_prompt_tps": 3037.5, + "engine_decode_tps": 96.6, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10404 ms (3037.5 tok/s), 59 generated in 611 ms (96.6 tok/s), drafts accepted 41 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (35040 hits / 35040 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "b4895f87f439", + "corpus_repeated": false, + "time": "2026-09-29T21:28:38", + "prompt_tokens": 28316, + "completion_tokens": 45, + "ttft_s": 9.936, + "e2e_s": 10.4, + "api_prompt_tps": 2849.8, + "api_decode_tps": 94.9, + "engine_prompt_tps": 2892.0, + "engine_decode_tps": 94.1, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 9791 ms (2892.0 tok/s), 45 generated in 478 ms (94.1 tok/s), drafts accepted 31 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25440 hits / 25440 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "f81947893a8b", + "corpus_repeated": false, + "time": "2026-09-29T21:28:49", + "prompt_tokens": 31632, + "completion_tokens": 48, + "ttft_s": 11.011, + "e2e_s": 11.496, + "api_prompt_tps": 2872.7, + "api_decode_tps": 97.0, + "engine_prompt_tps": 2926.4, + "engine_decode_tps": 96.1, + "log_lines": [ + "strata serve: prompt 31632 tokens = 0 reused + 31632 read in 10809 ms (2926.4 tok/s), 48 generated in 499 ms (96.1 tok/s), drafts accepted 32 of 38, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (27360 hits / 27360 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "cb947708c5cc", + "corpus_repeated": false, + "time": "2026-09-29T21:29:01", + "prompt_tokens": 31602, + "completion_tokens": 45, + "ttft_s": 10.976, + "e2e_s": 11.378, + "api_prompt_tps": 2879.2, + "api_decode_tps": 109.6, + "engine_prompt_tps": 2920.6, + "engine_decode_tps": 108.0, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10820 ms (2920.6 tok/s), 45 generated in 417 ms (108.0 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24480 hits / 24480 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "3e44ccd7ec28", + "corpus_repeated": false, + "time": "2026-09-29T21:18:00", + "prompt_tokens": 28314, + "completion_tokens": 48, + "ttft_s": 11.385, + "e2e_s": 11.891, + "api_prompt_tps": 2486.9, + "api_decode_tps": 93.0, + "engine_prompt_tps": 2524.7, + "engine_decode_tps": 88.5, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 11215 ms (2524.7 tok/s), 48 generated in 542 ms (88.5 tok/s), drafts accepted 34 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24958 hits / 24960 lookups)" + ], + "answer_head": "I'll first look at the repository structure to understand what files exist and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "0b6b57dfa6a4", + "corpus_repeated": false, + "time": "2026-09-29T21:18:13", + "prompt_tokens": 31634, + "completion_tokens": 55, + "ttft_s": 11.855, + "e2e_s": 12.398, + "api_prompt_tps": 2668.4, + "api_decode_tps": 99.4, + "engine_prompt_tps": 2704.3, + "engine_decode_tps": 98.6, + "log_lines": [ + "strata serve: prompt 31634 tokens = 0 reused + 31634 read in 11698 ms (2704.3 tok/s), 55 generated in 558 ms (98.6 tok/s), drafts accepted 38 of 44, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (29759 hits / 29760 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "caa0b992dd74", + "corpus_repeated": false, + "time": "2026-09-29T21:18:25", + "prompt_tokens": 31601, + "completion_tokens": 45, + "ttft_s": 11.847, + "e2e_s": 12.249, + "api_prompt_tps": 2667.3, + "api_decode_tps": 109.5, + "engine_prompt_tps": 2704.5, + "engine_decode_tps": 108.1, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 11684 ms (2704.5 tok/s), 45 generated in 416 ms (108.1 tok/s), drafts accepted 33 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24000 hits / 24000 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "e13c9cdd6797", + "corpus_repeated": false, + "time": "2026-09-29T21:52:23", + "prompt_tokens": 28315, + "completion_tokens": 84, + "ttft_s": 39.45, + "e2e_s": 40.422, + "api_prompt_tps": 717.7, + "api_decode_tps": 85.4, + "engine_prompt_tps": 720.7, + "engine_decode_tps": 83.1, + "log_lines": [ + "strata serve: prompt 28315 tokens = 0 reused + 28315 read in 39287 ms (720.7 tok/s), 84 generated in 1011 ms (83.1 tok/s), drafts accepted 56 of 67, 2 checkpoints", + "strata serve: decode expert cache hit rate: 94.9% (43073 hits / 45377 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context and find the relevant files." + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "f953f67441b4", + "corpus_repeated": false, + "time": "2026-09-29T21:53:04", + "prompt_tokens": 31633, + "completion_tokens": 88, + "ttft_s": 42.403, + "e2e_s": 43.165, + "api_prompt_tps": 746.0, + "api_decode_tps": 114.2, + "engine_prompt_tps": 749.3, + "engine_decode_tps": 113.3, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 42217 ms (749.3 tok/s), 88 generated in 777 ms (113.3 tok/s), drafts accepted 61 of 69, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.8% (45031 hits / 46048 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the \"last file\" being referenced." + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "4e71f26e7fd8", + "corpus_repeated": false, + "time": "2026-09-29T21:53:48", + "prompt_tokens": 31604, + "completion_tokens": 49, + "ttft_s": 42.269, + "e2e_s": 42.716, + "api_prompt_tps": 747.7, + "api_decode_tps": 107.5, + "engine_prompt_tps": 750.5, + "engine_decode_tps": 106.3, + "log_lines": [ + "strata serve: prompt 31604 tokens = 0 reused + 31604 read in 42111 ms (750.5 tok/s), 49 generated in 461 ms (106.3 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (26163 hits / 26396 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the \"last file\" being referenced." + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "1e52cb484c7f", + "corpus_repeated": false, + "time": "2026-09-29T21:55:17", + "prompt_tokens": 17345, + "completion_tokens": 8, + "ttft_s": 23.389, + "e2e_s": 23.454, + "api_prompt_tps": 741.6, + "api_decode_tps": 106.6, + "engine_prompt_tps": 744.7, + "engine_decode_tps": 101.7, + "log_lines": [ + "strata serve: prompt 17345 tokens = 0 reused + 17345 read in 23292 ms (744.7 tok/s), 8 generated in 79 ms (101.7 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (4159 hits / 4317 lookups)" + ], + "answer_head": "A466BDE8", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "c61aafff2d90", + "corpus_repeated": false, + "time": "2026-09-29T21:55:41", + "prompt_tokens": 29827, + "completion_tokens": 8, + "ttft_s": 39.958, + "e2e_s": 40.036, + "api_prompt_tps": 746.5, + "api_decode_tps": 89.7, + "engine_prompt_tps": 749.2, + "engine_decode_tps": 85.9, + "log_lines": [ + "strata serve: prompt 29827 tokens = 0 reused + 29827 read in 39812 ms (749.2 tok/s), 8 generated in 93 ms (85.9 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.2% (4154 hits / 4318 lookups)" + ], + "answer_head": "7BDBA3C1", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "7c040dd4c6d7", + "corpus_repeated": false, + "time": "2026-09-29T21:55:06", + "prompt_tokens": 7491, + "completion_tokens": 8, + "ttft_s": 10.682, + "e2e_s": 10.776, + "api_prompt_tps": 701.3, + "api_decode_tps": 74.7, + "engine_prompt_tps": 705.0, + "engine_decode_tps": 73.1, + "log_lines": [ + "strata serve: prompt 7491 tokens = 0 reused + 7491 read in 10625 ms (705.0 tok/s), 8 generated in 109 ms (73.1 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 90.2% (3891 hits / 4313 lookups)" + ], + "answer_head": "C43C98BD", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "2fd93144a29a", + "corpus_repeated": false, + "time": "2026-09-29T21:56:47", + "prompt_tokens": 15639, + "completion_tokens": 83, + "ttft_s": 21.242, + "e2e_s": 22.071, + "api_prompt_tps": 736.2, + "api_decode_tps": 98.8, + "engine_prompt_tps": 739.4, + "engine_decode_tps": 98.3, + "log_lines": [ + "strata serve: prompt 15639 tokens = 0 reused + 15639 read in 21151 ms (739.4 tok/s), 83 generated in 844 ms (98.3 tok/s), drafts accepted 53 of 73, 1 checkpoints", + "strata serve: decode expert cache hit rate: 98.5% (48689 hits / 49415 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there.", + "turn2_ttft_s": 0.627, + "turn2_prompt_tokens": 15676, + "turn2_log_lines": [ + "strata serve: prompt 15676 tokens = 15632 reused + 44 read in 521 ms (84.4 tok/s), 64 generated in 739 ms (86.6 tok/s), drafts accepted 37 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.1% (36768 hits / 37868 lookups)" + ] + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 1, + "run_id": "183f9c0b2a25", + "corpus_repeated": false, + "time": "2026-09-29T20:43:56", + "prompt_tokens": 119256, + "completion_tokens": 256, + "ttft_s": 55.136, + "e2e_s": 58.347, + "api_prompt_tps": 2162.9, + "api_decode_tps": 79.4, + "engine_prompt_tps": 2185.1, + "engine_decode_tps": 79.3, + "log_lines": [ + "strata serve: prompt 119256 tokens = 0 reused + 119256 read in 54577 ms (2185.1 tok/s), 256 generated in 3230 ms (79.3 tok/s), drafts accepted 151 of 208, 6 checkpoints", + "strata serve: decode expert cache hit rate: 95.5% (140181 hits / 146787 lookups)" + ], + "answer_head": "The last file shown is `include/strata/kernels/cpu/pool.hpp`. It declares the CPU expert pool (`ExpertPool`), which is the engine's mechanism for computing the routed MoE experts that do not fit in VRAM.\n\n**What it does:**\n\n1. **Thread Management:** It creates a pool of worker threads pinned to phy" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 2, + "run_id": "815c67976126", + "corpus_repeated": false, + "time": "2026-09-29T20:44:54", + "prompt_tokens": 130360, + "completion_tokens": 256, + "ttft_s": 60.567, + "e2e_s": 63.777, + "api_prompt_tps": 2152.3, + "api_decode_tps": 79.4, + "engine_prompt_tps": 2173.6, + "engine_decode_tps": 79.4, + "log_lines": [ + "strata serve: prompt 130360 tokens = 0 reused + 130360 read in 59974 ms (2173.6 tok/s), 256 generated in 3226 ms (79.4 tok/s), drafts accepted 158 of 225, 6 checkpoints", + "strata serve: decode expert cache hit rate: 94.5% (142001 hits / 150326 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing.\n\n## What `include/strata/kernels/gdn.hpp` does\n\nThis header declares the **non-projection parts of the Gated Delta-Net (GDN) layer** \u2014 the \"mixer\" used in 36 of the model's 48 layers (the other 12 are QSA full-attention layers). It is the C++ cou" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 3, + "run_id": "317fbfabc24a", + "corpus_repeated": false, + "time": "2026-09-29T20:45:59", + "prompt_tokens": 129913, + "completion_tokens": 256, + "ttft_s": 60.534, + "e2e_s": 64.056, + "api_prompt_tps": 2146.1, + "api_decode_tps": 72.4, + "engine_prompt_tps": 2168.8, + "engine_decode_tps": 72.0, + "log_lines": [ + "strata serve: prompt 129913 tokens = 0 reused + 129913 read in 59901 ms (2168.8 tok/s), 256 generated in 3556 ms (72.0 tok/s), drafts accepted 148 of 200, 6 checkpoints", + "strata serve: decode expert cache hit rate: 95.6% (138618 hits / 145073 lookups)" + ], + "answer_head": "The last file is `include/strata/kernels/gdn.hpp`. It declares the non-projection parts of the gated delta-net (GDN) layer used by 36 of the model's 48 layers. It defines `GdnShapes` (S=128, h_k=16, h_v=48) and declares `gdn_step`, which performs one in-place step of the delta-rule recurrence: it de" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 1, + "run_id": "56b3dec5f002", + "corpus_repeated": false, + "time": "2026-09-29T20:40:39", + "prompt_tokens": 1092, + "completion_tokens": 256, + "ttft_s": 1.378, + "e2e_s": 4.115, + "api_prompt_tps": 792.3, + "api_decode_tps": 93.2, + "engine_prompt_tps": 808.1, + "engine_decode_tps": 93.0, + "log_lines": [ + "strata serve: prompt 1092 tokens = 0 reused + 1092 read in 1351 ms (808.1 tok/s), 256 generated in 2753 ms (93.0 tok/s), drafts accepted 159 of 210, 1 checkpoints", + "strata serve: decode expert cache hit rate: 95.4% (137036 hits / 143638 lookups)" + ], + "answer_head": "Based on the content of `CMakeLists.txt`, here is an explanation of its function and a proposed improvement.\n\n### Explanation of `CMakeLists.txt`\n\nThis file serves as the top-level build configuration for the **Strata Engine** (version 0.1.26). Its primary responsibilities are:\n\n1. **Project Defini" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 2, + "run_id": "5da89525cd83", + "corpus_repeated": false, + "time": "2026-09-29T20:40:43", + "prompt_tokens": 1149, + "completion_tokens": 256, + "ttft_s": 1.323, + "e2e_s": 4.156, + "api_prompt_tps": 868.4, + "api_decode_tps": 90.0, + "engine_prompt_tps": 885.5, + "engine_decode_tps": 89.9, + "log_lines": [ + "strata serve: prompt 1149 tokens = 0 reused + 1149 read in 1298 ms (885.5 tok/s), 256 generated in 2847 ms (89.9 tok/s), drafts accepted 156 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.1% (144603 hits / 148933 lookups)" + ], + "answer_head": "Based on the content provided, here is an explanation of the `CMakeLists.txt` file and a proposed improvement.\n\n### Explanation of `CMakeLists.txt`\n\nThis file is the top-level build configuration for the **Strata Engine** (specifically Phase 1, Step 1). Its primary responsibilities are:\n\n1. **Proje" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 3, + "run_id": "3ad6050d1d4c", + "corpus_repeated": false, + "time": "2026-09-29T20:40:48", + "prompt_tokens": 1135, + "completion_tokens": 256, + "ttft_s": 1.33, + "e2e_s": 4.007, + "api_prompt_tps": 853.1, + "api_decode_tps": 95.3, + "engine_prompt_tps": 869.7, + "engine_decode_tps": 95.1, + "log_lines": [ + "strata serve: prompt 1135 tokens = 0 reused + 1135 read in 1305 ms (869.7 tok/s), 256 generated in 2691 ms (95.1 tok/s), drafts accepted 159 of 217, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.2% (145229 hits / 149472 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file defines the top-level build configuration for the **Strata Engine** project. Its primary responsibilities include:\n\n1. **Project Definition**: Sets the project name (`strata`), version (`0.1.26`), and language standard (C++20).\n2. **Target Management**: Conditionally adds" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 1, + "run_id": "459ef0e5c155", + "corpus_repeated": false, + "time": "2026-09-29T20:52:28", + "prompt_tokens": 232183, + "completion_tokens": 256, + "ttft_s": 131.32, + "e2e_s": 135.339, + "api_prompt_tps": 1768.1, + "api_decode_tps": 63.4, + "engine_prompt_tps": 1784.6, + "engine_decode_tps": 63.0, + "log_lines": [ + "strata serve: prompt 232183 tokens = 0 reused + 232183 read in 130101 ms (1784.6 tok/s), 256 generated in 4061 ms (63.0 tok/s), drafts accepted 150 of 240, 6 checkpoints", + "strata serve: decode expert cache hit rate: 93.7% (149829 hits / 159942 lookups)" + ], + "answer_head": "The last file is `serve/server.py` (the listing is truncated at the very end, in the `main()` function where it assigns `svc.gpu_index`).\n\n## What it does\n\nIt is the HTTP API layer of Strata: a pure-Python bridge between OpenAI/Anthropic-style clients and the C++ engine. Concretely:\n\n- **Engine adap" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 2, + "run_id": "fbabd65a593d", + "corpus_repeated": false, + "time": "2026-09-29T20:54:43", + "prompt_tokens": 259589, + "completion_tokens": 92, + "ttft_s": 152.099, + "e2e_s": 153.446, + "api_prompt_tps": 1706.7, + "api_decode_tps": 67.5, + "engine_prompt_tps": 1721.6, + "engine_decode_tps": 67.3, + "log_lines": [ + "strata serve: prompt 259589 tokens = 0 reused + 259589 read in 150784 ms (1721.6 tok/s), 92 generated in 1367 ms (67.3 tok/s), drafts accepted 61 of 75, 6 checkpoints", + "strata serve: decode expert cache hit rate: 90.0% (43983 hits / 48863 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the codebase and the last file in detail." + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 3, + "run_id": "40a721fd9a17", + "corpus_repeated": false, + "time": "2026-09-29T20:57:17", + "prompt_tokens": 261068, + "completion_tokens": 256, + "ttft_s": 152.605, + "e2e_s": 156.279, + "api_prompt_tps": 1710.7, + "api_decode_tps": 69.4, + "engine_prompt_tps": 1725.6, + "engine_decode_tps": 69.3, + "log_lines": [ + "strata serve: prompt 261068 tokens = 0 reused + 261068 read in 151288 ms (1725.6 tok/s), 256 generated in 3693 ms (69.3 tok/s), drafts accepted 151 of 231, 6 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (153481 hits / 159304 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing and then propose a concrete improvement.\n\n## What `serve/web/app.js` does\n\nThis file is the **entire client-side logic of the Strata web application** \u2014 a framework-free, single-file JavaScript app that talks only to the local Strata server. It po" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "563f1c703ebe", + "corpus_repeated": false, + "time": "2026-09-29T20:41:08", + "prompt_tokens": 34932, + "completion_tokens": 256, + "ttft_s": 16.748, + "e2e_s": 19.56, + "api_prompt_tps": 2085.7, + "api_decode_tps": 90.7, + "engine_prompt_tps": 2110.2, + "engine_decode_tps": 90.6, + "log_lines": [ + "strata serve: prompt 34932 tokens = 0 reused + 34932 read in 16554 ms (2110.2 tok/s), 256 generated in 2827 ms (90.6 tok/s), drafts accepted 167 of 216, 3 checkpoints", + "strata serve: decode expert cache hit rate: 94.1% (133137 hits / 141416 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing and propose an improvement.\n\n## What `docs/DETAILS.md` does\n\nThis is the comprehensive technical documentation file for the Strata project. It serves as the single source of truth for:\n\n1. **Performance benchmarks** \u2014 Detailed tables of prompt-pro" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "283cb867e188", + "corpus_repeated": false, + "time": "2026-09-29T20:41:28", + "prompt_tokens": 31582, + "completion_tokens": 256, + "ttft_s": 14.807, + "e2e_s": 18.058, + "api_prompt_tps": 2132.9, + "api_decode_tps": 78.4, + "engine_prompt_tps": 2160.4, + "engine_decode_tps": 78.3, + "log_lines": [ + "strata serve: prompt 31582 tokens = 0 reused + 31582 read in 14619 ms (2160.4 tok/s), 256 generated in 3271 ms (78.3 tok/s), drafts accepted 161 of 240, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.0% (151459 hits / 157708 lookups)" + ], + "answer_head": "The last file in the provided list is `docs/DETAILS.md`.\n\n### What it does\nThis file serves as the **comprehensive technical manual and reference guide** for the Strata engine. While the `README.md` focuses on quick installation and high-level marketing, `DETAILS.md` provides the deep technical spec" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "1aba3d88be7a", + "corpus_repeated": false, + "time": "2026-09-29T20:41:47", + "prompt_tokens": 31602, + "completion_tokens": 256, + "ttft_s": 14.833, + "e2e_s": 17.604, + "api_prompt_tps": 2130.5, + "api_decode_tps": 92.0, + "engine_prompt_tps": 2161.9, + "engine_decode_tps": 91.9, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 14618 ms (2161.9 tok/s), 256 generated in 2785 ms (91.9 tok/s), drafts accepted 160 of 207, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.5% (137828 hits / 142765 lookups)" + ], + "answer_head": "The last file in the provided list is `docs/DETAILS.md`.\n\n### What it does\nThis file serves as the comprehensive technical documentation and user manual for the \"Strata\" engine. It bridges the gap between the high-level marketing pitch in `README.md` and the raw source code. Specifically, it:\n\n1. *" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 1, + "run_id": "6c6e9cb15bc9", + "corpus_repeated": false, + "time": "2026-09-29T20:40:53", + "prompt_tokens": 3881, + "completion_tokens": 256, + "ttft_s": 2.267, + "e2e_s": 5.041, + "api_prompt_tps": 1711.6, + "api_decode_tps": 91.9, + "engine_prompt_tps": 1745.2, + "engine_decode_tps": 91.7, + "log_lines": [ + "strata serve: prompt 3881 tokens = 0 reused + 3881 read in 2224 ms (1745.2 tok/s), 256 generated in 2791 ms (91.7 tok/s), drafts accepted 155 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.3% (146401 hits / 150495 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file is the top-level build configuration for the **Strata Engine**. It orchestrates the compilation of the project, handling complex dependencies between CPU-only components, GPU kernels (CUDA/HIP), and testing infrastructure.\n\n### What the file does:\n\n1. **Project Configurati" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 2, + "run_id": "1df8c923675b", + "corpus_repeated": false, + "time": "2026-09-29T20:40:58", + "prompt_tokens": 4200, + "completion_tokens": 142, + "ttft_s": 2.418, + "e2e_s": 4.063, + "api_prompt_tps": 1736.7, + "api_decode_tps": 85.7, + "engine_prompt_tps": 1772.2, + "engine_decode_tps": 85.5, + "log_lines": [ + "strata serve: prompt 4200 tokens = 0 reused + 4200 read in 2370 ms (1772.2 tok/s), 142 generated in 1660 ms (85.5 tok/s), drafts accepted 96 of 114, 1 checkpoints", + "strata serve: decode expert cache hit rate: 89.6% (64163 hits / 71608 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context better." + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 3, + "run_id": "777f84f22df4", + "corpus_repeated": false, + "time": "2026-09-29T20:41:03", + "prompt_tokens": 4201, + "completion_tokens": 256, + "ttft_s": 2.409, + "e2e_s": 5.262, + "api_prompt_tps": 1744.1, + "api_decode_tps": 89.4, + "engine_prompt_tps": 1775.8, + "engine_decode_tps": 89.2, + "log_lines": [ + "strata serve: prompt 4201 tokens = 0 reused + 4201 read in 2366 ms (1775.8 tok/s), 256 generated in 2868 ms (89.2 tok/s), drafts accepted 161 of 222, 1 checkpoints", + "strata serve: decode expert cache hit rate: 96.0% (144002 hits / 149996 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file is the top-level build configuration for the **Strata Engine**. Its primary responsibilities are:\n\n1. **Project Definition**: Sets up the project name (`strata`), version (`0.1.26`), and C++20 standard.\n2. **Backend Selection**: Manages mutually exclusive GPU backends (CU" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "e39790e5649d", + "corpus_repeated": false, + "time": "2026-09-29T20:47:57", + "prompt_tokens": 17346, + "completion_tokens": 8, + "ttft_s": 9.075, + "e2e_s": 9.178, + "api_prompt_tps": 1911.3, + "api_decode_tps": 68.2, + "engine_prompt_tps": 1933.6, + "engine_decode_tps": 67.4, + "log_lines": [ + "strata serve: prompt 17346 tokens = 0 reused + 17346 read in 8971 ms (1933.6 tok/s), 8 generated in 119 ms (67.4 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 80.6% (3014 hits / 3740 lookups)" + ], + "answer_head": "37E3DB14", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "94aa92e58ada", + "corpus_repeated": false, + "time": "2026-09-29T20:48:07", + "prompt_tokens": 29820, + "completion_tokens": 8, + "ttft_s": 14.138, + "e2e_s": 14.241, + "api_prompt_tps": 2109.2, + "api_decode_tps": 68.2, + "engine_prompt_tps": 2134.7, + "engine_decode_tps": 66.5, + "log_lines": [ + "strata serve: prompt 29820 tokens = 0 reused + 29820 read in 13969 ms (2134.7 tok/s), 8 generated in 120 ms (66.5 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 80.6% (3033 hits / 3764 lookups)" + ], + "answer_head": "64EC0999", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "3c83d69c2581", + "corpus_repeated": false, + "time": "2026-09-29T20:47:52", + "prompt_tokens": 7493, + "completion_tokens": 8, + "ttft_s": 4.2, + "e2e_s": 4.307, + "api_prompt_tps": 1783.9, + "api_decode_tps": 65.8, + "engine_prompt_tps": 1816.6, + "engine_decode_tps": 64.9, + "log_lines": [ + "strata serve: prompt 7493 tokens = 0 reused + 7493 read in 4125 ms (1816.6 tok/s), 8 generated in 123 ms (64.9 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 74.8% (2704 hits / 3615 lookups)" + ], + "answer_head": "0E6415FF", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "7aed17dd03cd", + "corpus_repeated": false, + "time": "2026-09-29T20:48:48", + "prompt_tokens": 15636, + "completion_tokens": 256, + "ttft_s": 7.488, + "e2e_s": 10.882, + "api_prompt_tps": 2088.0, + "api_decode_tps": 75.1, + "engine_prompt_tps": 2114.8, + "engine_decode_tps": 75.1, + "log_lines": [ + "strata serve: prompt 15636 tokens = 0 reused + 15636 read in 7394 ms (2114.8 tok/s), 256 generated in 3410 ms (75.1 tok/s), drafts accepted 152 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 93.0% (136865 hits / 147168 lookups)" + ], + "answer_head": "## What `README.md` does\n\n`README.md` is the project's landing page and primary user-facing documentation. It serves several purposes:\n\n1. **Marketing/overview** \u2014 Opens with a headline claim (\"Run a 125-billion-parameter AI model on a normal gaming PC\") and a visual demo (the pagoda video) to immed", + "turn2_ttft_s": 0.438, + "turn2_prompt_tokens": 15915, + "turn2_log_lines": [ + "strata serve: prompt 15915 tokens = 15892 reused + 23 read in 332 ms (69.3 tok/s), 46 generated in 661 ms (69.6 tok/s), drafts accepted 27 of 44, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.4% (29047 hits / 30124 lookups)" + ] + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "cfa75b59eb61", + "corpus_repeated": false, + "time": "2026-09-29T21:39:52", + "prompt_tokens": 28314, + "completion_tokens": 256, + "ttft_s": 26.573, + "e2e_s": 29.595, + "api_prompt_tps": 1065.5, + "api_decode_tps": 84.4, + "engine_prompt_tps": 1071.8, + "engine_decode_tps": 83.7, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 26417 ms (1071.8 tok/s), 256 generated in 3058 ms (83.7 tok/s), drafts accepted 147 of 251, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.9% (171443 hits / 173268 lookups)" + ], + "answer_head": "The last file in the repository listing is `docs/DETAILS.md`.\n\n### What `docs/DETAILS.md` does\n\nIt is the comprehensive technical documentation and reference manual for the Strata engine. While the `README.md` focuses on quick installation and high-level usage, `DETAILS.md` provides the deep technic" + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "c27c8adc0b65", + "corpus_repeated": false, + "time": "2026-09-29T21:40:22", + "prompt_tokens": 31633, + "completion_tokens": 256, + "ttft_s": 26.904, + "e2e_s": 29.536, + "api_prompt_tps": 1175.8, + "api_decode_tps": 96.9, + "engine_prompt_tps": 1185.2, + "engine_decode_tps": 96.7, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 26691 ms (1185.2 tok/s), 256 generated in 2648 ms (96.7 tok/s), drafts accepted 160 of 214, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (147426 hits / 148799 lookups)" + ], + "answer_head": "I cannot analyze the last file because the provided repository content is truncated. The `docs/DETAILS.md` file cuts off mid-sentence in the \"Using it\" section (`...if y`), and no subsequent files are shown.\n\nHowever, I can analyze the **`chat.py`** file, which is the last *complete* file provided i" + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "60c6cbe1b14a", + "corpus_repeated": false, + "time": "2026-09-29T21:40:52", + "prompt_tokens": 31603, + "completion_tokens": 256, + "ttft_s": 27.476, + "e2e_s": 30.102, + "api_prompt_tps": 1150.2, + "api_decode_tps": 97.1, + "engine_prompt_tps": 1158.9, + "engine_decode_tps": 96.9, + "log_lines": [ + "strata serve: prompt 31603 tokens = 0 reused + 31603 read in 27271 ms (1158.9 tok/s), 256 generated in 2641 ms (96.9 tok/s), drafts accepted 154 of 209, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.6% (148622 hits / 149275 lookups)" + ], + "answer_head": "An analysis of the last file (`docs/DETAILS.md`) and a proposed improvement follows.\n\n### What the file does\n\n`docs/DETAILS.md` serves as the comprehensive technical manual for the Strata engine. It bridges the gap between the high-level marketing in the `README.md` and the raw source code. Specific" + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "8f89dfed9af3", + "corpus_repeated": false, + "time": "2026-09-29T22:00:26", + "prompt_tokens": 17344, + "completion_tokens": 8, + "ttft_s": 15.582, + "e2e_s": 15.663, + "api_prompt_tps": 1113.1, + "api_decode_tps": 86.5, + "engine_prompt_tps": 1119.9, + "engine_decode_tps": 83.8, + "log_lines": [ + "strata serve: prompt 17344 tokens = 0 reused + 17344 read in 15487 ms (1119.9 tok/s), 8 generated in 96 ms (83.8 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.3% (4205 hits / 4320 lookups)" + ], + "answer_head": "05449BFC", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "93a9a0e32114", + "corpus_repeated": false, + "time": "2026-09-29T22:00:42", + "prompt_tokens": 29825, + "completion_tokens": 9, + "ttft_s": 26.19, + "e2e_s": 26.262, + "api_prompt_tps": 1138.8, + "api_decode_tps": 110.5, + "engine_prompt_tps": 1146.7, + "engine_decode_tps": 103.9, + "log_lines": [ + "strata serve: prompt 29825 tokens = 0 reused + 29825 read in 26009 ms (1146.7 tok/s), 9 generated in 87 ms (103.9 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.2% (4241 hits / 4320 lookups)" + ], + "answer_head": "98C00B03", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "d1d745f05911", + "corpus_repeated": false, + "time": "2026-09-29T22:00:17", + "prompt_tokens": 7493, + "completion_tokens": 9, + "ttft_s": 7.948, + "e2e_s": 8.057, + "api_prompt_tps": 942.8, + "api_decode_tps": 73.4, + "engine_prompt_tps": 953.1, + "engine_decode_tps": 58.6, + "log_lines": [ + "strata serve: prompt 7493 tokens = 0 reused + 7493 read in 7861 ms (953.1 tok/s), 9 generated in 154 ms (58.6 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 94.0% (4062 hits / 4320 lookups)" + ], + "answer_head": "69231569", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "dedda4f9d6be", + "corpus_repeated": false, + "time": "2026-09-29T22:01:09", + "prompt_tokens": 15635, + "completion_tokens": 44, + "ttft_s": 13.63, + "e2e_s": 14.13, + "api_prompt_tps": 1147.1, + "api_decode_tps": 86.1, + "engine_prompt_tps": 1154.6, + "engine_decode_tps": 85.6, + "log_lines": [ + "strata serve: prompt 15635 tokens = 0 reused + 15635 read in 13541 ms (1154.6 tok/s), 44 generated in 514 ms (85.6 tok/s), drafts accepted 30 of 36, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.9% (24433 hits / 24957 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context better.", + "turn2_ttft_s": 0.577, + "turn2_prompt_tokens": 15672, + "turn2_log_lines": [ + "strata serve: prompt 15672 tokens = 15628 reused + 44 read in 490 ms (89.8 tok/s), 48 generated in 567 ms (84.6 tok/s), drafts accepted 28 of 43, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.6% (31236 hits / 31679 lookups)" + ] + } +] diff --git a/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.md b/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.md new file mode 100644 index 0000000..31b53b4 --- /dev/null +++ b/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.md @@ -0,0 +1,48 @@ +# Native benchmark matrix (v0.1.26) + +Prompt speeds are engine tok/s medians; output lists the first-run value and the three-run median. `prompt tokens` is the median measured count. Draft acceptance is the mean of per-run accepted/offered values from engine logs. + +## IQ3_XXS, one RTX 3090 + +| Context | Prompt tokens | Prompt tok/s | Decode first / median tok/s | TTFT median | Draft acceptance | +|---|---:|---:|---:|---:|---:| +| 1K | 1,135 | 869.7 | 93.0 / 93.0 | 1.33 s | 0.738 | +| 4K | 4,200 | 1,772.2 | 91.7 / 89.2 | 2.41 s | 0.763 | +| 32K | 31,602 | 2,160.4 | 90.6 / 90.6 | 14.83 s | 0.739 | +| 128K | 129,913 | 2,173.6 | 79.3 / 79.3 | 60.53 s | 0.723 | +| 262K | 259,589 | 1,725.6 | 63.0 / 67.3 | 152.10 s | 0.697 | + +## 32K model and GPU comparison + +| Model | GPUs / split | Prompt tokens | Prompt tok/s median | Decode first / median tok/s | TTFT median | Draft acceptance | +|---|---|---:|---:|---:|---:|---:| +| Coder IQ1_M | 1x 3090 | 31,601 | 2,502.4 | 52.7 / 66.8 | 12.80 s | 0.760 | +| Coder IQ1_M | 2x 3090, auto K=19 | 31,601 | 2,704.3 | 88.5 / 98.6 | 11.85 s | 0.908 | +| IQ3_XXS | 2x 3090, auto K=24 | 31,603 | 1,158.9 | 83.7 / 96.7 | 26.90 s | 0.690 | +| IQ3_S | 2x 3090, auto K=24 | 31,604 | 749.3 | 83.1 / 106.3 | 42.27 s | 0.871 | + +## Coder IQ1_M fixed layer split + +One initial 32K run per K, then three-run repeats for K=22–30. Prompts are independent and adaptive-cache behavior varies; compare the medians cautiously. + +| Split | Successful runs | Prompt tok/s median | Decode tok/s median | Notes | +|---|---:|---:|---:|---| +| Auto (K=19) | 3 | 2,704.3 | 98.6 | Layers 0–18 / 19–47 | +| K=18 | 1 | 2,324.6 | 83.1 | Repeat startup OOM while uploading a dense weight | +| K=22 | 3 | 2,951.6 | 103.3 | Layers 0–21 / 22–47 | +| K=24 | 3 | 3,123.2 | 100.2 | Layers 0–23 / 24–47 | +| K=26 | 3 | 3,205.2 | 93.5 | Layers 0–25 / 26–47 | +| K=28 | 3 | 3,034.9 | 96.6 | Layers 0–27 / 28–47 | +| K=30 | 3 | 2,920.6 | 96.1 | Layers 0–29 / 30–47 | + +## Correctness + +| Model / setup | Check | Result | +|---|---|---| +| IQ3_XXS, 1x 3090 | Needles 8K / 16K / 28K | 3/3 found | +| IQ3_XXS, 1x 3090 | 16K two-turn chat | 15,892 / 15,915 prompt tokens reused on turn two | +| IQ3_XXS, 2x 3090 auto K=24 | Needles 8K / 16K / 28K | 3/3 found | +| IQ3_XXS, 2x 3090 auto K=24 | 16K two-turn chat | 15,628 / 15,672 prompt tokens reused on turn two | +| IQ3_S, 2x 3090 auto K=24 | Needles 8K / 16K / 28K | 3/3 found | +| IQ3_S, 2x 3090 auto K=24 | 16K two-turn chat | 15,632 / 15,676 prompt tokens reused on turn two | +| Coder, 2x 3090 | Needles / two-turn | Not run | diff --git a/bench/results/2026-09-29-speed-0122/README.md b/bench/results/2026-09-29-speed-0122/README.md new file mode 100644 index 0000000..37d190c --- /dev/null +++ b/bench/results/2026-09-29-speed-0122/README.md @@ -0,0 +1,32 @@ +# Speed with engine 0.1.22 + +RTX 5070 12 GB (PCIe 5.0 x16), Ryzen 5 7600, 64 GB DDR5-5200, Windows 10. The ready-made 0.1.22 engine, one-shot runs +with what setup writes: `--prefill auto`, the shipped expert profile, `--expert-cache auto`, 8-bit KV above 4K, KV +streaming (`--kv-resident 32768`) from 64K, MTP (`--spec 4 --spec-min-p 0.5`), greedy, 256 generated tokens, images +off. The same code-agent prompts as `2026-09-28-speed-0114`. Every run: [`matrix.json`](matrix.json). + +## Prompt (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 519 | 1,226 | 1,844 | 1,836 | 1,682 | 1,304 | +| **IQ2_XS** | 524 | 1,196 | 1,799 | 1,611 | 1,495 | 1,181 | +| **IQ3_XXS** | 472 | 974 | 1,555 | 1,449 | 1,386 | - | +| **IQ3_S** | 419 | 893 | 1,499 | 1,285 | 1,245 | - | +| **Coder** | 660 | 1,522 | 1,871 | 1,938 | 1,779 | - | + +## Output (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 84.7 | 88.2 | 77.4 | 71.0 | 63.1 | 61.1 | +| **IQ2_XS** | 77.2 | 74.6 | 67.5 | 63.5 | 59.1 | 54.7 | +| **IQ3_XXS** | 65.1 | 62.3 | 49.8 | 53.6 | 47.0 | - | +| **IQ3_S** | 50.5 | 44.6 | 49.0 | 48.8 | 41.3 | - | +| **Coder** | 56.9 | 53.6 | 54.9 | 48.5 | 42.8 | - | + +- IQ2_XS was measured with Swift 1.5's IQ2_XS (the same speed as the original's); its 262K run had images on. +- IQ3_XXS and IQ3_S at 262K do not fit 64 GB of RAM; the Coder at 262K was not run again (0.1.14: 1,034 tokens/s). +- Against 0.1.14: prompts 1.2-1.5x faster at 32K-128K (the 0.1.22 prompt path: tensor-core attention, bit-identical + batched kernels, faster PLE reads). Output speed is the engine's same decode; one run per cell moves a few percent + with the text (speculative drafts), so compare it across many runs, not one. diff --git a/bench/results/2026-09-29-speed-0122/matrix.json b/bench/results/2026-09-29-speed-0122/matrix.json new file mode 100644 index 0000000..82d52f1 --- /dev/null +++ b/bench/results/2026-09-29-speed-0122/matrix.json @@ -0,0 +1,380 @@ +[ + { + "model": "Q2_0", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 40.0, + "decode_tok_s": 84.71, + "decoded": 256, + "prefill_tok_s": 519.48, + "ttft_s": 3.62, + "spec_accept": 0.786, + "tokens_per_round": 2.77, + "vram_slots": 4176 + }, + { + "model": "Q2_0", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 41.6, + "decode_tok_s": 88.23, + "decoded": 256, + "prefill_tok_s": 1226.49, + "ttft_s": 4.43, + "spec_accept": 0.839, + "tokens_per_round": 3.24, + "vram_slots": 4123 + }, + { + "model": "Q2_0", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 56.6, + "decode_tok_s": 77.37, + "decoded": 256, + "prefill_tok_s": 1843.83, + "ttft_s": 18.63, + "spec_accept": 0.808, + "tokens_per_round": 3.04, + "vram_slots": 3833 + }, + { + "model": "Q2_0", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 72.9, + "decode_tok_s": 71.0, + "decoded": 256, + "prefill_tok_s": 1835.64, + "ttft_s": 36.48, + "spec_accept": 0.685, + "tokens_per_round": 2.77, + "vram_slots": 3780 + }, + { + "model": "Q2_0", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 118.1, + "decode_tok_s": 63.08, + "decoded": 256, + "prefill_tok_s": 1681.64, + "ttft_s": 77.92, + "spec_accept": 0.7, + "tokens_per_round": 2.56, + "vram_slots": 3697 + }, + { + "model": "Q2_0", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 242.0, + "decode_tok_s": 61.12, + "decoded": 256, + "prefill_tok_s": 1303.83, + "ttft_s": 200.94, + "spec_accept": 0.627, + "tokens_per_round": 2.5, + "vram_slots": 3525 + }, + { + "model": "IQ2_XS", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 263.6, + "decode_tok_s": 54.68, + "decoded": 256, + "prefill_tok_s": 1180.58, + "ttft_s": 221.91, + "spec_accept": 0.632, + "tokens_per_round": 2.49, + "vram_slots": 3727 + }, + { + "model": "IQ3_S", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 56.0, + "decode_tok_s": 50.5, + "decoded": 256, + "prefill_tok_s": 419.48, + "ttft_s": 3.98, + "spec_accept": 0.811, + "tokens_per_round": 3.17, + "vram_slots": 2617 + }, + { + "model": "IQ3_S", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 60.0, + "decode_tok_s": 44.58, + "decoded": 256, + "prefill_tok_s": 892.84, + "ttft_s": 5.53, + "spec_accept": 0.672, + "tokens_per_round": 2.69, + "vram_slots": 2580 + }, + { + "model": "IQ3_S", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 75.6, + "decode_tok_s": 48.96, + "decoded": 256, + "prefill_tok_s": 1499.09, + "ttft_s": 22.65, + "spec_accept": 0.79, + "tokens_per_round": 2.9, + "vram_slots": 2383 + }, + { + "model": "IQ3_S", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 102.1, + "decode_tok_s": 48.8, + "decoded": 256, + "prefill_tok_s": 1284.81, + "ttft_s": 51.58, + "spec_accept": 0.797, + "tokens_per_round": 2.94, + "vram_slots": 2281 + }, + { + "model": "IQ3_S", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 159.2, + "decode_tok_s": 41.27, + "decoded": 256, + "prefill_tok_s": 1244.55, + "ttft_s": 104.81, + "spec_accept": 0.694, + "tokens_per_round": 2.73, + "vram_slots": 2292 + }, + { + "model": "Coder", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 34.5, + "decode_tok_s": 56.94, + "decoded": 256, + "prefill_tok_s": 660.44, + "ttft_s": 2.42, + "spec_accept": 0.74, + "tokens_per_round": 2.91, + "vram_slots": 2650 + }, + { + "model": "Coder", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 18.8, + "decode_tok_s": 53.65, + "decoded": 256, + "prefill_tok_s": 1521.84, + "ttft_s": 3.21, + "spec_accept": 0.736, + "tokens_per_round": 2.91, + "vram_slots": 2615 + }, + { + "model": "Coder", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 33.1, + "decode_tok_s": 54.85, + "decoded": 256, + "prefill_tok_s": 1870.76, + "ttft_s": 17.7, + "spec_accept": 0.806, + "tokens_per_round": 3.11, + "vram_slots": 2418 + }, + { + "model": "Coder", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 50.2, + "decode_tok_s": 48.46, + "decoded": 256, + "prefill_tok_s": 1937.69, + "ttft_s": 33.99, + "spec_accept": 0.653, + "tokens_per_round": 2.56, + "vram_slots": 2382 + }, + { + "model": "Coder", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 90.3, + "decode_tok_s": 42.75, + "decoded": 256, + "prefill_tok_s": 1778.66, + "ttft_s": 73.12, + "spec_accept": 0.588, + "tokens_per_round": 2.27, + "vram_slots": 2326 + }, + { + "model": "IQ2_XS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 43.6, + "decode_tok_s": 77.16, + "decoded": 256, + "prefill_tok_s": 523.77, + "ttft_s": 3.46, + "spec_accept": 0.811, + "tokens_per_round": 3.02, + "vram_slots": 4361 + }, + { + "model": "IQ2_XS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 43.7, + "decode_tok_s": 74.58, + "decoded": 256, + "prefill_tok_s": 1196.03, + "ttft_s": 4.47, + "spec_accept": 0.824, + "tokens_per_round": 3.36, + "vram_slots": 4309 + }, + { + "model": "IQ2_XS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 59.6, + "decode_tok_s": 67.46, + "decoded": 256, + "prefill_tok_s": 1798.65, + "ttft_s": 19.06, + "spec_accept": 0.789, + "tokens_per_round": 3.02, + "vram_slots": 4030 + }, + { + "model": "IQ2_XS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 81.4, + "decode_tok_s": 63.52, + "decoded": 256, + "prefill_tok_s": 1610.73, + "ttft_s": 41.37, + "spec_accept": 0.705, + "tokens_per_round": 2.6, + "vram_slots": 3978 + }, + { + "model": "IQ2_XS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 126.0, + "decode_tok_s": 59.11, + "decoded": 256, + "prefill_tok_s": 1494.53, + "ttft_s": 87.51, + "spec_accept": 0.704, + "tokens_per_round": 2.71, + "vram_slots": 3897 + }, + { + "model": "IQ3_XXS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 48.6, + "decode_tok_s": 65.12, + "decoded": 256, + "prefill_tok_s": 471.53, + "ttft_s": 3.65, + "spec_accept": 0.876, + "tokens_per_round": 4.08, + "vram_slots": 3281 + }, + { + "model": "IQ3_XXS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 48.5, + "decode_tok_s": 62.33, + "decoded": 256, + "prefill_tok_s": 974.3, + "ttft_s": 5.17, + "spec_accept": 0.826, + "tokens_per_round": 3.15, + "vram_slots": 3243 + }, + { + "model": "IQ3_XXS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 64.9, + "decode_tok_s": 49.83, + "decoded": 256, + "prefill_tok_s": 1554.53, + "ttft_s": 21.84, + "spec_accept": 0.766, + "tokens_per_round": 2.91, + "vram_slots": 3009 + }, + { + "model": "IQ3_XXS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 91.7, + "decode_tok_s": 53.58, + "decoded": 256, + "prefill_tok_s": 1449.37, + "ttft_s": 45.84, + "spec_accept": 0.748, + "tokens_per_round": 2.8, + "vram_slots": 2965 + }, + { + "model": "IQ3_XXS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 140.9, + "decode_tok_s": 46.97, + "decoded": 256, + "prefill_tok_s": 1386.04, + "ttft_s": 94.33, + "spec_accept": 0.607, + "tokens_per_round": 2.47, + "vram_slots": 2901 + } +] \ No newline at end of file diff --git a/bench/results/2026-09-29-speed-0126/README.md b/bench/results/2026-09-29-speed-0126/README.md new file mode 100644 index 0000000..e6f8fdd --- /dev/null +++ b/bench/results/2026-09-29-speed-0126/README.md @@ -0,0 +1,36 @@ +# Speed with engine 0.1.26 + +RTX 5070 12 GB (PCIe 5.0 x16), Ryzen 5 7600, 64 GB DDR5-5200, Windows 10. The ready-made 0.1.26 engine, one-shot runs +with what setup writes: `--prefill auto`, the shipped expert profile, `--expert-cache auto`, 8-bit KV above 4K, KV +streaming (`--kv-resident 32768`) from 64K, MTP (`--spec 4 --spec-min-p 0.5`), greedy, 256 generated tokens, images +off, no timing marks. The same code-agent prompts as `2026-09-29-speed-0122`. Every run: [`matrix.json`](matrix.json). + +## Prompt (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | +| --- | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 536 | 1,299 | 2,171 | 2,126 | 2,107 | +| **IQ2_XS** | 534 | 1,256 | 2,092 | 1,754 | 1,752 | +| **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 | + +## Output (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | +| --- | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 87.3 | 93.0 | 81.8 | 76.2 | 73.7 | +| **IQ2_XS** | 79.6 | 78.6 | 76.3 | 63.7 | 62.7 | +| **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 | + +- Against 0.1.22 (`2026-09-29-speed-0122`), prompts at 32K-128K are 8-28% faster: Q2_0 1,844 -> 2,171 at 32K and + 1,682 -> 2,107 at 128K, the Coder 1,779 -> 2,208 at 128K. The gains come from: + - 0.1.24's QSA selection on tensor cores; + - 0.1.25's grouping tables in mapped memory and fused norms; + - 0.1.26's batched draft-layer pass. +- 262K was not run again (0.1.22: Q2_0 1,304, IQ2_XS 1,181 tokens/s). +- Output speed is the same decode as before. One run per cell moves several percent with the text (the share of + accepted drafts, `spec_accept` in `matrix.json`). For example, the Coder's 128K answer accepted 55% of its drafts + and its 64K answer 71%. diff --git a/bench/results/2026-09-29-speed-0126/matrix.json b/bench/results/2026-09-29-speed-0126/matrix.json new file mode 100644 index 0000000..cd4bf7f --- /dev/null +++ b/bench/results/2026-09-29-speed-0126/matrix.json @@ -0,0 +1,352 @@ +[ + { + "model": "Q2_0", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 23.9, + "decode_tok_s": 87.33, + "decoded": 256, + "prefill_tok_s": 536.42, + "ttft_s": 3.4, + "spec_accept": 0.681, + "tokens_per_round": 2.72, + "vram_slots": 4174 + }, + { + "model": "Q2_0", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 27.6, + "decode_tok_s": 92.97, + "decoded": 256, + "prefill_tok_s": 1299.44, + "ttft_s": 4.21, + "spec_accept": 0.838, + "tokens_per_round": 3.23, + "vram_slots": 4121 + }, + { + "model": "Q2_0", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 40.8, + "decode_tok_s": 81.75, + "decoded": 256, + "prefill_tok_s": 2170.85, + "ttft_s": 16.02, + "spec_accept": 0.788, + "tokens_per_round": 2.99, + "vram_slots": 3832 + }, + { + "model": "Q2_0", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 57.3, + "decode_tok_s": 76.23, + "decoded": 256, + "prefill_tok_s": 2126.03, + "ttft_s": 32.06, + "spec_accept": 0.707, + "tokens_per_round": 2.8, + "vram_slots": 3778 + }, + { + "model": "Q2_0", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 87.7, + "decode_tok_s": 73.73, + "decoded": 256, + "prefill_tok_s": 2106.85, + "ttft_s": 62.48, + "spec_accept": 0.679, + "tokens_per_round": 2.71, + "vram_slots": 3695 + }, + { + "model": "IQ2_XS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 42.2, + "decode_tok_s": 79.62, + "decoded": 256, + "prefill_tok_s": 533.83, + "ttft_s": 3.51, + "spec_accept": 0.774, + "tokens_per_round": 2.89, + "vram_slots": 4359 + }, + { + "model": "IQ2_XS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 40.6, + "decode_tok_s": 78.6, + "decoded": 256, + "prefill_tok_s": 1256.02, + "ttft_s": 4.31, + "spec_accept": 0.81, + "tokens_per_round": 3.29, + "vram_slots": 4308 + }, + { + "model": "IQ2_XS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 53.6, + "decode_tok_s": 76.34, + "decoded": 256, + "prefill_tok_s": 2092.02, + "ttft_s": 16.57, + "spec_accept": 0.85, + "tokens_per_round": 3.2, + "vram_slots": 4029 + }, + { + "model": "IQ2_XS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 78.3, + "decode_tok_s": 63.69, + "decoded": 256, + "prefill_tok_s": 1753.65, + "ttft_s": 38.08, + "spec_accept": 0.636, + "tokens_per_round": 2.59, + "vram_slots": 3977 + }, + { + "model": "IQ2_XS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 115.1, + "decode_tok_s": 62.72, + "decoded": 256, + "prefill_tok_s": 1751.79, + "ttft_s": 74.85, + "spec_accept": 0.696, + "tokens_per_round": 2.6, + "vram_slots": 3896 + }, + { + "model": "IQ3_XXS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 46.9, + "decode_tok_s": 61.94, + "decoded": 256, + "prefill_tok_s": 482.04, + "ttft_s": 3.67, + "spec_accept": 0.845, + "tokens_per_round": 3.57, + "vram_slots": 3279 + }, + { + "model": "IQ3_XXS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 47.4, + "decode_tok_s": 61.64, + "decoded": 256, + "prefill_tok_s": 1007.48, + "ttft_s": 5.03, + "spec_accept": 0.801, + "tokens_per_round": 3.19, + "vram_slots": 3242 + }, + { + "model": "IQ3_XXS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 65.6, + "decode_tok_s": 58.49, + "decoded": 256, + "prefill_tok_s": 1745.16, + "ttft_s": 19.63, + "spec_accept": 0.789, + "tokens_per_round": 2.85, + "vram_slots": 3007 + }, + { + "model": "IQ3_XXS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 88.5, + "decode_tok_s": 57.21, + "decoded": 256, + "prefill_tok_s": 1609.31, + "ttft_s": 41.45, + "spec_accept": 0.74, + "tokens_per_round": 2.87, + "vram_slots": 2963 + }, + { + "model": "IQ3_XXS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 127.0, + "decode_tok_s": 48.95, + "decoded": 256, + "prefill_tok_s": 1602.33, + "ttft_s": 81.71, + "spec_accept": 0.643, + "tokens_per_round": 2.37, + "vram_slots": 2899 + }, + { + "model": "IQ3_S", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 54.2, + "decode_tok_s": 52.4, + "decoded": 256, + "prefill_tok_s": 426.6, + "ttft_s": 4.03, + "spec_accept": 0.822, + "tokens_per_round": 3.17, + "vram_slots": 2617 + }, + { + "model": "IQ3_S", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 58.9, + "decode_tok_s": 53.3, + "decoded": 256, + "prefill_tok_s": 912.99, + "ttft_s": 5.58, + "spec_accept": 0.85, + "tokens_per_round": 3.38, + "vram_slots": 2579 + }, + { + "model": "IQ3_S", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 72.8, + "decode_tok_s": 48.31, + "decoded": 256, + "prefill_tok_s": 1624.07, + "ttft_s": 21.07, + "spec_accept": 0.827, + "tokens_per_round": 3.0, + "vram_slots": 2383 + }, + { + "model": "IQ3_S", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 93.3, + "decode_tok_s": 46.25, + "decoded": 256, + "prefill_tok_s": 1640.34, + "ttft_s": 40.77, + "spec_accept": 0.693, + "tokens_per_round": 2.56, + "vram_slots": 2346 + }, + { + "model": "IQ3_S", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 144.6, + "decode_tok_s": 45.51, + "decoded": 256, + "prefill_tok_s": 1443.21, + "ttft_s": 90.72, + "spec_accept": 0.697, + "tokens_per_round": 2.73, + "vram_slots": 2291 + }, + { + "model": "Coder", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 37.0, + "decode_tok_s": 58.91, + "decoded": 256, + "prefill_tok_s": 656.36, + "ttft_s": 2.48, + "spec_accept": 0.743, + "tokens_per_round": 2.91, + "vram_slots": 2649 + }, + { + "model": "Coder", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 18.3, + "decode_tok_s": 55.1, + "decoded": 256, + "prefill_tok_s": 1583.1, + "ttft_s": 3.09, + "spec_accept": 0.713, + "tokens_per_round": 2.88, + "vram_slots": 2614 + }, + { + "model": "Coder", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 30.4, + "decode_tok_s": 54.89, + "decoded": 256, + "prefill_tok_s": 2177.17, + "ttft_s": 15.33, + "spec_accept": 0.731, + "tokens_per_round": 2.75, + "vram_slots": 2417 + }, + { + "model": "Coder", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 44.8, + "decode_tok_s": 53.22, + "decoded": 256, + "prefill_tok_s": 2236.49, + "ttft_s": 29.51, + "spec_accept": 0.709, + "tokens_per_round": 2.68, + "vram_slots": 2382 + }, + { + "model": "Coder", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 75.9, + "decode_tok_s": 43.04, + "decoded": 256, + "prefill_tok_s": 2208.27, + "ttft_s": 59.02, + "spec_accept": 0.553, + "tokens_per_round": 2.23, + "vram_slots": 2324 + } +] \ No newline at end of file diff --git a/bench/results/2026-09-30-community-rtx-5090/BUILD.json b/bench/results/2026-09-30-community-rtx-5090/BUILD.json new file mode 100644 index 0000000..a65c015 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/BUILD.json @@ -0,0 +1,14 @@ +{ + "source": "local", + "version": "0.1.29", + "archs": [ + 120 + ], + "vision": "gpu", + "cuda_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "src": "1437bc9455f7c0af", + "vision_src": "4b80385716918cce" +} \ No newline at end of file diff --git a/bench/results/2026-09-30-community-rtx-5090/Dockerfile b/bench/results/2026-09-30-community-rtx-5090/Dockerfile new file mode 100644 index 0000000..24949fb --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/Dockerfile @@ -0,0 +1,4 @@ +FROM nvidia/cuda@sha256:5dc1bca23d05bd37b011be68ec470c03b403a5da07ec3a86e41af9470e9d0cc6 +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends build-essential cmake ninja-build git ca-certificates curl python3 python3-venv python3-dev pkg-config && rm -rf /var/lib/apt/lists/* +ENV HOME=/workspace/home PYTHONUNBUFFERED=1 +WORKDIR /workspace/Strata diff --git a/bench/results/2026-09-30-community-rtx-5090/README.md b/bench/results/2026-09-30-community-rtx-5090/README.md new file mode 100644 index 0000000..88e664c --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/README.md @@ -0,0 +1,167 @@ +# Community benchmark: RTX 5090, Core Ultra 9 285K + +Measured on 2026-09-30 by [hagope](https://github.com/hagope), on a Linux +machine called OMAN. This tests Strata 0.1.29 with the original Flash-Next +IQ2_XS, one GPU, and a 131,072-token context limit. + +Median decode throughput was **179.4 tok/s at 4,096 prompt tokens, 175.7 tok/s +at 32,768, and 165.0 tok/s at 128,000**. These are synthetic code-explanation +requests with greedy decoding and a 256-token output cap. They do not establish +general answer quality or performance on other workloads. + +## Hardware and software + +- NVIDIA GeForce RTX 5090; 32,607 MiB reported VRAM; 575 W power limit. + PCIe capability: Gen 5, x16. The engine's startup transfer probe reported + 50.0 GB/s host-to-device. GPU clocks were not fixed for this test. +- Intel Core Ultra 9 285K; 24 logical CPUs. The engine selected AVX2 and + 23 expert-pool workers plus its host thread. +- 64 GB installed RAM; Linux reported 62.19 GiB usable. Local NVMe storage: + WDC WDS200T2B0C-00PXH0. 8 GiB system swap. +- Ubuntu 24.04.4 LTS, kernel 6.8.0-142-generic, NVIDIA driver 595.84. +- Source commit `d6708a4aae15b4860000d54c8af9e84d684bce09`; engine 0.1.29. + Locally compiled CUDA architecture 120, including the GPU vision helper. + See [BUILD.json](BUILD.json). +- CUDA 13.0.2 container; NVCC 13.0.88; GCC 13.3.0; Python 3.12.3. + Base image: `nvidia/cuda@sha256:5dc1bca23d05bd37b011be68ec470c03b403a5da07ec3a86e41af9470e9d0cc6`. + Installed Python dependencies are listed in [python-packages.txt](python-packages.txt). +- The regular inference server, GPU TTS, and GPU embedding service were paused. + Other CPU services remained running. The GPU was dedicated to Strata and its + vision helper; this was not a completely isolated operating system. + +## Model and configuration + +Model: `ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF`, revision +`ed59f92082b1e93c0e96d60a8b11aab089b52f09`: + +- `IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf` +- `IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf` +- `mmproj-Qwen3.8-Flash-Next-BF16.gguf` + +All three local GGUF SHA-256 hashes matched the revision's published LFS hashes. +[model-provenance.json](model-provenance.json) contains filenames, byte sizes, +revisions, and verified hashes. MTP was fetched by the installer from +`Qwen/Qwen3.8-Flash-Next`; its API reported revision +`de4b8e4d43b917e7706784d8bb445c9af86a3540` at verification time. The installer +uses `main` for those tensor-range downloads. Their individual output hashes +are retained in [mtp-manifest.json](mtp-manifest.json); the full BF16 upstream +shards were not downloaded or independently hash-verified. + +The unmodified installer prepared the native IQ2_XS pack and Q2_0 MTP experts. +[artifact-hashes.json](artifact-hashes.json) identifies the executables, +default expert profile, tokenizer, pack metadata/dense weights, and draft pack. + +- Context 131,072; INT8 KV; 32,768 KV cells per attention layer resident on GPU. +- Expert cache `auto`: 17,463 slots, 23.44 GiB VRAM, profile-prefilled with + **no eviction**. The bundled expert profile was used without calibration. +- Prefill `auto` selected chunks of 8,192 tokens, borrowing 3,421 expert-cache + slots during prompt processing. +- MTP `--spec 4 --spec-min-p 0.5`; built-in suffix drafting remained enabled. +- Low-RAM mode off; GPU vision enabled, 1,024 image tokens and a 700 MiB VRAM + reserve. The vision helper warmed up; benchmark requests contained no images. +- Experimental speed projection off; no custom control vectors or calibration. +- Reasoning disabled, temperature 0, maximum 256 generated tokens per speed run. + +The complete measured configuration is [strata-iq2_xs.json](strata-iq2_xs.json). +Startup choices and every request's timing/draft statistics are in +[engine.log](engine.log). + +## Method and reproduction + +Use the attached [Dockerfile](Dockerfile), the pinned source commit, and an empty +data directory. Mount a working directory as `/workspace`, with the checkout +at `/workspace/Strata`. Run setup inside the CUDA container with GPU access, +host IPC, and unlimited memlock: + +```bash +bash ./setup.sh --family qwen --model IQ2_XS --context 131072 --kv int8 \ + --vision gpu --experimental-speed-projection off --gpu 0 --low-ram off \ + --build --yes --no-start --port 18080 --data-dir /workspace/Strata-data +``` + +Launch the prepared server on loopback inside a container using host networking: + +```bash +/workspace/Strata/.venv/bin/python serve/server.py --engine strata \ + --config strata-iq2_xs.json --host 127.0.0.1 --port 18080 +``` + +Run [benchmark.py](benchmark.py) inside that container, after placing the script +at `/workspace/benchmark.py`. It generates deterministic synthetic Python +functions, adds a different nonce near the start of each request, and counts the +complete rendered chat prompt using Strata's tokenizer. It adjusts the filler +to the target token count and verifies the count against the server afterward. +The resulting request hashes are in [results.json](results.json). + +```bash +/workspace/Strata/.venv/bin/python /workspace/benchmark.py +/workspace/Strata/.venv/bin/python tools/needle_bench.py \ + --url http://127.0.0.1:18080 --lengths 32k,128k --depths 10,50,90 \ + --out /workspace/results/needles.json +``` + +One short warm-up request was excluded. Three runs at each length were executed +serially in increasing-length order on the same loaded engine. All nine speed +requests processed their entire prompt: **zero reused tokens**. The GPU expert +cache was filled at startup and retained between requests; no engine restart or +OS page-cache reset separated them. Downloads and file verification had already +warmed the filesystem cache. Loading time is excluded. + +The script measures streaming TTFT from immediately before the HTTP request +until the first nonempty text delta, ignoring empty role chunks and keep-alives. +With reasoning off, that delta contains answer text. Total latency ends at +stream completion. Both timings include HTTP and frontend tokenization on OMAN +over loopback. Engine prompt throughput uses freshly read tokens divided by +`prompt_ms`; decode throughput uses `engine_generated / decode_ms`. The JSON +preserves the engine timing values and output text for each run. + +## Results + +Each cell below is the median **[minimum–maximum]** of three runs. Every request +generated 256 tokens and stopped at the output limit, with no failed or cancelled +speed requests. + +| Prompt tokens | Reused | Prompt tok/s | Decode tok/s | TTFT seconds | Total seconds | +| ---: | ---: | ---: | ---: | ---: | ---: | +| 4,096 | 0 | 4,269.8 [3,510.2–4,273.3] | 179.4 [161.3–184.8] | 0.974 [0.973–1.183] | 2.392 [2.351–2.761] | +| 32,768 | 0 | 5,543.2 [5,527.1–5,549.6] | 175.7 [166.1–181.8] | 5.950 [5.942–5.968] | 7.390 [7.348–7.498] | +| 128,000 | 0 | 5,778.7 [5,767.0–5,791.9] | 165.0 [154.8–169.3] | 22.262 [22.212–22.308] | 23.850 [23.765–23.856] | + +Raw per-run records: [results.json](results.json). Calculated aggregates: +[summary.json](summary.json). The lower first 4K run is retained in the range. +Decode expert-cache hit rates were 97.8–99.7% for these nine requests. + +[monitor.py](monitor.py) sampled the host once per second, starting before model +load and ending after the recall checks. [telemetry.jsonl](telemetry.jsonl) +contains 250 samples over 255.9 seconds, with the following observed peaks: + +- GPU memory: **31,785 MiB (31.04 GiB)**, system-wide on the selected GPU. +- Host RAM: **45.54 GiB**, calculated as `MemTotal - MemAvailable`. This includes + Strata, other services, and non-reclaimable system memory; it is not process RSS. +- Swap allocation increased from **0.25 MiB to 425.50 MiB**, including increases + during the speed suite. Swap I/O rates were not measured, so this is not a + claim that inference ran without paging. No out-of-memory error occurred. + +Sampling and the server's own telemetry were active during inference. These +are sampled peaks; brief allocation spikes between samples may be missed. +Aggregates are also recorded in [memory-summary.json](memory-summary.json). + +## Recall and limitations + +The repository's unchanged `tools/needle_bench.py` found **all six needles**: +depths 10%, 50%, and 90% at both requested lengths. Actual prompt lengths were +30,804–30,805 tokens for `32k` and 126,318–126,320 for `128k`. All answers exactly +matched the expected code words. See [needles.json](needles.json). + +The final 128K recall case reused 16,384 prompt tokens; the other five reused +zero. Recall latency is therefore not used in the fresh-prompt speed table. +The script chooses needle depth by character position, not token position. + +This is one machine, one quantization, one configuration, and a small synthetic +workload. Long output, sampled decoding, thinking, coding-task correctness, +vision, tool use, multi-request concurrency, and a sustained thermal run were +not evaluated. The built-in needle check measures recall on these six inputs, +not general model accuracy. No same-workload baseline on another engine or GPU +was run; do not interpret the README's different-hardware numbers as a controlled +comparison. The 128,000-token speed prompt also does not fill every token of the +131,072-token context window. diff --git a/bench/results/2026-09-30-community-rtx-5090/artifact-hashes.json b/bench/results/2026-09-30-community-rtx-5090/artifact-hashes.json new file mode 100644 index 0000000..cde7e66 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/artifact-hashes.json @@ -0,0 +1,82 @@ +[ + { + "file": "Strata-data/mtp/mtp-q2_0.gguf", + "bytes": 889017216, + "sha256": "a22206a4d74eafbf31063a84610292535fb3b49af9a339963817fd04aed81e4d" + }, + { + "file": "Strata-data/mtp/rt/dense.bin", + "bytes": 116099072, + "sha256": "c724dc0b0822ada5d2977bf5bde821605feabaa64ea2e0045b67ca656329070a" + }, + { + "file": "Strata-data/mtp/rt/dense.txt", + "bytes": 1851, + "sha256": "991456cf4eb266eb8a888c349e548d11bc640f5dbd9149439aa9786af0f732fd" + }, + { + "file": "Strata-data/mtp/rt/draft_vocab.bin", + "bytes": 425196, + "sha256": "b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91" + }, + { + "file": "Strata-data/mtp/rt/experts.bin", + "bytes": 707788800, + "sha256": "09398406be61f1f54c93861f449e48b8df0bfccbc9ec9b2b7636775a6ea9244f" + }, + { + "file": "Strata-data/packs/iq2_xs/dense.bin", + "bytes": 1538035200, + "sha256": "d2af3d8331e5c7a1985d1d589747230f9d56719a6d33c7cddc9ee6b81cde6b13" + }, + { + "file": "Strata-data/packs/iq2_xs/index.txt", + "bytes": 93686, + "sha256": "19e781af360ca3b83fd90fe09e757ac9aa2a9dcada26810ddc9e933bdb112091" + }, + { + "file": "Strata-data/packs/iq2_xs/native_experts.txt", + "bytes": 3289, + "sha256": "48df605acb89c7e8c3176a51cec777c2ed344ea439e8f3a37e5ce4f9dcb6946c" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/chat_template.jinja", + "bytes": 9993, + "sha256": "12827f24b742ea4e80cdc12dbcf9622227056b9f797252a3149263d4f9aaadce" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/merges.txt", + "bytes": 3353258, + "sha256": "4ba698529766c7a2f5052083ea10cdf2485577f5237a332ee291054eb11e3332" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/token_type.json", + "bytes": 744960, + "sha256": "5088c8c298fc06af8382ddb3b76c888703ac2634e82263b97eedcc2ad202738b" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/tokenizer.json", + "bytes": 541, + "sha256": "c0bd435efbc6c3b28964b47999afe16c4ad268c7c7c4e8cb3af410796a6f30bf" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/vocab.json", + "bytes": 5737005, + "sha256": "4ba64f0332abcfb0b600b7df1537d1e836e68009d5fb7cdb77339738dc6365c4" + }, + { + "file": "Strata/data/expert-profile.bin", + "bytes": 196632, + "sha256": "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf" + }, + { + "file": "Strata/engine/strata", + "bytes": 43158256, + "sha256": "b7f18df1314ad438952ca11bb5ce5f23b41e7a572462426383d2ad8209fcf367" + }, + { + "file": "Strata/engine/strata-vision", + "bytes": 74993888, + "sha256": "0d4c955f255ba4c3a9f6f456d63292754fae440a8a39cb13b9b6564938448e19" + } +] diff --git a/bench/results/2026-09-30-community-rtx-5090/benchmark.py b/bench/results/2026-09-30-community-rtx-5090/benchmark.py new file mode 100644 index 0000000..cdb6e4c --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/benchmark.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Serial, fresh-prompt Strata benchmark. Run inside its prepared environment.""" +import argparse +import hashlib +import json +import statistics +import sys +import time +import urllib.request +from pathlib import Path + + +def get(url): + with urllib.request.urlopen(url, timeout=30) as response: + return json.load(response) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path("/workspace/Strata")) + parser.add_argument("--pack", type=Path, default=Path("/workspace/Strata-data/packs/iq2_xs")) + parser.add_argument("--url", default="http://127.0.0.1:18080") + parser.add_argument("--out", type=Path, default=Path("/workspace/results")) + parser.add_argument("--targets", default="4096,32768,128000") + parser.add_argument("--runs", type=int, default=3) + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + sys.path[:0] = [str(args.root), str(args.root / "tools")] + from strata_tokenizer import Tokenizer + from serve.frontend import ChatTemplate, openai_to_messages + directory = args.pack / "tokenizer" + vocab = json.loads((directory / "vocab.json").read_text()) + tokens = [None] * len(vocab) + for token, number in vocab.items(): + tokens[number] = token + tokenizer = Tokenizer(tokens, (directory / "merges.txt").read_text().splitlines(), + json.loads((directory / "token_type.json").read_text())) + template = ChatTemplate(directory / "chat_template.jinja") + initial = get(args.url + "/v1/status") + (args.out / "initial-status.json").write_text(json.dumps(initial, indent=2) + "\n") + rows = [] + + def request(content, maximum=256): + return {"model": "strata", "messages": [{"role": "user", "content": content}], + "temperature": 0, "reasoning_effort": "none", "max_tokens": maximum, + "stream": True, "stream_options": {"include_usage": True}} + + def count(req): + messages, tools, kwargs = openai_to_messages(req) + return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True)) + + def perform(label, req, expected=None): + body = json.dumps(req).encode() + (args.out / (label + "-request.json")).write_bytes(body + b"\n") + print("start", label, "tokens", expected, flush=True) + chunks, texts, first, finish = [], [], None, None + started = time.perf_counter() + wire = urllib.request.Request(args.url + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(wire, timeout=1800) as response: + for line in response: + if not line.startswith(b"data: "): + continue + payload = line[6:].strip() + if payload == b"[DONE]": + break + chunk = json.loads(payload) + chunks.append(chunk) + for choice in chunk.get("choices", []): + delta = choice.get("delta", {}) + text = (delta.get("content") or "") + (delta.get("reasoning_content") or "") + if text: + first = first if first is not None else time.perf_counter() - started + texts.append(text) + finish = choice.get("finish_reason") or finish + elapsed = time.perf_counter() - started + metrics = get(args.url + "/metrics") + engine = metrics["requests"][0] + usage = next((chunk["usage"] for chunk in reversed(chunks) if "usage" in chunk), {}) + row = {"label": label, "expected_prompt_tokens": expected, + "request_sha256": hashlib.sha256(body).hexdigest(), + "client_ttft_s": first, "client_elapsed_s": elapsed, "finish_reason": finish, + "usage": usage, "engine": engine, "text": "".join(texts)} + if expected is not None and engine["prompt_tokens"] != expected: + raise RuntimeError(f"token count mismatch: {expected} vs {engine['prompt_tokens']}") + if not texts: + raise RuntimeError(f"no text received for {label}") + (args.out / (label + "-raw.json")).write_text(json.dumps({"chunks": chunks, "row": row}, indent=2) + "\n") + rows.append(row) + (args.out / "results.json").write_text(json.dumps(rows, indent=2) + "\n") + print("done", label, json.dumps({"ttft_s": first, "elapsed_s": elapsed, "engine": engine}), flush=True) + return row + + perform("warmup", request("Reply with exactly the word READY.", 16)) + # Each nonce occurs before the filler so previous long prompts cannot be reused. + filler = "\n".join(f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003" + for i in range(12000)) + ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, " + "modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.") + for target in map(int, args.targets.split(",")): + for run in range(1, args.runs + 1): + prefix = f"Benchmark nonce: series-{target}-trial-{run}.\nReview this synthetic Python module:\n" + lo, hi = 0, len(filler) + while lo < hi: + middle = (lo + hi + 1) // 2 + if count(request(prefix + filler[:middle] + ending)) <= target: + lo = middle + else: + hi = middle - 1 + req = request(prefix + filler[:lo] + ending) + actual = count(req) + if actual < target - 20 or actual > target: + raise RuntimeError(f"could not construct target {target}: {actual}") + perform(f"tokens-{target}-run-{run}", req, actual) + measured = [row for row in rows if row["label"] != "warmup"] + groups = {} + for target in map(int, args.targets.split(",")): + subset = [r for r in measured if r["label"].startswith(f"tokens-{target}-")] + values = { + "prompt_tokens": [r["engine"]["prompt_tokens"] for r in subset], + "cached_tokens": [r["engine"].get("reused", 0) for r in subset], + "output_tokens": [r["engine"]["engine_generated"] for r in subset], + "client_ttft_s": [r["client_ttft_s"] for r in subset], + "client_elapsed_s": [r["client_elapsed_s"] for r in subset], + "prefill_tok_s": [(r["engine"]["prompt_tokens"] - (r["engine"].get("reused") or 0)) / (r["engine"]["prompt_ms"] / 1000) for r in subset], + "decode_tok_s": [r["engine"]["engine_generated"] / (r["engine"]["decode_ms"] / 1000) for r in subset], + } + groups[str(target)] = {key: {"median": statistics.median(v), "min": min(v), "max": max(v)} + for key, v in values.items()} + (args.out / "summary.json").write_text(json.dumps(groups, indent=2) + "\n") + print("summary", json.dumps(groups), flush=True) + + +if __name__ == "__main__": + main() diff --git a/bench/results/2026-09-30-community-rtx-5090/final-status.json b/bench/results/2026-09-30-community-rtx-5090/final-status.json new file mode 100644 index 0000000..de26a05 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/final-status.json @@ -0,0 +1 @@ +{"service": "strata", "model": "qwen3.8-flash-next-iq2_xs", "engine": "0.1.29", "started": 1790772696, "uptime_s": 196, "cache_max_tokens": 131072, "context": {"native": 131072, "max_positions": 131072}, "concurrency": {"serving": 1, "requested": 1}, "dialects": ["/v1/chat/completions", "/v1/messages"], "vision": {"enabled": true, "available": true, "error": null}, "activity": {"requests": 16, "in_flight": 0, "last_request_at": 1790772892}, "last_timings": {"cache_n": 16384, "prompt_n": 109934, "prompt_ms": 19791.2, "prompt_per_token_ms": 0.18, "prompt_per_second": 5554.7, "predicted_n": 9, "predicted_ms": 78.1, "predicted_per_token_ms": 8.678, "predicted_per_second": 115.2, "draft_n": 9, "draft_n_accepted": 7, "at": 1790772892}, "machine": {"at": 1790772892, "gpu": {"name": "NVIDIA GeForce RTX 5090", "used_mib": 32281.0, "total_mib": 32607.0, "util_pct": 100, "temp_c": 72, "power_w": 528.823}, "ram": {"used_gib": 45.4, "total_gib": 62.2}}} \ No newline at end of file diff --git a/bench/results/2026-09-30-community-rtx-5090/initial-status.json b/bench/results/2026-09-30-community-rtx-5090/initial-status.json new file mode 100644 index 0000000..93fe618 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/initial-status.json @@ -0,0 +1,46 @@ +{ + "service": "strata", + "model": "qwen3.8-flash-next-iq2_xs", + "engine": "0.1.29", + "started": 1790772696, + "uptime_s": 2, + "cache_max_tokens": 131072, + "context": { + "native": 131072, + "max_positions": 131072 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": true, + "available": true, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1790772698, + "gpu": { + "name": "NVIDIA GeForce RTX 5090", + "used_mib": 32195.0, + "total_mib": 32607.0, + "util_pct": 0, + "temp_c": 36, + "power_w": 83.403 + }, + "ram": { + "used_gib": 44.4, + "total_gib": 62.2 + } + } +} diff --git a/bench/results/2026-09-30-community-rtx-5090/memory-summary.json b/bench/results/2026-09-30-community-rtx-5090/memory-summary.json new file mode 100644 index 0000000..b750522 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/memory-summary.json @@ -0,0 +1,10 @@ +{ + "samples": 250, + "sample_duration_s": 255.8539924621582, + "sampling_method": "nominal 1 s; /proc/meminfo and nvidia-smi; startup through recall checks", + "ram_peak_GiB": 45.54487228393555, + "gpu_peak_MiB": 31785.0, + "swap_start_MiB": 0.25, + "swap_peak_MiB": 425.5, + "swap_end_MiB": 425.5 +} diff --git a/bench/results/2026-09-30-community-rtx-5090/model-provenance.json b/bench/results/2026-09-30-community-rtx-5090/model-provenance.json new file mode 100644 index 0000000..c22afda --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/model-provenance.json @@ -0,0 +1,46 @@ +[ + { + "repository": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", + "revision": "ed59f92082b1e93c0e96d60a8b11aab089b52f09", + "gguf_files": [ + { + "filename": "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "lfs": { + "sha256": "92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7", + "size": 39225954592, + "pointerSize": 136 + }, + "size": 39225954592, + "actual_sha256": "92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7", + "verified": true + }, + { + "filename": "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf", + "lfs": { + "sha256": "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113", + "size": 28800138432, + "pointerSize": 136 + }, + "size": 28800138432, + "actual_sha256": "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113", + "verified": true + }, + { + "filename": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", + "lfs": { + "sha256": "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0", + "size": 907543008, + "pointerSize": 134 + }, + "size": 907543008, + "actual_sha256": "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0", + "verified": true + } + ] + }, + { + "repository": "Qwen/Qwen3.8-Flash-Next", + "revision": "de4b8e4d43b917e7706784d8bb445c9af86a3540", + "gguf_files": [] + } +] diff --git a/bench/results/2026-09-30-community-rtx-5090/monitor.py b/bench/results/2026-09-30-community-rtx-5090/monitor.py new file mode 100644 index 0000000..6f9f808 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/monitor.py @@ -0,0 +1,18 @@ +"""Sample system RAM, swap and GPU memory once per second during the trial.""" +import json +import subprocess +import sys +import time +from pathlib import Path + +with Path(sys.argv[1] if len(sys.argv) > 1 else 'telemetry.jsonl').open('a') as output: + while True: + memory = {} + for line in Path('/proc/meminfo').read_text().splitlines(): + key, value = line.split(':', 1) + if key in ('MemTotal', 'MemAvailable', 'SwapTotal', 'SwapFree'): + memory[key + '_KiB'] = int(value.strip().split()[0]) + gpu = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.used,memory.total,utilization.gpu,power.draw,temperature.gpu', '--format=csv,noheader,nounits'], text=True).strip() + output.write(json.dumps({'epoch_s': time.time(), 'memory': memory, 'gpu': gpu}) + '\n') + output.flush() + time.sleep(1) diff --git a/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json b/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json new file mode 100644 index 0000000..fca1a9d --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json @@ -0,0 +1,429 @@ +[ + { + "name": "mtp.fc_embedding.weight", + "shard": "model-00120-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560, + 2560 + ], + "start": 1935412640, + "end": 1948519839, + "bytes": 13107200, + "file": "tensors/mtp.fc_embedding.weight.bin", + "sha256": "241d6e87ded317a61b1aeb3ca4e28c53f1caba09ad5be66092e91fe5e3e14751" + }, + { + "name": "mtp.fc_hidden.weight", + "shard": "model-00124-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560, + 2560 + ], + "start": 1716599928, + "end": 1729707127, + "bytes": 13107200, + "file": "tensors/mtp.fc_hidden.weight.bin", + "sha256": "97c8e427ad0177e2c713ed24a397d815b523eda15ef453f1ae6463f6c70a8f96" + }, + { + "name": "mtp.hyper_connection_mixer.hc_norm.weight", + "shard": "model-00037-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240 + ], + "start": 1742326680, + "end": 1742347159, + "bytes": 20480, + "file": "tensors/mtp.hyper_connection_mixer.hc_norm.weight.bin", + "sha256": "ce948a398e15aeaa403c424cda34e6eed296ab2570d591bb5ff3da642b255d64" + }, + { + "name": "mtp.hyper_connection_mixer.input_mix_weight_down.weight", + "shard": "model-00041-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 320, + 10240 + ], + "start": 1935412688, + "end": 1941966287, + "bytes": 6553600, + "file": "tensors/mtp.hyper_connection_mixer.input_mix_weight_down.weight.bin", + "sha256": "c633d2841fda463e82045e0b93fb8cb8d511ec0c9eda616020f01aca18d71947" + }, + { + "name": "mtp.hyper_connection_mixer.input_mix_weight_up.weight", + "shard": "model-00043-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240, + 320 + ], + "start": 1832518416, + "end": 1839072015, + "bytes": 6553600, + "file": "tensors/mtp.hyper_connection_mixer.input_mix_weight_up.weight.bin", + "sha256": "6565285f0ba2923703252763cfc11d8a9bda40ab42e7548e12464b04dbdbec13" + }, + { + "name": "mtp.layers.0.attn_hyper_connection.block_inject_weight.weight", + "shard": "model-00047-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 4, + 10240 + ], + "start": 1716599984, + "end": 1716681903, + "bytes": 81920, + "file": "tensors/mtp.layers.0.attn_hyper_connection.block_inject_weight.weight.bin", + "sha256": "c8afff64e7f54412d02120097c4255033c55245e1c1eed84cc630d428ccb864c" + }, + { + "name": "mtp.layers.0.attn_hyper_connection.hc_norm.weight", + "shard": "model-00049-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240 + ], + "start": 1935412672, + "end": 1935433151, + "bytes": 20480, + "file": "tensors/mtp.layers.0.attn_hyper_connection.hc_norm.weight.bin", + "sha256": "1fb619aeaaf637ccd70f46f1f8f8116e6a46448cb43026b246de8ee8286ed809" + }, + { + "name": "mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight", + "shard": "model-00053-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 320, + 10240 + ], + "start": 1832518424, + "end": 1839072023, + "bytes": 6553600, + "file": "tensors/mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight.bin", + "sha256": "e80ac8bf3e270e9d5a949ec7c913329dc8de017d69851334820fae7b8c86a7f5" + }, + { + "name": "mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight", + "shard": "model-00057-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240, + 320 + ], + "start": 1935412680, + "end": 1941966279, + "bytes": 6553600, + "file": "tensors/mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight.bin", + "sha256": "f80f1fd44e1183e7764ea496b11ff89ead9dd758f861d4e79a770bf54956b1a5" + }, + { + "name": "mtp.layers.0.mlp.experts.down_proj", + "shard": "model-00062-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 2560, + 640 + ], + "start": 1832518400, + "end": 3510239999, + "bytes": 1677721600, + "file": "tensors/mtp.layers.0.mlp.experts.down_proj.bin", + "sha256": "539c46234f73bac70450f731f40e715f77ac32faf77def0f3f800e58aaabbbc0" + }, + { + "name": "mtp.layers.0.mlp.experts.gate_up_proj", + "shard": "model-00060-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 1280, + 2560 + ], + "start": 115918328, + "end": 3471361527, + "bytes": 3355443200, + "file": "tensors/mtp.layers.0.mlp.experts.gate_up_proj.bin", + "sha256": "839e98f9642ebc884b178abd2090b6dc8b0bcd81ed92d7f7a08314c6a68f96d5" + }, + { + "name": "mtp.layers.0.mlp.gate.weight", + "shard": "model-00066-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 2560 + ], + "start": 1716599952, + "end": 1719221391, + "bytes": 2621440, + "file": "tensors/mtp.layers.0.mlp.gate.weight.bin", + "sha256": "f0d35fa41b360a08bc0c5b1e5766aa42df960291716ee189208b5d2599462c20" + }, + { + "name": "mtp.layers.0.mlp.shared_expert.down_proj.weight", + "shard": "model-00076-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560, + 640 + ], + "start": 1935412680, + "end": 1938689479, + "bytes": 3276800, + "file": "tensors/mtp.layers.0.mlp.shared_expert.down_proj.weight.bin", + "sha256": "d2ced8c81367cc494599d1a8cdc279c3dd6579b628ded05acd7495e99cee01d8" + }, + { + "name": "mtp.layers.0.mlp.shared_expert.gate_proj.weight", + "shard": "model-00072-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 640, + 2560 + ], + "start": 1832518528, + "end": 1835795327, + "bytes": 3276800, + "file": "tensors/mtp.layers.0.mlp.shared_expert.gate_proj.weight.bin", + "sha256": "f4a81109165853b3b64f36d809f98094b599763364070f5fa079200e1c386d4c" + }, + { + "name": "mtp.layers.0.mlp.shared_expert.up_proj.weight", + "shard": "model-00072-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 640, + 2560 + ], + "start": 1835795328, + "end": 1839072127, + "bytes": 3276800, + "file": "tensors/mtp.layers.0.mlp.shared_expert.up_proj.weight.bin", + "sha256": "172586861eea53efbff10afc43ded5b6e49c83879e9efc01e089c652bbb0a156" + }, + { + "name": "mtp.layers.0.mlp.shared_expert_gate.weight", + "shard": "model-00070-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 1, + 2560 + ], + "start": 1832518400, + "end": 1832523519, + "bytes": 5120, + "file": "tensors/mtp.layers.0.mlp.shared_expert_gate.weight.bin", + "sha256": "acdd306d9996d356e4667a16ff63af6fef086fc7f570f1bc00bbe882a2a93f6e" + }, + { + "name": "mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight", + "shard": "model-00078-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 4, + 10240 + ], + "start": 1832518424, + "end": 1832600343, + "bytes": 81920, + "file": "tensors/mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight.bin", + "sha256": "c5782dd92b479a1f8ef43d683fe9c917fd9e8fba81f23c1aae8817bfe4b476a6" + }, + { + "name": "mtp.layers.0.mlp_hyper_connection.hc_norm.weight", + "shard": "model-00082-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240 + ], + "start": 1935412656, + "end": 1935433135, + "bytes": 20480, + "file": "tensors/mtp.layers.0.mlp_hyper_connection.hc_norm.weight.bin", + "sha256": "21a504876b5e7b788301557c68dfb757999430eba36c66ec8ab96a63604dbfd1" + }, + { + "name": "mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight", + "shard": "model-00086-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 320, + 10240 + ], + "start": 1935412696, + "end": 1941966295, + "bytes": 6553600, + "file": "tensors/mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight.bin", + "sha256": "b71240036dea954e034d5ae04e097bcd7ac51cb28a44e4c93d198af3447278a1" + }, + { + "name": "mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight", + "shard": "model-00088-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240, + 320 + ], + "start": 1832518424, + "end": 1839072023, + "bytes": 6553600, + "file": "tensors/mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight.bin", + "sha256": "40756866bf2a5e82c28e407f717b6fa07614d593f78e79c7ceb2cd4ffe6dda94" + }, + { + "name": "mtp.layers.0.self_attn.indexer.index_qk_proj.weight", + "shard": "model-00090-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 640, + 2560 + ], + "start": 1832518416, + "end": 1835795215, + "bytes": 3276800, + "file": "tensors/mtp.layers.0.self_attn.indexer.index_qk_proj.weight.bin", + "sha256": "2befafae6e944c1fc651fd73d4d527eb6f138a6c1679065b003128ee3150e859" + }, + { + "name": "mtp.layers.0.self_attn.indexer.k_layernorm.weight", + "shard": "model-00094-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 128 + ], + "start": 1935412672, + "end": 1935412927, + "bytes": 256, + "file": "tensors/mtp.layers.0.self_attn.indexer.k_layernorm.weight.bin", + "sha256": "2db621f6a08b4085756fc69d60a4a1bd1d7fbf5d406456d2477075842efaae54" + }, + { + "name": "mtp.layers.0.self_attn.indexer.q_layernorm.weight", + "shard": "model-00100-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 128 + ], + "start": 1716599968, + "end": 1716600223, + "bytes": 256, + "file": "tensors/mtp.layers.0.self_attn.indexer.q_layernorm.weight.bin", + "sha256": "afaf59f68e251939970ffdeacad0667dffc657a522bea62cdc44a52816fc49d6" + }, + { + "name": "mtp.layers.0.self_attn.k_norm.weight", + "shard": "model-00102-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 256 + ], + "start": 1935412648, + "end": 1935413159, + "bytes": 512, + "file": "tensors/mtp.layers.0.self_attn.k_norm.weight.bin", + "sha256": "8f924b0357cf936e14fc34518205d000e1423aa60626827df81b0804fae8cdfd" + }, + { + "name": "mtp.layers.0.self_attn.k_proj.weight", + "shard": "model-00108-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 2560 + ], + "start": 1832518624, + "end": 1835140063, + "bytes": 2621440, + "file": "tensors/mtp.layers.0.self_attn.k_proj.weight.bin", + "sha256": "1a295dc2d6e633e808aeb19e00c97856a1817bbfcc83f5b610e2bfcacfcb8c38" + }, + { + "name": "mtp.layers.0.self_attn.o_proj.weight", + "shard": "model-00106-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560, + 6144 + ], + "start": 1832518400, + "end": 1863975679, + "bytes": 31457280, + "file": "tensors/mtp.layers.0.self_attn.o_proj.weight.bin", + "sha256": "9d2fcf0ac6ac19de87f638f710cfd1af6ad14141e75b7d3d5d29fbd06f374219" + }, + { + "name": "mtp.layers.0.self_attn.q_norm.weight", + "shard": "model-00112-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 256 + ], + "start": 1935412664, + "end": 1935413175, + "bytes": 512, + "file": "tensors/mtp.layers.0.self_attn.q_norm.weight.bin", + "sha256": "57957aa1e7c5a3ac628bff0ec5522ad55a39b8c0b8bd2d324ae640e3771617ef" + }, + { + "name": "mtp.layers.0.self_attn.q_proj.weight", + "shard": "model-00108-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 12288, + 2560 + ], + "start": 1835140064, + "end": 1898054623, + "bytes": 62914560, + "file": "tensors/mtp.layers.0.self_attn.q_proj.weight.bin", + "sha256": "5220aef3d288f40759f7356af9ef453e5ac0256a38749a9bb803a4e9db58150d" + }, + { + "name": "mtp.layers.0.self_attn.v_proj.weight", + "shard": "model-00108-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 2560 + ], + "start": 1898054624, + "end": 1900676063, + "bytes": 2621440, + "file": "tensors/mtp.layers.0.self_attn.v_proj.weight.bin", + "sha256": "39cb12f5424e965fa71fb81db0ee230c701b7b1e0b72c36641fde7e0e41bff41" + }, + { + "name": "mtp.pre_fc_norm_embedding.weight", + "shard": "model-00114-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560 + ], + "start": 1832518392, + "end": 1832523511, + "bytes": 5120, + "file": "tensors/mtp.pre_fc_norm_embedding.weight.bin", + "sha256": "04c4a570850e06f2d8913da8220d54d4c7f87db6eb6d45480b938e8ba41d6a86" + }, + { + "name": "mtp.pre_fc_norm_hidden.weight", + "shard": "model-00118-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240 + ], + "start": 1716599944, + "end": 1716620423, + "bytes": 20480, + "file": "tensors/mtp.pre_fc_norm_hidden.weight.bin", + "sha256": "b933b44559879449b1baf2af8385c5c237347307e3fd452394870cb53e6eab6d" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-30-community-rtx-5090/needles.json b/bench/results/2026-09-30-community-rtx-5090/needles.json new file mode 100644 index 0000000..01a7c07 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/needles.json @@ -0,0 +1,56 @@ +[ + { + "length": "32k", + "depth": 10, + "prompt_tokens": 30804, + "seconds": 6.5, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "32k", + "depth": 50, + "prompt_tokens": 30804, + "seconds": 5.8, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + }, + { + "length": "32k", + "depth": 90, + "prompt_tokens": 30805, + "seconds": 5.8, + "found": true, + "word": "willow-cobalt-696", + "answer": "willow-cobalt-696" + }, + { + "length": "128k", + "depth": 10, + "prompt_tokens": 126320, + "seconds": 22.5, + "found": true, + "word": "falcon-saffron-138", + "answer": "falcon-saffron-138" + }, + { + "length": "128k", + "depth": 50, + "prompt_tokens": 126318, + "seconds": 22.8, + "found": true, + "word": "quartz-tundra-528", + "answer": "quartz-tundra-528" + }, + { + "length": "128k", + "depth": 90, + "prompt_tokens": 126318, + "seconds": 20.1, + "found": true, + "word": "quartz-glacier-192", + "answer": "quartz-glacier-192" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-30-community-rtx-5090/python-packages.txt b/bench/results/2026-09-30-community-rtx-5090/python-packages.txt new file mode 100644 index 0000000..9e4e371 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/python-packages.txt @@ -0,0 +1,15 @@ +certifi==2026.7.22 +charset-normalizer==3.5.2 +cmake==4.4.3 +idna==3.20 +Jinja2==3.1.6 +MarkupSafe==3.0.3 +ninja==1.13.2 +numpy==2.5.3 +pillow==12.3.0 +psutil==7.2.2 +PyYAML==6.0.3 +regex==2026.9.29 +requests==2.34.2 +tqdm==4.70.1 +urllib3==2.8.0 diff --git a/bench/results/2026-09-30-community-rtx-5090/results.json b/bench/results/2026-09-30-community-rtx-5090/results.json new file mode 100644 index 0000000..1a0b67b --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/results.json @@ -0,0 +1,312 @@ +[ + { + "label": "warmup", + "expected_prompt_tokens": null, + "request_sha256": "b63e57873441a996a529b246a66cf12de70a7c671777f99329354d5c195f788f", + "client_ttft_s": 0.15764825499991275, + "client_elapsed_s": 0.19575888999997915, + "finish_reason": "stop", + "usage": { + "prompt_tokens": 19, + "completion_tokens": 2, + "total_tokens": 21, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772698.967025, + "duration_s": 0.2, + "finish": "stop", + "prompt_tokens": 19, + "reused": 0, + "output_tokens": 2, + "engine_generated": 2, + "prompt_ms": 134.9, + "decode_ms": 57.4, + "decode_tok_s": 34.8, + "hit_rate": 0.908 + }, + "text": "READY" + }, + { + "label": "tokens-4096-run-1", + "expected_prompt_tokens": 4096, + "request_sha256": "5d94c652067354bbe72930d2bdad3886564f08cf2546b32411af02d33ad3ce05", + "client_ttft_s": 1.1827884900003482, + "client_elapsed_s": 2.7608979090000503, + "finish_reason": "length", + "usage": { + "prompt_tokens": 4096, + "completion_tokens": 256, + "total_tokens": 4352, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772699.5014164, + "duration_s": 2.8, + "finish": "length", + "prompt_tokens": 4096, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1166.9, + "decode_ms": 1587.0, + "decode_tok_s": 161.3, + "hit_rate": 0.978 + }, + "text": "# Analysis of Synthetic Python Module: Deterministic Integer Transforms\n\nThe provided Python module consists of a series of functions, `task_00000` through `task_00112`, each implementing a specific deterministic integer transformation. While the code appears repetitive, it serves as a clear example of modular arithmetic, function design, and the trade-offs between explicit implementation and algorithmic abstraction. Below is a detailed discussion covering the mathematical basis, testing implications, naming conventions, complexity, and maintainability.\n\n## 1. Mathematical Basis: Deterministic Transforms and Modulo Arithmetic\n\nAt its core, every function in this module performs a linear transformation on an input integer `value`. The general pattern for `task_NNNNN` is:\n\n$$ f(x) = (x \\cdot a + b) \\pmod{M} $$\n\nWhere:\n- $M = 100003$ is a fixed modulus.\n- $a$ is the multiplier.\n- $b$ is the additive constant.\n\nFor most functions (e.g., `task_00000` to `task_00096`), the multiplier $a$ and the additive constant $b$ follow a" + }, + { + "label": "tokens-4096-run-2", + "expected_prompt_tokens": 4096, + "request_sha256": "8da8a04e70e4d916f6630729082bdfb9d6ebbb47117aad60bc0541bce198a213", + "client_ttft_s": 0.9743533680002656, + "client_elapsed_s": 2.3506501550000394, + "finish_reason": "length", + "usage": { + "prompt_tokens": 4096, + "completion_tokens": 256, + "total_tokens": 4352, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772702.5992615, + "duration_s": 2.3, + "finish": "length", + "prompt_tokens": 4096, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 959.3, + "decode_ms": 1385.0, + "decode_tok_s": 184.8, + "hit_rate": 0.993 + }, + "text": "# Analysis of Synthetic Python Module: Deterministic Integer Transforms\n\nThe provided Python module consists of a series of functions, `task_00000` through `task_00112`, each implementing a specific deterministic integer transformation. While the code appears repetitive, it serves as a clear example of modular arithmetic, function design, and the trade-offs between explicit implementation and algorithmic abstraction. Below is a detailed discussion of the code's structure, mathematical properties, testing implications, and maintainability.\n\n## 1. Mathematical Structure and Deterministic Transforms\n\nAt its core, every function in this module implements a linear congruential generator (LCG) step or a simple affine transformation modulo a prime number. The general form of each function is:\n\n$$ f_n(x) = (x \\cdot a_n + b_n) \\pmod{M} $$\n\nWhere:\n- $M = 100003$ is a fixed modulus.\n- $a_n$ is the multiplier for function $n$.\n- $b_n$ is the additive constant for function $n$.\n\nFor the first 97 functions (`task_00000` to `task_00096`" + }, + { + "label": "tokens-4096-run-3", + "expected_prompt_tokens": 4096, + "request_sha256": "946079edb58e764050805886156dc8f877cc29e1ca8d01c84e9a1e7917d49492", + "client_ttft_s": 0.9733456560002196, + "client_elapsed_s": 2.391696067000339, + "finish_reason": "length", + "usage": { + "prompt_tokens": 4096, + "completion_tokens": 256, + "total_tokens": 4352, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772705.2866879, + "duration_s": 2.4, + "finish": "length", + "prompt_tokens": 4096, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 958.5, + "decode_ms": 1427.2, + "decode_tok_s": 179.4, + "hit_rate": 0.989 + }, + "text": "# Analysis of Synthetic Python Module: Deterministic Integer Transforms\n\nThe provided Python module consists of a series of functions, `task_00000` through `task_00112`, each implementing a specific deterministic integer transformation. While the code appears repetitive, it serves as a clear example of modular arithmetic, function design, and the trade-offs between explicit implementation and algorithmic abstraction. Below is a detailed discussion of the code\u2019s structure, mathematical properties, testing implications, naming conventions, complexity, and maintainability.\n\n## 1. Mathematical Structure and Deterministic Transforms\n\nEach function follows the general form:\n```python\ndef task_XXXXX(value: int) -> int:\n return (value * multiplier + addend) % MOD\n```\nwhere `MOD = 100003`.\n\nFor most functions, the multiplier and addend are derived from the function index `i`:\n- `multiplier = i + 1`\n- `addend = i`\n\nThus, for `task_00000`, `multiplier = 1`, `addend = 0`.\nFor `task_00001`, `multiplier = 2`, `" + }, + { + "label": "tokens-32768-run-1", + "expected_prompt_tokens": 32768, + "request_sha256": "e37cfc2ab9867d91130927440df24a57255a736b8d0d829d07d828e22e3de572", + "client_ttft_s": 5.9679448089996185, + "client_elapsed_s": 7.498308491999978, + "finish_reason": "length", + "usage": { + "prompt_tokens": 32768, + "completion_tokens": 256, + "total_tokens": 33024, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772708.3260226, + "duration_s": 7.5, + "finish": "length", + "prompt_tokens": 32768, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 5928.6, + "decode_ms": 1541.2, + "decode_tok_s": 166.1, + "hit_rate": 0.994 + }, + "text": "Based on the provided Python module, here is a detailed technical review and explanation.\n\n### Overview of the Module\n\nThe provided code defines a series of functions, `task_00000` through `task_00888`, that perform deterministic integer transformations. Each function takes an integer `value` and returns a new integer based on a specific linear formula involving multiplication, addition, and modulo arithmetic. The benchmark nonce `series-32768-trial-1` suggests this code is part of a larger test suite or performance benchmark, likely designed to evaluate computational consistency, hash generation, or state machine transitions.\n\n### Mathematical Logic and Deterministic Transforms\n\nAt its core, every function in this module implements a linear congruential generator (LCG) style transformation, albeit with varying parameters. The general structure of each function is:\n\n$$ f(x) = (x \\cdot a + b) \\pmod{100003} $$\n\nWhere:\n* $x$ is the input `value`.\n* $a$ is the multiplier (coefficient).\n* $b$ is the additive constant.\n* $100003$ is the modulus." + }, + { + "label": "tokens-32768-run-2", + "expected_prompt_tokens": 32768, + "request_sha256": "ed2dfaa11aecad9f4563f33bb5f5d4b8704486508700b8fa572722cc1225ee26", + "client_ttft_s": 5.950024114999906, + "client_elapsed_s": 7.348446455000158, + "finish_reason": "length", + "usage": { + "prompt_tokens": 32768, + "completion_tokens": 256, + "total_tokens": 33024, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772716.4558623, + "duration_s": 7.3, + "finish": "length", + "prompt_tokens": 32768, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 5911.4, + "decode_ms": 1408.3, + "decode_tok_s": 181.8, + "hit_rate": 0.994 + }, + "text": "Based on the provided synthetic Python module, here is a detailed technical review and explanation.\n\n### 1. Structural Analysis and Pattern Recognition\n\nThe module consists of a series of functions named `task_00000` through `task_00888` (the list appears truncated at `task_00888`, but the pattern implies a larger set). Each function follows a strict, deterministic signature: `def task_XXXXX(value: int) -> int`.\n\nThe core logic within each function is a linear transformation followed by a modulo operation:\n$$ f(x) = (x \\cdot a + b) \\pmod{100003} $$\n\nWhere:\n* $x$ is the input `value`.\n* $a$ is the multiplier.\n* $b$ is the additive constant.\n* $100003$ is the modulus.\n\n#### The Multiplier Pattern ($a$)\nThe multiplier $a$ follows a cyclic pattern. It starts at 1 and increments by 1 for each function until it reaches 97. After `task_00096` (where $a=97$), the" + }, + { + "label": "tokens-32768-run-3", + "expected_prompt_tokens": 32768, + "request_sha256": "2a3c7342622e80c3cd8b37e062f0a2f64640c119ece8cccbf168639041eac079", + "client_ttft_s": 5.941602006999801, + "client_elapsed_s": 7.389697677000186, + "finish_reason": "length", + "usage": { + "prompt_tokens": 32768, + "completion_tokens": 256, + "total_tokens": 33024, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772724.435358, + "duration_s": 7.4, + "finish": "length", + "prompt_tokens": 32768, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 5904.6, + "decode_ms": 1457.1, + "decode_tok_s": 175.7, + "hit_rate": 0.995 + }, + "text": "Based on the provided Python module, here is a detailed technical review and explanation.\n\n### 1. Structural Overview and Pattern Analysis\n\nThe provided code consists of a series of function definitions, ranging from `task_00000` to `task_00888`. Each function follows a strict, repetitive structure:\n\n```python\ndef task_XXXXX(value: int) -> int:\n return (value * A + B) % 100003\n```\n\nThis module is a synthetic representation of a **linear congruential generator (LCG)** or a set of **affine transformations** applied to an integer input. The core logic is consistent across all functions, with only the coefficients `A` (multiplier) and `B` (addend) changing.\n\n### 2. Deterministic Integer Transforms and Modulo Arithmetic\n\nThe mathematical core of this module is the expression `(value * A + B) % 100003`. This is a classic example of a **deterministic integer transform**.\n\n* **Determinism:** For any given input `value`, the output is always the same. There is no randomness, state, or side effects. This makes" + }, + { + "label": "tokens-128000-run-1", + "expected_prompt_tokens": 128000, + "request_sha256": "3235aac3f934cf1d889c25973ca172b355509dc2522fdfb463fbefe979a9075d", + "client_ttft_s": 22.212050286999784, + "client_elapsed_s": 23.856042405000153, + "finish_reason": "length", + "usage": { + "prompt_tokens": 128000, + "completion_tokens": 256, + "total_tokens": 128256, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772733.6124191, + "duration_s": 23.8, + "finish": "length", + "prompt_tokens": 128000, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 22099.7, + "decode_ms": 1653.5, + "decode_tok_s": 154.8, + "hit_rate": 0.994 + }, + "text": "Based on the provided synthetic Python module, here is a detailed technical review and explanation.\n\n### Overview of the Module\n\nThe provided code consists of a massive collection of function definitions, ranging from `task_00000` to `task_03404` (and potentially beyond, as the input cuts off). Each function follows a strict, repetitive pattern. The core logic of every function is identical in structure, differing only in the specific integer constants used for multiplication and addition.\n\nThe general form of any function `task_N` is:\n```python\ndef task_N(value: int) -> int:\n return (value * multiplier + addend) % 100003\n```\n\n### 1. Deterministic Integer Transforms and Modulo Arithmetic\n\nThe primary mechanism in this module is a **deterministic linear transform** followed by a **modulo operation**.\n\n**The Linear Transform:**\nFor any given `value`, the function computes `value * multiplier + addend`. This is an affine transformation. In mathematics, an affine transformation is a function that preserves points, straight lines, and planes. Here, it maps an input integer to an output integer based on a fixed slope (`multiplier`) and" + }, + { + "label": "tokens-128000-run-2", + "expected_prompt_tokens": 128000, + "request_sha256": "5f4b8bc9f0afc7765320abd89960c0938e0d7cf5974e962fdbd0613fef31c8d4", + "client_ttft_s": 22.262365384000077, + "client_elapsed_s": 23.764614322999932, + "finish_reason": "length", + "usage": { + "prompt_tokens": 128000, + "completion_tokens": 256, + "total_tokens": 128256, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772759.195895, + "duration_s": 23.7, + "finish": "length", + "prompt_tokens": 128000, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 22150.5, + "decode_ms": 1511.7, + "decode_tok_s": 169.3, + "hit_rate": 0.997 + }, + "text": "# Analysis of the Synthetic Python Module\n\nThe provided Python module consists of a massive collection of functions, ranging from `task_00000` to `task_03404` (and potentially beyond, as the code is truncated). Each function follows a strict, repetitive pattern: it accepts an integer `value`, applies a linear transformation, and returns the result modulo a fixed prime number, `100003`.\n\n## 1. Mathematical Structure and Deterministic Transforms\n\nAt its core, every function in this module implements a **linear congruential generator (LCG)** step or a simple affine transformation. The general formula for any function `task_N` is:\n\n$$ f_N(x) = (x \\cdot a_N + b_N) \\pmod{M} $$\n\nWhere:\n* $M = 100003$ is the modulus.\n* $a_N$ is the multiplier for task $N$.\n* $b_N$ is the additive constant for task $N$.\n\n### The Modulus: 100003\nThe choice of `100003` is significant. It is a **prime number**. In" + }, + { + "label": "tokens-128000-run-3", + "expected_prompt_tokens": 128000, + "request_sha256": "5c3fb71db9f9f44765f28389d1032f2c8b6687d1bf5ca6f33aeb924072cfa6e4", + "client_ttft_s": 22.308453708999878, + "client_elapsed_s": 23.850161715000013, + "finish_reason": "length", + "usage": { + "prompt_tokens": 128000, + "completion_tokens": 256, + "total_tokens": 128256, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772784.6969988, + "duration_s": 23.8, + "finish": "length", + "prompt_tokens": 128000, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 22195.2, + "decode_ms": 1551.4, + "decode_tok_s": 165.0, + "hit_rate": 0.997 + }, + "text": "Based on the provided synthetic Python module, here is a detailed technical review and explanation.\n\n### Overview of the Module\n\nThe provided code consists of a massive collection of function definitions, ranging from `task_00000` to `task_03404`. Each function accepts a single integer argument `value` and returns an integer. The core logic within every function is identical in structure, differing only in the specific coefficients used for multiplication and addition.\n\nThe general pattern for any function `task_N` is:\n```python\ndef task_N(value: int) -> int:\n return (value * multiplier + addend) % 100003\n```\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nThe functions implement a **deterministic linear transform** over the integers. In mathematics, this is an affine transformation defined by $f(x) = ax + b$. However, the code applies this transformation within a finite field defined by the modulus $M = 100003$.\n\n1. **Modulo Arithmetic**: The use of `% 100003` ensures that the output is always within the range $[0, 100002" + } +] diff --git a/bench/results/2026-09-30-community-rtx-5090/strata-iq2_xs.json b/bench/results/2026-09-30-community-rtx-5090/strata-iq2_xs.json new file mode 100644 index 0000000..6066e2b --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/strata-iq2_xs.json @@ -0,0 +1,50 @@ +{ + "exe": "/workspace/Strata/engine/strata", + "args": [ + "--pack", + "/workspace/Strata-data/packs/iq2_xs", + "--native", + "/workspace/Strata-data/models/IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "--ple-gguf", + "/workspace/Strata-data/models/IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf", + "--expert-profile", + "/workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/workspace/Strata-data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768", + "--vision", + "--vram-reserve-mib", + "700" + ], + "cwd": "/workspace/Strata", + "tokenizer": "/workspace/Strata-data/packs/iq2_xs/tokenizer", + "model_name": "qwen3.8-flash-next-iq2_xs", + "log": "/workspace/Strata/strata-iq2_xs.log", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 18080, + "gpu": 0, + "gpus_asked": true, + "vision": { + "exe": "/workspace/Strata/engine/strata-vision", + "mmproj": "/workspace/Strata-data/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", + "model": "/workspace/Strata-data/models/IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "gpu": true, + "max_tokens": 1024 + } +} \ No newline at end of file diff --git a/bench/results/2026-09-30-community-rtx-5090/summary.json b/bench/results/2026-09-30-community-rtx-5090/summary.json new file mode 100644 index 0000000..05bc1e7 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/summary.json @@ -0,0 +1,113 @@ +{ + "4096": { + "prompt_tokens": { + "median": 4096, + "min": 4096, + "max": 4096 + }, + "cached_tokens": { + "median": 0, + "min": 0, + "max": 0 + }, + "output_tokens": { + "median": 256, + "min": 256, + "max": 256 + }, + "client_ttft_s": { + "median": 0.9743533680002656, + "min": 0.9733456560002196, + "max": 1.1827884900003482 + }, + "client_elapsed_s": { + "median": 2.391696067000339, + "min": 2.3506501550000394, + "max": 2.7608979090000503 + }, + "prefill_tok_s": { + "median": 4269.780047951632, + "min": 3510.1551118347757, + "max": 4273.343766301513 + }, + "decode_tok_s": { + "median": 179.37219730941703, + "min": 161.31064902331443, + "max": 184.8375451263538 + } + }, + "32768": { + "prompt_tokens": { + "median": 32768, + "min": 32768, + "max": 32768 + }, + "cached_tokens": { + "median": 0, + "min": 0, + "max": 0 + }, + "output_tokens": { + "median": 256, + "min": 256, + "max": 256 + }, + "client_ttft_s": { + "median": 5.950024114999906, + "min": 5.941602006999801, + "max": 5.9679448089996185 + }, + "client_elapsed_s": { + "median": 7.389697677000186, + "min": 7.348446455000158, + "max": 7.498308491999978 + }, + "prefill_tok_s": { + "median": 5543.187738945089, + "min": 5527.105893465573, + "max": 5549.571520509433 + }, + "decode_tok_s": { + "median": 175.69144190515408, + "min": 166.10433428497274, + "max": 181.77945040119295 + } + }, + "128000": { + "prompt_tokens": { + "median": 128000, + "min": 128000, + "max": 128000 + }, + "cached_tokens": { + "median": 0, + "min": 0, + "max": 0 + }, + "output_tokens": { + "median": 256, + "min": 256, + "max": 256 + }, + "client_ttft_s": { + "median": 22.262365384000077, + "min": 22.212050286999784, + "max": 22.308453708999878 + }, + "client_elapsed_s": { + "median": 23.850161715000013, + "min": 23.764614322999932, + "max": 23.856042405000153 + }, + "prefill_tok_s": { + "median": 5778.6505947947, + "min": 5767.012687427912, + "max": 5791.933827156025 + }, + "decode_tok_s": { + "median": 165.01224700270723, + "min": 154.82310250982763, + "max": 169.34576966329297 + } + } +} diff --git a/bench/results/2026-09-30-community-rtx-5090/telemetry.jsonl b/bench/results/2026-09-30-community-rtx-5090/telemetry.jsonl new file mode 100644 index 0000000..21baed0 --- /dev/null +++ b/bench/results/2026-09-30-community-rtx-5090/telemetry.jsonl @@ -0,0 +1,250 @@ +{"epoch_s": 1790772668.438457, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 58332840, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "2, 32607, 1, 60.13, 36"} +{"epoch_s": 1790772669.461572, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 57749256, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "1374, 32607, 25, 53.81, 36"} +{"epoch_s": 1790772670.483304, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 56952232, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "3719, 32607, 2, 130.61, 36"} +{"epoch_s": 1790772671.5050805, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 56947812, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "3719, 32607, 3, 86.30, 36"} +{"epoch_s": 1790772672.5268102, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 56930224, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "4949, 32607, 3, 62.43, 36"} +{"epoch_s": 1790772673.5491986, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 54141020, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 2, 59.82, 36"} +{"epoch_s": 1790772674.584606, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 46827008, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 0, 58.26, 36"} +{"epoch_s": 1790772675.6100278, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 39487436, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 0, 57.70, 36"} +{"epoch_s": 1790772676.6331685, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 32761416, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 0, 57.36, 36"} +{"epoch_s": 1790772677.6556065, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 24833136, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 0, 57.03, 36"} +{"epoch_s": 1790772679.1176229, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 20348260, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6893, 32607, 0, 57.33, 36"} +{"epoch_s": 1790772680.1513186, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19836220, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 58.46, 36"} +{"epoch_s": 1790772681.18351, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19863628, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 57.35, 36"} +{"epoch_s": 1790772682.2173855, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19918256, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 56.50, 36"} +{"epoch_s": 1790772683.2403264, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19836728, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 57.14, 36"} +{"epoch_s": 1790772684.263194, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19812576, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 57.01, 36"} +{"epoch_s": 1790772685.2866416, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19832496, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 56.75, 36"} +{"epoch_s": 1790772686.3135202, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19950804, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8387324}, "gpu": "6941, 32607, 0, 56.74, 36"} +{"epoch_s": 1790772687.3367112, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19874724, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8386812}, "gpu": "6941, 32607, 0, 56.90, 36"} +{"epoch_s": 1790772688.3587284, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19842500, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8386556}, "gpu": "6941, 32607, 0, 57.05, 36"} +{"epoch_s": 1790772689.3818972, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19944936, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8384252}, "gpu": "6941, 32607, 0, 57.04, 36"} +{"epoch_s": 1790772690.406354, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19871504, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8379900}, "gpu": "6941, 32607, 0, 56.74, 36"} +{"epoch_s": 1790772691.4390683, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19883588, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8376316}, "gpu": "6941, 32607, 0, 31.70, 35"} +{"epoch_s": 1790772692.470097, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19895676, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8372220}, "gpu": "6941, 32607, 0, 20.18, 35"} +{"epoch_s": 1790772693.5028179, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 20038008, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8203772}, "gpu": "6941, 32607, 0, 11.67, 35"} +{"epoch_s": 1790772694.5281374, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 20156748, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31267, 32607, 33, 28.99, 35"} +{"epoch_s": 1790772695.5503595, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19302012, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31351, 32607, 1, 96.33, 36"} +{"epoch_s": 1790772696.5729709, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18691716, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31699, 32607, 1, 88.24, 36"} +{"epoch_s": 1790772697.5949724, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18600496, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31699, 32607, 0, 83.40, 36"} +{"epoch_s": 1790772698.6135545, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18594848, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31699, 32607, 0, 56.88, 36"} +{"epoch_s": 1790772699.6351354, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18384636, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31729, 32607, 38, 71.98, 36"} +{"epoch_s": 1790772700.6604307, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18135500, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31769, 32607, 99, 227.76, 45"} +{"epoch_s": 1790772701.682456, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18126208, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 95, 359.78, 43"} +{"epoch_s": 1790772702.706684, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18118008, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 2, 244.34, 38"} +{"epoch_s": 1790772703.7335, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18095652, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 98, 409.97, 43"} +{"epoch_s": 1790772704.7526512, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18096236, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 97, 346.22, 45"} +{"epoch_s": 1790772705.7763088, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18088644, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 99, 290.87, 48"} +{"epoch_s": 1790772706.799191, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18089132, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 100, 370.80, 45"} +{"epoch_s": 1790772707.8183546, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18072284, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 97, 348.14, 45"} +{"epoch_s": 1790772708.8408382, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18071772, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 99, 204.77, 49"} +{"epoch_s": 1790772709.8652713, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18084484, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 99, 502.69, 49"} +{"epoch_s": 1790772710.8869991, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18091232, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 99, 477.46, 52"} +{"epoch_s": 1790772711.9077418, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18051376, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 100, 453.75, 50"} +{"epoch_s": 1790772712.945486, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18059000, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 98, 483.63, 48"} +{"epoch_s": 1790772713.9662626, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18068208, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 99, 482.43, 53"} +{"epoch_s": 1790772714.9933336, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17987384, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 93, 346.04, 47"} +{"epoch_s": 1790772716.0165942, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17960560, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 96, 347.16, 48"} +{"epoch_s": 1790772717.039366, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18132960, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 211.30, 51"} +{"epoch_s": 1790772718.0643644, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18138544, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 508.40, 53"} +{"epoch_s": 1790772719.0876768, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18147832, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 475.77, 55"} +{"epoch_s": 1790772720.1091926, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18103444, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 457.60, 53"} +{"epoch_s": 1790772721.1299815, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18100992, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 507.29, 54"} +{"epoch_s": 1790772722.1500635, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18112212, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 476.48, 52"} +{"epoch_s": 1790772723.1765406, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18011920, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 97, 382.48, 50"} +{"epoch_s": 1790772724.1962311, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18017628, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 274.45, 45"} +{"epoch_s": 1790772725.21881, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18114148, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 365.93, 54"} +{"epoch_s": 1790772726.2438593, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18128360, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 479.71, 54"} +{"epoch_s": 1790772727.2632627, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18143844, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 510.50, 56"} +{"epoch_s": 1790772728.2869742, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18150700, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 459.35, 56"} +{"epoch_s": 1790772729.3204784, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18162336, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 480.67, 58"} +{"epoch_s": 1790772730.3480747, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18062716, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 98, 494.31, 53"} +{"epoch_s": 1790772731.3745997, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18056756, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 94, 311.79, 52"} +{"epoch_s": 1790772732.3941443, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18080332, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 272.26, 47"} +{"epoch_s": 1790772733.4142647, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18087264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 134.10, 46"} +{"epoch_s": 1790772734.4370096, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18208276, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 222.96, 54"} +{"epoch_s": 1790772735.4588313, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18211508, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 513.78, 58"} +{"epoch_s": 1790772736.4805841, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18202380, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 513.06, 58"} +{"epoch_s": 1790772737.503986, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18205432, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 494.72, 57"} +{"epoch_s": 1790772738.5267396, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18196648, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 514.25, 59"} +{"epoch_s": 1790772739.5491192, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18054812, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 496.71, 60"} +{"epoch_s": 1790772740.5723188, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18048512, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 515.80, 58"} +{"epoch_s": 1790772741.5950322, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17928312, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 513.71, 58"} +{"epoch_s": 1790772742.6171873, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17944052, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 496.11, 60"} +{"epoch_s": 1790772743.639043, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17940264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 513.91, 60"} +{"epoch_s": 1790772744.6600034, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17833128, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 52, 496.12, 54"} +{"epoch_s": 1790772745.6818032, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17835068, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 497.48, 61"} +{"epoch_s": 1790772746.7033856, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17830900, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 516.30, 62"} +{"epoch_s": 1790772747.7276258, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17715960, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 496.96, 61"} +{"epoch_s": 1790772748.7482834, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17719684, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 513.01, 60"} +{"epoch_s": 1790772749.7694225, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17610640, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 507.09, 59"} +{"epoch_s": 1790772750.7923675, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17603368, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 485.92, 60"} +{"epoch_s": 1790772751.812411, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17595640, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 479.74, 64"} +{"epoch_s": 1790772752.8319893, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17586396, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 515.18, 63"} +{"epoch_s": 1790772753.8533502, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17622816, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 458.79, 63"} +{"epoch_s": 1790772754.8752813, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17623492, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 479.38, 61"} +{"epoch_s": 1790772755.9013746, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17629392, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 49, 450.65, 56"} +{"epoch_s": 1790772756.922106, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17626016, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 308.26, 58"} +{"epoch_s": 1790772757.9418297, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17607068, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 295.22, 53"} +{"epoch_s": 1790772758.9605587, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17603144, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 130.95, 52"} +{"epoch_s": 1790772759.9839687, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18282120, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 210.90, 61"} +{"epoch_s": 1790772761.006678, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18282984, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 515.74, 62"} +{"epoch_s": 1790772762.0434818, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18162840, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 520.51, 62"} +{"epoch_s": 1790772763.067759, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18150136, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 501.61, 62"} +{"epoch_s": 1790772764.089317, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18166848, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 520.68, 64"} +{"epoch_s": 1790772765.1115272, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18031696, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 500.77, 64"} +{"epoch_s": 1790772766.1324067, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18034652, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 521.99, 64"} +{"epoch_s": 1790772767.1545649, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17937296, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 521.65, 66"} +{"epoch_s": 1790772768.176144, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17929464, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 501.06, 64"} +{"epoch_s": 1790772769.198718, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17920788, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 520.32, 65"} +{"epoch_s": 1790772770.236203, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17799416, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 497.43, 64"} +{"epoch_s": 1790772771.257868, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17792564, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 523.67, 66"} +{"epoch_s": 1790772772.2799609, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17801924, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 520.28, 67"} +{"epoch_s": 1790772773.3021274, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17687256, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 498.60, 66"} +{"epoch_s": 1790772774.335996, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17678064, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 521.94, 66"} +{"epoch_s": 1790772775.35813, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17557356, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 521.58, 67"} +{"epoch_s": 1790772776.3823485, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17565428, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 489.46, 66"} +{"epoch_s": 1790772777.405725, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17569088, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 487.07, 68"} +{"epoch_s": 1790772778.4254801, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17570184, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 520.51, 66"} +{"epoch_s": 1790772779.4490557, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17625120, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 470.02, 67"} +{"epoch_s": 1790772780.473841, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17616188, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 487.32, 64"} +{"epoch_s": 1790772781.499789, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17505864, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 488.28, 67"} +{"epoch_s": 1790772782.523191, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17517408, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 328.98, 62"} +{"epoch_s": 1790772783.5435653, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17539636, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 303.74, 57"} +{"epoch_s": 1790772784.565325, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17527416, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 136.73, 56"} +{"epoch_s": 1790772785.5888178, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18242896, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 217.75, 64"} +{"epoch_s": 1790772786.612396, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18244028, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 524.56, 66"} +{"epoch_s": 1790772787.6342883, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18194804, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 526.80, 66"} +{"epoch_s": 1790772788.6568644, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18203332, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 507.39, 67"} +{"epoch_s": 1790772789.6793633, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18191904, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 521.05, 67"} +{"epoch_s": 1790772790.7027128, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18079592, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 503.11, 67"} +{"epoch_s": 1790772791.7242851, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18083776, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 527.45, 67"} +{"epoch_s": 1790772792.7456532, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17980956, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 505.96, 67"} +{"epoch_s": 1790772793.768554, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17984860, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 521.32, 68"} +{"epoch_s": 1790772794.7907064, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17972956, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 527.85, 66"} +{"epoch_s": 1790772795.8138406, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17850288, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 505.34, 68"} +{"epoch_s": 1790772796.8353448, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17848116, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 527.36, 69"} +{"epoch_s": 1790772797.8563817, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17846184, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 526.18, 69"} +{"epoch_s": 1790772798.8780813, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17723912, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 503.19, 68"} +{"epoch_s": 1790772799.899205, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17715168, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 523.83, 69"} +{"epoch_s": 1790772800.9237013, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17593528, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 526.99, 70"} +{"epoch_s": 1790772801.9461932, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17589112, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 492.53, 69"} +{"epoch_s": 1790772802.9673676, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17602032, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 497.32, 69"} +{"epoch_s": 1790772803.9868026, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17581748, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 524.68, 70"} +{"epoch_s": 1790772805.006854, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17479100, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 467.85, 71"} +{"epoch_s": 1790772806.027366, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17469612, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 494.48, 66"} +{"epoch_s": 1790772807.054402, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17465264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 508.83, 66"} +{"epoch_s": 1790772808.0764651, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17451560, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 341.96, 65"} +{"epoch_s": 1790772809.0972805, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18242708, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 326.58, 60"} +{"epoch_s": 1790772810.1193252, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18224312, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 231.55, 67"} +{"epoch_s": 1790772811.1443434, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18251360, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 513.76, 65"} +{"epoch_s": 1790772812.1641836, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18257168, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 507.31, 68"} +{"epoch_s": 1790772813.188216, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18264160, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 475.36, 68"} +{"epoch_s": 1790772814.2106729, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18280248, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 491.24, 70"} +{"epoch_s": 1790772815.2351635, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18226696, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 43, 408.46, 65"} +{"epoch_s": 1790772816.2571764, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18232216, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 516.37, 70"} +{"epoch_s": 1790772817.2793994, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18237844, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 492.67, 71"} +{"epoch_s": 1790772818.3027427, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18258420, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 85, 480.93, 69"} +{"epoch_s": 1790772819.3249714, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18262736, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 520.06, 70"} +{"epoch_s": 1790772820.3447847, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18263392, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 495.94, 70"} +{"epoch_s": 1790772821.3689287, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18252008, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 387.84, 70"} +{"epoch_s": 1790772822.391625, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18251760, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.36, 70"} +{"epoch_s": 1790772823.4142845, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18246696, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 499.02, 69"} +{"epoch_s": 1790772824.4363837, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18255784, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 474.00, 72"} +{"epoch_s": 1790772825.4570014, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18249508, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 534.05, 68"} +{"epoch_s": 1790772826.4777033, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18265224, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 488.60, 68"} +{"epoch_s": 1790772827.5001867, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18241316, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 338.84, 69"} +{"epoch_s": 1790772828.5244417, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18234208, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 529.48, 69"} +{"epoch_s": 1790772829.5457335, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18255808, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 532.12, 72"} +{"epoch_s": 1790772830.5685184, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18259268, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 507.47, 71"} +{"epoch_s": 1790772831.5907855, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18256224, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 532.53, 71"} +{"epoch_s": 1790772832.613174, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18178900, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.43, 64"} +{"epoch_s": 1790772833.6395922, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18163872, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 510.42, 72"} +{"epoch_s": 1790772834.660667, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18164500, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 529.48, 72"} +{"epoch_s": 1790772835.682373, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18067600, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 514.49, 71"} +{"epoch_s": 1790772836.7051973, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18067096, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.68, 71"} +{"epoch_s": 1790772837.7258525, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17941220, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 52, 511.56, 71"} +{"epoch_s": 1790772838.747495, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17946888, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 532.64, 72"} +{"epoch_s": 1790772839.7696228, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17948264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 529.32, 72"} +{"epoch_s": 1790772840.7897382, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17841772, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 513.67, 71"} +{"epoch_s": 1790772841.811278, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17838756, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 528.76, 72"} +{"epoch_s": 1790772842.8329659, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17838812, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.90, 71"} +{"epoch_s": 1790772843.8551986, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17717288, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 490.94, 72"} +{"epoch_s": 1790772844.8746738, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17722396, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 528.11, 71"} +{"epoch_s": 1790772845.8973172, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17723676, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 493.89, 72"} +{"epoch_s": 1790772846.91816, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17609420, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 85, 479.12, 71"} +{"epoch_s": 1790772847.939702, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17606604, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 528.62, 70"} +{"epoch_s": 1790772848.9587715, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17605816, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 482.68, 71"} +{"epoch_s": 1790772849.9811416, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18225312, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 2, 287.55, 62"} +{"epoch_s": 1790772851.0086215, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18219312, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 495.29, 70"} +{"epoch_s": 1790772852.0307431, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18212012, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 532.53, 73"} +{"epoch_s": 1790772853.0534828, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18241908, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 513.63, 71"} +{"epoch_s": 1790772854.0752146, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18240392, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 534.22, 71"} +{"epoch_s": 1790772855.0970914, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18192424, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 531.69, 73"} +{"epoch_s": 1790772856.119393, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18176072, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 511.80, 72"} +{"epoch_s": 1790772857.1404707, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18174816, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 531.85, 73"} +{"epoch_s": 1790772858.1629918, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18066588, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 52, 512.33, 71"} +{"epoch_s": 1790772859.1853132, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18066664, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 512.57, 72"} +{"epoch_s": 1790772860.206362, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18066844, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 532.25, 71"} +{"epoch_s": 1790772861.2286925, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17941852, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 511.81, 74"} +{"epoch_s": 1790772862.2505696, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17961916, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.91, 72"} +{"epoch_s": 1790772863.2736192, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17842052, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 52, 515.36, 72"} +{"epoch_s": 1790772864.2948847, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17837396, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.06, 72"} +{"epoch_s": 1790772865.315923, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17838760, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.20, 71"} +{"epoch_s": 1790772866.3383734, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17722852, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 77, 489.91, 74"} +{"epoch_s": 1790772867.3589919, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17723784, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.00, 72"} +{"epoch_s": 1790772868.3802085, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17724116, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 492.00, 72"} +{"epoch_s": 1790772869.4032836, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17610436, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 519.67, 68"} +{"epoch_s": 1790772870.4251704, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17593928, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 482.79, 71"} +{"epoch_s": 1790772871.446933, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17625500, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 490.11, 71"} +{"epoch_s": 1790772872.4693067, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18115856, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 42, 376.82, 63"} +{"epoch_s": 1790772873.4927008, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18130848, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 413.33, 71"} +{"epoch_s": 1790772874.517678, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18129660, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.46, 71"} +{"epoch_s": 1790772875.539969, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18122464, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 96, 513.83, 71"} +{"epoch_s": 1790772876.5611775, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18124472, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 525.10, 73"} +{"epoch_s": 1790772877.5850198, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18126548, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 533.66, 72"} +{"epoch_s": 1790772878.6076293, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18073280, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 511.73, 72"} +{"epoch_s": 1790772879.629884, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18098184, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 535.61, 74"} +{"epoch_s": 1790772880.6510599, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17972812, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.98, 73"} +{"epoch_s": 1790772881.675439, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17976576, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 507.68, 72"} +{"epoch_s": 1790772882.699754, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17973148, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 533.44, 72"} +{"epoch_s": 1790772883.722258, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17861120, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 508.82, 72"} +{"epoch_s": 1790772884.745278, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17864404, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 531.88, 72"} +{"epoch_s": 1790772885.769315, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17866576, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.83, 74"} +{"epoch_s": 1790772886.7924066, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17752540, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 488.78, 72"} +{"epoch_s": 1790772887.817747, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17751168, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 527.99, 69"} +{"epoch_s": 1790772888.8397095, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17735964, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 496.67, 72"} +{"epoch_s": 1790772889.8620257, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17625844, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 470.64, 71"} +{"epoch_s": 1790772890.884023, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17629264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 528.82, 72"} +{"epoch_s": 1790772891.9039407, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17631268, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 475.71, 71"} +{"epoch_s": 1790772892.925761, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17658484, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 242.06, 62"} +{"epoch_s": 1790772893.947652, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17660788, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 124.52, 62"} +{"epoch_s": 1790772894.9685812, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17662644, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 94.57, 60"} +{"epoch_s": 1790772895.9877603, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17666884, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 70.56, 59"} +{"epoch_s": 1790772897.009143, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17675152, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 69.94, 59"} +{"epoch_s": 1790772898.0305054, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17677208, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 69.68, 58"} +{"epoch_s": 1790772899.0518734, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17686920, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 69.10, 58"} +{"epoch_s": 1790772900.0737712, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17694368, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 68.64, 57"} +{"epoch_s": 1790772901.0949237, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17701040, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 68.54, 57"} +{"epoch_s": 1790772902.1162262, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17704052, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 68.07, 56"} +{"epoch_s": 1790772903.1371994, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17716036, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 67.54, 56"} +{"epoch_s": 1790772904.1573613, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17729424, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 66.79, 56"} +{"epoch_s": 1790772905.178784, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17734376, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 66.78, 55"} +{"epoch_s": 1790772906.2002432, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17741828, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 66.73, 55"} +{"epoch_s": 1790772907.2226708, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17744104, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 66.62, 54"} +{"epoch_s": 1790772908.2435381, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17741708, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 65.50, 54"} +{"epoch_s": 1790772909.2710078, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17724256, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 40.74, 53"} +{"epoch_s": 1790772910.2964864, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17746392, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 31.75, 53"} +{"epoch_s": 1790772911.3218958, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17745548, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 19.67, 53"} +{"epoch_s": 1790772912.3480182, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17746012, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.41, 52"} +{"epoch_s": 1790772913.3754818, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17733056, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.42, 52"} +{"epoch_s": 1790772914.402011, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17739736, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.55, 52"} +{"epoch_s": 1790772915.4289236, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17733576, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.24, 51"} +{"epoch_s": 1790772916.4575953, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17753656, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.35, 51"} +{"epoch_s": 1790772917.4829435, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17752892, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.47, 51"} +{"epoch_s": 1790772918.5089724, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17753536, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 12.31, 51"} +{"epoch_s": 1790772919.5349586, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17755604, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 12.49, 51"} +{"epoch_s": 1790772920.5655951, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17766328, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.14, 50"} +{"epoch_s": 1790772921.5931342, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17743004, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.21, 50"} +{"epoch_s": 1790772922.637384, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 20934704, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "30128, 32607, 4, 16.71, 50"} +{"epoch_s": 1790772924.2924495, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 37200652, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "2, 32607, 0, 60.26, 50"} diff --git a/bench/results/2026-09-30-tc-gemv-sm75/README.md b/bench/results/2026-09-30-tc-gemv-sm75/README.md new file mode 100644 index 0000000..8eaf902 --- /dev/null +++ b/bench/results/2026-09-30-tc-gemv-sm75/README.md @@ -0,0 +1,57 @@ +# BF16 GEMV on Turing tensor cores (sm_75): measured negative + +i7-8700K + RTX 2070 8 GB (sm_75, 36 SMs), engine 0.1.27 tree (`bf16_gemv.cu` is unchanged through 0.1.30), +qwen3.8-flash-next (~125.7B MoE, GGUF-verified) Q2_0 in production. Isolated benchmark only - +[`bench_tc_gemv.cu`](bench_tc_gemv.cu) touches nothing in the inference path. Question: the QSA prompt attention +already rides the Turing tensor cores (`mma.sync.m16n8k8`, the #270 path); can the decode GEMVs do the same? + +## Setup + +- Baseline: the production `bf16_gemv` warp kernel, transcribed verbatim +- TC variant: `mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32` on BF16->FP16 (the sm_75 MMA has native f16 only). + BF16->FP16 conversion is exact (0 / 2,000,000 values inexact - bf16's 7-bit mantissa fits in fp16's 10 bits); the + A-fragment packing is the same one #270 validated (`a0` = row `gid`, k columns `2t..2t+1`; broadcast makes + `a0 == a1 == {x[2t], x[2t+1]}`) +- Three TC variants to cover the conversion overhead from every angle: W preconverted to fp16 once at load + (`pc`), W converted in-register every call (`in`), and a fused ks=1 form that writes the output directly and skips + the reduce kernel (`fused`) +- The k-split across blocks (`ks`) is swept over all values that divide n_in, and the best is reported - the TC + kernel gets its best occupancy +- Parity against an fp64 host reference; 2000 iterations x 3 reps, warmed CUDA events + +## Results (best TC config per shape) + +| Shape (decode, n_in = 2560, BF16 W) | Baseline us | Best TC us | Speedup | Config | +| --- | ---: | ---: | ---: | --- | +| ssm_alpha/beta [2560, 48] | 8.73 | 11.32 | 0.77x | pc, ks=16 | +| indexer.k_proj [2560, 128] | 7.14 | 12.09 | 0.59x | pc, ks=16 | +| indexer.q_proj / router [2560, 512] | 9.48 | 15.78 | 0.60x | pc, ks=4 | +| ple_value [2560, 2560] | 35.08 | 77.73 | 0.45x | pc, ks=40 | + +- Numerics pass: TC max error vs fp64 reference 1.7e-6 .. 7.2e-6 (fp16-accumulation level), baseline + 0.7e-6 .. 2.3e-6. The TC variant computes the same thing, it is just slower. +- The warp kernel is already bandwidth-bound at 276-374 GB/s effective W bandwidth (374 GB/s on the 13 MB + [2560, 2560] shape); the TC path reaches only 166-169 GB/s (4-byte lane loads, conversion instructions, in-tile + launch overhead). +- A single-token GEMV broadcasts one token across the whole m16 MMA tile, so 15/16 of the MMA throughput is thrown + away - but the baseline is not compute-bound, so the wasted throughput buys nothing. The k-split sweep and the + fused variant do not recover it. +- One-time W conversion cost is negligible (2 ms for 13 MB), so preconverting W for the TC path does not help. + +## How to rerun + +``` +nvcc -arch=sm_75 -O3 -o bench_tc_gemv.exe bench_tc_gemv.cu +./bench_tc_gemv.exe +``` + +Prints the table above, per-shape latency/parity and the conversion exactness scan. On a newer card, adjust +`-arch`; the packed-A layout comment in the source documents the fragment mapping it relies on. + +## Conclusion + +**Keep the warp kernel. Tensor cores are not a promising direction for the decode GEMVs on sm_75**, and this was a +measured loss (1.3-2.2x slower), not a failed attempt to optimize. The Turing MMA stays worthwhile where the input +really has m16 rows of work: the QSA prompt-attention tiles, which is where #270 uses it. Someone looking to +re-evaluate on future hardware (a card with native bf16 or denser GEMV batching) can rerun this instead of +rebuilding it. \ No newline at end of file diff --git a/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu b/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu new file mode 100644 index 0000000..bead5e3 --- /dev/null +++ b/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu @@ -0,0 +1,305 @@ +// bench_tc_gemv.cu - ISOLATED benchmark: BF16 GEMV baseline vs Tensor Core (mma.m16n8k8, BF16->FP16) on sm_75. +// Nothing in the engine changes. Shapes are the REAL Strata decode GEMVs (BF16 weights, n_in = n_embd = 2560): +// ssm_alpha / ssm_beta [2560, 48] project_bf16(split=true) -> bf16_gemv_split(TPR=32) -> warp kernel +// indexer.k_proj [2560, 128] project_bf16(split=false) -> bf16_gemv -> warp kernel +// indexer.q_proj / ffn_gate_inp / mlp.gate [2560, 512] warp / split(TPR=32) -> warp kernel +// ple_value [2560, 2560] warp +// Baseline = bf16_gemv_warp_kernel transcribed verbatim from src/kernels/cuda/bf16_gemv.cu (production). +// TC variant = same maths; A = x broadcast down m16 (single-token GEMV), k-chunk = 8; +// (a) W preconverted bf16->fp16 once, x converted in-kernel (timed) [tc_preconv] +// (b) fully inline: W read as bf16 and converted in-register [tc_inline] +// Numerics: fp64 host reference; max abs err for baseline and both TC variants; bf16->fp16 exactness scan. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(e) do { cudaError_t err_ = (e); if (err_ != cudaSuccess) { \ + fprintf(stderr, "CUDA %s:%d %s\n", __FILE__, __LINE__, cudaGetErrorString(err_)); exit(1); } } while (0) + +__device__ __forceinline__ float bf16_f32(uint16_t v) { return __int_as_float((int) ((unsigned) v << 16)); } +static float bf16_f32_host(uint16_t v) { unsigned u = (unsigned) v << 16; float f; memcpy(&f, &u, 4); return f; } +static uint16_t f32_bf16_host(float f) { + unsigned u, r; memcpy(&u, &f, 4); + r = ((u >> 16) ^ (u >> 15)) & 1; u += 0x7fff + r; + return (uint16_t) (u >> 16); +} + +// ============ baseline: production warp kernel (verbatim semantics from bf16_gemv.cu) ============ +__global__ void gemv_warp(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 >> 5) + (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 += bf16_f32(x[i]) * bf16_f32(row[i]); + for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); + if (lane == 0) y[o] = acc; +} + +// ============ TC: A(x) broadcast, k-split over blocks, partial D row 0 -> scratch ============ +// A fragment (m16n8k8, .f16): lane l: a0 = A[m=l>>2][k=2(l&3)], a1 = A[m][k=2(l&3)+1], +// a2/a3 = same cols at row m+8. Broadcast => a2=a0, a3=a1. +// B fragment (.f16, col-major): lane l: b0 = B[k=2(l&3)][n=(l>>2)], b1 = B[k=2(l&3)+1][n]. +// B[k][n] = W[n][k], so lane l loads W[n][2(l&3)], W[n][2(l&3)+1] - coalesced within the row. +// D fragment: c0/c1 = D[m=l>>2][cols 2(l&3), +1], c2/c3 = row m+8. All m rows identical -> row 0. +__global__ void tc_preconv(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_f, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + // A (2 x f16x2): a0 = {A[m][2t], A[m+8][2t]}, a1 = {A[m][2t+1], A[m+8][2t+1]} (broadcast -> dup halves) + unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16); + // fp16 conversion in-register: bf16 -> f32 -> f16 (exact within fp16 range) + __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + // B is already fp16 here: load as __half2 directly (bf16 path must NOT convert twice) + __half2 wbh = *reinterpret_cast(&w_f[(n_base + (lane >> 2)) * n_in + kk0 + t2]); + unsigned b0 = *reinterpret_cast(&wbh); + 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"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +// same, but W stays bf16 and converts in-register (fully fair per-call cost) +__global__ void tc_inline(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16); + __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + 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"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +__global__ void tc_reduce(const float* __restrict__ partials, float* __restrict__ y, long long n_out, int ks) { + const long long o = blockIdx.x * blockDim.x + threadIdx.x; + if (o >= n_out) return; + float s = 0.f; + for (int q = 0; q < ks; ++q) s += partials[(size_t) ((o >> 3) * ks + q) * 8 + (o & 7)]; + y[o] = s; +} + +// variant with the OTHER candidate A layout: a0 = {A[gid][2t], A[gid+8][2t]} (same k-col, two rows), +// a1 = same for col 2t+1. Broadcast => both halves of a0 hold x[2t], both halves of a1 hold x[2t+1]. +__global__ void tc_dupcol(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2])); + __half2 hb = __floats2half2_rn(bf16_f32(x_b[kk0 + t2 + 1]), bf16_f32(x_b[kk0 + t2 + 1])); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + 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"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +// FUSED, ks=1 only: with a single k-fragment the partial IS the answer -> write y directly, no reduce kernel, +// no scratch. Fully inline bf16 W conversion (fairest per-call TC cost). +__global__ void tc_fused(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ y, long long n_in, long long n_out) { + const int tile = blockIdx.x, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = 0; kk0 < n_in; kk0 += 8) { + __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2 + 1])); + __half2 hb = ha; // broadcast: row gid+8 = row gid (single-token GEMV) + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + 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"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { y[n_base + t2] = c0; y[n_base + t2 + 1] = c1; } +} + +int main() { + CHECK(cudaSetDevice(0)); + cudaDeviceProp prop; CHECK(cudaGetDeviceProperties(&prop, 0)); + printf("device: %s, SMs %d, capability %d.%d\n", prop.name, prop.multiProcessorCount, prop.major, prop.minor); + + struct Shape { const char* name; long long n_in, n_out; }; + Shape shapes[] = { + {"ssm_alpha/beta [2560,48]", 2560, 48}, + {"indexer.k_proj [2560,128]", 2560, 128}, + {"q_proj/router [2560,512]", 2560, 512}, + {"ple_value [2560,2560]", 2560, 2560}, + }; + auto rng = [](unsigned& s) { s = s * 1664525u + 1013904223u; return (float) ((s >> 8) & 0xFFFF) / 65535.0f - 0.5f; }; + const int ITERS = 2000, WARM = 300; + + printf("\n%-26s %13s | %s\n", "shape", "baseline us", "tc variants (pc = W preconverted, in = inline conversion, fused = no reduce), speedup vs baseline"); + printf("%s\n", std::string(150, '-').c_str()); + + for (auto& sh : shapes) { + const long long n_in = sh.n_in, n_out = sh.n_out; + const size_t wn = (size_t) n_out * n_in; + std::vector hw(wn), hx(n_in), hf(wn); + std::vector hyb(n_out), hypc(n_out), hyin(n_out), hyfu(n_out); + std::vector href(n_out); + unsigned seed = 991u + (unsigned) (n_out & 0xFFF); + for (size_t i = 0; i < wn; ++i) hw[i] = f32_bf16_host(rng(seed) * 0.3f); + for (long long i = 0; i < n_in; ++i) hx[i] = f32_bf16_host(rng(seed) * 3.0f); + for (long long o = 0; o < n_out; ++o) { + double s = 0.0; + for (long long i = 0; i < n_in; ++i) s += (double) bf16_f32_host(hx[i]) * (double) bf16_f32_host(hw[(size_t) o * n_in + i]); + href[o] = s; + } + // preconvert W to fp16 (bf16 -> fp16 is exact within fp16 range) + for (size_t i = 0; i < wn; ++i) { __half h = __float2half_rn(bf16_f32_host(hw[i])); memcpy(&hf[i], &h, 2); } + + uint16_t *dx, *dw, *dwf; float *dy, *dyp; + CHECK(cudaMalloc(&dx, n_in * 2)); + CHECK(cudaMalloc(&dw, wn * 2)); CHECK(cudaMalloc(&dwf, wn * 2)); + CHECK(cudaMalloc(&dy, n_out * 4)); + CHECK(cudaMalloc(&dyp, (size_t)(n_out / 8) * 65 * 8 * 4)); + CHECK(cudaMemcpy(dx, hx.data(), n_in * 2, cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(dw, hw.data(), wn * 2, cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice)); + + // one-time W conversion cost (host->device, reported separately; the engine would fold this + // into the weight load exactly like Gemm::bf16 does for sm<80) + { + cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1)); + CHECK(cudaEventRecord(e0)); + CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice)); + CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1)); + float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1)); + printf("%-26s one-time W convert: %.2f ms (%.1f MB), tiles=%lld\n", sh.name, ms, wn * 2 / 1e6, n_out / 8); + } + + int tiles = (int) (n_out / 8); + // valid ks must divide n_in so each k-chunk is a multiple of 8; sweep ALL of them, report the best + const int cands[11] = {1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64}; + + auto timeit = [&](const char* tag, const std::function& fn) -> double { + for (int i = 0; i < WARM; ++i) fn(); + CHECK(cudaDeviceSynchronize()); + double best = 1e30; + for (int rep = 0; rep < 3; ++rep) { + cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1)); + CHECK(cudaEventRecord(e0)); + for (int i = 0; i < ITERS; ++i) fn(); + CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1)); + float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1)); + double us = ms * 1000.0 / ITERS; + if (us < best) best = us; + } + (void) tag; return best; + }; + + double t_base = timeit("base", [&]{ gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out); }); + gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out); + CHECK(cudaMemcpy(hyb.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + // occupancy sweep over k-chunk count for the preconverted-W TC kernel + int best_ks = 1; double t_pc = 1e30; + for (int i = 0; i < 11; ++i) { + const int ksv = cands[i]; + if (n_in % ksv != 0) continue; + dim3 g((unsigned) tiles, (unsigned) ksv); + double t = timeit("pcs", [&]{ tc_preconv<<>>(dx, dwf, dyp, n_in, n_out, ksv); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, ksv); }); + if (t < t_pc) { t_pc = t; best_ks = ksv; } + } + dim3 gtc((unsigned) tiles, (unsigned) best_ks); + tc_preconv<<>>(dx, dwf, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); + CHECK(cudaMemcpy(hypc.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double t_ti = timeit("tci", [&]{ tc_inline<<>>(dx, dw, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); }); + tc_inline<<>>(dx, dw, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); + CHECK(cudaMemcpy(hyin.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double t_fu = timeit("tcf", [&]{ tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out); }); + tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out); + CHECK(cudaMemcpy(hyfu.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double best_tc = t_pc; const char* best_var = "preconv"; + if (t_ti < best_tc) { best_tc = t_ti; best_var = "inline"; } + if (t_fu < best_tc) { best_tc = t_fu; best_var = "fused"; } + + double e_tc = 0, e_base = 0, sc = 0; + if (strcmp(best_var, "preconv") == 0) { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hypc[o] - href[o])); } + } else if (strcmp(best_var, "inline") == 0) { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyin[o] - href[o])); } + } else { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyfu[o] - href[o])); } + } + for (long long o = 0; o < n_out; ++o) { + e_base = std::max(e_base, std::fabs((double) hyb[o] - href[o])); + sc = std::max(sc, std::fabs(href[o])); + } + double gb_base = (double) (wn * 2) / t_base / 1e3; + double gb_tc = (double) (wn * 2) / best_tc / 1e3; + printf("%-26s %13.3f | pc %13.3f (ks=%d) | in %13.3f | fused %13.3f | BEST %s %7.3fx | maxerr tc %.2e base %.2e (scale %.1f, BW base %.0f tc %.0f GB/s)\n", + sh.name, t_base, t_pc, best_ks, t_ti, t_fu, best_var, t_base / best_tc, + e_tc, e_base, sc, gb_base, gb_tc); + + CHECK(cudaFree(dx)); CHECK(cudaFree(dw)); CHECK(cudaFree(dwf)); CHECK(cudaFree(dy)); CHECK(cudaFree(dyp)); + } + + { // bf16 -> fp16 exactness scan + unsigned seed = 777u; double worst = 0; int bad = 0, n = 2000000; + for (int i = 0; i < n; ++i) { + float f = (rng(seed) * 2.0f - 1.0f) * 100.0f; + uint16_t b = f32_bf16_host(f); + __half h = __float2half_rn(bf16_f32_host(b)); + if ((double) __half2float(h) != (double) bf16_f32_host(b)) { + bad++; worst = std::max(worst, std::fabs((double) __half2float(h) - (double) bf16_f32_host(b))); + } + } + printf("\nbf16->fp16 conversion exactness: %d / %d inexact, worst %.3g\n", bad, n, worst); + } + printf("BENCH_DONE\n"); + return 0; +} diff --git a/bench/results/2026-10-03-community-2x-mi50/README.md b/bench/results/2026-10-03-community-2x-mi50/README.md new file mode 100644 index 0000000..8d0301f --- /dev/null +++ b/bench/results/2026-10-03-community-2x-mi50/README.md @@ -0,0 +1,121 @@ +# Community benchmark: 2x AMD Instinct MI50 16 GB (gfx906), Xeon E5-2666 v3 + +Measured on 2026-10-03 by [JeanP00l](https://github.com/JeanP00l) on a Linux server. This tests the Coder +(IQ1_M) with a 131,072-token context, the layer split across two MI50 cards, and the gfx906 build of #638. That +build is an opt-in HIP build, separate from the wave32 RDNA backend. + +The median decode throughput was **50.1 tok/s at 4,096 prompt tokens, 47.8 tok/s at 32,768 and 45.7 tok/s at +128,000**. Prompts were read at 321, 523 and 517 tok/s. The requests are synthetic code-explanation requests +with greedy decoding and a 256-token output cap. They do not establish general answer quality or performance on +other workloads. + +## Hardware and software + +- **GPUs:** 2x AMD Instinct MI50 16 GB (Vega 20, gfx906, wave64; HIP names them "AMD Radeon VII"). Power limit + 85 W per card, set by the owner (the cards' own limit is higher). PCIe 3.0 x16 on both. Peer access between them + works, through the CPU's root complex (no direct bridge). Blower fans; no clock locking beyond the power limit. + The engine's PCIe probe measured 13.8 GB/s host to device. +- **CPU and RAM:** Intel Xeon E5-2666 v3 (10 cores, 20 threads, AVX2, no AVX-512); the engine used 9 expert-pool + workers plus its host thread. 32 GB DDR4 quad-channel (Linux reports 31.2 GiB). 8 GiB swap file. One SATA SSD. +- **OS and runtime:** Ubuntu 24.04.4 LTS, kernel 6.8.0-138-generic, the kernel's amdgpu driver. HIP 7.14 from the + community image `mixa3607/rocm-gfx906:7.14-complete` (AMD's current ROCm no longer ships gfx906 libraries). +- **Source:** [`mi50-bench-build`](https://github.com/JeanP00l/Strata/tree/mi50-bench-build) at `ea51fd3`, which is + `main` 99f3dbd (engine 0.1.38) with #638 (at 17beb33), #639, #640 and #637 merged. #638's later commits + (a914b13) only fix the CUDA/RDNA compile and do not change the gfx906 binary's behaviour. +- **Build:** `-DSTRATA_HIP_GFX906=ON -DCMAKE_HIP_ARCHITECTURES=gfx906 -DSTRATA_PORTABLE=ON`, ROCm clang, Ninja, + llama.cpp at the pinned 3cf0325. +- **Other services:** the machine's other GPU services were stopped, so the two cards ran only Strata. CPU services + (a database, a sync daemon) kept running. This was not a fully isolated operating system. + +## Model and configuration + +**Model:** [`ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF`](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF), +IQ1_M. The repository revision was not recorded; the shard SHA-256 hashes matched the `.sha256` files downloaded +with them: + +- `Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf` `e11083ba855e7666b48ea3f2db6a9c3a20c18751a012cc24f948de91b7087fad` +- `Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf` `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113` + +The native pack and the MTP draft layer were prepared with the repository's tools on 2026-09-29. The expert profile is the bundled +`data/expert-profile-coder.bin`. + +**Configuration** ([strata-coder.json](strata-coder.json); `/m` is the model directory, `/work` the build): + +- context 131,072, `--kv int8 --kv-resident 32768` (32,768 KV cells per attention layer in VRAM, the rest streamed + from RAM); +- `layer_split 27`: layers 0-26 on GPU 0, 27-47 on GPU 1. With #639 each GPU loads only its own layers' dense + weights; +- expert cache `auto`, `--vram-reserve-mib 600`: 6,912 + 5,376 slots = **all 12,288 experts in VRAM**, prefilled + from the profile, no eviction; +- `--prefill 4096`, with the prompt path borrowing 1,193 + 1,084 cache slots; +- MTP `--spec 4 --spec-min-p 0.5`; suffix drafting on (the default); +- `--pcie-frac 0`, required with `STRATA_ARENA_MMAP=1` (#640, the expert arena as a read-only mapped file; 23.4 + GiB of VRAM-held experts handed back to the OS at start); +- no vision, no calibration, no speed projection, no control vectors; +- reasoning off (`reasoning_effort: none`), temperature 0, 256 generated tokens per speed run. + +## Method + +[benchmark.py](benchmark.py) is the script of the +[RTX 5090 report](../2026-09-30-community-rtx-5090/README.md), unchanged. It builds deterministic synthetic Python +filler, puts a different nonce near the start of each request, and counts the rendered chat prompt with Strata's +tokenizer. Its request hashes and the output text of every run are in [results.json](results.json); the aggregates +are in [summary.json](summary.json). + +The server ran in a container with both cards (the repository's `serve/` and `tools/` from the source above): + +```bash +docker run --device=/dev/kfd --device=/dev/dri --group-add video --ipc=host --ulimit memlock=-1 \ + -e HSA_OVERRIDE_GFX_VERSION=9.0.6 -e STRATA_ARENA_MMAP=1 ... \ + python3 serve/server.py --engine strata --config strata-coder.json --port 8080 +python3 benchmark.py --root /opt/strata --pack /m/pack-coder --url http://127.0.0.1:8080 --out results/ +python3 tools/needle_bench.py --url http://127.0.0.1:8080 --lengths 32k,128k --depths 10,50,90 --out needles.json +``` + +- One short warm-up request is excluded. +- Three runs at each length ran serially, in increasing-length order, on the same loaded engine. +- All nine speed requests read their whole prompt: **zero reused tokens**. +- The expert cache was filled at start and kept between requests. Loading time is excluded. +- TTFT is streaming, from just before the HTTP request to the first nonempty text delta, over loopback. +- Prompt throughput is freshly read tokens / `prompt_ms`. Decode throughput is `engine_generated / decode_ms`. +- [engine.log](engine.log) is the engine's whole log for this session, including the start-up decisions. + +## Results + +Each cell is the median **[minimum-maximum]** of three runs. Every request generated 256 tokens and stopped at +the output limit. No speed request failed or was cancelled. + +| Prompt tokens | Reused | Prompt tok/s | Decode tok/s | TTFT seconds | Total seconds | +| ---: | ---: | ---: | ---: | ---: | ---: | +| 4,096 | 0 | 320.9 [309.9-324.7] | 50.1 [49.3-54.0] | 12.81 [12.66-13.26] | 17.90 [17.38-18.43] | +| 32,768 | 0 | 522.8 [522.6-523.4] | 47.8 [47.6-48.5] | 62.81 [62.75-62.84] | 68.10 [68.10-68.15] | +| 128,000 | 0 | 516.8 [516.5-516.9] | 45.7 [44.8-51.5] | 248.09 [248.06-248.27] | 253.75 [253.03-253.84] | + +- The decode expert-cache hit rate was 100% for every request. All experts are in VRAM; the CPU pool computes none. +- The 4K prompt reads at about 60% of the longer ones' speed, because a 4,096-token chunk pays the fixed per-chunk + cost once. +- Draft acceptance varies between runs (decode 44.8-51.5 tok/s at 128K) although the text is greedy. + +**Memory**, from [telemetry.jsonl](telemetry.jsonl) (1,699 one-second samples over 1,763 s, from start through +the recall checks): + +- VRAM peak: 15.42 GiB on GPU 0 and 14.70 GiB on GPU 1 (`mem_info_vram_used`, the whole card). +- RAM: `MemAvailable` never below **25.1 GiB** of 31.2. +- Swap: no growth during the run. The swap file held ~1.3 GiB from earlier use before the start. + +These are sampled values; brief peaks between samples can be missed. + +## Recall and limitations + +The repository's unchanged `tools/needle_bench.py` found **all six needles**, at depths 10%, 50% and 90% at both +lengths ([needles.json](needles.json)): + +- `32k` prompts were 25,776-25,777 tokens and `128k` prompts 103,725-103,727 tokens. +- The last 128K case reused 49,785 prompt tokens; the other five reused none. + +**Limits of this report:** +- One machine, one quantization, one configuration, and a small synthetic workload. +- Long output, sampled decoding, thinking, coding-task correctness, vision, tool use, concurrency and a sustained + thermal run were not part of this report. +- For context, on the same machine and model, llama.cpp (3cf0325, ROCm) measured 26.9 tok/s `tg128` on 2026-09-29. + That is a different workload, not a controlled comparison. diff --git a/bench/results/2026-10-03-community-2x-mi50/benchmark.py b/bench/results/2026-10-03-community-2x-mi50/benchmark.py new file mode 100644 index 0000000..cdb6e4c --- /dev/null +++ b/bench/results/2026-10-03-community-2x-mi50/benchmark.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Serial, fresh-prompt Strata benchmark. Run inside its prepared environment.""" +import argparse +import hashlib +import json +import statistics +import sys +import time +import urllib.request +from pathlib import Path + + +def get(url): + with urllib.request.urlopen(url, timeout=30) as response: + return json.load(response) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path("/workspace/Strata")) + parser.add_argument("--pack", type=Path, default=Path("/workspace/Strata-data/packs/iq2_xs")) + parser.add_argument("--url", default="http://127.0.0.1:18080") + parser.add_argument("--out", type=Path, default=Path("/workspace/results")) + parser.add_argument("--targets", default="4096,32768,128000") + parser.add_argument("--runs", type=int, default=3) + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + sys.path[:0] = [str(args.root), str(args.root / "tools")] + from strata_tokenizer import Tokenizer + from serve.frontend import ChatTemplate, openai_to_messages + directory = args.pack / "tokenizer" + vocab = json.loads((directory / "vocab.json").read_text()) + tokens = [None] * len(vocab) + for token, number in vocab.items(): + tokens[number] = token + tokenizer = Tokenizer(tokens, (directory / "merges.txt").read_text().splitlines(), + json.loads((directory / "token_type.json").read_text())) + template = ChatTemplate(directory / "chat_template.jinja") + initial = get(args.url + "/v1/status") + (args.out / "initial-status.json").write_text(json.dumps(initial, indent=2) + "\n") + rows = [] + + def request(content, maximum=256): + return {"model": "strata", "messages": [{"role": "user", "content": content}], + "temperature": 0, "reasoning_effort": "none", "max_tokens": maximum, + "stream": True, "stream_options": {"include_usage": True}} + + def count(req): + messages, tools, kwargs = openai_to_messages(req) + return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True)) + + def perform(label, req, expected=None): + body = json.dumps(req).encode() + (args.out / (label + "-request.json")).write_bytes(body + b"\n") + print("start", label, "tokens", expected, flush=True) + chunks, texts, first, finish = [], [], None, None + started = time.perf_counter() + wire = urllib.request.Request(args.url + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(wire, timeout=1800) as response: + for line in response: + if not line.startswith(b"data: "): + continue + payload = line[6:].strip() + if payload == b"[DONE]": + break + chunk = json.loads(payload) + chunks.append(chunk) + for choice in chunk.get("choices", []): + delta = choice.get("delta", {}) + text = (delta.get("content") or "") + (delta.get("reasoning_content") or "") + if text: + first = first if first is not None else time.perf_counter() - started + texts.append(text) + finish = choice.get("finish_reason") or finish + elapsed = time.perf_counter() - started + metrics = get(args.url + "/metrics") + engine = metrics["requests"][0] + usage = next((chunk["usage"] for chunk in reversed(chunks) if "usage" in chunk), {}) + row = {"label": label, "expected_prompt_tokens": expected, + "request_sha256": hashlib.sha256(body).hexdigest(), + "client_ttft_s": first, "client_elapsed_s": elapsed, "finish_reason": finish, + "usage": usage, "engine": engine, "text": "".join(texts)} + if expected is not None and engine["prompt_tokens"] != expected: + raise RuntimeError(f"token count mismatch: {expected} vs {engine['prompt_tokens']}") + if not texts: + raise RuntimeError(f"no text received for {label}") + (args.out / (label + "-raw.json")).write_text(json.dumps({"chunks": chunks, "row": row}, indent=2) + "\n") + rows.append(row) + (args.out / "results.json").write_text(json.dumps(rows, indent=2) + "\n") + print("done", label, json.dumps({"ttft_s": first, "elapsed_s": elapsed, "engine": engine}), flush=True) + return row + + perform("warmup", request("Reply with exactly the word READY.", 16)) + # Each nonce occurs before the filler so previous long prompts cannot be reused. + filler = "\n".join(f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003" + for i in range(12000)) + ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, " + "modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.") + for target in map(int, args.targets.split(",")): + for run in range(1, args.runs + 1): + prefix = f"Benchmark nonce: series-{target}-trial-{run}.\nReview this synthetic Python module:\n" + lo, hi = 0, len(filler) + while lo < hi: + middle = (lo + hi + 1) // 2 + if count(request(prefix + filler[:middle] + ending)) <= target: + lo = middle + else: + hi = middle - 1 + req = request(prefix + filler[:lo] + ending) + actual = count(req) + if actual < target - 20 or actual > target: + raise RuntimeError(f"could not construct target {target}: {actual}") + perform(f"tokens-{target}-run-{run}", req, actual) + measured = [row for row in rows if row["label"] != "warmup"] + groups = {} + for target in map(int, args.targets.split(",")): + subset = [r for r in measured if r["label"].startswith(f"tokens-{target}-")] + values = { + "prompt_tokens": [r["engine"]["prompt_tokens"] for r in subset], + "cached_tokens": [r["engine"].get("reused", 0) for r in subset], + "output_tokens": [r["engine"]["engine_generated"] for r in subset], + "client_ttft_s": [r["client_ttft_s"] for r in subset], + "client_elapsed_s": [r["client_elapsed_s"] for r in subset], + "prefill_tok_s": [(r["engine"]["prompt_tokens"] - (r["engine"].get("reused") or 0)) / (r["engine"]["prompt_ms"] / 1000) for r in subset], + "decode_tok_s": [r["engine"]["engine_generated"] / (r["engine"]["decode_ms"] / 1000) for r in subset], + } + groups[str(target)] = {key: {"median": statistics.median(v), "min": min(v), "max": max(v)} + for key, v in values.items()} + (args.out / "summary.json").write_text(json.dumps(groups, indent=2) + "\n") + print("summary", json.dumps(groups), flush=True) + + +if __name__ == "__main__": + main() diff --git a/bench/results/2026-10-03-community-2x-mi50/initial-status.json b/bench/results/2026-10-03-community-2x-mi50/initial-status.json new file mode 100644 index 0000000..fd96e13 --- /dev/null +++ b/bench/results/2026-10-03-community-2x-mi50/initial-status.json @@ -0,0 +1,50 @@ +{ + "service": "strata", + "model": "qwen3.8-flash-next-coder", + "loaded": true, + "auto_load": true, + "structured_output": { + "formats": [ + "json_object", + "json_schema" + ], + "method": "prompt_and_validate", + "constrained_decoding": false, + "stream_buffered": true + }, + "engine": "0.1.38", + "started": 1791055531, + "uptime_s": 2, + "cache_max_tokens": 131072, + "context": { + "native": 131072, + "max_positions": 131072 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": false, + "available": false, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1791055534, + "gpu": null, + "ram": { + "used_gib": 4.9, + "total_gib": 31.2 + } + } +} diff --git a/bench/results/2026-10-03-community-2x-mi50/needles.json b/bench/results/2026-10-03-community-2x-mi50/needles.json new file mode 100644 index 0000000..0eda889 --- /dev/null +++ b/bench/results/2026-10-03-community-2x-mi50/needles.json @@ -0,0 +1,56 @@ +[ + { + "length": "32k", + "depth": 10, + "prompt_tokens": 25776, + "seconds": 52.6, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "32k", + "depth": 50, + "prompt_tokens": 25776, + "seconds": 50.7, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + }, + { + "length": "32k", + "depth": 90, + "prompt_tokens": 25777, + "seconds": 50.8, + "found": true, + "word": "willow-cobalt-696", + "answer": "willow-cobalt-696" + }, + { + "length": "128k", + "depth": 10, + "prompt_tokens": 103727, + "seconds": 206.9, + "found": true, + "word": "falcon-saffron-138", + "answer": "falcon-saffron-138" + }, + { + "length": "128k", + "depth": 50, + "prompt_tokens": 103725, + "seconds": 205.9, + "found": true, + "word": "quartz-tundra-528", + "answer": "quartz-tundra-528" + }, + { + "length": "128k", + "depth": 90, + "prompt_tokens": 103725, + "seconds": 112.5, + "found": true, + "word": "quartz-glacier-192", + "answer": "quartz-glacier-192" + } +] \ No newline at end of file diff --git a/bench/results/2026-10-03-community-2x-mi50/results.json b/bench/results/2026-10-03-community-2x-mi50/results.json new file mode 100644 index 0000000..10d3c2b --- /dev/null +++ b/bench/results/2026-10-03-community-2x-mi50/results.json @@ -0,0 +1,382 @@ +[ + { + "label": "warmup", + "expected_prompt_tokens": null, + "request_sha256": "b63e57873441a996a529b246a66cf12de70a7c671777f99329354d5c195f788f", + "client_ttft_s": 0.44287488800182473, + "client_elapsed_s": 0.5121355729934294, + "finish_reason": "stop", + "usage": { + "prompt_tokens": 19, + "completion_tokens": 2, + "total_tokens": 21, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791055534.084382, + "duration_s": 0.5, + "finish": "stop", + "prompt_tokens": 19, + "reused": 0, + "output_tokens": 2, + "prompt_total": 19, + "prompt_read": 19, + "engine_generated": 2, + "prompt_ms": 398.1, + "decode_ms": 108.4, + "decode_tok_s": 18.5, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 3, + "drafts_accepted": 3 + }, + "text": "READY" + }, + { + "label": "tokens-4096-run-1", + "expected_prompt_tokens": 4096, + "request_sha256": "5d94c652067354bbe72930d2bdad3886564f08cf2546b32411af02d33ad3ce05", + "client_ttft_s": 13.26403624098748, + "client_elapsed_s": 18.427036346998648, + "finish_reason": "length", + "usage": { + "prompt_tokens": 4096, + "completion_tokens": 256, + "total_tokens": 4352, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791055535.8394356, + "duration_s": 18.4, + "finish": "length", + "prompt_tokens": 4096, + "reused": 0, + "output_tokens": 256, + "prompt_total": 4096, + "prompt_read": 4096, + "engine_generated": 256, + "prompt_ms": 13216.0, + "decode_ms": 5189.0, + "decode_tok_s": 49.3, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 210, + "drafts_accepted": 145 + }, + "text": "The provided Python module presents a series of deterministic integer transforms, each encapsulated within a uniquely named function. These functions, labeled from `task_00000` to `task_00112` (and potentially beyond), follow a consistent mathematical pattern: they take an integer input, apply a linear transformation of the form `(value * multiplier + offset) % modulus`, and return the result. This structure is a classic example of a linear congruential generator (LCG) component, often used in pseudo-random number generation, hashing, or cryptographic primitives, though here it appears to be a synthetic benchmark or test harness.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nEach function implements a linear congruential step: `f(x) = (a * x + c) % m`, where `a` is the multiplier, `c` is the increment, and `m` is the modulus (100003 in all cases). The modulus 100003 is a prime number, which is significant because it ensures that the multiplicative group modulo 100003 is cyclic, and for certain choices of `a` and `c`, the transformation can be a permutation of the" + }, + { + "label": "tokens-4096-run-2", + "expected_prompt_tokens": 4096, + "request_sha256": "8da8a04e70e4d916f6630729082bdfb9d6ebbb47117aad60bc0541bce198a213", + "client_ttft_s": 12.663496508001117, + "client_elapsed_s": 17.377855258993804, + "finish_reason": "length", + "usage": { + "prompt_tokens": 4096, + "completion_tokens": 256, + "total_tokens": 4352, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791055555.3915784, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 4096, + "reused": 0, + "output_tokens": 256, + "prompt_total": 4096, + "prompt_read": 4096, + "engine_generated": 256, + "prompt_ms": 12615.4, + "decode_ms": 4740.3, + "decode_tok_s": 54.0, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 208, + "drafts_accepted": 156 + }, + "text": "The provided Python module consists of a series of functions, each named with a specific pattern (`task_XXXXX`), that perform a deterministic integer transformation. Each function takes a single integer argument `value` and returns an integer result computed using a linear transformation followed by a modulo operation. The general form of each function is:\n\n```python\ndef task_XXXXX(value: int) -> int:\n return (value * A + B) % 100003\n```\n\nwhere `A` and `B` are constants specific to each function. The modulus `100003` is a prime number, which is significant in modular arithmetic because it ensures that the multiplicative group modulo 100003 is cyclic and that every non-zero element has a multiplicative inverse. This property is often exploited in cryptographic algorithms, hash functions, and pseudo-random number generators.\n\n### Deterministic Integer Transforms\n\nEach function implements a linear congruential transformation, a common technique in number theory and computer science. The transformation `value * A + B` is an affine transformation over the integers. When combined with the modulo operation, it becomes a function from the finite field (or ring) of integers modulo 10" + }, + { + "label": "tokens-4096-run-3", + "expected_prompt_tokens": 4096, + "request_sha256": "946079edb58e764050805886156dc8f877cc29e1ca8d01c84e9a1e7917d49492", + "client_ttft_s": 12.811999237994314, + "client_elapsed_s": 17.900370211005793, + "finish_reason": "length", + "usage": { + "prompt_tokens": 4096, + "completion_tokens": 256, + "total_tokens": 4352, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791055573.9388902, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 4096, + "reused": 0, + "output_tokens": 256, + "prompt_total": 4096, + "prompt_read": 4096, + "engine_generated": 256, + "prompt_ms": 12763.9, + "decode_ms": 5114.7, + "decode_tok_s": 50.1, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 222, + "drafts_accepted": 146 + }, + "text": "The provided Python module presents a series of deterministic integer transforms, each encapsulated within a uniquely named function. These functions, labeled from `task_00000` to `task_00112` (and potentially beyond), follow a consistent mathematical pattern: they take an integer input, apply a linear transformation, and return the result modulo a large prime number, specifically 100003. This structure serves as a synthetic benchmark for evaluating code generation, pattern recognition, and algorithmic consistency in automated systems.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nAt the core of each function is the expression `(value * multiplier + offset) % 100003`. This is a classic linear congruential generator (LCG) step, often used in pseudo-random number generation or cryptographic hashing, though here it is applied deterministically to a single input. The multiplier and offset vary per function, creating a unique mapping for each task. For instance, `task_00000` uses a multiplier of 1 and an offset of 0, effectively returning `value % 100003`. In contrast, `task_00097` uses a multiplier of 1" + }, + { + "label": "tokens-32768-run-1", + "expected_prompt_tokens": 32768, + "request_sha256": "e37cfc2ab9867d91130927440df24a57255a736b8d0d829d07d828e22e3de572", + "client_ttft_s": 62.74767600699852, + "client_elapsed_s": 68.09618598900852, + "finish_reason": "length", + "usage": { + "prompt_tokens": 32768, + "completion_tokens": 256, + "total_tokens": 33024, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791055594.1634562, + "duration_s": 68.0, + "finish": "length", + "prompt_tokens": 32768, + "reused": 0, + "output_tokens": 256, + "prompt_total": 32768, + "prompt_read": 32768, + "engine_generated": 256, + "prompt_ms": 62608.4, + "decode_ms": 5375.3, + "decode_tok_s": 47.6, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 230, + "drafts_accepted": 152 + }, + "text": "This Python module presents a highly repetitive, synthetic collection of functions that serve as a benchmark for deterministic integer transforms. The code consists of a series of functions named `task_00000` through `task_00888` (and potentially beyond), each performing a specific linear transformation on an input integer `value` and returning the result modulo 100003.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nAt the core of each function is a linear congruential generator (LCG) style operation: `(value * multiplier + addend) % 100003`. The modulus, 100003, is a prime number. This choice of modulus is significant because it ensures that the multiplicative group of integers modulo 100003 is cyclic, which is a desirable property for cryptographic or pseudo-random number generation contexts, although here it is used for deterministic hashing or transformation.\n\nThe structure of the functions reveals a pattern in the `multiplier` and `addend` parameters. For the first 97 functions (`task_00000` to `task_00096`), the multiplier increases linearly from 1 to" + }, + { + "label": "tokens-32768-run-2", + "expected_prompt_tokens": 32768, + "request_sha256": "ed2dfaa11aecad9f4563f33bb5f5d4b8704486508700b8fa572722cc1225ee26", + "client_ttft_s": 62.81415034100064, + "client_elapsed_s": 68.14694995200261, + "finish_reason": "length", + "usage": { + "prompt_tokens": 32768, + "completion_tokens": 256, + "total_tokens": 33024, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791055664.4150822, + "duration_s": 68.0, + "finish": "length", + "prompt_tokens": 32768, + "reused": 0, + "output_tokens": 256, + "prompt_total": 32768, + "prompt_read": 32768, + "engine_generated": 256, + "prompt_ms": 62675.9, + "decode_ms": 5359.3, + "decode_tok_s": 47.8, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 222, + "drafts_accepted": 147 + }, + "text": "This Python module presents a highly repetitive, synthetic collection of functions that perform deterministic integer transforms. Each function follows a strict pattern: it accepts an integer `value`, applies a linear transformation of the form `(value * multiplier + offset) % modulus`, and returns the result. The modulus is consistently set to `100003`, which is a prime number. This choice of modulus is significant because it ensures that the multiplicative group of integers modulo 100003 is cyclic, and every non-zero multiplier has a unique modular inverse. This property is often desirable in cryptographic or hashing contexts, though here it appears to be used for simple arithmetic obfuscation or benchmarking.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nThe core operation in each function is a linear congruential generator (LCG) step, commonly used in pseudo-random number generation. The formula $f(x) = (ax + c) \\pmod m$ defines an affine transformation over the finite field $\\mathbb{Z}_m$. In this module, $m = 100003$. The multipliers ($a$) and offsets ($c$) vary per function. For example, `task_00000`" + }, + { + "label": "tokens-32768-run-3", + "expected_prompt_tokens": 32768, + "request_sha256": "2a3c7342622e80c3cd8b37e062f0a2f64640c119ece8cccbf168639041eac079", + "client_ttft_s": 62.844907227001386, + "client_elapsed_s": 68.09568050300004, + "finish_reason": "length", + "usage": { + "prompt_tokens": 32768, + "completion_tokens": 256, + "total_tokens": 33024, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791055734.689819, + "duration_s": 68.0, + "finish": "length", + "prompt_tokens": 32768, + "reused": 0, + "output_tokens": 256, + "prompt_total": 32768, + "prompt_read": 32768, + "engine_generated": 256, + "prompt_ms": 62706.6, + "decode_ms": 5277.5, + "decode_tok_s": 48.5, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 234, + "drafts_accepted": 153 + }, + "text": "This Python module presents a highly repetitive, synthetic collection of functions that perform deterministic integer transforms. Each function follows a strict pattern: it accepts an integer `value`, applies a linear transformation of the form `(value * multiplier + offset) % modulus`, and returns the result. The modulus is consistently set to `100003`, which is a prime number. This choice of modulus is significant because it ensures that the multiplicative group of integers modulo 100003 is cyclic, meaning that for any non-zero multiplier, the transformation is bijective (a permutation) over the set of integers modulo 100003. This property is often desirable in cryptographic contexts or pseudo-random number generation, although here it appears to be used for benchmarking or synthetic data generation.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nThe core operation in each function is a linear congruential generator (LCG) step, defined by the formula $f(x) = (ax + c) \\pmod m$. In this module, $m = 100003$. The multiplier $a$ and the increment $c$ vary per function. For example, `task_00000` uses $a" + }, + { + "label": "tokens-128000-run-1", + "expected_prompt_tokens": 128000, + "request_sha256": "3235aac3f934cf1d889c25973ca172b355509dc2522fdfb463fbefe979a9075d", + "client_ttft_s": 248.26734286299325, + "client_elapsed_s": 253.83500957599608, + "finish_reason": "length", + "usage": { + "prompt_tokens": 128000, + "completion_tokens": 256, + "total_tokens": 128256, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791055809.118869, + "duration_s": 253.5, + "finish": "length", + "prompt_tokens": 128000, + "reused": 0, + "output_tokens": 256, + "prompt_total": 128000, + "prompt_read": 128000, + "engine_generated": 256, + "prompt_ms": 247841.6, + "decode_ms": 5596.2, + "decode_tok_s": 45.7, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 232, + "drafts_accepted": 152 + }, + "text": "This Python module represents a synthetic benchmark designed to test the performance and correctness of integer arithmetic operations, specifically focusing on linear transforms and modular arithmetic. The code consists of a series of functions, each named `task_XXXXX`, where `XXXXX` is a zero-padded integer index. Each function accepts a single integer argument `value` and returns an integer result.\n\n### 1. Deterministic Integer Transforms\n\nThe core logic of every function in this module is identical in structure:\n```python\nreturn (value * A + B) % M\n```\nWhere:\n- `value` is the input integer.\n- `A` is a multiplier (coefficient).\n- `B` is an additive constant.\n- `M` is the modulus, which is consistently `100003` throughout the entire module.\n\nThis represents a **linear congruential transform**. In computer science, such transforms are fundamental in pseudorandom number generation (LCG), hashing functions, and cryptographic primitives. The specific form `(value * A + B) % M` ensures that the output is always within the range `[0, M-1]`, regardless of how large the input `value` is.\n\n### 2" + }, + { + "label": "tokens-128000-run-2", + "expected_prompt_tokens": 128000, + "request_sha256": "5f4b8bc9f0afc7765320abd89960c0938e0d7cf5974e962fdbd0613fef31c8d4", + "client_ttft_s": 248.0881588330085, + "client_elapsed_s": 253.0268927290017, + "finish_reason": "length", + "usage": { + "prompt_tokens": 128000, + "completion_tokens": 256, + "total_tokens": 128256, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791056068.9450965, + "duration_s": 252.7, + "finish": "length", + "prompt_tokens": 128000, + "reused": 0, + "output_tokens": 256, + "prompt_total": 128000, + "prompt_read": 128000, + "engine_generated": 256, + "prompt_ms": 247669.4, + "decode_ms": 4967.1, + "decode_tok_s": 51.5, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 205, + "drafts_accepted": 163 + }, + "text": "This Python module represents a synthetic benchmark designed to test the performance and correctness of integer arithmetic operations, specifically focusing on linear transforms and modular arithmetic. The code consists of a series of functions, each named `task_XXXXX`, where `XXXXX` is a zero-padded integer index. Each function accepts a single integer argument `value` and returns an integer result.\n\n### 1. Deterministic Integer Transforms\n\nThe core logic of each function is a linear transformation of the form:\n$$ f(x) = (a \\cdot x + b) \\pmod m $$\nwhere:\n- $x$ is the input `value`.\n- $a$ is the multiplier (coefficient).\n- $b$ is the additive constant.\n- $m$ is the modulus, which is consistently set to `100003` across all functions.\n\nThe multiplier $a$ and the constant $b$ vary deterministically based on the function's index. For example:\n- `task_00000`: $a=1, b=0$\n- `task_00001`: $a=2, b=1$\n- `task_00002`:" + }, + { + "label": "tokens-128000-run-3", + "expected_prompt_tokens": 128000, + "request_sha256": "5c3fb71db9f9f44765f28389d1032f2c8b6687d1bf5ca6f33aeb924072cfa6e4", + "client_ttft_s": 248.0611828550027, + "client_elapsed_s": 253.7529949669988, + "finish_reason": "length", + "usage": { + "prompt_tokens": 128000, + "completion_tokens": 256, + "total_tokens": 128256, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1791056328.0391443, + "duration_s": 253.4, + "finish": "length", + "prompt_tokens": 128000, + "reused": 0, + "output_tokens": 256, + "prompt_total": 128000, + "prompt_read": 128000, + "engine_generated": 256, + "prompt_ms": 247650.3, + "decode_ms": 5720.0, + "decode_tok_s": 44.8, + "hit_rate": 1.0, + "ram_blobs": 0, + "file_blobs": 0, + "file_mb": 0.0, + "drafts_offered": 235, + "drafts_accepted": 149 + }, + "text": "This Python module represents a synthetic benchmark designed to test the performance and correctness of integer arithmetic operations, specifically focusing on linear transformations combined with modular arithmetic. The code consists of a series of functions, each named `task_XXXXX`, where `XXXXX` is a zero-padded integer index. Each function accepts a single integer argument `value` and returns a new integer calculated using the formula:\n\n$$ f(value) = (value \\times A + B) \\pmod{M} $$\n\nwhere $A$ is a multiplier, $B$ is an additive constant, and $M$ is the modulus, which is consistently set to `100003` throughout the module.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nThe core logic of each function is a deterministic linear congruential transformation. In computer science, such transformations are fundamental to pseudorandom number generators (PRNGs), hash functions, and cryptographic primitives. The specific form $ (value \\times A + B) \\pmod{M} $ ensures that the output is always within the range $[0, M-1]$.\n\nThe modulus $M = 100003$ is a prime number. This choice is significant because" + } +] diff --git a/bench/results/2026-10-03-community-2x-mi50/strata-coder.json b/bench/results/2026-10-03-community-2x-mi50/strata-coder.json new file mode 100644 index 0000000..d766bbf --- /dev/null +++ b/bench/results/2026-10-03-community-2x-mi50/strata-coder.json @@ -0,0 +1,45 @@ +{ + "exe": "/work/build-906/strata", + "args": [ + "--pack", + "/m/pack-coder", + "--native", + "/m/coder/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf", + "--ple-gguf", + "/m/coder/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf", + "--expert-profile", + "/opt/strata/data/expert-profile-coder.bin", + "--expert-cache", + "auto", + "--prefill", + "4096", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/m/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--vram-reserve-mib", + "600", + "--kv-resident", + "32768", + "--pcie-frac", + "0" + ], + "cwd": "/opt/strata", + "tokenizer": "/m/pack-coder/tokenizer", + "model_name": "qwen3.8-flash-next-coder", + "log": "/work/strata-coder.log", + "lib_dirs": [], + "port": 8080, + "host": "0.0.0.0", + "gpu": [ + 0, + 1 + ], + "layer_split": "27" +} \ No newline at end of file diff --git a/bench/results/2026-10-03-community-2x-mi50/summary.json b/bench/results/2026-10-03-community-2x-mi50/summary.json new file mode 100644 index 0000000..eddf5ac --- /dev/null +++ b/bench/results/2026-10-03-community-2x-mi50/summary.json @@ -0,0 +1,113 @@ +{ + "4096": { + "prompt_tokens": { + "median": 4096, + "min": 4096, + "max": 4096 + }, + "cached_tokens": { + "median": 0, + "min": 0, + "max": 0 + }, + "output_tokens": { + "median": 256, + "min": 256, + "max": 256 + }, + "client_ttft_s": { + "median": 12.811999237994314, + "min": 12.663496508001117, + "max": 13.26403624098748 + }, + "client_elapsed_s": { + "median": 17.900370211005793, + "min": 17.377855258993804, + "max": 18.427036346998648 + }, + "prefill_tok_s": { + "median": 320.90505253096626, + "min": 309.9273607748184, + "max": 324.68253087496237 + }, + "decode_tok_s": { + "median": 50.05181144544157, + "min": 49.3351320100212, + "max": 54.00502077927557 + } + }, + "32768": { + "prompt_tokens": { + "median": 32768, + "min": 32768, + "max": 32768 + }, + "cached_tokens": { + "median": 0, + "min": 0, + "max": 0 + }, + "output_tokens": { + "median": 256, + "min": 256, + "max": 256 + }, + "client_ttft_s": { + "median": 62.81415034100064, + "min": 62.74767600699852, + "max": 62.844907227001386 + }, + "client_elapsed_s": { + "median": 68.09618598900852, + "min": 68.09568050300004, + "max": 68.14694995200261 + }, + "prefill_tok_s": { + "median": 522.8165850031671, + "min": 522.5606236026192, + "max": 523.3802492956216 + }, + "decode_tok_s": { + "median": 47.767432313921596, + "min": 47.625248823321485, + "max": 48.50781620085268 + } + }, + "128000": { + "prompt_tokens": { + "median": 128000, + "min": 128000, + "max": 128000 + }, + "cached_tokens": { + "median": 0, + "min": 0, + "max": 0 + }, + "output_tokens": { + "median": 256, + "min": 256, + "max": 256 + }, + "client_ttft_s": { + "median": 248.0881588330085, + "min": 248.0611828550027, + "max": 248.26734286299325 + }, + "client_elapsed_s": { + "median": 253.7529949669988, + "min": 253.0268927290017, + "max": 253.83500957599608 + }, + "prefill_tok_s": { + "median": 516.8179839737974, + "min": 516.4588995551998, + "max": 516.857843499483 + }, + "decode_tok_s": { + "median": 45.745327186305, + "min": 44.75524475524476, + "max": 51.5391274586781 + } + } +} diff --git a/bench/results/2026-10-03-community-2x-mi50/telemetry.jsonl b/bench/results/2026-10-03-community-2x-mi50/telemetry.jsonl new file mode 100644 index 0000000..bafdea8 --- /dev/null +++ b/bench/results/2026-10-03-community-2x-mi50/telemetry.jsonl @@ -0,0 +1,1699 @@ +{"t": 1791055498.231, "mem_avail_kib": 30786360, "swap_free_kib": 7052840, "vram_used": [10924032,10924032]} +{"t": 1791055499.271, "mem_avail_kib": 30377400, "swap_free_kib": 7052840, "vram_used": [10964992,10964992]} +{"t": 1791055500.334, "mem_avail_kib": 30173356, "swap_free_kib": 7053096, "vram_used": [1064579072,11710464]} +{"t": 1791055501.391, "mem_avail_kib": 30172568, "swap_free_kib": 7053096, "vram_used": [1064579072,11710464]} +{"t": 1791055502.433, "mem_avail_kib": 30169280, "swap_free_kib": 7053096, "vram_used": [1064579072,11710464]} +{"t": 1791055503.477, "mem_avail_kib": 30191972, "swap_free_kib": 7053096, "vram_used": [1588826112,11661312]} +{"t": 1791055504.566, "mem_avail_kib": 30031712, "swap_free_kib": 7053096, "vram_used": [2394238976,892637184]} +{"t": 1791055505.624, "mem_avail_kib": 30051892, "swap_free_kib": 7053096, "vram_used": [2394238976,892637184]} +{"t": 1791055506.686, "mem_avail_kib": 30032244, "swap_free_kib": 7053096, "vram_used": [2394238976,892637184]} +{"t": 1791055507.731, "mem_avail_kib": 30040204, "swap_free_kib": 7053096, "vram_used": [2394189824,1863573504]} +{"t": 1791055508.773, "mem_avail_kib": 28961132, "swap_free_kib": 7053096, "vram_used": [2820055040,2377576448]} +{"t": 1791055509.818, "mem_avail_kib": 28300928, "swap_free_kib": 7053096, "vram_used": [2820943872,3018100736]} +{"t": 1791055510.884, "mem_avail_kib": 28350460, "swap_free_kib": 7053096, "vram_used": [2820943872,3726938112]} +{"t": 1791055512.032, "mem_avail_kib": 28368196, "swap_free_kib": 7053096, "vram_used": [2820943872,3726938112]} +{"t": 1791055513.107, "mem_avail_kib": 28343544, "swap_free_kib": 7053096, "vram_used": [2820943872,3726938112]} +{"t": 1791055514.156, "mem_avail_kib": 28271040, "swap_free_kib": 7053096, "vram_used": [16318500864,3802742784]} +{"t": 1791055515.207, "mem_avail_kib": 28260748, "swap_free_kib": 7053096, "vram_used": [16318509056,3802742784]} +{"t": 1791055516.252, "mem_avail_kib": 28267500, "swap_free_kib": 7053096, "vram_used": [16318509056,3802742784]} +{"t": 1791055517.291, "mem_avail_kib": 28265100, "swap_free_kib": 7053096, "vram_used": [16318509056,3802742784]} +{"t": 1791055518.332, "mem_avail_kib": 28258636, "swap_free_kib": 7053096, "vram_used": [16318509056,3802742784]} +{"t": 1791055519.379, "mem_avail_kib": 28277724, "swap_free_kib": 7053096, "vram_used": [16318509056,15456628736]} +{"t": 1791055520.431, "mem_avail_kib": 28278036, "swap_free_kib": 7053096, "vram_used": [16318509056,15456628736]} +{"t": 1791055521.479, "mem_avail_kib": 28278204, "swap_free_kib": 7053096, "vram_used": [16318509056,15456628736]} +{"t": 1791055522.525, "mem_avail_kib": 28272556, "swap_free_kib": 7053096, "vram_used": [16318509056,15456628736]} +{"t": 1791055523.573, "mem_avail_kib": 28265648, "swap_free_kib": 7053096, "vram_used": [16318509056,15456628736]} +{"t": 1791055524.619, "mem_avail_kib": 28246724, "swap_free_kib": 7053096, "vram_used": [16318509056,15456628736]} +{"t": 1791055525.666, "mem_avail_kib": 28241676, "swap_free_kib": 7053352, "vram_used": [16318509056,15456628736]} +{"t": 1791055526.719, "mem_avail_kib": 28245824, "swap_free_kib": 7053608, "vram_used": [16318509056,15456628736]} +{"t": 1791055527.769, "mem_avail_kib": 28248292, "swap_free_kib": 7053608, "vram_used": [16318509056,15456628736]} +{"t": 1791055528.860, "mem_avail_kib": 28238060, "swap_free_kib": 7053608, "vram_used": [16318509056,15456628736]} +{"t": 1791055529.899, "mem_avail_kib": 28231984, "swap_free_kib": 7053608, "vram_used": [16318513152,15456632832]} +{"t": 1791055530.936, "mem_avail_kib": 27595720, "swap_free_kib": 7053608, "vram_used": [16374341632,15571443712]} +{"t": 1791055531.981, "mem_avail_kib": 27529568, "swap_free_kib": 7053608, "vram_used": [16475328512,15663824896]} +{"t": 1791055533.023, "mem_avail_kib": 27517964, "swap_free_kib": 7053608, "vram_used": [16475328512,15663824896]} +{"t": 1791055534.065, "mem_avail_kib": 27358404, "swap_free_kib": 7053608, "vram_used": [16475328512,15663824896]} +{"t": 1791055535.108, "mem_avail_kib": 27225240, "swap_free_kib": 7053608, "vram_used": [16557064192,15718391808]} +{"t": 1791055536.145, "mem_avail_kib": 27226976, "swap_free_kib": 7053608, "vram_used": [16557481984,15718391808]} +{"t": 1791055537.183, "mem_avail_kib": 27227508, "swap_free_kib": 7053608, "vram_used": [16560840704,15718416384]} +{"t": 1791055538.221, "mem_avail_kib": 27226424, "swap_free_kib": 7053608, "vram_used": [16560840704,15718416384]} +{"t": 1791055539.259, "mem_avail_kib": 27218752, "swap_free_kib": 7053608, "vram_used": [16560840704,15718416384]} +{"t": 1791055540.297, "mem_avail_kib": 27224788, "swap_free_kib": 7054120, "vram_used": [16560840704,15718416384]} +{"t": 1791055541.333, "mem_avail_kib": 27209492, "swap_free_kib": 7054120, "vram_used": [16561463296,15718420480]} +{"t": 1791055542.372, "mem_avail_kib": 27218412, "swap_free_kib": 7054120, "vram_used": [16561463296,15718420480]} +{"t": 1791055543.410, "mem_avail_kib": 27208168, "swap_free_kib": 7054120, "vram_used": [16561471488,15720955904]} +{"t": 1791055544.449, "mem_avail_kib": 27197644, "swap_free_kib": 7054120, "vram_used": [16561483776,15728717824]} +{"t": 1791055545.486, "mem_avail_kib": 27225460, "swap_free_kib": 7054120, "vram_used": [16561483776,15728717824]} +{"t": 1791055546.522, "mem_avail_kib": 27222844, "swap_free_kib": 7054120, "vram_used": [16561483776,15728717824]} +{"t": 1791055547.560, "mem_avail_kib": 27216632, "swap_free_kib": 7054120, "vram_used": [16561483776,15728717824]} +{"t": 1791055548.601, "mem_avail_kib": 27109628, "swap_free_kib": 7054120, "vram_used": [16561487872,15729442816]} +{"t": 1791055549.641, "mem_avail_kib": 27107924, "swap_free_kib": 7054120, "vram_used": [16562458624,15730737152]} +{"t": 1791055550.677, "mem_avail_kib": 27109980, "swap_free_kib": 7054120, "vram_used": [16562458624,15730737152]} +{"t": 1791055551.717, "mem_avail_kib": 27102036, "swap_free_kib": 7054120, "vram_used": [16562458624,15730737152]} +{"t": 1791055552.756, "mem_avail_kib": 27094240, "swap_free_kib": 7054120, "vram_used": [16562458624,15730737152]} +{"t": 1791055553.797, "mem_avail_kib": 27104564, "swap_free_kib": 7054120, "vram_used": [16562458624,15730737152]} +{"t": 1791055554.835, "mem_avail_kib": 27102540, "swap_free_kib": 7054120, "vram_used": [16562458624,15730737152]} +{"t": 1791055555.873, "mem_avail_kib": 27188636, "swap_free_kib": 7054120, "vram_used": [16562458624,15730737152]} +{"t": 1791055556.915, "mem_avail_kib": 27199532, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055557.953, "mem_avail_kib": 27201496, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055558.992, "mem_avail_kib": 27210500, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055560.029, "mem_avail_kib": 27205028, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055561.065, "mem_avail_kib": 27217216, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055562.104, "mem_avail_kib": 27223476, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055563.142, "mem_avail_kib": 27227648, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055564.181, "mem_avail_kib": 27240288, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055565.217, "mem_avail_kib": 27237232, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055566.257, "mem_avail_kib": 27223536, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055567.293, "mem_avail_kib": 27211536, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055568.330, "mem_avail_kib": 27105576, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055569.368, "mem_avail_kib": 27108292, "swap_free_kib": 7054376, "vram_used": [16562458624,15730737152]} +{"t": 1791055570.402, "mem_avail_kib": 27100288, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055571.441, "mem_avail_kib": 27094024, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055572.477, "mem_avail_kib": 27101680, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055573.515, "mem_avail_kib": 27100552, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055574.552, "mem_avail_kib": 27178496, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055575.589, "mem_avail_kib": 27181928, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055576.626, "mem_avail_kib": 27191396, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055577.664, "mem_avail_kib": 27189424, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055578.701, "mem_avail_kib": 27200084, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055579.742, "mem_avail_kib": 27211748, "swap_free_kib": 7054376, "vram_used": [16562458624,15730896896]} +{"t": 1791055580.783, "mem_avail_kib": 27221836, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055581.821, "mem_avail_kib": 27231360, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055582.861, "mem_avail_kib": 27222248, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055583.900, "mem_avail_kib": 27228260, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055584.938, "mem_avail_kib": 27231048, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055585.978, "mem_avail_kib": 27236244, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055587.018, "mem_avail_kib": 27121292, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055588.053, "mem_avail_kib": 27122072, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055589.090, "mem_avail_kib": 27122960, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055590.127, "mem_avail_kib": 27114652, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055591.163, "mem_avail_kib": 27117328, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055592.207, "mem_avail_kib": 27107232, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055593.244, "mem_avail_kib": 27103404, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055594.284, "mem_avail_kib": 27146720, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055595.321, "mem_avail_kib": 27160428, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055596.356, "mem_avail_kib": 27166948, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055597.395, "mem_avail_kib": 27164564, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055598.431, "mem_avail_kib": 27178824, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055599.470, "mem_avail_kib": 27196184, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055600.507, "mem_avail_kib": 27206660, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055601.545, "mem_avail_kib": 27208100, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055602.587, "mem_avail_kib": 27207380, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055603.625, "mem_avail_kib": 27198348, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055604.663, "mem_avail_kib": 27199968, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055605.699, "mem_avail_kib": 27208528, "swap_free_kib": 7054376, "vram_used": [16562462720,15730900992]} +{"t": 1791055606.736, "mem_avail_kib": 27212224, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055607.776, "mem_avail_kib": 27203128, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055608.815, "mem_avail_kib": 27196956, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055609.854, "mem_avail_kib": 27201396, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055610.889, "mem_avail_kib": 27206104, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055611.929, "mem_avail_kib": 27208428, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055612.968, "mem_avail_kib": 27213028, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055614.005, "mem_avail_kib": 27225020, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055615.041, "mem_avail_kib": 27210732, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055616.080, "mem_avail_kib": 27209548, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055617.121, "mem_avail_kib": 27217180, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055618.160, "mem_avail_kib": 27220700, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055619.196, "mem_avail_kib": 27230556, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055620.233, "mem_avail_kib": 27221736, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055621.270, "mem_avail_kib": 27218132, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055622.308, "mem_avail_kib": 27148140, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055623.346, "mem_avail_kib": 27132364, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055624.384, "mem_avail_kib": 27128956, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055625.423, "mem_avail_kib": 27135464, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055626.460, "mem_avail_kib": 27139852, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055627.498, "mem_avail_kib": 27092632, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055628.536, "mem_avail_kib": 27091820, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055629.575, "mem_avail_kib": 27099320, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055630.615, "mem_avail_kib": 27098028, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055631.654, "mem_avail_kib": 27095252, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055632.692, "mem_avail_kib": 27097848, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055633.732, "mem_avail_kib": 27096964, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055634.771, "mem_avail_kib": 27100540, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055635.809, "mem_avail_kib": 27098044, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055636.848, "mem_avail_kib": 27083572, "swap_free_kib": 7054376, "vram_used": [16562462720,15731044352]} +{"t": 1791055637.889, "mem_avail_kib": 27081652, "swap_free_kib": 7054632, "vram_used": [16562462720,15731044352]} +{"t": 1791055638.930, "mem_avail_kib": 27092164, "swap_free_kib": 7054632, "vram_used": [16562462720,15731044352]} +{"t": 1791055639.967, "mem_avail_kib": 27076424, "swap_free_kib": 7054632, "vram_used": [16562462720,15731044352]} +{"t": 1791055641.007, "mem_avail_kib": 27086376, "swap_free_kib": 7054632, "vram_used": [16562462720,15731044352]} +{"t": 1791055642.043, "mem_avail_kib": 27094036, "swap_free_kib": 7054632, "vram_used": [16562462720,15731044352]} +{"t": 1791055643.082, "mem_avail_kib": 27091056, "swap_free_kib": 7054632, "vram_used": [16562462720,15731044352]} +{"t": 1791055644.119, "mem_avail_kib": 27083248, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055645.157, "mem_avail_kib": 27083096, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055646.194, "mem_avail_kib": 27084144, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055647.236, "mem_avail_kib": 27084076, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055648.273, "mem_avail_kib": 27080940, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055649.311, "mem_avail_kib": 27073976, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055650.349, "mem_avail_kib": 27078040, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055651.388, "mem_avail_kib": 27079168, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055652.427, "mem_avail_kib": 27084012, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055653.464, "mem_avail_kib": 27087476, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055654.502, "mem_avail_kib": 27079020, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055655.540, "mem_avail_kib": 27044148, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055656.579, "mem_avail_kib": 26957072, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055657.616, "mem_avail_kib": 26941260, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055658.653, "mem_avail_kib": 26944536, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055659.689, "mem_avail_kib": 26948040, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055660.729, "mem_avail_kib": 26946764, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055661.768, "mem_avail_kib": 26956812, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055662.805, "mem_avail_kib": 26958276, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055663.841, "mem_avail_kib": 26966880, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055664.877, "mem_avail_kib": 27187456, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055665.916, "mem_avail_kib": 27192464, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055666.954, "mem_avail_kib": 27202652, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055667.995, "mem_avail_kib": 27209164, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055669.032, "mem_avail_kib": 27199048, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055670.071, "mem_avail_kib": 27201904, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055671.110, "mem_avail_kib": 27211872, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055672.148, "mem_avail_kib": 27197860, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055673.188, "mem_avail_kib": 27200252, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055674.230, "mem_avail_kib": 27203396, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055675.272, "mem_avail_kib": 27205876, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055676.313, "mem_avail_kib": 27215284, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055677.349, "mem_avail_kib": 27215468, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055678.387, "mem_avail_kib": 27215768, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055679.426, "mem_avail_kib": 27224480, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055680.465, "mem_avail_kib": 27220480, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055681.504, "mem_avail_kib": 27224980, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055682.541, "mem_avail_kib": 27213148, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055683.579, "mem_avail_kib": 27215612, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055684.616, "mem_avail_kib": 27210608, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055685.655, "mem_avail_kib": 27211608, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055686.695, "mem_avail_kib": 27230392, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055687.737, "mem_avail_kib": 27232452, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055688.776, "mem_avail_kib": 27222972, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055689.819, "mem_avail_kib": 27226164, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055690.858, "mem_avail_kib": 27226732, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055691.894, "mem_avail_kib": 27215112, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055692.932, "mem_avail_kib": 27136108, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055693.970, "mem_avail_kib": 27123876, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055695.008, "mem_avail_kib": 27131908, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055696.043, "mem_avail_kib": 27134480, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055697.081, "mem_avail_kib": 27123560, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055698.122, "mem_avail_kib": 27088224, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055699.161, "mem_avail_kib": 27082256, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055700.200, "mem_avail_kib": 27083448, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055701.238, "mem_avail_kib": 27084708, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055702.275, "mem_avail_kib": 27083268, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055703.312, "mem_avail_kib": 27084276, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055704.349, "mem_avail_kib": 27070776, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055705.385, "mem_avail_kib": 27072360, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055706.421, "mem_avail_kib": 27064332, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055707.461, "mem_avail_kib": 27074996, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055708.499, "mem_avail_kib": 27069124, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055709.536, "mem_avail_kib": 27064808, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055710.576, "mem_avail_kib": 27065376, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055711.616, "mem_avail_kib": 27071152, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055712.658, "mem_avail_kib": 27073824, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055713.696, "mem_avail_kib": 27078324, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055714.735, "mem_avail_kib": 27077388, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055715.776, "mem_avail_kib": 27081472, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055716.817, "mem_avail_kib": 27059232, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055717.855, "mem_avail_kib": 27056972, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055718.896, "mem_avail_kib": 27070544, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055719.934, "mem_avail_kib": 27063232, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055720.972, "mem_avail_kib": 27063100, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055722.013, "mem_avail_kib": 27068064, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055723.053, "mem_avail_kib": 27061360, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055724.091, "mem_avail_kib": 27072316, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055725.129, "mem_avail_kib": 27071112, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055726.165, "mem_avail_kib": 27079216, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055727.206, "mem_avail_kib": 26964468, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055728.244, "mem_avail_kib": 26960688, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055729.279, "mem_avail_kib": 26968196, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055730.316, "mem_avail_kib": 26968836, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055731.352, "mem_avail_kib": 26972928, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055732.388, "mem_avail_kib": 26975004, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055733.429, "mem_avail_kib": 26973536, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055734.470, "mem_avail_kib": 26967296, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055735.509, "mem_avail_kib": 27167356, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055736.548, "mem_avail_kib": 27173116, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055737.586, "mem_avail_kib": 27170296, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055738.623, "mem_avail_kib": 27166192, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055739.662, "mem_avail_kib": 27171320, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055740.699, "mem_avail_kib": 27176712, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055741.737, "mem_avail_kib": 27179900, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055742.776, "mem_avail_kib": 27171924, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055743.815, "mem_avail_kib": 27175460, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055744.853, "mem_avail_kib": 27182596, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055745.888, "mem_avail_kib": 27187884, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055746.924, "mem_avail_kib": 27188676, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055747.961, "mem_avail_kib": 27193968, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055749.000, "mem_avail_kib": 27188348, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055750.041, "mem_avail_kib": 27192248, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055751.079, "mem_avail_kib": 27208128, "swap_free_kib": 7054632, "vram_used": [16562462720,15780212736]} +{"t": 1791055752.120, "mem_avail_kib": 27211044, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055753.162, "mem_avail_kib": 27213464, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055754.208, "mem_avail_kib": 27199404, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055755.250, "mem_avail_kib": 27203928, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055756.290, "mem_avail_kib": 27205276, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055757.330, "mem_avail_kib": 27215248, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055758.370, "mem_avail_kib": 27212892, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055759.406, "mem_avail_kib": 27202072, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055760.448, "mem_avail_kib": 27183044, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055761.486, "mem_avail_kib": 27189404, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055762.524, "mem_avail_kib": 27118668, "swap_free_kib": 7054888, "vram_used": [16562462720,15780212736]} +{"t": 1791055763.564, "mem_avail_kib": 27119428, "swap_free_kib": 7055144, "vram_used": [16562462720,15780212736]} +{"t": 1791055764.602, "mem_avail_kib": 27111956, "swap_free_kib": 7055144, "vram_used": [16562462720,15780212736]} +{"t": 1791055765.640, "mem_avail_kib": 27118060, "swap_free_kib": 7055400, "vram_used": [16562462720,15780212736]} +{"t": 1791055766.680, "mem_avail_kib": 27101512, "swap_free_kib": 7055400, "vram_used": [16562462720,15780212736]} +{"t": 1791055767.717, "mem_avail_kib": 27059700, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055768.756, "mem_avail_kib": 27064220, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055769.795, "mem_avail_kib": 27077464, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055770.834, "mem_avail_kib": 27079996, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055771.871, "mem_avail_kib": 27085352, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055772.911, "mem_avail_kib": 27073280, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055773.951, "mem_avail_kib": 27069192, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055774.989, "mem_avail_kib": 27074492, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055776.026, "mem_avail_kib": 27080564, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055777.069, "mem_avail_kib": 27069436, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055778.108, "mem_avail_kib": 27042728, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055779.148, "mem_avail_kib": 27050112, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055780.187, "mem_avail_kib": 27055592, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055781.225, "mem_avail_kib": 27052344, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055782.264, "mem_avail_kib": 27057472, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055783.301, "mem_avail_kib": 27064884, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055784.338, "mem_avail_kib": 27060428, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055785.378, "mem_avail_kib": 27071728, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055786.415, "mem_avail_kib": 27068660, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055787.454, "mem_avail_kib": 27080756, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055788.492, "mem_avail_kib": 27085204, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055789.530, "mem_avail_kib": 27073348, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055790.571, "mem_avail_kib": 27073200, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055791.610, "mem_avail_kib": 27084916, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055792.648, "mem_avail_kib": 27089456, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055793.687, "mem_avail_kib": 27077496, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055794.722, "mem_avail_kib": 27080172, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055795.759, "mem_avail_kib": 27085100, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055796.800, "mem_avail_kib": 26962752, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055797.837, "mem_avail_kib": 26968120, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055798.878, "mem_avail_kib": 26960616, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055799.914, "mem_avail_kib": 26948040, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055800.951, "mem_avail_kib": 26952144, "swap_free_kib": 7055656, "vram_used": [16562462720,15780212736]} +{"t": 1791055801.989, "mem_avail_kib": 26953992, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055803.028, "mem_avail_kib": 26960532, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055804.067, "mem_avail_kib": 26965552, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055805.106, "mem_avail_kib": 26974128, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055806.144, "mem_avail_kib": 26972560, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055807.183, "mem_avail_kib": 26975264, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055808.221, "mem_avail_kib": 26982524, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055809.259, "mem_avail_kib": 27194788, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055810.295, "mem_avail_kib": 27192136, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055811.334, "mem_avail_kib": 27194644, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055812.370, "mem_avail_kib": 27187420, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055813.411, "mem_avail_kib": 27187204, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055814.448, "mem_avail_kib": 27188332, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055815.483, "mem_avail_kib": 27177640, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055816.520, "mem_avail_kib": 27174588, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055817.559, "mem_avail_kib": 27176848, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055818.601, "mem_avail_kib": 27182692, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055819.642, "mem_avail_kib": 27187836, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055820.684, "mem_avail_kib": 27195216, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055821.724, "mem_avail_kib": 27199644, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055822.763, "mem_avail_kib": 27191188, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055823.802, "mem_avail_kib": 27196408, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055824.838, "mem_avail_kib": 27197040, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055825.874, "mem_avail_kib": 27201972, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055826.913, "mem_avail_kib": 27185608, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055827.953, "mem_avail_kib": 27191132, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055828.996, "mem_avail_kib": 27184156, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055830.037, "mem_avail_kib": 27195604, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055831.076, "mem_avail_kib": 27198932, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055832.113, "mem_avail_kib": 27203004, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055833.153, "mem_avail_kib": 27195552, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055834.195, "mem_avail_kib": 27181956, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055835.233, "mem_avail_kib": 27174912, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055836.268, "mem_avail_kib": 27177720, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055837.305, "mem_avail_kib": 27096924, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055838.343, "mem_avail_kib": 27066736, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055839.384, "mem_avail_kib": 27068032, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055840.422, "mem_avail_kib": 27064496, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055841.460, "mem_avail_kib": 27077312, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055842.497, "mem_avail_kib": 27020740, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055843.534, "mem_avail_kib": 27012660, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055844.573, "mem_avail_kib": 27017972, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055845.612, "mem_avail_kib": 27028316, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055846.649, "mem_avail_kib": 27037696, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055847.687, "mem_avail_kib": 27048544, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055848.726, "mem_avail_kib": 27051524, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055849.763, "mem_avail_kib": 27057704, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055850.799, "mem_avail_kib": 27064040, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055851.838, "mem_avail_kib": 27062364, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055852.875, "mem_avail_kib": 27069208, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055853.914, "mem_avail_kib": 27059192, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055854.954, "mem_avail_kib": 27057308, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055855.992, "mem_avail_kib": 27062296, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055857.031, "mem_avail_kib": 27071592, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055858.067, "mem_avail_kib": 27075048, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055859.109, "mem_avail_kib": 27076368, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055860.147, "mem_avail_kib": 27079348, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055861.185, "mem_avail_kib": 27076916, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055862.221, "mem_avail_kib": 27080080, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055863.258, "mem_avail_kib": 27087536, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055864.296, "mem_avail_kib": 27086868, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055865.334, "mem_avail_kib": 27078000, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055866.370, "mem_avail_kib": 27022304, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055867.407, "mem_avail_kib": 27016408, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055868.444, "mem_avail_kib": 27022060, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055869.483, "mem_avail_kib": 27025664, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055870.521, "mem_avail_kib": 27017064, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055871.559, "mem_avail_kib": 26952836, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055872.594, "mem_avail_kib": 26957724, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055873.631, "mem_avail_kib": 26959336, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055874.667, "mem_avail_kib": 26956340, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055875.706, "mem_avail_kib": 26956024, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055876.744, "mem_avail_kib": 26957508, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055877.782, "mem_avail_kib": 26961868, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055878.820, "mem_avail_kib": 26956108, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055879.859, "mem_avail_kib": 26964524, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055880.896, "mem_avail_kib": 26957848, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055881.938, "mem_avail_kib": 26961056, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055882.977, "mem_avail_kib": 26965252, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055884.014, "mem_avail_kib": 26967340, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055885.053, "mem_avail_kib": 26963848, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055886.089, "mem_avail_kib": 26960116, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055887.125, "mem_avail_kib": 26952072, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055888.163, "mem_avail_kib": 26946456, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055889.200, "mem_avail_kib": 26949076, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055890.237, "mem_avail_kib": 26950316, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055891.274, "mem_avail_kib": 26944588, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055892.311, "mem_avail_kib": 26946096, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055893.350, "mem_avail_kib": 26950504, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055894.388, "mem_avail_kib": 26959364, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055895.426, "mem_avail_kib": 26897296, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055896.462, "mem_avail_kib": 26886288, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055897.504, "mem_avail_kib": 26887292, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055898.546, "mem_avail_kib": 26893456, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055899.585, "mem_avail_kib": 26867416, "swap_free_kib": 7055912, "vram_used": [16562462720,15780212736]} +{"t": 1791055900.622, "mem_avail_kib": 26882632, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055901.658, "mem_avail_kib": 26835604, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055902.695, "mem_avail_kib": 26835292, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055903.733, "mem_avail_kib": 26841128, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055904.771, "mem_avail_kib": 26847472, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055905.805, "mem_avail_kib": 26834784, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055906.842, "mem_avail_kib": 26833228, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055907.882, "mem_avail_kib": 26829424, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055908.919, "mem_avail_kib": 26833128, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055909.957, "mem_avail_kib": 26848500, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055910.996, "mem_avail_kib": 26849664, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055912.033, "mem_avail_kib": 26842484, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055913.072, "mem_avail_kib": 26840556, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055914.112, "mem_avail_kib": 26842864, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055915.149, "mem_avail_kib": 26833392, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055916.189, "mem_avail_kib": 26837860, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055917.227, "mem_avail_kib": 26837744, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055918.265, "mem_avail_kib": 26842960, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055919.307, "mem_avail_kib": 26843360, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055920.346, "mem_avail_kib": 26847904, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055921.386, "mem_avail_kib": 26845176, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055922.426, "mem_avail_kib": 26838244, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055923.465, "mem_avail_kib": 26833300, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055924.502, "mem_avail_kib": 26830768, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055925.539, "mem_avail_kib": 26755348, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055926.575, "mem_avail_kib": 26758488, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055927.615, "mem_avail_kib": 26766984, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055928.652, "mem_avail_kib": 26770060, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055929.691, "mem_avail_kib": 26772532, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055930.727, "mem_avail_kib": 26782348, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055931.765, "mem_avail_kib": 26733304, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055932.803, "mem_avail_kib": 26731644, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055933.839, "mem_avail_kib": 26733236, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055934.877, "mem_avail_kib": 26737008, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055935.916, "mem_avail_kib": 26729460, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055936.954, "mem_avail_kib": 26729484, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055937.992, "mem_avail_kib": 26733140, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055939.030, "mem_avail_kib": 26733180, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055940.070, "mem_avail_kib": 26735396, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055941.106, "mem_avail_kib": 26735716, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055942.143, "mem_avail_kib": 26728044, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055943.184, "mem_avail_kib": 26728068, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055944.225, "mem_avail_kib": 26736532, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055945.263, "mem_avail_kib": 26722368, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055946.299, "mem_avail_kib": 26717752, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055947.336, "mem_avail_kib": 26712156, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055948.377, "mem_avail_kib": 26707700, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055949.416, "mem_avail_kib": 26700744, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055950.456, "mem_avail_kib": 26704772, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055951.498, "mem_avail_kib": 26720240, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055952.540, "mem_avail_kib": 26723660, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055953.580, "mem_avail_kib": 26725448, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055954.616, "mem_avail_kib": 26733992, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055955.652, "mem_avail_kib": 26726104, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055956.688, "mem_avail_kib": 26661972, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055957.727, "mem_avail_kib": 26668216, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055958.765, "mem_avail_kib": 26667440, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055959.803, "mem_avail_kib": 26665844, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055960.844, "mem_avail_kib": 26669992, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055961.884, "mem_avail_kib": 26670312, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055962.923, "mem_avail_kib": 26620728, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055963.961, "mem_avail_kib": 26618116, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055964.996, "mem_avail_kib": 26609020, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055966.034, "mem_avail_kib": 26603424, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055967.071, "mem_avail_kib": 26601940, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055968.108, "mem_avail_kib": 26601968, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055969.149, "mem_avail_kib": 26606744, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055970.187, "mem_avail_kib": 26612860, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055971.225, "mem_avail_kib": 26603300, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055972.263, "mem_avail_kib": 26617248, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055973.302, "mem_avail_kib": 26601532, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055974.339, "mem_avail_kib": 26595316, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055975.378, "mem_avail_kib": 26588948, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055976.417, "mem_avail_kib": 26581960, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055977.454, "mem_avail_kib": 26580832, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055978.492, "mem_avail_kib": 26587904, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055979.529, "mem_avail_kib": 26580052, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055980.573, "mem_avail_kib": 26592072, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055981.612, "mem_avail_kib": 26602408, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055982.651, "mem_avail_kib": 26609672, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055983.689, "mem_avail_kib": 26599384, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055984.726, "mem_avail_kib": 26600456, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055985.764, "mem_avail_kib": 26601536, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055986.800, "mem_avail_kib": 26605764, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055987.838, "mem_avail_kib": 26601476, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055988.876, "mem_avail_kib": 26539840, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055989.917, "mem_avail_kib": 26549632, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055990.960, "mem_avail_kib": 26554508, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055991.996, "mem_avail_kib": 26557172, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055993.035, "mem_avail_kib": 26559132, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055994.071, "mem_avail_kib": 26558932, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055995.111, "mem_avail_kib": 26508892, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055996.151, "mem_avail_kib": 26505396, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055997.186, "mem_avail_kib": 26500328, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055998.226, "mem_avail_kib": 26503400, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791055999.264, "mem_avail_kib": 26508472, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791056000.303, "mem_avail_kib": 26499316, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791056001.339, "mem_avail_kib": 26503112, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791056002.377, "mem_avail_kib": 26500700, "swap_free_kib": 7056168, "vram_used": [16562462720,15780212736]} +{"t": 1791056003.414, "mem_avail_kib": 26494204, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056004.453, "mem_avail_kib": 26475432, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056005.490, "mem_avail_kib": 26478272, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056006.530, "mem_avail_kib": 26469108, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056007.570, "mem_avail_kib": 26480516, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056008.610, "mem_avail_kib": 26488048, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056009.648, "mem_avail_kib": 26497012, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056010.686, "mem_avail_kib": 26503304, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056011.722, "mem_avail_kib": 26505548, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056012.761, "mem_avail_kib": 26499584, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056013.806, "mem_avail_kib": 26499544, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056014.846, "mem_avail_kib": 26499948, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056015.886, "mem_avail_kib": 26496844, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056016.924, "mem_avail_kib": 26503252, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056017.961, "mem_avail_kib": 26501492, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056018.998, "mem_avail_kib": 26506836, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056020.034, "mem_avail_kib": 26502124, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056021.069, "mem_avail_kib": 26502204, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056022.106, "mem_avail_kib": 26418472, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056023.144, "mem_avail_kib": 26422932, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056024.180, "mem_avail_kib": 26416784, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056025.220, "mem_avail_kib": 26422548, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056026.259, "mem_avail_kib": 26425028, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056027.294, "mem_avail_kib": 26417928, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056028.331, "mem_avail_kib": 26374484, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056029.370, "mem_avail_kib": 26475908, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056030.406, "mem_avail_kib": 26477268, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056031.444, "mem_avail_kib": 26470940, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056032.484, "mem_avail_kib": 26483548, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056033.522, "mem_avail_kib": 26494140, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056034.560, "mem_avail_kib": 26492772, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056035.601, "mem_avail_kib": 26484268, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056036.640, "mem_avail_kib": 26483784, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056037.678, "mem_avail_kib": 26474496, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056038.714, "mem_avail_kib": 26474740, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056039.750, "mem_avail_kib": 26468500, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056040.786, "mem_avail_kib": 26474560, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056041.823, "mem_avail_kib": 26473304, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056042.862, "mem_avail_kib": 26481400, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056043.902, "mem_avail_kib": 26489612, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056044.941, "mem_avail_kib": 26497944, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056045.978, "mem_avail_kib": 26502496, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056047.020, "mem_avail_kib": 26492140, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056048.059, "mem_avail_kib": 26491252, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056049.100, "mem_avail_kib": 26496820, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056050.138, "mem_avail_kib": 26502980, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056051.177, "mem_avail_kib": 26502276, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056052.216, "mem_avail_kib": 26503716, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056053.256, "mem_avail_kib": 26508472, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056054.295, "mem_avail_kib": 26507916, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056055.340, "mem_avail_kib": 26505080, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056056.380, "mem_avail_kib": 26370928, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056057.417, "mem_avail_kib": 26375044, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056058.455, "mem_avail_kib": 26375952, "swap_free_kib": 7056424, "vram_used": [16562462720,15780212736]} +{"t": 1791056059.493, "mem_avail_kib": 26388432, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056060.529, "mem_avail_kib": 26399116, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056061.567, "mem_avail_kib": 26401792, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056062.604, "mem_avail_kib": 26410992, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056063.642, "mem_avail_kib": 26428944, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056064.681, "mem_avail_kib": 26443564, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056065.717, "mem_avail_kib": 26440300, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056066.757, "mem_avail_kib": 26445148, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056067.795, "mem_avail_kib": 26447432, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056068.836, "mem_avail_kib": 26459360, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056069.874, "mem_avail_kib": 27160652, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056070.912, "mem_avail_kib": 27153184, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056071.949, "mem_avail_kib": 27156136, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056072.989, "mem_avail_kib": 27163684, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056074.027, "mem_avail_kib": 27160772, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056075.065, "mem_avail_kib": 27168152, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056076.102, "mem_avail_kib": 27152460, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056077.142, "mem_avail_kib": 27161560, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056078.180, "mem_avail_kib": 27156604, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056079.220, "mem_avail_kib": 27155992, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056080.261, "mem_avail_kib": 27148936, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056081.299, "mem_avail_kib": 27154572, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056082.335, "mem_avail_kib": 27135620, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056083.372, "mem_avail_kib": 27147816, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056084.413, "mem_avail_kib": 27152776, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056085.451, "mem_avail_kib": 27159968, "swap_free_kib": 7056680, "vram_used": [16562462720,15780212736]} +{"t": 1791056086.486, "mem_avail_kib": 27163956, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056087.524, "mem_avail_kib": 27164560, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056088.562, "mem_avail_kib": 27160000, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056089.602, "mem_avail_kib": 27156140, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056090.643, "mem_avail_kib": 27162940, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056091.682, "mem_avail_kib": 27167484, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056092.719, "mem_avail_kib": 27172256, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056093.757, "mem_avail_kib": 27179256, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056094.796, "mem_avail_kib": 27172512, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056095.833, "mem_avail_kib": 27161336, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056096.875, "mem_avail_kib": 27093708, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056097.919, "mem_avail_kib": 27099928, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056098.958, "mem_avail_kib": 27105480, "swap_free_kib": 7057192, "vram_used": [16562462720,15780212736]} +{"t": 1791056099.997, "mem_avail_kib": 27107512, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056101.034, "mem_avail_kib": 27105132, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056102.073, "mem_avail_kib": 27057848, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056103.110, "mem_avail_kib": 27054940, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056104.149, "mem_avail_kib": 27061248, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056105.186, "mem_avail_kib": 27052944, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056106.224, "mem_avail_kib": 27044384, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056107.264, "mem_avail_kib": 27051396, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056108.301, "mem_avail_kib": 27057152, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056109.342, "mem_avail_kib": 27047636, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056110.380, "mem_avail_kib": 27044136, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056111.416, "mem_avail_kib": 27051244, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056112.452, "mem_avail_kib": 27037292, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056113.488, "mem_avail_kib": 27041392, "swap_free_kib": 7057704, "vram_used": [16562462720,15780212736]} +{"t": 1791056114.526, "mem_avail_kib": 27052100, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056115.562, "mem_avail_kib": 27060292, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056116.603, "mem_avail_kib": 27052104, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056117.642, "mem_avail_kib": 27053824, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056118.682, "mem_avail_kib": 27056972, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056119.722, "mem_avail_kib": 27060620, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056120.763, "mem_avail_kib": 27058968, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056121.800, "mem_avail_kib": 27053384, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056122.837, "mem_avail_kib": 27049972, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056123.874, "mem_avail_kib": 27048216, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056124.911, "mem_avail_kib": 27045528, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056125.945, "mem_avail_kib": 26974804, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056126.982, "mem_avail_kib": 26973428, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056128.020, "mem_avail_kib": 26981284, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056129.063, "mem_avail_kib": 26984344, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056130.099, "mem_avail_kib": 26974396, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056131.139, "mem_avail_kib": 26928388, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056132.176, "mem_avail_kib": 26921292, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056133.214, "mem_avail_kib": 26915944, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056134.251, "mem_avail_kib": 26923340, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056135.288, "mem_avail_kib": 26926644, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056136.325, "mem_avail_kib": 26922148, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056137.366, "mem_avail_kib": 26926284, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056138.404, "mem_avail_kib": 26935284, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056139.442, "mem_avail_kib": 26934052, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056140.480, "mem_avail_kib": 26932784, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056141.519, "mem_avail_kib": 26937600, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056142.558, "mem_avail_kib": 26947676, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056143.594, "mem_avail_kib": 26917988, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056144.632, "mem_avail_kib": 26926396, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056145.670, "mem_avail_kib": 26924076, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056146.708, "mem_avail_kib": 26932924, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056147.746, "mem_avail_kib": 26936096, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056148.782, "mem_avail_kib": 26927864, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056149.819, "mem_avail_kib": 26934088, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056150.859, "mem_avail_kib": 26938940, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056151.897, "mem_avail_kib": 26936200, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056152.936, "mem_avail_kib": 26930348, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056153.975, "mem_avail_kib": 26935920, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056155.015, "mem_avail_kib": 26856312, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056156.052, "mem_avail_kib": 26859028, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056157.088, "mem_avail_kib": 26862032, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056158.125, "mem_avail_kib": 26874388, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056159.164, "mem_avail_kib": 26875240, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056160.202, "mem_avail_kib": 26874388, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056161.240, "mem_avail_kib": 26827160, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056162.280, "mem_avail_kib": 26830064, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056163.322, "mem_avail_kib": 26829156, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056164.360, "mem_avail_kib": 26827184, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056165.397, "mem_avail_kib": 26827320, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056166.433, "mem_avail_kib": 26828344, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056167.470, "mem_avail_kib": 26830900, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056168.506, "mem_avail_kib": 26835156, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056169.541, "mem_avail_kib": 26822744, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056170.579, "mem_avail_kib": 26825920, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056171.615, "mem_avail_kib": 26832956, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056172.657, "mem_avail_kib": 26830464, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056173.697, "mem_avail_kib": 26830576, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056174.734, "mem_avail_kib": 26834536, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056175.773, "mem_avail_kib": 26834636, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056176.811, "mem_avail_kib": 26838456, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056177.847, "mem_avail_kib": 26845532, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056178.885, "mem_avail_kib": 26849912, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056179.924, "mem_avail_kib": 26842688, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056180.965, "mem_avail_kib": 26845188, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056182.004, "mem_avail_kib": 26848964, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056183.045, "mem_avail_kib": 26858260, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056184.085, "mem_avail_kib": 26851808, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056185.122, "mem_avail_kib": 26794952, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056186.159, "mem_avail_kib": 26770972, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056187.199, "mem_avail_kib": 26772204, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056188.239, "mem_avail_kib": 26770428, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056189.274, "mem_avail_kib": 26777372, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056190.313, "mem_avail_kib": 26772236, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056191.350, "mem_avail_kib": 26722336, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056192.390, "mem_avail_kib": 26723520, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056193.428, "mem_avail_kib": 26728316, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056194.466, "mem_avail_kib": 26728640, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056195.509, "mem_avail_kib": 26717428, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056196.547, "mem_avail_kib": 26720120, "swap_free_kib": 7057960, "vram_used": [16562462720,15780212736]} +{"t": 1791056197.586, "mem_avail_kib": 26727212, "swap_free_kib": 7058216, "vram_used": [16562462720,15780212736]} +{"t": 1791056198.624, "mem_avail_kib": 26719348, "swap_free_kib": 7058216, "vram_used": [16562462720,15780212736]} +{"t": 1791056199.662, "mem_avail_kib": 26726360, "swap_free_kib": 7058216, "vram_used": [16562462720,15780212736]} +{"t": 1791056200.702, "mem_avail_kib": 26727572, "swap_free_kib": 7058216, "vram_used": [16562462720,15780212736]} +{"t": 1791056201.740, "mem_avail_kib": 26726808, "swap_free_kib": 7058216, "vram_used": [16562462720,15780212736]} +{"t": 1791056202.777, "mem_avail_kib": 26710352, "swap_free_kib": 7058216, "vram_used": [16562462720,15780212736]} +{"t": 1791056203.817, "mem_avail_kib": 26715956, "swap_free_kib": 7058216, "vram_used": [16562462720,15780212736]} +{"t": 1791056204.856, "mem_avail_kib": 26686244, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056205.892, "mem_avail_kib": 26692748, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056206.928, "mem_avail_kib": 26691344, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056207.967, "mem_avail_kib": 26706640, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056209.007, "mem_avail_kib": 26711480, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056210.046, "mem_avail_kib": 26714560, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056211.089, "mem_avail_kib": 26715768, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056212.127, "mem_avail_kib": 26714748, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056213.166, "mem_avail_kib": 26716824, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056214.205, "mem_avail_kib": 26722028, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056215.242, "mem_avail_kib": 26719692, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056216.281, "mem_avail_kib": 26661052, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056217.316, "mem_avail_kib": 26629380, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056218.353, "mem_avail_kib": 26627628, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056219.389, "mem_avail_kib": 26629080, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056220.430, "mem_avail_kib": 26634212, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056221.468, "mem_avail_kib": 26627980, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056222.508, "mem_avail_kib": 26578936, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056223.546, "mem_avail_kib": 26591204, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056224.588, "mem_avail_kib": 26593616, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056225.627, "mem_avail_kib": 26594836, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056226.665, "mem_avail_kib": 26589616, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056227.698, "mem_avail_kib": 26599280, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056228.736, "mem_avail_kib": 26600436, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056229.774, "mem_avail_kib": 26603676, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056230.813, "mem_avail_kib": 26605368, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056231.851, "mem_avail_kib": 26606572, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056232.888, "mem_avail_kib": 26601284, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056233.926, "mem_avail_kib": 26606720, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056234.967, "mem_avail_kib": 26618212, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056236.005, "mem_avail_kib": 26608300, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056237.044, "mem_avail_kib": 26604076, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056238.081, "mem_avail_kib": 26603260, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056239.119, "mem_avail_kib": 26598644, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056240.158, "mem_avail_kib": 26603504, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056241.197, "mem_avail_kib": 26608884, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056242.237, "mem_avail_kib": 26600264, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056243.276, "mem_avail_kib": 26590872, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056244.317, "mem_avail_kib": 26595832, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056245.357, "mem_avail_kib": 26603048, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056246.395, "mem_avail_kib": 26608292, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056247.432, "mem_avail_kib": 26600056, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056248.473, "mem_avail_kib": 26522500, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056249.511, "mem_avail_kib": 26514572, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056250.549, "mem_avail_kib": 26515632, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056251.585, "mem_avail_kib": 26524244, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056252.624, "mem_avail_kib": 26524988, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056253.666, "mem_avail_kib": 26524348, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056254.703, "mem_avail_kib": 26516788, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056255.740, "mem_avail_kib": 26469156, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056256.780, "mem_avail_kib": 26469304, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056257.816, "mem_avail_kib": 26461976, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056258.853, "mem_avail_kib": 26462492, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056259.890, "mem_avail_kib": 26466816, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056260.927, "mem_avail_kib": 26451764, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056261.966, "mem_avail_kib": 26455332, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056263.004, "mem_avail_kib": 26462756, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056264.040, "mem_avail_kib": 26465096, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056265.077, "mem_avail_kib": 26459236, "swap_free_kib": 7058472, "vram_used": [16562462720,15780212736]} +{"t": 1791056266.117, "mem_avail_kib": 26445820, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056267.154, "mem_avail_kib": 26454668, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056268.190, "mem_avail_kib": 26466980, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056269.229, "mem_avail_kib": 26464116, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056270.267, "mem_avail_kib": 26466836, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056271.306, "mem_avail_kib": 26468528, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056272.347, "mem_avail_kib": 26471008, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056273.385, "mem_avail_kib": 26463288, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056274.424, "mem_avail_kib": 26465856, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056275.463, "mem_avail_kib": 26485364, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056276.500, "mem_avail_kib": 26483660, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056277.540, "mem_avail_kib": 26489328, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056278.580, "mem_avail_kib": 26493088, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056279.622, "mem_avail_kib": 26484592, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056280.659, "mem_avail_kib": 26474480, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056281.695, "mem_avail_kib": 26409780, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056282.733, "mem_avail_kib": 26404464, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056283.771, "mem_avail_kib": 26405244, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056284.810, "mem_avail_kib": 26409472, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056285.849, "mem_avail_kib": 26410444, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056286.886, "mem_avail_kib": 26409880, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056287.922, "mem_avail_kib": 26394588, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056288.958, "mem_avail_kib": 26407828, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056289.996, "mem_avail_kib": 26419372, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056291.034, "mem_avail_kib": 26421544, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056292.074, "mem_avail_kib": 26441988, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056293.110, "mem_avail_kib": 26451816, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056294.149, "mem_avail_kib": 26449856, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056295.192, "mem_avail_kib": 26460632, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056296.230, "mem_avail_kib": 26468496, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056297.268, "mem_avail_kib": 26476476, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056298.306, "mem_avail_kib": 26483440, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056299.344, "mem_avail_kib": 26481528, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056300.383, "mem_avail_kib": 26472552, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056301.422, "mem_avail_kib": 26475336, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056302.459, "mem_avail_kib": 26471252, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056303.495, "mem_avail_kib": 26474984, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056304.532, "mem_avail_kib": 26483512, "swap_free_kib": 7058728, "vram_used": [16562462720,15780212736]} +{"t": 1791056305.569, "mem_avail_kib": 26487368, "swap_free_kib": 7058984, "vram_used": [16562462720,15780212736]} +{"t": 1791056306.611, "mem_avail_kib": 26480544, "swap_free_kib": 7058984, "vram_used": [16562462720,15780212736]} +{"t": 1791056307.649, "mem_avail_kib": 26491436, "swap_free_kib": 7058984, "vram_used": [16562462720,15780212736]} +{"t": 1791056308.686, "mem_avail_kib": 26500192, "swap_free_kib": 7058984, "vram_used": [16562462720,15780212736]} +{"t": 1791056309.728, "mem_avail_kib": 26503584, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056310.768, "mem_avail_kib": 26502732, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056311.806, "mem_avail_kib": 26501228, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056312.844, "mem_avail_kib": 26496984, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056313.880, "mem_avail_kib": 26487656, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056314.921, "mem_avail_kib": 26494244, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056315.959, "mem_avail_kib": 26431008, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056316.997, "mem_avail_kib": 26367740, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056318.038, "mem_avail_kib": 26378032, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056319.077, "mem_avail_kib": 26389748, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056320.111, "mem_avail_kib": 26396336, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056321.148, "mem_avail_kib": 26409160, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056322.187, "mem_avail_kib": 26423448, "swap_free_kib": 7059240, "vram_used": [16562462720,15780212736]} +{"t": 1791056323.226, "mem_avail_kib": 26427008, "swap_free_kib": 7059752, "vram_used": [16562462720,15780212736]} +{"t": 1791056324.262, "mem_avail_kib": 26436748, "swap_free_kib": 7059752, "vram_used": [16562462720,15780212736]} +{"t": 1791056325.298, "mem_avail_kib": 26436444, "swap_free_kib": 7059752, "vram_used": [16562462720,15780212736]} +{"t": 1791056326.338, "mem_avail_kib": 26419732, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056327.376, "mem_avail_kib": 26418196, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056328.414, "mem_avail_kib": 27107208, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056329.453, "mem_avail_kib": 27114624, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056330.493, "mem_avail_kib": 27109288, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056331.531, "mem_avail_kib": 27115992, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056332.567, "mem_avail_kib": 27128344, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056333.603, "mem_avail_kib": 27130812, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056334.639, "mem_avail_kib": 27139632, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056335.677, "mem_avail_kib": 27142536, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056336.718, "mem_avail_kib": 27144676, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056337.755, "mem_avail_kib": 27157084, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056338.794, "mem_avail_kib": 27163160, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056339.831, "mem_avail_kib": 27161192, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056340.869, "mem_avail_kib": 27167648, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056341.907, "mem_avail_kib": 27164496, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056342.942, "mem_avail_kib": 27166156, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056343.979, "mem_avail_kib": 27159380, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056345.020, "mem_avail_kib": 27171320, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056346.059, "mem_avail_kib": 27172392, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056347.095, "mem_avail_kib": 27168528, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056348.134, "mem_avail_kib": 27172960, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056349.175, "mem_avail_kib": 27167676, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056350.213, "mem_avail_kib": 27161588, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056351.250, "mem_avail_kib": 27165364, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056352.289, "mem_avail_kib": 27156116, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056353.327, "mem_avail_kib": 27157784, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056354.365, "mem_avail_kib": 27158216, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056355.405, "mem_avail_kib": 27157900, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056356.443, "mem_avail_kib": 27085888, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056357.482, "mem_avail_kib": 27093184, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056358.519, "mem_avail_kib": 27097112, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056359.557, "mem_avail_kib": 27092320, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056360.598, "mem_avail_kib": 27083200, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056361.636, "mem_avail_kib": 27031248, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056362.674, "mem_avail_kib": 27039524, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056363.716, "mem_avail_kib": 27049964, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056364.752, "mem_avail_kib": 27052340, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056365.789, "mem_avail_kib": 27054632, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056366.826, "mem_avail_kib": 27055652, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056367.864, "mem_avail_kib": 27043812, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056368.903, "mem_avail_kib": 27043312, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056369.944, "mem_avail_kib": 27037444, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056370.980, "mem_avail_kib": 27041392, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056372.021, "mem_avail_kib": 27039728, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056373.060, "mem_avail_kib": 27049312, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056374.097, "mem_avail_kib": 27052924, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056375.134, "mem_avail_kib": 27053828, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056376.169, "mem_avail_kib": 27056776, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056377.205, "mem_avail_kib": 27046544, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056378.241, "mem_avail_kib": 27056468, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056379.279, "mem_avail_kib": 27058276, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056380.317, "mem_avail_kib": 27064068, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056381.354, "mem_avail_kib": 27059344, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056382.390, "mem_avail_kib": 27072476, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056383.425, "mem_avail_kib": 27065612, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056384.463, "mem_avail_kib": 26998608, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056385.500, "mem_avail_kib": 26991096, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056386.536, "mem_avail_kib": 26991280, "swap_free_kib": 7060008, "vram_used": [16562462720,15780212736]} +{"t": 1791056387.573, "mem_avail_kib": 26952792, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056388.610, "mem_avail_kib": 26957176, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056389.647, "mem_avail_kib": 26966136, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056390.684, "mem_avail_kib": 26924604, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056391.724, "mem_avail_kib": 26929364, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056392.764, "mem_avail_kib": 26931860, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056393.805, "mem_avail_kib": 26933268, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056394.841, "mem_avail_kib": 26925500, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056395.881, "mem_avail_kib": 26938012, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056396.918, "mem_avail_kib": 26929728, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056397.955, "mem_avail_kib": 26932664, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056398.994, "mem_avail_kib": 26918164, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056400.031, "mem_avail_kib": 26929620, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056401.068, "mem_avail_kib": 26933580, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056402.106, "mem_avail_kib": 26939924, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056403.145, "mem_avail_kib": 26930428, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056404.184, "mem_avail_kib": 26938356, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056405.223, "mem_avail_kib": 26943280, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056406.260, "mem_avail_kib": 26946776, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056407.295, "mem_avail_kib": 26936652, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056408.331, "mem_avail_kib": 26941648, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056409.366, "mem_avail_kib": 26939432, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056410.404, "mem_avail_kib": 26933112, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056411.442, "mem_avail_kib": 26941192, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056412.482, "mem_avail_kib": 26934848, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056413.520, "mem_avail_kib": 26937536, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056414.557, "mem_avail_kib": 26862620, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056415.597, "mem_avail_kib": 26867168, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056416.634, "mem_avail_kib": 26860468, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056417.672, "mem_avail_kib": 26860476, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056418.716, "mem_avail_kib": 26859876, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056419.754, "mem_avail_kib": 26816916, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056420.791, "mem_avail_kib": 26814644, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056421.828, "mem_avail_kib": 26819700, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056422.867, "mem_avail_kib": 26830876, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056423.907, "mem_avail_kib": 26831360, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056424.948, "mem_avail_kib": 26829344, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056425.987, "mem_avail_kib": 26834072, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056427.024, "mem_avail_kib": 26834624, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056428.062, "mem_avail_kib": 26826336, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056429.098, "mem_avail_kib": 26823144, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056430.135, "mem_avail_kib": 26817984, "swap_free_kib": 7060264, "vram_used": [16562462720,15780212736]} +{"t": 1791056431.173, "mem_avail_kib": 26825216, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056432.209, "mem_avail_kib": 26819872, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056433.248, "mem_avail_kib": 26812552, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056434.285, "mem_avail_kib": 26812104, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056435.327, "mem_avail_kib": 26810664, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056436.366, "mem_avail_kib": 26818768, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056437.404, "mem_avail_kib": 26827684, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056438.441, "mem_avail_kib": 26825888, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056439.479, "mem_avail_kib": 26827940, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056440.519, "mem_avail_kib": 26823660, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056441.558, "mem_avail_kib": 26820544, "swap_free_kib": 7060520, "vram_used": [16562462720,15780212736]} +{"t": 1791056442.594, "mem_avail_kib": 26825624, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056443.632, "mem_avail_kib": 26816164, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056444.670, "mem_avail_kib": 26748920, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056445.706, "mem_avail_kib": 26759020, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056446.743, "mem_avail_kib": 26761728, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056447.779, "mem_avail_kib": 26756980, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056448.816, "mem_avail_kib": 26723176, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056449.853, "mem_avail_kib": 26727756, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056450.895, "mem_avail_kib": 26690000, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056451.937, "mem_avail_kib": 26688288, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056452.977, "mem_avail_kib": 26686608, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056454.016, "mem_avail_kib": 26690356, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056455.055, "mem_avail_kib": 26693484, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056456.093, "mem_avail_kib": 26690756, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056457.132, "mem_avail_kib": 26687712, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056458.166, "mem_avail_kib": 26703320, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056459.204, "mem_avail_kib": 26695548, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056460.245, "mem_avail_kib": 26699980, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056461.284, "mem_avail_kib": 26693664, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056462.323, "mem_avail_kib": 26703528, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056463.360, "mem_avail_kib": 26705700, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056464.395, "mem_avail_kib": 26704740, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056465.431, "mem_avail_kib": 26707748, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056466.469, "mem_avail_kib": 26706972, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056467.507, "mem_avail_kib": 26712500, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056468.545, "mem_avail_kib": 26687612, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056469.582, "mem_avail_kib": 26693524, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056470.620, "mem_avail_kib": 26688688, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056471.661, "mem_avail_kib": 26687240, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056472.701, "mem_avail_kib": 26684420, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056473.739, "mem_avail_kib": 26696344, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056474.779, "mem_avail_kib": 26701084, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056475.820, "mem_avail_kib": 26625316, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056476.862, "mem_avail_kib": 26632568, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056477.899, "mem_avail_kib": 26631368, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056478.935, "mem_avail_kib": 26643548, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056479.972, "mem_avail_kib": 26646812, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056481.011, "mem_avail_kib": 26649036, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056482.047, "mem_avail_kib": 26597980, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056483.084, "mem_avail_kib": 26597352, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056484.122, "mem_avail_kib": 26601356, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056485.162, "mem_avail_kib": 26600404, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056486.201, "mem_avail_kib": 26591804, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056487.238, "mem_avail_kib": 26594940, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056488.275, "mem_avail_kib": 26589616, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056489.313, "mem_avail_kib": 26595720, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056490.349, "mem_avail_kib": 26586124, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056491.388, "mem_avail_kib": 26585280, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056492.426, "mem_avail_kib": 26595164, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056493.463, "mem_avail_kib": 26599156, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056494.501, "mem_avail_kib": 26591680, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056495.537, "mem_avail_kib": 26584956, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056496.576, "mem_avail_kib": 26581144, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056497.614, "mem_avail_kib": 26596828, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056498.652, "mem_avail_kib": 26606072, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056499.689, "mem_avail_kib": 26607228, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056500.727, "mem_avail_kib": 26596608, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056501.766, "mem_avail_kib": 26602828, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056502.804, "mem_avail_kib": 26584404, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056503.842, "mem_avail_kib": 26594072, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056504.884, "mem_avail_kib": 26606064, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056505.920, "mem_avail_kib": 26612924, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056506.957, "mem_avail_kib": 26614020, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056507.994, "mem_avail_kib": 26529720, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056509.030, "mem_avail_kib": 26510572, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056510.066, "mem_avail_kib": 26494876, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056511.105, "mem_avail_kib": 26503716, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056512.143, "mem_avail_kib": 26509276, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056513.182, "mem_avail_kib": 26512172, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056514.218, "mem_avail_kib": 26468064, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056515.255, "mem_avail_kib": 26462744, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056516.292, "mem_avail_kib": 26459220, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056517.328, "mem_avail_kib": 26458756, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056518.364, "mem_avail_kib": 26468484, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056519.400, "mem_avail_kib": 26467308, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056520.440, "mem_avail_kib": 26474920, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056521.479, "mem_avail_kib": 26465712, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056522.514, "mem_avail_kib": 26457924, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056523.552, "mem_avail_kib": 26458152, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056524.588, "mem_avail_kib": 26467844, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056525.624, "mem_avail_kib": 26473036, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056526.660, "mem_avail_kib": 26476116, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056527.698, "mem_avail_kib": 26470296, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056528.734, "mem_avail_kib": 26478668, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056529.773, "mem_avail_kib": 26480912, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056530.810, "mem_avail_kib": 26473896, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056531.846, "mem_avail_kib": 26483160, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056532.883, "mem_avail_kib": 26494944, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056533.920, "mem_avail_kib": 26490612, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056534.958, "mem_avail_kib": 26491580, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056535.997, "mem_avail_kib": 26492172, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056537.034, "mem_avail_kib": 26481332, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056538.069, "mem_avail_kib": 26477212, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056539.105, "mem_avail_kib": 26484236, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056540.142, "mem_avail_kib": 26480300, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056541.187, "mem_avail_kib": 26413868, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056542.226, "mem_avail_kib": 26419576, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056543.262, "mem_avail_kib": 26419544, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056544.299, "mem_avail_kib": 26417352, "swap_free_kib": 7060776, "vram_used": [16562462720,15780212736]} +{"t": 1791056545.338, "mem_avail_kib": 26410184, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056546.373, "mem_avail_kib": 26411440, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056547.410, "mem_avail_kib": 26364204, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056548.449, "mem_avail_kib": 26429448, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056549.488, "mem_avail_kib": 26442104, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056550.524, "mem_avail_kib": 26445372, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056551.560, "mem_avail_kib": 26444128, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056552.602, "mem_avail_kib": 26447020, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056553.639, "mem_avail_kib": 26449068, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056554.677, "mem_avail_kib": 26459664, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056555.715, "mem_avail_kib": 26464968, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056556.758, "mem_avail_kib": 26466256, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056557.800, "mem_avail_kib": 26475960, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056558.839, "mem_avail_kib": 26470196, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056559.878, "mem_avail_kib": 26470076, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056560.916, "mem_avail_kib": 26470032, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056561.952, "mem_avail_kib": 26473744, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056562.991, "mem_avail_kib": 26483032, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056564.028, "mem_avail_kib": 26476552, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056565.065, "mem_avail_kib": 26478520, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056566.103, "mem_avail_kib": 26480716, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056567.143, "mem_avail_kib": 26483992, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056568.179, "mem_avail_kib": 26482280, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056569.214, "mem_avail_kib": 26474100, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056570.253, "mem_avail_kib": 26466308, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056571.290, "mem_avail_kib": 26456712, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056572.328, "mem_avail_kib": 26460928, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056573.365, "mem_avail_kib": 26455888, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056574.401, "mem_avail_kib": 26459284, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056575.438, "mem_avail_kib": 26330540, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056576.475, "mem_avail_kib": 26333524, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056577.512, "mem_avail_kib": 26345164, "swap_free_kib": 7061032, "vram_used": [16562462720,15780212736]} +{"t": 1791056578.550, "mem_avail_kib": 26356328, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056579.586, "mem_avail_kib": 26368708, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056580.623, "mem_avail_kib": 26378068, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056581.662, "mem_avail_kib": 26536596, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056582.701, "mem_avail_kib": 27246944, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056583.735, "mem_avail_kib": 27246184, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056584.770, "mem_avail_kib": 27246884, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056585.808, "mem_avail_kib": 27249868, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056586.845, "mem_avail_kib": 27264692, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056587.884, "mem_avail_kib": 27278076, "swap_free_kib": 7061288, "vram_used": [16562462720,15780212736]} +{"t": 1791056588.921, "mem_avail_kib": 27278280, "swap_free_kib": 7061544, "vram_used": [16562462720,15780212736]} +{"t": 1791056589.959, "mem_avail_kib": 27286908, "swap_free_kib": 7061544, "vram_used": [16562462720,15780212736]} +{"t": 1791056590.996, "mem_avail_kib": 27280784, "swap_free_kib": 7061544, "vram_used": [16562462720,15780212736]} +{"t": 1791056592.030, "mem_avail_kib": 27284304, "swap_free_kib": 7061544, "vram_used": [16562462720,15780212736]} +{"t": 1791056593.068, "mem_avail_kib": 27289076, "swap_free_kib": 7061544, "vram_used": [16562462720,15780212736]} +{"t": 1791056594.105, "mem_avail_kib": 27295184, "swap_free_kib": 7061544, "vram_used": [16562462720,15780212736]} +{"t": 1791056595.141, "mem_avail_kib": 27295844, "swap_free_kib": 7061544, "vram_used": [16562462720,15780212736]} +{"t": 1791056596.179, "mem_avail_kib": 27300520, "swap_free_kib": 7061544, "vram_used": [16562462720,15780212736]} +{"t": 1791056597.216, "mem_avail_kib": 27308812, "swap_free_kib": 7061544, "vram_used": [16562462720,15780212736]} +{"t": 1791056598.249, "mem_avail_kib": 27309044, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056599.285, "mem_avail_kib": 27293708, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056600.322, "mem_avail_kib": 27290800, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056601.359, "mem_avail_kib": 27299680, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056602.398, "mem_avail_kib": 27287892, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056603.436, "mem_avail_kib": 27281440, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056604.475, "mem_avail_kib": 27283740, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056605.510, "mem_avail_kib": 27287336, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056606.546, "mem_avail_kib": 27291688, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056607.585, "mem_avail_kib": 27298488, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056608.624, "mem_avail_kib": 27293124, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056609.663, "mem_avail_kib": 27289564, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056610.704, "mem_avail_kib": 27290292, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056611.741, "mem_avail_kib": 27218636, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056612.778, "mem_avail_kib": 27228940, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056613.817, "mem_avail_kib": 27228884, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056614.854, "mem_avail_kib": 27217352, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056615.891, "mem_avail_kib": 27221384, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056616.929, "mem_avail_kib": 27180548, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056617.967, "mem_avail_kib": 27180168, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056619.000, "mem_avail_kib": 27168504, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056620.034, "mem_avail_kib": 27171584, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056621.071, "mem_avail_kib": 27170460, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056622.109, "mem_avail_kib": 27172984, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056623.149, "mem_avail_kib": 27167644, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056624.187, "mem_avail_kib": 27168872, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056625.226, "mem_avail_kib": 27174068, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056626.266, "mem_avail_kib": 27168032, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056627.304, "mem_avail_kib": 27177440, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056628.342, "mem_avail_kib": 27175160, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056629.376, "mem_avail_kib": 27183136, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056630.416, "mem_avail_kib": 27183732, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056631.458, "mem_avail_kib": 27145584, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056632.494, "mem_avail_kib": 27153072, "swap_free_kib": 7062056, "vram_used": [16562462720,15780212736]} +{"t": 1791056633.537, "mem_avail_kib": 27029244, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056634.576, "mem_avail_kib": 27165880, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056635.613, "mem_avail_kib": 27171352, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056636.649, "mem_avail_kib": 27174252, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056637.688, "mem_avail_kib": 27178088, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056638.731, "mem_avail_kib": 27176348, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056639.768, "mem_avail_kib": 27193528, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056640.806, "mem_avail_kib": 27212948, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056641.844, "mem_avail_kib": 27230136, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056642.880, "mem_avail_kib": 27243648, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056643.917, "mem_avail_kib": 27245220, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056644.957, "mem_avail_kib": 27256476, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056645.996, "mem_avail_kib": 27262944, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056647.033, "mem_avail_kib": 27260152, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056648.072, "mem_avail_kib": 27276816, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056649.111, "mem_avail_kib": 27286940, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056650.146, "mem_avail_kib": 27282488, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056651.183, "mem_avail_kib": 27276668, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056652.222, "mem_avail_kib": 27279968, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056653.259, "mem_avail_kib": 27277928, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056654.295, "mem_avail_kib": 27289496, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056655.335, "mem_avail_kib": 27284848, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056656.378, "mem_avail_kib": 27285108, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056657.419, "mem_avail_kib": 27294072, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056658.457, "mem_avail_kib": 27299836, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056659.493, "mem_avail_kib": 27302556, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056660.531, "mem_avail_kib": 27293024, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056661.570, "mem_avail_kib": 27282192, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056662.609, "mem_avail_kib": 27224944, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056663.645, "mem_avail_kib": 27226892, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056664.682, "mem_avail_kib": 27217612, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056665.721, "mem_avail_kib": 27217320, "swap_free_kib": 7062056, "vram_used": [16562462720,15780356096]} +{"t": 1791056666.759, "mem_avail_kib": 27220928, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056667.797, "mem_avail_kib": 27166284, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056668.835, "mem_avail_kib": 27169080, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056669.872, "mem_avail_kib": 27157400, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056670.911, "mem_avail_kib": 27161852, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056671.949, "mem_avail_kib": 27164192, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056672.991, "mem_avail_kib": 27171880, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056674.032, "mem_avail_kib": 27175900, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056675.071, "mem_avail_kib": 27180048, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056676.108, "mem_avail_kib": 27178816, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056677.146, "mem_avail_kib": 27183336, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056678.188, "mem_avail_kib": 27182644, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056679.225, "mem_avail_kib": 27180336, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056680.260, "mem_avail_kib": 27171328, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056681.298, "mem_avail_kib": 27160368, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056682.336, "mem_avail_kib": 27166876, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056683.375, "mem_avail_kib": 27160132, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056684.415, "mem_avail_kib": 27044632, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056685.456, "mem_avail_kib": 27183840, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056686.494, "mem_avail_kib": 27183056, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056687.531, "mem_avail_kib": 27206132, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056688.567, "mem_avail_kib": 27208128, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056689.603, "mem_avail_kib": 27216564, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056690.640, "mem_avail_kib": 27224072, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056691.678, "mem_avail_kib": 27237128, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056692.716, "mem_avail_kib": 27225840, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056693.755, "mem_avail_kib": 27232016, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056694.792, "mem_avail_kib": 27232940, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056695.830, "mem_avail_kib": 27249248, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056696.867, "mem_avail_kib": 27255452, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056697.908, "mem_avail_kib": 27250532, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056698.948, "mem_avail_kib": 27254992, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056699.985, "mem_avail_kib": 27262772, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056701.023, "mem_avail_kib": 27273692, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056702.062, "mem_avail_kib": 27269552, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056703.102, "mem_avail_kib": 27273960, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056704.139, "mem_avail_kib": 27279876, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056705.175, "mem_avail_kib": 27284552, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056706.213, "mem_avail_kib": 27285008, "swap_free_kib": 7063336, "vram_used": [16562462720,15780356096]} +{"t": 1791056707.248, "mem_avail_kib": 27283904, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056708.285, "mem_avail_kib": 27289520, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056709.325, "mem_avail_kib": 27298924, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056710.364, "mem_avail_kib": 27298892, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056711.400, "mem_avail_kib": 27302720, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056712.436, "mem_avail_kib": 27306144, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056713.473, "mem_avail_kib": 27234856, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056714.514, "mem_avail_kib": 27236428, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056715.552, "mem_avail_kib": 27222628, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056716.590, "mem_avail_kib": 27221956, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056717.628, "mem_avail_kib": 27220216, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056718.666, "mem_avail_kib": 27172220, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056719.706, "mem_avail_kib": 27169292, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056720.744, "mem_avail_kib": 27159108, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056721.782, "mem_avail_kib": 27167504, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056722.823, "mem_avail_kib": 27168972, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056723.860, "mem_avail_kib": 27177064, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056724.897, "mem_avail_kib": 27167316, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056725.935, "mem_avail_kib": 27175624, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056726.974, "mem_avail_kib": 27170764, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056728.013, "mem_avail_kib": 27176080, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056729.052, "mem_avail_kib": 27178284, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056730.090, "mem_avail_kib": 27170172, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056731.130, "mem_avail_kib": 27172264, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056732.166, "mem_avail_kib": 27176696, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056733.210, "mem_avail_kib": 27173748, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056734.251, "mem_avail_kib": 27178952, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056735.291, "mem_avail_kib": 27064460, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056736.329, "mem_avail_kib": 27049120, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056737.367, "mem_avail_kib": 27181884, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056738.404, "mem_avail_kib": 27182768, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056739.442, "mem_avail_kib": 27179504, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056740.476, "mem_avail_kib": 27181000, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056741.517, "mem_avail_kib": 27193236, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056742.556, "mem_avail_kib": 27210160, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056743.597, "mem_avail_kib": 27222064, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056744.637, "mem_avail_kib": 27221168, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056745.676, "mem_avail_kib": 27238156, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056746.715, "mem_avail_kib": 27243164, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056747.751, "mem_avail_kib": 27249048, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056748.786, "mem_avail_kib": 27264620, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056749.822, "mem_avail_kib": 27253444, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056750.861, "mem_avail_kib": 27260392, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056751.901, "mem_avail_kib": 27267208, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056752.939, "mem_avail_kib": 27254616, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056753.976, "mem_avail_kib": 27273968, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056755.016, "mem_avail_kib": 27280096, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056756.056, "mem_avail_kib": 27290644, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056757.095, "mem_avail_kib": 27280580, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056758.131, "mem_avail_kib": 27283628, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056759.167, "mem_avail_kib": 27274432, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056760.205, "mem_avail_kib": 27276652, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056761.242, "mem_avail_kib": 27270784, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056762.281, "mem_avail_kib": 27272056, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056763.321, "mem_avail_kib": 27278708, "swap_free_kib": 7063592, "vram_used": [16562462720,15780356096]} +{"t": 1791056764.358, "mem_avail_kib": 27197104, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056765.394, "mem_avail_kib": 27205764, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056766.429, "mem_avail_kib": 27211032, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056767.466, "mem_avail_kib": 27205440, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056768.502, "mem_avail_kib": 27197648, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056769.541, "mem_avail_kib": 27156648, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056770.581, "mem_avail_kib": 27150580, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056771.616, "mem_avail_kib": 27158092, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056772.655, "mem_avail_kib": 27151404, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056773.694, "mem_avail_kib": 27158576, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056774.732, "mem_avail_kib": 27167108, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056775.767, "mem_avail_kib": 27168544, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056776.804, "mem_avail_kib": 27169652, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056777.840, "mem_avail_kib": 27169424, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056778.874, "mem_avail_kib": 27171516, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056779.911, "mem_avail_kib": 27166564, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056780.948, "mem_avail_kib": 27161048, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056781.985, "mem_avail_kib": 27169404, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056783.023, "mem_avail_kib": 27176032, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056784.062, "mem_avail_kib": 27174376, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056785.098, "mem_avail_kib": 27170624, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056786.134, "mem_avail_kib": 27167532, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056787.173, "mem_avail_kib": 27166348, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056788.210, "mem_avail_kib": 27172048, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056789.248, "mem_avail_kib": 27175260, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056790.288, "mem_avail_kib": 27173536, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056791.325, "mem_avail_kib": 27165868, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056792.368, "mem_avail_kib": 27152892, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056793.406, "mem_avail_kib": 27030652, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056794.439, "mem_avail_kib": 27043260, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056795.478, "mem_avail_kib": 27043704, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056796.515, "mem_avail_kib": 27035424, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056797.553, "mem_avail_kib": 27040464, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056798.591, "mem_avail_kib": 27042400, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056799.628, "mem_avail_kib": 27039104, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056800.665, "mem_avail_kib": 27033548, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056801.700, "mem_avail_kib": 26978336, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056802.735, "mem_avail_kib": 26971956, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056803.775, "mem_avail_kib": 26980216, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056804.814, "mem_avail_kib": 26982276, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056805.852, "mem_avail_kib": 26986832, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056806.890, "mem_avail_kib": 26948560, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056807.930, "mem_avail_kib": 26948988, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056808.966, "mem_avail_kib": 26951868, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056810.002, "mem_avail_kib": 26940112, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056811.041, "mem_avail_kib": 26944016, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056812.079, "mem_avail_kib": 26949708, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056813.120, "mem_avail_kib": 26945644, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056814.159, "mem_avail_kib": 26943744, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056815.198, "mem_avail_kib": 26910316, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056816.233, "mem_avail_kib": 26899016, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056817.270, "mem_avail_kib": 26904452, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056818.305, "mem_avail_kib": 26910580, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056819.347, "mem_avail_kib": 26904028, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056820.385, "mem_avail_kib": 26902196, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056821.423, "mem_avail_kib": 26899152, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056822.461, "mem_avail_kib": 26906520, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056823.499, "mem_avail_kib": 26900256, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056824.533, "mem_avail_kib": 26893500, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056825.569, "mem_avail_kib": 26910824, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056826.606, "mem_avail_kib": 26912284, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056827.644, "mem_avail_kib": 26911564, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056828.681, "mem_avail_kib": 26919200, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056829.719, "mem_avail_kib": 26925228, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056830.758, "mem_avail_kib": 26929044, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056831.793, "mem_avail_kib": 26850008, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056832.831, "mem_avail_kib": 26852896, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056833.868, "mem_avail_kib": 26865016, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056834.907, "mem_avail_kib": 26864896, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056835.944, "mem_avail_kib": 26867136, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056836.982, "mem_avail_kib": 26817568, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056838.023, "mem_avail_kib": 26820036, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056839.060, "mem_avail_kib": 26811416, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056840.095, "mem_avail_kib": 26811936, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056841.130, "mem_avail_kib": 26812128, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056842.167, "mem_avail_kib": 26820260, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056843.208, "mem_avail_kib": 26815316, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056844.247, "mem_avail_kib": 26821004, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056845.281, "mem_avail_kib": 26835368, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056846.317, "mem_avail_kib": 26831480, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056847.353, "mem_avail_kib": 26825416, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056848.391, "mem_avail_kib": 26826536, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056849.430, "mem_avail_kib": 26831128, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056850.469, "mem_avail_kib": 26822828, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056851.507, "mem_avail_kib": 26813012, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056852.546, "mem_avail_kib": 26817212, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056853.583, "mem_avail_kib": 26819072, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056854.622, "mem_avail_kib": 26823168, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056855.660, "mem_avail_kib": 26827620, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056856.699, "mem_avail_kib": 26825708, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056857.738, "mem_avail_kib": 26816848, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056858.776, "mem_avail_kib": 26821920, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056859.815, "mem_avail_kib": 26826656, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056860.852, "mem_avail_kib": 26820228, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056861.887, "mem_avail_kib": 26744668, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056862.925, "mem_avail_kib": 26751844, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056863.964, "mem_avail_kib": 26759528, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056865.000, "mem_avail_kib": 26764416, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056866.043, "mem_avail_kib": 26754976, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056867.082, "mem_avail_kib": 26748568, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056868.121, "mem_avail_kib": 26709380, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056869.157, "mem_avail_kib": 26705412, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056870.193, "mem_avail_kib": 26687324, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056871.230, "mem_avail_kib": 26682380, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056872.266, "mem_avail_kib": 26685172, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056873.303, "mem_avail_kib": 26693936, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056874.340, "mem_avail_kib": 26691652, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056875.376, "mem_avail_kib": 26679728, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056876.414, "mem_avail_kib": 26694328, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056877.451, "mem_avail_kib": 26681808, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056878.488, "mem_avail_kib": 26674752, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056879.524, "mem_avail_kib": 26670300, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056880.560, "mem_avail_kib": 26677420, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056881.598, "mem_avail_kib": 26680136, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056882.637, "mem_avail_kib": 26673872, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056883.675, "mem_avail_kib": 26671700, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056884.713, "mem_avail_kib": 26680096, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056885.748, "mem_avail_kib": 26687196, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056886.786, "mem_avail_kib": 26686556, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056887.827, "mem_avail_kib": 26681220, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056888.862, "mem_avail_kib": 26677588, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056889.903, "mem_avail_kib": 26700524, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056890.945, "mem_avail_kib": 26704172, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056891.983, "mem_avail_kib": 26707240, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056893.020, "mem_avail_kib": 26636548, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056894.057, "mem_avail_kib": 26637328, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056895.095, "mem_avail_kib": 26641952, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056896.132, "mem_avail_kib": 26642128, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056897.170, "mem_avail_kib": 26642644, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056898.207, "mem_avail_kib": 26646672, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056899.244, "mem_avail_kib": 26589056, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056900.280, "mem_avail_kib": 26587188, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056901.317, "mem_avail_kib": 26589372, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056902.352, "mem_avail_kib": 26585352, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056903.389, "mem_avail_kib": 26586308, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056904.425, "mem_avail_kib": 26588040, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056905.462, "mem_avail_kib": 26591516, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056906.496, "mem_avail_kib": 26602804, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056907.531, "mem_avail_kib": 26595900, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056908.568, "mem_avail_kib": 26601196, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056909.605, "mem_avail_kib": 26596976, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056910.641, "mem_avail_kib": 26586220, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056911.679, "mem_avail_kib": 26584368, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056912.719, "mem_avail_kib": 26592776, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056913.756, "mem_avail_kib": 26599676, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056914.793, "mem_avail_kib": 26597960, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056915.830, "mem_avail_kib": 26599456, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056916.868, "mem_avail_kib": 26600032, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056917.912, "mem_avail_kib": 26606280, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056918.951, "mem_avail_kib": 26610500, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056919.984, "mem_avail_kib": 26592576, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056921.019, "mem_avail_kib": 26595364, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056922.058, "mem_avail_kib": 26593052, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056923.096, "mem_avail_kib": 26599416, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056924.137, "mem_avail_kib": 26598716, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056925.177, "mem_avail_kib": 26526708, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056926.217, "mem_avail_kib": 26532616, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056927.253, "mem_avail_kib": 26525132, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056928.289, "mem_avail_kib": 26527404, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056929.327, "mem_avail_kib": 26534524, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056930.368, "mem_avail_kib": 26517360, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056931.407, "mem_avail_kib": 26508320, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056932.444, "mem_avail_kib": 26518856, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056933.482, "mem_avail_kib": 26532072, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056934.527, "mem_avail_kib": 26525560, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056935.566, "mem_avail_kib": 26542084, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056936.604, "mem_avail_kib": 26525880, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056937.642, "mem_avail_kib": 26543500, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056938.681, "mem_avail_kib": 26551764, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056939.720, "mem_avail_kib": 26563440, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056940.758, "mem_avail_kib": 26567696, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056941.796, "mem_avail_kib": 26582568, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056942.835, "mem_avail_kib": 26492888, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056943.870, "mem_avail_kib": 27202780, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056944.906, "mem_avail_kib": 27200072, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056945.944, "mem_avail_kib": 27206604, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056946.983, "mem_avail_kib": 27216936, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056948.020, "mem_avail_kib": 27229080, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056949.059, "mem_avail_kib": 27241764, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056950.096, "mem_avail_kib": 27240568, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056951.134, "mem_avail_kib": 27240920, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056952.172, "mem_avail_kib": 27258576, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056953.210, "mem_avail_kib": 27259612, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056954.247, "mem_avail_kib": 27272748, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056955.286, "mem_avail_kib": 27277216, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056956.326, "mem_avail_kib": 27282428, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056957.361, "mem_avail_kib": 27281552, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056958.400, "mem_avail_kib": 27283852, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056959.440, "mem_avail_kib": 27280848, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056960.479, "mem_avail_kib": 27289980, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056961.515, "mem_avail_kib": 27290736, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056962.552, "mem_avail_kib": 27295236, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056963.590, "mem_avail_kib": 27296780, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056964.630, "mem_avail_kib": 27286064, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056965.668, "mem_avail_kib": 27293052, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056966.705, "mem_avail_kib": 27287168, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056967.743, "mem_avail_kib": 27294492, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056968.780, "mem_avail_kib": 27295432, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056969.818, "mem_avail_kib": 27284960, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056970.856, "mem_avail_kib": 27289032, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056971.892, "mem_avail_kib": 27216080, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056972.928, "mem_avail_kib": 27212760, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056973.970, "mem_avail_kib": 27217044, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056975.010, "mem_avail_kib": 27224000, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056976.049, "mem_avail_kib": 27235856, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056977.089, "mem_avail_kib": 27178204, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056978.127, "mem_avail_kib": 27174724, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056979.165, "mem_avail_kib": 27177504, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056980.201, "mem_avail_kib": 27175176, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056981.240, "mem_avail_kib": 27163472, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056982.279, "mem_avail_kib": 27168700, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056983.315, "mem_avail_kib": 27161536, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056984.352, "mem_avail_kib": 27165080, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056985.390, "mem_avail_kib": 27154624, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056986.426, "mem_avail_kib": 27147688, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056987.462, "mem_avail_kib": 27157564, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056988.501, "mem_avail_kib": 27152092, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056989.540, "mem_avail_kib": 27159644, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056990.577, "mem_avail_kib": 27160712, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056991.614, "mem_avail_kib": 27164748, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056992.650, "mem_avail_kib": 27158332, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056993.687, "mem_avail_kib": 27161512, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056994.727, "mem_avail_kib": 27155344, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056995.764, "mem_avail_kib": 27146944, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056996.798, "mem_avail_kib": 27160024, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056997.840, "mem_avail_kib": 27143144, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056998.876, "mem_avail_kib": 27138880, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791056999.912, "mem_avail_kib": 27030400, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791057000.948, "mem_avail_kib": 27031624, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791057001.988, "mem_avail_kib": 27024940, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791057003.029, "mem_avail_kib": 27029412, "swap_free_kib": 7063848, "vram_used": [16562462720,15780356096]} +{"t": 1791057004.069, "mem_avail_kib": 27035228, "swap_free_kib": 7064104, "vram_used": [16562462720,15780356096]} +{"t": 1791057005.106, "mem_avail_kib": 27041836, "swap_free_kib": 7064104, "vram_used": [16562462720,15780356096]} +{"t": 1791057006.144, "mem_avail_kib": 27045192, "swap_free_kib": 7064104, "vram_used": [16562462720,15780356096]} +{"t": 1791057007.182, "mem_avail_kib": 26988336, "swap_free_kib": 7064104, "vram_used": [16562462720,15780356096]} +{"t": 1791057008.219, "mem_avail_kib": 27001344, "swap_free_kib": 7064104, "vram_used": [16562462720,15780356096]} +{"t": 1791057009.257, "mem_avail_kib": 27001116, "swap_free_kib": 7064104, "vram_used": [16562462720,15780356096]} +{"t": 1791057010.293, "mem_avail_kib": 26998056, "swap_free_kib": 7064104, "vram_used": [16562462720,15780356096]} +{"t": 1791057011.332, "mem_avail_kib": 27001124, "swap_free_kib": 7064360, "vram_used": [16562462720,15780356096]} +{"t": 1791057012.373, "mem_avail_kib": 26998588, "swap_free_kib": 7064360, "vram_used": [16562462720,15780356096]} +{"t": 1791057013.411, "mem_avail_kib": 26947260, "swap_free_kib": 7064360, "vram_used": [16562462720,15780356096]} +{"t": 1791057014.451, "mem_avail_kib": 26939092, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057015.488, "mem_avail_kib": 26938508, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057016.527, "mem_avail_kib": 26936284, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057017.564, "mem_avail_kib": 26933688, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057018.600, "mem_avail_kib": 26933448, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057019.640, "mem_avail_kib": 26916876, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057020.677, "mem_avail_kib": 26914256, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057021.716, "mem_avail_kib": 26920008, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057022.753, "mem_avail_kib": 26922608, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057023.790, "mem_avail_kib": 26934740, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057024.828, "mem_avail_kib": 26941320, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057025.869, "mem_avail_kib": 26947652, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057026.909, "mem_avail_kib": 26934888, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057027.945, "mem_avail_kib": 26931616, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057028.982, "mem_avail_kib": 26933752, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057030.019, "mem_avail_kib": 26930524, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057031.059, "mem_avail_kib": 26928352, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057032.098, "mem_avail_kib": 26933440, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057033.138, "mem_avail_kib": 26938800, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057034.178, "mem_avail_kib": 26943004, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057035.216, "mem_avail_kib": 26935168, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057036.253, "mem_avail_kib": 26928456, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057037.291, "mem_avail_kib": 26854016, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057038.328, "mem_avail_kib": 26864556, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057039.366, "mem_avail_kib": 26869516, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057040.403, "mem_avail_kib": 26887532, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057041.444, "mem_avail_kib": 26880252, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057042.481, "mem_avail_kib": 26851308, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057043.519, "mem_avail_kib": 26837640, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057044.556, "mem_avail_kib": 26842932, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057045.595, "mem_avail_kib": 26845048, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057046.634, "mem_avail_kib": 26847252, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057047.672, "mem_avail_kib": 26846076, "swap_free_kib": 7064616, "vram_used": [16562462720,15780356096]} +{"t": 1791057048.709, "mem_avail_kib": 26838116, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057049.745, "mem_avail_kib": 26845448, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057050.782, "mem_avail_kib": 26833368, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057051.820, "mem_avail_kib": 26831704, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057052.858, "mem_avail_kib": 26827604, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057053.898, "mem_avail_kib": 26829840, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057054.939, "mem_avail_kib": 26838380, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057055.977, "mem_avail_kib": 26837196, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057057.015, "mem_avail_kib": 26828992, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057058.052, "mem_avail_kib": 26821608, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057059.090, "mem_avail_kib": 26824316, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057060.128, "mem_avail_kib": 26826412, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057061.165, "mem_avail_kib": 26822128, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057062.203, "mem_avail_kib": 26816756, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057063.242, "mem_avail_kib": 26820560, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057064.282, "mem_avail_kib": 26825456, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057065.320, "mem_avail_kib": 26830708, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057066.357, "mem_avail_kib": 26824308, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057067.394, "mem_avail_kib": 26752540, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057068.430, "mem_avail_kib": 26747444, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057069.466, "mem_avail_kib": 26740600, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057070.503, "mem_avail_kib": 26734032, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057071.542, "mem_avail_kib": 26731196, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057072.579, "mem_avail_kib": 26729872, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057073.617, "mem_avail_kib": 26684864, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057074.657, "mem_avail_kib": 26678148, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057075.693, "mem_avail_kib": 26689868, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057076.732, "mem_avail_kib": 26695888, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057077.772, "mem_avail_kib": 26702588, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057078.809, "mem_avail_kib": 26697280, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057079.850, "mem_avail_kib": 26702228, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057080.886, "mem_avail_kib": 26704592, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057081.923, "mem_avail_kib": 26698412, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057082.961, "mem_avail_kib": 26701956, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057083.999, "mem_avail_kib": 26704804, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057085.038, "mem_avail_kib": 26704812, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057086.076, "mem_avail_kib": 26707056, "swap_free_kib": 7065128, "vram_used": [16562462720,15780356096]} +{"t": 1791057087.115, "mem_avail_kib": 26684320, "swap_free_kib": 7065640, "vram_used": [16562462720,15780356096]} +{"t": 1791057088.155, "mem_avail_kib": 26678496, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057089.192, "mem_avail_kib": 26683716, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057090.229, "mem_avail_kib": 26685556, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057091.265, "mem_avail_kib": 26687284, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057092.304, "mem_avail_kib": 26691696, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057093.341, "mem_avail_kib": 26682872, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057094.380, "mem_avail_kib": 26686088, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057095.417, "mem_avail_kib": 26694112, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057096.453, "mem_avail_kib": 26696244, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057097.489, "mem_avail_kib": 26699616, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057098.527, "mem_avail_kib": 26706152, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057099.563, "mem_avail_kib": 26645076, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057100.599, "mem_avail_kib": 26651648, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057101.639, "mem_avail_kib": 26645064, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057102.675, "mem_avail_kib": 26636728, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057103.712, "mem_avail_kib": 26637844, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057104.753, "mem_avail_kib": 26637228, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057105.792, "mem_avail_kib": 26583192, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057106.832, "mem_avail_kib": 26581180, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057107.872, "mem_avail_kib": 26581108, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057108.911, "mem_avail_kib": 26588108, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057109.948, "mem_avail_kib": 26599952, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057110.985, "mem_avail_kib": 26600108, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057112.023, "mem_avail_kib": 26601732, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057113.061, "mem_avail_kib": 26602484, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057114.097, "mem_avail_kib": 26592736, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057115.135, "mem_avail_kib": 26594956, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057116.174, "mem_avail_kib": 26599640, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057117.211, "mem_avail_kib": 26593160, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057118.251, "mem_avail_kib": 26600084, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057119.288, "mem_avail_kib": 26573664, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057120.327, "mem_avail_kib": 26567104, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057121.365, "mem_avail_kib": 26584752, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057122.400, "mem_avail_kib": 26595396, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057123.437, "mem_avail_kib": 26591652, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057124.477, "mem_avail_kib": 26585420, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057125.517, "mem_avail_kib": 26584796, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057126.558, "mem_avail_kib": 26584636, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057127.593, "mem_avail_kib": 26580720, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057128.632, "mem_avail_kib": 26581332, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057129.668, "mem_avail_kib": 26573608, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057130.703, "mem_avail_kib": 26583168, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057131.741, "mem_avail_kib": 26518672, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057132.780, "mem_avail_kib": 26528668, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057133.816, "mem_avail_kib": 26532224, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057134.853, "mem_avail_kib": 26529100, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057135.891, "mem_avail_kib": 26530788, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057136.929, "mem_avail_kib": 26530888, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057137.964, "mem_avail_kib": 26527108, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057139.001, "mem_avail_kib": 26538132, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057140.040, "mem_avail_kib": 26557344, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057141.078, "mem_avail_kib": 26555040, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057142.114, "mem_avail_kib": 26559288, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057143.158, "mem_avail_kib": 26550828, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057144.196, "mem_avail_kib": 26550164, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057145.234, "mem_avail_kib": 26554032, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057146.270, "mem_avail_kib": 26558576, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057147.310, "mem_avail_kib": 26567844, "swap_free_kib": 7065896, "vram_used": [16562462720,15780356096]} +{"t": 1791057148.348, "mem_avail_kib": 26467652, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057149.389, "mem_avail_kib": 26936572, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057150.426, "mem_avail_kib": 26950892, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057151.466, "mem_avail_kib": 26957240, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057152.504, "mem_avail_kib": 26969276, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057153.541, "mem_avail_kib": 26974864, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057154.579, "mem_avail_kib": 26975064, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057155.620, "mem_avail_kib": 26978340, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057156.659, "mem_avail_kib": 26989320, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057157.696, "mem_avail_kib": 27002780, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057158.734, "mem_avail_kib": 27006948, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057159.772, "mem_avail_kib": 27007132, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057160.810, "mem_avail_kib": 27013664, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057161.849, "mem_avail_kib": 27018108, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057162.887, "mem_avail_kib": 27028380, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057163.925, "mem_avail_kib": 27033712, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057164.965, "mem_avail_kib": 27038304, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057166.003, "mem_avail_kib": 27031064, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057167.042, "mem_avail_kib": 27036896, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057168.080, "mem_avail_kib": 27036708, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057169.119, "mem_avail_kib": 27038844, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057170.157, "mem_avail_kib": 27040860, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057171.196, "mem_avail_kib": 27045052, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057172.233, "mem_avail_kib": 27035660, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057173.271, "mem_avail_kib": 27033884, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057174.314, "mem_avail_kib": 27033848, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057175.353, "mem_avail_kib": 27034968, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057176.393, "mem_avail_kib": 27048860, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057177.431, "mem_avail_kib": 27053672, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057178.470, "mem_avail_kib": 27061072, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057179.510, "mem_avail_kib": 27055232, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057180.548, "mem_avail_kib": 26960632, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057181.585, "mem_avail_kib": 26952380, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057182.621, "mem_avail_kib": 26942108, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057183.660, "mem_avail_kib": 26942236, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057184.699, "mem_avail_kib": 26951896, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057185.737, "mem_avail_kib": 26946176, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057186.772, "mem_avail_kib": 26891816, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057187.808, "mem_avail_kib": 26895856, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057188.847, "mem_avail_kib": 26900296, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057189.885, "mem_avail_kib": 26908432, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057190.924, "mem_avail_kib": 26910856, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057191.964, "mem_avail_kib": 26899196, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057193.003, "mem_avail_kib": 26909492, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057194.043, "mem_avail_kib": 26917308, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057195.082, "mem_avail_kib": 26921092, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057196.124, "mem_avail_kib": 26928576, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057197.164, "mem_avail_kib": 26934672, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057198.207, "mem_avail_kib": 26936748, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057199.246, "mem_avail_kib": 26935680, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057200.287, "mem_avail_kib": 26932848, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057201.326, "mem_avail_kib": 26925164, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057202.364, "mem_avail_kib": 26925404, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057203.402, "mem_avail_kib": 26928744, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057204.442, "mem_avail_kib": 26935124, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057205.479, "mem_avail_kib": 26928952, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057206.518, "mem_avail_kib": 26932008, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057207.559, "mem_avail_kib": 26929600, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057208.597, "mem_avail_kib": 26929688, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057209.633, "mem_avail_kib": 26924308, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057210.669, "mem_avail_kib": 26925888, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057211.706, "mem_avail_kib": 26856688, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057212.743, "mem_avail_kib": 26849444, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057213.780, "mem_avail_kib": 26856692, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057214.818, "mem_avail_kib": 26861644, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057215.854, "mem_avail_kib": 26864968, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057216.890, "mem_avail_kib": 26859064, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057217.926, "mem_avail_kib": 26808096, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057218.966, "mem_avail_kib": 26815488, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057220.005, "mem_avail_kib": 26820624, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057221.042, "mem_avail_kib": 26821724, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057222.079, "mem_avail_kib": 26819284, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057223.118, "mem_avail_kib": 26812176, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057224.157, "mem_avail_kib": 26805956, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057225.195, "mem_avail_kib": 26817024, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057226.233, "mem_avail_kib": 26813616, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057227.273, "mem_avail_kib": 26822488, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057228.312, "mem_avail_kib": 26821472, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057229.351, "mem_avail_kib": 26815252, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057230.390, "mem_avail_kib": 26819828, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057231.430, "mem_avail_kib": 26818056, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057232.468, "mem_avail_kib": 26813328, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057233.506, "mem_avail_kib": 26804028, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057234.542, "mem_avail_kib": 26810440, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057235.580, "mem_avail_kib": 26804100, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057236.619, "mem_avail_kib": 26819344, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057237.664, "mem_avail_kib": 26817396, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057238.701, "mem_avail_kib": 26819852, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057239.740, "mem_avail_kib": 26811676, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057240.778, "mem_avail_kib": 26807268, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057241.816, "mem_avail_kib": 26787380, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057242.854, "mem_avail_kib": 26788112, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057243.891, "mem_avail_kib": 26716208, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057244.927, "mem_avail_kib": 26722464, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057245.964, "mem_avail_kib": 26730984, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057247.002, "mem_avail_kib": 26734972, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057248.038, "mem_avail_kib": 26741224, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057249.078, "mem_avail_kib": 26745100, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057250.114, "mem_avail_kib": 26701952, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057251.154, "mem_avail_kib": 26694368, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057252.191, "mem_avail_kib": 26685568, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057253.230, "mem_avail_kib": 26683856, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057254.266, "mem_avail_kib": 26678140, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057255.303, "mem_avail_kib": 26674628, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057256.338, "mem_avail_kib": 26671136, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057257.373, "mem_avail_kib": 26673032, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057258.412, "mem_avail_kib": 26685356, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057259.453, "mem_avail_kib": 26675828, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057260.496, "mem_avail_kib": 26556140, "swap_free_kib": 7065896, "vram_used": [16562462720,15780495360]} +{"t": 1791057261.534, "mem_avail_kib": 29262176, "swap_free_kib": 7065896, "vram_used": [13813174272,12855922688]} diff --git a/bench/results/2026-10-03-v100-prompt-attn/README.md b/bench/results/2026-10-03-v100-prompt-attn/README.md new file mode 100644 index 0000000..ab8b326 --- /dev/null +++ b/bench/results/2026-10-03-v100-prompt-attn/README.md @@ -0,0 +1,104 @@ +# V100 (sm_70): a tensor-core QSA prompt attention (2026-10-03) + +On sm_70 the prompt path ran the QSA attention on the decode kernel, one query at a time with FP32 FMAs. `prompt_attn_v70_kernel` +(`src/kernels/cuda/qsa_prompt_attn.cu`) does the two matrix products on Volta's tensor cores (`mma.sync.m8n8k4`). +`STRATA_PROMPT_ATTN_OLD=1` is the old path, so every number below is the same binary with and without that switch. + +## Rig + +- Tesla V100-PCIE-32GB (sm_70, PCIe gen3 x16), driver 550.120, one card used; a second V100 and a Quadro RTX 4000 (sm_75) are in the + PC and hidden with `CUDA_VISIBLE_DEVICES`. Intel Core i9-7960X (AVX-512), 125 GB RAM, Linux 6.8, CUDA 12.8, GCC 13. +- Engine: `origin/main` at `99f3dbd` (0.1.35 + 83 commits) with this change, built with + `-DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_EXPERIMENTAL_SM60=ON`. +- Model: Unsloth `Qwen3.8-Flash-Next-UD-IQ4_XS` (3 shards), packed with `tools/iq_pack.py --compat-bf16`, MTP head from + `tools/mtp_fetch.py`. Not one of setup's models (see the limits). `--max-context 204800`, `--kv int8`, `--spec 2`. + +## Prompt speed + +One server start per configuration (cold), a 2K warm-up request, then three prompts of random words, each answered greedily +(temperature 0, 48 tokens). The numbers are the server's own line `strata serve: prompt N tokens = 0 reused + N read in T ms`. One run per +cell; repeated starts of the same configuration gave the same seconds. + +| Prompt tokens | old path | new kernel | gain | read time, old -> new | +| ---: | ---: | ---: | ---: | ---: | +| 7,194 | 1,010 tok/s | 1,164 tok/s | +15% | 7.1 s -> 6.2 s | +| 28,650 | 1,063 tok/s | 1,251 tok/s | +18% | 26.9 s -> 22.9 s | +| 114,338 | 973 tok/s | 1,123 tok/s | +15% | 117.5 s -> 101.8 s | + +Decode is unchanged within the noise (38-51 tok/s, 48 tokens per request): it does not use this kernel. + +## Where the time went (nsys, one V100, 28,650-token prompt, GPU kernel time of the whole capture: prefill plus 128-193 decode tokens) + +`strata-1gpu-32k-*.nsys-rep`; the "before" capture is 0.1.35 (`d9ab843`), the "after" one is the same base with this change and the BF16 change +of #540 / the closed #593 (BF16 GEMMs through FP16; that one only removes `magma_sgemmEx`, which is not in this table). + +| | before | after | +| --- | ---: | ---: | +| QSA attention on the decode kernel (`attn_chunk_kernel<1>`) | 5.78 s (19.2%) | 0.18 s (decode steps only) | +| `prompt_attn_v70_kernel` | - | 2.16 s (9.0%; 12% of the prompt part) | + +## Accuracy + +`qsa_prompt_attn_parity` (synthetic, no model; build with `-DSTRATA_PARITY_PROMPT_ATTN=ON`), V100, 32K context, 2,048 queries per chunk, output scale 3.6: + +| KV | error vs FP64, old kernel | error vs FP64, new kernel | time per chunk, old -> new | +| --- | ---: | ---: | ---: | +| int8 | 2.4e-6 | 5.1e-6 | 38.1 -> 13.4 ms (2.8x) | +| fp16 | 1.9e-6 | 5.3e-6 | 37.3 -> 28.3 ms (1.3x) | + +The 1,500- and 2,100-token contexts also pass (int8: 3.2x and 2.2x). The test's Q4_0 cases are skipped below sm_80, where the dispatcher keeps the +old kernel (upstream's mode 4 is sm_80+ only). + +## Output checks + +- **Needle recall** (`tools/needle_bench.py --lengths 8k,32k,128k --depths 10,30,50,70,90`, greedy, thinking off, a fresh server per + configuration; prompts of 7.9K, 32.0K and 122.7K tokens): **15 of 15 found with the old path, 15 of 15 with the new kernel.** The read times of + the later depths are shorter because the server reuses the checkpoint of the text before the needle. +- **Greedy output** (48 tokens, the three prompts above): identical for the 28,650- and 114,338-token prompts. For the 7,194-token prompt the + answer starts the same and **differs later**: the kernel sums in another order and a greedy decode can follow a near tie elsewhere. A recall test + with a code word does not tell small shifts of the output distribution apart, and a teacher-forced top-1 comparison was not run. + +## Distribution check (teacher-forced, against the old path and against controls) + +The method of `docs/UNSLOTH_Q4.md`: `STRATA_LOGPOS= STRATA_LOGPOS_TOPK=256` on a serve engine (`--short-read 640 --adapt-every 100000`, greedy, +`--max-context 204800`). Each prompt is a chat: a long first message (8,543 / 32,906 / 99,040 tokens of this repository's docs and code, read by the +batched prompt path, i.e. by the kernel under test), a short reply, and a last message of ~600 tokens of other repository text that goes through the verify +windows, where every token is scored: 617 positions per prompt. KL is old || other over the old run's top 256 plus a bucket for the rest. + +| comparison | KL mean (8.5K / 33K / 99K) | argmax same | top-10 overlap | +| --- | --- | --- | --- | +| old path vs old path (a second run) | 0 / 0 / 0 | 100% | 100% | +| new kernel vs new kernel (a second run) | 0 / 0 / 0 | 100% | 100% | +| **old path vs new kernel** | 0.028 / 0.040 / 0.116 | 97.7 / 93.2 / 86.4% | 93.3 / 91.9 / 88.4% | +| control A: old path, BF16 GEMMs without the FP16 detour (`STRATA_BF16_VIA_F16=0`) | 0.026 / 0.051 / 0.090 | 97.2 / 91.4 / 91.2% | 92.9 / 91.4 / 88.5% | +| control B: old path, `--prefill 2048` instead of auto (8192) | 0.023 / 0.035 / 0.038 | 97.9 / 94.8 / 95.6% | 92.9 / 92.2 / 89.7% | + +Median KL old vs new: 0.0007 / 0.0088 / 0.022; p99: 0.35 / 0.39 / 1.12 (heavy-tailed). The perplexity of the true tokens moves a lot under every +change (old 365 / 127 / 24; new 346 / 192 / 12; control A 395 / 161 / 18), so it says nothing about quality here. + +Reading: the model amplifies small numeric differences, and both controls, which change nothing but the order of the rounding, move the distribution as +much as the kernel does. At 99K the kernel is somewhat above both controls; this is one document and 617 positions, so a real effect there is neither +confirmed nor excluded. + +**The kernel on the model's own data.** A temporary check (not in this PR) ran the decode kernel beside the new one on the same inputs, for every 8th batch of +32 queries, in all 12 QSA layers, on the three prompts above (positions up to 98K, ~5 million (query, head) rows of 256): ||new - old|| / ||old|| per row is +4.4e-7 on average and 4.8e-6 in the worst row; the largest absolute difference is 4e-5 against values up to 31. No trend over the layers or the context +length. That is FP32 rounding level, so the differences above come from the model's sensitivity, not from the kernel's arithmetic. + +## Limits + +- sm_70 only (`__CUDA_ARCH__` 700-749). Q4_0 KV (`--kv q4_0`) and the QSA block scores (`block_scores_kernel`, the warp kernel below sm_80) still use their + old kernels on Volta. +- One request, one card. The Unsloth IQ4_XS pack is not a setup model; the GSQ-RCO quants were not run on this rig. +- The profile above is one capture of one prompt. The distribution check is one document per length; the 99K row is the least certain. + +## Reproduce + +```sh +cmake -S . -B build -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF -DSTRATA_PARITY_PROMPT_ATTN=ON \ + -DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_EXPERIMENTAL_SM60=ON +cmake --build build --target strata qsa_prompt_attn_parity -j +CUDA_VISIBLE_DEVICES=0 ./build/qsa_prompt_attn_parity 32768 2048 5 # the accuracy table +STRATA_PROMPT_ATTN_OLD=1 # the old path; without the variable: the new kernel +python tools/needle_bench.py --url http://127.0.0.1:8081 --lengths 8k,32k,128k --depths 10,30,50,70,90 +``` diff --git a/chat.py b/chat.py new file mode 100644 index 0000000..124c727 --- /dev/null +++ b/chat.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""A tiny terminal chat for a running Strata server (start it with run-.bat / run-.sh first). + + python chat.py [--port 8080] [--think none|low|medium|high] + +Type a message and press Enter. /image attaches a picture to your next message (when the server was set up +with images), /think sets how long the model thinks first, /reset starts a new conversation, +/quit leaves. Standard library only. +""" +from __future__ import annotations + +import argparse +import base64 +import json +import mimetypes +import os +import sys +import time +import urllib.request + + +def stream(url, messages, think, max_tokens): + body = {"model": "strata", "messages": messages, "stream": True, "max_tokens": max_tokens, + "reasoning_effort": think} + req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=3600) as r: + for raw in r: + line = raw.decode("utf-8", "replace").strip() + if not line.startswith("data: ") or line == "data: [DONE]": + continue + d = json.loads(line[6:])["choices"][0]["delta"] + yield d.get("reasoning_content") or "", d.get("content") or "" + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--host", default="127.0.0.1") + ap.add_argument("--think", default="medium", choices=["none", "low", "medium", "high"], + help="how long the model thinks before answering (none = answer directly)") + ap.add_argument("--no-think", action="store_true", help="same as --think none") + ap.add_argument("--max-tokens", type=int, default=4096) + a = ap.parse_args() + url = f"http://{a.host}:{a.port}/v1/chat/completions" + gray, reset = ("\033[90m", "\033[0m") if sys.stdout.isatty() else ("", "") + messages, pending = [], [] + think = "none" if a.no_think else a.think + print(f"Strata chat ({url}). /image = attach a picture, /think none|low|medium|high (now: {think}), " + f"/reset = new conversation, /quit = leave.") + while True: + try: + user = input("\nyou> ").strip() + except (EOFError, KeyboardInterrupt): + print() + return 0 + if user in ("/quit", "/exit"): + return 0 + if user == "/reset": + messages, pending = [], [] + print("(new conversation)") + continue + if user.startswith("/think"): + level = user[6:].strip().lower() + if level in ("none", "low", "medium", "high"): + think = level + print(f"(thinking: {think})") + else: + print("(usage: /think none|low|medium|high)") + continue + if user.startswith("/image"): + path = user[6:].strip().strip('"').strip("'") + if not os.path.isfile(path): + print(f"(no such file: {path or '?'} - usage: /image )") + continue + mime = mimetypes.guess_type(path)[0] or "image/jpeg" + data = base64.b64encode(open(path, "rb").read()).decode() + pending.append({"type": "image_url", "image_url": {"url": f"data:{mime};base64,{data}"}}) + print(f"(picture attached: {os.path.basename(path)} - now type your question)") + continue + if not user: + continue + if pending: + messages.append({"role": "user", "content": [*pending, {"type": "text", "text": user}]}) + pending = [] + else: + messages.append({"role": "user", "content": user}) + answer, n, t0 = [], 0, time.time() + print("model> ", end="", flush=True) + try: + in_think = False + for reasoning, content in stream(url, messages, think, a.max_tokens): + if reasoning: + if not in_think: + print(gray, end="") + in_think = True + print(reasoning, end="", flush=True) + if content: + if in_think: + print(reset + "\n", end="") + in_think = False + print(content, end="", flush=True) + answer.append(content) + n += 1 + if in_think: + print(reset, end="") + except OSError as e: + print(f"\n(could not reach the server at {url}: {e})") + messages.pop() + continue + dt = time.time() - t0 + print(f"\n{gray}[{n} chunks in {dt:.1f} s]{reset}") + messages.append({"role": "assistant", "content": "".join(answer)}) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake new file mode 100644 index 0000000..d59bba9 --- /dev/null +++ b/cmake/hip_backend.cmake @@ -0,0 +1,110 @@ +# 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/data/draft_vocab.bin b/data/draft_vocab.bin new file mode 100644 index 0000000..217f274 Binary files /dev/null and b/data/draft_vocab.bin differ diff --git a/data/draft_vocab_cyrillic.bin b/data/draft_vocab_cyrillic.bin new file mode 100644 index 0000000..06e22cb Binary files /dev/null and b/data/draft_vocab_cyrillic.bin differ diff --git a/data/draft_vocab_en.bin b/data/draft_vocab_en.bin new file mode 100644 index 0000000..c588b56 Binary files /dev/null and b/data/draft_vocab_en.bin differ diff --git a/data/draft_vocab_fr.bin b/data/draft_vocab_fr.bin new file mode 100644 index 0000000..21fff5d Binary files /dev/null and b/data/draft_vocab_fr.bin differ diff --git a/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.gguf b/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.gguf new file mode 100644 index 0000000..5c10294 Binary files /dev/null and b/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.gguf differ diff --git a/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.json b/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.json new file mode 100644 index 0000000..82946d6 --- /dev/null +++ b/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.json @@ -0,0 +1,26 @@ +{ + "mode": "project", + "dir": "per-layer", + "scale": 1.0, + "layer_range": [ + 4, + 44 + ], + "refusal_harmful_thinkoff": 2.0, + "refusal_harmful_thinkon": 2.0, + "refusal_harmless_thinkoff": 4.0, + "refusal_harmless_thinkon": 6.0, + "broken": 0, + "kl_mean": 0.18598, + "kl_max": 18.26549, + "kl_p99": 3.143571, + "decode_tps": 51.19, + "vector_file": "Qwen3.8-Flash-Next-experimental-speed-projection.gguf", + "base_model_gguf": "unsloth/Qwen3.8-Flash-Next-GGUF UD-Q2_K_XL", + "base_model_sha256_shard1": "a4f3b21e77353999829f2f767e9ac21ce9c71d29a74f2cc9eda48c9bf23c8b86", + "worktree_commit": "37e026e3b", + "criterion_status": "PASS", + "dirty_direction": false, + "note": "projection ablation h -= s*(h.v)*v, v unit-normalized per layer. dir=per-layer", + "branch": "cvec-hooks (github.com/Cudila/llama.cpp)" +} diff --git a/data/experimental-speed-projection/README.md b/data/experimental-speed-projection/README.md new file mode 100644 index 0000000..ad4a008 --- /dev/null +++ b/data/experimental-speed-projection/README.md @@ -0,0 +1,21 @@ +# experimental-speed-projection (EXPERIMENTAL, off by default) + +`Qwen3.8-Flash-Next-experimental-speed-projection.gguf` is a 480 KB control vector for Qwen3.8-Flash-Next: one unit +direction of 2,560 values per layer (`direction.1` .. `direction.47`, GGUF `controlvector` format). The JSON beside it +is the configuration its authors selected and their scores. + +**What it does.** Turned on, Strata removes each direction from the residual stream after layers 4-44 +(`h -= (h . v) v` on every hyper-connection stream), the same operation as llama.cpp's `--cvec-mode project` in the +package's patches. The package's own documentation describes the vector as a **refusal-direction projection**: 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 the model's predictions +slightly on ordinary text (measured here: `bench/results/2026-09-27-esp/`). It is not an optimization in the engine: +on the same text it costs 0.2-0.4% per token; a chat's speed with it on depends on the text the model writes. + +**Turning it on.** `START-HERE.bat --setup` asks (default: off), or pass `--experimental-speed-projection on`. With it +loaded, the web app's Sampling drawer and the API field `"experimental_speed_projection": false` switch it off per +request. See `docs/DETAILS.md`, "Experimental speed projection". + +**Origin and license.** A local package of the vector (the published original uses filenames containing "refusal"; +the bytes are the same), made from Qwen3.8-Flash-Next activations, so the Qwen Community License 1.0 of the model +applies to it. Made for the original Qwen3.8-Flash-Next (not Swift 1.5). diff --git a/data/expert-profile-coder.bin b/data/expert-profile-coder.bin new file mode 100644 index 0000000..4198aef Binary files /dev/null and b/data/expert-profile-coder.bin differ diff --git a/data/expert-profile.bin b/data/expert-profile.bin new file mode 100644 index 0000000..a4ed7e5 Binary files /dev/null and b/data/expert-profile.bin differ diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100755 index 0000000..f167bed --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# Entry point for the Strata container. The engine is compiled during docker +# build and lives in the image, so the first start only downloads the model. +# The install config is kept on the /data volume so a recreated container skips +# the setup pass and goes straight to serving. +set -e +cd /opt/strata || exit 1 + +STRATA_DATA="${STRATA_DATA:-/data}" +FAMILY="${FAMILY:-qwen}" +MODEL="${MODEL:-IQ2_XS}" +CONTEXT="${CONTEXT:-32768}" +VISION="${VISION:-no}" # no | yes | cpu (the image encoder on the CPU) +HOST="${HOST:-0.0.0.0}" +PORT="${PORT:-8080}" +API_KEY="${API_KEY:-}" +KV="${KV:-}" # int8 | q4_0 | k8v4; empty: setup.py's own default (int8) +GPUS="${GPUS:-}" # "0,2" or "all": one model across several cards (docs/MULTI_GPU.md) +GPU="${GPU:-}" # one card, numbered as nvidia-smi numbers them +LAYER_SPLIT="${LAYER_SPLIT:-}" # with GPUS: where each later card's layers start (default: auto) +LOW_RAM="${LOW_RAM:-auto}" # on: the experts come from the pack's experts.bin, not from RAM + +# setup.py starts the newest strata-*.json it finds, so link in exactly the one +# this family and model were set up with. The config is the recorded output of +# that setup (the pack, the profile, the quant, the KV decision), not settings +# the entry point could rebuild from env vars. qwen has an empty family tag. +case "$FAMILY" in qwen) prefix="" ;; *) prefix="${FAMILY}-" ;; esac +tag="${prefix}$(printf '%s' "$MODEL" | tr 'A-Z' 'a-z')" +cfg="$STRATA_DATA/config/strata-$tag.json" +mkdir -p "$STRATA_DATA/config" + +# REINSTALL is only needed to change settings for a model that is already set up +# (context, vision, KV, host, api_key). Switching between models already on the +# volume needs no setup pass: their config is already there. +# +# KV / GPUS / GPU / LAYER_SPLIT are passed only when set, so an unset one keeps +# setup.py's own default. LOW_RAM is always passed: setup.py measures the PC's RAM +# from /proc/meminfo, which in a container is the host's total, not the container's +# limit, so a memory-capped container has to ask for the low-RAM mode itself. +if [ "${REINSTALL:-0}" = "1" ] || [ ! -f "$cfg" ]; then + echo "Setting up $tag: downloading the model (~70 GB; the engine is already in the image)." + set -- --family "$FAMILY" --model "$MODEL" --context "$CONTEXT" --vision "$VISION" \ + --data-dir "$STRATA_DATA" --host "$HOST" --api-key "$API_KEY" \ + --port "$PORT" --no-start --low-ram "$LOW_RAM" + if [ -n "$KV" ]; then set -- "$@" --kv "$KV"; fi + if [ -n "$GPUS" ]; then set -- "$@" --gpus "$GPUS"; fi + if [ -n "$GPU" ]; then set -- "$@" --gpu "$GPU"; fi + if [ -n "$LAYER_SPLIT" ]; then set -- "$@" --layer-split "$LAYER_SPLIT"; fi + .venv/bin/python setup.py --setup --yes "$@" + [ -e "/opt/strata/strata-$tag.json" ] && { cmp -s "/opt/strata/strata-$tag.json" "$cfg" || cp -f "/opt/strata/strata-$tag.json" "$cfg"; } +else + [ -e "/opt/strata/strata-$tag.json" ] || ln -s "$cfg" "/opt/strata/strata-$tag.json" +fi + +# Later starts skip straight here: setup.py finds the installed config and +# launches serve/server.py (OpenAI- and Anthropic-compatible API on :8080). +# GPUS / GPU / LAYER_SPLIT are repeated on purpose. Given at the start they pin the +# cards for this model, and setup.py saves them in its config; without them a config +# that names one card is offered once to a pair, on its own, when the host has two +# cards that can share the model (setup.py's offer_together, docs/MULTI_GPU.md). +set -- --port "$PORT" +if [ -n "$GPUS" ]; then set -- "$@" --gpus "$GPUS"; fi +if [ -n "$GPU" ]; then set -- "$@" --gpu "$GPU"; fi +if [ -n "$LAYER_SPLIT" ]; then set -- "$@" --layer-split "$LAYER_SPLIT"; fi +exec .venv/bin/python setup.py "$@" diff --git a/docs/AI_SETUP.md b/docs/AI_SETUP.md new file mode 100644 index 0000000..3eb9dfc --- /dev/null +++ b/docs/AI_SETUP.md @@ -0,0 +1,200 @@ +# Installing Strata for a user (instructions for AI agents) + +This page is written for an AI coding assistant (Claude Code, Cursor, Codex, GitHub Copilot, ...) that a user asked to +set up Strata on their PC. Strata runs the Qwen3.8-Flash-Next model locally on one NVIDIA or AMD graphics card plus +system RAM, and serves an OpenAI- and Anthropic-compatible API on `http://127.0.0.1:8080`. The human-oriented +version of everything below is [INSTALL.md](INSTALL.md). + +Work through the steps in order. Tell the user what you are doing in plain words; they may not be technical. + +## 0. Ground rules + +- **Never expose the server without an API key.** Keep the default `--host 127.0.0.1`. Only if the user asks for + access from other devices, use `--host 0.0.0.0` **together with** `--api-key `, and give the + user the key. Never put a tunnel or port forward in front of a server without a key. +- Do not change the user's system beyond what setup does (setup installs Python for the user account if needed, + and everything else inside the Strata folder and its `Strata-data` folder). Ask before installing drivers. +- The model download is ~70 GB (94 GB for Unsloth's UD-IQ4_XS, 111 GB for UD-Q4_K_XL). Confirm the user is fine with that before you + start, especially on a metered connection. +- Setup is long-running (an hour or more on a slow connection). Run it in the background or with a long timeout and + poll its output; do not kill it because it is quiet for a while. It is resumable: running the same command again + continues where it stopped. + +## 1. Check the PC + +The quickest way is setup's own check, which prints the GPU(s), driver, RAM, CPU, free disk and whether this PC can run +Strata, and installs nothing except Python and the `.venv` it needs to run (step 2 gets the repository first): + +``` +Windows: START-HERE.bat --check +Linux: ./setup.sh --check +``` + +To check by hand: + +| What | Windows (PowerShell) | Linux | +| --- | --- | --- | +| OS | `[Environment]::OSVersion` | `cat /etc/os-release` | +| NVIDIA GPU, VRAM, driver | `nvidia-smi --query-gpu=index,name,memory.total,driver_version --format=csv` | the same | +| AMD GPU | `Get-CimInstance Win32_VideoController \| Select-Object Name, AdapterRAM` (AdapterRAM is capped at 4 GB; trust the model name) | `lspci \| grep -i -E 'vga\|display'`; VRAM: `cat /sys/class/drm/card*/device/mem_info_vram_total` (bytes); `rocm-smi` only if ROCm is installed | +| RAM | `(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB` | `free -g` | +| Free disk | `Get-PSDrive -PSProvider FileSystem` | `df -h .` | + +Requirements (details: [INSTALL.md](INSTALL.md#what-you-need)): + +- **GPU:** NVIDIA RTX 20, 30, 40 or 50 series, 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; 12 GB of VRAM or more (an NVIDIA card with 8 GB runs, + slowly). GTX 10 series and older, and integrated GPUs, are not supported; Pascal / Volta cards (P40, V100) and some + older AMD cards have experimental paths the user opts into ([OLDER_GPUS.md](OLDER_GPUS.md)). +- **Driver:** NVIDIA 580 or newer. AMD on Linux: the kernel's amdgpu driver; on Windows: a current AMD Adrenalin + driver. If the driver is missing or too old, tell the user to update it (NVIDIA App / nvidia.com/drivers, or AMD + Software) and restart; do not install drivers yourself unless they ask. +- **RAM:** 32 GB or more (see step 3). **Disk:** ~80 GB free, ideally on an NVMe SSD. **CPU:** x86-64 with AVX2. Without AVX2 (Xeon E5 v1/v2 and older) setup still installs, as an experimental and slow build it compiles on the PC (10-20 minutes): tell the user that before starting ([INSTALL.md](INSTALL.md#older-cpus-experimental)). +- **OS:** Windows 10/11 or Linux (Ubuntu 22.04/24.04 are fully automatic). + +If the PC does not meet them, say which part is missing and stop. + +## 2. Get Strata + +``` +git clone https://github.com/Niko1221/Strata.git +``` + +Without git: download https://github.com/Niko1221/Strata/archive/refs/heads/main.zip and unzip it. Pick a drive with +enough free space: the model files go to a `Strata-data` folder **next to** the Strata folder (or `--data-dir ` +on another drive). + +## 3. Pick the model + +By the PC's RAM (ask the user whether they mainly want it for code - then the Coder is a good pick at any RAM size): + +| RAM | `--family` / `--model` | Notes | +| --- | --- | --- | +| 32 GB | `--family coder` (size IQ1_M) | for code; with a 24 GB card Q2_0 and IQ2_XS also run (setup picks the low-RAM mode) | +| 48 GB | `--family qwen --model IQ2_XS` | or `Q2_0` (fastest) | +| 64 GB | `--family qwen --model IQ2_XS` (recommended) | `IQ3_XXS` / `IQ3_S` are slower and a bit better | +| 96 GB+ | `--family qwen --model IQ3_S` | `--family unsloth --model UD-IQ4_XS` (~4-bit, 94 GB, part of the experts read from the SSD under ~80 GB of RAM); `--model UD-Q4_K_XL` is experimental: NVIDIA only, NVMe SSD, 7-8.5 tokens/s on 64 GB | + +`--family swift` (Swift 1.5, a fine-tune that thinks shorter; sizes Q2_0, IQ2_XS, IQ3_XXS) is the alternative to +`qwen`. With `--yes` and no `--model`, setup picks the recommended size for the RAM itself. More: [MODELS.md](MODELS.md). + +## 4. Run setup without questions + +From the Strata folder (Windows: in `cmd`, or `cmd /c START-HERE.bat ...` from PowerShell): + +``` +Windows: START-HERE.bat --yes --family qwen --model IQ2_XS --no-start +Linux: ./setup.sh --yes --family qwen --model IQ2_XS --no-start +``` + +The flags (all of them: `START-HERE.bat --help`): + +| Flag | Meaning | +| --- | --- | +| `--yes` | take the recommended answer to every question (no prompts) | +| `--family qwen\|swift\|coder\|unsloth` | the model version | +| `--model Q2_0\|IQ2_XS\|IQ3_XXS\|IQ3_S\|IQ1_M\|UD-IQ4_XS\|UD-Q4_K_XL` | the size (the Coder is IQ1_M, Unsloth UD-IQ4_XS or UD-Q4_K_XL) | +| `--context N` | context in tokens; default by VRAM: 32768 under 14 GB, 65536 under 20 GB, else 131072 | +| `--vision yes\|no\|gpu\|cpu` | read pictures; `--yes` leaves images off. AMD cards: `cpu` | +| `--gpu N` / `--gpus 0,1` / `--gpus all` | one card, or several sharing the model (default: the card with the most VRAM) | +| `--backend cuda\|hip` | NVIDIA or AMD engine; chosen by itself on a PC with only one kind of card | +| `--data-dir PATH` | where the 70-120 GB of model files go | +| `--port N` | the server port (default 8080) | +| `--host H --api-key K` | listen beyond this PC; **only together with a key** | +| `--no-start` | install only, do not start the server | +| `--setup` | install another model or change settings of an installed one | +| `--check` | only check the PC | + +`--no-start` is recommended for agents: the server runs in the foreground until its window is closed, which would +block your shell. Start it separately in step 6. + +Notes: +- **Linux:** setup uses `sudo apt` (or dnf/pacman) to install Python with venv if it is missing, and on AMD may need + `build-essential` and `git`. You cannot type the user's password: if a `sudo` step is needed, ask the user to run it + (e.g. `sudo apt install python3-venv build-essential git`) and then rerun setup. +- **AMD on Linux:** setup installs ROCm into `.venv` (~10 GB, no sudo) unless a system ROCm 7 exists, and compiles the + engine for the card (10-20 minutes, once). +- **AMD on Windows (new in 0.1.34):** setup downloads the ready-made AMD engine (~550 MB, ROCm included) - nothing + is compiled and only the AMD driver is needed. Before the model download it runs `engine\strata-device.exe + --list-devices`; if that does not list the card, the driver is the problem (tell the user to update AMD Software). + One card per model and no images on Windows for now. It is new: ask the user to report how it runs (docs/AMD_HIP.md). +- **NVIDIA with no ready-made engine for the card:** setup offers to install build tools and compile (20-40 minutes); + `--yes` accepts. + +## 5. While it downloads, tell the user + +- It downloads about 70 GB from Hugging Face; how long depends on their connection (at 100 Mbit/s roughly 1.5-2 + hours). It can be stopped and continues where it left off. +- Then it prepares the model for their PC (a few minutes) and, on AMD on Linux, compiles the engine. +- **When the model starts, the PC can be slow or stop responding for 1-3 minutes** (longest the first time): Strata + loads 35-55 GB into RAM and locks part of it for the graphics card. That is normal; they should not close the window. +- Nothing leaves their PC: the model runs locally. + +## 6. Start the server + +Setup prints the start script it wrote (`start script: run-.bat`). The name is the family tag plus the size, +lower case: `run-iq2_xs`, `run-swift-iq2_xs`, `run-coder-iq1_m`, `run-unsloth-ud-iq4_xs`. + +``` +Windows (PowerShell): Start-Process -FilePath ".\run-iq2_xs.bat" (opens its own window) +Linux: nohup ./run-iq2_xs.sh > strata-server.out 2>&1 & +``` + +Or `START-HERE.bat` / `./setup.sh` without flags, which starts the installed model (it asks which one when several are +installed; add `--yes` to take the first). The server opens the user's browser on `http://127.0.0.1:8080` when it is +ready. Closing its window (or stopping the process) stops the model. + +## 7. Verify + +The HTTP server answers once the model is loaded (30-90 s on later starts, a few minutes the first time). Poll: + +``` +curl http://127.0.0.1:8080/health +``` + +It returns `{"status": "ok", "model": ..., "max_context": ..., "images": ..., "api_key": ..., "loaded": true, ...}`. +Then: + +``` +curl http://127.0.0.1:8080/v1/models +curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" -d "{\"model\": \"strata\", \"messages\": [{\"role\": \"user\", \"content\": \"Say hello in five words.\"}], \"max_tokens\": 64, \"reasoning_effort\": \"none\"}" +``` + +With an API key, add `-H "Authorization: Bearer "`. The server window prints a `ready: http://127.0.0.1:8080/v1` +line when it is ready; the engine log is `strata-.log` in the Strata folder. + +## 8. Connect the user's apps + +- **Browser:** `http://127.0.0.1:8080` - Chat, a live Monitor, and About (settings and addresses). +- **Any OpenAI-compatible app or agent:** base URL `http://127.0.0.1:8080/v1`, any API key (or the configured one), + any model name. +- **Anthropic-compatible apps:** `http://127.0.0.1:8080/v1/messages`. +- **Codex CLI and other Responses API apps:** `http://127.0.0.1:8080/v1/responses` (stateless; Codex's + `config.toml`: [DETAILS.md](DETAILS.md#the-responses-api-and-codex-cli)). +- **Claude Code:** `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`, `ANTHROPIC_MODEL` set to a Claude model name it knows + (Strata ignores the name), and any `ANTHROPIC_AUTH_TOKEN` (or the configured key). +- **Thinking level:** `"reasoning_effort": "none" | "low" | "medium" | "high"` (default high). +- Strata answers one request at a time; `"parallel": N` in the model's config (or setup `--parallel N`) decodes up to + N together ([BATCHING.md](BATCHING.md)). API details: [DETAILS.md](DETAILS.md#using-it). + +## 9. When something fails + +| Symptom | What to do | +| --- | --- | +| `the NVIDIA driver is too old` | The user updates the driver (NVIDIA App or nvidia.com/drivers) and restarts; rerun setup. | +| Download or install stopped | Rerun the same setup command; it continues. | +| `port 8080 is already in use` | Strata is already running (check `/health`), or use `--port 8081`. | +| Very slow, disk busy, or "the engine stopped unexpectedly" | Not enough free RAM: close programs, or set up a smaller size (`--setup --model Q2_0` or IQ2_XS). | +| `ExpertCache: cudaMalloc(...) failed: out of memory` with free VRAM (Windows) | The page file is off or tiny: set it to "System managed" and restart. | +| `prompt ... exceeds the context` | Rerun setup with `--setup --context `. | +| No AMD GPU found (Linux) | The amdgpu driver lists no GPU; check the card and driver. Integrated GPUs are not supported. | +| Python or build tools could not be installed | Install what the message names (links are printed), then rerun. | + +More: [TROUBLESHOOTING.md](TROUBLESHOOTING.md) and the [full table](DETAILS.md#troubleshooting). If it still fails, +collect `strata-.log` and the setup output, and suggest an issue at https://github.com/Niko1221/Strata/issues. + +## Alternative: the MCP server + +Strata also has an MCP server, so an AI tool can check, install, start and stop Strata through tool calls +(`strata_status`, `strata_models`, `strata_install`, `strata_start`, `strata_stop`, `strata_logs`) instead of the +shell commands above. See [MCP_SERVER.md](MCP_SERVER.md). diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md new file mode 100644 index 0000000..35b0626 --- /dev/null +++ b/docs/AMD_HIP.md @@ -0,0 +1,499 @@ +# AMD Radeon: the HIP backend (gfx1100, gfx1101, gfx1200, gfx1201, gfx1030) + +Strata runs on AMD Radeon cards through its HIP backend, the same engine as on NVIDIA compiled for AMD. This page +covers the build on Linux (on Windows a ready-made engine, see [Windows](#windows)) for the RX 7900 XT / XTX (RDNA3, gfx1100) and the +RX 9070 / 9070 XT / Radeon AI PRO R9700 (RDNA4, gfx1201; see [RDNA4](#rdna4-gfx1201)). The RX 7800 XT / 7700 XT +(gfx1101) and the RX 9060 XT (gfx1200) were validated by their owners (see [Community-validated +cards](#community-validated-cards)); the RX 6800 / 6900 series (RDNA2, gfx1030) builds and runs too, reported by a community machine and not yet validated by the maintainers (see [RDNA2](#rdna2-gfx1030)). Setup chooses it by itself on a PC with no NVIDIA card Strata can use (`--backend hip` on a PC with both); the +install steps for users are in [INSTALL.md](INSTALL.md#amd-cards). gfx906 (Instinct MI50 / MI60, Radeon VII; wave64) has a separate +opt-in build, see [gfx906](#gfx906-instinct-mi50--mi60-radeon-vii-wave64-built-from-source). Other AMD architectures and mixed +AMD/NVIDIA execution in one run are not supported. + +The backend maps the CUDA-shaped runtime and BLAS calls to HIP/hipBLAS, uses +RDNA2/RDNA3/RDNA4's signed integer dot instruction for quantized kernels, and supplies +wave32 shuffle/packed-byte operations. CUDA-only QSA matrix instructions have +an ordered FP32 fallback. Prefill supports both dequantization plus hipBLAS GEMM and opt-in HIP ggml MMQ. +An optional, calibrated hipBLASLt path accelerates dense projections (per-architecture tables in `tools/hip`). +This does not claim bit-identical model answers across backends. See +[performance settings and evidence](AMD_HIP_PERFORMANCE.md). + +## Install with setup (recommended) + +On Linux with an RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT or Radeon AI PRO R9700 and +the kernel's amdgpu driver (no ROCm install needed): + +```sh +./setup.sh --backend hip +``` + +- **Detection:** setup finds the card through the kernel's KFD topology. Integrated Radeon GPUs are listed as not + supported. On a PC without an NVIDIA card Strata can use, `--backend hip` is chosen automatically. +- **ROCm:** a system ROCm 7 in `/opt/rocm` (or `$ROCM_PATH`) with hipcc and hipBLAS is used when present. Otherwise + (or when it is older than 7.0) ROCm is installed into `.venv` from AMD's TheRock wheels (~10 GB, no sudo), pinned + to the version this backend was tested with, from the card family's index: `gfx110X-dgpu` for gfx1100 / gfx1101, + `gfx120X-all` for gfx1200 / gfx1201, `gfx103X-all` for gfx1030 (`STRATA_ROCM_VERSION` / + `STRATA_ROCM_INDEX` override them; the gfx1030 index is not checked to carry the pinned version: a system + ROCm 7 is the tested path there). +- **Engine:** compiled on your PC for the card's architecture (10-20 minutes, once; again after a `git pull` that + changes it, or when you pick a card of another architecture). This needs a C++ compiler and git + (`sudo apt install build-essential git`). +- **hipBLASLt tuning table:** setup uses `tools/hip/-hipblaslt-.txt` only when it matches both the + card's architecture and the installed hipBLASLt version (read from `hipblaslt-version.h`; 1.2.0 is `100200`). + Otherwise it says so and the prompt's dense matrix products use plain hipBLAS (slower prompts, same answers). + A table's solution ids are valid only for that pair, and the engine refuses any other table. +- **Several cards:** setup takes one card (the one with the most VRAM, or `--gpu N`) unless you name more: + `./setup.sh --backend hip --gpus 1,0` splits the model's layers across them, the first one the main card (numbers + as setup lists them; `--gpus all` = every supported card, the most VRAM first). Every chosen card must be one of the + architectures above; the engine is compiled for each of them (cards of two families, e.g. gfx1100 + gfx1201, need + a system ROCm 7: AMD's wheels hold one family). A split pays only when no single card holds the model's experts + (see RDNA4 below). +- **Limits for now:** images only through the CPU encoder (`--vision cpu`, 0.1.32). Setup does not offer the tuning + (calibration) on AMD yet: its controls are being checked on HIP one at a time (#566). Since 0.1.39 a tuning run by + hand (`./setup.sh --calibrate`) is saved for the AMD card it ran on and reused when setup runs again. The Monitor + shows the card's load, VRAM, temperature and power from Linux sysfs (0.1.32). + +The rest of setup is the same as on NVIDIA: the model download, the start script, the server. + +## Windows + +Since 0.1.34 an AMD card on Windows is set up like an NVIDIA one: download Strata, double-click `START-HERE.bat`. +On a PC with no NVIDIA card Strata can use, the AMD card is chosen by itself; with both, setup asks +(`START-HERE.bat --backend hip` picks AMD directly). + +- **You need:** Windows 10 or 11 (64-bit), one of the cards above, and a current AMD driver ([AMD Software: + Adrenalin Edition](https://www.amd.com/en/support/download/drivers.html)). Nothing else: no ROCm or HIP SDK + install, no compiler, no admin rights. +- **Detection:** setup reads the display adapters Windows lists (their PCI ids; the VRAM size from the display + driver's registry entry). An integrated Radeon is listed as not supported. +- **Engine:** the ready-made `strata-windows-x64-hip.zip` from the release (built by `tools\hip\build_windows.bat` + for gfx1100, gfx1101, gfx1102, gfx1200, gfx1201 and gfx1030) goes into `engine\`. It carries the ROCm libraries the + engine loads (`engine\rocm\bin`: the HIP runtime, hipBLAS / rocBLAS / hipBLASLt with their kernels for these cards, + amd_comgr and the Microsoft C++ runtime; ROCm 10.2.0a20260930 from AMD's TheRock builds, licenses in + `engine\rocm\licenses`). The HIP runtime works through the AMD driver's own components, so the driver is the one + thing it needs from the PC. +- **The HIP runtime next to `strata.exe` (0.1.35, #468 #461):** `amdhip64_7.dll` and `amd_comgr.dll` are also put in + `engine\` (setup copies them there on every start). Windows looks in the program's folder before System32, where + some AMD drivers install their own `amdhip64_7.dll`; with that one, the bundled libraries crashed on the first + prompt (an access violation, or `hipErrorInvalidDeviceFunction`). The engine's log names the runtime it loaded + (`strata generate: HIP runtime ...`). +- **Before the ~60 GB model download** setup runs `engine\strata-device.exe --list-devices` (with `engine\rocm\bin` on + the PATH): if the HIP runtime does not see the card, setup stops there and points to the driver. It also gives the + card's HIP number: with an integrated Radeon that is device 1, not 0 (#325). From then on setup lists the AMD cards + as HIP numbers them, so `--gpu N` and the config's `"gpu"` are HIP numbers. +- **Differences from Windows-on-NVIDIA and Linux-on-AMD:** no images yet (the CPU image encoder is Linux-only for + now), one card per model (`--gpus` is Linux-only for now), no calibration. +- Two Windows-only engine details (#247, #325): hipBLAS can return success and still leave `hipErrorInvalidValue` + set after some BF16/FP16 GEMMs (seen on gfx1201); the engine clears that one stale error after a GEMM that + succeeded, on Windows only. `hipHostGetDevicePointer` returns the host pointer itself on Windows: kernels read + mapped memory through it correctly, but a device-to-device copy into it does not land, which is why + `tests/hip/handoff` times out there (the engine does not use that copy; `tests/hip/mapped_alias` reports it). +- Two more (#380, #377, by BlueKingMuch, measured on an RX 6800 that drives the desktop): `hipMemGetInfo` on Windows + does not subtract what the desktop and other programs hold on the card, so `--expert-cache auto` filled the card + past what Windows keeps in VRAM and decode fell from 41 to 30 tok/s. The engine now lowers that free figure by + what Windows' video memory budget for the process withholds (logged once: `strata: Windows budgets N of this + card's M MiB ...`; `STRATA_WDDM_BUDGET=0` turns it off). And the PCIe probe times its copies on the host clock + there, since HIP's events read impossible speeds (3,300-26,000 GB/s), so a slow link now gets a smaller + `pcie_frac` as on NVIDIA. + +**What is validated (0.1.34):** #325's author ran the engine of this port on an RX 9070 XT (Windows 11, ROCm +10.2.0a20260930 in `.venv`, compiled on the PC): Coder IQ1_M at 32K, 29.2 tok/s decode, ~181 tok/s prefill, +correct answers; ctest 42 of 46. The maintainers have no Windows AMD card: the release zip was built on an NVIDIA PC, +and checked there on the Ryzen CPU's integrated Radeon (gfx1036, a test build of the same tree): with only the zip's +libraries on the PATH, `strata-device` lists the card and a hipBLAS BF16 GEMM matches the CPU; the HIP ctest passes +52 of 56, the 4 failures the same as on the RX 9070 XT (`hip_handoff`, and three tests that need a pack fixture). +The ready-made zip itself has not run a model on a discrete card yet - please report. + +**Reporting a Windows AMD run** (an issue, or on #325): your card and driver version (AMD Software > System), then + +```bat +engine\strata-device.exe --list-devices +engine\strata-device.exe --selftest +``` + +(from the Strata folder, after `set PATH=%CD%\engine\rocm\bin;%PATH%`), the end of `strata-.log`, and the +speed lines the server window prints for a first answer. + +**Building it yourself:** `tools\hip\build_windows.bat` (Visual Studio 2022 Build Tools with the C++ workload, Python, +git; no admin, no AMD GPU) installs ROCm from AMD's TheRock wheels into `.rocm-win`, builds, and packages +`dist\strata-windows-x64-hip.zip`; `START-HERE.bat --backend hip --prebuilt dist\` installs that one. +`tools\hip\build_windows.bat tests` also builds the HIP tests (`ctest` in `build-hip-win`, with +`.rocm-win\Lib\site-packages\_rocm_sdk_devel\bin` on the PATH). `STRATA_HIP_ARCHS` picks other architectures. + +## Build + +Requirements: a working ROCm driver/runtime, HIP development headers and +compiler, hipBLAS and (for tuned dense prefill) hipBLASLt development files, CMake 3.24+, a C++20 host compiler, and Git. +The model still needs sufficient system RAM and fast SSD storage for its PLE +table. VRAM occupancy alone is not a throughput measurement. + +```sh +cmake -S . -B build-hip \ + -DCMAKE_BUILD_TYPE=Release \ + -DSTRATA_ENABLE_HIP=ON -DSTRATA_ENABLE_CUDA=OFF \ + -DCMAKE_HIP_ARCHITECTURES=gfx1100 +cmake --build build-hip --target strata -j2 +``` + +`CMAKE_HIP_ARCHITECTURES` is `gfx1100`, `gfx1101`, `gfx1200`, `gfx1201`, or a list such as `"gfx1100;gfx1201"` +(one binary for both). gfx1102 (the same wave32, 64 KiB LDS and dot4 instruction) builds with a warning: it passed +ctest (#192) but no model run has been reported; so does gfx1030 (RDNA2: the older `v_dot4_i32_i8`, a community run in #311). At startup the engine and `strata-device` compare each GPU they use +(`gcnArchName` up to the `:` feature suffix) with the architectures the binary was compiled for, and require +wave32. A binary carried to another card stops with the card's name, its architecture and the build's list, +instead of failing later with "invalid device function". + +If CMake cannot find the HIP compiler, add +`-DCMAKE_HIP_COMPILER=/path/to/rocm/llvm/bin/clang++`. On the Fedora-family test +host this was `/usr/lib64/rocm/llvm/bin/clang++`. Use the compiler and libraries +from the same ROCm installation. Do not enable both GPU backends in one build. + +Native IQ experts are enabled by default. CMake fetches the llama.cpp revision +pinned by this repository. For an offline build, point `STRATA_GGML_DIR` at a +checkout of that exact revision; using an arbitrary newer checkout changes the +dependency being tested. + +## Model and serving configuration + +Prepare a supported model pack and its MTP runtime using the existing tools. +For OrcaRouter IQ3_XXS, follow [the explicit compatibility conversion](ORCA.md); +this backend does not change quantization, model licenses, or tokenizers. +Add `--experts-bin` to the `tools/iq_pack.py` command: mmap requires the pack's +`experts.bin`, which the default native packing command does not emit. This +consumes additional disk space. Original GSQ-RCO IQ3_XXS uses shard 2 for PLE; +Orca uses shard 1. Keep each model's own pack and tokenizer together. + +Use `build-hip/strata` as the executable in the server JSON. Select the AMD +device with `ROCR_VISIBLE_DEVICES`/`HIP_VISIBLE_DEVICES` if necessary. Start with +a modest context and prefill chunk size before measuring larger workloads. +Keep the PLE file on an SSD. Do not assume a configured context length proves +successful full-window inference. + +Large pinned host allocations can fail on ROCm even when ordinary RAM is +available. The existing `--mmap-experts` path avoids allocating the full pinned +expert arena; it still depends on OS file-cache residency and may stall on +storage reads. It does not make SSD access equivalent to RAM. + +Starting args for the original GSQ-RCO IQ3_XXS model (replace the paths): + +```sh +build-hip/strata --serve \ + --pack packs/iq3xxs \ + --native /path/to/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf \ + --ple-gguf /path/to/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf \ + --mmap-experts --expert-profile data/expert-profile.bin --expert-cache auto \ + --prefill 512 --spec 4 --spec-min-p 0.5 --mtp mtp/rt \ + --max-context 4096 --kv int8 --pool-workers 15 \ + --adapt-every 0 --pcie-frac 0 --vram-reserve-mib 1024 +``` + +`--serve` is the engine's internal token protocol. For a browser or OpenAI API, +put these args in the `args` array of the [server JSON example](ORCA.md#local-server), +set `exe` to `build-hip/strata`, and use the matching pack's `tokenizer` directory. +Launch with `.venv/bin/python -m serve.server --engine strata --config strata-hip.json --port 8080`. +The worker count above was used on a 16-core CPU; measure it for your CPU. +The 4K context is a smoke-test starting point, not a model limit. The expert cache +sizes itself automatically and leaves 1 GiB of VRAM headroom. + +**The card also drives a Linux desktop (#560 #516):** keep more VRAM free than the default 700 MiB, e.g. +`./setup.sh --vram-reserve-mib 3072`. With the cache filling the card, the desktop's next VRAM need makes amdgpu move +GPU memory to system RAM (GTT), the OOM killer then ends KWin/plasmashell or `systemd-oomd` ends apps, or the +compositor fails with "Failed to pin framebuffer with error -12". + +The installer supports this backend (see "Install with setup" above). Images run through the CPU encoder for now (`--vision cpu`). +Setup installs one AMD card, or several with `--gpus` (the engine's layer split; see RDNA4 below). + +## RDNA4 (gfx1201) + +The RX 9070 / 9070 XT and the Radeon AI PRO R9700 run the same kernels as gfx1100: wave32, 64 KiB of LDS per +workgroup, the signed dot4 instruction (`v_dot4_i32_iu8` through `__builtin_amdgcn_sudot4`) and a 100 MHz wall +clock. The first report and patch came from doplxyz (#178). Validated on 2026-09-30 on doplxyz's test machine: +an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 3900X (16 threads, no AVX-512), +47 GB RAM, Ubuntu 24.04 in a KVM/VFIO guest. + +- **Build:** complete HIP build with tests (`-DCMAKE_HIP_ARCHITECTURES=gfx1201 -DSTRATA_BUILD_TESTS=ON + -DSTRATA_PREFILL_MMQ=ON`), with the system ROCm 7.14 (hipBLASLt 1.4.1) and with setup's own path: TheRock + 7.10.0a20251120 wheels from `gfx120X-all` (hipBLASLt 1.2.0) and `build_engine_hip`. +- **ctest** (all 45 registered tests, R9700): 42 pass, `hip_prefill_hipblaslt_gemm` skips (no table), and two + fail for reasons outside the GPU: `ple_parity` needs the Q2_0 model fixture, `expert_multi_test` needs an + AVX-512 CPU. `hip_handoff` needed the volatile ring store: on gfx1201 a plain store to mapped pinned memory + stays in the GPU's L2 until the stream is synchronized. +- **Arch check:** a gfx1100-only build stops on the gfx1201 card at startup with the message above (engine and + `strata-device`). +- **End to end** (Coder IQ1_M, setup's arguments: `--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5`, + MTP, `--kv int8`, `--max-context 32768`; 128 greedy tokens, system ROCm 7.14, no hipBLASLt table). The answers + are coherent and the same on both cards. The live server smoke (`serve/server.py`: web page, models, props, + chat, prefix reuse, streaming, the Anthropic endpoint, a sampled code answer) passed 9/9 on each card. + + | card | expert cache | peak VRAM | 4K prompt | 4K decode | 16K prompt | 16K decode | + |---|---|---|---|---|---|---| + | Radeon AI PRO R9700 32 GB | 12,288 slots, 23.4 GiB | 29.7 GiB | 982 tok/s | 45.5 tok/s | 1,402 tok/s | 48.3 tok/s | + | RX 9070 XT 16 GB | 4,931 slots, 9.4 GiB | 15.6 GiB | 782 tok/s | 30.8 tok/s | 1,235 tok/s | 35.4 tok/s | + | R9700, TheRock 7.10 wheels | 12,288 slots | | 957 tok/s | 44.2 tok/s | 1,284 tok/s | 43.9 tok/s | + + The engine's resident memory was about 26 GB in every run. Since 0.1.31 `__byte_perm` is one `v_perm_b32` and the + packed byte subtracts/compare work on four lanes at once (#262, ttio2tech): decode +15% on the R9700 (46.0 -> 53.0 + tok/s on a 4K prompt, 52.0 -> 60.5 warm) and +5-7% on the 9070 XT, prompts unchanged, the same tokens. +- **hipBLASLt:** the validation above used hipBLASLt 1.4.1. A table calibrated on the R9700 at the engine's shapes + with that version (0.98-1.76x per GEMM over hipBLAS) changed the end-to-end prompt speed by 0-3%, within noise, + so none was shipped for it: there the plain hipBLAS path is already close. For hipBLASLt 1.5.0 (ROCm + 10.2.0a nightly) `tools/hip/gfx1201-hipblaslt-100500.txt` is shipped (see "Tuning table" below); on one R9700 it + measured +3.9% prompt speed on 4,210-token prompts (1,590 vs 1,531 tok/s), a modest gain. + With the hipBLASLt 1.2.2 of a system ROCm 7.2.4 the plain path is far off, and `tools/hip/gfx1201-hipblaslt-100202.txt` + is shipped for it (24 of the gfx1100 table's 26 shapes; setup uses it only with that exact version): on an R9700 + with the full IQ3_XXS, `--kv int8 --kv-resident 32768`, a fresh 32K prompt read at 638 -> 1,177 tok/s and a 7K one + at 656 -> 1,164 tok/s with it, decode unchanged. `hip_prefill_hipblaslt_gemm` passes with it. +- **Both cards in one run (layer split, engine 0.1.30):** the config's `"backend": "hip", "gpu": [1, 0]` (R9700 + first) runs through `serve/server.py` (setup writes it with `--gpus 1,0` since 0.1.31). Auto split put layers 0-27 on the R9700 and + 28-47 on the 9070 XT. With every expert on the GPUs the split gives exactly the tokens of the R9700 alone (4K and + 16K prompts); checkpoints on the split (second turn, rewind, a prompt sharing a prefix, a cancelled prompt + retried) give exactly the tokens of a fresh read. The conversation cache refuses a split at start (exit 2). + On this pair the split does not pay: the R9700 alone already holds all 12,288 expert pairs. + + | run (the same session, warm) | 4K prompt | 16K prompt | decode | + |---|---|---|---| + | R9700 alone | 1,794 tok/s | 1,804 tok/s | 51-52 tok/s | + | R9700 + 9070 XT, auto split | 1,384 tok/s | 1,906 tok/s | 42-43 tok/s | + | RX 9070 XT alone | 1,016 tok/s | 1,519 tok/s | 38-40 tok/s | + + A split is worth it when no single card holds the model's experts. Since 0.1.31 a split pins the whole expert + arena on Linux (the 8 GiB cap is for Windows/WSL2 only, #253): with an expert cache of 1,500 on the R9700 (most + experts streamed) the split read a 16K prompt at 1,803 tok/s instead of 1,287, with the same tokens in 5 + 5 + starts. `"split_skip_if_fits": true` in the config (0.1.31, opt-in) runs such a pair on the first card alone when it + holds every profiled expert: with the R9700 first, 4K prompts 1,776 tok/s (split: 1,244) and decode ~60 tok/s + (split: ~51), the tokens of the R9700 alone (docs/MULTI_GPU.md). +- **Speed switches (engine 0.1.32, measured on the R9700 / 9070 XT with the Coder IQ1_M pack):** + - the MoE router (`router_top10`) runs a HIP kernel without its serial FP64 sum and block barriers by default: the + same ids and weights bit for bit (`hip_router_fast` checks 65,536 rows), 39 -> 9-12 us per call, the same greedy + tokens (5 + 5 starts). Decode: 62.4 -> 70.0 tok/s on the R9700 and +4% on the 9070 XT in one A/B here (ROCm 10.2 + nightly); a user's repeated A/B/A/B with setup's TheRock 7.10 wheels and an i5-12600K measured +1-4%, inside a + 12-20% run-to-run spread (#432) - how much it gains depends on how much of decode the router is on that setup. + `STRATA_HIP_ROUTER_OLD=1` runs the portable kernel. + - `STRATA_HIP_WMMA=1` (opt-in, gfx12 only, int8 KV): the prompt path's QSA attention on RDNA4 matrix cores + (`v_wmma_f32_16x16x16_f16`, FP16 hi + lo halves like the CUDA tensor-core kernel; `hip_prompt_attn_wmma` bounds it + against the FP32 kernel and FP64). 7.2-7.5x the portable kernel; R9700 prompts 4K 1,784 -> 2,427 tok/s, 16K + 1,797 -> 2,700 (a user with TheRock 7.10: +29-34%, #432). Not bitwise: greedy text differs from token ~50 on, as with the CUDA tensor-core attention. With it + the prompt path's expert ring is 96 slots (as STRATA_PREFILL_RING=96): with the default 384 the 9070 XT's 4K + prompts fell to 718 tok/s; with 96 they gain (1,017 -> 1,211; 16K 1,518 -> 2,032). PR #329 + (bsorensen110) contributed an equivalent gfx12 WMMA kernel of the same speed (within 1%); this one also masks KV + pages that KV streaming has not made resident, as the decode kernel does. + - The prompt path's QSA top-k picks its kernel by the blocks a query actually has, not the cache's capacity (#337, + bsorensen110): the same ids, on by default with AMD (NVIDIA keeps its capacity rule: there the 64K prompts read + 1-3% slower with it). `STRATA_SELECT_WMMA=1` (opt-in, gfx12) adds #337's + matrix-core block scorer; it selects slightly differently (254 of 256 queries the same) and gained +1.5% on 16K + prompts at a 262K context on the R9700. +- **Known:** rarely (about 1 start in 10) a HIP run's greedy output differs from another start's at some token, on + one card or two and on engine 0.1.29 as well; not yet explained. +- **Not validated:** images, long contexts beyond 16K, answer-quality benchmarks. + +## Community-validated cards + +Run by their owners, not on the maintainers' machines; setup accepts them like gfx1100 / gfx1201. setup ships a +hipBLASLt table for gfx1200 (the numbers below); gfx1101 has none (make one with [Tuning table](#tuning-table) +and compare the prompt speed with and without it). + +- **gfx1101, RX 7800 XT 16 GB** (jhohertz, #254; engine 0.1.29, Ryzen 9 5950X, 121 GiB RAM, system ROCm with + hipBLASLt 1.4.1): `./setup.sh --backend hip` detected the card and compiled the engine; `strata-device --selftest` + passed; ctest 30/32 (`ple_parity` needs the Q2_0 fixture, `platform_memory_test` the memlock limit). Coder IQ1_M, + 64K context, MTP, with a table the owner calibrated: fresh prompts of 4K-9K tokens at 898-953 tok/s, decode + 38-44 tok/s (128 tokens). +- **gfx1200, RX 9060 XT 16 GB** (Efeisot, #256 after #176; engine 0.1.29, Ryzen 9 7950X, 64 GiB RAM, ROCm 7.2 with + hipBLASLt 1.2.2): ctest 32/32 (without `ple_parity` and `platform_memory_test`). Coder IQ1_M, greedy, MTP + `--spec 4 --spec-min-p 0.5`, with a table the owner calibrated: + + | prompt | prompt speed | decode | + |---|---|---| + | 2,374 tokens | 540 tok/s | 27.1 tok/s (0.69 draft acceptance; 31.0 at 1.00) | + | 65K (`--kv int8 --kv-resident 65536 --prefill 16384`) | 748-753 tok/s | 26-40 tok/s by acceptance | + | 130K (the same flags) | 725 tok/s | - | + + Greedy output was the same across runs. For comparison, llama.cpp's HIP build measured 20 tok/s decode and + 450 tok/s prompt on that card. + + Since 0.1.38 setup ships that table (`tools/hip/gfx1200-hipblaslt-100202.txt`). On engine 0.1.31, one binary (ctest + 37/37, without `ple_parity` and `platform_memory_test`), prompts of repeated code blocks, prefill 2560 for + the short prompt and 16384 with `--kv int8 --kv-resident 65536` otherwise, two runs each - prompt speed + with the table vs plain hipBLAS (no table): + + | prompt | with the table | plain hipBLAS | gain | + |---|---|---|---| + | 2,374 tokens | 597-599 tok/s | 396-398 tok/s | 1.50x | + | 65,045 tokens | 754-757 tok/s | 380 tok/s | 1.99x | + | 130,091 tokens (the same flags) | 719 tok/s | 363-370 tok/s | 1.98x | + +## RDNA2 (gfx1030) + +The RX 6800 / 6800 XT / 6900 XT / 6950 XT run the same kernels: wave32 and 64 KiB of LDS per workgroup. The one +difference is the dot instruction: RDNA2 has no `v_dot4_i32_iu8` (gfx11 and newer), so +`dp4a` uses the plain signed `v_dot4_i32_i8` through `__builtin_amdgcn_sdot4`, which compiles to a single +`v_dot4c_i32_i8` (same signed x signed byte products, modulo 2^32). There is no WMMA; the QSA scorer takes the +same ordered FP32 fallback as gfx1100. CMake lists gfx1030 as unvalidated (the build warns) until a maintainer has +run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx1030), an i7-13700KF (8 P-cores and +8 E-cores, AVX2, no AVX-512), 63 GB RAM, NixOS, ROCm 7.2.3 from nixpkgs (clang 22, hipBLAS 3.2). + +- **Build and tests** (engine 0.1.26): a complete HIP build for gfx1030, made by hand with cmake and ROCm's own + `clang++` (the nixpkgs ROCm is not an `/opt/rocm` tree, so setup's `build_engine_hip` was not exercised; the + binary was placed in `engine/` for setup to use). All 28 registered ctest tests pass on the card, including + `hip_device_selftest`. An engine 0.1.30 build of this branch configures, builds and runs clean on the same card; + the speeds below are measured on it. +- **End to end** (Swift 1.5 IQ3_XXS, `--context 131072` with `--kv-resident 32768 --adapt-every 1 + --vram-reserve-mib 1024`, 200 greedy tokens): 38-42 tok/s decode with the default 15 CPU pool workers (one per + physical core except the host thread; 8 workers: 36; 24 = every logical core: 27), consistent even with the + 131,072-token context full. +- **Prefill** (the same 15-worker configuration): 246 tok/s on a 2,000-token prompt, 330-339 tok/s at the auto + 8,192-token chunk (7,997 and 15,967 tokens; time to first token 8.9 and 48.3 s), 133 tok/s on a 522-token + prompt - short prompts are fixed overhead (19-25 tok/s on 34 tokens). Decode after a 16K prefill holds at + 45.5 tok/s. +- **16 GB card:** the expert cache holds 6,310 slots (10.2 GiB) at 16K context and 5,247 slots at 131,072, where + setup keeps the KV cache in VRAM because IQ3_XXS needs about 60 GB of RAM plus the cache to stream it. The + `--pcie-frac 0` and `--adapt-every 0` of the 7900 XTX configuration in + [AMD_HIP_PERFORMANCE.md](AMD_HIP_PERFORMANCE.md) cost 8.6 and 13.6 tok/s here (30 with the defaults): keep the + defaults on a 16 GB card. +- **hipBLASLt:** ROCm's hipBLASLt ships no gfx1030 kernels, so there is no table and the plain hipBLAS path runs. +- **gfx1031** (RX 6700 XT, #524): setup knows it (the `gfx103X-all` wheels, unvalidated); its reporter runs it daily + on one card. +- **Not validated:** gfx1032 (the same `dp4a` path, no hardware report), setup's own build path and the + `gfx103X-all` wheels on gfx1030, images, answer-quality benchmarks. RDNA1 (gfx1012, RX 5500 XT) builds by hand: + [OLDER_GPUS.md](OLDER_GPUS.md#amd-building-gfx906-and-gfx1012). + +## gfx906 (Instinct MI50 / MI60, Radeon VII): wave64, built from source + +gfx906 is wave64 and has no WMMA and no packed byte arithmetic, so the wave32 backend above refuses it. A separate opt-in build compiles the CUDA sources as HIP through a small compat layer +(`include/strata/platform/hip_compat/`), with a CUDA warp mapped to a logical half of the 64-lane wavefront +(32-wide shuffles, a ballot of its own half). The hot kernels have wave64 layouts of their own (below). Setup does +not build it yet: build by hand, and run `serve/server.py` with a config as on any other card. + +**ROCm.** AMD's current ROCm releases no longer ship gfx906 libraries. The build and the measurements below used +HIP 7.14 from the community image [`mixa3607/rocm-gfx906:7.14-complete`](https://hub.docker.com/r/mixa3607/rocm-gfx906) +(rocBLAS/hipBLAS with gfx906 kernels), on the kernel's amdgpu driver (Ubuntu 24.04, kernel 6.8). hipBLASLt is not +used. + +```sh +# inside the image, with this checkout at /src and llama.cpp at the pinned commit in third_party/llama.cpp +apt-get update && apt-get install -y cmake ninja-build git python3 build-essential +cmake -S . -B build-906 -G Ninja -DSTRATA_HIP_GFX906=ON -DCMAKE_HIP_ARCHITECTURES=gfx906 \ + -DSTRATA_GGML_DIR=/src/third_party/llama.cpp \ + -DCMAKE_C_COMPILER=/opt/rocm/llvm/bin/clang -DCMAKE_CXX_COMPILER=/opt/rocm/llvm/bin/clang++ +ninja -C build-906 strata +``` + +`STRATA_HIP_GFX906` turns on the CUDA targets and refuses `STRATA_ENABLE_HIP` (one HIP build at a time). Run the +container with `--device=/dev/kfd --device=/dev/dri --group-add video --ipc=host --ulimit memlock=-1`; on some boards +`HSA_OVERRIDE_GFX_VERSION=9.0.6` is needed for the runtime to accept the card. + +**What differs from the CUDA build** (all under `STRATA_HIP_GFX906`; each A/B switch restores the CUDA layout): + +| | gfx906 | switch | +|---|---|---| +| grouped native experts | mode 7: signs as `dp4a(g ^ m, u) - dp4a(m, u)` (no byte SIMD), grids and activations in LDS, one weight load per group; the IQ formats only (Unsloth's K-quant / Q5_1 / Q8_0 experts take the CUDA layout) | `STRATA_EXP_MODE=2` (previous AMD layout) | +| MMVQ | one wavefront per row, 64-lane butterfly, no LDS | `STRATA_MMVQ_WAVE=0` | +| router top-10 | one wavefront, register argmax | - | +| verify-window routing (256-expert router) | the window's tokens in one multi-column BF16 projection + one top-k, ~3 ms of a ~55 ms window | `STRATA_ROUTE_PER_TOKEN=1` | +| hyper-connection read | norm loads in flight, 8 lanes per row for `up` | `STRATA_GR_FAST=0` | +| `gr_down_multi`, opt-in | split along K (8 rows x 5 slices of 2048), ~3% per window; sums in another order than the single-token read, so off by default | `STRATA_GR_SPLIT=1` | +| IQ4 table lookup | llama.cpp's `v_perm_b32` sequence (HIP's `__byte_perm` is a scratch array) | - | +| QSA prompt attention | the FP32 kernel (no tensor cores / WMMA) | - | + +Every switch above was checked bitwise against the layout it replaces: the parity tests on synthetic data, +`native_expert_bench` on real GGUF rows (one mode against another), and the greedy text of a fixed request. + +**Measured** on 2x Instinct MI50 16 GB (85 W power limit each, PCIe 3.0 x16 both, peer access between them), +Xeon E5-2666 v3 (10 cores, AVX2), 32 GB DDR4, SATA SSD; Coder IQ1_M (`--native` pack), 131,072-token context, +`--kv int8 --kv-resident 32768`, `--layer-split 27`, `--prefill 4096`, MTP `--spec 4 --spec-min-p 0.5`, +`--pcie-frac 0`, `STRATA_ARENA_MMAP=1`. Measured on the port this build was cut from (builds on the 0.1.30 and 0.1.33 bases, the same +kernels, plus the layer-split weight trim and the mapped arena, which are separate pull requests): + +- all 12,288 experts held in VRAM across the two cards; +- a 17,043-token agent prompt (Claude Code's first request, tools included) read in 43.5 s (392 tok/s), decode + on it 57.7-59.3 tok/s; +- 25 GB of the 32 GB RAM available while serving; +- six repeats of that request with a 6,000-token output cap and a 900-second two-client load test run six times + (407 requests, 202,940 tokens): no stalls, no errors, no GPU faults. + +For comparison on the same machine: llama.cpp (3cf0325, ROCm) on the same Coder IQ1_M measured 26.9 tok/s `tg128`. + +**Not done:** setup.py detection and an automatic build, Windows, images (`--vision`), MI60 and Radeon VII (the +same gfx906 ISA; not run), a single-card run, the tensor-split experiment (the halves of every layer on two cards; +it works but is not part of this build). + +## Tuning table + +A hipBLASLt table holds solution ids that are valid only for one GPU architecture and one hipBLASLt version, so it +is calibrated on the card with the ROCm the engine runs with. The shipped gfx1100 table's rows are the engine's +dense GEMM shapes; to calibrate them for another card or version (a few minutes): + +```sh +cmake --build build-hip --target tune_hipblaslt +CASES=$(awk 'NR>2 {printf " --case %s,%s,%s,%s,%s", $1, $5, $2, $3, $4}' tools/hip/gfx1100-hipblaslt-100200.txt) +./build-hip/tune_hipblaslt $CASES --tuning-out table.txt +``` + +The file's second line names the architecture and version (`STRATA_HIPBLASLT_TUNING_V1 gfx1201 100401`); save it +as `tools/hip/-hipblaslt-.txt` for setup, or point `STRATA_HIPBLASLT_TUNING` at it. Compare the +prompt speed with and without it before keeping it. + +Shipped tables: + +- `gfx1100-hipblaslt-100100.txt`, `gfx1100-hipblaslt-100200.txt`: RX 7900 XTX. +- `gfx1201-hipblaslt-100500.txt`: Radeon AI PRO R9700 (gfx1201, 32 GB), calibrated with ROCm 10.2.0a20260914 + (AMD's `gfx120X-all` nightly, hipBLASLt 1.5.0, library build `d3164197`). 16 dense GEMM geometries at T=4096 and + T=8192, 32 rows. setup uses it only when the installed hipBLASLt reports 1.5.0 (it is found in `/opt/rocm` + when that is a system ROCm 7 or newer). The version number is the only thing the engine can check, so another + 1.5.0 build could number its solutions differently. `hip_prefill_hipblaslt_gemm` (with `STRATA_HIPBLASLT_TUNING` + set) is a smoke test: it refuses a table for another architecture or version and checks that one BF16 and one + F16 row exist and agree with hipBLASEx, which covers 2 of the 32 rows. It does not prove that a solution id is + valid: the engine falls back to hipBLASEx for an id the library rejects, and the test still passes. Run it with + `STRATA_HIPBLASLT_VERBOSE=1` and look for `fallbacks=0` in its summary line, and recalibrate with + `tune_hipblaslt` before using this table with a different 1.5.0 build. + +## Original backend validation (PR #94) + +The following is historical validation of the original backend, not a fresh +test count for this replacement. Current build/test evidence and performance +limits are recorded in [AMD_HIP_PERFORMANCE.md](AMD_HIP_PERFORMANCE.md). + +Tested against upstream `c1e903310f211e6630780c3bd2038778c071c68d` (0.1.20), +with pinned llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d`. +The host has an RX 7900 XTX (24 GiB), Ryzen 9 7950X3D, 64 GiB system RAM, +and Fedora-family Linux with ROCm 7.1.52802 / Clang 20. The original model used +for the smoke check was on mechanical RAID0; cold page faults were slow. Keep +latency-sensitive data on SSD and measure warm residency separately. + +- Complete HIP Release build, including the executable and parity targets. +- All 25 tests selected by the command below passed on 2026-09-29. +- Intrinsic parity includes signed packed-byte dot products and overflow. +- CPU/GPU mapped-memory handoff covers delayed publication, changing payloads, + and repeated graph replay in both directions. +- GR coverage includes the maximum eight-token fused batch and graph replay + after inputs change. Native QSA checks the scalar HIP fallback. +- Q8_K quantization is byte-exact against the existing reference. HIP's + `__fmul_rn` can become ordinary multiplication; disabling contraction in + `quantize_act.cu` preserves the separately rounded product before the magic + rounding bias is added. CUDA's compile flags remain unchanged. +- The mmap regression covers canonical and differing native layer sizes, + truncated/oversized files, lookup bounds, and reopening after errors. +- CUDA 13 / GCC 15 / sm_89 executable build passed; GR, sampler, quantization, + and mmap tests passed on the same tree. This is a regression check, not a + claim of complete CUDA inference validation. +- CPU-only `strata-plan` build passed without either GPU backend. +- Real GSQ-RCO IQ3_XXS server smoke with mmap, the shipped expert profile, + automatic GPU cache, and MTP passed arithmetic, executable Python addition, + system-marker recall, and 1,170-token batched-prefill recall. All four requests + ended normally with correct answers; one engine process served them all. + The cache held 11,142 experts (18.08 GiB), with 874 MiB of VRAM free after + startup. These short checks do not establish a throughput or quality benchmark. + +Build all targets before running the registered focused checks: + +```sh +cmake --build build-hip -j2 +ctest --test-dir build-hip --output-on-failure --timeout 60 \ + -E '^(ple_parity|platform_memory_test)$' +``` + +`ple_parity` requires an external model fixture. `platform_memory_test` requests +256 MiB of locked memory; the test shell's 8 MiB memlock limit prevented that +test from passing. These are explicit exclusions, not skipped tests counted as +passes. Additional unpublished upstream fixture suites are not covered. + +The published performance table explicitly identifies the measured development +snapshot; it must not be read as a benchmark of every subsequent rebase. Vision, long-context stress, broad answer-quality +equivalence, other AMD cards, and mixed-vendor inference are not validated here. diff --git a/docs/AMD_HIP_PERFORMANCE.md b/docs/AMD_HIP_PERFORMANCE.md new file mode 100644 index 0000000..1816c2f --- /dev/null +++ b/docs/AMD_HIP_PERFORMANCE.md @@ -0,0 +1,145 @@ +# RX 7900 XTX support and performance evidence + +This opt-in Linux `gfx1100` backend supersedes the initial support in +[PR #94](https://github.com/Niko1221/Strata/pull/94). It retains HIP runtime and +wave32 integer-dot compatibility, native mmap layout validation, and MTP, then +adds HIP MMQ, optional calibrated dense hipBLASLt GEMM, native prefill batching, +and the host-memory / SSD paths used by the measured configuration. HIP blocking +expert uploads use one reusable pinned staging buffer, including prompt-cache +refills, to avoid repeated pageable-source registrations. + +## Reproduce the configuration + +Build instructions are in [AMD_HIP.md](AMD_HIP.md). Use the repository-pinned +llama.cpp dependency; do not silently substitute another revision. Build with +`STRATA_PREFILL_MMQ=ON` and use these runtime variables for the measured arm: + +```sh +export STRATA_PREFILL_MMQ=1 +export STRATA_HIPBLASLT_TUNING="$PWD/tools/hip/gfx1100-hipblaslt-100100.txt" +export STRATA_PREFILL_RING=96 +export STRATA_IO_THREADS=32 +``` + +The supplied table is calibrated for gfx1100 and hipBLASLt version 100100. +It is not a universal ROCm tuning table. The runtime guards architecture, +library version and actual shape/stride/workspace requirements, falling back +when a table entry is unavailable or incompatible. HIP MMQ is opt-in at runtime. Default CUDA selection is preserved. + +Measured engine configuration: Orca Flash Next IQ3_XXS, native pack plus matching +GGUF/tokenizer/template, `--mmap-experts --resident-cpu-experts`, fixed ranked +`--expert-profile`, `--expert-cache auto`, `--prefill 8192`, `--spec 4`, +`--spec-min-p 0.5`, matching MTP runtime, `--max-context 262144`, `--kv int8`, +`--kv-resident 32768`, `--pool-workers 15`, `--adapt-every 0`, `--pcie-frac 0`, +and `--vram-reserve-mib 1024`. Keep PLE on SSD. + +`--resident-cpu-experts` copies the complement of the static GPU cache to ordinary +RAM. It requires mmap and a fixed expert profile. The slots the prompt path may +borrow keep their experts in RAM too as far as the budget below allows (the rest +use the mapped fallback while borrowed and for their refill), and adaptive swaps +(`--adapt-every`) exchange experts between VRAM and the RAM copy without reading +the file. The copy is pageable; `--resident-experts` (CUDA, chosen by setup) +page-locks it and uses 4 GiB of headroom. Allocation needs sufficient available RAM; +on Linux this option requires readable standard cgroup-v2 mounts. For each +finite cgroup ancestor, the guard credits only `inactive_file` after subtracting +`file_dirty` and `file_writeback`, capped by current usage; it remains bounded by +the ancestor limit and host `MemAvailable`, with 8 GiB headroom. This accounts +for reclaimable clean file cache but cannot reserve memory against concurrent +system or process allocations. +The POSIX PLE path issues direct reads through a configurable worker pool. + +Use a dedicated idle server, restart it between arms, and capture its engine log: + +```sh +python3 tools/hip/bench_prefill.py \ + --model MODEL_NAME --url http://127.0.0.1:8080 \ + --engine-log /path/to/engine.log --label candidate --output candidate.json +``` + +The script uses the same synthetic source prompts and request order as the +reported measurements: a small warmup, then 140/280/140/280 functions, with one +follow-up after each fresh prompt. It enforces zero reused tokens for the fresh +prompts and records prefill, decode, wall time and stop reason. It requires the +unbuffered log to contain exactly one completed timing record per request. The +128-token output cap is intentional for throughput measurement, not task success. +Never use cancelled-request timing lines as throughput evidence. + +## Final revision benchmark + +Measured on 2026-09-29, source revision `9568e78da663e6b224ab96d57baf450717b36e73`. +HIP executable SHA-256: `705f5925a788bc227bad72abfb5466032e0879d752fea9afc3eb32051b35182b`. +The control and candidate below were both measured anew in this session; no +historical benchmark values are mixed into the table. The control binary SHA-256 +is `4522d4937ca4a41ca294d31b60df8c2bc4df5b7a6caf65eaad10c036e08491f7`; +its source was an existing local runtime snapshot rather than a clean upstream commit. +Both arms use an RX 7900 XTX 24 GiB / gfx1100, Ryzen 9 7950X3D, +64 GiB installed RAM, Fedora-family Linux, ROCm 7.1 and a 272 W GPU cap. +Other model services are stopped for measurement and restored afterward. +Sampling: temperature 0, top-k 1, top-p 1, min-p 0, seed 42, reasoning disabled. + +| Fresh request, execution order | Control prefill t/s | Candidate prefill t/s | Candidate output t/s | Candidate request wall time | +| --- | ---: | ---: | ---: | ---: | +| 4,210 tokens, first use | 240.0 | 447.5 | 55.5 | 11.729 s | +| 8,830 tokens, first use at this size | 484.8 | 873.7 | 55.7 | 12.420 s | +| 4,210 tokens, warmed | 457.2 | 901.1 | 56.7 | 6.937 s | +| 8,830 tokens, warmed | 478.9 | 966.5 | 59.2 | 11.314 s | + +Each request generated exactly 128 tokens and finished at the intentional length +cap. All four fresh prompts had zero reused KV tokens. Fresh-prompt prefill was +1.80–2.02x the freshly measured existing AMD runtime; fresh-request wall time was +40–46% lower. This is a comparison with our existing HIP runtime, not unmodified +upstream, which does not provide this backend. The candidate also completed four +cached follow-ups in 2.95–3.26 seconds. Those follow-ups are not apples-to-apples +prefill comparisons: cache reuse differs with generated text and checkpoint +selection. Full sanitized measurements are in +[the fresh-run JSON](benchmarks/2026-09-29-gfx1100.json). + +Before this revision, an intermediate package missing the HIP upload staging +buffer stalled on the 8,830-token request and was rejected. Restoring staging +allowed the complete sequence above to finish. That failed attempt is not +included in the throughput table. No watchdog limit was raised to obtain these +results. + +Zero KV reuse is not equivalent to a cold filesystem cache. First-use speed +and warmed speed are reported separately. Individual observations do not +establish confidence intervals or a general rate at every context length. + +## Correctness and quality limits + +Both HIP and CUDA executables built from the measured source revision. CUDA was +compile-checked, not performance-tested by this run. The selected HIP CTest suite +passed **29/29** with the tuning table enabled, including expert-upload readback, +asynchronous handoff, QSA, MMQ, Lt GEMM, KV streaming and PLE reading. The excluded +`ple_parity` requires an external fixture; `platform_memory_test` requires a +larger locked-memory limit than the test account provides. Separately, three +real IQ3_XXS PLE matrix graph replays passed, and the POSIX direct-file test passed +queued reads, short EOF, wake, close/drain and reopen checks. + +Development checks passed eight MMQ numerical comparisons, four actual Lt GEMM +comparisons, and native QSA/indexer/embedding parity including tail states, +chunk continuation and image overrides. Real quantized MMQ relative L2 error +was approximately 0.0026 against raw-FP32/dequantized-weight reference, reflecting +Q8 activation arithmetic; this is not bitwise numerical equivalence. + +End-to-end coding quality is not established by these numerical checks or capped +throughput requests. Validate completed tasks with independent runtime tests; this +contribution makes no broad answer-quality or agentic-reliability claim. + +The changes do not claim better model reasoning, verified full-context behavior, +end-to-end vision validation, Windows HIP, other AMD architectures, or mixed +AMD/NVIDIA execution. Existing CUDA multi-GPU code remains present but is not +validation of HIP multi-GPU support. + +## Attribution and rejected experiments + +The measurements above were taken before this backend was rebased onto engine 0.1.24. The PR's own batched +embedding gather and QSA indexer append (adapted from +[PR #108](https://github.com/Niko1221/Strata/pull/108), commit +`acd487233c0bbe2217a6881c5bb43f8a283b0de5`) were dropped in the rebase: 0.1.24 already does both on every +backend, bit-exact (C-2, C-4). #108's optional GDN parallel/split path is not included. Existing upstream MMQ orchestration is retained and enabled for +HIP with AMD architecture identification and the correct backend compilation. + +Static 16K chunks, expanded FP16 expert tuning, and a 192-slot ring did not offer +a consistent end-to-end win in the evaluated workload. The table includes only +the selected 30 dense-shape rows. Microkernel speedups alone were not sufficient +to select a configuration. No increase in GPU power cap was used. diff --git a/docs/BATCHING.md b/docs/BATCHING.md new file mode 100644 index 0000000..7672dcc --- /dev/null +++ b/docs/BATCHING.md @@ -0,0 +1,215 @@ +# Several requests at once (batch slots) + +By default Strata serves **one request at a time**: the others wait in the server's queue. With `"parallel": N` +(the engine's `--batch N`, also spelled `--slots N`) the engine keeps up to N conversations open and decodes them +**together**: every verify window then carries one token of each conversation, so the dense weights, the shared +expert, the head and every routed expert two conversations share are read once per window for all of them. +Combined with a layer split across several GPUs and `--batch-groups`, the cards also work on different +conversations at the same time instead of waiting for each other. + +It is opt-in and changes nothing when the options are absent (#465; the engine part is PR #559). + +## Turning it on + +One GPU: add `"parallel": 2` to the model's config (`strata-.json`) and restart, or run setup with +`--parallel 2`. Setup recommends it only where it does not cost speed (below); any number you ask for is kept as +asked, with a note when it is more than setup would recommend. + +``` +"parallel": 2 +``` + +With a layer split, the engine options go into the config's `args`: + +``` +"args": [ ..., "--batch", "8", "--batch-groups", "4", "--trim-stage-weights" ], +"layer_split": "12,24,36" +``` + +| Option | What it does | +| --- | --- | +| `"parallel": N` / `--batch N` / `--slots N` (2..8) | up to N conversations decoded together; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. | +| `--batch-groups G` | with a layer split: the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. | +| `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. | + +The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots (a +window holds 8 rows), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads +the count the engine reports (`INFO batch_slots=N`), and `GET /v1/status` says it (`concurrency.serving`). + +### What a slot costs, and what setup recommends + +Every slot's session takes VRAM that the expert cache would otherwise hold: 0.56 GiB at a 32K context with 8-bit +KV, more with a longer context unless the KV cache streams (`--kv-resident`: then only the attention's 32K window +stays in VRAM, and each slot's whole KV cache takes pinned RAM - 1.6 GB at 128K). On a card whose experts mostly run +on the CPU, a batch also reads about as many distinct experts as the requests one by one (different conversations +route to different experts), so the gain is in **latency** (nobody waits for a whole answer), and a request alone +runs slower (the smaller expert cache): 11-24 % on a 12 GB card, see the measurements below. + +So setup recommends `"parallel"` **only where the experts mostly fit in VRAM**: the expert cache (each card's VRAM +less ~5 GB, every card of a layer split counted) must still hold at least half of the model's experts beside the +slots, and the slots may take at most a fifth of it, up to 4 slots. With Q2_0 at 32K that is 3 slots on a 24 GB +card, 4 from 32 GB or on a split such as 2 x 16 GB; IQ3_S needs 32 GB or a split. Everywhere else (any 12 or 16 GB +card alone) it stays at one at a time and setup says: "parallel N reduces waiting for several users but costs +about 10-25% speed per request on this card". `--parallel N` is honoured as asked either way. + +## How the server uses the slots + +- **One request alone** runs on the usual solo path (verify windows with MTP drafts): the fastest single stream. +- **When a second request arrives**, the first is stopped (`STOP`) and continues in a batch slot with its prompt + plus what it generated so far - the engine's prompt cache holds exactly that, so nothing is read again - and the + new request is admitted next to it. A request in a slot decodes **without MTP drafts** (one token per window). +- **A request left alone in a slot** (the others finished, nobody waits) goes back to the solo path: the slot is + stopped, the engine copies its sessions back and decodes with MTP drafts again (at most twice per request; with + `--prompt-cache 0` it stays in the slot; `STRATA_PARALLEL_SOLO=0` turns it off). The draft layer's own K/V was + built for another conversation then, but measured it accepted as many drafts (140 of 172) as a draft layer that + read the conversation (140 of 173). +- **More requests than slots** wait for a free one (`/metrics` -> `live.slots` shows each slot: idle, reading or + decoding, its tokens and tok/s; `live.running` the requests in flight). +- **Each admission** reads the request's prompt through the usual prompt path (prompt cache and conversation + checkpoints included) and produces its first token there; the state is then copied into the slot. Admissions + are taken one at a time, and **the slots decode between the prompt's chunks**: after each chunk (`--prefill`, + 2048-8192 tokens) they decode for half as long as the chunk took (`STRATA_BATCH_DECODE_SHARE`, default 0.5), so + a long prompt slows the others down instead of stopping them. The chunks are the ones one uninterrupted read + takes, so the prompt's arithmetic is unchanged. +- **A long prompt gives way to a short one** (#656's cooperative preemption): when a request with a prompt under + half as long is waiting, the server sends `BYIELD`; at its next chunk boundary the long read stops, the part read + so far is copied into a slot, the short request is admitted, and the long one then goes on from its slot with the + same chunks (at most twice per request). +- **Each slot is a conversation cache.** A finished slot keeps what it holds (the prompt, the answer, and the + checkpoint at the prompt's last turn boundary); the next turn of that conversation goes to that slot and the + engine copies its state back (50-60 ms for a short conversation) instead of reading the history again - also for + a client that drops the reply's thinking from the history (the checkpoint matches up to the new turn). A new + conversation takes an empty slot, else the one used longest ago. +- Slots are assigned so that consecutive requests land in different pipeline groups (`--batch-groups`). +- A client that disconnects stops its slot (`BSTOP`); the others go on. + +## Exactness + +A batch row's arithmetic is the single-token window's, so with greedy decoding **every conversation of a batch +produces exactly the tokens it produces alone** - verified token by token for 8 concurrent conversations of 150 +tokens, with and without the pipeline (`tools/batch_test.py`), and on one RTX 5070 for 4 conversations, for a long +prompt read while two others decode, for a prompt that gave way and went on, for a next turn continued from its +slot (from all it holds, and from its turn checkpoint without the reply's thinking), and for a request stopped in +its slot and continued on the solo path (`tools/batch_interleave_test.py`). These +settings make the comparison exact: + +- `STRATA_IQ_MT_MIN=1` (the multi-token CPU expert kernels for every group, as for the solo path's own + exactness tests: by default an expert's rows round differently alone than in a group, so the output depends on + how many rows of a window share an expert - which differs between a batch and a request alone), +- `--pcie-frac 0`: the PCIe share of the missed experts is chosen per window from the window's misses, so the + same expert can run on the GPU in one window and on the CPU in another, which rounds differently, and +- `--adapt-every 1000000` (the VRAM tier fixed), and `--no-prefill-borrow` while a prompt is read beside decoding + slots: their windows then see the expert cache without the slots the prompt borrowed (those experts run on the + CPU). + +With the default settings the outputs stay coherent but drift apart after some tokens, as two solo runs whose +windows differ can. Measured on the RTX 5070 (Q2_0, 4 conversations of 200 tokens, `tools/batch_test.py` without +the settings above): one equal to its solo run, the others apart from token 0, 99 and 174 - the first token already +differed for one, because the adaptive VRAM tier had moved experts between the solo runs and the batch; all four +texts read as well as their solo runs. + +Sampled requests (temperature, top_p, top_k, min_p, seed) are drawn row by row with the solo window's +counter-based draw (Philox(seed, position)). + +## Limits (for now) + +- Batch windows carry no MTP drafts: a conversation in a slot decodes one token per window (the solo path keeps + its drafts, which is why a request alone is not put in a slot, and goes back to it when left alone). +- Repetition / frequency / presence penalties are not applied in batch windows. +- A prompt shorter than one chunk is read in one piece (the slots wait for it); a read gives way only at a chunk + boundary, and not for pictures. +- Admissions are one at a time: two new long prompts are read one after the other. +- `--batch-groups` needs every stage on its own GPU; a pipelined slot is not kept as a conversation cache. +- The slot sessions take VRAM (above) and, with KV streaming, pinned RAM. + +## Measured + +One RTX 5070 (12 GB), Ryzen 5 7600, 64 GB DDR5, Q2_0, 32K context, through the HTTP server: C different requests +sent at once (an 800-word essay each, 256 tokens per answer, greedy, thinking off), median of 3 rounds: + +| Concurrent | Setting | Total tok/s | vs one at a time | Per request tok/s | First token: median / last of the round | +| ---: | --- | ---: | ---: | ---: | ---: | +| 1 | one at a time (default; what setup recommends on this card) | 74.3 | - | 83.6 | 0.4 s / 0.4 s | +| 1 | `"parallel": 2` | 67.3 | -9 % | 74.8 | 0.4 s / 0.4 s | +| 1 | `"parallel": 4` | 57.9 | -22 % | 63.8 | 0.4 s / 0.4 s | +| 2 | one at a time | 71.6 | - | 77.3 | 2.1 s / 4.1 s | +| 2 | `"parallel": 2` | 61.0 | -15 % | 32.6 | 0.5 s / 0.9 s | +| 2 | `"parallel": 4` | 54.6 | -24 % | 28.7 | 0.6 s / 0.7 s | +| 4 | one at a time | 70.7 | - | 79.6 | 6.0 s / 11.2 s | +| 4 | `"parallel": 2` | 61.2 | -13 % | 32.2 | 4.5 s / 9.3 s | +| 4 | `"parallel": 4` | 63.1 | -11 % | 16.9 | 1.0 s / 1.8 s | + +On this card the slots buy **waiting time, not speed**: the fourth of four requests starts after 1.8 s instead of +11.2 s, but together they decode 11-24 % slower than one after the other, and a request alone loses 11 % (2 slots) +or 24 % (4 slots), because the slots' sessions (0.56 GiB each) come out of the expert cache and most experts run +on the CPU: a batch window over 4 conversations reads 24 CPU experts per layer against ~8 for one, so it costs about +what the 4 tokens cost one after the other (`strata batch:` in the engine log: 54 ms per 4-row window, ~20 ms per +1-row window). This is why setup leaves a 12 GB card at one at a time. Cards that hold most experts in VRAM, and a +layer split, are where the slots also add speed (below). + +A 4-GPU layer split (4 x 16 GB, PCIe Gen3), IQ3_S, `--batch 8 --batch-groups 4 --trim-stage-weights`, through +the HTTP server, 400 tokens per answer, temperature 0.7 (PR #559): + +| Concurrent requests | Per request | Total | +| ---: | ---: | ---: | +| 1 | 123 tok/s (solo path) | 120 tok/s | +| 2 | 57 tok/s | 113 tok/s | +| 4 | 51 tok/s | 205 tok/s | +| 8 | 45 tok/s | 360 tok/s | + +With the patches below on engine 0.1.38 and parking on, through the service: 8 requests at temperature 0 -> 369 +tok/s, at 0.7 -> 358 tok/s. + +`--trim-stage-weights` alone raised the share of experts held in VRAM on that machine from 76-85 % to 84-100 % +per card. + +## Together with conversation parking + +`--conversation-cache-mib N --conversation-cache-slots K` (DETAILS.md) works with the layer split too: a request +whose conversation was parked is restored on every stage before its admission, so an agent and its sub-agents, or +several chats that alternate, come back without reading their history again. Measured on the same 4-GPU split, +two long conversations alternating through the HTTP server: the first turns took 3.9 s and 5.7 s to the first token +(their prompts read), the follow-ups 0.53 s and 0.46 s. + +## Testing + +Four scripts drive a built engine or a running server; each exits non-zero on a failure. `serve/test_parallel.py` +tests the server's side with a scripted engine (no GPU). + +| Script | What it checks | +| --- | --- | +| `tools/batch_test.py` | the same prompts alone (`GEN`) and together in the batch slots (`BGEN`): every slot's greedy tokens equal its solo tokens; prints the aggregate rate. `--batch-groups` in `--extra` tests the pipeline, `--keys "temperature=0.7"` the sampled rows. | +| `tools/batch_interleave_test.py` | a long prompt read while two slots decode, a prompt that gives way (`BYIELD`) and goes on, and a next turn continued from its slot: each equal to its solo tokens. | +| `tools/parking_test.py` | a follow-up to a conversation decodes the same tokens whether its state stayed live or came back from the parking cache (with a layer split: every stage's image). | +| `tools/early_close_test.py` | a client that stops reading a streamed answer early (alone, and with a second request running) does not leave its tokens to the next request (server). | + +For exact comparisons pass `--pcie-frac 0 --adapt-every 1000000` (and the scripts set `STRATA_IQ_MT_MIN=1`): + +``` +python3 tools/batch_test.py --exe engine/strata --config strata-.json --batch 8 --n 8 \ + --extra "--layer-split 12,24,36 --trim-stage-weights --batch-groups 4 --pcie-frac 0 --adapt-every 1000000" +python3 tools/batch_interleave_test.py --exe engine/strata --config strata-.json \ + --extra "--pcie-frac 0 --adapt-every 1000000 --no-prefill-borrow" +python3 tools/parking_test.py --exe engine/strata --config strata-.json \ + --extra "--layer-split 12,24,36 --conversation-cache-mib 8192 --conversation-cache-slots 4 --pcie-frac 0" +STRATA_KEY= python3 tools/early_close_test.py http://127.0.0.1:8080 +``` + +## Engine protocol (`--serve`) + +On top of `GEN` / `GENI`: + +| Line | Direction | Meaning | +| --- | --- | --- | +| `BGEN [keys] ` | in | read the prompt (as `GEN 1`), then continue in `` | +| `BGENI [keys] ` | in | the same with images | +| `BADM <1/0>` | out | after the admission's `DONE`: 1 = it continues in the slot, 0 = it ended | +| `BT ` | out | a token of that slot | +| `BDONE ` | out | the slot is free again (it keeps its conversation) | +| `BSTOP ` | in | end that slot at its next window | +| `BYIELD ` | in | the prompt being read gives way at its next chunk boundary; its part read waits in `` (the admission's own, or a free slot for a solo request) | +| `YIELDED ` | out | before the `DONE cancel` of a read that gave way: the request is sent again later and goes on from there | +| `INFO ... batch_slots=N` | out | the slots the engine runs (only with `--batch`) | + +`tools/batch_test.py` drives the engine directly: the same prompts alone, then together, compared token by token, +and the aggregate rate. diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.md new file mode 100644 index 0000000..e6903fa --- /dev/null +++ b/docs/COMMUNITY_BENCHMARKS.md @@ -0,0 +1,170 @@ +# Community benchmark results + +Share measurements from your own hardware so other users can judge how Strata +might run on a similar machine. This guide suggests a report format and a pull +request workflow; a single model, GPU, or context length is enough to contribute. + +Existing [benchmark reports](../bench/results/) provide examples. The +[engine 0.1.26 speed report](../bench/results/2026-09-29-speed-0126/README.md) +includes hardware, settings, and per-run JSON. The +[technical details](DETAILS.md#speed-measured) explain the published measurements +and their limits. Report what you actually measured and label estimates separately. + +## Community reports + +- [2026-09-30: RTX 5090, Core Ultra 9 285K, 64 GB RAM](../bench/results/2026-09-30-community-rtx-5090/README.md): + Strata 0.1.29, original Flash-Next IQ2_XS, 131,072-token context; three runs + each at 4,096, 32,768, and 128,000 prompt tokens, plus six recall checks. +- [2026-10-03: 2x AMD Instinct MI50 16 GB (gfx906), Xeon E5-2666 v3, 32 GB RAM](../bench/results/2026-10-03-community-2x-mi50/README.md): + the gfx906 build (#638) with #639 and #640, Coder IQ1_M, 131,072-token context, layer split across both cards; + three runs each at 4,096, 32,768, and 128,000 prompt tokens, plus six recall checks. + +## What to record + +Include enough information for someone else to repeat your run: + +- **Hardware:** GPU model, VRAM, selected GPUs for a multi-GPU run, CPU, installed + RAM, and storage type. Include PCIe link speed and width, GPU power limits, and + other workloads when known or relevant. +- **Software:** OS, Strata commit and engine version, driver and CUDA version + (or ROCm for HIP), and release binary or source build. Include changed build options. +- **Model:** exact repository and revision when available, quantization, GGUF + filenames, and vision encoder if enabled. Identify custom packs, expert + profiles, or draft vocabularies, with hashes or reproducible preparation steps. +- **Settings:** launch command and relevant run configuration, context limit, KV + type and streaming window, expert cache, low-RAM mode, prefill size, CPU workers, + MTP, reasoning effort, sampling, and vision. State whether calibration or + experimental speed projection was enabled; attach the resulting settings. +- **Workload:** benchmark command or script, shareable prompts or instructions to + build them, actual prompt and generated token counts, output cap, repetitions, + and cache state for each run. + +Use GB or GiB consistently and name the unit. Mark unavailable values explicitly +instead of guessing. Remove credentials and private content from configurations, +prompts, and logs before publishing them. + +## How to measure + +Start with a configuration that already works on your machine. You do not need to +download every model or test the largest context. A useful initial speed report +tests one short prompt and one longer prompt that fits, with a fixed output cap +(for example, 256 tokens). Record the actual output length if the model ends early. + +For each configuration, try at least three measured runs and publish all of them +with a median and range. If you only have one run, say so. Explain any warm-up and +whether model loading is included in the timing. + +Strata reuses conversation prefixes and adapts its expert cache. Separate prompts +that are fully processed from follow-ups that reuse tokens, and report the number +of reused and freshly read tokens from the engine log. Describe how you reset or +retained state between runs. A warmed expert cache and a reused prompt prefix are +different conditions; record both when possible. + +Keep these measurements separate: + +- **Prompt throughput:** freshly processed prompt tokens per second, from the + engine's timing output. Keep the corresponding token count and duration. +- **Decode throughput:** generated tokens per second, from the engine's timing + output. Count reasoning tokens too, or explain any different convention. +- **Time to first token:** seconds from sending the request to its first generated + token. For a streaming API measurement, ignore keep-alives and empty deltas and + state whether the first token is reasoning or answer text. +- **Total latency:** elapsed seconds for the whole request. State whether measured + at the engine or client, and whether loading, vision encoding, or queueing is included. +- **Memory:** observed RAM and VRAM usage, including whether the value is a startup + snapshot or a peak during inference. Report paging or out-of-memory failures. + +Attach the engine timing lines and your measurement script if you used one. Avoid +calculating decode throughput by dividing generated tokens by total request time, +which also includes prompt processing. Cancelled or failed requests belong in the +report as failures, outside the successful throughput summary. + +When comparing versions or settings, run both on the same machine and workload +and list every changed setting. Preserve the per-run results: output text and +draft acceptance can change speed even when the input is identical. + +## Optional correctness checks + +Speed measurements alone do not establish answer quality. Include a small check +relevant to your workload, such as a completed coding task with test results, a +tool call followed by its result, or an image question with an expected answer. + +For long-context recall, the repository includes +[`tools/needle_bench.py`](../tools/needle_bench.py). With a running local server, +from the repository root: + +```bash +python tools/needle_bench.py --help +python tools/needle_bench.py --url http://127.0.0.1:8080 --lengths 32k,128k --depths 10,50,90 --out needles.json +``` + +Choose lengths your configured context can hold. The script supports `--api-key` +for an authenticated server; keep that key out of published commands. Save the +reported actual prompt lengths, misses, errors, and skipped cases as well as +successes. A needle test measures recall on those inputs, not overall model quality. + +## Submit a report + +1. Fork Strata and create a branch for your report. +2. Add a folder such as `bench/results/YYYY-MM-DD-community-rtx-5090/`. Use the + measurement date and a short hardware label; add a suffix if the name exists. +3. Put a `README.md` based on the template below in that folder, together with + per-run JSON or CSV and small scripts or prompts needed to repeat it. Use your + own data format and document its fields and units. Keep large model files and + generated packs out of the PR. +4. Open a pull request against `Niko1221/Strata:main`. Summarize the hardware, + model, configurations tested, and limitations. Keep a results-only submission + separate from engine changes so reviewers can assess the measurements directly. + +Maintainers can review the report and decide where to include it. Adding a report +does not require changing the README's headline performance claims. For a failed +run or a suspected bug, a GitHub issue with the configuration and relevant logs +may be more useful than a benchmark PR. + +## Report template + +Copy this into your report's `README.md`, replace the placeholders, and remove +sections that do not apply. Use `not measured` for missing measurements; the table +contains no example performance numbers. + +````markdown +# Community benchmark on GPU name + +Measured on DATE by HANDLE. State what was tested and the main limitation. + +## Hardware and software + +- GPU and VRAM; CPU; installed RAM; storage; PCIe link if known: +- OS; driver; CUDA or ROCm: +- Strata commit; engine version; release binary or source build: +- Background workloads and any power limits: + +## Model and configuration + +- Model repository and revision; quantization; GGUF filenames: +- Vision encoder; custom packs or profiles: +- Context; KV type and streaming; cache; prefill; low-RAM mode: +- MTP; reasoning; sampling; calibration; experimental speed projection: + +```text +Exact launch command and relevant configuration, with credentials removed. +``` + +## Method + +Link prompts and scripts. Describe output cap, repetitions, warm-up, loading, +prompt reuse, expert-cache state, timing boundaries, and memory measurement. + +## Results + +| Configuration | Actual prompt tokens | Reused tokens | Generated tokens | Runs | Prompt tok/s median and range | Decode tok/s median and range | TTFT seconds median and range | +| --- | ---: | ---: | ---: | ---: | --- | --- | --- | +| Fill in measured values | | | | | | | | + +Link per-run data and logs. Include total latency and memory observations when +measured, with units and timing boundaries. List failures and skipped cases. + +## Correctness and limitations + +Describe checks, expected answers, observed results, and untested behavior. +```` diff --git a/docs/DETAILS.md b/docs/DETAILS.md new file mode 100644 index 0000000..d9484e6 --- /dev/null +++ b/docs/DETAILS.md @@ -0,0 +1,1127 @@ +# 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/HOW_IT_WORKS.md b/docs/HOW_IT_WORKS.md new file mode 100644 index 0000000..7c8f9ee --- /dev/null +++ b/docs/HOW_IT_WORKS.md @@ -0,0 +1,77 @@ +# How does Strata work? + +Models like Qwen3.8-Flash-Next normally run on servers with hundreds of gigabytes of graphics memory. Your graphics +card has 12-24 GB. Strata makes it fit by **sharing the work across your whole PC** - the same idea as a kitchen, where +the things you use all the time stay on the counter and the rest waits in the pantry. Back to the +[README](../README.md#how-does-it-work). + +## Who does what + +

The model's 24,576 experts: the busiest on the graphics card, all of them in RAM, a lookup table on the SSD

+ +- **The model is a team of 24,576 small specialists ("experts"),** and each word it writes needs only 10 of them. + So it doesn't have to have all of them on the graphics card at once. +- **Your graphics card** does the part of the work needed for every word, and keeps the few thousand experts that + are asked most often. It keeps learning which ones those are while you use it. +- **Your RAM** holds every expert. When a word needs one the card doesn't have, **your processor** works on it - + at the same time as the graphics card, so neither waits for the other. +- **Your SSD** holds a big lookup table; the model only reads a few small rows of it per word. + +The same in technical terms: + +- **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). + 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. +- **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). On a PC with little RAM + and a big card, the [low-RAM mode](MODELS.md#a-big-graphics-card-and-little-ram) keeps in RAM only what the GPU does + not hold. +- **SSD:** the 28.8 GB n-gram table, read a few rows per token through the OS cache. + +This works the same on NVIDIA (CUDA) and AMD (HIP) cards: the same engine, compiled for each. + +## Guess, then check + +

A small helper guesses the next words; the big model checks them all at once and keeps the right ones

+ +- **Guess, then check.** A small, fast helper built into the model guesses the next few words, and the big model + checks all the guesses in one go. It keeps the ones it agrees with and writes the next word itself - so one step + often produces several words. The helper only guesses - the big model decides every word - so you get the same + quality answer, 1.6-1.8x sooner. +- In technical terms: 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** 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. + +## Reading long texts + +**Long texts are read in big pieces** (up to 8,192 tokens - pieces of words - at a time), which is why a long +document or code base is read at over 1,000 tokens per second. The experts of the next layer stream to the GPU over +PCIe while the current layer's attention runs. After the first message, Strata keeps the conversation and reads only +what is new, so follow-ups start in seconds. + +## More + +The [details](DETAILS.md#how-it-works) explain every part and its numbers, and the +[paper](paper/Strata-Paper.pdf) tells the whole story, with the measurements behind it. + +## Credits + +- Model: [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team; compressed versions by + [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF); + [Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF) by UkisAI; the experimental + [UD-Q4_K_XL](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF) by Unsloth (its support follows + [eddoursul/Strata](https://github.com/eddoursul/Strata)). Their licenses apply to the model files. +- Built with parts of [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) (MIT). Ideas from + [Splash](https://github.com/incoai/splash), [ninfer](https://github.com/Neroued/ninfer) and + [HyperQwen](https://github.com/syv-ai/HyperQwen). More in the [details](DETAILS.md#credits-and-licenses). +- The AMD (HIP) backend: [AMD_HIP.md](AMD_HIP.md) names the contributors and the machines it was validated on. + +## License + +Strata is open source under the [MIT License](../LICENSE). A few parts carry their own licenses: `third_party/ggml` +(MIT, llama.cpp / ggml), the web app's font (SIL Open Font License 1.1) and the experimental speed projection's +vector in `data/experimental-speed-projection` (Qwen Community License 1.0, from the model's activations). The +models are not part of this repository; each model's own license applies to its files. diff --git a/docs/INSTALL.md b/docs/INSTALL.md new file mode 100644 index 0000000..4ab28fb --- /dev/null +++ b/docs/INSTALL.md @@ -0,0 +1,260 @@ +# Installing Strata + +Everything about installing, starting, updating and configuring Strata, on Windows and Linux, with an NVIDIA or an +AMD graphics card. The short version is in the [README](../README.md#install); an AI coding assistant can do all of +this for you with [AI_SETUP.md](AI_SETUP.md). + +> **On this page:** [What you need](#what-you-need) · [Windows](#windows) · [Linux](#linux) · +> [AMD cards](#amd-cards) · [Several cards](#two-or-three-cards) · [Docker](#docker-linux) · +> [Older CPUs](#older-cpus-experimental) · [Updating](#updating) · [Where things are stored](#where-things-are-stored) · +> [Setup's questions](#setups-questions) · [Tuning](#tuning-for-your-pc) · [All options](#options-without-questions) + +## What you need + +| | | +| --- | --- | +| **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. **AMD** Radeon RX 7900 XT / XTX, RX 9070 / 9070 XT and Radeon AI PRO R9700 (validated), RX 7800 XT / 7700 XT and RX 9060 XT (validated by their owners), RX 6800 / 6900 series (community-reported), with 12 GB of VRAM or more. See [AMD cards](#amd-cards). | +| **RAM** | Enough for the size you pick ([which model](MODELS.md#pick-by-ram)); **64 GB** runs every size. A big GPU makes up for less RAM - the [low-RAM mode](MODELS.md#a-big-graphics-card-and-little-ram). | +| **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](#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 copy of its experts for the fast CPU kernel. On Linux with an AMD card, ROCm takes ~10 GB more when setup installs it. An NVMe SSD is strongly recommended: it makes the first start much faster. | +| **OS** | Windows 10/11, or Linux (Ubuntu 22.04/24.04 get everything installed automatically). | +| **Driver** | **NVIDIA:** a current driver, version 580 or newer ([nvidia.com/drivers](https://www.nvidia.com/drivers) or the NVIDIA App). **AMD:** on Linux the kernel's amdgpu driver (no ROCm install needed); on Windows a current AMD Software: Adrenalin Edition driver ([amd.com/support](https://www.amd.com/en/support)). | + +The driver is the only thing you install yourself. Everything else - Python, the engine, the model - is set up for +you the first time: Python 3.12 if you have none (for your user account, no admin), a private Python environment in +`.venv/`, the Strata engine, the model and the MTP draft layer. On NVIDIA it uses the ready-made engine for RTX +20/30/40/50 and NVIDIA's CUDA libraries from pip (~0.4 GB); 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). More: [details](DETAILS.md#before-you-start). + +## Windows + +1. [Download this project](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) and unzip it (or + `git clone` it). +2. Double-click **`START-HERE.bat`**. +3. Answer a few questions - or just press Enter each time for the recommended choice ([the questions](#setups-questions)). + +Then it downloads everything (the model is ~70 GB, so the first time takes a while - you can stop and it picks up +where it left off) and **starts the model**. Your browser opens the Strata app at `http://127.0.0.1:8080`. + +> **While the model starts, your PC can be slow or stop responding for 1-3 minutes** (longest the first time): Strata +> loads 35-55 GB into your RAM and locks part of it for the graphics card. That's normal - wait, and don't close the +> window. The window tells you what it is doing. + +**Next time**, just double-click `START-HERE.bat` again: it starts right away (30-90 s to load the model), nothing is +downloaded twice. Close its window to stop the model. `SETUP.bat` (the same as `START-HERE.bat --setup`) installs +another model or changes the settings. Starting Strata from Task Scheduler at logon needs two task settings, or the +start is 24x slower: [Running it at startup](DETAILS.md#running-it-at-startup-task-scheduler). + +## 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; `./setup.sh --setup` installs another model or changes the settings. Other distributions, +WSL and compiling: [details](DETAILS.md#linux). + +## AMD cards + +The steps are the same as with NVIDIA: `START-HERE.bat` on Windows, `./setup.sh` on Linux. Setup finds the Radeon +card and chooses the AMD (HIP) engine by itself on a PC with no NVIDIA card Strata can use; `--backend hip` chooses +it on a PC that has both. Supported cards: RX 7900 XT / XTX (gfx1100), RX 7800 XT / 7700 XT (gfx1101), RX 9060 XT +(gfx1200), RX 9070 / 9070 XT and Radeon AI PRO R9700 (gfx1201), and the RX 6800 / 6900 series (gfx1030). Integrated +Radeon GPUs are listed as not supported. + +On Linux setup uses a system ROCm 7 when there is one, or installs ROCm into `.venv` from AMD's wheels (~10 GB, no +sudo), and compiles the engine on your PC for the card (10-20 minutes, once; it needs a C++ compiler and git: +`sudo apt install build-essential git`). Several AMD cards share the model with `--gpus`, as on NVIDIA. + +What differs from NVIDIA for now: pictures are read by the image encoder on the CPU (`--vision cpu`, 10-30 s per +picture), `--calibrate` is NVIDIA-only, and Unsloth's 4-bit model needs an NVIDIA card. Measurements per card, the +build by hand and the tuning tables: [AMD_HIP.md](AMD_HIP.md). + +## Two or three cards + +**Two or three NVIDIA cards?** Just run `START-HERE.bat`: it lists your cards, says which ones Strata can use, and +asks whether to share the model across them (recommended when two can). An install made on one card asks once at +its next start. Or choose yourself: `START-HERE.bat --gpus 0,2` (both, remembered), `--gpus all`, or `--gpu 0` (one +card, this start only). Each card keeps the experts of its own layers, and prompts flow through the cards in a +pipeline: on an RTX 5080 + RTX 3090 prompts were read 18-20% faster than on the 5080 alone, decoding on par. +Every card must be an RTX 20 series or newer with 8 GB or more. See [MULTI_GPU.md](MULTI_GPU.md). + +**Several AMD cards:** setup takes one card (the one with the most VRAM, or `--gpu N`) unless you name more: +`--gpus 1,0` splits the model's layers across them, the first one the main card (numbers as setup lists them). A +split pays only when no single card holds the model's experts ([AMD_HIP.md](AMD_HIP.md#rdna4-gfx1201)). + +## Docker (Linux) + +The same idea, in a container (NVIDIA cards). + +1. Host: Docker with the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html) + and a driver **580 or newer** (CUDA 13.0). +2. Build (this compiles the engine into the image, so the container never compiles): + `docker build -t strata .` + `docker build -t strata --build-arg CUDA_ARCHITECTURES=89 .` builds for one card only (faster). + The default covers RTX 30 (86), RTX 40 (89), RTX 50 (120) and A-series (80); a card outside that + set needs a rebuild with its own arch. Add `--build-arg BUILD_VISION=0` to skip the image encoder. +3. Run (the first start downloads the ~70 GB model, then starts; later starts go straight to serving): + `docker run --rm --gpus all -p 8080:8080 --ulimit memlock=-1 -v strata-data:/data strata` + + The setup choices are env vars: `-e MODEL=IQ2_XS -e FAMILY=qwen -e CONTEXT=32768 -e VISION=no` + (or `MODEL=Q2_0|IQ3_XXS|IQ3_S`, `FAMILY=swift|coder`; the defaults above are the recommended ones). + `-e VISION=cpu` keeps the image encoder on the CPU. `-e KV=int8|q4_0|k8v4` picks the KV cache + precision; `k8v4` is INT8 K with 4-bit V and keeps its KV in VRAM from 64K up. + Only the model files, the prepared pack, the MTP layer and the install config live in the + `strata-data` volume; the engine is part of the image. Switching between models already on the + volume needs no setup pass: `-e MODEL=Q2_0 -e FAMILY=coder` picks that model's config. Add + `-e REINSTALL=1` only to change settings for a model already set up (context, vision, KV, host, + api_key, LOW_RAM), since those are recorded in its config. + Strata loads 32-62 GB into RAM. `--gpus all` on a host with two usable cards takes both: the + layer split is setup's recommended default ([MULTI_GPU.md](MULTI_GPU.md)), and a volume + set up for one card switches to the pair on its first start there. Pin one card with `-e GPU=0`, + or name them with `-e GPUS=0,2` and where the later card's layers start with `-e LAYER_SPLIT=18`. + A memory limit needs `-e LOW_RAM=on`, which maps the model's experts from the pack instead of + keeping them in RAM: setup.py measures the host's RAM, not the container's limit, so it cannot + see a cap. LOW_RAM runs on one card unless `GPUS` names several (then the experts the cards do not hold are + read through the OS file cache, which can fill the RAM during long prompts). + The server listens on `0.0.0.0:8080` by default; set `-e API_KEY=` before exposing the port + to a network. The image has a `HEALTHCHECK` on `/health`, so `docker ps` shows the container + healthy once the model is loaded, and `GET /v1/status` says what it is running. + +## Older CPUs (experimental) + +Strata's ready-made engine needs AVX2 (Intel Haswell 2013, AMD Zen 2017 or newer). Since 0.1.39 an older CPU - AVX +only (Sandy Bridge / Ivy Bridge, Xeon E5 v1/v2, AMD Bulldozer) or SSE4.2 only (Nehalem / Westmere, Xeon X5600) - runs +as an **experimental** build that setup compiles on that PC. Run setup as usual: it says the CPU has no AVX2, warns +that this is experimental and slow, and compiles the engine (10-20 minutes, once; Windows needs the Visual Studio Build +Tools and the CUDA Toolkit, which setup offers to install). It does not stop. The ready-made engine still refuses such +a CPU, and says so. + +What differs in that build (`STRATA_ISA_FLOOR=avx` or `none`, chosen from the CPU): + +- ggml-cpu is compiled for AVX or SSE4.2 instead of AVX2, and the CPU's share of the experts runs on its kernels. + Strata's own AVX2 / AVX-512 kernels stay in the program but are used only on a CPU that has them. +- Only the i-quant models' packs run (every model setup installs on such a CPU); the AVX-512 Q2_0 pack does not. +- Speed: the GPU part is unchanged and the CPU part is slower, so a GPU with more VRAM (more experts cached there) + helps most. With the older paths forced on a Ryzen 5 7600 + RTX 5070 and the expert cache held at 1500 slots, greedy + decode went from 26 to 11-17 tok/s with the AVX build and to 3.5-3.8 tok/s with the SSE4.2 build (Coder and IQ3_XXS, + 10 prompts each, one run). An old Xeon with DDR3 will be slower than these. +- Untested on a real old CPU by us. It was checked here by forcing the older paths on a Ryzen 5 7600 + (`STRATA_FORCE_ISA=avx` or `sse`): the answers were sane and passed the engine's checks, but not the same token for + token as the normal build (ggml-cpu rounds the CPU experts differently, as the AVX2 kernel does from the AVX-512 + one). Contributors ran earlier versions of the same approach on a Xeon E5-2680 (2.87 tok/s with a GTX 1080 Ti) + and on Xeon E5-2687W / X5690 machines. +- AMD cards: Linux only (setup compiles the AMD engine there anyway); NVIDIA on Windows and Linux. +- Two-socket Xeons: memory on the other socket is slow; keep the RAM on one CPU if you can. + +By hand: `cmake ... -DSTRATA_ISA_FLOOR=avx` (or `none`) builds it; `STRATA_ISA_FLOOR=avx` set for setup builds it on +any PC (to try it). Problems and results on real hardware are welcome as GitHub issues. + +## Updating + +**`UPDATE.bat`** (Linux: `./update.sh`) updates Strata without starting the model - for when the GPU is busy with +something else, or you just want the new version ready. In a `git clone` it runs `git pull`, then does what +`START-HERE.bat` does before a start: the engine (a new ready-made one when the new version needs it; on Linux a +compiled engine is compiled again when its source changed), the Python packages, and each installed model's settings +and draft subset. The model files are not touched (at most a new engine is downloaded) and no question is asked. +Close the model's window first (a running engine cannot be replaced); start the model later with `START-HERE.bat` as +usual. In a copy that was downloaded as a zip it says to download the new zip (below): it cannot fetch new files +itself. + +Or by hand: download the new version and unzip it anywhere (or `git pull`), then run `START-HERE.bat` (Linux: +`./setup.sh`) in it. The model files are kept in a `Strata-data` folder next to your Strata folder, so a new copy +finds them and sets itself up the same way - nothing big is downloaded again. On Linux after a `git pull`, setup +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. + +## Where things are stored + +- **Your chats: only in your browser.** The Chat tab keeps the conversation, its settings and the API key you typed + in the browser's local storage (`strata.*` keys) - not on the server and not in the Strata folder. Pictures are not + kept, only their names. Another browser or a private window starts empty; clearing the site's data deletes them. +- **How the model starts:** `strata-.json` in the Strata folder (context, GPUs, host, API key, ...), written + by setup; next to it `run-.bat` / `.sh`, the log `strata-.log` and, when you use "Use for other + apps too", `strata-.shared-settings.json`. Running setup again for the same model (another context, say) + rewrites the keys setup writes (`exe`, `args`, `port`, `gpu`, `host`, `api_key`, `vision`, ...) and keeps the + ones you added (`sampling`, `mcp_servers`, `mcp`, `cors_origins`, ...); the earlier file is kept as + `strata-.json.bak` (0.1.39). Engine options you added to `"args"` by hand are not carried over: setup names + them, and you add them again. +- **The model files** (`models/`, `packs/`, `mtp/`, 70-120 GB): in **`Strata-data` next to the Strata folder**, or + wherever `--data-dir` put them. +- **Where that data folder is:** `%APPDATA%\Strata\settings.json` on Windows, `~/.config/strata/settings.json` on + Linux ([details](DETAILS.md#before-you-start)). +- **The program itself:** `.venv/`, `engine/` and `third_party/` in the Strata folder. +- **Where github.com cannot be reached:** a build from source downloads llama.cpp's source (ggml, gguf-py) from + GitHub at the commit `LLAMA_CPP_COMMIT` in `setup.py` names. Put that commit's tree in `third_party/llama.cpp` + yourself (from a mirror or another PC) and setup uses it instead (#585). + +## Setup's questions + +- **Which model and size?** The original, Swift 1.5, the Coder or Unsloth's 4-bit, and Q2_0, IQ2_XS, IQ3_XXS or + IQ3_S - see [which model](MODELS.md). +- **How much context?** How much text it can keep in mind at once (it suggests one for your card). 384K and + 512K (experimental) extend the model past its trained 262K by rope scaling - the setup turns it on itself (yarn and a + covering factor; `--rope-scaling`/`--rope-scale` override) ([details](DETAILS.md): "Context extension past + 262K"). +- **Images?** Whether it should also read pictures. The image encoder (0.9 GB) runs on the GPU (0.1-0.5 s per + picture, ~1.4 GB of VRAM kept free for it) or on the CPU (10-30 s per picture, nothing on the GPU); with AMD cards + on the CPU for now. [Details](DETAILS.md#images-vision). +- **Experimental speed projection?** Off unless you say yes - [read what it does](DETAILS.md#experimental-speed-projection-experimental-off-by-default) + first. It changes how the model answers, and only the original model offers it. + +With `--yes` setup takes the recommended answer to every question. + +## Tuning for your PC + +Every PC is different: `START-HERE.bat --calibrate` (Linux: `./setup.sh --calibrate`) measures a few engine settings +on yours and keeps the fastest (about 5-10 minutes; on an RTX 5070 with a Ryzen 5 7600 it made the Coder 7% faster). +It keeps a setting only when it is more than 3% faster, and the result is remembered per PC and model, so updates +keep it. NVIDIA cards for now. [What it measures](DETAILS.md#double-click-start-herebat). + +## Options without questions + +``` +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 (setup picks the one with the most VRAM) +START-HERE.bat --gpus 0,2 several GPUs sharing the model +START-HERE.bat --vram-reserve-mib 2048 leave 2 GB of VRAM free for other programs (remembered) +START-HERE.bat --no-browser do not open the chat page when the model is ready (remembered; + --browser undoes it) +START-HERE.bat --setup --backend hip the AMD engine on a PC that also has an NVIDIA card +START-HERE.bat --setup --host 0.0.0.0 --api-key reachable from other devices, with a key +START-HERE.bat --calibrate tune the engine for this PC (about 5-10 minutes), then start +START-HERE.bat --check only check this PC +``` + +**Leaving VRAM for other programs (#493):** Strata fills the graphics card's free VRAM with experts (the expert cache) +and leaves `--vram-reserve-mib` MiB free: 700 by default. For a game, a 3D program or another model beside it, leave +more: `START-HERE.bat --vram-reserve-mib 2048` (Linux: `./setup.sh --vram-reserve-mib 2048`) writes it into the +model's `strata-.json` and starts it; at setup (`--setup --vram-reserve-mib 2048`) it goes into the new config. +By hand: add `"--vram-reserve-mib", "2048"` to the config's `"args"` list and restart. The expert cache is then that +much smaller, so answers can be a little slower. The engine sizes its cache from the VRAM free when it starts: what +another program already holds then is left alone anyway; the reserve is room for what it takes later. + +**An AMD card that also drives a Linux desktop (#560 #516):** with the default reserve the expert cache fills the +card, and when the desktop (the compositor, a browser, a new app) needs more VRAM, the amdgpu driver moves GPU memory +to system RAM, which the model's experts already fill: the OOM killer then ends the desktop session (KWin, plasmashell) +or the compositor fails ("Failed to pin framebuffer"). `./setup.sh --vram-reserve-mib 3072` fixed it in both reports +(about 2.3 GB fewer experts in VRAM, a few % of speed). Setup and the server window say so on such a PC. + +**A card under 8 GB (#496):** when the default reserve leaves the expert cache too little room, the engine lowers the +reserve (down to 300 MiB) until it fits, and warns if the card then ends nearly full. If the start stops with "no VRAM +is left for the expert cache", that log line says how much is short; an 8K context and `--draft-vocab en` at setup +free the most. + +**Model files downloaded by hand, or from a mirror (#495):** setup's step 5 prints the folder it expects them in +(`Strata-data\models\\`, e.g. `Strata-data\models\IQ3_XXS\`): put them there with their original names, or +point setup at them with `--gguf-dir`. To let setup download from a Hugging Face mirror itself, set `HF_ENDPOINT` +first (Windows: `set HF_ENDPOINT=https://hf-mirror.com`, Linux: `export HF_ENDPOINT=https://hf-mirror.com`): the same +pinned revisions and checks apply, and the MTP draft layer comes from there too. + +On Linux the same options go to `./setup.sh`. `START-HERE.bat --help` lists them all. The server's own settings +(sharing the GPU with games, MCP tools, CORS, API keys, the API itself) are in the [details](DETAILS.md#using-it). diff --git a/docs/INTEL.md b/docs/INTEL.md new file mode 100644 index 0000000..38b331e --- /dev/null +++ b/docs/INTEL.md @@ -0,0 +1,652 @@ +# Strata on an Intel Arc + +Strata's engine is CUDA. On an Intel Arc it runs as **Strata's own engine, ported to SYCL** (`sycl/`, the +section "The engine itself on Intel" below), behind the same Strata server: OpenAI and Anthropic APIs, streaming, +tool calls, MCP and the web app all unchanged. llama.cpp's SYCL backend is the comparison point in the tables (it +runs the same GGUF at about a third of the speed). + +Everything Intel-specific lives in `sycl/`; no shared file of upstream's is changed, so upstream merges stay clean. +`sycl/setup_intel.py` and `sycl/serve/server_intel.py` wrap upstream's `setup.py` and `serve/server.py` from +outside. + +Written for and measured on an **Arc Pro B70 (32 GB)** running the Coder (IQ1_M) on Ubuntu 24.04, in a +PCIe 3.0 x8 slot (the card trains at Gen3 x8 there; it can do Gen5 x16). + +## What you get (2026-10-01) + +| | NVIDIA (Strata engine) | Intel Arc, Strata SYCL port | Intel Arc, llama.cpp | +|---|---|---|---| +| models | all four | the Coder IQ1_M; the original IQ2_XS too (experts beyond VRAM in the host mirror: 58-64 tok/s) | the Coder (fits VRAM) | +| model files | the same GGUFs | the same GGUFs + a native pack | the same GGUFs | +| where the model lives | experts in RAM, hot ones on the card | every expert in VRAM (`--stream-experts`: no host copy), shard 2's lookup table read from the SSD by row | all of shard 1 on the card, shard 2 paged from disk | +| RAM needed | 32-64 GB | little (23 GB is fine) | little (23 GB is fine) | +| decode, Coder IQ1_M | 44-51 tok/s on an RTX 5070 | **78.2 tok/s** (19-token prompt, 256 greedy tokens), **75.7** after a 2,184-token prompt, 69 after 40K, 66.6 after 128K, 55.9 after 256K; 48-72 through the API | 23-25 tok/s | +| prompt reading | ~1,870 tok/s | **790 tok/s** at 2,184 tokens, 1,117 at 40K, 888 at 128K, 757 at 256K | ~150 tok/s (424 at 105K) | +| speculative decoding (MTP) | yes | yes (the base checkpoint's draft layer; 70-85% of drafts accepted on code) | no | +| images | yes | not yet | not yet | +| context | up to 262K | 256K measured, 56 tok/s decode there (`--kv-resident`: the KV in pinned host memory, the attended window in VRAM) | 131K measured ceiling | + +Decode speed with speculative decoding depends on the text: code drafts well, prose less so (see "Speed depends +on the text"). The SYCL numbers are greedy runs of the engine (as in "How to run it by hand" below, 256 new +tokens) on engine 0.1.31-sycl (2026-10-01; 0.1.32-0.1.38-sycl reproduce them exactly); +"Decode round 2" below lists what each change bought. + +## Setup + +Build the engine and its runtime image first ("How to build it" below), then: + + python3 sycl/setup_intel.py [setup.py's options, e.g. --model IQ2_XS --context 32768 --port 8085] + +This is upstream's `setup.py`, run with the Intel steps swapped in (it imports setup.py and replaces those steps; +setup.py itself is unchanged). The model choice, download, pack, tokenizer, MTP draft layer and the context and KV +questions are setup's own. What changes: + +- **GPU check:** the Arc is found in sysfs (vendor 8086 under `xe` or `i915`) and offered through setup's AMD + path. That is the path that builds locally and has no images. +- **Engine step:** it uses the SYCL build (`build-sycl-aot/strata`, run in the `strata-sycl-dev` image by + `sycl/serve/strata-sycl.sh`) instead of compiling CUDA or HIP. +- **RAM rule:** this does not apply. The CUDA engine keeps every expert in RAM; the port streams them from the + GGUF into VRAM (`--stream-experts`), so RAM only decides the KV streaming. `--check` lists what fits by VRAM. +- **The config:** it uses the container's paths and `"backend": "sycl"`. The VRAM reserve is 1,024 MiB up to + 32K and 2,048 MiB with 4,096-token prompt chunks above that. KV streaming (`--kv-resident 32768`) is on from + 64K up when the RAM holds the KV. A `model_switcher` or `sampling` block from an earlier config is kept. + `run-.sh` starts `sycl/serve/server_intel.py`. + +If a future `setup.py` drops a step this relies on, it stops with a message instead of writing a wrong config. +The models, packs and checkout must sit under the folder `strata-sycl.sh` mounts at `/work` (the one above the +checkout, or `STRATA_SYCL_ROOT`). + +Then `run-.sh` (or `sycl/setup_intel.py` again) starts the model. The first start of a 30 GB model +takes about two minutes. `--port N` and `--host 0.0.0.0` work as in upstream's setup. + +## Things that matter on this GPU + +- **`SYCL_CACHE_PERSISTENT` must be 0.** The persistent JIT cache segfaults on Xe2 during the first + compile. The start script sets it; if you run llama-server by hand, do too. +- **The whole model goes on the card** (`--n-gpu-layers 999`), except `per_layer_token_embd.weight`, + the single 28.8 GB tensor of shard 2. `--override-tensor per_layer_token_embd=CPU` keeps it in host + memory, mmapped and paged from the SSD by row, which is how the model's authors serve it. Host RSS + stays around 2 GB. +- **Thinking.** The model reasons before it answers. Strata's web app has the setting; for an API + client, put `{"reasoning_effort": "none"}` in `strata-.shared-settings.json` next to the + config, or send `chat_template_kwargs: {"enable_thinking": false}` per request. Without one of + those a short `max_tokens` is spent entirely inside the think block and the answer looks empty. +- **`/health` says 503 while loading**; the server polls `/props` instead. + +## How much context fits + +The architecture keeps this small: only every fourth layer is full attention (12 of 48); the other +36 are gated-delta-net layers with a fixed-size recurrent state that does not grow with context. +Per token, the 12 attention layers keep 2 KV heads x 256 x (K + V) at q8_0, plus the +sparse-attention indexer's keys. **Measured: about 20 KiB per token** (VRAM grows 0.6 GB per 32k +of context with everything else unchanged). + +| context | VRAM in use, model loaded | headroom on 32 GB | status | +|---|---|---|---| +| 32,768 | 28.4 GB | 3.5 GB | measured, the default | +| 65,536 | 29.0 GB | 2.9 GB | measured, loads | +| 98,304 | 29.6 GB | 2.3 GB | measured, loads | +| 131,072 | 30.3 GB | 1.5 GB | **measured, the practical ceiling**: a 104,798-token prompt (79% of the window) read in 247 s at 424 tok/s, then answered | +| 163,840 | ~31.0 GB | ~0.9 GB | not attempted: under the 1.2 GB safety margin | +| 262,144 | ~32.6 GB | none | **does not fit - asking for it took the host down** | + +**Do not ask for more than fits.** On this driver a GPU allocation past VRAM does not fail: the xe +driver evicts buffers into host RAM, the kernel runs out of memory, and the machine livelocks until +its hardware watchdog resets it. A 262K request did exactly that on 2026-09-29, and llama.cpp's own +"failed to fit params" check fired too late to prevent it. Compute the KV size first and leave +1.5 GB free. + +Prompt reading gets faster with size, because the work batches better: ~150 tok/s on a 2.7k-token +prompt, 424 tok/s on a 105k-token one. So a full 128k window costs about five minutes to read, +not fifteen. + +## The engine itself on Intel: the SYCL port (`sycl/`) + +Everything above runs the model through llama.cpp. This is the other half: Strata's own engine - the 50 CUDA +kernels and the host code that drives them (streams, events, graph capture, pinned memory) - built for the +Arc with oneAPI. It is a migration of the tree, not a new backend: the engine has no backend seam to slot +into. + +**Layout.** `sycl/src` and `sycl/include` mirror the tree and hold only the files the port changes; the +SYCL build (`sycl/CMakeLists.txt`) takes every other source from the original location. No upstream file +is edited. `sycl/include/dpct/` is the vendored SYCLomatic helper library, so the port builds without the +migration tool. + +**How it was made, so it can be redone.** + +1. `sycl/tools/Dockerfile` - the dev image: the llama.cpp SYCL image plus SYCLomatic (`dpct` 2025.3), + ninja, and the CUDA 12.8 headers that `sycl/tools/get-cuda-headers.sh` pulls out of NVIDIA's pip wheels + (dpct parses CUDA; it needs the headers, not the toolkit). +2. `sycl/tools/migrate.sh` - writes a compilation database for the 86 CUDA-touching translation units and + runs dpct over them. 85 migrate; dpct reports no line it could not migrate, and about 1,400 advisory + notes. +3. `sycl/tools/fixups.py` - what dpct got wrong or could not do, as an idempotent script with a reason per + item. The ones that mattered: + - CUDA's null stream means the default stream; dpct turned it into a null `sycl::queue*`. Every + stream cast now goes through `strata::q_of()` (`sycl/include/strata/sycl_queue.hpp`). + - `__ldg((const float*) p)` came out as `*p`, reading one byte of a float scale (two sites, s_gemv). + - `__fadd_rn(a, b ? c : d)` lost its parentheses (two sites). + - the ggml lookup tables were threaded through kernel parameters with the wrong table per template; + they are plain `static const` arrays read from device code, as ggml-sycl does. + - helper headers renamed since dpct 2025.3 (`entangle`, `chunked_partition`), graph introspection and + `cudaGraphUpload` (no SYCL equivalents), `%globaltimer` (the stage profiler reads zeros). +4. `sycl/tools/build.sh` - configure + build with icpx inside the image. Two compiler flags are load-bearing: + `-fp-model=precise` (icpx defaults to a fast FP model) and `-cl-fp32-correctly-rounded-divide-sqrt` + for the device compiler - the Arc's fp32 divide is not correctly rounded by default (OpenCL allows + 2.5 ulp), and Strata's quantizers are byte-exact against ggml through `amax / 127`. Measured: without + it `quantize_act_parity` has 303k mismatches, with it none. + +**Where it stands (2026-09-29).** The whole tree builds and links: the `strata` binary and 22 kernel +parity tests. On the B70, 19 of the 22 pass byte-for-byte or within their tolerances; the other three +need model fixtures (`iq_parity`, `ple_parity`) or the tensor-core kernel below (`qsa_prompt_attn`). + +| parity test | result | +|---|---| +| bf16_gemv, cvec, dequant_s2, elementwise, gdn, gr, kv_q4, kv_q8, kv_stream, qsa, quantize_act, rope, router_top10, s2_gemv, s2_gemv_q8, s_gemv, s_gemv_q8k, sampler, shared_expert | pass | +| iq_parity, ple_parity | need fixtures (a `logs/iq_fixture` directory, a Q2_0 shard) | +| qsa_prompt_attn_parity | needs the tensor-core kernel (below) | +| kv_hybrid_parity (0.1.27, hybrid K8V4 KV) | appends, gathers and attention pass; its last step is that same tensor-core kernel | + +**The engine end to end (2026-09-29, later the same day).** It generates. Prompt "Write a Python function +that returns the n-th Fibonacci number", greedy, 64 tokens: + +> `` The user wants a Python function that returns the n-th Fibonacci number. Let me consider the +> options: 1. **Recursive approach** - Simple but O(2^n) time complexity, very slow for large n. 2. +> **Iterative approach** - O(n) time, O(1) ... + +Measured on the same card, same 2,185-token prompt, 64 greedy tokens (AOT build, `--spec 2`, +`--no-prefill-borrow`), against llama.cpp's SYCL build serving the same GGUF: + +| | llama.cpp SYCL | Strata SYCL port | +|---|---|---| +| prompt reading | 138-319 tok/s | **560 tok/s** (693 at 2,000 tokens, 180 at 300) | +| decode, suffix drafter only (`--spec 2`) | 24.2-26.0 tok/s | 20.2-20.8 tok/s | +| decode with the MTP draft layer (`--spec 4 --mtp`) | - | **42.7 tok/s** at the 2,185-token context (81% accepted, 2.9 tokens/round); 45.3 on a short prompt | + +Prompt reading is where Strata's design pays (oneMKL GEMM over dequantised experts, the whole model on +the card). Decode is at ~80%: a speculative round costs ~53 ms whatever its size and the suffix drafter +is accepted 9% of the time, so nearly every round yields one token; `--spec 4` (16.9 tok/s) was worse +than `--spec 2` (20.8) for that reason. The kernels themselves run at 130-160 GB/s of weights on a card +that streams 600 GB/s (`sycl/probe/bw.cpp`, incompressible data) - the same class llama.cpp reaches - +and five variants of the hot Q6_K matvec (lanes per row, rows per warp, unroll, 16-byte loads, software +pipelining; `mmvq_bench`) all landed in that band. The draft source was the lever: the base +Qwen3.8-Flash-Next checkpoint's MTP layer (`tools/mtp_fetch.py fetch`, `mtp_pack.py --experts q2_0`, +`mtp_rt.py`; 4.9 GB downloaded, 809 MiB of VRAM) drafts for the Coder fine-tune at 87% acceptance: +3.4 tokens per 53 ms round, 45 tok/s, the same greedy tokens. The `mtp.cpp` path ran on the first try +under the same flags. + +Without AOT the runtime JIT-compiles every kernel on first use, ~47 s the first time a process runs; +`SYCL_CACHE_PERSISTENT=1 SYCL_CACHE_DIR=
` keeps that across runs (15 MB). + +How to run it by hand (a greedy test run, the way every number in this section was measured; inside the +`strata-sycl-dev` image, AOT build in `build-sycl-aot/`): + +``` +STRATA_VERIFY_DEVICE_PLAN=1 STRATA_VERIFY_NO_HOST=1 \ +build-sycl/strata --pack --native --ple-gguf \ + --expert-profile data/expert-profile-coder.bin --expert-cache auto --stream-experts \ + --prefill auto --spec 4 --spec-min-p 0.5 --max-context 8192 --tokens --max-new 64 --greedy +``` + +- `--stream-experts` (this port): no resident host copy of the experts; every one of the 12,288 goes from + the GGUF into the VRAM cache through a small staging ring (`GgufExpertSource`). Upstream needs 32 GB of + RAM for this model; with the flag the engine runs on 23 GiB. +- `STRATA_VERIFY_DEVICE_PLAN=1`: the GPU plans each layer itself (upstream's E-6; off by default there). +- `STRATA_VERIFY_NO_HOST=1` (this port): the host waits for the whole window graph instead of per-layer + rings. Only valid with every expert resident, which is the case on a 32 GB card. +- `--no-prefill-borrow`: the prompt path must not lend expert slots (a lent expert is served from the host + behind a flag the GPU does not see reliably here; long prompts hung without it). + +What the port had to get right beyond compiling (each is an entry in `sycl/tools/fixups.py` or a flag): + +- **Host-mapped flags.** Strata's decode is a GPU/CPU handshake through host-mapped memory. `volatile` + device loads do not bypass the caches on Intel; system-scope atomics do, and they are the only thing + measured to work (`sycl/probe/doorbell.cpp`, six variants). Host-to-device visibility *during* a kernel + stays unreliable on this platform, which is why the all-resident path waits for the window instead. +- **Bounded spins.** A device spin that never sees its flag is not a hang of one process: the xe driver + times the queue out and resets the GT node by node - a window graph has 2,400 - and the card stays + wedged until a reboot (twice). Every spin is capped (`kSpinMax`). +- **32-lane sub-groups.** The kernels are written for warps; dpct pinned 134 of 289 launches, the rest + would run at Xe2's default 16 (`-fsycl-default-sub-group-size=32`). +- **Synchronous copies.** `cudaMemcpy` blocks; dpct's default-queue `memcpy` did not wait. With the + streaming ring that filled the expert cache from overwritten buffers: non-deterministic residuals, NaN by + layer 5. Found with the per-layer residual ladder (`STRATA_VERIFY_DEBUG=1` prints R after every layer). +- `native_expert_parity` hand-ported: the GPU native expert kernel matches ggml's float reference on real + IQ1_M rows (rel 1.1e-2, the same class as the CPU path). + +Profiling: `sycl/tools/Dockerfile.unitrace` builds the dev image with Intel's unitrace; `unitrace -d` around +the engine plus `sycl/rank_kernels.py` gives device time per kernel. `mmvq_bench` and `native_expert_parity +NATIVE_BENCH=1` time the two hot kernel families in isolation (warm the clocks first: a 5 ms run measures +the ramp, not the kernel). + +**After the 0.1.25-0.1.27 merge (2026-09-30, same card, same flags, AOT).** Fibonacci prompt (19 tokens), +64 greedy tokens: decode 46.5 tok/s (85% of drafts accepted). The 2,184-token prompt: 566 tok/s prompt, +38.3 tok/s decode (77% accepted on that text); the draft layer's prompt pass is now upstream's batched one +(38.6 ms for 2,184 tokens, from 105 ms for 19 before it). Parity: 19 of 22, byte-exact `quantize_act` back. + +**Speed work, 2026-09-30 (after the 0.1.27 merge).** What moved the numbers, measured on the B70 with the +same prompts as above (outputs identical before and after each change): + +| change | effect | +|---|---| +| every window graph and the drafter's graphs captured at load (`STRATA_WARM_GRAPHS=0`: as before) | the first request no longer pays 250-290 ms of captures | +| the commit graph left running while the drafter's round runs on its own queue (`Verifier::commit(wait=false)` + `commit_finish`) | decode 38.3 -> 43.0 tok/s at the 2,184-token context, 46.5 -> 49.8 short | +| upstream 0.1.29 merged (GDN recurrence pipelining, the block-scores read, sampler) | 2,184-token prompt 765 -> 792 tok/s, decode at that context 43.1 -> 45.2 | +| the draft layer's batched prompt pass takes prompts under 64 rows (it fell back to per-6-token graphs) | its prompt cost on 19 tokens 106 -> 16 ms | +| one device module per kernel (`-fsycl-device-code-split=per_kernel`) | the first launch in the prompt path (the embedding gather) 245 -> 1 ms | +| the expert dequant writes each thread's run of FP16 values as one vector store (it wrote them one 2-byte store at a time) | dequant per expert 0.085 -> 0.030 ms; prompt 496 -> 575 tok/s at 2,184 tokens, 720 -> 841 at 8,000 | +| SWAR sign compare/subtract in the expert dots, a local-memory resident-plan kernel, a split-K fused down kernel (bit-identical to the single-token one) | parity-clean, no measurable decode change; kept | +| the PLE row reader's default queue depth 16 -> 64 blocking O_DIRECT threads (`STRATA_IO_THREADS`; 128 and 256 change nothing: the drive tops out near 85k IOPS on the 27k random 4 KB reads a 2,184-token prompt needs) | the rows of that prompt 466 -> 330 ms | +| a short first prompt chunk (`STRATA_PREFILL_FIRST`, default 256 tokens) so the GPU starts while the remaining rows are still being read | 2,184 tokens: 711 -> 765 tok/s, 8,000: 857 -> 986; time to first token about 150 ms less. The chunk boundary moves rounding in the expert GEMMs, so a long greedy continuation can diverge late (token 45 of 64 on the test prompt) | + +Draft policy sweep (2,184-token prompt, 128 tokens): windows of 6 (`--spec 4`) at 41.6-43.5 tok/s; `--spec 2` +33.6, `--spec 6` 35-37; `--spec-min-p` 0.3-0.7 within noise. Profiles (unitrace, `strata-sycl-dev:metrics` with +Intel's metrics libraries and `dev.xe.observation_paranoid=0`): the expert dot kernels are ALU-bound (77% XVE +active), the dense projections memory-latency bound (92-128 GB/s at 84-93% occupancy), a decode round is 80-85% +kernel time and ~5 us of launch gap per node over 2,400-2,600 nodes. + +**XMX.** oneMKL's FP16 GEMMs already run on the XMX units (30-60 TFLOP/s in `xmx_gemm_bench`); the prompt path is +bound by the dequant that feeds them, not by the products. Two joint_matrix kernels were written and are correct +but lose to the existing paths on this card, so both stay opt-in: `xmx_gemm_iq` (a fused dequant + GEMM straight +from the quantized rows, 4-5x slower than dequant + oneMKL) and `qsa_prompt_attn_xmx` (the port of the mma.sync +prompt attention; `qsa_prompt_attn_parity` passes at 1e-6 of scale, 3x slower than the FP32 fallback per chunk; +`STRATA_PROMPT_ATTN_XMX=1`). Where the prompt time goes now (2,184 / 8,000 tokens): dequant 28% / 27%, GEMMs +22% / 20%, the per-layer host grouping 9.5% / 9%, attention 7% / 14%, embeddings + PLE rows 13% / 5%. + +A trap worth knowing: with a native pack `--prefill-until N` does not feed the rest of the prompt through the +token loop (it is skipped for native packs), so the tokens after N are dropped and the model free-runs. Compare +output tokens between paths, never only timings. + +**An 80,000-token prompt (2026-09-30).** Where the time goes changes completely at this scale: + +- **The VRAM plan.** `--expert-cache auto` fills the card down to `--vram-reserve-mib` *before* the KV state + (about 1 GB in INT8 at 81,920 cells) and the prompt chunk buffers (about 2 GB at `--prefill 8192`) exist. With + the 1,536 MiB default that put 30.95 of the B70's 32.6 GB in use, the driver started migrating buffers and the + run never finished. `--max-context 81920 --kv int8 --vram-reserve-mib 3072 --prefill 4096` peaks at 28.8 GB. + (80k ids also exceed Linux's 128 KB single-argument limit: `--tokens-file`.) +- **Streamed experts.** The reserve costs cache slots (10,348 of 12,288 at 3 GB), and the prompt path streams the + missing experts from the GGUF for every chunk. Two port bugs sat on this path and are fixed: the stream plan + held `GgufExpertSource::blob()` pointers across ~1,900 reads of a 512-slot ring (so blobs were overwritten + before they were copied: the 75 s / 1,065 tok/s measured first was computed partly with the wrong experts), and + the stream-all walk hangs on this card in its first large chunk (the copy engine stops on a barrier). The stager + threads now read the blobs themselves, and the port uses the per-layer routed-only walk (`STRATA_PREFILL_RING=8` + upstream, the port's default; `STRATA_PREFILL_STREAM_ALL=1` restores the other for debugging). +- **Correct result: 80,000 tokens in 101 s = 790 tok/s.** GPU time: expert down GEMM 26.0 s, attention 15.4 s, + dequant 12.7 s, QSA block selection 9.3 s (0.2 s at 8k: it scans every block of the context per query), gate/up + GEMM 8.9 s, gather 6.1 s, the per-layer grouping sync 5.2 s, GDN recurrence 4.8 s. The PLE rows are free at this + scale (97.6% row-cache hits). +- **Decode after such a prompt, and the fix.** Without lending cache slots to the prompt path (`--no-prefill-borrow`, + which the port used from the start) the reserve evicts ~1,900 experts for good and decode after the prompt runs at + 2 tok/s. Borrowing lends ~940 slots to the prompt path and refills them in about a second afterwards: 80,000 + tokens in 75 s = **1,062 tok/s, decode 35-40 tok/s** after it, at `--vram-reserve-mib 2048 --prefill 4096`. + It costs ~1 s on short prompts (2,184 tokens: 610 vs 792 tok/s), so the port borrows by default only above a + 32K context (`--prefill-borrow` / `--no-prefill-borrow` decide explicitly). + +**Long contexts (2026-10-01, engine 0.1.32-sycl, setup's flags: `--kv-resident 32768 --vram-reserve-mib 2048 +--prefill 4096`, the prompt path borrowing cache slots - the default above 32K).** Same text repeated to length, +then 256 greedy tokens: + +| context | KV | prompt | decode after | peak VRAM | experts in the host mirror | +|---|---|---|---|---|---| +| 128K | int8 | 888 tok/s (144 s) | **66.6 tok/s** | 29.9 GB | none | +| 128K | q4_0 | 848 tok/s (151 s) | 62.8 tok/s | 29.7 GB | none | +| 128K | k8v4, KV in VRAM | **1,006 tok/s** (127 s) | **66.8 tok/s** | 30.7 GB | 103 (0.2 GB) | +| 256K | int8 | 757 tok/s (338 s) | **55.9 tok/s** | 30.2 GB | none | +| 256K | q4_0 | 737 tok/s (347 s) | 51.7 tok/s | 30.0 GB | none | +| 256K | k8v4, KV in VRAM | 823 tok/s (311 s) | 52.2 tok/s | 30.9 GB | 865 (1.7 GB) | + +Borrowing keeps every expert in VRAM (the prompt buffers live in lent cache slots, refilled after the prompt). +Without it (`--no-prefill-borrow`) the buffers keep their own VRAM and ~1,000-2,300 experts move to the pinned host +mirror: the prompt is 2-5% faster, decode after it 10-23% slower (0.1.31 without borrowing: 128K int8 934 / 59.5, +q4_0 887 / 53.4, k8v4 1,026 / 54.4; 256K int8 784 / 48.7, q4_0 763 / 43.2, k8v4 838 / 42.3 tok/s). + +KV streaming (`--kv-resident`) keeps the whole KV in pinned host memory and only the attended window in VRAM, so +the KV pushes no experts out; setup.py turns it on from 64K up and keeps INT8 (the faster of the +two at every size here). Without it the KV pushes experts out and decode after the prompt fell to 4-9 tok/s at +128K-256K (2026-09-30). `--kv k8v4` does not support streaming yet: setup keeps its KV in VRAM, which pushes up to +more experts out; those come from the pinned host mirror over PCIe (planned item 2), so decode holds at 42 tok/s at +256K (it was 3.8 before the mirror). k8v4 reads prompts fastest (no streaming copies) and works through the FP32 +attention fallback (its dedicated prompt kernel is the XMX one below). + +**XMX prompt attention v2.** 64-cell chunks, vector-packed K^T and V, hi+lo Q in one accumulator per scale group, +one accumulator update per chunk: 1.4-1.5x faster than v1 and correct in all modes (`qsa_prompt_attn_parity`, +and `kv_hybrid_parity` passes completely with it), but still ~2x slower than the FP32 fallback (13.4 vs 5.5 ms per +chunk, INT8, 32K context). This attention is gather-bound: each query position selects its own ~2,000 cells, so +the K/V fetch dominates and only 12 of the 16 matrix rows are real heads. Opt-in: `STRATA_PROMPT_ATTN_XMX=1` +(64-cell chunks, 120 KB of local memory) or `=32`. + +**XMX v2 in the full matrix, and why a grouped kernel is not next (2026-09-30).** With `STRATA_PROMPT_ATTN_XMX=1` +(stage timing on, ~8-10% overhead) the long prompts run 23-33% slower than with the FP32 attention: 128K int8 666 vs +960 tok/s, k8v4 596 vs 983; 256K k8v4 506 vs 752, int8 536 vs 718 (q4_0 does not use the XMX kernel). The obvious +fix, gathering the union of neighbouring positions' cells once, depends on how much their selections overlap. +Measured on the last chunk of an 80K prompt (first QSA layer, `STRATA_DUMP_SEL=`): the union of 8 consecutive +positions is 3.3x one position's 2,051 cells (16: 5.1x), and only 12% of a selection is shared by all 8. Grouping +would cut the K/V gather to ~40% but multiply the arithmetic by 3-5x: at best 5-8 s of an 80K prompt. Not built. + +**Serving the port (2026-09-30).** `serve/server.py --engine strata` runs the SYCL engine unchanged through +`sycl/serve/strata-sycl.sh`, an `exe` that starts the binary inside the oneAPI runtime image with the serve pipes +attached (paths in the config's `args` are the container's, the data root mounted at `/work`). A config: + +```json +{"engine": "strata", "exe": "/sycl/serve/strata-sycl.sh", + "args": ["--pack", "/work/pack", "--native", "", "--ple-gguf", "", + "--expert-profile", "data/expert-profile-coder.bin", "--expert-cache", "auto", "--stream-experts", + "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", "/work/mtp/rt", + "--max-context", "32768", "--kv", "int8", "--vram-reserve-mib", "1024"], + "sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "repetition_penalty": 1.05}, ...} +``` + +Measured through the OpenAI API with those sampling defaults: 36 tok/s decode on a first turn, 33 on a follow-up +(which reuses the conversation's cached prompt), against 24-26 for llama.cpp on the same card. After the decode work +(2026-10-01 build): 48-72 tok/s on a ~190-token answer, prompt included (the first request after a start is the slower +one); 55-59 tok/s over 5,000-18,000-token answers on the 2026-09-30 build. The reserve matters: +with `--stream-experts` there is no host copy of the experts, so any expert left out of VRAM is read from the SSD +and computed on the CPU whenever it is routed. At 1,536 MiB the cache came up 128 experts short and decode fell to +5-10 tok/s; 1,024 MiB fits all 12,288 with 2 GB of VRAM still free. + +**Logprobs (2026-10-02).** `/v1/chat/completions` takes OpenAI's `"logprobs": true` and `"top_logprobs": 0..20`, +streamed or not, through `sycl/serve/server_intel.py`; the reply carries `choices[0].logprobs.content[]` (`token`, +`logprob`, `bytes`, `top_logprobs`), and with thinking on the thinking tokens under `reasoning_content`. The engine +(the port only) gets `logprobs=K` on its GEN line and writes an `LP logprob id:logprob ...` line after each `T` +line, from the verify window's head logits - the distribution the token was taken from, before temperature, +penalties and sampling. Upstream's server ignores the lines, and an engine never asked writes none. Each token +costs one 1 MB logits row copy when asked. Measured (IQ2_XS, "capital of France"): "Paris" at -0.0019 (p 0.998), the +same answer and no measurable time without it. Not on `/v1/completions` or the Anthropic endpoint yet. + +**The Monitor tab on Intel.** `sycl/serve/server_intel.py` is `serve/server.py` with two additions made at run +time: + +- **GPU readings.** When NVML has no card, it plugs `sycl/serve/xe_telemetry.py` into `serve/telemetry.py`'s + `gpu_reader`. That reads the Arc through sysfs (temperature, power and its cap, the PCIe link the card + trained at). Load and VRAM come from `/run/gpustat.json`: xe reports them per client in `/proc/*/fdinfo`, + which only root can read, so a small root sampler writes them (`sycl/tools/gpustat.py`; install it with its + `gpustat.service` as its header says). +- **A Model menu.** A run config may name a `model_switcher` (an RPC taking `{"mode": m}`) for a host that swaps + models on one card. The web app's header then gets a Model menu (`sycl/serve/web/switcher.js`, injected into + the page). + +**Speed depends on the text.** Decode with speculative decoding tracks how often the draft layer guesses right. +The served engine at 32K context: 45-51 tok/s on the test prompt (continuing a Fibonacci function, 77-85% +of drafts accepted), 30-39 tok/s on a chat answer with prose (55-72%); sampling and the repetition penalty cost +nothing measurable. The engine used to abort at exit in serve mode (a queue wait in a destructor after the +runtime's teardown began); it now exits directly once its requests are done. + +**Planned (2026-09-30), in order.** Ranked by payoff on this card; the first three were taken first. + +1. Expert dot products on XMX in integer mode: a decode window (up to 6 tokens) fits one INT8 DPAS (1-8 rows), the + i-quant grids decode to small integers, the activations are already INT8. Today: scalar dp4a, ALU-bound (77%). + **Parked**: three `joint_matrix` versions (opt-in `STRATA_EXPERT_XMX=1`, do not enable) were 1.4x and 2-3x slower + than dp4a, and the third (B filled in place with `joint_matrix_apply`) hung the GPU. At 1-6 rows the grid decode + and the packed-B layout cost more than the DPAS saves. +2. Experts missing from VRAM read from pinned host memory over PCIe instead of the SSD (the 256K decode collapse). + **Done**: at start-up every expert without a VRAM slot is read into a pinned host mirror (`STRATA_MIRROR_MIB`, by + default free RAM less 4 GiB), and the device-built verify plan points the expert kernels straight at it. Before, + that plan dropped non-resident experts, so output with misses was wrong. Forced test (`--expert-cache 8000`, + 1,879 experts / 3.6 GiB out of VRAM): decode 2.6 -> 40.9 tok/s (full cache 43.3), prompt 451 -> 640 tok/s + (776), output tokens identical to the full-cache run. About 3.6 GiB of VRAM can go to context for ~6% of decode. +3. KV streaming (`--kv-resident`) from 64K up: only the attended window of the KV in VRAM. **Done**: 256K decodes at + 31 tok/s (from 4-5). +4. QSA block selection on XMX: every query against every pooled block, a dense product that grows with the context. +5. The hot decode kernels re-tuned for Xe2's native 16-wide sub-groups (twice the registers per thread). + **Tried, no gain**: SIMD16 builds of the multi-column mmvq and the wide Q6_K kernel (`STRATA_MMVQ_SG`: 16 all, + 1 IQ4_XS only, 2 short outputs only; default 32). Alone (`mmvq_sg_bench`) SIMD16 is up to 1.45x faster on IQ4_XS + and 1.3x on the 640-row shared-expert projections, 10-25% slower on the large K-quant ones; in the engine no + setting beats SIMD32 beyond run-to-run noise (SIMD32 itself lands at 39 or 45 tok/s). Output tokens identical. + The same bench shows the real headroom: the dense decode kernels stream 100-280 GB/s of a 608 GB/s card + (Q6_K, the most common type, ~146 GB/s at 2-4 columns). + **Found and fixed: misaligned loads.** A Q6_K block is 210 bytes, so every block's `ql`/`qh` runs start only + 2-byte aligned, and the B70 splits a misaligned 16-byte load into pieces. The same weights repacked at a + 224-byte stride ran 2.3-4.7x faster (`q6k_align_bench`). Without changing the layout, the wide Q6_K kernel now + does two aligned 16-byte loads and a shift (`load16_a2`; both stay inside the block) and takes every Q6_K + shape and window width (it used to be gated to n_out >= 4096, 1-4 columns): 2560->10240 at 1/2/4/6 columns + 160/145/141/101 -> 493/432/331/273 GB/s, the 248K-row head 150 -> 407 GB/s at 1 column. Output tokens + identical. **Coder decode 44.9 -> 54 tok/s** (2k prompt, greedy). `STRATA_MMVQ_A2=0` restores the old path. + Still misaligned: IQ4_XS (136 B, 8-aligned, ~100 GB/s), IQ4_NL (18 B), Q8_0 (34 B); Q4_K/Q5_K are aligned + but use 4-byte loads in the multi kernel (230-280 GB/s). + +**Decode round 2 (2026-09-30), from a unitrace of 256 decoded tokens.** Each step measured on its own, 19-token prompt, +256 tokens, two runs each, output tokens identical throughout: + +| | decode | +|---|---| +| after the Q6_K alignment fix | 53.9 tok/s | +| + `resident_plan` grouping in parallel (thread 0 alone took 73 us per layer, ~3.5 ms a round) | 57.1 | +| + the GR down kernel reads the activations directly (the 60 KB SLM tile per group capped occupancy) | 58.7 | +| + wide 16-byte-load kernels for Q4_K, Q5_K, IQ4_XS (codebook in registers) | 62.6 | +| + wide kernels for Q8_0 (MTP dense, shexp down of layer 0) and IQ4_NL (shexp down); Q6_K's activation loads aligned | 65.6 | +| + the GR down projection sliced by columns (each group stages one 128-column slice of xn, 4 lanes per row) + a fixed-order reduce | 70.6 | +| + IQ4_NL expert dots (the down projection in 39 of 48 layers): codebook in registers, weights as aligned 4-byte loads, bitwise the same ints (2026-10-01) | 76.1 | +| + GR norm per (token, stream), bitwise the same; aligned weight loads in the IQ3_XXS/IQ3_S/IQ2_S gate/up dots | **77.9** | + +The last step changes the output: identical for 146 tokens, then a near-tie after a comma goes the other way (the new +kernels sum in a different order). Q8_0 kernels 4-6x (189 -> 31 us at 2560 x 10240, 2 columns), IQ4_NL 640 -> 2560 +28 -> 6.6 us. The aligned-load helper only loads its second chunk when the address is unaligned, so it never reads a +16-byte chunk without a needed byte and cannot cross a page at the end of an allocation. `STRATA_MMVQ_WIDE_32=0` +restores the old Q8_0/IQ4_NL kernels. The sliced GR down kernel (GR read 108.6 -> 76.5 us at 6 tokens, sums equal to +~1e-7) flips that near-tie back: its output is the original one. `STRATA_GR_DOWN_SLICED=0` restores the direct kernel. + +Kernel level: IQ4_XS 107 -> 323 GB/s at 2 columns (61 -> 212 at 6), Q4_K/Q5_K 1.3-1.6x; the GR read 135 -> 110 us at +6 tokens (bitwise equal). Switches to the old paths: `STRATA_PLAN_PARALLEL=0`, `STRATA_GR_DOWN_DIRECT=0`, +`STRATA_MMVQ_WIDE_K=0`. (`iq_parity` reports 10 "missing fixture" failures with and without the change: the oracle +fixtures are not in the port's tree.) + +**Two-speed runs, explained (2026-09-30).** Identical greedy runs decode at either ~45 or ~39 tok/s. A per-gather +trace of the PLE reader (`STRATA_PLE_TRACE=1`) shows the slow runs pay one 226 ms PLE read stall in the first +decode round, after the window graphs are captured; every other read and round matches the fast runs. Prompt time +plus decode time is the same in both modes (4.95-5.17 s): the stall lands either in the prompt's PLE wait or in the +first decode round, so it is a once-per-process cost, not lost throughput. Ruled out: NVMe APST, the I/O scheduler +(`none`), CPU starvation (93% idle during decode), I/O thread count. Compare runs on time to first token + decode. +6. INT8 prompt GEMMs: experts dequantized to INT8, oneMKL/oneDNN INT8 on XMX (half the dequant bytes, 2x rate). +7. Fewer graph nodes per decode round (~2,500 at ~5 us): norm+rope, scores+top-k, gate+quantize fused. +8. Wider speculation (two draft branches per verify window): the kernels are latency-bound, so it is nearly free. +9. A model bigger than VRAM: the original Qwen3.8-Flash-Next IQ2_XS (35.5 GB of experts; the same path suits Q2_0 + and Swift 1.5) on the B70 with 23 GB of RAM. ~24 GB of experts in VRAM, the rest (~10-12 GB) in the pinned host + mirror the device plan reads over PCIe (item 2). The port has the IQ2_XS/IQ3_XXS/Q2_0 expert kernels. Open: whether + a 10+ GB pinned mirror fits beside everything else in 23 GB, and decode with that share of experts on a Gen3 x8 + link (3.6 GB mirrored measured 40.9 tok/s; expect less). Needs the 68 GB download. + **Done (2026-10-01)**: shard 1 downloaded (39.2 GB; shard 2 is byte-identical to the Coder's, so a hard link), + a native pack (`tools/iq_pack.py`, 6 s), the original model's expert profile, the same MTP draft layer. 18,329 of + 24,576 experts in VRAM (24.6 GiB), 6,247 in the pinned host mirror (8.4 GiB, 9 s to fill), host RAM never below + 12 GB free. **Decode 50.8 tok/s** on the 19-token prompt and **60.6** after 2,184 tokens, prompt 549 tok/s; + coherent, correct answers on both. Q2_0 and Swift 1.5 (similar size) should behave the same; IQ3_XXS/IQ3_S + (43-50 GB of experts) would need 19-26 GB mirrored, more than 23 GB of RAM allows. + +**Keeping up with upstream.** A merge of upstream `main` into `b70` leaves the copies in `sycl/` behind +wherever upstream touched a file they mirror. They are refreshed by re-migration, not by hand (done for +0.1.25-0.1.27, 2026-09-30): + +1. Merge upstream into `b70`. No shared file should conflict: the Intel code is all in `sycl/`. Then check that + `sycl/setup_intel.py --check` and `sycl/serve/server_intel.py --engine mock` still run against the new + setup.py and server.py. +2. Migrate the *old* upstream tree (a `git archive` of the pre-merge commit) with `migrate.sh` into + `sycl-base`, and the merged tree into `sycl-new`; about 3 minutes each in the dev image. +3. `sycl/tools/normalize.sh ` on both: dpct's file names, the unchanged files, the + message serials, then `fixups.py`. Two runs of dpct on the same source now differ only in the kernel + name hashes it generates. +4. For every file present in both: `git merge-file sycl/F sycl-base/F sycl-new/F`. Files upstream did not + change are left alone. Copies dpct never produced (`verify.cpp`, `mtp.cpp`, `remote_experts.cpp` + include no CUDA header directly) take upstream's diff by hand; new parity tests are copied in and + listed in `sycl/CMakeLists.txt`. +5. A fixup whose pattern upstream changed shows up as a compile error (the PTX gate became an `#elif` + under upstream's `__HIPCC__` guard); extend the fixup, re-run it, rebuild. + +**The 0.1.31 merge (2026-10-01).** Upstream 0.1.29 -> 0.1.31 (132 commits) by the steps above: 45 migrated files +changed for real (27 more only in dpct's kernel-name hashes), 38 conflicts resolved, verify.cpp/mtp.cpp/ +conversation_state.cpp ported by hand. A symbol audit (the port's feature identifiers counted before and after) is +part of the procedure now: it caught a dropped mirror hook and four doorbell waits that had lost their spin bound +(upstream renamed the loops; `fixups.py` covers both spellings). What the merge needed beyond conflicts: + +- **The expert kernels.** Upstream sends the i-quant experts to new multi kernels (one warp per row, 8 rows a + group); the port's grid is sized for its own kernels (8 lanes a row, 32 rows a group), so only a quarter of each + expert's rows were written and the output was end-of-text tokens. The port's kernels stay the default (they also + serve upstream's new Q4_K/Q5_K/Q5_1/Q8_0 experts); `STRATA_EXPERT_SPLIT=1` runs upstream's, with their grid. +- **Prompt-slot borrowing hung** in the first chunk of any prompt with it on (40K, 128K; GPU busy) - fixed after + the 0.1.32 merge, see "Prompt-slot borrowing: the hang" below. +- **Upstream's new tests found three dpct mistranslations from the first migration.** dpct writes `__fadd_rn(a, b)` + as `a + b` without parentheses, so `__fadd_rn(sum, c ? x : y)` became `sum + c ? x : y` (replaced, not added): in + the native QSA indexer's per-token pooled key (the decode path: blocks completed while generating got wrong + pooled keys; prompt blocks come from the batched kernel and were right), in the native QSA scores (an opt-in + path) and in the s2 activation rounding (every value 0; the Q2_0 s2 pack, unused here). Fixed, and `fixups.py` + now parenthesises. `qsa_parity`'s batch-vs-sequential test passes; decode output after long prompts changed. +- **Upstream's new kernels against the port's on the B70** (decode tok/s, Coder 19 / 2,184-token prompts, IQ2_XS + 19): port defaults 78.1 / 75.7 / 58.6; `STRATA_EXPERT_SPLIT=1` 65.6-69.5 / 67.2 / 49.1 (-11 to -16%); + `STRATA_GR_V3=1` 73.2 / 72.4 (-4 to -6%). Both stay opt-in. +- **Lanes per row of the port's expert kernels** (`STRATA_GU_LANES` / `STRATA_DOWN_LANES`, 4/8/16/32 at run time): + gate/up 8 or 16 x down 4 or 8 all decode in 37.7-38.6 ms per verify round (2 runs each, Coder, both prompts); tok/s + differences between them are draft acceptance (each split rounds differently). The default (8 / 8) stays. +- **Speed after the merge:** Coder 78.2 / 75.7 tok/s (as before), IQ2_XS 58.6 / 64.2 (from 50.8 / 60.6). +- **Still failing:** (`iq_multi_parity` on IQ2_XS: fixed later, see "Two model-specific bugs"), `s2_expert_grouped_parity` (the s2 path), `kv_hybrid_parity`'s last step + (needs the unported tensor-core prompt kernel). `ple_parity` and `native_expert_parity` need model files. + +**The 0.1.32 merge (2026-10-01).** Upstream 0.1.31 -> 0.1.32 (89 commits) by the same steps; the hash-only +differences are now canonicalized before `git merge-file` (the port's kernel-name hashes are kept), which left 10 +files with real conflicts. What it needed: + +- **Upstream's async commit** (`set_commit_async` / `wait_commit`) maps onto the port's own deferred commit + (`commit(n, err, false)` + `commit_finish`); `wait_commit` is `commit_finish`. +- **Upstream's new hyper-connection read variants** (split / staged, chosen per card by a bit-for-bit self-test at + start) are not used by the port, which keeps its sliced down / split norm read; the self-test segfaulted on the + B70, so on SYCL it runs only with `STRATA_HC_CHECK=1` (open). The port's split-norm kernel was renamed + (`gr_norm_split_port_kernel`): upstream now has one of the same name. +- Two kernel names collided after hash canonicalization (renamed), and fused_gr's per-block shared-memory query is + a fixup now. +- **Result:** every output identical to 0.1.31 (Coder 19 / 2,184-token prompts and IQ2_XS, 256 greedy tokens), + same speeds (Coder 77.7-78.1 / 75.7 tok/s, IQ2_XS 58.5), 40K prompt 1,201 tok/s then 65.1 tok/s decode. + `kv_hybrid_parity` and `qsa_prompt_attn_parity` pass (the tests now turn on the XMX prompt attention they + check); `iq_multi_parity` (IQ2_XS) and `s2_expert_grouped_parity` as before. + +**The 0.1.33 merge (2026-10-01).** Upstream 0.1.32 -> 0.1.33 (17 commits): no shared file conflicted (the Intel +code is all in `sycl/`); six engine files changed upstream and were merged by the same re-migration (only those six: +the other files dpct produced differently were left alone). Two conflicts: `--resident-cpu-experts` (upstream's new +`resident_cpu_explicit` beside the port's `--stream-experts`) and the prompt attention's compute-capability check +(the port keeps its XMX dispatch). `sycl/setup_intel.py` and `sycl/serve/server_intel.py` ran unchanged against the +new setup.py and server.py. Every output identical (Coder, IQ2_XS, the 40K prompt with borrowing); `gr_parity` and +`qsa_prompt_attn_parity` pass. + +**Prompt-slot borrowing: the hang (fixed 2026-10-01).** From 0.1.31 on, a prompt that borrowed cache slots stopped +in its first full chunk with the GPU at 100% and the host waiting on the compute queue. It was never a borrowing +bug: borrowing is just the only way the Coder streams experts during a prompt (every expert is resident otherwise), +and the streamed path's stager deadlocked. Its threads read experts into a ring of 16 page-locked buffers and, to +reuse one, waited on the copy queue's event for the DMA that last read it (the CUDA form, `cudaEventSynchronize`). +Under the Level Zero v2 adapter that event, once a host thread had waited on it, no longer released the other +queue's barrier that also listed it, and the GPU waited forever - only once a layer streamed more than 16 experts +(the ring wrapped). The v1 adapter (`SYCL_UR_USE_LEVEL_ZERO_V2=0`) and a 256-buffer ring both ran; so did a sync +after every phase (`STRATA_PREFILL_SYNC=1`, kept as a debug switch). The fix: the copy queue writes a sequence +number into page-locked host memory after each DMA and the stager polls it - no host thread waits on a queue's +event. Output is bit-identical to the run without borrowing; borrowing is the default above 32K again. + +**Two model-specific bugs found with Swift 1.5 (fixed 2026-10-01).** UkisAI's Swift 1.5 IQ2_XS (setup's `swift` +family, the same GSQ-RCO layout) decoded token 0 forever: NaN logits from layer 13 on. + +- **`--stream-experts` read the wrong shard.** Since upstream 0.1.31, `ExpertLayout::gguf_file` is per layer AND role + (`3 * layer + role`; a shard boundary can fall inside a layer). The port's `GgufExpertSource` still indexed it by + layer, so a layer in shard 2 was read from shard 1 at shard 2's offsets: garbage IQ1_M scales, infinities after the + fp16 dequantization. The original model keeps every expert in shard 1 and never noticed; Swift's layers 13-47 are + in shard 2. `STRATA_DBG_NAN=1` now also reports the experts' fp16 GEMM inputs (activations, dequantized gate/up). +- **IQ2_XS products were garbage** (the long-failing `iq_multi_parity` IQ2_XS case): ggml's `vec_dot_iq2_xs` reads + its four 16-bit codes through a `uint16_t*` to an `int2`, type punning the SYCL device compiler does not honour; + the dequantizer, which reads the codes directly, was exact. The codes are extracted by shifts now (the dot and the + expert kernels' `Split<17>`); the test checks against a CPU decode from ggml's tables too and passes. No model here + uses IQ2_XS tensors, Swift included - this was not Swift's bug, only found on the way. + +Swift 1.5 IQ2_XS after both: correct answers, 51-118 words of thinking on short questions, 48 tok/s raw decode. + +**Load time (2026-10-02).** Starting a model is mostly the expert cache's fill from the GGUF (`--stream-experts`): +the Coder's 23.4 GiB of experts took 64-76 s, the IQ2_XS's 24.9 GiB 91 s, because the fill read each expert's +three slices, copied the blob and waited for the copy before the next read. It is a pipeline now: the slots are +admitted in profile order first (the same placement), the reads go in file order by up to 8 threads into +page-locked batches of 64, and a batch's copies run while the next one is read. Cold page cache: 76.2 s -> 18.8 s +(0.33 -> 1.34 GB/s); a whole Coder start from the engine's launch to its first token 82 s -> 26 s, the IQ2_XS +120 s -> 41 s (its 8.2 GB host mirror is ~9 s of the rest). Output identical. `STRATA_FILL_SERIAL=1` is the old fill. + +**The stream-all prompt walk is back (2026-10-03).** It copies every expert the VRAM cache does not hold, layer by +layer ahead of the compute, instead of only the routed ones. It hung on the B70 until the stager and PLE fixes of +2026-10-02 and runs since. It now runs by default when the VRAM holds more than 90% of the (layer, expert) pairs; +past that it would copy several times the routed experts (the IQ2_XS keeps a quarter of them in the RAM mirror: a +2,184-token prompt fell from ~560 to 254 tok/s with it). `STRATA_PREFILL_STREAM_ALL=1` / `=0` force it on or off. +Coder, outputs identical either way: + +| prompt | routed-only | stream-all | +|---|---|---| +| 40K int8 | 1,106 tok/s | 1,160 | +| 128K int8, KV streaming | 897 | 920 | +| 128K k8v4 | 1,006 | 1,041 | +| 256K int8, KV streaming | 760 | 780 | + +Measured alongside: the 2,184-token prompt reads 784-799 tok/s on both the 0.1.35+PR and the 0.1.38 build (three +runs each), so the 825 seen once on 0.1.35 was session variance, not a regression. The prompt path at 40K (Coder, +GPU timeline): expert dequant 15.7%, expert GEMMs 23.4%, host grouping 6.5%, gather 5.7%, combine 2.4%, prompt +attention 19.2%, QSA select 6.8%, DeltaNet recurrence 5.8%, hyper-connection reads 4.6%. Upstream's sm_90 cluster +kernels (greedy sampler, QSA top-k) would save next to nothing here: the sampler reads ~6 MB a round against a 13 ms +token. Q4_0 tensor-core prompt attention (#452) is not worth porting: the port's XMX prompt attention is 2-3x slower +than the plain kernel it uses for every KV format. + +**The 0.1.38 merge (2026-10-03).** Upstream 0.1.35 -> 0.1.38 (83 commits) merged the seven PRs the port had taken +early, so their header forks in `sycl/include` are gone; the merge base for the 3-way merge was the port's own "main + +PRs" migration. New in the port with it: the DeltaNet output norm without its dead FP32 store, two prompt-path +fixes (the fused layout's buffers, the streamed walk's resident lookup), `STRATA_GR_DOWN_MAX4=1` (opt-in; neutral on +the B70: 2,184-token prompt 793 vs 788 tok/s, decode 76.2 vs 76.3). Stubbed in the port: `--peer-device` (a second +GPU as an expert-cache tier: upstream's code is CUDA calls; `open` refuses with a message) and the fused int8 prompt +kernels (#136, part of the MMQ library the port does not build). Off on SYCL: the sm_90 thread-block-cluster greedy +sampler and QSA top-k (no SYCL counterpart; the callers take the plain kernels). `STRATA_GDN_KEYHEAD=1` stays opt-in +(still 8% slower here: 727 vs 788 tok/s). `qsa_prompt_attn_parity` now also tests upstream's Q4_0 tensor-core mode +(#452), which the port does not have: those cases report "refused" (the int8 and fp16 XMX cases pass); a `--kv +q4_0` prompt takes the older kernel, as before. Outputs identical (Coder, IQ2_XS, 40K); 128K int8 KV streaming +892 / 66.8 tok/s. + +**0.1.35 and seven open upstream PRs (2026-10-02).** Upstream main 0.1.33 -> 0.1.35 merged as before, then seven open +PRs ported into `sycl/` ahead of upstream (one dpct run of main + all of them, 3-way merged into only the files they +touch; `sycl/tools/merge_upstream.py`). Their header changes live in `sycl/include` until upstream merges them. + +| PR | what | on the B70 | +|---|---|---| +| #385 (sergqwer) | stager: a buffer's first job of a generation waits for the previous DMA from it | race fix; same output | +| #463 (constantindjonkam) | decode waits for an adaptive swap before reading the residency table | determinism fix | +| #453 (architectds) | the drafter's batched K/V on the KV-streaming ring | 128K int8: 888 -> 895 tok/s prompt, 66.6 -> 67.0 decode | +| #374 (sergqwer) | the first chunk's PLE rows read beside layer 0 | part of the 2,184-token prompt's 784 -> 825 tok/s | +| #363 (BlueKingMuch) | the PCIe expert call: group stride, fused SwiGLU + q8_1 | IQ2_XS decode +1.7%; re-done on the port's lane kernels | +| #407 (sergqwer) | `--adapt-tuned` (opt-in) | neutral here; stays opt-in | +| #413 (BlueKingMuch) | DeltaNet recurrence per key head | bit-identical but 8% slower prompt here: off (`STRATA_GDN_KEYHEAD=1`) | + +#374 needed two port fixes: its next-chunk read assumed every chunk is the full chunk length (the port's first chunk +is 256 tokens: the second chunk's rows were read from the wrong place), and its host wait on the PLE upload's event, +now inside the layer loop, deadlocked the prompt past ~4K tokens under the Level Zero v2 adapter (the stager's bug +again): the upload is marked by a polled sequence number now. #413's gate is an NVIDIA SM-count rule and its parity +test an SM-holding NVIDIA bench (not built). Outputs identical to 0.1.33 (Coder 19 / 2,184 tokens, IQ2_XS, 40K). + +**Not ported yet (2026-10-01).** + +- Three kernels carry inline PTX (`mma.sync` tensor-core matrix ops, `ldmatrix`, `cp.async`): + `qsa_prompt_attn`, `qsa_select`'s block scores, `native_qsa_score`. The SYCL build takes the "older card" + fallback the CUDA build uses below sm_80. `qsa_prompt_attn` also has an XMX version (`joint_matrix`, opt-in + `STRATA_PROMPT_ATTN_XMX=1`): correct, but slower than the fallback (see "XMX prompt attention v2"). +- The ggml MMQ prefill path (`moe_mmq.cu`) needs llama.cpp's ggml-cuda sources; not built. +- AOT device code is what runs: `AOT=bmg-g31 BUILD_DIR=.../build-sycl-aot` (the JIT build costs ~47 s of + compiling on the first window). + +## Not done + +- Images, on both Intel engines. Strata's vision path encodes with `strata-vision` into embeddings the CUDA + engine reads; neither the SYCL port nor the llama.cpp config wires it yet. +- Speculative decoding on the llama.cpp path (the GGUF carries no draft layer llama.cpp can use). The SYCL + port has it (MTP draft layer, `--mtp`). + +## Measured, 2026-10-01, Arc Pro B70, Coder IQ1_M, 32K context, INT8 KV: the SYCL port (engine 0.1.31-sycl) + +| | | +|---|---| +| decode | 78.2 tok/s on a 19-token prompt, 75.7 after a 2,184-token prompt (256 greedy tokens, MTP + suffix drafts) | +| prompt | 780 tok/s on 2,184 tokens; 934 tok/s at 128K, 784 at 256K | +| through the API | 48-72 tok/s on a ~190-token chat answer, prompt included (the first request after a start is the slower one) | +| VRAM | all 12,288 experts resident, ~1.9 GB free with everything loaded (`--vram-reserve-mib 1024`) | +| RAM | no host copy of the experts (`--stream-experts`) | + +## Measured, 2026-09-29, Arc Pro B70, Coder IQ1_M, 32K context, q8_0 KV: llama.cpp + +| | | +|---|---| +| load | ~100 s | +| VRAM | 28.4 of 32 GB | +| decode | 23-25 tok/s; GPU 92% busy at 165 W, CPU idle | +| prefill | 149 tok/s on a 2,701-token prompt; 424 tok/s on a 104,798-token prompt at 131k context | +| quality | correct code on every test; matches the NVIDIA path token for token in spirit, not measured | diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md new file mode 100644 index 0000000..7b6acfe --- /dev/null +++ b/docs/INTEL_ARC.md @@ -0,0 +1,126 @@ +# Intel Arc (experimental) + +Strata 0.1.39 includes an **experimental Intel Arc engine**: Strata's own engine ported to SYCL (Intel oneAPI). +maxfridbe wrote it in [#423](https://github.com/Niko1221/Strata/pull/423), with fixes from the people testing it. +The code is in `sycl/`, and the port's own notes, measurements and maintenance procedure are in +[docs/INTEL.md](INTEL.md). This page covers what you need, how to build it, and what has been tested. + +**Experimental means:** the Strata maintainers have no Intel GPU. We compile the port and run its kernel tests, but +we have not run it on an Arc. Every result on Arc hardware below comes from the community. The NVIDIA and AMD +engines are unchanged: the Intel build is a separate CMake target, off by default. + +There is **no ready-made Intel engine** in the release zips. You build it from source on Linux. + +## What has been run, and by whom + +| | Hardware | Result | Reported in | +|---|---|---|---| +| Port author | Arc Pro B70 32 GB, Ubuntu 24.04 | Coder IQ1_M: 70-78 tok/s decode, ~790 tok/s prompt; IQ2_XS: 51-64 tok/s; 256K context measured | #423, [INTEL.md](INTEL.md) | +| Community | 2x Arc Pro B70, `--layer-split` | Flash-Next IQ3_XXS 66 tok/s decode, 394 tok/s prompt (with the `stage_room` fix that is now in 0.1.39) | #423 | +| Community | Arc Pro B50 16 GB | Coder IQ1_M ~23 tok/s, IQ2_XS ~25-27 tok/s, up to 128K | #423 | +| Community | Arc B580 12 GB, WSL2 | IQ2_XS ~21 tok/s, Coder ~15 tok/s; **device loss also seen** | #423 | +| Strata maintainers | no Arc | compile check and kernel tests on a CPU device only (below) | this release | + +The 0.1.39 port re-migrates 0.1.38's port onto the 0.1.39 engine sources (the #606 NaN fix, the #649 verify +trace, the new prompt paths). It compiles and its kernel tests run, but **nobody has run the 0.1.39 port on an Arc +yet**. The numbers in the table were measured on earlier versions. + +## What was tested here (0.1.39) + +- **Compiles:** Ubuntu 24.04 (WSL2), Intel oneAPI DPC++ 2026.1.1 + oneMKL 2026.1. The whole `sycl/` project + builds with 0 errors: the `strata` engine plus all 157 targets (the kernel parity tests and benches). The build is + SPIR-V (JIT). The AOT build (`STRATA_SYCL_AOT`) was not built here, because it needs `ocloc`. +- **Kernel parity tests on a CPU** (`ONEAPI_DEVICE_SELECTOR=opencl:cpu`, Intel's OpenCL CPU runtime, AMD Ryzen 5 7600): + 14 of 25 pass. That is the same set that PR #423's own 0.1.38 port passes on that device: the failures are tight + float tolerances on the CPU's math (rel 3e-6 against a 1e-6 limit), model fixtures that are not present, and two + tests that time out on a CPU. This is a check that the kernels compile and compute, not a test of an Arc. +- **Setup:** `--backend sycl` warns, then hands over to `sycl/setup_intel.py` on Linux (unit tests: + `tools/test_setup_sycl.py`). +- **Unchanged:** the CUDA engine's greedy output, checked byte-identical against the gated 0.1.39 build (Q2_0 and Coder). + The HIP build is not affected (the option is off by default). + +**Not tested by anyone yet:** Windows (no native build path; see below), Arc on WSL2 for the 0.1.39 port, the Alchemist +A-series, integrated Arc GPUs (the B390 / Panther Lake in #515; the shared-memory planning does not exist yet), and +images (not wired on Intel). + +## What you need + +- **Linux**, e.g. Ubuntu 24.04, with Intel's GPU driver (the `xe` or `i915` kernel driver plus the compute runtime / + Level Zero; on Ubuntu, `intel-opencl-icd libze1 libze-intel-gpu1`, or Intel's + [client GPU guide](https://dgpu-docs.intel.com/driver/client/overview.html)). +- **Intel oneAPI**: the DPC++ compiler (`icpx`, 2025.3 or newer; 2026.1 is what was built here) and **oneMKL**. About 5 GB. +- `cmake` 3.24+, `ninja`, `git` (the build fetches ggml unless you point `STRATA_GGML_DIR` at a llama.cpp checkout), + Python 3. +- For `setup --backend sycl` today: **Docker**. `sycl/setup_intel.py` runs the engine in the `strata-sycl-dev` + image built from `sycl/tools/Dockerfile`. Note that the Dockerfile starts from a community llama.cpp SYCL image + (`ghcr.io/snailium/...`), not an Intel or Strata image. +- VRAM: the port keeps the experts on the card (`--stream-experts`). A 32 GB card holds the Coder IQ1_M or IQ2_XS. + Smaller cards mirror part of the experts in RAM and are slower. + +## Build (Linux) + +Install oneAPI from Intel's apt repository (this is what was used here): + +```sh +wget -qO- https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS.PUB \ + | sudo gpg --dearmor -o /usr/share/keyrings/oneapi-archive-keyring.gpg +echo "deb [signed-by=/usr/share/keyrings/oneapi-archive-keyring.gpg] https://apt.repos.intel.com/oneapi all main" \ + | sudo tee /etc/apt/sources.list.d/oneAPI.list +sudo apt update +sudo apt install intel-oneapi-compiler-dpcpp-cpp intel-oneapi-mkl-devel ninja-build cmake git +``` + +Then build the engine. Either command works: the first goes through the top-level CMake option, the second +configures the `sycl/` project directly. + +```sh +source /opt/intel/oneapi/setvars.sh +cmake -S . -B build-sycl -G Ninja -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DSTRATA_ENABLE_SYCL=ON +# or: cmake -S sycl -B build-sycl -G Ninja -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx +cmake --build build-sycl --target strata +``` + +Options: + +- `-DSTRATA_SYCL_AOT=bmg-g31` (Arc Pro B70) or `bmg-g21` (B580 / B570 / Pro B60) compiles the GPU code ahead of + time. This needs `ocloc` (Intel's `intel-ocloc` package). Without it, the first start JIT-compiles every kernel, + which takes about 47 s. +- `-DSTRATA_SYCL_PARITY=OFF` skips the kernel tests (on by default). Run them with + `ctest --test-dir build-sycl` on the card. + +`setup_intel.py` looks for `build-sycl-aot/strata` or `build-sycl/strata` in the checkout. With the +top-level option the engine is at `build-sycl/sycl/strata`, so either use `-S sycl` or set `STRATA_SYCL_BIN`. + +## Setup and running + +```sh +./setup.sh --backend sycl [setup's usual options, e.g. --model IQ2_XS --context 32768] +``` + +This prints the experimental warning and continues with `sycl/setup_intel.py`. That script finds the Arc in sysfs, +uses the SYCL engine you built, and writes the config and `run-.sh`. It still downloads and packs the model +the usual way. To run the engine by hand (no Docker), see "How to run it by hand" in [INTEL.md](INTEL.md). + +Things that matter on an Arc (details in INTEL.md): + +- **Do not ask for more VRAM than the card has.** On the `xe` driver, an allocation past VRAM can push buffers into + RAM until the machine runs out of memory and stalls. Leave about 1.5 GB free. +- `SYCL_CACHE_PERSISTENT=0`: the persistent JIT cache crashed on Xe2 during the first compile. +- Two cards: `ONEAPI_DEVICE_SELECTOR=level_zero:*` (the image pins `level_zero:0`; `strata-sycl.sh` now passes the + variable through) and `--layer-split`. +- `STRATA_VERIFY_NO_HOST=1` (set by `strata-sycl.sh`) is only valid when every expert is in VRAM. On smaller cards + that path is the one that has hung, and #667 found the likely reason: the GPU does not see the CPU's flag + stores without a system fence. + +## Windows + +There is no Windows path yet. `setup --backend sycl` on Windows stops and points here. oneAPI exists for Windows, +but `sycl/CMakeLists.txt` uses GCC-style flags (`-mavx512f`, `-fp-model=precise`, `-qmkl`) and the runner is a +bash/Docker script, so a native Windows build would need work. Nobody has tried it. WSL2 with an Arc has been +used by one tester (the B580 row above), but setup cannot detect the card there, because it reads `/sys/class/drm`, +which WSL2 does not have. + +## Reporting a problem + +Open an issue with: the card, the driver version, `sycl-ls` output, the oneAPI version, the model and flags, and the +engine's stderr. Results from real cards are what move this from experimental to supported. diff --git a/docs/MCP_SERVER.md b/docs/MCP_SERVER.md new file mode 100644 index 0000000..4fc0536 --- /dev/null +++ b/docs/MCP_SERVER.md @@ -0,0 +1,205 @@ +# Strata's MCP server: let your AI assistant install and run Strata + +`tools/strata_mcp.py` is an [MCP](https://modelcontextprotocol.io) server for the AI assistant you already use +(Claude Code, Claude Desktop, Cursor, VS Code, Codex ...). Add it once, then ask in plain words: + +- "Install Strata for this PC." +- "Start Strata." / "Stop Strata." +- "Is Strata running? How much VRAM does it use?" +- "Which Strata model fits my PC?" +- "Strata didn't start - what does the log say?" +- "How fast is Strata on this PC?" (a short speed test) +- "How do I connect Open WebUI / the OpenAI SDK / Claude Code to Strata?" + +The assistant calls the server's tools. The tools run Strata's own setup and start the model the way the start +scripts do. It is one Python file that uses only the standard library, so it works before setup has created +`.venv`. It needs Python 3.10 or newer, 64-bit on Windows. + +It is not the same thing as [Tools from MCP servers](DETAILS.md#tools-from-mcp-servers). That feature +(`serve/mcp.py`) lets the *Strata model* call tools from your MCP servers in its chat page. This page is the other +direction: *your assistant* manages Strata. + +## Add it + +You need a copy of Strata: the zip from GitHub, or `git clone https://github.com/Niko1221/Strata`. Below, +`C:\Users\you\Strata` (Windows) and `/home/you/Strata` (Linux) stand for that folder. Use `python3` on Linux. On +Windows, use `py` if `python` is not on your PATH. + +### Claude Code + +```bash +claude mcp add strata -- python C:\Users\you\Strata\tools\strata_mcp.py # Windows +claude mcp add strata -- python3 /home/you/Strata/tools/strata_mcp.py # Linux +``` + +Add `--scope user` to have it in every project. `/mcp` in Claude Code shows that it is connected. + +### Claude Desktop + +Open Settings > Developer > Edit Config (`claude_desktop_config.json`) and add: + +```json +{ + "mcpServers": { + "strata": { + "command": "python", + "args": ["C:\\Users\\you\\Strata\\tools\\strata_mcp.py"] + } + } +} +``` + +On Linux, use `"command": "python3"` and `"args": ["/home/you/Strata/tools/strata_mcp.py"]`. Restart Claude +Desktop after the change. + +### Cursor + +Use `~/.cursor/mcp.json` for every project, or `.cursor/mcp.json` in one project. The format is the same as +Claude Desktop's: + +```json +{ + "mcpServers": { + "strata": { + "command": "python", + "args": ["C:\\Users\\you\\Strata\\tools\\strata_mcp.py"] + } + } +} +``` + +### VS Code (GitHub Copilot agent mode) + +Use `.vscode/mcp.json` in a workspace, or run "MCP: Open User Configuration" from the command palette: + +```json +{ + "servers": { + "strata": { + "type": "stdio", + "command": "python", + "args": ["C:\\Users\\you\\Strata\\tools\\strata_mcp.py"] + } + } +} +``` + +On Linux, use `"command": "python3"` and `"args": ["/home/you/Strata/tools/strata_mcp.py"]`. + +### Codex CLI + +In `~/.codex/config.toml`: + +```toml +[mcp_servers.strata] +command = "python" +args = ['C:\Users\you\Strata\tools\strata_mcp.py'] # Linux: command = "python3", args = ["/home/you/Strata/tools/strata_mcp.py"] +tool_timeout_sec = 180 # strata_stop / strata_benchmark can take longer than 60 s +``` + +### Any other MCP client + +The command is `python /tools/strata_mcp.py`. The transport is stdio. It speaks MCP revision +2025-06-18, and also 2025-03-26 and 2024-11-05. + +`--root ` manages a Strata folder other than the one the file is in. For example: +`python D:\tools\strata_mcp.py --root D:\Strata`. + +## The tools + +| Tool | What it does | Arguments (all optional) | +| --- | --- | --- | +| `strata_status` | Whether a model is running: the model, engine version, context, busy or idle, VRAM and RAM in use. What is installed: models, start scripts, engine version, data folder, downloads. An install in progress. This PC's hardware: OS, CPU, RAM, GPUs, page file, free disk. The model and context setup recommends for this PC. | `port`, `hardware` (true/false) | +| `strata_models` | Every family and size setup offers, with download size, RAM needed, whether it fits this PC, and whether it is installed. Also the context lengths and the recommendation. | - | +| `strata_install` | Runs setup without questions, in the background (see below). Without `confirm: true` it only returns the plan. A second call shows the progress. `cancel: true` stops the install. | `family` (qwen, swift, coder, unsloth), `model` (Q2_0, IQ2_XS, IQ3_XXS, IQ3_S, IQ1_M, UD-IQ4_XS, UD-Q4_K_XL), `context` (8192 ... 524288), `vision` (no, yes, gpu, cpu), `kv` (int8, q4_0, k8v4), `gpu` (a number) or `gpus` ("0,2", "all"), `backend` (auto, cuda, hip), `low_ram`, `port`, `data_dir`, `confirm`, `cancel` | +| `strata_start` | Starts an installed model in the background and waits until it answers. If it is not ready after `wait_seconds` (default 50), it returns "loading". | `model` (an id from `strata_status`, e.g. `q2_0`, `coder-iq1_m`; default: the most recently used), `port`, `gpu`, `wait_seconds` (0-600) | +| `strata_stop` | Unloads the model through the server's own API, then ends the server it started. | `port`, `force` | +| `strata_logs` | The last lines of the server log, the engine log or the setup log. | `source` (server, engine, setup), `model`, `lines` (1-500) | +| `strata_benchmark` | Sends a short fixed request (greedy, thinking off) and reports output and prompt tokens/s. | `port`, `max_tokens` (16-512) | +| `strata_connect_info` | The OpenAI and Anthropic base URLs, the model id, whether a key is needed, and settings for Claude Code, Codex, the OpenAI SDK, curl, Cursor, Continue and Open WebUI. | `port` | + +Every result is JSON with a one-line `summary`. It is sent both as text and as MCP structured content. + +## How it works + +**Install.** `strata_install` uses setup's own logic and tables (it imports `setup.py`'s `MODELS`, `FAMILIES`, +`CONTEXTS` and RAM checks) to fill in what you left out: + +- the size setup itself would pick: IQ3_XXS from 60 GB of RAM, Q2_0 from about 44 GB, the Coder from about 28 GB, + and the Coder in the low-RAM mode below that when the GPU makes up for the RAM; +- the context setup recommends for the GPU's VRAM; +- images off. + +The first call returns the plan: the download size (58-111 GB), the free disk space, the RAM check, and the exact +setup command. The assistant should show you the plan and call again with `confirm: true` once you agree. + +It then runs the same steps `START-HERE.bat` / `setup.sh` run: + +1. It creates `.venv` with the Python it runs on, if `.venv` is missing. +2. It runs `setup.py --yes --no-start --family ... --model ... --context ... --vision ...` as a background process. + The output goes to `.strata-mcp/setup.log` in the Strata folder. + +The tool returns at once. Call it again to see the step (1-7), the download percentage, or setup's error message. +Everything setup has finished is skipped on the next run, and downloads resume. If the AI app closes, the install +keeps running. The install is refused while a model this server started is running, because setup may replace the +engine files that model uses. + +**Start.** `strata_start` runs the same command as the `run-` script, `serve/server.py --engine strata +--config strata-.json --port N`, with the venv's Python, without `--open` (no browser) and without a console +window. The server's output goes to `.strata-mcp/server.log`. The tool then polls `GET /health` until the model +answers. Loading takes 1-3 minutes. If the server ends while loading, the tool returns the end of its log. The model +keeps running after the AI app closes, until `strata_stop`. If the AI app runs its tools inside a Windows job that +does not allow processes to leave it, the model ends together with the app. + +Two cases are refused: + +- a model is already running: the tool returns it and starts nothing; +- another program uses the port: the tool says so. + +**Stop.** `strata_stop` first sends `POST /unload`. The server sends the engine `QUIT`, and the engine frees its +VRAM and pinned RAM itself, as when you close the window. Then the server ends: + +- Linux: SIGTERM, which runs the server's own Ctrl+C path. +- Windows: the process ends. Its job object ends the vision encoder and the MCP servers it started. + +While a request is running, the tool refuses unless you pass `force: true`. + +**Status.** The tool reads `GET /health`, `/v1/status`, `/status` and, on older servers, `/metrics` on 127.0.0.1. +If a config of the folder sets an `api_key`, the tool sends that key with its own requests. It never shows the key. + +## Safety + +- **No shell, no free paths.** Every argument is checked against a fixed schema and against setup's own choices. An + unknown argument, a model or family setup does not offer, or a `gpus` value other than digits and commas is + refused before anything runs. Commands are passed as argument lists; nothing goes through a shell. +- **Paths.** The only path argument is `data_dir`. It must be one of: + - the current Strata data folder; + - a folder inside the Strata folder; + - a new absolute folder whose name starts with `Strata` (e.g. `D:\Strata-data`), whose parent exists, and which is + not in a system folder. + + `..`, relative paths and network (UNC) paths are refused. Logs are read only from `.strata-mcp/` and from the + engine log a config names, if that log is inside the Strata folder or the data folder. +- **Only its own processes.** The server records the process id *and start time* of every process it starts, in + `.strata-mcp/*.json`. It only ends a process when both match, so a process id the OS has given to another program + is never touched. A Strata started some other way (its window, a run script, a service) is only asked over its + API to unload the model. To end that server, close its window. +- **Big downloads need a yes.** `strata_install` does nothing until it is called with `confirm: true`. The plan + shows the download size and the free space first, and the install is refused if the disk is too small. +- **Local only.** The server checks `127.0.0.1` and never changes the network settings: it does not install with + `--host 0.0.0.0` or an API key. To share Strata on your network, run setup yourself (see + [Using it](DETAILS.md#using-it)). Experimental options are left off too: the speed projection, rope scaling past + 262K and `--build`. Run setup by hand for those. + +## Troubleshooting + +- **The assistant does not see the tools.** Run the command by hand: + `python C:\Users\you\Strata\tools\strata_mcp.py`. It should print `[strata-mcp] ready (Strata folder ...)` to + stderr and wait for input (Ctrl+C ends it). If it reports `not a Strata folder`, the path is wrong or `--root` is + needed. Python older than 3.10 is refused. +- **The install failed.** Ask the assistant for the setup log (`strata_logs` with `source: setup`), or open + `.strata-mcp/setup.log`. Setup's `[X]` line says what to fix. Then install again: every finished step is skipped. +- **The model does not start.** Get the server log with `strata_logs`, and the engine log with `source: engine`. + [Troubleshooting](DETAILS.md#troubleshooting) has the usual causes. +- **Tests.** `python -m unittest tools/test_strata_mcp.py` runs the tests with a fake setup and server. They do not + download anything or use the GPU. diff --git a/docs/MODELS.md b/docs/MODELS.md new file mode 100644 index 0000000..1ffc87f --- /dev/null +++ b/docs/MODELS.md @@ -0,0 +1,155 @@ +# Which model? Sizes, versions and what fits + +Strata runs one model, [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next), in several **sizes** +(the same model, compressed more or less) and several **versions** (the original, a coding version, a fine-tune). +The installer recommends one for your PC; this page explains the choice. Back to the [README](../README.md). + +> **On this page:** [Pick by RAM](#pick-by-ram) · [Speed](#how-fast-is-each-size) · [The sizes](#the-sizes) · +> [Will it fit?](#will-it-fit) · [The versions](#the-versions) · [Adding another model](#adding-or-switching-models) + +## Pick by RAM + +| Your RAM | Take | Why | +| --- | --- | --- | +| **32 GB** | **Coder** | it fits 32 GB; best at code, weaker at everything else ([why](#coder)). With a 24 GB card, Q2_0 and IQ2_XS run too ([low-RAM mode](#a-big-graphics-card-and-little-ram)) and are the better pick for general use | +| **48 GB** | **IQ2_XS** (or Q2_0, the fastest) | the larger sizes do not fit | +| **64 GB** | **IQ2_XS** (recommended), or IQ3_XXS / IQ3_S | every size fits (IQ3_S with little else open) | +| **96 GB or more** | **IQ3_S**, or [Unsloth's UD-IQ4_XS](#unsloth-ud-iq4_xs) (~4-bit) | room for the largest sizes | + +Not sure? Take **IQ2_XS**. The **Coder** is the one that fits a 32 GB PC, but it keeps only 256 of the 512 experts, +chosen on code data, so it is weaker outside code and in languages other than English. For general use, or whenever +your RAM allows, take a full model (Q2_0, IQ2_XS or IQ3_S). + +## How fast is each size + +Measured on an RTX 5070 (12 GB), a Ryzen 5 7600 and 64 GB of RAM: + +| Size | Writes answers (short chat) | Writes answers (128K context) | Reads your prompt | +| --- | ---: | ---: | ---: | +| **Q2_0** | 94 tokens/s | 76 tokens/s | 2,650 tokens/s | +| **IQ2_XS** | 79 tokens/s | 63 tokens/s | 2,090 tokens/s | +| **IQ3_XXS** | 62 tokens/s | 49 tokens/s | 1,750 tokens/s | +| **IQ3_S** | 53 tokens/s | 46 tokens/s | 1,620 tokens/s | +| **Coder** (IQ1_M) | 55 tokens/s | 43 tokens/s | 2,180 tokens/s | + +Measured on an AMD RX 9070 XT (16 GB), a Ryzen 9 3900X and 47 GB of RAM (Linux, setup's own install; Q2_0 is +above setup's RAM estimate for 47 GB and was installed with `--model Q2_0 --yes`): + +| Size | Writes answers (short chat) | Writes answers (128K context) | Reads your prompt | +| --- | ---: | ---: | ---: | +| **Q2_0** | 60 tokens/s | 48 tokens/s | 1,160 tokens/s | +| **IQ2_XS** | 52 tokens/s | 36 tokens/s | 1,110 tokens/s | +| **Coder** (IQ1_M) | 44 tokens/s | 33 tokens/s | 1,420 tokens/s | + +- **Writes answers** = how fast the reply appears (tokens per second; a token is about ¾ of a word). +- **Reads your prompt** = how fast it takes in what you send (long documents, code, chat history), measured on a + 32K-token prompt; a 4K prompt reads at 910-1,580 tokens/s. A 32K prompt takes about 15 seconds with Q2_0. + +A card with more VRAM is faster, because more of the model fits on the GPU: an RTX 3090 (24 GB) should do roughly +100-140 tokens per second. All measurements, long-context numbers and estimates for other cards are in the +[details](DETAILS.md#speed-measured). The AMD measurements per card (RX 9070 XT, Radeon AI PRO R9700, RX 7800 XT, +RX 9060 XT, RX 6900 XT) are in [AMD_HIP.md](AMD_HIP.md#rdna4-gfx1201). + +Every PC is different: `START-HERE.bat --calibrate` measures a few engine settings on yours and keeps the fastest +(about 5-10 minutes; on the PC above it made the Coder 7% faster; NVIDIA cards for now). Measured Strata on your own +PC? See [Community benchmark results](COMMUNITY_BENCHMARKS.md) for a report template and how to share your results +in a pull request. + +## The sizes + +| Model | RAM+VRAM Requirements | Speed | Quality | +| --- | ---: | --- | --- | +| **Q2_0** | 37.6 GB | fastest | good | +| **IQ2_XS** | 39.2 GB | fast | better (**recommended**) | +| **IQ3_XXS** | 47.0 GB | slower | great | +| **IQ3_S** | 54.8 GB | slowest | best: matches the full model on the published tests (original model only) | + +The download is 66-76 GB for the three smaller sizes ([details](DETAILS.md#which-model)); the first start also +fetches the MTP draft layer (~6 GB, +1 GB with images). + +## Will it fit? + +Shard 1 is the part of the model that gets loaded when it starts: its experts go into your **RAM**, the rest onto +your graphics card (the second shard, a 29 GB lookup table, stays on the SSD). So it fits when your **RAM is at least +the experts + about 10 GB** for Windows and your other programs - the experts are most of shard 1: 34 GB for Q2_0, +35.5 for IQ2_XS, 43 for IQ3_XXS, 50 for IQ3_S, 23 for the Coder (the dense weights in shard 1 go to the graphics +card). With 64 GB of RAM every size fits (IQ3_S with little else open); with 48 GB, Q2_0 and IQ2_XS. A bigger graphics card makes it faster, but it doesn't lower the RAM needed +- except in the low-RAM mode below. + +### A big graphics card and little RAM + +On a PC whose RAM cannot hold the experts beside the system, setup maps them from the model's files instead and keeps +in RAM only what the graphics card does not hold (the [low-RAM mode](DETAILS.md#speed-measured), chosen by setup). For +example, a 32 GB PC with a 24 GB GPU runs Q2_0, IQ2_XS and the Coder this way, and a 32 GB PC with a 12-16 GB GPU the +Coder. With a small card most experts then come from the SSD and it is much slower (setup says so). +`START-HERE.bat --setup --low-ram on|off` overrides the choice. + +## The versions + +### Qwen3.8-Flash-Next + +The original, in all four sizes. With images, and with the +[experimental speed projection](DETAILS.md#experimental-speed-projection-experimental-off-by-default) as an option. + +### Coder + +**[Coder](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF)** - ISTA-DASLab's coding version: +it keeps 256 of each layer's 512 experts, chosen on code (with agentic and image) data, and drops the rest (91% of +the full model's SWE-bench Verified score, 99% of LiveCodeBench, by its authors). One size (IQ1_M: its experts stored +like IQ3_S): shard 1 is **29.6 GB**, so it fits a PC with **32 GB of RAM**, runs 262K context on 64 GB, and reads long +prompts the fastest of all. With half the experts gone it is weaker outside code and in languages other than +English, Chinese and other CJK text included (#438: Chinese answers came out wrong or looping where English was +fine). For general use, or whenever your RAM allows, take a size that keeps every expert: Q2_0, IQ2_XS or IQ3_S. +More: [details](DETAILS.md#or-the-coder-half-the-experts-for-code). + +``` +START-HERE.bat --setup --family coder +``` + +### Swift 1.5 + +**[Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF)** - a fine-tune by UkisAI that +thinks much shorter before answering, so you get the answer sooner, with about the same quality. Same speed per +token, and about the same RAM as the same size of the original (no IQ3_S). Its own license applies (see its page). +More: [details](DETAILS.md#or-swift-15-a-fine-tune-that-thinks-shorter). + +``` +START-HERE.bat --setup --family swift --model IQ2_XS +``` + +### Unsloth UD-IQ4_XS + +**Unsloth's UD-IQ4_XS** (~4-bit) is the fourth version in setup's menu (`--family unsloth`, its first size), a +regular choice from 0.1.39: a 94 GB download with 59.5 GB of experts (IQ3_S and IQ4_NL), between IQ3_S and UD-Q4_K_XL +in quality. Strata keeps your RAM minus 24 GB of the experts in RAM and reads the rest from the SSD while it answers: +on a 64 GB PC part of them come from the SSD (slower; an NVMe SSD helps), from ~80 GB of RAM all of them stay in RAM. +It needs 48 GB of RAM or more and engine 0.1.38 or newer; images are an option, as with the other models. +Details: [UD-IQ4_XS](UNSLOTH_Q4.md#ud-iq4_xs-setup-from-0139-621). + +``` +START-HERE.bat --setup --family unsloth --model UD-IQ4_XS +``` + +### Unsloth UD-Q4_K_XL (experimental) + +**Unsloth's 4-bit UD-Q4_K_XL** (experimental) is the second size of the same family (`--family unsloth`): the closest +to the full model, but a 111 GB download whose 77 GB of experts do not fit in RAM. Strata keeps your RAM minus 24 GB +of them in RAM and reads the rest from the SSD while it answers: 7-8.5 tokens/s on a 64 GB PC with a 12 GB GPU, several +times slower than the sizes above, and long prompts are slow. It needs 48 GB of RAM or more, an NVMe SSD and one +NVIDIA GPU (no images yet). Details and measurements: [UD-Q4_K_XL](UNSLOTH_Q4.md). + +``` +START-HERE.bat --setup --family unsloth --model UD-Q4_K_XL +``` + +### OrcaRouter Uncensored IQ3_XXS + +For **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](ORCA.md). It needs an +explicit packing conversion and is not an installer menu option. + +## Adding or switching models + +You can add another model any time with `SETUP.bat` (the same as `START-HERE.bat --setup`; on Linux +`./setup.sh --setup`). Files another model shares are not downloaded again (the Coder uses the original's shard 2 and +vision encoder). With more than one model installed, `START-HERE.bat` asks which one to start; `run-.bat` +(Linux: `run-.sh`) starts one directly. diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md new file mode 100644 index 0000000..1270125 --- /dev/null +++ b/docs/MULTI_GPU.md @@ -0,0 +1,174 @@ +# Strata on two or three GPUs (layer split) + +One model can run across several NVIDIA cards in one PC. The layers are split into contiguous ranges, one per GPU: +the first card runs layers 0 to K-1, the next card runs K onward, and so on; the last card also runs the output head +and the draft (MTP) layer. Each card keeps an expert cache for **its own layers only**, so two cards hold about twice +the experts one card holds - for the Coder model on a 16 GB + 24 GB pair, nearly all of them, which is where the +speed comes from (decode then barely touches the CPU pool). + +This is pipeline (layer) parallelism, not tensor parallelism: a token crosses from one card to the next once per +verify window (a few hundred KB through pinned RAM), not twice per layer. No NVLink or peer-to-peer access is +needed; cards on x4 or x1 slots work, and the PCIe share of each card is probed on its own link. A `--pcie-frac` you give +is every card's share and skips those probes; there is no per-card setting yet. + +## Using it + +**Nothing to type.** `START-HERE.bat` (Linux: `./setup.sh`) lists your NVIDIA cards and says for each one whether +Strata can use it: + +``` + Your NVIDIA GPUs: + GPU 0: NVIDIA GeForce RTX 5080, 16 GB VRAM - can be used + GPU 1: NVIDIA GeForce GTX 1080 Ti, 11 GB VRAM - not supported - older than the RTX 20 series (compute capability 6.1; Strata needs 7.5 or newer) + GPU 2: NVIDIA GeForce RTX 3090, 24 GB VRAM - can be used + ... + 1) GPU 0 (NVIDIA GeForce RTX 5080, 16 GB) + GPU 2 (NVIDIA GeForce RTX 3090, 24 GB) together (recommended) + 2) GPU 2 (NVIDIA GeForce RTX 3090, 24 GB) only + 3) GPU 0 (NVIDIA GeForce RTX 5080, 16 GB) only +Which GPUs? [1]: +``` + +When two or more cards can share the model, the two best together are recommended (the newest generation first: +it becomes the main card). A model installed on one card asks once, at its next start, whether to use both from +now on; the answer is kept. + +**Choosing yourself** (at setup or at any start): + +``` +--gpus 0,2 these cards together, as nvidia-smi numbers them; the first is the main one. Remembered. +--gpus all every card that can share the model +--gpu 0 one card (at a start: for that start only) +--layer-split auto (default) or the first layer of each later card, e.g. 18 or 16,32 +``` + +**Not supported** (setup says so and names the cards that can be used instead): +- a card older than the RTX 20 series (compute capability below 7.5: GTX 10 and older); +- a card with less than 8 GB of VRAM, together with others (each card holds a copy of the dense weights and its + own prompt buffers) - unless you name it with `--gpus`: then setup says the risk and asks (`--yes` with the named + cards goes ahead); +- Intel GPUs, and a mix of NVIDIA and AMD cards. (AMD cards share a model among themselves: `./setup.sh --backend + hip --gpus 1,0`, see [AMD_HIP.md](AMD_HIP.md).) + +Or edit an existing config (`strata-*.json`), then restart: + +```json +"gpu": [0, 2], +"layer_split": "auto" +``` + +`"layer_split"` is `"auto"` (placed by each card's free VRAM) or the **first layer of each later card**: one rising +number per card after the first, not a count of layers per card. With 4 cards and a 48-layer model, `"24,36,42"` +(or `[24, 36, 42]`) puts layers 0-23 on the first card, 24-35 on the second, 36-41 on the third and 42-47 on the last. +The server checks it before the start and says what is wrong (0.1.39, #644). + +**Skip the split when the first card holds everything** (opt-in, 0.1.31): `"split_skip_if_fits": true` in the config +(engine flag `--split-skip-if-fits`, with `--layer-split auto`) runs on the first card alone when it holds every +profiled expert plus the context's KV, the draft layer and the reserve, and says so in the log; otherwise the split +stays. On an R9700 32 GB + RX 9070 XT the R9700 holds all of the Coder's experts: with the flag 4K prompts read at +1,776 tok/s instead of 1,244 (split) and decode runs at ~60 tok/s instead of ~51 (16K prompts ~5% slower than split). + +**Short prompts on a split (0.1.32, #340).** 0.1.30 gave each card's prompt path a loan from its own expert cache, +refilled after every request; on cards that hold nearly all their experts that cost short prompts up to a third of +their speed. 0.1.32 refills all cards at once, uses a smaller streaming ring on a split, and lets a card with free +VRAM keep its own prompt buffers - the same output as 0.1.31, measured on an R9700 + RX 9070 XT: 2K prompts 993 -> +1,265 tok/s, 16K 1,852 -> 1,950, decode unchanged. `STRATA_SPLIT_OWN=1` (opt-in) gives every card its own buffers: +2K 1,450 and 16K 2,227 tok/s there, but a full card then keeps a different set of experts resident, so the output +differs from the default's (stable and coherent); `STRATA_SPLIT_OWN=auto` does that only where the buffers are at +most 12% of each card's VRAM. + +**The idle card can help one-chunk prompts (opt-in, `STRATA_PREFILL_HELP=1`).** A prompt that fits one chunk runs the stages one after the other, so while +one card reads its layers the other idles. With it on, each stage hands a share of its streamed experts to the idle card: it +streams them over its own PCIe link into its own (lent) prompt buffers, computes their rows on the MMQ path and sends +them back - `--peer-device`'s peer streaming, without P2P (the activations and the rows go through mapped host memory, +read by copy kernels, so they do not queue behind the expert blobs on either card's copy engine). The share falls with +the prompt (0.41 of the streamed experts at 1.5K tokens, 0.32 at 3K) and is off from ~3.3K tokens, where the stages +overlap anyway and no share paid. Measured on 2x RTX 3090 (UD-Q4_K_XL, no P2P), prompt tok/s without / with: 1.1K 496 / +723, 1.5K 674 / 833, 2K 878 / 1,128, 2.5K 1,017 / 1,296, 3K 1,260 / 1,440; 4K and 8K unchanged, decode unchanged. It +costs no VRAM (the idle card's own prompt buffers) and ~110 KB of mapped host memory per token of the largest chunk it +helped (~360 MB at 3.3K tokens). The rows it computes round like a different MMQ grouping, so the output is not +bit-identical to the default's (it is repeatable: same prompt, same output), which is why it is **opt-in**: +`STRATA_PREFILL_HELP=1` turns it on. Native packs on the MMQ prompt path only (not with the fused prompt kernels, +`STRATA_PF_FUSED=1`, nor with `--peer-device`). With it on, `STRATA_PREFILL_HELP_FRAC=f` fixes the share. + +The engine flags behind it: `--layer-split K1[,K2..]|auto` and `--split-device D1[,D2..]` (the later stages' +devices; default the next visible ones). `--layer-split K --split-device 0` runs both stages on one card sharing +everything - the bit-exact check of the hand-off, not a speed mode. + +**Each card loads only its own layers' dense weights** (0.1.39, PR #639) with explicit split points (`--layer-split +27`, not `auto`): every card used to keep a full copy (~3.4 GB for the Coder) though its stage reads only its own +layers, and the VRAM it frees goes to that card's expert cache (2x MI50 16 GB, Coder: 8,819 -> 10,626 experts in +VRAM, decode 39.2 -> 41.7 tok/s). Opt-in for now, on AMD and NVIDIA alike: `STRATA_STAGE_TRIM=1` (please report how +it goes). +A card holding more experts can change which experts run on the GPU, so the output can differ slightly from a run +without it. + +**auto** tries every placement (all of them for two or three cards; proportional to the free VRAM beyond that) and +keeps the one whose caches would hold the most of the expert profile, hottest pairs weighted most; ties go to the +placement that leaves the fullest card the most room. The startup log prints the choice: + +``` +strata generate: layer split auto: K=19 - the caches hold 11767 of 12288 profiled pairs (fullest device 100%) +strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window +``` + +## What each card holds + +- **every card**: a copy of the dense weights (~3.4 GB for the Coder), its own session state (the KV cache of the full + context), its verify window and its prompt-path buffers, and an expert cache for its layers filled from the profile; +- **the last card**: also the output head and the draft layer (~0.8 GB); +- **host RAM**: the expert arena once, shared by all cards (the CPU pool computes whatever no card holds). + +Prompts are read in chunks that flow through the cards in turn; while a later card reads chunk c, the first card +already reads chunk c+1. Conversation checkpoints save and restore every card's state; the adaptive expert swaps copy +into the card that owns the layer. + +## Limits (for now) + +- **Works across cards** (bench/results/2026-09-29-layer-split-limits): + - images (`--vision`): each card keeps its own image-position table; + - control vectors and the experimental speed projection: each card holds the vector's tables, switched on and + off per request on all of them; + - KV streaming (`--kv-resident`): each card streams the KV of its own session; + - mid-prompt checkpoints (`--prompt-cache-every`): each card saves its part of a checkpoint when it has read that + chunk; + - the older helper-GPU caches (`--expert-cache-remote`, docs/SECOND_GPU.md): they take the visible GPUs no stage + runs on, and hold only experts no stage's cache holds. On the test rig, a 2080 Ti helper made decoding slower, + as it did without a split: its per-layer round trip costs more than the CPU pool needs for those experts. +- `--mmap-experts` needs a canonical pack (`experts.bin`), with or without a split; a native (IQ) pack says so at + start. +- The prompt path has its own buffers on every card (1.5 GB each at the default 2048-token chunk; `--prefill 1024` + halves that) instead of borrowing cache slots as one card does. An explicit `--expert-cache` on the first card is + capped to leave room for them. +- Under WDDM (Windows, and WSL2) only 8 GiB of the expert arena is pinned (more, mapped into two GPU contexts, + leaves WDDM refusing allocations); the rest streams through the pinned staging ring. A Linux driver has no such + limit, so there the whole arena is pinned (since 0.1.31; the cap cost a 4090 + 3060 split two thirds of its + prompt speed, #253). `STRATA_ARENA_PIN_GIB=N` pins at most N GiB, `0` the whole arena, on any OS. +- Every card needs compute capability 7.5 (RTX 20 or newer). The pre-sm_80 QSA scorer path is fp32 FMAs, so a + Turing card runs the same kernels instead of the tensor-core prompt attention. + +## Measured + +The Coder on an RTX 5080 + RTX 3090 (Ryzen 9 9950X3D), 32K context; details in +`bench/results/2026-09-29-layer-split/`: + +| | Prompt 16K / 28K tok/s | Decode story / code tok/s | +|---|---|---| +| 5080 alone | 1,726-2,017 / 1,970 | 83-87 / 88-105 | +| 5080 + 3090, best split (K=26) | 2,039 / 2,357 | 84 / 110 | +| 5080 + 3090, auto (K=22) | 2,037 / 2,073 | 80 / 109 | + +- **Prompts gain the most** (+18-20%): each card reads its own layers of the chunk while the other reads the next. +- **Decode is on par with the faster card alone**, and ahead on code. Once both caches hold nearly every routed + expert, the per-layer GPU time decides. +- **Correctness:** one GPU is byte-identical to 0.1.20, and the hand-off itself is bit-exact. + +**Which cards and in what order:** +- Put the fastest card first; auto gives it as many layers as its cache allows. +- Leave out a much slower card when two already hold the model. An RTX 2080 Ti as a third card made the 5080 + + 3090 pair slower (68 / 90 tok/s decode): every extra card costs its own round per window. +- More cards pay off when the model's routed experts do not fit the faster ones. + +## Several conversations at once + +With a layer split, `--batch N --batch-groups G --trim-stage-weights` decodes several conversations together and +pipelines them through the cards: see [BATCHING.md](BATCHING.md). diff --git a/docs/NVIDIA_V100.md b/docs/NVIDIA_V100.md new file mode 100644 index 0000000..7e8b0c4 --- /dev/null +++ b/docs/NVIDIA_V100.md @@ -0,0 +1,71 @@ +# NVIDIA Tesla V100 / Titan V (Volta, sm_70): the community build + +Strata's ready-made engine and the support matrix start at compute capability 7.5 (RTX 20). A V100 (7.0) runs the same +engine compiled for it, through the experimental build that issue #236 added. It is **community-tested, not part of the +supported cards**: no ready-made engine is published for it and the numbers below come from one machine. + +## Build + +CUDA 13 dropped Volta, so the build needs a **CUDA 12.x** toolkit (12.8 was used) and a host GCC that toolkit accepts. + +```sh +cmake -S . -B build -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF \ + -DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_EXPERIMENTAL_SM60=ON +cmake --build build --target strata -j +``` + +Setup does the same by itself for a model on a V100 (the experimental CUDA 12 engine, in `engine-cuda12/`: ready-made +on Windows, compiled with a CUDA 12.x toolkit on Linux; [OLDER_GPUS.md](OLDER_GPUS.md)). For a PC with a V100 and a newer card, a build for both architectures (`-DCMAKE_CUDA_ARCHITECTURES="70;86"`) is the +natural choice (a community report in issue #509 ran an RTX 3080 beside a V100 that way; it was not repeated here). On the +measuring PC a Quadro RTX 4000 (sm_75) sits beside the V100s and was hidden with `CUDA_VISIBLE_DEVICES` because the sm_70-only +build has no code for it. + +## What runs on Volta + +The flag only lowers the floor (CMake and the runtime device check) and replaces two intrinsics Volta lacks. It does not +select "old" kernels everywhere: which kernel runs is decided per architecture when the engine is built. + +| Part of the prompt path | On sm_70 | +| --- | --- | +| MoE experts (ggml MMQ) | `dp4a` kernels (Volta has no int8 tensor cores) | +| Dense projections (dequantized weights) | FP16 tensor-core GEMMs (cuBLAS / CUTLASS `s884`) | +| BF16 projections (hyper-connection, router, indexer, ...) | converted to FP16 and run on the FP16 tensor cores (#655, #540; `STRATA_BF16_TC=0`: cuBLAS BF16, an FP32 SIMT kernel on Volta) | +| QSA attention for decode and verify windows (and prompts with `STRATA_PROMPT_ATTN_OLD=1`) | #540's kernel (fewer shuffles, bit-exact; `STRATA_ATTN_PRE75=0`: the one other cards run) | +| QSA prompt attention, int8 / FP16 / K8V4 KV | `prompt_attn_v70_kernel` on `mma.m8n8k4` (`STRATA_PROMPT_ATTN_OLD=1`: the decode kernel, one query at a time) | +| QSA prompt attention, Q4_0 KV | the decode kernel | +| QSA block scores | the warp kernel (the tensor-core scorer needs sm_80) | + +## Measured + +One V100-PCIE-32GB, i9-7960X, Unsloth `UD-IQ4_XS` (not a setup model), int8 KV, MTP `--spec 2`; prompt read speed of random-word prompts, tokens/s, +with and without the Volta attention kernel (`STRATA_PROMPT_ATTN_OLD=1`): + +| Prompt tokens | old attention path | `prompt_attn_v70_kernel` | +| --- | ---: | ---: | +| 7,194 | 1,010 | 1,164 | +| 28,650 | 1,063 | 1,251 | +| 114,338 | 973 | 1,123 | + +Decode was 38-51 tok/s in every run and is not affected. The profile, the parity numbers, the needle test and the limits are in +[bench/results/2026-10-03-v100-prompt-attn](../bench/results/2026-10-03-v100-prompt-attn/README.md). + +What the kernel does and does not guarantee: against an FP64 reference its error is about 5e-6 (output scale 3.6; the FP32 kernel it replaces: 2e-6); 15 of 15 +needles were found; greedy output was identical on the 28,650- and 114,338-token prompts and differed late in the answer on the 7,194-token one (another +summation order). + +## Checking and benchmarking the Volta kernels + +```sh +cmake -S . -B build -DSTRATA_PARITY_PROMPT_ATTN=ON ... && cmake --build build --target qsa_prompt_attn_parity +CUDA_VISIBLE_DEVICES=0 ./build/qsa_prompt_attn_parity 32768 2048 5 # synthetic, no model; exit 0 = PASS +``` + +It compares the tensor-core attention with the FP32 kernel and an FP64 host reference and times both. The Q4_0 cases are skipped below +sm_80. + +## Limits + +- A layer split over two V100 was not measured with this kernel. The cards work in turn on a single request, so a split adds expert-cache room, not prompt speed. +- sm_60 (Pascal) is covered by the same flag but was not measured here. +- Volta's tensor cores take FP16 only: a model's BF16 weights are converted, and a weight outside FP16's range would saturate (none did in + the check above). diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md new file mode 100644 index 0000000..8547983 --- /dev/null +++ b/docs/OLDER_GPUS.md @@ -0,0 +1,111 @@ +# Older GPUs (experimental) + +Strata's supported cards are NVIDIA RTX 20 / 30 / 40 / 50 and the AMD cards in [AMD_HIP.md](AMD_HIP.md). The cards +below run through **opt-in, experimental** paths that community members wrote and measured on their own machines. The +maintainers have none of these cards: each path is compile-checked and unit-tested here, and the ready-made engines +and their output stay exactly as they were. Numbers are the reporters' own, on one machine each. + +## Support matrix + +### NVIDIA + +| Cards | Compute capability | How it runs | What is different on it | Reported | +| --- | --- | --- | --- | --- | +| Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32 | not measured | +| Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there, #395) | P40, IQ3_S, engine 0.1.30: prompt 217-374 tok/s, decode 30-33 tok/s (#395) | +| Tesla V100, Titan V | 7.0 | the CUDA 12 engine | BF16 projections on the FP16 tensor cores (#655, #540); the prompt attention on `mma.m8n8k4` (#600); a leaner attention kernel (#540) | V100-PCIE-32GB, UD-IQ4_XS: prompt 1,123-1,251 tok/s (#600); V100 32GB, IQ2_XS: prompt +22% from #540 | +| RTX 20 (Turing) | 7.5 | **supported**, the ready-made engine | opt-in: `STRATA_BF16_TC=1` runs the BF16 projections on the FP16 tensor cores | RTX 2080 Ti, Q2_0: prompt +15-18% (#655) | + +A card needs enough VRAM to be useful: 12 GB or more is recommended, as for every card (a 2 GB GT 1030 is compute +capability 6.1 too, and cannot hold any of the model). + +### AMD + +| Cards | Architecture | How it runs | Reported | +| --- | --- | --- | --- | +| RX 6800 / 6900 series | gfx1030 | setup (`--backend hip`), unvalidated | [AMD_HIP.md](AMD_HIP.md#rdna2-gfx1030) | +| RX 6700 XT | gfx1031 | setup (`--backend hip`), unvalidated (#524) | used daily by its reporter, one card | +| RX 5500 XT (RDNA1) | gfx1012 | built by hand: `-DCMAKE_HIP_ARCHITECTURES=gfx1012` (HIP 5.7 or 7) | 8 GB card, IQ3_S, 8K prompt: 15.3 tok/s decode (#442) | +| Instinct MI50 / MI60, Radeon VII | gfx906 (wave64) | built by hand: `-DSTRATA_HIP_GFX906=ON` | 2x MI50, Coder IQ1_M, 128K context: decode 50.1 / 47.8 / 45.7 tok/s at 4K / 32K / 128K prompt tokens, prompt ~520 tok/s (#677) | + +## NVIDIA: the CUDA 12 engine + +CUDA 13 dropped Pascal and Volta: it cannot compile for them. Setup therefore keeps a **second engine**, built with +CUDA 12.9 and `-DSTRATA_EXPERIMENTAL_SM60=ON`, in its own folder (`engine-cuda12\`, beside `engine\`). One engine runs +per model, so the choice is made per model, by the oldest card that model runs on: + +- **Every card the model uses is RTX 20 or newer:** the ready-made CUDA 13 engine, as always. +- **A card is Pascal or Volta:** the CUDA 12 engine. Setup says so (`CUDA 12: sm_70 is older than CUDA 13 supports + ...`). On Windows it downloads `strata-windows-x64-cuda12.zip` with NVIDIA's CUDA 12 libraries (from pip, like the + CUDA 13 ones); on Linux, or with `--build`, it compiles the engine with a CUDA 12.x toolkit. + +### Opting in + +An older card is used only when you choose it; a PC with a newer card keeps recommending the newer one. + +| You | Setup | +| --- | --- | +| have only Pascal / Volta NVIDIA cards (and no AMD card it can use) | uses them, with the CUDA 12 engine | +| name the card: `START-HERE.bat --setup --gpu 1`, or `--gpus 0,1` with a newer card | uses it; the model gets the CUDA 12 engine | +| `--cuda 12` (or `STRATA_CUDA=12`) | the CUDA 12 engine for this model, on any card | +| `--cuda 13` | the CUDA 13 engine even with an older card (a warning: it has no code for that card) | +| `STRATA_EXPERIMENTAL_SM60=1` | the older cards are listed as usable (the setting from #295 still works) | + +The choice is kept in the model's config (`"cuda": 12`): its starts and `UPDATE.bat` keep it, and other models keep +their own engine. Setting the model up again chooses again (by its cards; add `--cuda 12` to keep a forced choice). A Pascal / Volta card added to a model at a start (`--gpus`) moves that model to the +CUDA 12 engine. + +`--cuda 12` is also the way to run Strata with an NVIDIA driver older than 580: CUDA 12 needs 528 or newer on Windows +(527.41, NVIDIA's minor-version compatibility) and 525 on Linux; setup's "driver too old" stop says so. Such old +drivers were not tested here. + +### Mixed cards + +A model that shares a V100 with an RTX 30 / 40 card runs both on the CUDA 12 engine (it has code for sm_60 to sm_89, +plus PTX). An RTX 50 card (sm_120) in a CUDA 12 engine is a warning, not a stop: CUDA 12.8 and newer compile for it, +but engines built with 12.8 crashed on long prompts there (#220, #224). Keep the RTX 50 card on its own model (`--gpu +N`), where it runs the CUDA 13 engine. + +### Building it yourself + +```sh +# Linux (Windows: the same with the toolkit's nvcc.exe) +cmake -S . -B build-cuda12 -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF -DSTRATA_EXPERIMENTAL_SM60=ON \ + -DCMAKE_CUDA_ARCHITECTURES="61;70" -DCMAKE_CUDA_COMPILER=/usr/local/cuda-12.9/bin/nvcc +cmake --build build-cuda12 --target strata -j +``` + +Setup does the same when it compiles: it looks for the newest CUDA 12.x toolkit (`STRATA_NVCC=` picks +one, #601; on glibc 2.43 use 12.8, see [TROUBLESHOOTING.md](TROUBLESHOOTING.md)). + +### What the flag changes, and what it does not + +`-DSTRATA_EXPERIMENTAL_SM60=ON` lowers the runtime floor to compute capability 6.0 and compiles the older cards' code +paths into that build only: the Volta prompt attention (#600), #540's attention kernel (used below sm_75), and the +Pascal BF16 path. The ready-made CUDA 13 engine has none of them, so its kernels and its output are unchanged. The +FP16 path for BF16 projections is in every build but runs by default only below sm_75; RTX 20 owners can try it with +`STRATA_BF16_TC=1` (`=0` turns it off on a V100). It is not bitwise the same as cuBLAS's BF16 kernel (FP16 tensor-core +sums round differently): #540 measured a mean KL of 8.4e-3 on the next-token distribution of 24 code prompts on a V100 +(the same top-1 in 23), the size of other summation-order changes; #655 a worst relative difference of 3.5e-5 per +product on an RTX 2080 Ti. + +A/B switches: `STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0` +(#540's kernel off). [NVIDIA_V100.md](NVIDIA_V100.md) has the V100 build, its measurements and the parity test. + +## AMD: building gfx906 and gfx1012 + +Setup does not build these; build by hand and run `serve/server.py` with a config, as on any other card. + +- **gfx906** (MI50 / MI60 / Radeon VII, wave64): a separate opt-in build, `-DSTRATA_HIP_GFX906=ON + -DCMAKE_HIP_ARCHITECTURES=gfx906` (not `STRATA_ENABLE_HIP`). Current ROCm no longer ships gfx906 libraries; the + reporter used a community ROCm 7.14 image. Recipe, kernels and measurements: [AMD_HIP.md](AMD_HIP.md#gfx906-instinct-mi50--mi60-radeon-vii-wave64-built-from-source). +- **gfx1012** (RX 5500 XT): the wave32 backend, `-DSTRATA_ENABLE_HIP=ON -DCMAKE_HIP_ARCHITECTURES=gfx1012`. HIP 5.7 + (Ubuntu's packages) works: older hipBLAS (0.x) is used through rocBLAS, the legacy HIP names and the missing + `__syncwarp` are version-gated, and RDNA1's missing signed dot4 uses llama.cpp's SDWA sequence + (`-DSTRATA_GFX1012_PORTABLE_DOT=ON`: the portable one). + +## Reports welcome + +These paths stay experimental until more people run them. A report with the card, the driver / ROCm version, the +model and the engine log (`strata-.log`) in an issue helps; [COMMUNITY_BENCHMARKS.md](COMMUNITY_BENCHMARKS.md) +has the format for measurements. diff --git a/docs/ORCA.md b/docs/ORCA.md new file mode 100644 index 0000000..5d0cfb6 --- /dev/null +++ b/docs/ORCA.md @@ -0,0 +1,95 @@ +# OrcaRouter IQ3_XXS compatibility + +Validated on Linux with an RTX 5090 (32 GB), Ryzen 9 9950X3D and 128 GB RAM on 2026-09-27. + +The target is `orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF`, **IQ3_XXS** (two shards, 85.20 GB total). +It has Strata's Qwen4Exp geometry, but ordinary quantization also compresses the hyperconnection, +small attention and PLE projections which Strata's kernels read as BF16. + +`tools/iq_pack.py --compat-bf16` expands only those projections, rounding to BF16 using nearest-even. +This adds rounding relative to the GGUF's dequantized weights; it does not recover the original BF16 +checkpoint or its quality. Expert weights, native attention weights, embeddings and the 28.8 GB PLE +lookup table remain unchanged. The latter stays on disk. The pack records its conversions in +`compat-bf16.json`. + +The native loader retains this pack's converted PLE key. Its existing native Q2_0 key path remains +available to the original model. Hugging Face snapshot symlinks are supported; all split shards must +finish downloading before packing. Pass the snapshot filename, not its hash-named blob target. + +## Preparation + +Build Strata normally using the pinned llama.cpp dependency. Python needs numpy, regex and gguf-py +from that dependency (`STRATA_GGUF_PY` can point to its `gguf-py` directory). + +```sh +.venv/bin/python tools/iq_pack.py \ + --gguf /path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf \ + --out packs/orca-iq3_xxs --compat-bf16 +``` + +Use this model's own tokenizer exported into the pack. Do not share another model's `dense.bin`, +and do not rename the Orca files to impersonate one of setup's GSQ-RCO models. + +Strata's persistent server also requires the MTP runtime, prepared by the existing tools: + +```sh +.venv/bin/python tools/mtp_fetch.py fetch --out mtp +.venv/bin/python tools/mtp_pack.py --src mtp --experts q2_0 --out mtp/mtp-q2_0.gguf +.venv/bin/python tools/mtp_rt.py --gguf mtp/mtp-q2_0.gguf --out mtp/rt +cp data/draft_vocab.bin mtp/rt/draft_vocab.bin +``` + +This uses the original model's draft head, as setup does for Swift. The target model verifies its +proposals; draft acceptance and performance must be measured for this fine-tune. + +## Local server + +Save the following as `strata-orca-iq3_xxs.json` at the repository root, replacing both `/path/to/` +entries with the **same first shard**. Orca's PLE table is in shard 1. Start with a 32K context and +512-token prefill chunks; the expert cache sizes itself to available VRAM. The expert arena alone +needs about 49.8 GiB of available system RAM, plus draft/runtime buffers and other applications. + +```json +{ + "exe": "build/strata", + "args": [ + "--pack", "packs/orca-iq3_xxs", + "--native", "/path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", "/path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf", + "--expert-profile", "data/expert-profile.bin", "--expert-cache", "auto", + "--prefill", "512", "--spec", "4", "--spec-min-p", "0.5", + "--mtp", "mtp/rt", "--max-context", "32768", "--kv", "int8" + ], + "cwd": ".", + "tokenizer": "packs/orca-iq3_xxs/tokenizer", + "model_name": "orcarouter-qwen3.8-flash-next-uncensored-iq3_xxs", + "log": "strata-orca-iq3_xxs.log", + "host": "127.0.0.1", + "port": 8080 +} +``` + +Run from the repository root: + +```sh +.venv/bin/python -m serve.server --engine strata --config strata-orca-iq3_xxs.json --port 8080 +``` + +The web interface is at `http://127.0.0.1:8080`; API clients use `http://127.0.0.1:8080/v1`. +Vision is not configured in this text-only example. Performance of the original GSQ-RCO model +does not establish this fine-tune's speed or accuracy. + +## Scope and validation + +- IQ3_XXS is the target of this change; other Orca quantizations are not validated. +- IQ3_M additionally uses Q5_0 expert down matrices, which the native GPU expert path does not support. +- The installer model menu is unchanged. This is an explicit local packing workflow. +- Focused conversion and split-file tests: `.venv/bin/python -m unittest discover -s tools -p test_iq_pack.py`. +- All eight packing tests, 17 server tests and the GPU gated-residual parity check passed. +- The complete model packed successfully: 460 tensors converted, 1.39 GiB of converted BF16 weights; + 1.43 GiB total packed dense weights. The 48 expert layers remain IQ3_XXS gate/up and IQ4_NL down. +- Real server checks passed: arithmetic, Python code, translation, a longer explanation, multi-turn context + reuse (25 prompt tokens reused), streaming cancellation and a subsequent correct response. The engine + PID stayed unchanged. These are smoke tests, not a quality benchmark or a full-context stress test. +- With the configuration above, a 111-token explanation generated at 77.7 tokens/s (engine decode timing); + total request time was 1.77 seconds. This single short measurement is not a general throughput claim. diff --git a/docs/ORCA_Q4_K_S.md b/docs/ORCA_Q4_K_S.md new file mode 100644 index 0000000..25815ff --- /dev/null +++ b/docs/ORCA_Q4_K_S.md @@ -0,0 +1,36 @@ +# OrcaRouter Uncensored Q4_K_S (manual setup) + +This path uses the three original `orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF` Q4_K_S shards without rewriting their expert, embedding or PLE table bytes. It is separate from the installer model menu. Keep all three shard filenames together. + +The ordinary GGUF quantizes some small projections which Strata reads as BF16. `--compat-bf16` dequantizes and rounds those projections to BF16 in the separate pack; it does not restore their original precision. The Q5_0 PLE table remains in the source GGUF and currently uses the mapped reader (`--ple-io mmap`). The Q4_K gate/up experts and Q5_0/Q5_1 down experts remain in GGUF form, including layers whose three tensors cross shard boundaries (each role is read from its own shard). The GPU expert kernels take Q4_K with Q5_1 (or Q8_0) downs; Q5_0 downs are not among them yet, and the engine refuses to start on a pack with such a layer (it names the layer). + +## Build and prepare + +Build Strata with CUDA, native experts, `STRATA_ORCA_Q4KS_MMQ=ON` (and `STRATA_BUILD_TESTS=ON` for the two parity programs below). This opt-in compiles the Q5_0 GGML MMQ instance for CUDA or HIP (the Q4_K and Q5_1 instances come with the engine's K-quant MMQ build on CUDA); the usual Q8_0 draft-layer instance remains in both builds. HIP also needs `STRATA_PREFILL_MMQ=ON`. Select your card's compute capability, for example `89` on an L40S. On Windows with Ninja and CUDA 12.6, use the Visual Studio developer environment and `-DCMAKE_CUDA_RUNTIME_LIBRARY=Shared` to keep the CUDA runtime linkage consistent. The default pinned ggml checkout is supported by the project build. + +```sh +cmake -S . -B build -G Ninja -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_ORCA_Q4KS_MMQ=ON -DCMAKE_CUDA_ARCHITECTURES=89 -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared -DCMAKE_BUILD_TYPE=Release +cmake --build build --target strata native_expert_parity ple_q5_parity +python tools/iq_pack.py --gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --out packs/orca-q4_k_s --compat-bf16 +``` + +`iq_pack.py` needs NumPy and the `gguf-py` module from the pinned llama.cpp dependency (`STRATA_GGUF_PY` can point to that directory). It writes a roughly 1.43 GiB dense pack and a native-expert manifest. The original 112 GB of model shards are read in place; `experts.bin` is optional and is not written by this command. + +Check the changed kernels against the real files before starting the service: + +```sh +build/native_expert_parity /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00002-of-00003.gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00003-of-00003.gguf 0 5 6 20 47 +build/ple_q5_parity /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf +``` + +## Engine flags + +Pass the same first shard to `--native` and `--ple-gguf`; Strata discovers the other two shards by name. For a first text-only run, use 32K context and a modest cache. Once that passes, increase the context and cache with memory measurements on the target machine. + +```sh +--pack packs/orca-q4_k_s --native /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --ple-gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --ple-io mmap --expert-profile data/expert-profile.bin --expert-cache auto --prefill 512 --spec 4 --mtp /path/to/mtp/rt --max-context 32768 --kv int8 +``` + +For two GPUs in persistent server mode, add `--layer-split auto --split-device 1` (with CUDA0 and CUDA1 visible). The usual Strata MTP runtime is built from the original model's draft layer; draft acceptance on the Uncensored fine-tune must be measured. Keep this model's own tokenizer from the pack. Do not combine `--expert-cache-per-layer` with a variable-size native cache: that policy's slot ordering is independent of the pack's per-layer blob sizes. + +This port does not claim that Q4_K_S beats llama.cpp on a given computer. Compare the same model bytes, prompt, context, output length and GPU load; report prefill and decode separately. diff --git a/docs/SECOND_GPU.md b/docs/SECOND_GPU.md new file mode 100644 index 0000000..8dd82b2 --- /dev/null +++ b/docs/SECOND_GPU.md @@ -0,0 +1,162 @@ +# CUDA1–3 expert experiment + +CUDA0 keeps the dense layers, KV/state, MTP and its existing expert cache. Up to +three independent expert caches fill CUDA1, CUDA2 and CUDA3 in that order. Each +expert has one owner: CUDA0, one secondary GPU, or the CPU pool. Each secondary +GPU computes its rows while the CPU pool works; the results return through +private pinned host buffers before CUDA0 continues the layer. The GPU launches +can overlap, but each layer waits for all three. + +The shipped profile ranks 8,000 `(layer, expert)` pairs. CUDA0 takes its usual +`--expert-cache auto` allocation. With only CUDA1, it takes the first remaining +pairs. When CUDA2 or CUDA3 is enabled, the remaining profiled pairs are assigned +round robin to the secondary GPUs. The ranked list is then extended with all +other pairs in expert-then-layer order and distributed in the same way. This +fills the additional VRAM and lets all secondary GPUs see frequent experts, but +unranked experts may hardly ever be routed. The startup +log reports slots and GiB per card; each request reports the number of expert +entries actually computed on each secondary GPU. Remote outputs are packed +before returning over PCIe/USB4: the request log compares MiB transferred +with the previous full-row transfer. The input and routing metadata use pinned +host staging. This reduces transfer traffic and launch overhead, but does not +release the expert arena in system RAM or significantly change VRAM use. + +The optional `--gpu-placement layer` gives each layer to exactly one secondary +GPU (layer number modulo the number of enabled cards). It fills that card with +the most frequently routed experts of its layers first, then the unranked ones. +This can reduce USB4 device switches and synchronization when several secondary +cards serve the same layer in the default `stripe` mode. All three cards still +keep their requested expert slots; the primary CUDA0 cache and CPU fallback +continue to work. The log counts active layer launches on each card, so the +tradeoff can be measured alongside tokens per second. This placement is +experimental and may be slower if a given layer needs more than one card's +compute capacity. + +The experiment requires the corresponding visible CUDA devices and a CUDA +enabled build. Each card must keep at least 512 MiB free. Tiers must be enabled +in order. Under WDDM (Windows, WSL2), CUDA registration of the host expert arena is capped at +8 GiB to leave room for the contexts and MTP on CUDA0 (`STRATA_ARENA_PIN_GIB` overrides it; on Linux the whole +arena is registered). The rest remains +available to the CPU pool; the PCIe expert path is available only for the +registered layers. Without secondary GPUs, the original uncapped registration +behavior applies. + +On an existing Linux installation, apply the patch to its source tree, then run: + +```sh +./setup.sh --setup --gpu1-experts 5000 --gpu2-experts 5000 --gpu3-experts 5000 +``` + +On Windows, from PowerShell in the installation folder: + +```powershell +.\START-HERE.bat --setup --gpu1-experts 5000 --gpu2-experts 5000 --gpu3-experts 5000 +``` + +To test the layer placement instead, add `--gpu-placement layer` to the setup +command. To go back, run the same command with `--gpu-placement stripe`. After +the new engine is built, the mode can also be changed without a rebuild: edit +`--expert-cache-remote-placement` in `strata-iq3_xxs.json` from `layer` to +`stripe` or vice versa and restart the server. If the argument is absent, the +default is `stripe`. + +Choose the same model, size, context and image settings as your current +installation when prompted. Setup recompiles the engine, updates its server +configuration, and starts it. Later starts keep those settings. To tune the +slots without recompiling, edit the values after `--expert-cache-device1`, +`--expert-cache-device2` and `--expert-cache-device3` in the stored +`strata-iq3_xxs.json`, then restart with `.\run-iq3_xxs.bat`. + +Compare identical requests at one, two and four GPUs, preferably with several +repeats. VRAM use alone does not show useful offload: compare the per-request +CUDA1–3 counts and tokens per second. More GPU contexts and synchronization +may lower the speed. Prompt prefill still uses CUDA0; secondary GPUs serve +decode, including MTP verification. No peer-to-peer access is required. + +Longer contexts reserve more KV/state memory on CUDA0, which reduces its +automatic expert cache. On a 64 GB PC `setup.py` limits IQ3_XXS to 128K even +if 262K was selected; the secondary caches still require the host expert arena. +To try 262K on 64 GB, choose Q2_0 or IQ2_XS instead and check that CUDA0 still +has enough free VRAM after loading. Benchmark long prompts separately from +short decode requests. + +The existing warning about the CUDA0 expert-cache GPU hit path still applies: +its outputs diverge from cache-off runs. Treat performance as experimental +until the generated tokens have been validated. + +## Optional helper decode optimization + +`--remote-expert-opt` (`--serve` only) optimizes the CUDA1-3 helper caches +above. The engine's default is off; since 0.1.39b setup adds it to a config on +two or more GPUs (`--gpus`, or "use both" at start). It acts only when a helper +cache is configured; a layer split runs exactly as before. To leave it out: +setup's `--no-remote-expert-opt`, or `"remote_expert_opt": false` in the +model's `strata-*.json` (kept when setup runs again). Measured by the PR's +author: dual RTX 4090 +63% mixed / +132% code decode over the plain helper +path; RTX 5090 + 4090 +28% / +63%. The primary cache avoids admitting experts already held +by a helper, and helpers replace cold experts with frequently routed CPU +misses using their existing same-layer slots. Each helper reduces its expert +outputs to a weighted partial sum on its GPU before returning one vector per +token. Tokens with no CPU expert work skip CPU activation quantization. + +For an existing server configuration with CUDA0 as the primary and CUDA1 as a +helper, use these engine arguments alongside the model and profile arguments: + +```text +--expert-cache auto --expert-cache-device1 auto --remote-expert-opt +``` + +`--expert-cache-device1`, `--expert-cache-device2` and +`--expert-cache-device3` now also accept `auto`: fill each helper from its +assigned ranking using actual aligned expert bytes and free VRAM, retaining +the existing 512 MiB allowance. Explicit numeric budgets still work. This is +startup capacity sizing, not throughput balancing; with several helpers a +card's truncated candidate tail is not redistributed to another card. + +The optimization uses the existing host scheduling and pinned-host transport, +not P2P or tensor parallelism. Each layer still waits for its participating +helpers. It changes floating-point summation order, so enabled output is not +claimed to be bitwise identical. Only two-card CUDA operation has been measured; +three/four cards and HIP have not been validated. Without the switch, the +existing decode path remains in use. This does not optimize the separate +`--peer-device` path below or change its existing incompatibility with helper +caches. + +## Peer tier (`--peer-device`) + +`--peer-device N` puts a second adaptive expert cache on CUDA device N. It +takes the ranked pairs CUDA0's cache does not hold, as many as fit. The peer +computes the rows of its own experts, for decode windows and for prompt +chunks; the activations and the results cross NVLink or another P2P path. The +tier adapts while the server runs, like the primary cache. It is an +alternative to the CUDA1-3 caches above, not a third tier beside them. + +- `--peer-device N` (default off): enable the tier on CUDA device N (N >= 1). +- `--peer-reserve-mib M` (default 600): leave M MiB free on the peer card; the + cache takes what remains. The prompt-path buffers need this headroom. +- `--peer-slots N` (default 0): cap the tier at N experts; 0 = as many as fit. +- `--peer-adapt-swaps N` (default -1): swaps per adaptive round on the peer; + -1 uses the primary's `--adapt-swaps`. +- `--peer-prefill-rows N` (default -1): the share of each prompt chunk's rows + the peer computes; -1 is half of chunk x top-k, 0 keeps prompt rows on the + primary. + +`--peer-device` requires `--expert-profile` and an enabled expert cache, and +the device must be visible; it refuses otherwise. It also refuses +`--layer-split` (a different second-GPU mode: use one or the other) and +`--expert-cache-device1..3` (the peer tier already caches experts on that card): + + strata generate: --peer-device cannot be combined with --layer-split (use one or the other) + strata generate: --peer-device cannot be combined with --expert-cache-device1..3 (the peer tier already caches experts there) + +Without `--peer-device` the binary is unchanged; its output is byte-identical +to the release. With `--peer-device` and the same expert set split across the +two cards, the generated tokens are byte-identical to the single-GPU run under +the exactness gate. + +With a peer the prompt path keeps the MMQ path; the fused int8 prompt path is +not yet combined with the peer's rows. Mapped host buffers gain +`cudaHostAllocPortable` only with a peer, since only then does a second +context write them. The tier size is manual for now (`--peer-reserve-mib`, +`--peer-slots`); automatic sizing on small cards wants the buffer lending of +#216 and is a follow-up. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md new file mode 100644 index 0000000..7287409 --- /dev/null +++ b/docs/TROUBLESHOOTING.md @@ -0,0 +1,78 @@ +# Something went wrong? + +The common problems and what to do. Back to the [README](../README.md#something-went-wrong). The full table of +error messages, with the older engine fixes, is in the [details](DETAILS.md#troubleshooting). + +## While installing or starting + +**My PC froze, or got very slow, the first time Strata started.** +That's normal while it starts, most of all the first time. Strata loads 35-55 GB into your RAM, locks part of it for +the graphics card, and works out how much of the model fits on your GPU. The mouse can freeze for a few minutes. +**Wait, and don't close the window.** The next starts are much faster. Still frozen after 10 minutes? Restart the +PC, close other programs (browsers use a lot of RAM) and try again. If it keeps happening, pick a smaller size (Q2_0 +or IQ2_XS). + +**It stopped while downloading or installing.** +Run `START-HERE.bat` (Linux: `./setup.sh`) again. It continues where it stopped. + +**It says the NVIDIA driver is too old.** +Update it (NVIDIA App or [nvidia.com/drivers](https://www.nvidia.com/drivers)), restart the PC, and run +`START-HERE.bat` again. + +**It says 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`. + +**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. + +**Linux: the engine does not compile (`unsupported GNU version`, or `exception specification is incompatible` for +`cospi`/`sinpi`/`rsqrt`).** Two known mismatches between the CUDA toolkit and a new Linux (#601): +- gcc newer than 14 (Ubuntu 26.04's default 15): CUDA 12.x and 13.0 refuse it. Install g++-14 and run + `CXX=g++-14 CUDAHOSTCXX=g++-14 ./setup.sh`. +- glibc 2.43 with CUDA 12.9: the toolkit's math headers clash with glibc's, already in CMake's first test compile. + Use CUDA 12.8 or 13.x instead. Setup takes the newest toolkit it finds; `STRATA_NVCC=/usr/local/cuda-12.8/bin/nvcc + ./setup.sh` makes it use that one (only that one). + +**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. Started from Task +Scheduler, it can be 24x slower: see [Running it at startup](DETAILS.md#running-it-at-startup-task-scheduler). + +## While it answers + +**It's very slow and the disk light keeps blinking.** +Your PC is out of free RAM. Close other programs, or pick a smaller size (Q2_0 or IQ2_XS). + +**An answer stopped with "the engine stopped unexpectedly".** +Usually not enough RAM (on Linux the system then stops the engine). Just send your message again: Strata starts the +engine by itself. If it keeps happening, close other programs or pick a smaller size. + +**It says the prompt exceeds the context.** +The conversation is longer than the context you chose. Start a new chat, or run `SETUP.bat` and pick more +context. + +**It is slower than the tables.** +The monitor plugged into the graphics card 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. + +**Pictures are refused, or slow.** +"this server was started without the vision encoder": the model was set up for text only - run setup again with +`--vision gpu` (or `--vision cpu`). Pictures that take 10-30 s are read by the encoder on the CPU; `--vision gpu` +(NVIDIA, ~1.4 GB of VRAM) makes it 0.1-0.5 s. + +## AMD cards + +**"No AMD GPU found (the amdgpu driver's KFD topology is empty)" on Linux.** +The kernel's amdgpu driver is not loaded for the card. Integrated Radeon GPUs are listed as not supported; setup +lists every card it found and whether Strata can use it. + +**The engine stops at start with the card's name, its architecture and the build's list.** +The engine was compiled for another card (for example after moving the Strata folder to another PC). Run +`./setup.sh --setup --backend hip`: it compiles the engine for this card's architecture. + +**Large pinned host allocations fail on ROCm although RAM is free.** +See [AMD_HIP.md](AMD_HIP.md#model-and-serving-configuration): the mapped expert mode avoids the full pinned arena. + +## Still stuck? + +Look in the [full troubleshooting table](DETAILS.md#troubleshooting), or open an +[issue](https://github.com/Niko1221/Strata/issues) and attach `strata-.log` from the Strata folder. diff --git a/docs/UNSLOTH_Q4.md b/docs/UNSLOTH_Q4.md new file mode 100644 index 0000000..e275dec --- /dev/null +++ b/docs/UNSLOTH_Q4.md @@ -0,0 +1,270 @@ +# Unsloth UD-Q4_K_XL (experimental) + +**Experimental.** Setup offers it from engine 0.1.32 ([below](#setup)); the manual workflow after that section works +with engine 0.1.31 or newer. Validated on one PC: Windows 10, an RTX 5070 (12 GB), 64 GB of RAM and an AVX-512 CPU, +on 2026-10-01. + +The target is Unsloth's 4-bit quantization of the same model the other packs use: +[unsloth/Qwen3.8-Flash-Next-GGUF, `UD-Q4_K_XL`, revision `38bb39e`](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/tree/38bb39ee97821de2c9009abb7e93950eec396e66/UD-Q4_K_XL). +"UD-Q4_K_XL" is a mix of formats, not Q4_K everywhere: the routed experts are Q4_K (Q5_K in layer 2) for gate/up and +Q5_1 (Q8_0 in layers 2, 4, 30, 46, 47) for down; the token embedding, the output head, the attention and shared-expert +projections and the PLE key are Q8_0; the 28.8 GB PLE table is IQ4_NL. The routed experts are 71.7 GiB, about twice +the 3-bit models'. + +## Setup + +`START-HERE.bat --setup` (Linux: `./setup.sh --setup`) and choose **Qwen3.8-Flash-Next (Unsloth)**, marked +`[experimental]`; or directly: + +```sh +START-HERE.bat --setup --family unsloth --model UD-Q4_K_XL +``` + +What setup does differently for this model: + +- It needs 48 GB of RAM or more (with less it asks, default no; `--model UD-Q4_K_XL --yes` installs it anyway) and + engine 0.1.32 or newer (checked before anything is downloaded), and an NVIDIA + GPU: it has not been run on AMD cards (its prompt kernels for the Q4_K / Q5_K experts are NVIDIA-only), so with + `--backend hip` setup says so and asks before the download (#429; `--model UD-Q4_K_XL --yes` tries it). One GPU + by default: the RAM budget below has no layer split (the engine refuses `--resident-budget-gib` with one). No + images (the vision encoder is not wired to this file yet) and no experimental speed projection (not tested with it). +- Several GPUs (#498): when the RAM holds the GGUF files and 24 GB more (~135 GB of RAM) and two or more cards can + share it, setup asks (one GPU stays the default; `--gpus 0,1` takes the split). The split runs **without** the RAM budget: all 77 GB of experts are loaded into RAM from the GGUFs at + start, the files pass through the OS file cache while they load, and the config gets `"gpu": [0, 1]` and + `"layer_split": "auto"`. Measured on 2x RTX 3090 with 165 GiB (#498): decode 31 tok/s on one card with the budget, + 64-78 tok/s split (55 tok/s at a 128K prompt), with `MemAvailable` never under 68 GiB. With less RAM, `--gpus` + keeps one GPU and says so, and `START-HERE.bat --gpus 0,1` on an installed UD-Q4_K_XL stops with the reason + (it used to keep the budget, and the engine exited with code 2). +- It downloads the four shards below from the pinned revision `38bb39e` (resumable, like the other models), then + checks each one's size and SHA-256 against the table below; the check takes a few minutes once and is remembered + in the file's finish mark. A file with the wrong hash is deleted, so the next run downloads it again. +- It packs with `--compat-bf16` and never writes `experts.bin` (`--low-ram` does not apply). +- The RAM budget is the PC's RAM less 24 GB: `--resident-budget-gib 40` on 64 GB, at most all 71 GiB of experts on + 96 GB or more. From a 64K context up, where the KV cache moves to RAM, its size comes out of the budget. Setup's + `--resident-budget-gib N` sets another one (a bigger one is kept, with a note on what it risks). +- It recommends an 8K context on a GPU under 14 GB (every GB of KV cache is a GB less of cached experts). + +## The files + +Four shards, 111,334,654,784 bytes (111.3 GB) together. Shard 1 holds only the metadata; layer 11's down projection is +in shard 2 and its gate/up in shard 3, which this engine handles (`native_experts.txt` v4). + +| File | Bytes | SHA-256 | +| --- | --- | --- | +| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf` | 10,946,624 | `4448186216b3af4cc558bbce2c3213f01608f8f8b2e5267a9767971dd3ec8082` | +| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf` | 49,859,583,136 | `3f342f1c1580473f1ee94ddd5b28206e8c07a70fa1a366f59d1d6c922919a6c9` | +| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf` | 49,376,141,504 | `56758f40269cad5cd9b0d3d6fbae0f40f6d5be6de49e4ab392dbe83157d9cbd3` | +| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf` | 12,087,983,520 | `753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a` | + +Keep the four files together in one folder under these names (the engine finds shards 2-4 from shard 1's name; a +missing shard is an error that names it). Setup checks them itself; by hand, check them before packing +(`sha256sum -c`, or `Get-FileHash` on Windows). +Hugging Face snapshot symlinks work if you pass the snapshot's file name, not the hash-named blob it points to. + +## What it needs + +| | | +| --- | --- | +| Disk | 111.3 GB for the four files, 1.4 GB for the pack, ~6 GB for the MTP draft layer if you have none yet. **No `experts.bin`**: the engine reads the experts from the GGUF files in place. An NVMe SSD matters: the experts that fit neither VRAM nor the RAM budget are read from it for every token. | +| RAM | 64 GB measured. The RAM budget (below) holds the most-used experts; the rest come from the SSD through the OS file cache. | +| GPU | 12 GB measured (RTX 5070): after the weights, the draft layer and the buffers, the expert cache held 1,280 of the 24,576 experts (3.7 GiB) at 4K context. | + +## The pack (by hand) + +Build Strata (or install 0.1.31+), then, from the repository root, with gguf-py from the pinned llama.cpp +(setup installs it; `STRATA_GGUF_PY` can point to its `gguf-py` folder): + +```sh +.venv/bin/python tools/iq_pack.py \ + --gguf /path/to/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf \ + --out packs/ud-q4_k_xl --compat-bf16 +``` + +About 30 seconds. It writes `index.txt`, `dense.bin` (1.4 GB), `native_experts.txt`, the tokenizer, `conversions.json` +and `compat-bf16.json`. **`--compat-bf16` is required**: this file stores 195 small projections (the hyper-connection +up/down matrices, `output_hc_*` and the PLE value) as Q8_0, while the engine reads them as BF16. Without the flag the +packer refuses and writes nothing; with it, they are dequantized and rounded to BF16 (nearest-even). Do not add +`--experts-bin`: it would write a 77 GB copy of the experts that this mode does not need. + +## The numbers: what is native and what is converted + +The routed experts, the token embedding, the output head, the attention and shared-expert projections, the PLE key and +the PLE table are used as the GGUF stores them (the engine has GPU kernels and CPU (ggml) paths for Q4_K, Q5_K, Q5_1 and +Q8_0). The small tensors the engine reads as floats are converted, and `conversions.json` lists every one with its +source/destination type, method, whether it is exact, the largest absolute error and the source bytes' SHA-256: +264 F32 tensors (routers, injections, SSM gates) whose values are already BF16's are stored as BF16 exactly; the 195 +Q8_0 projections above are rounded to BF16 (largest absolute error 0.0144, in `hc_ffn_up`); the PLE convolution (F32) +is narrowed to F16 when the engine loads it (largest error 3e-8). That is the compatibility Unsloth's file needs; it is +not the original BF16 checkpoint. The output matches llama.cpp's on the same file: +[Quality](#quality-against-llamacpp-on-the-same-file). + +## The MTP draft layer + +The draft layer is the base model's, the same one the other packs use. If setup installed Strata, you have it +(`mtp/rt` in `Strata-data`). Otherwise build it as [docs/ORCA.md](ORCA.md#preparation) shows (`tools/mtp_fetch.py`, +`tools/mtp_pack.py`, `tools/mtp_rt.py`, then copy `data/draft_vocab.bin` to `mtp/rt/`). + +## The server + +Save as `strata-ud-q4_k_xl.json` at the repository root (or next to setup's other `strata-*.json`), with `/path/to/` +pointing at **shard 1**. `--ple-gguf` is not needed: the engine finds the shard that holds the PLE table +(`per_layer_token_embd.weight`, shard 2) by name. `--resident-budget-gib` turns on the mapped mode with a RAM budget +(it implies `--mmap-experts`). + +```json +{ + "exe": "engine/strata.exe", + "args": [ + "--pack", "packs/ud-q4_k_xl", + "--native", "/path/to/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", + "--resident-budget-gib", "40", + "--expert-profile", "data/expert-profile.bin", "--expert-cache", "auto", + "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", + "--mtp", "mtp/rt", "--max-context", "8192" + ], + "cwd": ".", + "tokenizer": "packs/ud-q4_k_xl/tokenizer", + "model_name": "qwen3.8-flash-next-ud-q4_k_xl", + "log": "strata-ud-q4_k_xl.log", + "host": "127.0.0.1", + "port": 8080 +} +``` + +```sh +.venv/bin/python -m serve.server --engine strata --config strata-ud-q4_k_xl.json --port 8080 +``` + +(`engine/strata.exe` is setup's engine on Windows; a self-built one is `build/strata`.) The expert profile is the base +model's (`data/expert-profile.bin`); it ranks the same 48 x 512 experts and decides which ones the GPU cache and the RAM +budget take first. + +**Choosing the RAM budget N:** your RAM minus 20-24 GB (the OS, the engine itself, the 126 MB router copy, and room for +the OS file cache that serves the rest). On 64 GB, 40. The engine clamps a budget larger than the RAM it finds free +(minus 4 GB and a 256 MiB margin) and says so; before #403's fix such a clamped budget could then fail the start. Everything above N comes from the SSD for every token, so N is the setting that matters +most; a bigger budget was faster in every measurement (24 / 32 / 40 GiB). When the driver page-locks the whole budget +(24 GiB did on this PC, 32 and 40 did not), the GPU also computes a share of the misses over PCIe, as in the resident +low-RAM mode; `STRATA_RESIDENT_PIN=0` keeps the budget locked only (the CPU then computes every miss). + +**Context:** measured at 4K. The KV cache takes VRAM from the expert cache, so a longer context makes decoding slower; +8K is a reasonable start on 12 GB. `--kv int8` halves the KV cache's VRAM. + +## What to expect (RTX 5070 12 GB, 64 GB RAM, Windows, one short greedy prompt) + +| RAM budget | Greedy output | Notes | +| --- | --- | --- | +| 24 GiB | 5.1-5.2 tok/s (2 runs, before the routing prefetch below) | 2.2 GB read from the SSD per verify round (~3.5 tokens) | +| 40 GiB | **7-8.5 tok/s** (6 runs: 6.7-8.6, mean 7.9) | 1.1 GB read from the SSD per verify round, ~0.33 GB per token | + +- The first answer comes about 60 s after the engine starts (mostly loading: the RAM budget is copied from the GGUF + files at start). A 30-token prompt then took 5-6 s. +- Long prompts (engine 0.1.32): a 16K prompt is read at **160 tokens/s** (15,873 tokens in 99 s; 0.1.31: 57 tokens/s, + 273-282 s). Reading a prompt streams every expert once per 4K chunk, and the third of them outside the RAM budget + come from the SSD (~35 GB per chunk), so the prompt path now reads them with 32 threads and up to 128 blobs in + flight when the experts are read from the GGUF in place (`STRATA_STAGER_THREADS` / `STRATA_STAGER_RING` override + it; 4 and 16 before, still the default for every other model). Between the chunks, the 28.8 GB PLE table's rows + take ~5 s per chunk. +- An engine compiled with `-DSTRATA_MMQ_KQUANTS=ON` multiplies the Q4_K / Q5_K / Q5_1 experts of a prompt with + llama.cpp's MMQ kernels (as the other models' formats always are) instead of dequantizing them to FP16: 4x less GPU + time for those products, but on this PC the prompt waits for the SSD either way (29 s per 4K chunk with or + without). Off in the released engine: it loads every kernel at start, and these took 1-3 expert slots of VRAM from + every model. +- The speed varies from run to run (6.7-8.6 tok/s at 40 GiB for the same prompt), with what the OS file cache holds. +- For comparison, IQ3_S (all its experts in RAM) writes ~53 tok/s on the same PC ([the speed tables](DETAILS.md#speed-measured)). +- Where the time goes (`--stats` on the command line): at 40 GiB about 550-750 ms of each verify round (3.5 tokens) is + reading experts from the SSD, ~75 ms the CPU's expert kernels, ~13 ms the GPU. + +## Quality: against llama.cpp on the same file + +Strata and llama.cpp (the pinned commit `3cf0325`, a CPU build reading the GGUF memory-mapped) were given the same +token sequences, and at every position each wrote its 20 most likely next tokens with their log-probabilities: Strata +through its verify windows (`STRATA_LOGPOS` with `STRATA_LOGPOS_TOPK=20`), llama.cpp from `llama_get_logits_ith` over +one batch. Strata ran with the recommended settings (RAM budget 40 GiB, the MTP draft layer on, greedy, +`--adapt-every 100000` so the expert cache does not move during the run). Per position: whether the most likely token is the same (argmax +agreement), how many of the 5 / 10 most likely tokens both have, the KL divergence (llama.cpp's distribution against +Strata's, over llama.cpp's top 20 plus one bucket for the rest), and the perplexity of the sequence under each. + +| Token set | Positions | Argmax agreement | Top-5 / top-10 overlap | KL | Perplexity Strata / llama.cpp | +| --- | ---: | ---: | ---: | ---: | ---: | +| Code: Strata's greedy answer to a coding prompt (an LRU cache in Python, 56-token prompt) | 400 | **99.0%** | 95.6% / 95.3% | 0.0008 | 1.067 / 1.070 | +| Thinking: Strata's greedy answer to a reasoning puzzle (with thinking, 55-token prompt) | 324 | **97.5%** | 96.2% / 96.4% | 0.0016 | 1.107 / 1.106 | +| After a 16K prompt: Strata's greedy continuation (256 tokens) of the 16,384 real-text tokens below | 256 | 90.2% | 88.1% / 89.3% | 0.039 | 1.619 / 1.623 | +| Real text after a 16K prompt: the last 510 tokens of 16,384 tokens of this repository's docs and code | 510 | 91.2% | 88.3% / 89.9% | 0.035 | 4.27 / 4.29 | +| The same 511 positions with only 512 tokens before them | 511 | 89.2% | 86.0% / 86.3% | 0.061 | 8.99 / 8.87 | + +For comparison, [eddoursul/Strata](https://github.com/eddoursul/Strata) reported 98.2-99.3% (code), 95.6-95.8% +(thinking) and 97.7% (after a 16K prompt) for the same file against llama.cpp on an RTX 3090. + +**Where they differ:** at near-ties. Grouped by llama.cpp's own gap between its two most likely tokens, Strata picks +the same token at every position of the code and thinking answers where that gap is 0.2 or more (695 of 695) and at +every position after the 16K prompt where it is 0.5 or more (144 of 144 in the continuation, 254 of 254 in the real +text; 50 of 54 and 117 of 121 between 0.2 and 0.5). Text after a long document has many more near-ties than a short +answer (58 of the continuation's 256 positions and 135 of the real text's 510 have a gap under 0.2, against 13 of the +code answer's 400), which is why its agreement is lower. It is not the long context itself: the same real-text +positions after only 512 tokens agree a little less (89.2%), and the perplexities match within 3% in every set. For +scale, Strata's own greedy run and its teacher-forced rerun of the continuation pick different tokens at 6% of the +positions (93.8% the same: other window sizes, other experts in VRAM), the same kind of near-tie flips. The 16K +prompts were read by Strata's batched prompt path (15,872 tokens), the rest through the verify windows. These numbers +are the FP16 prompt path's (the released engine's); with the MMQ prompt path (`-DSTRATA_MMQ_KQUANTS=ON`, above) the +continuation after the 16K prompt agrees at 92.2% (KL 0.029, three runs, identical). + +To repeat it: Strata's side is `STRATA_LOGPOS=` with `STRATA_LOGPOS_TOPK=20` (engine 0.1.32) on a serve +engine with `--short-read` covering the positions to compare; llama.cpp's side was a short program over +`llama_decode` / `llama_get_logits_ith` writing the same top 20 per position. + +## Opt-ins and switches (environment variables) + +| | | +| --- | --- | +| `STRATA_LOOKAHEAD=0` | Turns off the routing-aware prefetch (on by default in this mode): while the CPU works on a layer, a thread applies the next layer's router to this layer's input and asks the OS to read the predicted experts' pages. Pages only, the answers are the same. About half of the SSD reads were predicted; mean +14% (6.9 -> 7.9 tok/s). `STRATA_LOOKAHEAD_K` sets the experts per token (default 10). | +| `STRATA_KQ256=1` | Multi-token AVX2 kernels for the Q4_K / Q5_1 / Q8_0 experts. Bit-exact with ggml's, but measured no faster, so off. | +| `STRATA_PARTIAL_PIN=1` | Registers the hottest part of the RAM budget (up to `STRATA_PARTIAL_PIN_GIB`, default 24) with the GPU driver, so the GPU computes a share of the misses over PCIe (`--pcie-frac`). Measured no faster on this PC, and it changes the numerics of those experts (GPU kernels instead of the CPU's), so off. | +| `STRATA_FETCH_THREADS=N` | Threads that read the experts from the GGUF while it answers (default 8; 16 was no faster). The prompt path has its own: `STRATA_STAGER_THREADS` (default 32 here) and `STRATA_STAGER_RING` (128). | + +## UD-IQ4_XS (setup from 0.1.39, #621) + +Unsloth's `UD-IQ4_XS` at the same revision is in setup too, as a regular choice (not experimental; the Unsloth +family's first size and its default): `START-HERE.bat --setup --family unsloth --model UD-IQ4_XS` (engine 0.1.38 or +newer). It sits between IQ3_S and UD-Q4_K_XL: its routed experts are IQ3_S gate/up (IQ4_XS +in one layer) with IQ4_NL downs (Q8_0 in five layers), 59.5 GB of them; the dense side (Q8_0 projections, the IQ4_NL +PLE table, a Q6_K head) is UD-Q4_K_XL's. Three shards, 93.7 GB: + +| File | Bytes | SHA-256 | +| --- | ---: | --- | +| `Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf` | 10,946,624 | `5ce89370720f8bf90890f439361282104c1aa1482d4013bb9a50923e758e71a4` | +| `Qwen3.8-Flash-Next-UD-IQ4_XS-00002-of-00003.gguf` | 49,835,229,856 | `577a38a2392b40ca2193cea502e1d92f60b8cd370675d308e0ec21885d9daaa7` | +| `Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00003.gguf` | 43,836,407,744 | `d4634e6d84f0ebb0940be15c90d3790bf6464e3dea3a1cddc567dc0e83ad8833` | + +Setup treats it like UD-Q4_K_XL (the list above): the same RAM budget (your RAM less 24 GB; at most all 55 GiB of its +experts, so a PC with ~80 GB of RAM or more holds all of them), the pack with `--compat-bf16`, no `experts.bin`, one +GPU by default. It does not ask on AMD: its experts' formats have prompt kernels there too. Images are an option (asked, +off by default; NVIDIA): the image path has no restriction for this pack, which uses the original model's image +encoder; not yet run with images. + +What is known so far: it packs and runs on a Strix Halo (AMD gfx1151, 128 GB unified memory), where prompts read at +~820 tokens/s at 8K and 64K and the answers passed the retrieval checks at 8K and 64K. It has **not** been measured on +NVIDIA yet; please report what you see. One fidelity note that applies to every `--compat-bf16` pack (UD-Q4_K_XL too): +the pack rounds the file's Q8_0 hyper-connection projections to BF16, and on the Strix Halo that rounding put +perplexity 6-9% above llama.cpp's on the same file (teacher-forced, short context). Reading the Q8_0 values instead +closes most of that gap; it is measured on AMD only and not in this release. + +## Scope and validation + +- UD-Q4_K_XL and UD-IQ4_XS at revision `38bb39e` are targeted. Other Unsloth quantizations use formats this engine may + not have kernels for; the engine checks every layer's formats at start and refuses an unsupported one by name. +- Tests: the packer's synthetic 4-shard and conversion tests (`.venv/bin/python -m unittest discover -s tools -p + test_iq_pack.py`); CTests `gguf_split_test`, `expert_layout_test`, `native_expert_parity_*` (the three real expert + format pairs against ggml-cpu, the Q5_1 min term, Q8_0 rows), `prefill_mmq_kquant_test` (with `-DSTRATA_MMQ_KQUANTS=ON`: the + prompt path's MMQ products for Q4_K / Q5_K / Q5_1 / Q8_0 against ggml's dequantized weights); the in-place mode against `experts.bin` on the Coder + (identical tokens and logits). +- Real runs: greedy answers to a coding prompt (correct) at every budget and setting above, identical across them; + the same tokens as llama.cpp at 97.5-99% of the positions of short greedy answers and 90-91% after a 16K prompt, + differing mostly at near-ties (above). Not yet: sampled decoding, long conversations. Please report what you see. + +## Credits + +The split-artifact loader, the expert formats' GPU kernels and the packing of Unsloth's files follow +[eddoursul/Strata](https://github.com/eddoursul/Strata) (PR #245), which ran these files first. The Q8_0 kernels, the +per-role shard column and the PLE convolution's F32 -> F16 fix come from @gopinath87607's PR #255; per-role shard names +were also proposed by @jagsan-cyber in PR #247. The quantization is [Unsloth](https://huggingface.co/unsloth)'s; the +model is Qwen's ([license](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)). diff --git a/docs/benchmarks/2026-09-29-gfx1100.json b/docs/benchmarks/2026-09-29-gfx1100.json new file mode 100644 index 0000000..bf0e5ef --- /dev/null +++ b/docs/benchmarks/2026-09-29-gfx1100.json @@ -0,0 +1,299 @@ +{ + "source_commit": "9568e78da663e6b224ab96d57baf450717b36e73", + "date": "2026-09-29", + "candidate_binary_sha256": "705f5925a788bc227bad72abfb5466032e0879d752fea9afc3eb32051b35182b", + "note": "Fresh same-session control and candidate runs. Throughput cap 128; not a coding-quality benchmark.", + "control": [ + { + "kind": "warmup", + "trial": 0, + "wall_s": 0.45770244899904355, + "metrics": { + "prompt_tokens": 15.0, + "reused": 0.0, + "fresh": 15.0, + "prefill_ms": 335.0, + "prefill_tps": 44.8, + "generated": 2.0, + "decode_ms": 115.0, + "decode_tps": 17.5 + }, + "finish_reason": "stop" + }, + { + "kind": "cold", + "trial": 1, + "wall_s": 20.068275763012934, + "metrics": { + "prompt_tokens": 4210.0, + "reused": 0.0, + "fresh": 4210.0, + "prefill_ms": 17538.0, + "prefill_tps": 240.0, + "generated": 128.0, + "decode_ms": 2518.0, + "decode_tps": 50.8 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 1, + "wall_s": 4.412000925018219, + "metrics": { + "prompt_tokens": 4451.0, + "reused": 4337.0, + "fresh": 114.0, + "prefill_ms": 1943.0, + "prefill_tps": 58.7, + "generated": 128.0, + "decode_ms": 2451.0, + "decode_tps": 52.2 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 2, + "wall_s": 20.731399575975956, + "metrics": { + "prompt_tokens": 8830.0, + "reused": 0.0, + "fresh": 8830.0, + "prefill_ms": 18213.0, + "prefill_tps": 484.8, + "generated": 128.0, + "decode_ms": 2505.0, + "decode_tps": 51.1 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 2, + "wall_s": 5.0592734439997, + "metrics": { + "prompt_tokens": 9071.0, + "reused": 8823.0, + "fresh": 248.0, + "prefill_ms": 2601.0, + "prefill_tps": 95.4, + "generated": 128.0, + "decode_ms": 2441.0, + "decode_tps": 52.4 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 3, + "wall_s": 11.695648370019626, + "metrics": { + "prompt_tokens": 4210.0, + "reused": 0.0, + "fresh": 4210.0, + "prefill_ms": 9209.0, + "prefill_tps": 457.2, + "generated": 128.0, + "decode_ms": 2477.0, + "decode_tps": 51.7 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 3, + "wall_s": 4.093982424004935, + "metrics": { + "prompt_tokens": 4451.0, + "reused": 4337.0, + "fresh": 114.0, + "prefill_ms": 1896.0, + "prefill_tps": 60.1, + "generated": 128.0, + "decode_ms": 2188.0, + "decode_tps": 58.5 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 4, + "wall_s": 20.84539221401792, + "metrics": { + "prompt_tokens": 8830.0, + "reused": 0.0, + "fresh": 8830.0, + "prefill_ms": 18437.0, + "prefill_tps": 478.9, + "generated": 128.0, + "decode_ms": 2392.0, + "decode_tps": 53.5 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 4, + "wall_s": 5.357054464984685, + "metrics": { + "prompt_tokens": 9071.0, + "reused": 8823.0, + "fresh": 248.0, + "prefill_ms": 2658.0, + "prefill_tps": 93.3, + "generated": 128.0, + "decode_ms": 2682.0, + "decode_tps": 47.7 + }, + "finish_reason": "length" + } + ], + "optimized": [ + { + "kind": "warmup", + "trial": 0, + "wall_s": 0.46265592801501043, + "metrics": { + "prompt_tokens": 15.0, + "reused": 0.0, + "fresh": 15.0, + "prefill_ms": 335.0, + "prefill_tps": 44.8, + "generated": 2.0, + "decode_ms": 121.0, + "decode_tps": 16.5 + }, + "finish_reason": "stop" + }, + { + "kind": "cold", + "trial": 1, + "wall_s": 11.728894605010282, + "metrics": { + "prompt_tokens": 4210.0, + "reused": 0.0, + "fresh": 4210.0, + "prefill_ms": 9408.0, + "prefill_tps": 447.5, + "generated": 128.0, + "decode_ms": 2308.0, + "decode_tps": 55.5 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 1, + "wall_s": 2.9531024169991724, + "metrics": { + "prompt_tokens": 4451.0, + "reused": 4337.0, + "fresh": 114.0, + "prefill_ms": 740.0, + "prefill_tps": 154.0, + "generated": 128.0, + "decode_ms": 2193.0, + "decode_tps": 58.4 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 2, + "wall_s": 12.42044531099964, + "metrics": { + "prompt_tokens": 8830.0, + "reused": 0.0, + "fresh": 8830.0, + "prefill_ms": 10107.0, + "prefill_tps": 873.7, + "generated": 128.0, + "decode_ms": 2298.0, + "decode_tps": 55.7 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 2, + "wall_s": 3.2599652509961743, + "metrics": { + "prompt_tokens": 9071.0, + "reused": 8823.0, + "fresh": 248.0, + "prefill_ms": 1070.0, + "prefill_tps": 231.7, + "generated": 128.0, + "decode_ms": 2173.0, + "decode_tps": 58.9 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 3, + "wall_s": 6.937167472002329, + "metrics": { + "prompt_tokens": 4210.0, + "reused": 0.0, + "fresh": 4210.0, + "prefill_ms": 4672.0, + "prefill_tps": 901.1, + "generated": 128.0, + "decode_ms": 2256.0, + "decode_tps": 56.7 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 3, + "wall_s": 3.1877827199932653, + "metrics": { + "prompt_tokens": 4451.0, + "reused": 4337.0, + "fresh": 114.0, + "prefill_ms": 827.0, + "prefill_tps": 137.8, + "generated": 128.0, + "decode_ms": 2350.0, + "decode_tps": 54.5 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 4, + "wall_s": 11.314008287008619, + "metrics": { + "prompt_tokens": 8830.0, + "reused": 0.0, + "fresh": 8830.0, + "prefill_ms": 9136.0, + "prefill_tps": 966.5, + "generated": 128.0, + "decode_ms": 2161.0, + "decode_tps": 59.2 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 4, + "wall_s": 3.0476601750124246, + "metrics": { + "prompt_tokens": 9071.0, + "reused": 8957.0, + "fresh": 114.0, + "prefill_ms": 734.0, + "prefill_tps": 155.3, + "generated": 128.0, + "decode_ms": 2296.0, + "decode_tps": 55.7 + }, + "finish_reason": "length" + } + ], + "control_binary_sha256": "4522d4937ca4a41ca294d31b60df8c2bc4df5b7a6caf65eaad10c036e08491f7" +} diff --git a/docs/media/guess-and-check.svg b/docs/media/guess-and-check.svg new file mode 100644 index 0000000..f1ff030 --- /dev/null +++ b/docs/media/guess-and-check.svg @@ -0,0 +1,23 @@ +Speculative decoding: a small helper guesses words, the big model checks them at onceGuess, then check - many words per stepA small, fast helper inside the model guesses the next words. The big model checks all the guesses in one goand keeps the ones it agrees with. The big model decides every word - it just arrives 1.6-1.8x sooner.Helper guessesBig model checksdefreverse(items):defreverse(items):, key):4 words in one step3 guesses kept + its own word \ No newline at end of file diff --git a/docs/media/how-it-works.svg b/docs/media/how-it-works.svg new file mode 100644 index 0000000..cab167b --- /dev/null +++ b/docs/media/how-it-works.svg @@ -0,0 +1,23 @@ +How Strata splits the model between your graphics card, RAM and SSDThe model is made of 24,576 small specialists - “experts”.For each word it writes, it asks only 10 of them. Strata keeps the busy oneson your graphics card and the rest in RAM - so it runs on a normal PC.10 at work for one wordGraphics cardSmall but very fast: 12-24 GBRuns the core of the modelfor every word, and keeps the~4,000 experts used mostthe most-used expertsRAM + processorBig: 32-64 GB of memoryHolds all 24,576 experts. When aword needs one the card doesn'thave, the CPU does it - at onceall 24,576 expertsSSDHolds a 29 GB lookup tableThe model looks up a fewsmall rows of it per word -no need to keep it in RAMa few rows per word \ No newline at end of file diff --git a/docs/media/make_figures.py b/docs/media/make_figures.py new file mode 100644 index 0000000..0af0a0e --- /dev/null +++ b/docs/media/make_figures.py @@ -0,0 +1,178 @@ +"""docs/media/make_figures.py - the README's "How does it work?" illustrations, in the Strata app's style: its colors +(serve/web/tokens.css), its icons (serve/web/sprite.svg) and its font (Outfit, embedded, SIL OFL 1.1). Light and dark +follow the reader's system setting. + + python docs/media/make_figures.py # writes docs/media/how-it-works.svg and docs/media/guess-and-check.svg +""" +import base64 +import random +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +OUT = ROOT / "docs" / "media" +SPRITE = (ROOT / "serve" / "web" / "sprite.svg").read_text(encoding="utf-8") +FONT = base64.b64encode((ROOT / "serve" / "web" / "fonts" / "outfit-latin-wght.woff2").read_bytes()).decode() + +# the app's tokens (light, then dark) +CSS = """ +@font-face{font-family:"Outfit";src:url(data:font/woff2;base64,%s) format("woff2");font-weight:100 900} +text{font-family:"Outfit",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;fill:#221e1f} +.bg{fill:#f9fafb}.card{fill:#ffffff;stroke:#dee5ee;stroke-width:1}.soft{fill:#f7f7f7} +.muted{fill:#6f6f6f}.ink{fill:#221e1f}.icon{color:#2F384C} +.acc{fill:#10b981}.acc-t{fill:#0c8a60}.acc-tint{fill:#ecfdf5}.acc-line{stroke:#10b981} +.info{fill:#0f97ff}.info-t{fill:#0668c2}.info-tint{fill:#e8f4ff} +.warn{fill:#e39b0b}.warn-t{fill:#8a5a00}.warn-tint{fill:#fff6e0} +.dan{fill:#e0283f}.dan-tint{fill:#fdecee}.dan-t{fill:#b01a2e} +.dot{fill:#dee5ee}.line{stroke:#dee5ee}.arrow{stroke:#6f6f6f;fill:none}.arrowhead{fill:#6f6f6f} +.dash{stroke:#6f6f6f;fill:none;stroke-dasharray:4 4} +.on-acc{fill:#ffffff}.icon-acc{color:#0c8a60}.icon-dan{color:#b01a2e} +@media (prefers-color-scheme:dark){ +text,.ink{fill:#eef1f3}.bg{fill:#0e1113}.card{fill:#161a1d;stroke:#2a3036}.soft{fill:#1d2226} +.muted{fill:#8e979f}.icon{color:#c7cdd3} +.acc{fill:#34d399}.acc-t{fill:#4ade80}.acc-tint{fill:rgba(52,211,153,.12)}.acc-line{stroke:#34d399} +.info{fill:#3aa9ff}.info-t{fill:#7cc4ff}.info-tint{fill:rgba(58,169,255,.12)} +.warn{fill:#f5b53d}.warn-t{fill:#f8c96a}.warn-tint{fill:rgba(245,181,61,.12)} +.dan{fill:#ff5a6e}.dan-tint{fill:rgba(255,90,110,.12)}.dan-t{fill:#ff8a98} +.dot{fill:#2a3036}.line{stroke:#2a3036}.arrow{stroke:#8e979f}.arrowhead{fill:#8e979f}.dash{stroke:#8e979f} +.on-acc{fill:#052e20}.icon-acc{color:#4ade80}.icon-dan{color:#ff8a98} +} +""" % FONT + + +def icon(name, x, y, size=28, cls="icon"): + """A sprite icon at (x, y), `size` px, drawn in the class's color (the icons use currentColor).""" + m = re.search(r']*>(.*?)' % name, SPRITE, re.S) + return (f'{m.group(1)}') + + +def text(x, y, s, size=14, weight=400, cls="ink", anchor="start"): + return (f'{s}') + + +def rect(x, y, w, h, r=14, cls="card"): + return f'' + + +def svg(w, h, body, title): + return (f'{title}' + f'{rect(0, 0, w, h, 20, "bg")}{body}') + + +def dots(x, y, cols, rows, step, lit, lit_cls="acc", r=2.6, seed=1): + """A grid of expert dots; `lit` of them (spread at random) in the accent color.""" + rnd = random.Random(seed) + n = cols * rows + on = set(rnd.sample(range(n), min(lit, n))) + out = [] + for i in range(n): + cx, cy = x + (i % cols) * step, y + (i // cols) * step + out.append(f'') + return "".join(out) + + +def arrow(x1, y1, x2, y2, cls="arrow"): + return (f'' + f'') + + +def how_it_works(): + W, H = 960, 470 + b = [] + # the headline strip: one word, 10 experts + b.append(rect(24, 24, W - 48, 92)) + b.append(icon("i-chat", 48, 50, 36)) + b.append(text(100, 62, "The model is made of 24,576 small specialists - “experts”.", 19, 600)) + b.append(text(100, 88, "For each word it writes, it asks only 10 of them. Strata keeps the busy ones", + 15, 400, "muted")) + b.append(text(100, 106, "on your graphics card and the rest in RAM - so it runs on a normal PC.", 15, 400, "muted")) + b.append(dots(W - 262, 46, 28, 4, 7.6, 10, seed=3)) + b.append(text(W - 262, 94, "10 at work for one word", 12, 500, "acc-t")) + # three cards + cw, ch, cy = 288, 316, 136 + xs = [24, 24 + cw + 24, 24 + 2 * (cw + 24)] + cards = [ + ("i-gpu", "Graphics card", "Small but very fast: 12-24 GB", "acc", + ["Runs the core of the model", "for every word, and keeps the", "~4,000 experts used most"], + "the most-used experts", 5, 26, 26 * 5, "acc"), + ("i-memory", "RAM + processor", "Big: 32-64 GB of memory", "info", + ["Holds all 24,576 experts. When a", "word needs one the card doesn't", "have, the CPU does it - at once"], + "all 24,576 experts", 10, 26, 18, "info"), + ("i-disk", "SSD", "Holds a 29 GB lookup table", "warn", + ["The model looks up a few", "small rows of it per word -", "no need to keep it in RAM"], + "", 0, 0, 0, "warn"), + ] + for (ic, title, sub, tone, lines, dlabel, rows, cols, lit, lit_cls), x in zip(cards, xs): + b.append(rect(x, cy, cw, ch)) + b.append(rect(x + 20, cy + 20, 48, 48, 12, tone + "-tint")) + b.append(icon(ic, x + 30, cy + 30, 28, "icon")) + b.append(text(x + 82, cy + 42, title, 19, 700)) + b.append(text(x + 82, cy + 62, sub, 13, 500, tone + "-t")) + for i, ln in enumerate(lines): + b.append(text(x + 20, cy + 104 + i * 21, ln, 15, 400, "ink")) + if rows: + b.append(dots(x + 26, cy + 196, cols, rows, 9.4, lit, lit_cls, seed=len(title))) + b.append(text(x + 20, cy + 196 + rows * 9.4 + 14, dlabel, 12, 500, "muted")) + else: # the SSD: a table of rows, a few being read + for r in range(6): + yy = cy + 190 + r * 17 + b.append(rect(x + 20, yy, cw - 40, 11, 4, "warn" if r in (1, 4) else "soft")) + b.append(text(x + 20, cy + 306, "a few rows per word", 12, 500, "muted")) + return svg(W, H, "".join(b), "How Strata splits the model between your graphics card, RAM and SSD") + + +def guess_and_check(): + W, H = 960, 330 + b = [rect(24, 24, W - 48, H - 48)] + b.append(icon("i-thinking", 48, 48, 30)) + b.append(text(92, 70, "Guess, then check - many words per step", 19, 700)) + b.append(text(92, 94, "A small, fast helper inside the model guesses the next words. The big model checks all the " + "guesses in one go", 15, 400, "muted")) + b.append(text(92, 113, "and keeps the ones it agrees with. The big model decides every word - it just arrives 1.6-1.8x sooner.", + 15, 400, "muted")) + words = ["def", "reverse", "(items", "):"] + fixed = ", key):" # the model's own word where the guess was wrong + ok = [True, True, True, False] + # row 1: the helper's guesses (dashed chips) + y1, y2 = 156, 238 + b.append(text(48, y1 + 24, "Helper guesses", 14, 600, "muted")) + b.append(text(48, y2 + 24, "Big model checks", 14, 600, "muted")) + x = 176 + xs = [] + for i, w in enumerate(words[:4]): + wd = 34 + len(w) * 9 + xs.append((x, wd)) + b.append(f'') + b.append(text(x + wd / 2, y1 + 25, w, 16, 500, "ink", "middle")) + x += wd + 14 + # row 2: the verdicts + for i, ((x, wd), good) in enumerate(zip(xs, ok)): + tone = "acc" if good else "dan" + b.append(rect(x, y2, wd, 38, 10, tone + "-tint")) + b.append(text(x + wd / 2 - 8, y2 + 25, words[i], 16, 600, tone + "-t", "middle")) + b.append(icon("i-check" if good else "i-error", x + wd - 22, y2 + 11, 16, "icon-" + tone)) + if not good: # the model's own word beside the rejected guess + fx = x + wd + 10 + fw = 26 + len(fixed) * 9 + b.append(rect(fx, y2, fw, 38, 10, "acc-tint")) + b.append(text(fx + fw / 2, y2 + 25, fixed, 16, 600, "acc-t", "middle")) + xs[i] = (fx, fw) + b.append(f'') + # the result + rx = xs[-1][0] + xs[-1][1] + 40 + b.append(arrow(rx, y2 + 19, rx + 30, y2 + 19)) + b.append(rect(rx + 42, y2 - 6, W - 48 - (rx + 42), 50, 12, "acc")) + b.append(icon("i-bolt", rx + 54, y2 + 6, 26, "on-acc-icon")) + b.append(text(rx + 90, y2 + 16, "4 words in one step", 15, 700, "on-acc")) + b.append(text(rx + 90, y2 + 34, "3 guesses kept + its own word", 12, 500, "on-acc")) + return svg(W, H, "".join(b).replace('class="on-acc-icon"', 'class="icon" style="color:#ffffff"'), + "Speculative decoding: a small helper guesses words, the big model checks them at once") + + +if __name__ == "__main__": + (OUT / "how-it-works.svg").write_text(how_it_works(), encoding="utf-8") + (OUT / "guess-and-check.svg").write_text(guess_and_check(), encoding="utf-8") + for f in ("how-it-works.svg", "guess-and-check.svg"): + print(f, (OUT / f).stat().st_size, "bytes") diff --git a/docs/media/pagoda-preview.webp b/docs/media/pagoda-preview.webp new file mode 100644 index 0000000..630ce1d Binary files /dev/null and b/docs/media/pagoda-preview.webp differ diff --git a/docs/media/runpagoda.png b/docs/media/runpagoda.png new file mode 100644 index 0000000..45aa6eb Binary files /dev/null and b/docs/media/runpagoda.png differ diff --git a/docs/paper/Strata-Paper.pdf b/docs/paper/Strata-Paper.pdf new file mode 100644 index 0000000..fcfd2eb Binary files /dev/null and b/docs/paper/Strata-Paper.pdf differ diff --git a/docs/paper/tiers.svg b/docs/paper/tiers.svg new file mode 100644 index 0000000..867ba8e --- /dev/null +++ b/docs/paper/tiers.svg @@ -0,0 +1,18 @@ + + +GPU VRAM 12 GB · 672 GB/s +dense weights ~3.3 GBmixers · GR · routers · head +expert cache: everything left (~6 GB)~4,500 of 24,576 experts, adaptive +MTP layer0.8 GB +KV + state0.3-3 GB +PCIe 4.0 x16 · ~26 GB/s · experts by DMA (prompt, 20% of misses, cache swaps) + +System RAM 64 GB DDR5 · ~41-52 GB/s · 6 CPU cores (AVX-512) +pinned expert arena: all 24,576 experts34 GB (Q2_0) · 35.5 GB (IQ2_XS) · 43 GB (IQ3_XXS); the CPU computes misses in place +OS page cache: hot n-gram rows+ OS, embedding table, buffers +NVMe · 16 row reads per token, issued a step ahead + +SSD +GGUF shard 1 (37.6-47 GB): read once at start +GGUF shard 2: n-gram table 28.8 GB, memory-mapped + \ No newline at end of file diff --git a/include/strata/artifact/dequant.hpp b/include/strata/artifact/dequant.hpp new file mode 100644 index 0000000..d5a314c --- /dev/null +++ b/include/strata/artifact/dequant.hpp @@ -0,0 +1,292 @@ +#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 new file mode 100644 index 0000000..298dc3b --- /dev/null +++ b/include/strata/artifact/gguf_reader.hpp @@ -0,0 +1,606 @@ +// 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 model; anything else must be +// refused with a precise error rather than silently mis-run. +struct Qwen4ExpGuard { + uint32_t block_count = 48, hidden = 2560, experts = 0, experts_used = 0, head_count = 24, + head_count_kv = 2; // 0 = presence-only: pruned variants (GSQ-RCO Coder) legitimately ship + // 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"; + if (arch->s != "qwen4exp") return "architecture is '" + arch->s + "', this engine requires 'qwen4exp'"; + struct Req { + const char* key; + uint64_t want; + }; + const Req reqs[] = { + {"qwen4exp.block_count", want.block_count}, + {"qwen4exp.embedding_length", want.hidden}, + {"qwen4exp.expert_count", want.experts}, + {"qwen4exp.expert_used_count", want.experts_used}, + {"qwen4exp.attention.head_count", want.head_count}, + {"qwen4exp.attention.head_count_kv", want.head_count_kv}, + }; + for (const auto& r : reqs) { + const MetaValue* v = g.get(r.key); + if (!v) return std::string("missing ") + r.key; + if (r.want && v->u != r.want) + return std::string(r.key) + " = " + std::to_string(v->u) + ", expected " + std::to_string(r.want); + } + return {}; // empty == ok +} + +} // namespace strata diff --git a/include/strata/artifact/gguf_split.hpp b/include/strata/artifact/gguf_split.hpp new file mode 100644 index 0000000..0f01001 --- /dev/null +++ b/include/strata/artifact/gguf_split.hpp @@ -0,0 +1,52 @@ +// 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 new file mode 100644 index 0000000..1cb8af7 --- /dev/null +++ b/include/strata/core/conversation_buffer.hpp @@ -0,0 +1,154 @@ +#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 new file mode 100644 index 0000000..b105deb --- /dev/null +++ b/include/strata/core/conversation_cache.hpp @@ -0,0 +1,283 @@ +// 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 new file mode 100644 index 0000000..0e908b4 --- /dev/null +++ b/include/strata/core/conversation_memory.hpp @@ -0,0 +1,19 @@ +#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 new file mode 100644 index 0000000..1a56680 --- /dev/null +++ b/include/strata/core/conversation_snapshot.hpp @@ -0,0 +1,96 @@ +#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 new file mode 100644 index 0000000..d095e3a --- /dev/null +++ b/include/strata/core/coupled_draft.hpp @@ -0,0 +1,90 @@ +// 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 new file mode 100644 index 0000000..091dff1 --- /dev/null +++ b/include/strata/core/device.hpp @@ -0,0 +1,95 @@ +// 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 new file mode 100644 index 0000000..6f28b97 --- /dev/null +++ b/include/strata/core/emulate.hpp @@ -0,0 +1,36 @@ +// 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 new file mode 100644 index 0000000..8c031ff --- /dev/null +++ b/include/strata/core/expert_cache.hpp @@ -0,0 +1,227 @@ +// 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 new file mode 100644 index 0000000..8fbc4a5 --- /dev/null +++ b/include/strata/core/expert_source.hpp @@ -0,0 +1,720 @@ +// 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"); + +/// 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_; } + 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_; + 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 new file mode 100644 index 0000000..369bfe3 --- /dev/null +++ b/include/strata/core/graph.hpp @@ -0,0 +1,117 @@ +// 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 new file mode 100644 index 0000000..8c21035 --- /dev/null +++ b/include/strata/core/hit_hook.hpp @@ -0,0 +1,41 @@ +// 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 new file mode 100644 index 0000000..aec6e9e --- /dev/null +++ b/include/strata/core/layer.hpp @@ -0,0 +1,627 @@ +// 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(); +/// 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); +uint64_t block_buffers_init(const ModelGeometry& g, void* base, BlockBuffers& b); + +// ================================ 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 new file mode 100644 index 0000000..7b27fec --- /dev/null +++ b/include/strata/core/layout.hpp @@ -0,0 +1,97 @@ +// 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 +#include + +namespace strata::core { + +/// The model's geometry, taken from `docs/semantics.md` and the artifact's own metadata. Every field here +/// is a number a kernel depends on, so a change is a change to a kernel contract and not a tuning knob. +struct ModelGeometry { + int64_t n_embd = 2560; + int64_t n_layers = 48; + int64_t qsa_interval = 4; ///< every 4th layer is full attention: layers 3, 7, ... 47 + + // GDN (36 layers) + int64_t ssm_state_size = 128; + int64_t ssm_k_heads = 16; + int64_t ssm_v_heads = 48; + int64_t ssm_d_conv = 4; + int64_t ssm_conv_channels = 10240; ///< 2*128*16 + 128*48 + int64_t ssm_value_dim = 6144; ///< 128 * 48 + + // QSA (12 layers) + int64_t n_head = 24; + int64_t n_head_kv = 2; + int64_t head_dim = 256; + int64_t idx_q_heads = 4; + int64_t idx_key_dim = 128; + + // gated residual, on every layer + int64_t hc = 4; + int64_t hc_lr = 320; + + // MoE, on every layer + int64_t n_expert = 512; + int64_t n_ff = 640; + + int64_t 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(); } +}; + +/// 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/mtp.hpp b/include/strata/core/mtp.hpp new file mode 100644 index 0000000..bfb6ee0 --- /dev/null +++ b/include/strata/core/mtp.hpp @@ -0,0 +1,188 @@ +// 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 + +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); } + 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 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; }; + 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 new file mode 100644 index 0000000..2d3cb94 --- /dev/null +++ b/include/strata/core/native_dense.hpp @@ -0,0 +1,45 @@ +#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 new file mode 100644 index 0000000..ff45dd6 --- /dev/null +++ b/include/strata/core/native_head.hpp @@ -0,0 +1,68 @@ +#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 new file mode 100644 index 0000000..ed876f4 --- /dev/null +++ b/include/strata/core/on_device.hpp @@ -0,0 +1,22 @@ +#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 new file mode 100644 index 0000000..a6e3766 --- /dev/null +++ b/include/strata/core/peer_experts.hpp @@ -0,0 +1,106 @@ +// 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 new file mode 100644 index 0000000..28a6f98 --- /dev/null +++ b/include/strata/core/pinned.hpp @@ -0,0 +1,152 @@ +// 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 new file mode 100644 index 0000000..46c9378 --- /dev/null +++ b/include/strata/core/progress.hpp @@ -0,0 +1,59 @@ +// 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/remote_expert_opt.hpp b/include/strata/core/remote_expert_opt.hpp new file mode 100644 index 0000000..5eb488c --- /dev/null +++ b/include/strata/core/remote_expert_opt.hpp @@ -0,0 +1,53 @@ +#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 new file mode 100644 index 0000000..224d24f --- /dev/null +++ b/include/strata/core/remote_experts.hpp @@ -0,0 +1,89 @@ +#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 new file mode 100644 index 0000000..4d63320 --- /dev/null +++ b/include/strata/core/session.hpp @@ -0,0 +1,436 @@ +// 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 new file mode 100644 index 0000000..e68f7b3 --- /dev/null +++ b/include/strata/core/verify.hpp @@ -0,0 +1,364 @@ +// 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 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 new file mode 100644 index 0000000..5c6414f --- /dev/null +++ b/include/strata/core/weights.hpp @@ -0,0 +1,141 @@ +// 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_; } + 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 new file mode 100644 index 0000000..8794479 --- /dev/null +++ b/include/strata/hip_compat/cublas_v2.h @@ -0,0 +1,60 @@ +#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 new file mode 100644 index 0000000..969acef --- /dev/null +++ b/include/strata/hip_compat/cuda_fp16.h @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h new file mode 100644 index 0000000..8ea907a --- /dev/null +++ b/include/strata/hip_compat/cuda_runtime.h @@ -0,0 +1,143 @@ +#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 new file mode 100644 index 0000000..cf546fc --- /dev/null +++ b/include/strata/hip_compat/cuda_runtime_api.h @@ -0,0 +1,2 @@ +#pragma once +#include "cuda_runtime.h" diff --git a/include/strata/hip_compat/intrinsics.hpp b/include/strata/hip_compat/intrinsics.hpp new file mode 100644 index 0000000..3129f04 --- /dev/null +++ b/include/strata/hip_compat/intrinsics.hpp @@ -0,0 +1,162 @@ +#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 new file mode 100644 index 0000000..50a0862 --- /dev/null +++ b/include/strata/hip_compat/math_constants.h @@ -0,0 +1,4 @@ +#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 new file mode 100644 index 0000000..5c32532 --- /dev/null +++ b/include/strata/kernels/bf16_bits.hpp @@ -0,0 +1,61 @@ +// 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 new file mode 100644 index 0000000..e3efe0f --- /dev/null +++ b/include/strata/kernels/bf16_gemv.hpp @@ -0,0 +1,56 @@ +// 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 new file mode 100644 index 0000000..ab05db8 --- /dev/null +++ b/include/strata/kernels/cpu/expert.hpp @@ -0,0 +1,179 @@ +// 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 new file mode 100644 index 0000000..0eff498 --- /dev/null +++ b/include/strata/kernels/cpu/expert_layout.hpp @@ -0,0 +1,82 @@ +// 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). +bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err); +/// The newest native_experts.txt this engine reads. v4 = v3 plus the per-role shard column `gate,up,down`, +/// written only when some layer's roles are in different shards (every other pack stays v3, byte for byte). +inline constexpr int kExpertLayoutVersion = 4; + +} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/iq_avx2.hpp b/include/strata/kernels/cpu/iq_avx2.hpp new file mode 100644 index 0000000..a9628d3 --- /dev/null +++ b/include/strata/kernels/cpu/iq_avx2.hpp @@ -0,0 +1,26 @@ +// 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 new file mode 100644 index 0000000..a9a71c4 --- /dev/null +++ b/include/strata/kernels/cpu/iq_avx512.hpp @@ -0,0 +1,18 @@ +// 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 new file mode 100644 index 0000000..c9afc3f --- /dev/null +++ b/include/strata/kernels/cpu/kq_avx1.hpp @@ -0,0 +1,18 @@ +// 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 new file mode 100644 index 0000000..01b7a63 --- /dev/null +++ b/include/strata/kernels/cpu/kq_avx2.hpp @@ -0,0 +1,25 @@ +// 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 new file mode 100644 index 0000000..9b80742 --- /dev/null +++ b/include/strata/kernels/cpu/native_expert.hpp @@ -0,0 +1,49 @@ +// 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 new file mode 100644 index 0000000..662bb03 --- /dev/null +++ b/include/strata/kernels/cpu/pool.hpp @@ -0,0 +1,286 @@ +// 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 new file mode 100644 index 0000000..a447eb5 --- /dev/null +++ b/include/strata/kernels/cvec.hpp @@ -0,0 +1,61 @@ +// 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 new file mode 100644 index 0000000..5a8ed08 --- /dev/null +++ b/include/strata/kernels/dequant_bf16.hpp @@ -0,0 +1,27 @@ +// 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 new file mode 100644 index 0000000..2603f48 --- /dev/null +++ b/include/strata/kernels/dequant_s2.hpp @@ -0,0 +1,18 @@ +// 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 new file mode 100644 index 0000000..e73be4d --- /dev/null +++ b/include/strata/kernels/dp4a.hpp @@ -0,0 +1,45 @@ +// 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 new file mode 100644 index 0000000..ae0973c --- /dev/null +++ b/include/strata/kernels/elementwise.hpp @@ -0,0 +1,128 @@ +// 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 new file mode 100644 index 0000000..396d690 --- /dev/null +++ b/include/strata/kernels/f16_bits.hpp @@ -0,0 +1,104 @@ +// 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 new file mode 100644 index 0000000..0cf7c66 --- /dev/null +++ b/include/strata/kernels/fused_gdn.hpp @@ -0,0 +1,35 @@ +// 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 * sigmoid(z) +#pragma once + +#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); + +void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, + void* stream); + +} // namespace strata::kernels diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp new file mode 100644 index 0000000..b5f95fc --- /dev/null +++ b/include/strata/kernels/fused_gr.hpp @@ -0,0 +1,67 @@ +// 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 new file mode 100644 index 0000000..898e2a8 --- /dev/null +++ b/include/strata/kernels/gdn.hpp @@ -0,0 +1,97 @@ +// 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. The real artifact: S = 128, h_k = 16, h_v = 48. +struct GdnShapes { + int64_t S = 0; ///< head dim, and the state's contracted axis + int64_t h_k = 0; ///< key/query heads (q and k are (h_k, S)) + int64_t h_v = 0; ///< value heads (v, z, o are (h_v, S)); h_v must be a multiple of h_k +}; + +/// 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 new file mode 100644 index 0000000..2c38f6f --- /dev/null +++ b/include/strata/kernels/iq_kernels.hpp @@ -0,0 +1,80 @@ +// 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). +// +// 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 new file mode 100644 index 0000000..930b628 --- /dev/null +++ b/include/strata/kernels/kv_q4.hpp @@ -0,0 +1,61 @@ +// 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 new file mode 100644 index 0000000..a535cc3 --- /dev/null +++ b/include/strata/kernels/kv_q8.hpp @@ -0,0 +1,41 @@ +// 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 new file mode 100644 index 0000000..514474b --- /dev/null +++ b/include/strata/kernels/kv_stream.hpp @@ -0,0 +1,104 @@ +// 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 new file mode 100644 index 0000000..18dbb68 --- /dev/null +++ b/include/strata/kernels/mrope.hpp @@ -0,0 +1,64 @@ +// 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 new file mode 100644 index 0000000..b517156 --- /dev/null +++ b/include/strata/kernels/native_flash_attn.hpp @@ -0,0 +1,36 @@ +#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 new file mode 100644 index 0000000..feebefe --- /dev/null +++ b/include/strata/kernels/native_gdn.hpp @@ -0,0 +1,22 @@ +#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 new file mode 100644 index 0000000..58334f4 --- /dev/null +++ b/include/strata/kernels/native_gdn_preprocess.hpp @@ -0,0 +1,37 @@ +#pragma once +#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*sigmoid(z). Gamma contains only +// 128 floats and broadcasts across heads. Destination is disjoint from inputs. +void native_gdn_out_norm(const float* output, const float* z, const float* gamma, + float* destination, int64_t heads, int64_t cols, + float epsilon, void* stream); + +} // namespace strata::kernels diff --git a/include/strata/kernels/native_gr_norm.hpp b/include/strata/kernels/native_gr_norm.hpp new file mode 100644 index 0000000..b8bb4ed --- /dev/null +++ b/include/strata/kernels/native_gr_norm.hpp @@ -0,0 +1,18 @@ +#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 new file mode 100644 index 0000000..790b883 --- /dev/null +++ b/include/strata/kernels/native_gr_postops.hpp @@ -0,0 +1,28 @@ +#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 new file mode 100644 index 0000000..a1554e5 --- /dev/null +++ b/include/strata/kernels/native_mmvq.hpp @@ -0,0 +1,115 @@ +#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 new file mode 100644 index 0000000..34760ef --- /dev/null +++ b/include/strata/kernels/native_moe.hpp @@ -0,0 +1,21 @@ +#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 new file mode 100644 index 0000000..97c4990 --- /dev/null +++ b/include/strata/kernels/native_ple_postops.hpp @@ -0,0 +1,38 @@ +#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 new file mode 100644 index 0000000..c56eb4d --- /dev/null +++ b/include/strata/kernels/native_qsa.hpp @@ -0,0 +1,30 @@ +#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 new file mode 100644 index 0000000..fe66d4b --- /dev/null +++ b/include/strata/kernels/native_qsa_indexer.hpp @@ -0,0 +1,46 @@ +#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 new file mode 100644 index 0000000..9427a77 --- /dev/null +++ b/include/strata/kernels/native_qsa_score.hpp @@ -0,0 +1,31 @@ +#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 new file mode 100644 index 0000000..95511b8 --- /dev/null +++ b/include/strata/kernels/native_rope.hpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..0511b0b --- /dev/null +++ b/include/strata/kernels/native_router.hpp @@ -0,0 +1,19 @@ +#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 new file mode 100644 index 0000000..a321ea7 --- /dev/null +++ b/include/strata/kernels/ngram.hpp @@ -0,0 +1,216 @@ +// 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 new file mode 100644 index 0000000..76ae789 --- /dev/null +++ b/include/strata/kernels/ple.hpp @@ -0,0 +1,123 @@ +// 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 new file mode 100644 index 0000000..7826dbc --- /dev/null +++ b/include/strata/kernels/q8_1_finite.hpp @@ -0,0 +1,33 @@ +// 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 new file mode 100644 index 0000000..dc26024 --- /dev/null +++ b/include/strata/kernels/qsa.hpp @@ -0,0 +1,369 @@ +// 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 + +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; } + +/// The selection width: `min(n_kv, idx_top_k + idx_block - 1)`. +/// +/// The `r - 1 = 3` is not slack, it is the incomplete tail: the budget is whole blocks PLUS whatever cells do +/// not fill one. So the plan's "selection skipped when context <= 2,048" is conservative by two - the source's +/// own bound is 2,051, and `ref/qsa.py` L292-294 records the disagreement. Below the bound the selection is +/// the IDENTITY, which `topk_512` is required to reproduce exactly rather than approximately. +inline int64_t qsa_selection_width(int64_t n_kv, const QsaShapes& s) { + const int64_t w = s.idx_top_k + s.idx_block - 1; + return n_kv < w ? n_kv : w; +} + +/// 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 + 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; + +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 new file mode 100644 index 0000000..45c0f30 --- /dev/null +++ b/include/strata/kernels/qsa_decode_attn.hpp @@ -0,0 +1,46 @@ +// 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 (ceil(cap / CHUNK), n_head_kv): s = q.k * scale for 12 heads x CHUNK cells, chunk max m and sum l, +// acc = p . V -> partials +// grid (n_head): merge the chunks with the usual log-sum-exp rescale +// +// FP16 pools or INT8 pools (codes + fp16 scale per 64 values, `kv_q8.hpp`). The grid is sized by the capacity; +// the real count comes from `step[kStepWidth]` as for every other capturable QSA kernel. +#pragma once + +#include "strata/kernels/qsa.hpp" + +#include + +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; +}; + +/// Scratch floats for `cap` selected cells: partial accumulators, maxima and sums. +uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s); + +void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream); + +/// Plan v0.3 P5: `n_q` queries at once, each with its own selection: q [n_q, n_head, 256], ids [n_q, cap], steps +/// [n_q, kStepCount], attn [n_q, n_head, 256]; scratch is `n_q` times the single-query size. +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); + +} // namespace strata::kernels diff --git a/include/strata/kernels/qsa_prompt_attn.hpp b/include/strata/kernels/qsa_prompt_attn.hpp new file mode 100644 index 0000000..2391aae --- /dev/null +++ b/include/strata/kernels/qsa_prompt_attn.hpp @@ -0,0 +1,32 @@ +// 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 new file mode 100644 index 0000000..3150816 --- /dev/null +++ b/include/strata/kernels/qsa_select.hpp @@ -0,0 +1,57 @@ +// 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 new file mode 100644 index 0000000..49d858b --- /dev/null +++ b/include/strata/kernels/quantize_act.hpp @@ -0,0 +1,58 @@ +// 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 new file mode 100644 index 0000000..45e54fa --- /dev/null +++ b/include/strata/kernels/rope.hpp @@ -0,0 +1,64 @@ +// 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 new file mode 100644 index 0000000..b494ddc --- /dev/null +++ b/include/strata/kernels/rope_scaling.hpp @@ -0,0 +1,193 @@ +// 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 new file mode 100644 index 0000000..e10295e --- /dev/null +++ b/include/strata/kernels/router_top10.hpp @@ -0,0 +1,26 @@ +// 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 new file mode 100644 index 0000000..af6f52f --- /dev/null +++ b/include/strata/kernels/s2_expert_grouped.hpp @@ -0,0 +1,131 @@ +// 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 new file mode 100644 index 0000000..a09b822 --- /dev/null +++ b/include/strata/kernels/s2_gemv.hpp @@ -0,0 +1,25 @@ +// 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 new file mode 100644 index 0000000..9c7beb9 --- /dev/null +++ b/include/strata/kernels/s2_gemv_q8.hpp @@ -0,0 +1,22 @@ +// 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 new file mode 100644 index 0000000..340df04 --- /dev/null +++ b/include/strata/kernels/s_gemv.hpp @@ -0,0 +1,133 @@ +// 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 new file mode 100644 index 0000000..a740101 --- /dev/null +++ b/include/strata/kernels/sampler.hpp @@ -0,0 +1,86 @@ +// 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 new file mode 100644 index 0000000..44b37d8 --- /dev/null +++ b/include/strata/kernels/shared_expert.hpp @@ -0,0 +1,103 @@ +// 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 new file mode 100644 index 0000000..50d951a --- /dev/null +++ b/include/strata/kernels/verify_kernels.hpp @@ -0,0 +1,98 @@ +// 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 + +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`. +void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok, + const 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 new file mode 100644 index 0000000..2884817 --- /dev/null +++ b/include/strata/ngram/ple_reader.hpp @@ -0,0 +1,100 @@ +// 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 new file mode 100644 index 0000000..b974f1f --- /dev/null +++ b/include/strata/plan/plan.hpp @@ -0,0 +1,168 @@ +// 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/platform/direct_file.hpp b/include/strata/platform/direct_file.hpp new file mode 100644 index 0000000..c59eb91 --- /dev/null +++ b/include/strata/platform/direct_file.hpp @@ -0,0 +1,60 @@ +// 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 new file mode 100644 index 0000000..fe8ea15 --- /dev/null +++ b/include/strata/platform/hip_compat/cublas_v2.h @@ -0,0 +1,26 @@ +// 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 new file mode 100644 index 0000000..4cd2d3c --- /dev/null +++ b/include/strata/platform/hip_compat/cuda_fp16.h @@ -0,0 +1,2 @@ +#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 new file mode 100644 index 0000000..4cd2d3c --- /dev/null +++ b/include/strata/platform/hip_compat/cuda_runtime.h @@ -0,0 +1,2 @@ +#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 new file mode 100644 index 0000000..b00d57b --- /dev/null +++ b/include/strata/platform/hip_compat/math_constants.h @@ -0,0 +1,4 @@ +// 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 new file mode 100644 index 0000000..b0de6c4 --- /dev/null +++ b/include/strata/platform/hip_compat/strata_hip.h @@ -0,0 +1,295 @@ +// 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 new file mode 100644 index 0000000..202a3bf --- /dev/null +++ b/include/strata/platform/memory.hpp @@ -0,0 +1,46 @@ +// 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/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp new file mode 100644 index 0000000..60d1c71 --- /dev/null +++ b/include/strata/prefill/gemm.hpp @@ -0,0 +1,66 @@ +// 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 new file mode 100644 index 0000000..3358bea --- /dev/null +++ b/include/strata/prefill/kernels.hpp @@ -0,0 +1,100 @@ +// 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/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); + +// ---- GDN (state 128, 16 k heads, 48 v heads, 10240 conv channels, 4 taps) +/// gate[t,h] = softplus(ab[t,h] + dt[h]) * ssm_a[h]; beta[t,h] = sigmoid(ab[t, 48 + h]) (ab: [T, 96]) +void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream); +/// The 4-tap causal conv + SiLU over the chunk (history [C][3] in, updated to the chunk's last three inputs), then +/// the L2 norm of the q and k heads of every token. h: [T, C]. +void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream); +/// The recurrence over the chunk, state in registers; y16[t] = rmsnorm(o) * gamma * sigmoid(z) in FP16 (what the +/// out projection reads); y is FP32 scratch. +void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, + const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream); + +// ---- MoE +/// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router). +void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream); +/// Expert blob (Strata pack layout, Q2_0) -> BF16 matrices: gate/up interleaved [1280, 2560], down [2560, 640]. +void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream); +/// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up) +void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream); +/// h16[n, r] = fp16(silu(g[n, r]) * u[n, r]) (the shared expert, gate and up separate, width 640) +void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream); +/// 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_k w[t, k] * D[slot[t, k], :] +void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, + int64_t T, 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, 24, 512] (q | gate per head) -> q [T, 24, 256] +void split_q(const float* q_full, float* q, int64_t T, void* stream); +/// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized) +void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, 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 new file mode 100644 index 0000000..a18590f --- /dev/null +++ b/include/strata/prefill/moe_fused.hpp @@ -0,0 +1,64 @@ +// 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 new file mode 100644 index 0000000..7c9e328 --- /dev/null +++ b/include/strata/prefill/moe_fused_iq.hpp @@ -0,0 +1,41 @@ +// 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; n_embd 2560, n_ff 640). +struct NativeGeom { + int gu_type = -1, d_type = -1; ///< ggml types + size_t gu_row = 0, d_row = 0; ///< bytes per gate/up row and per down row + size_t up_off = 0, down_off = 0; ///< inside the blob +}; + +/// 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 new file mode 100644 index 0000000..0859dca --- /dev/null +++ b/include/strata/prefill/moe_mmq.hpp @@ -0,0 +1,88 @@ +// 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 new file mode 100644 index 0000000..15df6e4 --- /dev/null +++ b/include/strata/prefill/prefill.hpp @@ -0,0 +1,184 @@ +// 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; + + /// 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 new file mode 100644 index 0000000..7fe4bfa --- /dev/null +++ b/include/strata/program/conv_cache.hpp @@ -0,0 +1,43 @@ +// 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 new file mode 100644 index 0000000..04462a8 --- /dev/null +++ b/include/strata/program/logits_selection.hpp @@ -0,0 +1,30 @@ +#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 new file mode 100644 index 0000000..4864ce9 --- /dev/null +++ b/include/strata/spec/controller.hpp @@ -0,0 +1,73 @@ +// 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 new file mode 100644 index 0000000..c77b869 --- /dev/null +++ b/include/strata/spec/draft_policy.hpp @@ -0,0 +1,52 @@ +// 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 new file mode 100644 index 0000000..731bbef --- /dev/null +++ b/include/strata/spec/suffix_drafter.hpp @@ -0,0 +1,53 @@ +// 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/ref/load.py b/ref/load.py new file mode 100644 index 0000000..0e4575a --- /dev/null +++ b/ref/load.py @@ -0,0 +1,212 @@ +"""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"} + +# (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)} + + +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/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3db8418 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,23 @@ +# The Python packages setup.py installs into .venv, pinned so a checkout installs the same ones on any day (#214). +# setup.py's pip step reads this file; an install from before it keeps the packages it has. +# Python 3.10+ (numpy's newest releases need a newer Python: one line per range). +numpy==2.5.3; python_version >= "3.12" +numpy==2.4.6; python_version == "3.11" +numpy==2.2.6; python_version < "3.11" +jinja2==3.1.6 +regex==2026.9.10 +pyyaml==6.0.3 +tqdm==4.70.1 +requests==2.34.2 +cmake==4.4.3 +ninja==1.13.2 +pillow==12.3.0 +psutil==7.2.2 + +# their dependencies +markupsafe==3.0.3 +certifi==2026.7.22 +charset-normalizer==3.5.1 +idna==3.20 +urllib3==2.8.0 +colorama==0.4.6; sys_platform == "win32" diff --git a/serve/__init__.py b/serve/__init__.py new file mode 100644 index 0000000..c3b0bdd --- /dev/null +++ b/serve/__init__.py @@ -0,0 +1 @@ +"""serve - plan v0.3 P8: the API layer (text in, token ids to the engine, text deltas out).""" diff --git a/serve/chat_golden.json b/serve/chat_golden.json new file mode 100644 index 0000000..652e336 --- /dev/null +++ b/serve/chat_golden.json @@ -0,0 +1,197 @@ +[ + { + "name": "single user", + "messages": [ + { + "role": "user", + "content": "Hello" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "system + user", + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "What is 2+2?" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\nWhat is 2+2?<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\nWhat is 2+2?<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "multi-turn", + "messages": [ + { + "role": "system", + "content": "Be brief." + }, + { + "role": "user", + "content": "Hi" + }, + { + "role": "assistant", + "content": "Hello! How can I help?" + }, + { + "role": "user", + "content": "Explain BPE in one sentence." + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\nBe brief.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n\n\n\n\nHello! How can I help?<|im_end|>\n<|im_start|>user\nExplain BPE in one sentence.<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\nBe brief.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n\n\n\n\nHello! How can I help?<|im_end|>\n<|im_start|>user\nExplain BPE in one sentence.<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "assistant with thinking", + "messages": [ + { + "role": "user", + "content": "What is 17*23?" + }, + { + "role": "assistant", + "content": "Let me compute.", + "reasoning_content": "17*23 = 17*20 + 17*3 = 340+51 = 391" + }, + { + "role": "user", + "content": "Thanks" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nWhat is 17*23?<|im_end|>\n<|im_start|>assistant\n\n17*23 = 17*20 + 17*3 = 340+51 = 391\n\n\nLet me compute.<|im_end|>\n<|im_start|>user\nThanks<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nWhat is 17*23?<|im_end|>\n<|im_start|>assistant\n\n17*23 = 17*20 + 17*3 = 340+51 = 391\n\n\nLet me compute.<|im_end|>\n<|im_start|>user\nThanks<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "no generation prompt", + "messages": [ + { + "role": "user", + "content": "Hello" + }, + { + "role": "assistant", + "content": "Hi there" + } + ], + "add_generation_prompt": false, + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n\n\n\nHi there<|im_end|>\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n\n\n\nHi there<|im_end|>\n" + }, + { + "name": "thinking disabled", + "messages": [ + { + "role": "user", + "content": "Hello" + } + ], + "enable_thinking": false, + "rendered": "<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "error": null, + "hf": "<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + }, + { + "name": "unicode content", + "messages": [ + { + "role": "user", + "content": "你好,世界 😀" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\n你好,世界 😀<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\n你好,世界 😀<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "tool call and response", + "messages": [ + { + "role": "user", + "content": "Weather in Oslo?" + }, + { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "type": "function", + "function": { + "name": "get_weather", + "arguments": { + "city": "Oslo" + } + } + } + ] + }, + { + "role": "tool", + "content": "{\"temp\": 3}", + "name": "get_weather" + }, + { + "role": "user", + "content": "And in Bergen?" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the weather", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + } + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\n# Tools\n\nYou have access to the following functions:\n\n\n{\"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"description\": \"Get the weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\"}}, \"required\": [\"city\"]}}}\n\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n<|im_end|>\n<|im_start|>user\nWeather in Oslo?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n\n\nOslo\n\n\n<|im_end|>\n<|im_start|>user\n\n{\"temp\": 3}\n<|im_end|>\n<|im_start|>user\nAnd in Bergen?<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\n# Tools\n\nYou have access to the following functions:\n\n\n{\"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"description\": \"Get the weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\"}}, \"required\": [\"city\"]}}}\n\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n<|im_end|>\n<|im_start|>user\nWeather in Oslo?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n\n\nOslo\n\n\n<|im_end|>\n<|im_start|>user\n\n{\"temp\": 3}\n<|im_end|>\n<|im_start|>user\nAnd in Bergen?<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "empty user", + "messages": [ + { + "role": "user", + "content": "" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "whitespace and newlines", + "messages": [ + { + "role": "user", + "content": " line1\n line2\n\n\nend " + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nline1\n line2\n\n\nend<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nline1\n line2\n\n\nend<|im_end|>\n<|im_start|>assistant\n\n" + } +] \ No newline at end of file diff --git a/serve/chat_template.jinja b/serve/chat_template.jinja new file mode 100644 index 0000000..a087700 --- /dev/null +++ b/serve/chat_template.jinja @@ -0,0 +1,184 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- set sysns = namespace(count=0, text='') %} +{%- for message in messages %} + {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %} + {%- set sys_content = render_content(message.content, false, true)|trim %} + {%- if sys_content %} + {%- set sysns.text = sysns.text + ('\n' if sysns.text else '') + sys_content %} + {%- endif %} + {%- set sysns.count = sysns.count + 1 %} + {%- endif %} +{%- endfor %} +{%- set num_sys = sysns.count %} +{%- set merged_system = sysns.text %} +{%- set reasoning_instructions = '' %} +{%- if enable_thinking is undefined or enable_thinking is true %} + {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %} + {%- if resolved_reasoning_effort == 'high' %} + {%- set resolved_reasoning_effort = 'xhigh' %} + {%- endif %} + {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %} + {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }} + {%- endif %} + {%- if resolved_reasoning_effort == 'xhigh' %} + {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %} + {%- elif resolved_reasoning_effort == 'low' %} + {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %} + {%- endif %} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {%- if reasoning_instructions %} + {{- reasoning_instructions + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if merged_system %} + {{- '\n\n' + merged_system }} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if merged_system %} + {{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\n' }} + {%- elif reasoning_instructions %} + {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- if loop.index0 >= num_sys %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" or message.role == "developer" %} + {{- raise_exception('System message must be at the beginning.') }} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if tool_call.name is not defined or tool_call.name is none %} + {{- raise_exception('Tool call is missing a function name.') }} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is mapping %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- elif tool_call.arguments is string %} + {%- if tool_call.arguments|trim %} + {{- raise_exception('Tool call arguments for function "' + (tool_call.name | string) + '" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }} + {%- endif %} + {%- elif tool_call.arguments is defined and tool_call.arguments is not none %} + {{- raise_exception('Tool call arguments for function "' + (tool_call.name | string) + '" must be an object/mapping or a JSON string.') }} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} +{#- Unsloth fixes - developer role, merged system messages, tool calling #} \ No newline at end of file diff --git a/serve/frontend.py b/serve/frontend.py new file mode 100644 index 0000000..02a1d2f --- /dev/null +++ b/serve/frontend.py @@ -0,0 +1,676 @@ +"""serve/frontend.py - plan v0.3 P8: the request/response layer between API clients and the engine. + +Everything here is text: no model, no GPU. The engine consumes token ids and produces text deltas; this module + + * normalizes OpenAI Chat Completions and Anthropic Messages requests into the chat template's message form, + * renders the model's own Jinja chat template (pack `tokenizer/chat_template.jinja`) exactly as Hugging Face + does (checked against the pack's `chat_golden.json`, 10 cases incl. thinking and tools), + * parses the streamed output incrementally into reasoning (`...`), content and tool calls in + the template's XML form (`VALUE...`), + never emitting a partial tag to the client. + +Design note: plan v0.3 describes a single C++ process. The frontend is Python first because the template is Jinja +and the formats change often; the engine boundary is token ids in, text deltas out, which keeps a later C++ port +(or a pybind wrapper) a local change. +""" +from __future__ import annotations + +import json +import re +import uuid +from dataclasses import dataclass, field +from pathlib import Path + +import jinja2 +from jinja2.sandbox import ImmutableSandboxedEnvironment + + +# ------------------------------------------------------------------------------------------------ template +class TemplateRequestError(jinja2.exceptions.TemplateError, ValueError): + """The template refused the request's messages (e.g. "No user query found in messages."): a ValueError, so the + client gets a 400 with the template's message instead of a dropped connection (#365).""" + + +class ChatTemplate: + """The model's chat template, rendered with the same Jinja settings as transformers' apply_chat_template.""" + + def __init__(self, path: str | Path): + def raise_exception(message): + raise TemplateRequestError(message) + + def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False): + return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys) + + env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=["jinja2.ext.loopcontrols"]) + env.filters["tojson"] = tojson + env.globals["raise_exception"] = raise_exception + self.source = Path(path).read_text(encoding="utf-8") + self.template = env.from_string(self.source) + + def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True, + **kwargs) -> str: + return self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, + **kwargs) + + +# ------------------------------------------------------------------------------------------------ requests +def _text_of(content) -> str: + if content is None: + return "" + if isinstance(content, str): + return content + return "".join(part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") in + ("text", "input_text", None)) + + +IMAGE_PARTS = ("image_url", "input_image", "image") + +# Thinking levels. The model's template knows low, medium and xhigh (its default; "high" means xhigh), and +# enable_thinking=false for none. Clients spell these many ways; everything maps onto those four. +EFFORT = {"none": None, "off": None, "minimal": None, "disabled": None, "false": None, + "low": "low", "medium": "medium", "high": "xhigh", "xhigh": "xhigh", "max": "xhigh", "maximum": "xhigh"} + + +def effort_kwargs(value) -> dict: + """A reasoning effort as given by a client -> the template's kwargs. Unknown values are a 400, not a crash.""" + if value is None or value == "": + return {} + if value is False: + return {"enable_thinking": False} + key = str(value).strip().lower() + if key not in EFFORT: + raise ValueError(f"unknown reasoning effort {value!r}: use none, low, medium or high") + level = EFFORT[key] + return {"enable_thinking": False} if level is None else {"reasoning_effort": level} + + +def budget_effort(tokens) -> dict: + """Anthropic's thinking budget (budget_tokens) -> a level: under 2K low, under 8K medium, else high.""" + try: + n = int(tokens) + except (TypeError, ValueError): + return {} + return {"reasoning_effort": "low" if n < 2048 else "medium" if n < 8192 else "xhigh"} + + +def _has_image(content) -> bool: + return isinstance(content, list) and any(isinstance(p, dict) and p.get("type") in IMAGE_PARTS for p in content) + + +def _image_source(part: dict) -> str: + """An image part's source as one string: a data: URL, an http(s) URL or a local file path. + OpenAI: {"type": "image_url", "image_url": {"url": ...}} (or "image_url": "..."), Responses-style + {"type": "input_image", "image_url": ...}; Anthropic: {"type": "image", "source": {"type": "base64", + "media_type": ..., "data": ...}} or {"source": {"type": "url", "url": ...}}.""" + if part.get("type") == "image": + src = part.get("source") or {} + if src.get("type") == "base64": + return f"data:{src.get('media_type', 'image/png')};base64,{src.get('data', '')}" + return src.get("url") or src.get("path") or "" + url = part.get("image_url") + if isinstance(url, dict): + url = url.get("url") + return url or "" + + +def _parts_of(content): + """Message content for the template: a string when there is no image (unchanged behaviour), otherwise the + template's list form - text items and image items, in order - whose image items carry their source.""" + if not _has_image(content): + return _text_of(content) + items = [] + for part in content: + if not isinstance(part, dict): + continue + if part.get("type") in IMAGE_PARTS: + items.append({"type": "image", "source": _image_source(part)}) + elif part.get("type") in ("text", "input_text", None) and "text" in part: + items.append({"type": "text", "text": part.get("text", "")}) + return items + + +def images_of(messages: list[dict]) -> list[str]: + """The image sources of the rendered conversation, in prompt order (the template renders one + <|vision_start|><|image_pad|><|vision_end|> per image item, message by message).""" + return [item["source"] for m in messages if isinstance(m.get("content"), list) + for item in m["content"] if item.get("type") == "image"] + + +# #537: a literal / inside a message's text is plain text, not the model's reasoning markers. The +# tokenizer matches those two strings as their special tokens everywhere (GGUF token type 4, as llama.cpp does), so +# a user quoting "" used to hand the model a real end-of-reasoning token. Before the template is rendered +# they are swapped for these private-use characters, and the server encodes the spans they mark as ordinary text. +THINK_TAGS = {"": "\U000F0E01", "": "\U000F0E02"} +THINK_MARKS = {v: k for k, v in THINK_TAGS.items()} + + +def _mark(text: str) -> str: + for tag, mark in THINK_TAGS.items(): + text = text.replace(tag, mark) + return text + + +def _mark_deep(v): + if isinstance(v, str): + return _mark(v) + if isinstance(v, dict): + return {k: _mark_deep(x) for k, x in v.items()} + if isinstance(v, list): + return [_mark_deep(x) for x in v] + return v + + +def _has_tag(v) -> bool: + if isinstance(v, str): + return "" in v or "" in v + if isinstance(v, dict): + return any(_has_tag(x) for x in v.values()) + if isinstance(v, list): + return any(_has_tag(x) for x in v) + return False + + +def mark_think_literals(messages: list[dict], tools: list[dict] | None): + """#537: (messages, tools) with every literal / in their text swapped for THINK_TAGS' marks, and + whether there was one (None: no change, the same objects back - a prompt without them renders as it always did). + An assistant message whose content opens with a whole ... block (clients that send the reasoning + inline) keeps that one block as the model's markers, as before.""" + if not _has_tag(messages) and not _has_tag(tools): + return messages, tools, False + out = [] + for m in messages: + m = dict(m) + content = m.get("content") + for k, v in m.items(): + if k != "role": + m[k] = _mark_deep(v) + if m.get("role") == "assistant" and isinstance(content, str) and content.lstrip().startswith("") \ + and "" in content: + i, j = content.index("") + len(""), content.index("") + m["content"] = content[:i] + _mark(content[i:j]) + "" + _mark(content[j + len(""):]) + out.append(m) + return out, _mark_deep(tools), True + + +_THINK_MARK_RE = re.compile("|".join(THINK_MARKS)) + + +def unmark_think_literals(prompt: str) -> tuple[str, list[tuple[int, int]]]: + """The rendered prompt with THINK_TAGS' marks turned back into the tags' text, and the (start, end) spans of those + tags in it: the server encodes them as ordinary text (the tokenizer's encode_plain_spans).""" + out, spans, pos, n = [], [], 0, 0 + for m in _THINK_MARK_RE.finditer(prompt): + out.append(prompt[pos:m.start()]) + n += m.start() - pos + tag = THINK_MARKS[m.group(0)] + out.append(tag) + spans.append((n, n + len(tag))) + n += len(tag) + pos = m.end() + out.append(prompt[pos:]) + return "".join(out), spans + + +def _late_system_to_user(messages: list[dict]) -> list[dict]: + """The chat template takes a system message only at the start ("System message must be at the beginning"). + Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user + turn, some OpenAI clients a late "developer" message (issue #56) - so those become user messages, in place: + merging them into the first one would change the prompt's start and cost the conversation cache every turn.""" + return [dict(m, role="user") if m.get("role") == "system" and i > 0 else m for i, m in enumerate(messages)] + + +def _object_list(value, name: str) -> list[dict]: + """#460: a request's "messages" (or a message's "tool_calls") as a list of objects. Some clients send the array + double-encoded, as a JSON string, which used to be iterated character by character and crashed on m.get: such a + string is decoded. Anything that is still not a list of objects is a ValueError, which the server answers with + a 400 naming the field. None (or no field) is an empty list, as a missing field always was.""" + if value is None: + return [] + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + raise ValueError(f"{name} must be a list of objects (a string was sent that is not JSON)") from None + if not isinstance(value, list) or not all(isinstance(m, dict) for m in value): + raise ValueError(f"{name} must be a list of objects") + return value + + +def _tool_list(value, wrapper: str | None) -> list[dict]: + """#592: a request's "tools" as a list of tool objects, each with a name - in the OpenAI shape + {"type": "function", "function": {"name": ...}} (`wrapper` "function"; a bare {"name": ...} is still taken), or + in the Anthropic shape {"name": ...} (`wrapper` None). A value that is not (a string such as "auto", a list of + names, an object without a name) is a ValueError - a 400 naming the field - where it used to take the request + thread down with no reply at all. No value (or an empty one) is no tools, as always.""" + if not value: + return [] + shape = ('{"type": "function", "function": {"name": ..., "parameters": {...}}}' if wrapper else + '{"name": ..., "input_schema": {...}}') + try: + tools = _object_list(value, "tools") + except ValueError: + raise ValueError(f"tools must be a list of tool objects, each {shape}") from None + for i, t in enumerate(tools): + fn = t.get(wrapper, t) if wrapper and t.get("type") == wrapper else t + if not isinstance(fn, dict) or not isinstance(fn.get("name"), str) or not fn["name"]: + raise ValueError(f"tools[{i}] has no name: each tool must be {shape}") + return tools + + +def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: + """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" + messages = [] + for m in _object_list(req.get("messages"), "messages"): + role = m.get("role") + if role == "developer": + role = "system" + out = {"role": role, "content": _parts_of(m.get("content")) if role in ("user", "tool", "assistant") else _text_of(m.get("content"))} + if m.get("reasoning_content"): + out["reasoning_content"] = m["reasoning_content"] + if m.get("tool_calls"): + calls = [] + for c in _object_list(m["tool_calls"], "tool_calls"): + fn = c.get("function", c) + if not isinstance(fn, dict): + raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)") + args = fn.get("arguments") + if isinstance(args, str): # the template requires a mapping, not a JSON string + args = json.loads(args) if args.strip() else {} + calls.append({"function": {"name": fn.get("name"), "arguments": args or {}}}) + out["tool_calls"] = calls + messages.append(out) + tools = [t.get("function", t) if t.get("type") == "function" else t + for t in _tool_list(req.get("tools"), "function")] or None + kwargs = {} + # OpenAI Chat Completions: "reasoning_effort"; Responses style: "reasoning": {"effort": ...} + reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {} + kwargs.update(effort_kwargs(req.get("reasoning_effort") or reasoning.get("effort"))) + # the vLLM / llama.cpp convention: {"chat_template_kwargs": {"enable_thinking": false, "reasoning_effort": "low"}} + for k, v in (req.get("chat_template_kwargs") or {}).items(): + if k == "enable_thinking" and not v: + kwargs = {"enable_thinking": False} + elif k == "reasoning_effort" and "enable_thinking" not in kwargs: + kwargs.update(effort_kwargs(v)) + return _late_system_to_user(messages), tools, kwargs + + +def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[dict], list[dict] | None, dict]: + """Anthropic Messages -> (template messages, template tools, template kwargs). `think_unasked`: a request + without "thinking", an effort or a budget gets the template's default (it thinks), as through 0.1.31; False + renders it without thinking (#278, the config's "anthropic_thinking": "on_request").""" + messages = [] + system = req.get("system") + if system: + messages.append({"role": "system", "content": _text_of(system)}) + for m in _object_list(req.get("messages"), "messages"): + content = m.get("content") + if isinstance(content, str): + messages.append({"role": m["role"], "content": content}) + continue + if m.get("role") == "user" and _has_image(content) and not any( + isinstance(b, dict) and b.get("type") == "tool_result" for b in content): + messages.append({"role": "user", "content": _parts_of(content)}) + continue + text, reasoning, calls = [], [], [] + for block in content or []: + kind = block.get("type") + if kind == "text": + text.append(block.get("text", "")) + elif kind == "thinking": + reasoning.append(block.get("thinking", "")) + elif kind == "tool_use": + calls.append({"function": {"name": block.get("name"), "arguments": block.get("input") or {}}}) + elif kind == "tool_result": + messages.append({"role": "tool", "content": _text_of(block.get("content"))}) + if text or calls or reasoning: + out = {"role": m["role"], "content": "".join(text)} + if reasoning: + out["reasoning_content"] = "".join(reasoning) + if calls: + out["tool_calls"] = calls + messages.append(out) + tools = [{"name": t["name"], "description": t.get("description", ""), "parameters": t.get("input_schema", {})} + for t in _tool_list(req.get("tools"), None)] or None + kwargs = {} + # Anthropic: "thinking": {"type": "disabled"} or {"type": "enabled", "budget_tokens": N}; + # "output_config": {"effort": "low" | "medium" | "high"} + thinking = req.get("thinking") + effort = (req.get("output_config") or {}).get("effort") if isinstance(req.get("output_config"), dict) else None + if isinstance(thinking, dict) and thinking.get("type") == "disabled": + kwargs["enable_thinking"] = False + elif effort: + kwargs.update(effort_kwargs(effort)) + elif isinstance(thinking, dict) and thinking.get("budget_tokens"): + kwargs.update(budget_effort(thinking["budget_tokens"])) + elif thinking is None and not req.get("reasoning_budget_tokens") and not think_unasked: + # Opt-in (the config's "anthropic_thinking": "on_request"; the default thinks as 0.1.31 did, since a + # client that never asks would otherwise lose the thinking on every turn). Anthropic's thinking is + # opt-in there. Claude Code's helper calls (a session title, a topic check) ask for none + # and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all. + # A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs. A + # request that gives its own reasoning_budget_tokens (#123) asks for thinking, so it thinks as before. + kwargs["enable_thinking"] = False + return _late_system_to_user(messages), tools, kwargs + + +# ------------------------------------------------------------------------------------------------ output parser +@dataclass +class ToolCall: + name: str + arguments: dict + id: str = field(default_factory=lambda: "call_" + uuid.uuid4().hex[:24]) + + +@dataclass +class Event: + kind: str # "reasoning" | "content" | "tool_call" + text: str = "" + call: ToolCall | None = None + + +THINK_END = "" +CALL_START = "" +CALL_END = "" + + +PARAM_END = "" +FUNC_END = "" + + +def param_end(text: str, final: bool = False) -> int: + """Where a parameter value in `text` ends: the first `` followed (after whitespace) by the next + `` - the same text inside a value (a file that documents the call format, #210) is + part of the value. -1: none yet; -2: a candidate whose follower has not arrived (streaming; `final` accepts it).""" + at = text.find(PARAM_END) + while at >= 0: + after = text[at + len(PARAM_END):].lstrip() + if after.startswith(("` after the call's own ``, found by walking + its parameters with param_end, so a value may contain either tag. -1: not complete yet. A body that is not in + the call format ends at the first ``, as before.""" + s = text.lstrip() + pos = len(text) - len(s) + if not s.startswith("", pos) + if gt < 0: + return -1 + pos = gt + 1 + while True: + rest = text[pos:] + s = rest.lstrip() + pos += len(rest) - len(s) + if s.startswith("", pos) + if gt < 0: + return -1 + end = param_end(text[gt + 1:]) + if end < 0: + return -1 + pos = gt + 1 + end + len(PARAM_END) + elif s.startswith(FUNC_END): + rest = text[pos + len(FUNC_END):] + s = rest.lstrip() + if s.startswith(CALL_END): + return pos + len(FUNC_END) + len(rest) - len(s) + return -1 if CALL_END.startswith(s) else text.find(CALL_END, pos) + elif not s or " ToolCall: + """`\\n\\nVALUE\\n...` -> ToolCall. Values are JSON-decoded + when the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON + objects/arrays/numbers/booleans).""" + body = body.strip() + if not body.startswith("" not in body: + raise ValueError("malformed tool call: " + body[:80]) + name = body[len("")] + rest = body[body.index(">") + 1:] + props = ((schema or {}).get("parameters") or {}).get("properties") or {} + args = {} + while "")] + rest = rest[rest.index(">") + 1:] + end = param_end(rest, final=True) + value = rest[:end] if end >= 0 else rest + rest = rest[end + len(PARAM_END):] if end >= 0 else "" + if value.startswith("\n"): + value = value[1:] + if value.endswith("\n"): + value = value[:-1] + declared = (props.get(pname) or {}).get("type") + if declared == "string": + args[pname] = value + else: + try: + args[pname] = json.loads(value) + except ValueError: + args[pname] = value + return ToolCall(name=name, arguments=args) + + +class OutputParser: + """Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held back + until it is complete, so clients never see ` between -> str|raw -> ... -> done + self.scall = None # the ToolCall being streamed (its id is reused by the final event) + self.sfirst = True + self.sval_started = False + self.sdeclared = {} + + def _scan(self) -> list[Event]: + """Advance the streaming view of the call body in self.buf (see stream_tools).""" + out = [] + + def args(s): + if s: + out.append(Event("tool_args", s, call=self.scall)) + while True: + rest = self.buf[self.sp:] + if self.ss == "name": + a = rest.find("", a + 10) if a >= 0 else -1 + if b < 0: + return out + name = rest[a + 10:b] + self.scall = ToolCall(name=name, arguments={}) + props = ((self.schemas.get(name) or {}).get("parameters") or {}).get("properties") or {} + self.sdeclared = {k: (v or {}).get("type") for k, v in props.items()} + out.append(Event("tool_start", call=self.scall)) + args("{") + self.sp += b + 1 + self.ss = "between" + elif self.ss == "between": + stripped = rest.lstrip() + self.sp += len(rest) - len(stripped) + if stripped.startswith("") + if b < 0: + return out + pname = stripped[11:b] + args(("" if self.sfirst else ",") + json.dumps(pname) + ":") + self.sfirst = False + self.sp += b + 1 + if self.sdeclared.get(pname) == "string": + args('"') + self.ss, self.sval_started = "str", False + else: + self.ss = "raw" + elif stripped.startswith(""): + args("}") + self.sp += len("") + self.ss = "done" + else: + return out # a tag still arriving (or trailing text): wait + elif self.ss == "str": + if not self.sval_started: + if not rest: + return out + if rest[0] == "\n": # the value's leading newline is not part of it + self.sp += 1 + rest = rest[1:] + self.sval_started = True + end = param_end(rest) + if end >= 0: + value = rest[:end] + if value.endswith("\n"): + value = value[:-1] + args(json.dumps(value)[1:-1] + '"') + self.sp += end + len(PARAM_END) + self.ss = "between" + continue + # an undecided (-2) is held from its start, like a tag still arriving + safe = rest.find(PARAM_END) if end == -2 else len(rest) - self._hold(rest, (PARAM_END,)) + if safe > 0 and rest[safe - 1] == "\n": # may be the trailing newline before + safe -= 1 + if safe > 0: + args(json.dumps(rest[:safe])[1:-1]) + self.sp += safe + return out + elif self.ss == "raw": + end = param_end(rest) + if end < 0: + return out + value = rest[:end] + if value.startswith("\n"): + value = value[1:] + if value.endswith("\n"): + value = value[:-1] + try: + v = json.loads(value) + except ValueError: + v = value + args(json.dumps(v, ensure_ascii=False)) + self.sp += end + len(PARAM_END) + self.ss = "between" + else: + return out + + def _close_scan(self) -> list[Event]: + """A streamed call that ended without a clean : close its JSON so clients can still parse it.""" + out = [] + if self.scall is None or self.ss == "done": + return out + tail = "" + if self.ss == "str": + tail += '"' + elif self.ss == "raw": + tail += json.dumps(self.buf[self.sp:].strip("\n")) + tail += "}" + out.append(Event("tool_args", tail, call=self.scall)) + self.ss = "done" + return out + + def _hold(self, text: str, tags: tuple[str, ...]) -> int: + """Length of the longest suffix of `text` that is a proper prefix of one of `tags`.""" + best = 0 + for tag in tags: + for n in range(1, len(tag)): + if text.endswith(tag[:n]): + best = max(best, n) + return best + + def feed(self, delta: str) -> list[Event]: + self.buf += delta + out: list[Event] = [] + while True: + if self.state == "reasoning": + i = self.buf.find(THINK_END) + if i < 0: + keep = self._hold(self.buf, (THINK_END,)) + if len(self.buf) > keep: + out.append(Event("reasoning", self.buf[:len(self.buf) - keep])) + self.buf = self.buf[len(self.buf) - keep:] + return out + if i: + out.append(Event("reasoning", self.buf[:i])) + self.buf = self.buf[i + len(THINK_END):] + self.state, self.lead = "content", True + elif self.state == "content": + if self.lead: # newlines right after or a call + stripped = self.buf.lstrip("\n") + if not stripped: + self.buf = "" + return out + self.buf, self.lead = stripped, False + i = self.buf.find(CALL_START) + if i < 0: + # Hold a partial tag AND the newlines before it: if a tool call follows, they are dropped, + # so emitting them early would make streamed and whole outputs differ. + j = len(self.buf) - self._hold(self.buf, (CALL_START,)) + while j > 0 and self.buf[j - 1] == "\n": + j -= 1 + if j > 0: + out.append(Event("content", self.buf[:j])) + self.buf = self.buf[j:] + return out + if i and self.buf[:i].strip(): + out.append(Event("content", self.buf[:i].rstrip("\n"))) + self.buf = self.buf[i + len(CALL_START):] + self.state = "call" + else: + i = call_end(self.buf) + if self.stream_tools: + if i >= 0: + whole, self.buf = self.buf, self.buf[:i] # scan only the body + out += self._scan() + out += self._close_scan() + self.buf = whole + else: + out += self._scan() + if i < 0: + return out + body = self.buf[:i] + self.buf = self.buf[i + len(CALL_END):] + name = body.strip()[len("", 1)[0] + call = parse_tool_call(body, self.schemas.get(name)) + if self.scall is not None: + call.id = self.scall.id + out.append(Event("tool_call", call=call)) + self._reset_scan() + self.state, self.lead = "content", True + + def finish(self) -> list[Event]: + """End of generation: flush whatever is held (an unterminated tool call is returned as content; one that was + already announced stays unfinished: its JSON is not closed and no "tool_call" follows it, #211).""" + out = [] + if self.state == "call" and self.stream_tools and self.scall is not None: + out += self._scan() # the output ended inside a call that was already announced + if self.ss == "done": # only its is missing: the call itself is whole + out.append(Event("tool_call", call=self.scall)) + self.buf = "" + self._reset_scan() + return out + if self.buf: + kind = {"reasoning": "reasoning", "content": "content"}.get(self.state, "content") + text = self.buf if self.state != "call" else CALL_START + self.buf + out.append(Event(kind, text)) + self.buf = "" + return out diff --git a/serve/mcp.py b/serve/mcp.py new file mode 100644 index 0000000..4586e2c --- /dev/null +++ b/serve/mcp.py @@ -0,0 +1,676 @@ +"""serve/mcp.py - tools from MCP (Model Context Protocol) servers for the web app's chats. + +The user lists servers in the run config (`"mcp_servers"`, or Claude Desktop's `"mcpServers"` block pasted as is) or +in a separate file (`--mcp-config`). Each one is either a program Strata starts (`command`, `args`, `env`, `cwd`: +the stdio transport, newline-delimited JSON-RPC 2.0 on its stdin/stdout) or an address (`url`, `headers`: the +Streamable HTTP transport, JSON-RPC POSTed, answered as JSON or as an event stream). Both are implemented here with +the standard library only; no MCP SDK is needed. + +`McpHub` owns every configured server: it starts them in the background when the server starts, offers their tools to +the model as OpenAI function tools named `__` (two servers may both have a `search`), and routes a call +back to the server that has it. A server that does not start is left out with one log line; the chat works without +it. A server that stops later (a crash) is started again on its next call. + +Tool results reach the model as text: the MCP content blocks joined, capped at `max_result_chars` (a directory tree or +a web page can be megabytes, far more than a context holds) with a note saying so. A failed call - the tool's own +error, a crash, a timeout - becomes a result that starts with "error:", so the model can react instead of the chat +breaking. +""" +from __future__ import annotations + +import collections +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request + +from serve.winjob import contain + +PROTOCOL = "2025-06-18" # the MCP revision Strata asks for; the server's answer is used as given +DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0} + + +class McpError(RuntimeError): + """A server answered with an error, stopped, or could not be reached.""" + + +class McpTimeout(McpError): + pass + + +class McpCancelled(McpError): + """The chat was stopped while the call ran.""" + + +class _Slot: + """One request waiting for its response.""" + + def __init__(self): + self.done = threading.Event() + self.msg = None + self.error = None + + +def _wait(slot: _Slot, timeout: float, cancel: threading.Event | None, what: str): + """Wait for a response, checking the chat's stop button and the deadline a few times a second.""" + deadline = time.monotonic() + timeout + while not slot.done.wait(0.05): + if cancel is not None and cancel.is_set(): + raise McpCancelled("stopped") + if time.monotonic() > deadline: + raise McpTimeout(f"{what} timed out after {timeout:g} s") + if slot.error: + raise slot.error + msg = slot.msg + if "error" in msg: + err = msg["error"] if isinstance(msg["error"], dict) else {"message": str(msg["error"])} + raise McpError(f"{err.get('message') or 'error'} (code {err.get('code')})") + return msg.get("result") or {} + + +# ------------------------------------------------------------------------------------------------ transports +class StdioTransport: + """A server Strata starts: JSON-RPC messages one per line on its stdin and stdout; its stderr is its log.""" + kind = "stdio" + + def __init__(self, name: str, cfg: dict): + self.name, self.cfg = name, cfg + self.proc = None + self.lock = threading.Lock() # the pending requests + self.write_lock = threading.Lock() # stdin; separate, so a full pipe can't block the reader + self.pending: dict[int, _Slot] = {} + self.next_id = 0 + self.stderr = collections.deque(maxlen=40) # its last log lines, for the error message when it fails + self.protocol = PROTOCOL + + def start(self): + env = dict(os.environ) + env.update({str(k): str(v) for k, v in (self.cfg.get("env") or {}).items()}) + command = str(self.cfg["command"]) + # On Windows `npx`, `uvx` and friends are .cmd files that CreateProcess finds only with their extension + exe = shutil.which(command, path=env.get("PATH")) or command + extra = {} + if os.name == "nt": + extra["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0) + else: + extra["start_new_session"] = True # its own process group, so close() ends its children too + try: + self.proc = subprocess.Popen([exe, *[str(a) for a in self.cfg.get("args") or []]], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.cfg.get("cwd") or None, + env=env, **extra) + except OSError as e: + raise McpError(f"could not start {command!r}: {e}") from None + contain(self.proc) # ends with the server, however it ends (Windows) + self._err_reader = threading.Thread(target=self._read_stderr, daemon=True) + self._err_reader.start() + threading.Thread(target=self._read, daemon=True).start() + + def alive(self) -> bool: + return self.proc is not None and self.proc.poll() is None and not getattr(self, "ended", False) + + @staticmethod + def _lines(f): + """A pipe's lines until it closes (or close() closed it under us).""" + try: + yield from f + except (OSError, ValueError): + return + + def _read_stderr(self): + for raw in self._lines(self.proc.stderr): + line = raw.decode("utf-8", "replace").rstrip() + if line: + self.stderr.append(line) + if os.environ.get("STRATA_DEBUG"): + print(f"[mcp {self.name}] {line}", flush=True) + + def _read(self): + for raw in self._lines(self.proc.stdout): + line = raw.decode("utf-8", "replace").strip() + if not line: + continue + try: + msg = json.loads(line) + except ValueError: # a server that prints to stdout; the spec forbids it + self.stderr.append(line) + continue + for m in msg if isinstance(msg, list) else [msg]: + if isinstance(m, dict): + self._dispatch(m) + self.ended = True + # the server's last log line says why it stopped: let the stderr reader take it first (the pipe closes with + # the process), or the error raced it and said only "the server stopped" + self._err_reader.join(1.0) + code = self.proc.poll() + err = McpError(f"the server stopped{f' (exit code {code})' if code is not None else ''}{self._tail()}") + with self.lock: + slots, self.pending = list(self.pending.values()), {} + for s in slots: + s.error = err + s.done.set() + + def _tail(self) -> str: + return f": {self.stderr[-1][:300]}" if self.stderr else "" + + def _dispatch(self, m: dict): + if "method" in m: + if "id" in m: # a request from the server: we offer no client features + try: + if m["method"] == "ping": + self._send({"jsonrpc": "2.0", "id": m["id"], "result": {}}) + else: + self._send({"jsonrpc": "2.0", "id": m["id"], + "error": {"code": -32601, "message": f"method not supported: {m['method']}"}}) + except McpError: + pass + return # notifications (log messages, list changes): not used + with self.lock: + slot = self.pending.pop(m.get("id"), None) + if slot is not None: # an answer to a call that timed out is simply dropped + slot.msg = m + slot.done.set() + + def _send(self, msg: dict): + data = json.dumps(msg, ensure_ascii=False).encode("utf-8") + b"\n" + try: + with self.write_lock: + self.proc.stdin.write(data) + self.proc.stdin.flush() + except (OSError, ValueError): + raise McpError(f"the server stopped{self._tail()}") from None + + def request(self, method: str, params: dict, timeout: float, cancel=None): + if not self.alive(): + raise McpError(f"the server is not running{self._tail()}") + slot = _Slot() + with self.lock: + self.next_id += 1 + rid = self.next_id + self.pending[rid] = slot + try: + self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}) + return _wait(slot, timeout, cancel, method) + except (McpTimeout, McpCancelled) as e: + with self.lock: + self.pending.pop(rid, None) + try: # tell the server to stop working on it + self.notify("notifications/cancelled", {"requestId": rid, "reason": str(e)}) + except McpError: + pass + raise + + def notify(self, method: str, params: dict | None = None): + self._send({"jsonrpc": "2.0", "method": method, **({"params": params} if params is not None else {})}) + + def close(self): + """As the spec says: close its stdin, give it a moment to exit, then end it (and what it started).""" + p = self.proc + if p is None: + return + try: + p.stdin.close() + except OSError: + pass + try: + p.wait(timeout=2) + except subprocess.TimeoutExpired: + self._kill_tree(p) + for f in (p.stdout, p.stderr): + try: + f.close() + except OSError: + pass + + @staticmethod + def _kill_tree(p): + try: + if os.name == "nt": # npx.cmd -> node: end the whole tree + subprocess.run(["taskkill", "/PID", str(p.pid), "/T", "/F"], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=10) + else: + os.killpg(p.pid, signal.SIGTERM) + try: + p.wait(timeout=2) + except subprocess.TimeoutExpired: + os.killpg(p.pid, signal.SIGKILL) + except (OSError, subprocess.SubprocessError): + pass + try: + p.kill() + except OSError: + pass + + +class HttpTransport: + """A server at an address (Streamable HTTP): every message is a POST; the answer is JSON or an event stream that + carries it. The session id the server hands out at `initialize` rides on every later request.""" + kind = "http" + + def __init__(self, name: str, cfg: dict): + self.name, self.url = name, str(cfg["url"]) + self.headers = {str(k): str(v) for k, v in (cfg.get("headers") or {}).items()} + self.session = None + self.protocol = None # sent as MCP-Protocol-Version once negotiated + self.next_id = 0 + self.lock = threading.Lock() + self.broken = None + + def start(self): + pass + + def alive(self) -> bool: + return self.broken is None + + def _headers(self) -> dict: + h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "strata", **self.headers} + if self.session: + h["Mcp-Session-Id"] = self.session + if self.protocol: + h["MCP-Protocol-Version"] = self.protocol + return h + + def _post(self, msg: dict, rid, timeout: float, slot: _Slot | None): + try: + req = urllib.request.Request(self.url, data=json.dumps(msg, ensure_ascii=False).encode("utf-8"), + headers=self._headers(), method="POST") + with urllib.request.urlopen(req, timeout=timeout) as r: + if r.headers.get("Mcp-Session-Id"): + self.session = r.headers["Mcp-Session-Id"] + if slot is None: # a notification: 202, nothing to read + return + ctype = r.headers.get("Content-Type", "") + if "text/event-stream" in ctype: + found = self._from_events(r, rid) + else: + body = r.read() + found = None + parsed = json.loads(body) if body.strip() else None + for m in parsed if isinstance(parsed, list) else [parsed]: + if isinstance(m, dict) and m.get("id") == rid and "method" not in m: + found = m + if found is None: + raise McpError("the server's answer did not contain a response") + slot.msg = found + except urllib.error.HTTPError as e: + detail = "" + try: + detail = e.read().decode("utf-8", "replace")[:300] + except OSError: + pass + if e.code == 404 and self.session: # the session expired: a restart starts a new one + self.broken = McpError("the server ended the session") + err = McpError(f"HTTP {e.code} {e.reason}{': ' + detail if detail else ''}") + if slot is None: + raise err from None + slot.error = err + except (OSError, ValueError, McpError) as e: + err = e if isinstance(e, McpError) else McpError(f"could not reach {self.url}: {e}") + if slot is None: + raise err from None + slot.error = err + finally: + if slot is not None: + slot.done.set() + + @staticmethod + def _from_events(r, rid): + """Read the event stream until the event that answers `rid` (it may carry notifications first).""" + data = [] + for raw in r: + line = raw.decode("utf-8", "replace").rstrip("\r\n") + if line.startswith("data:"): + data.append(line[5:].lstrip(" ")) + elif not line and data: + try: + m = json.loads("\n".join(data)) + except ValueError: + m = None + data = [] + for x in m if isinstance(m, list) else [m]: + if isinstance(x, dict) and x.get("id") == rid and "method" not in x: + return x + return None + + def request(self, method: str, params: dict, timeout: float, cancel=None): + if self.broken: + raise self.broken + with self.lock: + self.next_id += 1 + rid = self.next_id + slot = _Slot() + # the POST runs on its own thread so the stop button and the deadline are noticed while it waits + threading.Thread(target=self._post, args=({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}, + rid, timeout + 5, slot), daemon=True).start() + try: + return _wait(slot, timeout, cancel, method) + except (McpTimeout, McpCancelled) as e: + threading.Thread(target=self._quiet_notify, args=("notifications/cancelled", + {"requestId": rid, "reason": str(e)}), daemon=True).start() + raise + + def _quiet_notify(self, method, params): + try: + self.notify(method, params) + except McpError: + pass + + def notify(self, method: str, params: dict | None = None): + self._post({"jsonrpc": "2.0", "method": method, **({"params": params} if params is not None else {})}, + None, 10, None) + + def close(self): + if not self.session: + return + try: # end the session on the server (it may not allow that) + req = urllib.request.Request(self.url, headers=self._headers(), method="DELETE") + urllib.request.urlopen(req, timeout=3).close() + except (OSError, ValueError): + pass + + +# ------------------------------------------------------------------------------------------------ one server +class McpServer: + """One configured server: started once (and again after it stopped), with the tools it listed.""" + + def __init__(self, name: str, cfg: dict, settings: dict): + self.name, self.cfg, self.settings = name, cfg, settings + self.kind = "http" if cfg.get("url") else "stdio" + self.status = "idle" # idle -> starting -> ready | failed; ready -> stopped when it ends + self.error = None + self.tools: list[dict] = [] + self.info: dict = {} + self.transport = None + self.lock = threading.Lock() + self.last_start = 0.0 + + def start(self) -> bool: + with self.lock: + return self._start() + + def _start(self) -> bool: + if self.transport is not None: + self.transport.close() + self.status, self.error, self.last_start = "starting", None, time.monotonic() + t = HttpTransport(self.name, self.cfg) if self.kind == "http" else StdioTransport(self.name, self.cfg) + self.transport = t + timeout = float(self.settings["start_timeout_s"]) + try: + t.start() + res = t.request("initialize", {"protocolVersion": PROTOCOL, "capabilities": {}, + "clientInfo": {"name": "strata", "title": "Strata", "version": "1"}}, + timeout) + t.protocol = str(res.get("protocolVersion") or PROTOCOL) + self.info = {k: v for k, v in (res.get("serverInfo") or {}).items() if k in ("name", "title", "version")} + self.info["protocol"] = t.protocol + t.notify("notifications/initialized") + tools, cursor = [], None + for _ in range(100): # pages; a server that never stops paging is cut off + try: + page = t.request("tools/list", {"cursor": cursor} if cursor else {}, timeout) + except McpError as e: + if "code -32601" in str(e) and not tools: # a server without tools (prompts/resources only) + break + raise + tools += [x for x in page.get("tools") or [] if isinstance(x, dict) and x.get("name")] + cursor = page.get("nextCursor") + if not cursor: + break + self.tools, self.status = tools, "ready" + names = ", ".join(x["name"] for x in tools[:8]) + (", ..." if len(tools) > 8 else "") + print(f"[strata] MCP server {self.name!r}: {len(tools)} tool{'s' * (len(tools) != 1)}" + f"{' (' + names + ')' if tools else ''}", flush=True) + return True + except McpError as e: + self.status, self.error, self.tools = "failed", str(e), [] + t.close() + print(f"[strata] MCP server {self.name!r} did not start: {e}. Its tools are left out; the chat works " + "without them.", flush=True) + return False + + def call(self, tool: str, arguments: dict, timeout: float, cancel=None) -> dict: + with self.lock: + if self.transport is None or not self.transport.alive(): + # it stopped since its last call (a crash, an expired session): start it again; one that failed to + # start is tried again at most every 10 s, so a broken command does not run on every call + if self.status == "failed" and time.monotonic() - self.last_start < 10: + raise McpError(f"the server is not running ({self.error or 'it stopped'})") + print(f"[strata] MCP server {self.name!r} had stopped; starting it again", flush=True) + if not self._start(): + raise McpError(f"the server could not be started again: {self.error}") + t = self.transport + try: + return t.request("tools/call", {"name": tool, "arguments": arguments}, timeout, cancel) + except McpError as e: + if not t.alive(): + self.status, self.error = "stopped", str(e) + raise + + def close(self): + with self.lock: + if self.transport is not None: + self.transport.close() + if self.status in ("ready", "starting"): + self.status = "stopped" + + +# ------------------------------------------------------------------------------------------------ the hub +def result_text(result: dict) -> str: + """An MCP tool result as the text the model reads: the text blocks as they are, other blocks named.""" + parts = [] + for block in result.get("content") or []: + if not isinstance(block, dict): + continue + kind = block.get("type") + if kind == "text": + parts.append(str(block.get("text", ""))) + elif kind == "resource": + res = block.get("resource") or {} + parts.append(str(res["text"]) if "text" in res else f"[resource {res.get('uri', '')} " + f"({res.get('mimeType', 'binary')}), not shown]") + elif kind == "resource_link": + parts.append(f"[resource link: {block.get('name') or ''} {block.get('uri', '')}]".replace(" ", " ")) + elif kind in ("image", "audio"): + size = len(block.get("data") or "") * 3 // 4 + parts.append(f"[{kind} ({block.get('mimeType', '?')}, {size:,} bytes): not shown to the model]") + else: + parts.append(json.dumps(block, ensure_ascii=False)) + if not parts and result.get("structuredContent") is not None: + parts.append(json.dumps(result["structuredContent"], ensure_ascii=False)) + return "\n".join(parts) + + +def _clean(name: str) -> str: + return re.sub(r"[^A-Za-z0-9_-]", "_", str(name)) or "x" + + +class McpHub: + """Every configured server, and the merged, namespaced tool list the model sees.""" + + def __init__(self, servers: dict[str, dict], settings: dict | None = None): + self.settings = {**DEFAULTS, **(settings or {})} + self.servers = {name: McpServer(name, cfg, self.settings) for name, cfg in servers.items()} + self.threads: list[threading.Thread] = [] + self._routes: dict[str, tuple[McpServer, str]] = {} + + def start(self, wait: bool = False): + """Start every server on its own thread (npx may download a package first: that must not delay the chat).""" + self.threads = [threading.Thread(target=s.start, daemon=True, name=f"mcp-{s.name}") + for s in self.servers.values()] + for t in self.threads: + t.start() + if wait: + self.wait(None) + + def wait(self, timeout: float | None) -> None: + """Wait (up to `timeout` s in all) for servers that are still starting.""" + end = None if timeout is None else time.monotonic() + timeout + for t in self.threads: + t.join(None if end is None else max(0.0, end - time.monotonic())) + + def routes(self) -> dict[str, tuple[McpServer, str]]: + """tool name the model sees -> (server, the tool's own name). A server that stopped after it was ready keeps + its tools here: a call starts it again.""" + out = {} + for s in self.servers.values(): + if s.status not in ("ready", "stopped"): + continue + for t in s.tools: + name = f"{_clean(s.name)}__{_clean(t['name'])}"[:64] + n = 2 + while name in out: # two names that differ only in cleaned characters + name = f"{name[:60]}_{n}" + n += 1 + out[name] = (s, t["name"]) + self._routes = out + return out + + def template_tools(self, exclude=()) -> list[dict]: + """The tools in the chat template's form ({name, description, parameters}); `exclude`: names the request + brought itself (those win).""" + out = [] + for name, (s, tool) in self.routes().items(): + if name in exclude: + continue + t = next(x for x in s.tools if x["name"] == tool) + schema = t.get("inputSchema") if isinstance(t.get("inputSchema"), dict) else {} + out.append({"name": name, "description": str(t.get("description") or t.get("title") or ""), + "parameters": schema or {"type": "object", "properties": {}}}) + return out + + def openai_tools(self) -> list[dict]: + return [{"type": "function", "function": t} for t in self.template_tools()] + + def call(self, name: str, arguments: dict, cancel: threading.Event | None = None) -> dict: + """Run one tool -> {"ok", "text" (what the model reads, capped), "chars" (its full length), "truncated", + "ms", "server", "tool"}. Errors become text starting with "error:"; only McpCancelled is raised.""" + t0 = time.monotonic() + server, tool = self._routes.get(name) or self.routes().get(name, (None, name)) + out = {"server": server.name if server else None, "tool": tool} + if server is None: + text, ok = f"error: there is no tool named {name!r}", False + else: + try: + res = server.call(tool, arguments if isinstance(arguments, dict) else {}, + float(self.settings["timeout_s"]), cancel) + text, ok = result_text(res), not res.get("isError") + if not ok: + text = "error: " + (text or "the tool reported an error") + except McpCancelled: + raise + except McpError as e: + text, ok = f"error: {e}", False + cap = int(self.settings["max_result_chars"]) + full = len(text) + if cap > 0 and full > cap: + text = text[:cap] + (f"\n\n[... truncated: the tool returned {full:,} characters; only the first " + f"{cap:,} are shown]") + out.update(ok=ok, text=text, chars=full, truncated=cap > 0 and full > cap, + ms=int((time.monotonic() - t0) * 1000)) + return out + + def status(self) -> dict: + """GET /mcp: every server, its state and its tools (for the web app).""" + routes = self.routes() + servers = [] + for s in self.servers.values(): + names = {tool: n for n, (srv, tool) in routes.items() if srv is s} + servers.append({"name": s.name, "transport": s.kind, "status": s.status, "error": s.error, + "info": s.info, + "tools": [{"name": names.get(t["name"], t["name"]), "tool": t["name"], + "description": str(t.get("description") or "")[:300]} for t in s.tools]}) + return {"servers": servers, "tools": len(routes), + "settings": {k: self.settings[k] for k in ("timeout_s", "max_result_chars", "max_rounds")}} + + def close(self): + for s in self.servers.values(): + try: + s.close() + except Exception: # noqa: BLE001 - closing is best effort + pass + + +# ------------------------------------------------------------------------------------------------ config +def _check_server(name, cfg, where) -> dict: + if not isinstance(cfg, dict): + raise SystemExit(f"[strata] {where}: MCP server {name!r} must be an object with \"command\" or \"url\"") + if cfg.get("url"): + if cfg.get("type") == "sse": + raise SystemExit(f"[strata] {where}: MCP server {name!r} uses the old SSE transport (\"type\": \"sse\"); " + "Strata speaks Streamable HTTP - most servers offer it at /mcp") + if not isinstance(cfg.get("headers") or {}, dict): + raise SystemExit(f"[strata] {where}: MCP server {name!r}: \"headers\" must be an object") + return cfg + if not isinstance(cfg.get("command"), str) or not cfg["command"].strip(): + raise SystemExit(f"[strata] {where}: MCP server {name!r} needs \"command\" (a program to start) or \"url\"") + if not isinstance(cfg.get("args") or [], list): + raise SystemExit(f"[strata] {where}: MCP server {name!r}: \"args\" must be a list") + if not isinstance(cfg.get("env") or {}, dict): + raise SystemExit(f"[strata] {where}: MCP server {name!r}: \"env\" must be an object") + return cfg + + +def servers_from(block, where: str) -> dict[str, dict]: + """{"name": {...}} with the entries checked; `"disabled": true` leaves one out.""" + if block is None: + return {} + if not isinstance(block, dict): + raise SystemExit(f"[strata] {where}: the MCP servers must be an object {{\"name\": {{...}}}}") + return {str(n): _check_server(n, c, where) for n, c in block.items() + if not (isinstance(c, dict) and c.get("disabled") is True)} + + +def settings_from(cfg: dict) -> dict: + """The run config's optional `"mcp"` block: timeout_s, max_result_chars, max_rounds, start_timeout_s.""" + out = {} + for key, value in (cfg.get("mcp") or {}).items(): + number = isinstance(value, (int, float)) and not isinstance(value, bool) + if key in ("timeout_s", "start_timeout_s"): + if not number or value <= 0: + raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a number of seconds > 0") + out[key] = float(value) + elif key in ("max_result_chars", "max_rounds"): + if not number or value != int(value) or value < 1: + raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a positive integer") + out[key] = int(value) + else: + print(f"[strata] config mcp.{key}={value!r}: unknown key, ignored", flush=True) + return out + + +def hub_from_config(cfg: dict, mcp_config_path: str | None = None) -> McpHub | None: + """The run config's `"mcp_servers"` (or `"mcpServers"`) plus the servers in the --mcp-config file (Claude + Desktop's format: {"mcpServers": {...}}); a name in both takes the file's entry. None when there are none.""" + servers = {} + servers.update(servers_from(cfg.get("mcp_servers"), "config mcp_servers")) + servers.update(servers_from(cfg.get("mcpServers"), "config mcpServers")) + if mcp_config_path: + try: + with open(mcp_config_path, encoding="utf-8-sig") as f: + data = json.load(f) + except (OSError, ValueError) as e: + raise SystemExit(f"[strata] --mcp-config {mcp_config_path}: {e}") from None + block = data.get("mcpServers", data.get("mcp_servers")) if isinstance(data, dict) else None + if block is None: + raise SystemExit(f"[strata] --mcp-config {mcp_config_path}: expected {{\"mcpServers\": {{...}}}}") + servers.update(servers_from(block, f"--mcp-config {mcp_config_path}")) + if not servers: + return None + return McpHub(servers, settings_from(cfg)) + + +if __name__ == "__main__": # python -m serve.mcp config.json: list what a config offers + hub = hub_from_config(json.load(open(sys.argv[1], encoding="utf-8-sig")) if len(sys.argv) > 1 else {}, + sys.argv[2] if len(sys.argv) > 2 else None) + if hub is None: + sys.exit("no MCP servers configured") + hub.start(wait=True) + print(json.dumps(hub.status(), indent=1)) + hub.close() diff --git a/serve/mcp_fake_server.py b/serve/mcp_fake_server.py new file mode 100644 index 0000000..c4200b0 --- /dev/null +++ b/serve/mcp_fake_server.py @@ -0,0 +1,172 @@ +"""serve/mcp_fake_server.py - a small MCP server for serve/test_mcp.py (no MCP SDK, no network beyond localhost). + + python serve/mcp_fake_server.py stdio: JSON-RPC lines on stdin/stdout + python serve/mcp_fake_server.py --http 8765 Streamable HTTP on 127.0.0.1:8765/mcp + +Tools: echo (returns its text), fail (a tool error, isError), sleep (answers after `seconds`), big (`n` characters), +die (the process exits mid-call), add (two integers). tools/list pages two tools at a time (`--page N`), so the +client's pagination is exercised. `--crash-at-start` exits before answering anything. With FAKE_MCP_LOG set, the +server appends what it saw (calls, cancellations) to that file, one JSON line each. +""" +from __future__ import annotations + +import json +import os +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +TOOLS = [ + {"name": "echo", "description": "Returns the text it is given.", + "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}, + {"name": "fail", "description": "Always fails.", "inputSchema": {"type": "object", "properties": {}}}, + {"name": "sleep", "description": "Waits, then answers.", + "inputSchema": {"type": "object", "properties": {"seconds": {"type": "number"}}}}, + {"name": "big", "description": "Returns n characters.", + "inputSchema": {"type": "object", "properties": {"n": {"type": "integer"}}}}, + {"name": "die", "description": "Ends the server.", "inputSchema": {"type": "object", "properties": {}}}, + {"name": "add", "description": "Adds two integers.", + "inputSchema": {"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}}}, +] +PAGE = 2 +cancelled: set = set() + + +def log(event: dict): + path = os.environ.get("FAKE_MCP_LOG") + if path: + with open(path, "a", encoding="utf-8") as f: + f.write(json.dumps(event) + "\n") + + +def text(t, error=False): + return {"content": [{"type": "text", "text": t}], "isError": error} + + +def handle(msg: dict): + """-> the response for a request, None for a notification.""" + method, rid, params = msg.get("method"), msg.get("id"), msg.get("params") or {} + if "id" not in msg: + if method == "notifications/cancelled": + cancelled.add(params.get("requestId")) + log({"cancelled": params.get("requestId")}) + return None + if method == "initialize": + return {"jsonrpc": "2.0", "id": rid, "result": { + "protocolVersion": params.get("protocolVersion", "2025-06-18"), "capabilities": {"tools": {}}, + "serverInfo": {"name": "fake", "version": "0.1"}}} + if method == "tools/list": + start = int(params.get("cursor") or 0) + page = {"tools": TOOLS[start:start + PAGE]} + if start + PAGE < len(TOOLS): + page["nextCursor"] = str(start + PAGE) + return {"jsonrpc": "2.0", "id": rid, "result": page} + if method == "tools/call": + name, args = params.get("name"), params.get("arguments") or {} + log({"call": name, "arguments": args}) + if name == "echo": + result = text(str(args.get("text", ""))) + elif name == "fail": + result = text("it failed on purpose", error=True) + elif name == "sleep": + time.sleep(float(args.get("seconds", 1))) + result = text("slept") + elif name == "big": + result = text("y" * int(args.get("n", 100000))) + elif name == "die": + sys.stderr.write("dying on purpose\n") + sys.stderr.flush() + os._exit(3) + elif name == "add": + result = text(str(int(args.get("a", 0)) + int(args.get("b", 0)))) + else: + return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32602, "message": f"unknown tool {name}"}} + return {"jsonrpc": "2.0", "id": rid, "result": result} + return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": f"no method {method}"}} + + +def stdio(): + for f in (sys.stdin, sys.stdout, sys.stderr): # MCP's stdio is UTF-8, whatever the Windows code page is + f.reconfigure(encoding="utf-8") + out = threading.Lock() + + def answer(msg): + r = handle(msg) + if r is not None and msg.get("id") not in cancelled: + with out: + sys.stdout.write(json.dumps(r) + "\n") + sys.stdout.flush() + + for line in sys.stdin: + if not line.strip(): + continue + msg = json.loads(line) + if msg.get("method") == "tools/call": # calls on threads: a slow one must not block cancellation + threading.Thread(target=answer, args=(msg,), daemon=True).start() + else: + answer(msg) + + +def http_server(port: int = 0) -> ThreadingHTTPServer: + """Streamable HTTP at /mcp: JSON answers, except tools/call, which answers as an event stream (a progress + notification first); a session id from initialize is required afterwards.""" + sessions = set() + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.0" + + def log_message(self, *a): + pass + + def do_POST(self): + msg = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))) + if msg.get("method") != "initialize" and self.headers.get("Mcp-Session-Id") not in sessions: + self.send_response(400) + self.end_headers() + return + r = handle(msg) + if r is None: + self.send_response(202) + self.end_headers() + return + if msg.get("method") == "tools/call": + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + note = {"jsonrpc": "2.0", "method": "notifications/progress", "params": {"progress": 1}} + self.wfile.write(b"event: message\ndata: " + json.dumps(note).encode() + b"\n\n") + self.wfile.write(b"event: message\ndata: " + json.dumps(r).encode() + b"\n\n") + return + body = json.dumps(r).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + if msg.get("method") == "initialize": + sid = f"s-{len(sessions) + 1}" + sessions.add(sid) + self.send_header("Mcp-Session-Id", sid) + self.end_headers() + self.wfile.write(body) + + def do_DELETE(self): + sessions.discard(self.headers.get("Mcp-Session-Id")) + self.send_response(200) + self.end_headers() + + httpd = ThreadingHTTPServer(("127.0.0.1", port), H) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + return httpd + + +if __name__ == "__main__": + if "--page" in sys.argv: + PAGE = int(sys.argv[sys.argv.index("--page") + 1]) + if "--crash-at-start" in sys.argv: + sys.stderr.write("cannot start: missing configuration\n") + sys.exit(2) + if "--http" in sys.argv: + server = http_server(int(sys.argv[sys.argv.index("--http") + 1])) + print(f"listening on http://127.0.0.1:{server.server_address[1]}/mcp", flush=True) + threading.Event().wait() + stdio() diff --git a/serve/responses.py b/serve/responses.py new file mode 100644 index 0000000..4a017c3 --- /dev/null +++ b/serve/responses.py @@ -0,0 +1,538 @@ +"""serve/responses.py - #451: OpenAI's Responses API (POST /v1/responses), stateless, on the chat path. + +A Responses request becomes the same template messages, tools and kwargs a Chat Completions request does, runs through +the same Service.run, and its events (reasoning, text, tool calls) come back as Responses output items and typed SSE +events. Nothing is stored: the client sends the whole conversation in `input` every time (`store: false`, as Codex CLI +does), including the reasoning, message and function_call items of earlier answers. + +Codex CLI is the first client. What it needs, and what this does: + * `instructions` and `developer` messages -> the system message (leading ones merged, so the prompt start is stable + and the conversation cache holds across turns); + * function tools, also inside `namespace` tools (Codex's MCP and agent tools: the model sees `namespace.name`) and + `custom` tools (a free-form `input` string); hosted tools (web search, ...) are left out, the model cannot run them; + * reasoning items: the model's thinking is returned as `reasoning_text` content (no summaries: this model does not + write them, see docs/DETAILS.md) and, when `include` asks for `reasoning.encrypted_content`, also as an opaque + `encrypted_content` string (base64, not encrypted: the client already holds the text). Either form sent back is + put into the conversation again, so the prompt matches what the model wrote and the cache is reused; + * the official event order: response.created, response.in_progress, response.output_item.added, deltas, + ...done events, response.output_item.done, and response.completed / response.incomplete / response.failed. + +Based on #630 by CC-David-CC (the item/event assembler, namespace tools, call_id ordering of tool results). +""" +from __future__ import annotations + +import base64 +import copy +import json +import time +import uuid + +from serve.frontend import Event, _late_system_to_user, _parts_of, effort_kwargs + +ENCRYPTED_PREFIX = "strata.r1:" # our own reasoning replay strings; others' are ignored +HOSTED_TOOLS = ("web_search", "web_search_preview", "file_search", "computer_use_preview", "computer_use", + "code_interpreter", "image_generation", "local_shell", "mcp", "tool_search") + + +class ResponsesError(ValueError): + """A request error in the Responses format: {"error": {"message", "type", "param", "code"}}.""" + + def __init__(self, message, param=None, code=None, status=400, kind="invalid_request_error"): + super().__init__(message) + self.param, self.code, self.status, self.kind = param, code, status, kind + + def body(self): + return error_body(str(self), self.kind, self.param, self.code) + + +def error_body(message, kind="invalid_request_error", param=None, code=None) -> dict: + return {"error": {"message": message, "type": kind, "param": param, "code": code}} + + +def new_id(prefix: str) -> str: + return f"{prefix}_{uuid.uuid4().hex}" + + +# ------------------------------------------------------------------------------------------------ request -> chat +def _content(content, param): + """A message's (or a tool output's) content -> the template's form: a string, or text and image parts.""" + if content is None: + return "" + if isinstance(content, str): + return content + if not isinstance(content, list): + raise ResponsesError("expected a string or an array of content parts", param) + parts = [] + for j, part in enumerate(content): + if isinstance(part, str): + parts.append({"type": "text", "text": part}) + continue + if not isinstance(part, dict): + raise ResponsesError("expected a content part object", f"{param}[{j}]") + kind = part.get("type") + if kind in ("input_text", "output_text", "text", "summary_text", "reasoning_text"): + parts.append({"type": "text", "text": part.get("text") or ""}) + elif kind == "refusal": + parts.append({"type": "text", "text": part.get("refusal") or ""}) + elif kind in ("input_image", "image_url"): + if not part.get("image_url"): + raise ResponsesError("only images given as image_url (a data: or http(s) URL) are supported; " + "this server keeps no files", f"{param}[{j}]", "unsupported_parameter") + parts.append({"type": "input_image", "image_url": part["image_url"]}) + else: + raise ResponsesError(f"content parts of type {kind!r} are not supported (text and images are)", + f"{param}[{j}].type", "unsupported_parameter") + return _parts_of(parts) + + +def _reasoning_text(item, param) -> str: + """The thinking a reasoning item carries: its reasoning_text content, else our own encrypted_content. A summary + alone, or another server's encrypted_content, carries none that can go back into the prompt.""" + texts = [p.get("text") or "" for p in item.get("content") or [] if isinstance(p, dict) + and p.get("type") in ("reasoning_text", "text")] + if texts: + return "".join(texts) + enc = item.get("encrypted_content") + if isinstance(enc, str) and enc.startswith(ENCRYPTED_PREFIX): + try: + return json.loads(base64.b64decode(enc[len(ENCRYPTED_PREFIX):], validate=True).decode("utf-8"))["text"] + except (ValueError, KeyError, TypeError, UnicodeError): + raise ResponsesError("this reasoning item's encrypted_content is damaged", param + ".encrypted_content", + "invalid_encrypted_content") from None + return "" + + +def _arguments(raw, param) -> dict: + """A function_call's arguments (a JSON string) -> the mapping the template renders. Arguments that are not a JSON + object (a call the output ended inside) are kept as text rather than refusing the whole conversation.""" + if isinstance(raw, dict): + return raw + if raw is None or (isinstance(raw, str) and not raw.strip()): + return {} + if not isinstance(raw, str): + raise ResponsesError("function_call arguments must be a JSON string", param) + try: + value = json.loads(raw) + except ValueError: + return {"arguments": raw} + return value if isinstance(value, dict) else {"arguments": value} + + +def _tool_output(item, param): + out = item.get("output") + if isinstance(out, dict): # some clients send a JSON result as an object + return json.dumps(out, ensure_ascii=False) + return out if isinstance(out, str) else _content(out, param + ".output") + + +def input_messages(req: dict) -> list[dict]: + """`instructions` + `input` -> the chat template's messages.""" + messages = [] + instructions = req.get("instructions") + if instructions not in (None, ""): + messages.append({"role": "system", "content": _content(instructions, "instructions") + if not isinstance(instructions, str) else instructions}) + items = req.get("input") + if items is None: + raise ResponsesError("input is required: a string or an array of input items", "input", "missing_required_parameter") + if isinstance(items, str): + items = [{"type": "message", "role": "user", "content": items}] + if not isinstance(items, list): + raise ResponsesError("input must be a string or an array of input items", "input") + thinking = [] # reasoning waiting for the assistant turn it belongs to + open_turn = None # the assistant message the next function_call joins + + def turn(content=""): + nonlocal open_turn + open_turn = {"role": "assistant", "content": content} + if thinking: + open_turn["reasoning_content"] = "".join(thinking) + thinking.clear() + messages.append(open_turn) + return open_turn + + for i, item in enumerate(items): + param = f"input[{i}]" + if not isinstance(item, dict): + raise ResponsesError("expected an input item object", param) + kind = item.get("type") or ("message" if "role" in item else None) + if kind == "message": + role = item.get("role") + if role not in ("user", "assistant", "system", "developer"): + raise ResponsesError(f"unknown message role {role!r}", param + ".role") + content = _content(item.get("content"), param + ".content") + if role == "assistant": + turn(content if isinstance(content, str) else "".join( + p.get("text", "") for p in content if p.get("type") == "text")) + else: + open_turn = None + thinking.clear() + messages.append({"role": "system" if role == "developer" else role, "content": content}) + elif kind == "reasoning": + text = _reasoning_text(item, param) + if text: + if open_turn is not None and (open_turn.get("tool_calls") or open_turn["content"]): + open_turn = None # thinking starts a new model turn + thinking.append(text) + elif kind in ("function_call", "custom_tool_call"): + name = item.get("name") + if not isinstance(name, str) or not name: + raise ResponsesError("a function_call needs a name", param + ".name") + if item.get("namespace"): + name = f"{item['namespace']}.{name}" + if kind == "function_call": + args = _arguments(item.get("arguments"), param + ".arguments") + else: + args = {"input": item.get("input") if isinstance(item.get("input"), str) else ""} + target = open_turn if open_turn is not None and not thinking else turn() + target.setdefault("tool_calls", []).append({"function": {"name": name, "arguments": args}, + "_call_id": item.get("call_id")}) + elif kind in ("function_call_output", "custom_tool_call_output"): + messages.append({"role": "tool", "content": _tool_output(item, param), "_call_id": item.get("call_id")}) + open_turn = None + thinking.clear() + elif kind == "item_reference": + raise ResponsesError("item references need stored responses, and this server keeps none: send the items " + "themselves", param, "unsupported_parameter") + else: + raise ResponsesError(f"input items of type {kind!r} are not supported", param + ".type", + "unsupported_parameter") + _order_tool_results(messages) + # leading system/developer messages (Codex: instructions, then its developer message) become one system message + # at the start; later ones become user messages in place, as on the chat path + lead = 0 + while lead < len(messages) and messages[lead]["role"] == "system" and isinstance(messages[lead]["content"], str): + lead += 1 + if lead > 1: + messages[:lead] = [{"role": "system", "content": "\n\n".join(m["content"] for m in messages[:lead])}] + return _late_system_to_user(messages) + + +def _order_tool_results(messages): + """The template places tool results by position: each run of tool messages is put in the order of the calls of + the assistant turn before it (a client may send the results in the order they finished), then the private call + ids are dropped.""" + i = 0 + while i < len(messages): + if messages[i]["role"] != "tool": + i += 1 + continue + j = i + while j < len(messages) and messages[j]["role"] == "tool": + j += 1 + prev = messages[i - 1] if i else {} + order = [c.get("_call_id") for c in prev.get("tool_calls") or []] + rank = {cid: k for k, cid in enumerate(order) if cid} + messages[i:j] = sorted(messages[i:j], key=lambda m: rank.get(m.get("_call_id"), len(order))) + i = j + for m in messages: + m.pop("_call_id", None) + for c in m.get("tool_calls") or []: + c.pop("_call_id", None) + + +def request_tools(req: dict): + """-> (template tools or None, {template name: (namespace, name, kind)}, names of hosted tools left out).""" + tools, names, skipped = [], {}, [] + given = req.get("tools") or [] + if not isinstance(given, list): + raise ResponsesError("tools must be an array", "tools") + + def add(tool, param, namespace=None, ns_description=""): + kind = tool.get("type") + name = tool.get("name") + if not isinstance(name, str) or not name: + raise ResponsesError("a tool needs a name", param + ".name") + flat = f"{namespace}.{name}" if namespace else name + description = tool.get("description") or "" + if ns_description: + description = ns_description + ("\n\n" + description if description else "") + if kind == "function": + params = tool.get("parameters") or {"type": "object", "properties": {}} + else: # custom: free-form text, maybe in a grammar the model reads + fmt = tool.get("format") or {} + if isinstance(fmt, dict) and fmt.get("type") == "grammar" and fmt.get("definition"): + description += f"\n\nThe input must follow this {fmt.get('syntax', '')} grammar:\n{fmt['definition']}" + params = {"type": "object", "properties": {"input": {"type": "string", "description": "the raw input"}}, + "required": ["input"]} + tools.append({"name": flat, "description": description, "parameters": params}) + names[flat] = (namespace, name, kind) + + for i, tool in enumerate(given): + param = f"tools[{i}]" + if not isinstance(tool, dict): + raise ResponsesError("expected a tool object", param) + kind = tool.get("type") + if kind in ("function", "custom"): + add(tool, param) + elif kind == "namespace": + for j, member in enumerate(tool.get("tools") or []): + if not isinstance(member, dict) or member.get("type", "function") not in ("function", "custom"): + raise ResponsesError("a namespace holds function tools", f"{param}.tools[{j}]") + add({"type": "function", **member}, f"{param}.tools[{j}]", tool.get("name"), + tool.get("description") or "") + elif kind in HOSTED_TOOLS or isinstance(kind, str): + skipped.append(kind) # the model cannot run OpenAI's hosted tools: left out + else: + raise ResponsesError("a tool needs a type", param + ".type") + choice = req.get("tool_choice") + if choice == "none": + return None, names, skipped + return tools or None, names, skipped + + +def text_format(req: dict): + """`text.format` -> the chat path's response_format (None: plain text).""" + text = req.get("text") + if text is None: + return None + if not isinstance(text, dict): + raise ResponsesError("text must be an object", "text") + fmt = text.get("format") + if fmt is None: + return None + if not isinstance(fmt, dict): + raise ResponsesError("text.format must be an object", "text.format") + kind = fmt.get("type") + if kind in (None, "text"): + return None + if kind == "json_object": + return {"type": "json_object"} + if kind == "json_schema": + spec = {k: fmt[k] for k in ("name", "schema", "strict", "description") if k in fmt} + return {"type": "json_schema", "json_schema": spec} + raise ResponsesError("text.format.type must be text, json_object or json_schema", "text.format.type") + + +def check_request(req: dict) -> None: + """What this stateless server cannot do, refused before anything runs.""" + if req.get("previous_response_id"): + raise ResponsesError("this server keeps no responses (stateless): send the whole conversation in input " + "instead of previous_response_id", "previous_response_id", "unsupported_parameter") + if req.get("conversation"): + raise ResponsesError("this server keeps no conversations (stateless): send the whole conversation in input", + "conversation", "unsupported_parameter") + if req.get("background"): + raise ResponsesError("background responses are not supported: use stream or wait for the answer", + "background", "unsupported_parameter") + if req.get("prompt"): + raise ResponsesError("stored prompt templates are not supported: send instructions and input", + "prompt", "unsupported_parameter") + n = req.get("max_output_tokens") + if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n < 1): + raise ResponsesError("max_output_tokens must be a positive whole number", "max_output_tokens") + reasoning = req.get("reasoning") + if reasoning is not None and not isinstance(reasoning, dict): + raise ResponsesError("reasoning must be an object", "reasoning") + + +def template_kwargs(req: dict, shared: dict) -> dict: + effort = (req.get("reasoning") or {}).get("effort") + if effort is None: + effort = shared.get("reasoning_effort") # the Chat settings shared with apps, as on the chat path + try: + return effort_kwargs(effort) + except ValueError as e: + raise ResponsesError(str(e), "reasoning.effort") from None + + +# ------------------------------------------------------------------------------------------------ output +class Assembler: + """One response: its output items and its typed events, built from Service.run's events. The non-streaming + answer is the `response` of the last event, so both modes are the same items.""" + + def __init__(self, req: dict, model: str, prompt_tokens: int, names: dict, encrypted: bool, + json_mode: bool = False): + self.names, self.encrypted, self.json_mode = names, encrypted, json_mode + self.prompt_tokens = prompt_tokens + self.seq = 0 + self.item = None # the open output item + self.json_text = [] # structured output: the answer, held until it is checked + reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {} + self.response = { + "id": new_id("resp"), "object": "response", "created_at": int(time.time()), "status": "in_progress", + "background": False, "error": None, "incomplete_details": None, + "instructions": req.get("instructions"), "max_output_tokens": req.get("max_output_tokens"), + "model": model, "output": [], "parallel_tool_calls": req.get("parallel_tool_calls", True), + "previous_response_id": None, + "reasoning": {"effort": reasoning.get("effort"), "summary": reasoning.get("summary")}, + "store": False, "temperature": req.get("temperature"), + "text": req.get("text") if isinstance(req.get("text"), dict) else {"format": {"type": "text"}}, + "tool_choice": req.get("tool_choice", "auto"), "tools": req.get("tools") or [], + "top_p": req.get("top_p"), "truncation": "disabled", "usage": None, "user": None, + "metadata": req.get("metadata") or {}} + + # --- events + def event(self, kind, **data) -> dict: + e = {"type": kind, "sequence_number": self.seq, **data} + self.seq += 1 + return e + + def snapshot(self) -> dict: + return copy.deepcopy(self.response) + + def start(self) -> list[dict]: + return [self.event("response.created", response=self.snapshot()), + self.event("response.in_progress", response=self.snapshot())] + + def in_progress(self) -> dict: + """A keep-alive a client counts as activity (SSE comments are not events: Codex's idle timer ignores them).""" + return self.event("response.in_progress", response=self.snapshot()) + + def _open(self, item) -> list[dict]: + self.response["output"].append(item) + self.item = item + out = [self.event("response.output_item.added", output_index=self.index, item=copy.deepcopy(item))] + if item["type"] == "message": + part = {"type": "output_text", "text": "", "annotations": [], "logprobs": []} + item["content"].append(part) + out.append(self.event("response.content_part.added", item_id=item["id"], output_index=self.index, + content_index=0, part=copy.deepcopy(part))) + return out + + @property + def index(self) -> int: + return len(self.response["output"]) - 1 + + def close(self, status="completed") -> list[dict]: + item, self.item = self.item, None + if item is None: + return [] + at, out = self.response["output"].index(item), [] + item["status"] = status + if item["type"] == "message": + part = item["content"][0] + out += [self.event("response.output_text.done", item_id=item["id"], output_index=at, content_index=0, + text=part["text"], logprobs=[]), + self.event("response.content_part.done", item_id=item["id"], output_index=at, content_index=0, + part=copy.deepcopy(part))] + elif item["type"] == "reasoning": + text = item["content"][0]["text"] + out.append(self.event("response.reasoning_text.done", item_id=item["id"], output_index=at, + content_index=0, text=text)) + if self.encrypted: + item["encrypted_content"] = ENCRYPTED_PREFIX + base64.b64encode( + json.dumps({"text": text}, ensure_ascii=False).encode("utf-8")).decode("ascii") + elif item["type"] == "function_call": + out.append(self.event("response.function_call_arguments.done", item_id=item["id"], output_index=at, + name=item["name"], arguments=item["arguments"])) + elif item["type"] == "custom_tool_call": + out.append(self.event("response.custom_tool_call_input.done", item_id=item["id"], output_index=at, + input=item["input"])) + out.append(self.event("response.output_item.done", output_index=at, item=copy.deepcopy(item))) + return out + + def feed(self, ev: Event) -> list[dict]: + out = [] + kind = ev.kind + if kind == "reasoning": + if not ev.text: + return out + if self.item is None or self.item["type"] != "reasoning": + out += self.close() + out += self._open({"id": new_id("rs"), "type": "reasoning", "status": "in_progress", "summary": [], + "content": [{"type": "reasoning_text", "text": ""}]}) + self.item["content"][0]["text"] += ev.text + out.append(self.event("response.reasoning_text.delta", item_id=self.item["id"], output_index=self.index, + content_index=0, delta=ev.text)) + elif kind == "content": + if not ev.text: + return out + if self.json_mode: # sent once it is checked (finish) + out += self.close() + self.json_text.append(ev.text) + return out + if self.item is None or self.item["type"] != "message": + out += self.close() + out += self._open({"id": new_id("msg"), "type": "message", "status": "in_progress", + "role": "assistant", "content": []}) + self.item["content"][0]["text"] += ev.text + out.append(self.event("response.output_text.delta", item_id=self.item["id"], output_index=self.index, + content_index=0, delta=ev.text, logprobs=[])) + elif kind == "tool_start": + out += self.close() + out += self._open(self._call_item(ev)) + elif kind == "tool_args": + item = self.item + if item is None or item.get("call_id") != ev.call.id: + return out + if item["type"] == "function_call": # a custom tool's input is sent whole, at its end + item["arguments"] += ev.text + out.append(self.event("response.function_call_arguments.delta", item_id=item["id"], + output_index=self.index, delta=ev.text)) + elif kind == "tool_call": + item = self.item + if item is None or item.get("call_id") != ev.call.id: # a call that was not announced while written + out += self.close() + out += self._open(self._call_item(ev)) + item = self.item + if item["type"] == "function_call": + item["arguments"] = json.dumps(ev.call.arguments, ensure_ascii=False) + out.append(self.event("response.function_call_arguments.delta", item_id=item["id"], + output_index=self.index, delta=item["arguments"])) + if item["type"] == "custom_tool_call": + value = ev.call.arguments.get("input") if isinstance(ev.call.arguments, dict) else None + item["input"] = value if isinstance(value, str) else json.dumps(ev.call.arguments, ensure_ascii=False) + out.append(self.event("response.custom_tool_call_input.delta", item_id=item["id"], + output_index=self.index, delta=item["input"])) + out += self.close() + return out + + def _call_item(self, ev: Event) -> dict: + namespace, name, kind = self.names.get(ev.call.name, (None, ev.call.name, "function")) + if kind == "custom": + item = {"id": new_id("ctc"), "type": "custom_tool_call", "status": "in_progress", "call_id": ev.call.id, + "name": name, "input": ""} + else: + item = {"id": new_id("fc"), "type": "function_call", "status": "in_progress", "call_id": ev.call.id, + "name": name, "arguments": ""} + if namespace: + item["namespace"] = namespace + return item + + def finish(self, done: dict, validate=None) -> list[dict]: + """The end: close what is open, then response.completed (or .incomplete when max_output_tokens ran out). + `validate(text, finish)` checks a structured answer and returns its text (or raises).""" + length = done.get("finish") == "length" + # a call still open was cut off (its tool_call never came, #211): incomplete, whatever the finish + unfinished = self.item is not None and self.item["type"] in ("function_call", "custom_tool_call") + out = self.close("incomplete" if length or unfinished else "completed") + if self.json_mode: + text = validate("".join(self.json_text), done.get("finish")) + out += self._open({"id": new_id("msg"), "type": "message", "status": "in_progress", "role": "assistant", + "content": []}) + self.item["content"][0]["text"] = text + out.append(self.event("response.output_text.delta", item_id=self.item["id"], output_index=self.index, + content_index=0, delta=text, logprobs=[])) + out += self.close() + n = done.get("completion_tokens", 0) + prompt = done.get("prompt_tokens", self.prompt_tokens) + self.response["usage"] = { + "input_tokens": prompt, "input_tokens_details": {"cached_tokens": min(done.get("reused") or 0, prompt)}, + "output_tokens": n, "output_tokens_details": {"reasoning_tokens": done.get("reasoning_tokens", 0)}, + "total_tokens": prompt + n} + if length: + self.response["status"] = "incomplete" + self.response["incomplete_details"] = {"reason": "max_output_tokens"} + return out + [self.event("response.incomplete", response=self.snapshot())] + self.response["status"] = "completed" + self.response["completed_at"] = int(time.time()) + return out + [self.event("response.completed", response=self.snapshot())] + + def failed(self, message: str, code: str = "server_error") -> dict: + """response.failed: an error after the stream started (the HTTP status is already sent).""" + if self.item is not None: + self.item["status"] = "incomplete" + self.item = None + self.response["status"] = "failed" + self.response["error"] = {"code": code, "message": message} + return self.event("response.failed", response=self.snapshot()) + + +def collect(events) -> dict: + """The non-streaming answer: the final response object.""" + last = None + for e in events: + if e is not None: + last = e + return last["response"] diff --git a/serve/runconfig.py b/serve/runconfig.py new file mode 100644 index 0000000..472b002 --- /dev/null +++ b/serve/runconfig.py @@ -0,0 +1,179 @@ +"""serve/runconfig.py - #564: the web page's Settings view of the run config (strata-.json). + +A short list of documented keys can be read and changed from Strata's own page (GET / POST /config). Everything +else in the file - the keys setup writes, the network and security keys (host, api_key, cors_origins, +trusted_origins, allowed_hosts), the MCP servers and before_load (which run programs), sampling keys not listed +here - is kept as it is: a change touches only the keys it names (as setup run again keeps the user's keys, #629). +The earlier file is kept as strata-.json.bak. The server reads the config when it starts, so a change is +used from the next start on. +""" +from __future__ import annotations + +import json +import os +import shutil +from pathlib import Path + +# (key, kind, help). kind: "bool", "int>=0", "num>=0", ("enum", values), "names", or ("sampling", check) for a key +# of the "sampling" block, ("arg", flag) for an engine option kept in "args". +EDITABLE = [ + ("sampling.temperature", ("sampling", "num>=0"), + "Default temperature for requests that send none (0 = greedy, the default without a sampling block)"), + ("sampling.top_p", ("sampling", "0=0", "Cap the thinking of every request at this many tokens (0 or empty: no cap)"), + ("fit_max_tokens", "bool", "Shorten a max_tokens that does not fit the context instead of answering 400"), + ("anthropic_thinking", ("enum", ["model", "on_request"]), + "Anthropic requests that do not ask for thinking: think as the model does (model) or not (on_request)"), + ("effort_position", ("enum", ["start", "end"]), + "Where a non-default reasoning effort goes: start (the default) or end (keeps the cache when it changes)"), + ("aliases", "names", "Other model names the server lists and answers to (comma-separated)"), + ("idle_unload_s", "num>=0", "Unload the model after this many seconds without requests (0 or empty: never)"), + ("lazy_load", "bool", "Start without loading the model; the first request loads it (text only)"), + ("engine_silence_s", "num>=0", "End a request when the engine says nothing for this long (default 300 s, 0 = wait)"), + ("api_monitor", "bool", "Keep the last 100 requests' prompts and answers in memory for /api-monitor"), + ("open_browser", "bool", "Open the chat page in the browser when the model is ready"), + ("vram_reserve_mib", ("arg", "--vram-reserve-mib"), + "VRAM in MiB the engine leaves free for other programs (engine default 700)"), +] +SPEC = {k: kind for k, kind, _ in EDITABLE} + + +def _arg(cfg: dict, flag: str): + a = cfg.get("args") if isinstance(cfg.get("args"), list) else [] + if flag in a[:-1]: + v = str(a[a.index(flag) + 1]) + return int(v) if v.isdigit() else v + return None + + +def value_of(cfg: dict, key: str): + kind = SPEC[key] + if isinstance(kind, tuple) and kind[0] == "sampling": + s = cfg.get("sampling") + return s.get(key.split(".", 1)[1]) if isinstance(s, dict) else None + if isinstance(kind, tuple) and kind[0] == "arg": + return _arg(cfg, kind[1]) + return cfg.get(key) + + +def view(cfg: dict, path: str | Path) -> dict: + """GET /config: the editable keys with their values (None: not set, the default applies).""" + out = [] + for key, kind, help_ in EDITABLE: + k = kind[0] if isinstance(kind, tuple) else kind + out.append({"key": key, "value": value_of(cfg, key), "help": help_, + "kind": "number" if k in ("sampling", "arg", "int>=0", "num>=0") else k, + **({"choices": kind[1]} if k == "enum" else {})}) + return {"file": Path(path).name, "keys": out, + "note": "Saved to the run config; used from the next start of the model."} + + +def _number(key, v, whole=False, lo=0.0, hi=None, lo_open=False): + if isinstance(v, bool) or not isinstance(v, (int, float)) or (whole and v != int(v)) or \ + (v <= lo if lo_open else v < lo) or (hi is not None and v > hi): + rng = f"{'more than' if lo_open else 'at least'} {lo:g}" + (f" and at most {hi:g}" if hi is not None else "") + raise ValueError(f"{key}: expected a {'whole ' if whole else ''}number, {rng}, not {v!r}") + return int(v) if whole else v + + +def check(key: str, v, cfg: dict): + """The value to store for `key`, or a ValueError naming what is expected. None removes the key (its default).""" + if key not in SPEC: + raise ValueError(f"{key!r} cannot be changed here (only the keys the Settings view lists)") + if v is None: + return None + kind = SPEC[key] + k = kind[0] if isinstance(kind, tuple) else kind + if k == "bool": + if not isinstance(v, bool): + raise ValueError(f"{key}: expected true or false, not {v!r}") + if key == "lazy_load" and v and cfg.get("vision"): + raise ValueError("lazy_load: lazy loading is text-only, and this model reads images (\"vision\")") + return v + if k == "enum": + if v not in kind[1]: + raise ValueError(f"{key}: expected one of {', '.join(kind[1])}, not {v!r}") + return v + if k == "names": + if isinstance(v, str): + v = [x.strip() for x in v.split(",") if x.strip()] + if not isinstance(v, list) or not all(isinstance(x, str) and x.strip() and len(x) <= 128 for x in v): + raise ValueError(f"{key}: expected a list of model names, not {v!r}") + return v or None + if k == "int>=0": + return _number(key, v, whole=True) + if k == "num>=0": + return _number(key, v) + if k == "arg": + return _number(key, v, whole=True) + rule = kind[1] # a sampling key: the server's own rules + if rule == "num>=0": + return float(_number(key, v)) + if rule == "0 tuple[dict, list[str]]: + """The config with `changes` ({key: value or None}) made, and the keys that changed. Every value is checked + first, so a request with one bad value changes nothing (ValueError).""" + if not isinstance(changes, dict) or not changes: + raise ValueError('send {"set": {"": , ...}}') + checked = {k: check(k, v, cfg) for k, v in changes.items()} + new = json.loads(json.dumps(cfg)) # a deep copy: the caller's dict is left alone + changed = [] + for key, v in checked.items(): + if value_of(new, key) == v: + continue + kind = SPEC[key] + if isinstance(kind, tuple) and kind[0] == "sampling": + s = dict(new.get("sampling") or {}) if isinstance(new.get("sampling"), dict) else {} + sub = key.split(".", 1)[1] + if v is None: + s.pop(sub, None) + else: + s[sub] = v + if s: + new["sampling"] = s + else: + new.pop("sampling", None) + elif isinstance(kind, tuple) and kind[0] == "arg": + a = list(new.get("args") or []) + flag = kind[1] + if flag in a[:-1]: + i = a.index(flag) + if v is None: + del a[i:i + 2] + else: + a[i + 1] = str(v) + elif v is not None: + a += [flag, str(v)] + new["args"] = a + elif v is None: + new.pop(key, None) + else: + new[key] = v + changed.append(key) + return new, changed + + +def save(path: str | Path, cfg: dict) -> Path: + """The config written whole (a temporary file moved over the old one), the earlier one kept as .bak.""" + path = Path(path) + bak = path.with_name(path.name + ".bak") + shutil.copyfile(path, bak) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + os.replace(tmp, path) + return bak + + +def load(path: str | Path) -> dict: + cfg = json.loads(Path(path).read_text(encoding="utf-8-sig")) + if not isinstance(cfg, dict): + raise ValueError(f"{Path(path).name} is not a JSON object") + return cfg diff --git a/serve/server.py b/serve/server.py new file mode 100644 index 0000000..9e66982 --- /dev/null +++ b/serve/server.py @@ -0,0 +1,4145 @@ +"""serve/server.py - plan v0.3 P8: OpenAI and Anthropic endpoints over any engine that maps token ids to tokens. + + python -m serve.server --engine mock --port 8095 (a scripted engine, for clients and tests) + python -m serve.server --engine strata --config strata.json --port 8080 (the real engine, resident) + +Endpoints: POST /v1/chat/completions (OpenAI, stream and non-stream), POST /v1/messages (Anthropic, stream and +non-stream), GET /v1/models, GET /models, GET /props, GET /slots, GET /health, GET /mcp. One sequence at a time behind a FIFO (plan: one resident sequence). +Tools from MCP servers (serve/mcp.py, `"mcp_servers"` in the config or --mcp-config) are offered only to requests that +ask for them with `"strata_mcp": true` - the web app does; other clients see exactly the API they always saw. +Images (optional, when the config has a "vision" entry): OpenAI image_url parts and Anthropic image blocks (base64 +data, http(s) URLs or local file paths) go through `strata-vision` (the model's mmproj file) and reach the engine as +embeddings (`GENI`). JPEG/PNG/BMP/GIF go straight in; WebP, TIFF, AVIF, ... (agents like omp send WebP) are +converted to PNG first with Pillow. +Requests whose prompt plus max tokens exceed the engine's context are REJECTED with 400, never truncated. +An unset (or 0, or -1) max tokens means "unlimited": whatever the prompt leaves of the context. + +The engine boundary is `Engine.generate(prompt_ids, max_new, sampling, cancel) -> iterator of token ids`. +`StrataEngine` keeps one `strata --serve` process resident (weights, expert arena and VRAM tier load once) and +talks to it over stdin/stdout; `MockEngine` is a scripted stand-in that makes every API path testable without a GPU. +""" +from __future__ import annotations + +import argparse +import contextlib +import collections +import base64 +import hashlib +import hmac +import codecs +import ctypes +import json +import os +import queue +import re +import select +import signal +import socket +import struct +import subprocess +import sys +import tempfile +import threading +import time +import urllib.request +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Iterator, Protocol +from urllib.parse import parse_qs, urlsplit + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) # run as a script (run-.bat) as well as a module +from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 + images_of, mark_think_literals, openai_to_messages, unmark_think_literals) +from serve.mcp import McpCancelled, hub_from_config # noqa: E402 +from serve import runconfig # noqa: E402 +from serve.winjob import contain # noqa: E402 +from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 +from serve import responses as responses_api # noqa: E402 +from serve.responses import ResponsesError, error_body as responses_error_body # noqa: E402 + +IM_END = "<|im_end|>" +IMAGE_PAD = "<|image_pad|>" +# #458: the trailing effort turn ("effort_position": "end"); low is the template's own sentence, medium (which the +# template says nothing for: no xhigh sentence is medium there) says it, since the xhigh one stays at the top +EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n" +EFFORT_TEXT = {"low": "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the " + "conclusion without unnecessary elaboration.", + "medium": "Reasoning effort is set to medium. Think as much as the task needs, without unnecessary " + "elaboration."} +VISION_START = "<|vision_start|>" +# #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a +# broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens" +# sets it; 0 turns it off. +REPEAT_STOP_TOKENS = 256 +# #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) +REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n\n\n" +LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1") +CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here +# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first +# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer. +RATE_WINDOW_S = 2.0 +RATE_MIN_SPAN_S = 0.25 # younger than this there is no rate yet: the mean so far, with the span floored here +# #481: a running request whose engine prints nothing (no T, PP or any other line) for this long has lost step with the +# server (the engine's main thread waits, untimed, for its next command): the engine is ended and the request fails; +# the next request starts it again. The config's "engine_silence_s" sets it (0: wait forever, as before). +ENGINE_SILENCE_S = 300.0 +# ... except while a prompt is read: a PP line comes once per chunk (up to 32768 tokens with --prefill auto, issue +# #282), and the slowest PCs read ~100 tok/s, so a first chunk can take minutes before the first line. Until the first +# PP the wait adds the chunk's tokens at PP_FLOOR_TOK_S; after one, a chunk may take PP_SLACK x the last one's time. +PP_CHUNK_MAX = 32768 +PP_FLOOR_TOK_S = 50.0 +PP_SLACK = 3.0 + + +# ------------------------------------------------------------------------------------------------ engines +class Engine(Protocol): + max_context: int + def generate(self, ids: list[int], max_new: int, sampling: dict, cancel: threading.Event) -> Iterator[int]: ... + + +class MockEngine: + """Replays a scripted completion (text) as token ids, one per step, then the end-of-turn token. Given a list of + scripts, each request gets the next one and the last one repeats (a tool call, then the answer after it).""" + + def __init__(self, tokenizer, script: str | list[str], max_context: int = 32768, delay_s: float = 0.0): + self.tok, self.max_context, self.delay = tokenizer, max_context, delay_s + end = tokenizer.encode(IM_END, parse_special=True) + self.scripts = [tokenizer.encode(x, parse_special=True) + end for x in ([script] if isinstance(script, str) + else script)] + self.script, self.turns = self.scripts[0], 0 + self.last_prompt: list[int] = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.last_prompt = list(ids) + self.last_embeddings = embeddings + if len(self.scripts) > 1: + self.script = self.scripts[min(self.turns, len(self.scripts) - 1)] + self.turns += 1 + for t in self.script[:max_new]: + if cancel.is_set(): + return + if self.delay: + time.sleep(self.delay) + yield t + + +class EngineDied(RuntimeError): + """The engine process ended in the middle of a request (issue #27: on Linux, the out-of-memory killer).""" + + +class EngineStarting(RuntimeError): + """The engine is (re)starting and has not said READY yet (#344): no context size to plan a request with - a 503, + not a 400 about the prompt.""" + + +class ModelBusy(RuntimeError): + """Explicit model controls must not interrupt active or queued requests.""" + + +class EngineSilent(EngineDied): + """#481: the engine said nothing for too long during a request (or never acknowledged a STOP): the two sides lost + step - the engine waiting for its next command, the server for this request's end - and the server ended it. An + EngineDied, so the request ends with an error and the next one starts the engine again.""" + + +class EngineStuck(RuntimeError): + """The engine process did not end after QUIT, terminate and kill: the server keeps it (and says so) rather than + reporting its GPU and RAM as given back.""" + + +class GpuBusy(RuntimeError): + """The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, another + model server) is using it, so the engine is not started into the little that is left.""" + + +ENGINE_REQUEST = re.compile( + # "+ 12288 of 98179 read": a request cancelled while its prompt was read (#471) + r"prompt (?P\d+) tokens = (?P\d+) reused \+ \d+(?: of \d+)? read in (?P[\d.]+) ms " + r"\((?P[\d.]+) tok/s\), " + r"(?P\d+) generated in (?P[\d.]+) ms \((?P[\d.]+) tok/s\)") + + +_echoing: set[str] = set() # the logs echo_requests already follows (restart() runs StrataEngine.__init__ again) + +DRAFT_HEAD_FAIL = "the draft head does not fit" +DRAFT_HEAD_HINT = ("a smaller draft vocabulary needs less VRAM: --draft-vocab cyrillic (English, code and the Cyrillic " + "script) or --draft-vocab en (English and code, ~215 MiB less than the default). Start once with " + "it - START-HERE.bat --draft-vocab en (Windows) or ./setup.sh --draft-vocab en - and the model " + "keeps it; or a smaller --context in setup.") + + +def start_failure_hint(log: str | None, offset: int) -> str: + """#474: what to change when the engine stopped at the start because the MTP draft head did not fit the VRAM + left: the engine's own `strata mtp:` lines after that failure (0.1.36+: what it needs, what is free, the smaller + subsets), else the same advice in words for an older engine. "" for any other failure: the log says why.""" + if not log: + return "" + try: + with open(log, "rb") as f: + f.seek(offset) + text = f.read().decode("utf-8", "replace") + except (OSError, ValueError): + return "" + if DRAFT_HEAD_FAIL not in text: + return "" + said = [x.strip()[len("strata mtp: "):] for x in text.splitlines() + if x.strip().startswith("strata mtp: ") and ("draft head over" in x or "hint:" in x)] + return ". mtp: " + DRAFT_HEAD_FAIL + ". " + (" ".join(said) if said else "Hint: " + DRAFT_HEAD_HINT) + + +def start_log_tail(log: str | None, offset: int, n: int = 20) -> str: + """#496: the last n lines this start wrote to the engine log, for the error when the engine ended before READY - + whatever the failure, the engine's own reason is in them (people posted the traceback without the log). "" when + there is no log or nothing in it from this start.""" + if not log: + return "" + try: + with open(log, "rb") as f: + f.seek(0, 2) + start = max(offset, f.tell() - 64 * 1024) # enough for 20 lines, never an earlier start's + f.seek(start) + text = f.read().decode("utf-8", "replace") + except (OSError, ValueError): + return "" + lines = text.splitlines()[1 if start > offset else 0:] # not a line cut in half + lines = [x.rstrip() for x in lines if x.strip()][-n:] + if not lines: + return "" + return "\nthe engine log's last lines:\n" + "\n".join(" " + x for x in lines) + + +def echo_requests(log_path: str, offset: int) -> None: + """STRATA_REQUEST_LINES=1: one stdout line per finished request, from the engine's own summary in its log. + + The engine's stderr goes to the log file (the start narrator reads it), so a supervisor that only sees this + process's output - a tray, llama-swap - has no per-request numbers. This re-states the engine's line with the + total the two times make: `request prompt P cached C output O prompt_read R ms total S ms prefill X tok/s decode Y + tok/s` (prompt_read: the time the engine spent reading the prompt's new tokens, not a time to first token). + """ + with open(log_path, "r", encoding="utf-8", errors="replace") as f: + f.seek(offset) + while True: + line = f.readline() + if not line: + time.sleep(0.2) + continue + m = ENGINE_REQUEST.search(line) + if m: + read_ms, gen_ms = float(m["read"]), float(m["gen_ms"]) + print("[strata] request prompt %s cached %s output %s prompt_read %.0f ms total %.0f ms prefill %s " + "tok/s decode %s tok/s" % (m["prompt"], m["reused"], m["gen"], read_ms, read_ms + gen_ms, m["pp"], + m["tg"]), flush=True) + + +def experts_loading_words(args: list, size: str) -> str: + """#505: what the start does with the experts, by the engine's flags (generate.cpp's option parsing): a RAM budget + copies the hottest N GiB into RAM (--resident-budget-gib), the resident low-RAM mode the ones the GPU does not hold + (--resident-experts), plain --mmap-experts reads them from the model files through the OS file cache (nothing is + loaded into RAM up front); otherwise all of them go into RAM.""" + if "--resident-budget-gib" in args: + try: + n = f"up to {float(args[args.index('--resident-budget-gib') + 1]):g} GiB" + except (IndexError, ValueError): + n = "a RAM budget" + return (f"loading the most-used experts into RAM ({n}; the rest are read from the model files as needed) " + "and locking part of them for the GPU.") + if "--resident-experts" in args: + return (f"loading the experts the GPU does not hold into RAM (of {size}) and locking part of them for the " + "GPU.") + if "--mmap-experts" in args: + return (f"mapping the experts from the model files ({size}, --mmap-experts): they are not loaded into RAM - " + "the OS file cache reads them as the GPU's expert cache fills and as requests need them.") + return f"loading the experts into RAM ({size}) and locking part of them for the GPU." + + +def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, heartbeat=20.0) -> None: + """While the engine starts, say in the server window what it is doing, from its log: the start reads tens of GB + into RAM and locks part of it for the GPU, and on many PCs everything is slow or frozen for a minute or more - + people closed the window thinking it had hung. The warning comes at that step, not after it.""" + gb = 0.0 + if "--native" in args: # about the size of the experts it will read + try: + gb = os.path.getsize(args[args.index("--native") + 1]) / 1e9 + except (OSError, IndexError): + pass + size = f"about {gb:.0f} GB" if gb >= 1 else "tens of GB" + loading = experts_loading_words(args, size) + t0 = last = time.time() + said = set() + + def say(key, text): + nonlocal last + if key not in said: + said.add(key) + last = time.time() + print(text, flush=True) + + say("weights", "[strata] starting the engine: reading the model's weights ...") + pos = offset + while not done.wait(0.5): + try: + with open(log_path, "rb") as f: + f.seek(pos) + chunk = f.read() + except OSError: + chunk = b"" + if chunk.count(b"\n"): + cut = chunk.rfind(b"\n") + 1 + pos += cut + for line in chunk[:cut].decode("utf-8", "replace").splitlines(): + if "PLE on" in line or "expert arena:" in line or "experts via mmap" in line: # #505: mapped + say("arena", f"[strata] {loading}\n" + " YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES NOW - this is normal.\n" + " Please wait and don't close this window; the browser opens when it is ready.") + elif " loaded " in line and "GiB at" in line: + say("loaded", "[strata] experts loaded: " + line.split(" loaded ", 1)[1].strip() + + f" ({time.time() - t0:.0f} s so far)") + elif "expert cache " in line and " slots, " in line and "auto" not in line: + n = line.split("expert cache ", 1)[1].split(";")[0].replace(" slots,", " experts,").strip() + say("cache", f"[strata] filling the GPU's expert cache ({n}) ...") + elif "session is up" in line: + say("up", "[strata] almost ready ...") + if time.time() - last > heartbeat: + last = time.time() + print(f"[strata] still starting ({time.time() - t0:.0f} s) - please wait ...", flush=True) + + +class ConvCacheLog: + """#596: the engine's conversation cache as its log tells it (the engine writes "strata serve: conversation + cache: parked N tokens ...; parked=P bytes=B evictions=E" and "restored N tokens ...; parked=P bytes=B" to stderr, + which is the log): read on from where it was last read, from the start of the engine's current run.""" + EVENT = re.compile(r"conversation cache: (parked|skipped|restored) (\d+) tokens.*?parked=(\d+) bytes=(\d+)" + r"(?: evictions=(\d+))?") + DROPPED = re.compile(r"conversation cache: dropped \d+ superseded .*?parked=(\d+)") + READ_MAX = 1 << 20 # at most the last MiB of new lines per read + + def __init__(self): + self.key, self.pos = None, 0 + self.reset() + + def reset(self): + self.state = {"parked": 0, "bytes": 0, "evictions": 0, "parks": 0, "restores": 0, "last_event": None, + "last_tokens": None, "last_at": None} + + def poll(self, path, start) -> dict: + """The state after the log's new lines; `start` is where the engine's current run began in it.""" + if not path or start is None: + return dict(self.state) + if self.key != (path, start): # another start of the engine: its cache starts empty + self.key, self.pos = (path, start), start + self.reset() + try: + size = os.path.getsize(path) + if size < self.pos: # the log was emptied or replaced + self.pos = 0 + if size - self.pos > self.READ_MAX: + self.pos = size - self.READ_MAX + with open(path, "rb") as f: + f.seek(self.pos) + data = f.read(size - self.pos) + except OSError: + return dict(self.state) + end = data.rfind(b"\n") + 1 # whole lines only: the rest is read next time + self.pos += end + now = time.time() + for line in data[:end].decode("utf-8", "replace").splitlines(): + if "conversation cache:" not in line: + continue + m = self.EVENT.search(line) + if m: + st = self.state + st["parked"], st["bytes"] = int(m.group(3)), int(m.group(4)) + if m.group(5) is not None: + st["evictions"] = int(m.group(5)) + if m.group(1) != "skipped": + st["parks" if m.group(1) == "parked" else "restores"] += 1 + st["last_event"], st["last_tokens"], st["last_at"] = m.group(1), int(m.group(2)), now + continue + m = self.DROPPED.search(line) + if m: + self.state["parked"] = int(m.group(1)) + return dict(self.state) + + +def conversation_cache_view(info: dict, hist: list, totals: dict, parked: dict) -> dict: + """#596: the Monitor's Conversation cache card: the parked conversations (the engine's opt-in + --conversation-cache-mib: budget, slots, what its log says) and how much of the prompts the cache gave back.""" + mib = info.get("conversation_cache_mib") + last = hist[-1] if hist else None + return {"enabled": isinstance(mib, int) and mib > 0, "budget_mib": mib if isinstance(mib, int) else None, + "slots": info.get("conversation_cache_slots"), **parked, + "requests": len(hist), "requests_reused": sum(1 for r in hist if (r.get("reused") or 0) > 0), + "reused_tokens": totals.get("reused", 0), "prompt_tokens": totals.get("prompt_tokens", 0), + "last_reused": last.get("reused") if last else None, + "last_prompt": last.get("prompt_tokens") if last else None} + + +_BTRACE = bool(os.environ.get("STRATA_BATCH_TRACE")) + + +def btrace(*a): + if _BTRACE: + print("[batch-trace]", threading.get_ident() % 10000, *a, file=sys.stderr, flush=True) + + +EOS_IDS = {248044, 248046} # <|endoftext|>, <|im_end|>: the engine's default --eos-ids + + +class StrataEngine: + """The resident engine: `strata --serve` reads `GEN ` lines and streams `T ` lines, then + `DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough. + + Per-request sampling rides the same line as engine-side keys between max_new and the ids + (`temperature=F top_p=F top_k=N seed=N`, the engine's own spelling). An absent temperature keeps the + engine's default, which is greedy; `temperature=0` means the same thing, so it is not forwarded. + """ + silence_s = ENGINE_SILENCE_S # #481: main() sets the config's engine_silence_s (survives restart()) + silent_note = None # #481: why the server ended a silent engine (death_note says it) + batch = 0 # --batch: the engine's batch slots (0: one request at a time) + + # `last`: the figures of the engine's last DONE line. With batch slots several requests run at once, each on its + # own thread, so each one reads its own request's figures (Service.run records them); one at a time, the one dict. + @property + def last(self): + if self.batch: + tl = self.__dict__.setdefault("_tl", threading.local()) + if not hasattr(tl, "last"): + tl.last = {} + return tl.last + return self.__dict__.get("_last", {}) + + @last.setter + def last(self, value): + self.__dict__["_last"] = value + if self.batch: + tl = self.__dict__.setdefault("_tl", threading.local()) + tl.last = value + + def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None, + env: dict | None = None, lazy: bool = False): + self.spawn = (exe, list(args), cwd, log, env) # to start it again after it died (issue #27) + paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")} + self.model_path = paths.get("--native") or paths.get("--pack", "pack/full") + self.log_path = log + self.proc, self.pump, self.log = None, None, None + self.ended, self.unloaded = True, True + self.max_context = int(args[args.index("--max-context") + 1]) if "--max-context" in args else 4096 + self.can_stop = False # the engine honours a STOP line mid-request (READY stop) + self.last = {} + self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) + self.prefill_tok_s_mean = None + self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines + self.silent_note = None + try: # a ready-made engine's BUILD.json says its version + self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version") + except (OSError, ValueError): + self.info["version"] = None + if lazy: + return + self.unloaded = False # `ended` stays True until READY (below): not alive while starting (#344) + self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL + loading = threading.Event() # set once READY: the narrator below stops + log_start = os.path.getsize(log) if log else 0 # where this start's lines begin (start_failure_hint) + self.log_start = log_start # #596: the Monitor's conversation cache reads from here + if log: + threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading), + daemon=True).start() + # once per log: the follower keeps reading the same (appended) log across restarts and reloads + if os.environ.get("STRATA_REQUEST_LINES") and os.path.abspath(log) not in _echoing: + _echoing.add(os.path.abspath(log)) + threading.Thread(target=echo_requests, args=(log, os.path.getsize(log)), daemon=True).start() + self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) + contain(self.proc) # ends with the server, however it ends (Windows) + self.max_context = 0 + for line in self.proc.stdout: + if line.startswith("INFO "): + for kv in line.split()[1:]: + k, _, v = kv.partition("=") + self.info[k] = int(v) if v.lstrip("-").isdigit() else v + if line.startswith("READY"): + f = line.split() + self.max_context = int(f[1]) + self.can_stop = "stop" in f[2:] + break + loading.set() + if self.max_context <= 0: + try: # its pipes and our handle on its log (the log stays) + self.proc.wait(timeout=5) + self.proc.stdin.close() + self.proc.stdout.close() + if log: + self.log.close() + except (OSError, subprocess.TimeoutExpired): + pass + raise RuntimeError("the engine exited before it was ready" + (f" (see {log})" if log else "") + + start_failure_hint(log, log_start) + start_log_tail(log, log_start)) + self.known_ctx = self.max_context # survives a failed restart: requests keep their limit and restart it + # (from PR #41, midhatn) a locally built engine can sit next to another release's BUILD.json: engines that + # report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older ones + if self.info.get("engine"): + self.info["version"] = str(self.info["engine"]) + self.ended = False # READY: alive from here (restart() set it True, #344) + # the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks) + self.lines: queue.Queue = queue.Queue() + # --batch: concurrent requests in the engine's batch slots (see generate_batched). The engine says how many + # it runs (INFO batch_slots=N: it may have fewer than asked, or none, when they do not fit) + asked = next((int(args[args.index(k) + 1]) for k in ("--batch", "--slots") if k in args), 0) + self.batch = int(self.info.get("batch_slots") or 0) + if asked and self.batch != asked: + print(f"[strata] parallel requests: {asked} asked, the engine runs {self.batch or 'one at a time'} " + "(its log says why)", flush=True) + groups = int(args[args.index("--batch-groups") + 1]) if "--batch-groups" in args else 1 + groups = groups if self.batch and groups > 0 and self.batch % groups == 0 else 1 + gs = self.batch // groups if self.batch else 0 + # slots in the order that spreads requests over the pipeline's groups first: 0, gs, 2gs, .., 1, gs+1, .. + self.slot_order = [g * gs + t for t in range(gs) for g in range(groups)] + self.slot_q = [queue.Queue() for _ in range(self.batch)] + self.slot_busy = [False] * self.batch + # what each slot's sessions hold (prompt + every token a window fed), so a conversation's next turn goes to + # the slot that has its start (the engine checks it again); when the slot was last used + self.slot_held: list[list[int]] = [[] for _ in range(self.batch)] + self.slot_used = [0.0] * self.batch + self.slot_live: list[dict | None] = [None] * self.batch # /metrics: the request in each slot + self.slot_cv = threading.Condition() + self.waiting = 0 # requests waiting for the control lines (ctl) + self.wait_lens: list[list[int]] = [] # ... their prompt lengths (a long read gives way to short ones) + self.ctl_epoch = 0 # how often the control lines were taken + self._yielded = None # (slot, tokens read): the last request on them gave way + self.ctl = threading.Lock() # one admission or solo request on the control lines at a time + self.wlock = threading.Lock() # stdin writes from several request threads + self.pump = threading.Thread(target=self._pump, daemon=True) + self.pump.start() + + def _pump(self): + proc, lines = self.proc, self.lines # this process's: a restart replaces both (#344) + slot_q = self.slot_q + for line in proc.stdout: + if line.startswith(("BT ", "BDONE ")) and slot_q: # --batch: a batch slot's own lines + try: + slot_q[int(line.split()[1])].put(line) + continue + except (IndexError, ValueError): + pass + lines.put(line) + if self.proc is proc: # a killed engine's pump must not mark its successor dead + self.ended = True # its output closed: it is gone, even before the OS says so + lines.put(None) + for q in slot_q: + q.put(None) + + def death_note(self) -> str: + """Why the engine most likely ended, from the end of its log: its own watchdog (issue #29), else RAM.""" + if getattr(self, "silent_note", None): # #481: the server ended it, not the OS or the engine itself + return self.silent_note + tail = "" + try: + with open(self.log_path, "rb") as f: + f.seek(0, 2) + f.seek(max(0, f.tell() - 4096)) + tail = f.read().decode("utf-8", "replace") + except (OSError, TypeError): + pass + for line in reversed(tail.splitlines()): + if "issue #29" in line: + return ("The engine stopped itself because it had stopped making progress - a hang it caught. Its log " + "line: " + line.strip() + " - please report it at github.com/Niko1221/Strata/issues.") + rc = self.proc.poll() + last = next((x.strip() for x in reversed(tail.splitlines()) if x.strip().startswith(("strata", "ERR"))), "") + if rc is not None and rc >= 0 and last: # it ended by itself: its own last words say why (#215) + return (f"The engine exited (code {rc}). Its last log line: {last} - if that does not explain it, please " + "report it at github.com/Niko1221/Strata/issues with the log.") + return ("The usual cause is running out of RAM: Linux then ends the biggest program (check: sudo dmesg | " + "grep -i -E 'killed process|out of memory'); Windows slows down instead. Close other programs or use a " + "smaller model (Q2_0 / IQ2_XS).") + + def alive(self) -> bool: + return self.proc is not None and not getattr(self, "ended", False) and self.proc.poll() is None + + def exit_code(self): + if self.proc is None: + return None + try: + return self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + return None + + def unload(self): + """Release GPU/RAM between requests, retaining the spawn config for automatic reloading.""" + self.close() + self.unloaded = True + + RESTART_RETRY_S = 15.0 # between the tries of restart(): a dying engine's VRAM may take a while to come back + + def restart(self, tries: int = 3): + """Start the engine again (the same command) after it died; the new process has its own line queue. + close() ends and waits for the old process first (EngineStuck when it cannot be ended). A start that still + exits before READY - a dead engine's VRAM can take a while to come back, notably on ROCm - is retried + (PR #637).""" + self.close() + info = dict(self.info) + self.starting = True # prepare() answers 503 "starting" meanwhile (#344) + try: + for i in range(tries): + # #344: not alive until READY - __init__ sets max_context to 0 and blocks until the engine says + # READY, and a request that saw alive() in that window skipped load() and failed with "context + # (0)". __init__ clears `ended` itself once READY (before its pump thread can set it again). + self.ended = True + try: + self.__init__(*self.spawn) + break + except RuntimeError: + try: + self.proc.wait(timeout=60) + except (subprocess.TimeoutExpired, OSError): + pass + if i == tries - 1: + raise + print(f"[strata] the engine did not start (try {i + 1} of {tries}); again in " + f"{self.RESTART_RETRY_S:g} s", flush=True) + time.sleep(self.RESTART_RETRY_S) + finally: + self.starting = False + self.info = {**info, **self.info} + + def _parse_done(self, line): + f = line.split() + self.last = {"generated": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]), + "decode_ms": float(f[4]), "finish": f[5]} + if len(f) >= 9: # the conversation cache's fields (engine 0.1.3+) + self.last.update(drafts_accepted=int(f[6]), drafts_offered=int(f[7]), reused=int(f[8])) + if len(f) >= 11: # decode hit rate fields + self.last.update(hits=int(f[9]), lookups=int(f[10])) + if len(f) >= 14: # the expert tiers (engine 0.1.31+): RAM / file blobs, file MB + self.last.update(ram_blobs=int(f[11]), file_blobs=int(f[12]), file_mb=float(f[13])) + if len(f) >= 15: # #471 (engine 0.1.36+): the prompt tokens actually read + self.last.update(prompt_read=int(f[14])) + if len(f) >= 16: # #588 (engine 0.1.39+): routed experts read over PCIe + self.last.update(offloaded=int(f[15])) + + def vram(self, reserve_mib: int | None, timeout: float = 120.0) -> dict: + """#533: `VRAM ` between requests (the caller holds the service's FIFO): the engine shrinks its + expert cache until that much VRAM is free, or grows it back when more is free; None: back to the reserve it + started with. -> the engine's figures (expert_slots, expert_cache_mib, vram_free_mib, ...); raises ValueError + with the engine's reason (e.g. it was not started with --vram-elastic), EngineDied when it ended.""" + if not self.alive(): + raise EngineDied("the engine is not running") + self.proc.stdin.write("VRAM" + ("" if reserve_mib is None else f" {int(reserve_mib)}") + "\n") + self.proc.stdin.flush() + deadline = time.time() + timeout + while True: + try: + line = self.lines.get(timeout=max(0.1, deadline - time.time())) + except queue.Empty: + raise EngineDied("the engine did not answer the VRAM command") from None + if line is None: + raise EngineDied("the engine ended") + line = line.strip() + if line.startswith("ERR"): + raise ValueError(line[4:].strip() or "the engine refused the VRAM command") + if line.startswith("VRAM "): + out = {} + for kv in line.split()[1:]: + k, _, v = kv.partition("=") + out[k] = int(v) if v.lstrip("-").isdigit() else v + self.info.update({k: out[k] for k in ("expert_slots", "vram_free_mib") if k in out}) + self.info["vram"] = out + return out + if time.time() > deadline: + raise EngineDied("the engine did not answer the VRAM command") + + @staticmethod + def sampling_keys(sampling: dict) -> str: + keys = "" + t = sampling.get("temperature") + if isinstance(t, (int, float)) and float(t) > 0.0: + keys += f" temperature={float(t)!r}" + tp = sampling.get("top_p") + if isinstance(tp, (int, float)) and float(tp) < 1.0: + keys += f" top_p={float(tp)!r}" + tk = sampling.get("top_k") + if isinstance(tk, int) and not isinstance(tk, bool) and tk >= 0: + # the engine's sampled path keeps at most 64 candidates: 0 ("off") and wider lists get all 64 + keys += f" top_k={tk if 1 <= tk <= 64 else 64}" + mp = sampling.get("min_p") + if isinstance(mp, (int, float)) and 0.0 < float(mp) <= 1.0: + keys += f" min_p={float(mp)!r}" + rp = sampling.get("repetition_penalty") + rp_on = isinstance(rp, (int, float)) and float(rp) != 1.0 + pf = sampling.get("frequency_penalty") + pf_on = isinstance(pf, (int, float)) and float(pf) != 0.0 + pp = sampling.get("presence_penalty") + pp_on = isinstance(pp, (int, float)) and float(pp) != 0.0 + if rp_on: + keys += f" penalty_repeat={float(rp)!r}" + if pf_on: + keys += f" penalty_freq={float(pf)!r}" + if pp_on: + keys += f" penalty_present={float(pp)!r}" + if rp_on or pf_on or pp_on: + # a penalty without a window counts over nothing: the engine's default is the last 64 tokens + pln = sampling.get("penalty_last_n") + if isinstance(pln, int) and not isinstance(pln, bool) and pln > 0: + keys += f" penalty_last_n={pln}" + else: + keys += " penalty_last_n=64" + seed = sampling.get("seed") + if isinstance(seed, int) and seed > 0: + keys += f" seed={seed}" + # setup's calibration (tools/calibrate.py): engine settings for this request only, measured without a restart + tune = sampling.get("strata_tune") + if isinstance(tune, dict): + for k in ("pcie_frac", "spec_min_p"): + v = tune.get(k) + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0: + keys += f" {k}={float(v)!r}" + return keys + StrataEngine.projection_key(sampling) + + @staticmethod + def projection_key(sampling: dict) -> str: + """`cvec=0|1`: the experimental-speed-projection control vector for this request, when the engine was + started with one (--control-vector-scaled; an engine without one ignores the key). Absent = on.""" + on = sampling.get("experimental_speed_projection") + return f" cvec={int(on)}" if isinstance(on, bool) else "" + + def _send(self, text: str): + btrace("send>", text[:60]) + try: + with self.wlock: + self.proc.stdin.write(text + "\n") + self.proc.stdin.flush() + except OSError: # the pipe is gone: the engine died (not the client) + raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None + + def _control(self, cancel, on_token, stop_when=None): + """Reads the control lines of the request on them (GEN / BGEN), yielding None heartbeats. Calls on_token(id) + for each `T`; returns ("done", None) at DONE, or ("badm", continues) at BADM (after DONE). `stop_when()` + true sends STOP once (the request is then read to its DONE).""" + stopped = False + while True: + try: + line = self.lines.get(timeout=10.0) + except queue.Empty: + if cancel.is_set() and not stopped: + self._send("STOP") + stopped = True + yield None + continue + if line is None: + raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") + if not line.startswith(("PP ", "INFO")): + btrace("ctl<", self._ctl_mode, line.strip()[:60]) + if line.startswith("T "): + on_token(int(line[2:])) + if not stopped and (cancel.is_set() or (stop_when is not None and stop_when())): + self._send("STOP") + stopped = True + yield False # a token is pending (not a heartbeat) + elif line.startswith("PP "): + f = line.split() + if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): + self.progress = (int(f[1]), int(f[2])) + self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None + yield None + elif line.startswith("DONE"): + self._parse_done(line) + self._last_done = line + elif line.startswith("BADM "): + f = line.split() + self._ctl_result = ("badm", len(f) >= 3 and f[2] == "1") + return + elif line.startswith("YIELDED "): # the read gave way (BYIELD): + f = line.split() + if len(f) >= 3 and f[1].lstrip("-").isdigit() and f[2].isdigit(): + self._yielded = (int(f[1]), int(f[2])) + elif line.startswith("ERR"): + raise ValueError(line[4:].strip()) + if line.startswith("DONE") and self._ctl_mode == "solo": + self._ctl_result = ("done", None) + return + + def _drain_control(self, until: str, timeout: float = 300.0): + """After a consumer left early: read the control lines up to the next `until` line (DONE or BADM) so the next + request does not read this one's leftovers. Returns that line (None: the engine ended or never answered).""" + end = time.monotonic() + timeout + while time.monotonic() < end: + try: + line = self.lines.get(timeout=max(0.1, end - time.monotonic())) + except queue.Empty: + break + if line is None: + return None + if line.startswith("DONE"): + self._parse_done(line) + if line.startswith(until) or line.startswith("ERR"): + return line + return None + + def _release_slot_when_done(self, slot: int, stream: list[int] | None = None): + """A slot whose consumer left (a stop token, a stop string, a disconnect): BSTOP it and free it once the engine + says BDONE (in the background). `stream`: the prompt and every token of it so far - with the tokens still to + come before BDONE, all but the last are what the slot holds then (the next turn of its conversation).""" + try: + self._send(f"BSTOP {slot}") + except EngineDied: + pass + def wait(): + end = time.monotonic() + 600.0 + tail = list(stream or []) + while time.monotonic() < end: + try: + line = self.slot_q[slot].get(timeout=5.0) + except queue.Empty: + continue + if line is None: + tail = [] + break + if line.startswith("BT "): + try: + tail.append(int(line.split()[2])) + except (IndexError, ValueError): + tail = [] + if line.startswith("BDONE "): + break + self.slot_held[slot] = tail[:-1] if stream and tail else [] + with self.slot_cv: + self.slot_busy[slot] = False + self.slot_cv.notify_all() + threading.Thread(target=wait, daemon=True).start() + + YIELDS_MAX = 2 # #656: how often one request's prompt read gives way to a shorter waiting one + + def _take_control(self, cancel, plen: int, after_epoch: int | None = None): + """Waits for the control lines (one prompt read at a time), yielding None heartbeats; False when cancelled. + `after_epoch`: a request whose read gave way lets the requests waiting then go first.""" + entry = [plen] + with self.slot_cv: + self.waiting += 1 + self.wait_lens.append(entry) + beat = time.monotonic() + try: + while True: + with self.slot_cv: + turn = after_epoch is None or self.ctl_epoch > after_epoch or self.waiting <= 1 + if turn and self.ctl.acquire(timeout=0.5): + break + if not turn: + with self.slot_cv: + self.slot_cv.wait(timeout=0.5) + if cancel.is_set(): + return False + if time.monotonic() - beat >= 10.0: # a heartbeat every 10 s, as the engine's own wait + beat = time.monotonic() + yield None + finally: + with self.slot_cv: + self.waiting -= 1 + self.wait_lens.remove(entry) + with self.slot_cv: + self.ctl_epoch += 1 + self.slot_cv.notify_all() + return True + + SOLO_AGAIN_MAX = 2 # how often a request left alone in a slot goes back to the solo path + SOLO_AGAIN_MIN_LEFT = 32 # ... only with at least this many tokens still allowed (max_tokens) + + def _may_go_solo(self, left: int, times: int, embeddings) -> bool: + """A request decoding in a slot that is alone now (no other slot busy, nobody waiting) goes back to the solo + path with its MTP drafts: the engine continues it from the slot's sessions (its slot cache; INFO + slot_cache=1). STRATA_PARALLEL_SOLO=0 keeps it in the slot.""" + if (embeddings or times >= self.SOLO_AGAIN_MAX or left < self.SOLO_AGAIN_MIN_LEFT or + not (self.info or {}).get("slot_cache") or os.environ.get("STRATA_PARALLEL_SOLO") == "0"): + return False + with self.slot_cv: + return sum(1 for b in self.slot_busy if b) == 1 and self.waiting == 0 + + def _shorter_waiting(self, plen: int) -> bool: + """#656: someone waits for the control lines with a prompt under half this one's: worth giving way to.""" + with self.slot_cv: + return any(e[0] * 2 <= plen for e in self.wait_lens) + + def generate_batched(self, ids, max_new, sampling, cancel, embeddings=None): + """--batch. Alone (no slot busy, nobody waiting): the solo path (GEN, with drafts: the fastest stream) + - and when another request arrives meanwhile, this one is STOPped and continues in a batch slot (BGEN with + its prompt + what it generated: the engine reuses that prefix). Otherwise: BGEN into a free slot, then the + slot's own BT lines until BDONE. Several requests run at once; the control lines (prompt reading, admission) + are taken one request at a time - and a long prompt read gives way at a chunk boundary to a waiting request + with a much shorter prompt (#656: `BYIELD `; the part read waits in a slot and the read goes on after). + A consumer that stops early leaves the engine in step: the solo request is STOPped and read to its DONE, an + admission to its BADM, a slot is BSTOPped and freed at its BDONE.""" + self.progress = None + keys = self.sampling_keys(sampling or {}) + out: list[int] = [] + pending: list[int] = [] + prompt, left = list(ids), int(max_new) + ok = yield from self._take_control(cancel, len(prompt)) + if not ok: + return + holding = True + btrace("ctl acquired") + slot, gen0, reserved = None, None, None + phase = "none" # solo -> (admit -> slot) ; "done" once the engine has finished with this request + stop_sent = False + yields, solo_again = 0, 0 + try: + while True: # a request in a slot that is left alone goes back to the solo path + if not holding: + ok = yield from self._take_control(cancel, len(prompt)) + if not ok: + return + holding = True + with self.slot_cv: + alone = not any(self.slot_busy) and self.waiting == 0 + if alone and left > 1: + head = f"GENI {left}{keys} {embeddings}" if embeddings else f"GEN {left}{keys}" + self._send(f"{head} {','.join(str(int(t)) for t in prompt)}") + phase = "solo" + self._ctl_mode, self._ctl_result, self._yielded = "solo", None, None + def others(): + with self.slot_cv: + return self.waiting > 0 + for x in self._control(cancel, pending.append, stop_when=others): + while pending: + t = pending.pop(0) + out.append(t) + yield t + if x is None: # a heartbeat (False: a token, flushed above) + if (reserved is None and not out and not embeddings and yields < self.YIELDS_MAX and + self._shorter_waiting(len(prompt))): + with self.slot_cv: # the slot the part read will wait in + reserved = self.pick_slot(prompt) + if reserved is not None: + self.slot_busy[reserved] = True + if reserved is not None: + self._send(f"BYIELD {reserved}") + yield None + phase = "none" # its DONE is read + while pending: + t = pending.pop(0) + out.append(t) + yield t + if self._yielded is not None and reserved is not None and self._yielded[0] == reserved: + slot, reserved = reserved, None # gave way: the read goes on in that slot (below) + elif reserved is not None: # it did not give way: the slot is free again + with self.slot_cv: + self.slot_busy[reserved] = False + self.slot_cv.notify_all() + reserved = None + if slot is None: + finish = (self.last or {}).get("finish") if isinstance(self.last, dict) else None + left = int(max_new) - len(out) + if cancel.is_set() or left <= 0 or finish in ("stop", "length") or (out and out[-1] in EOS_IDS): + return + prompt = list(ids) + out # promoted: it continues in a batch slot from here + while True: + if slot is None: + # a free slot (they free themselves at BDONE, which needs no control lines): the one that holds + # the start of this prompt (its conversation's last turn), else the one used longest ago + with self.slot_cv: + while True: + slot = self.pick_slot(prompt) + if slot is not None: + self.slot_busy[slot] = True + break + self.slot_cv.wait(timeout=10.0) + if cancel.is_set(): + return + if self._yielded is not None: # it gave way: the others waiting then go first + self.slot_held[slot] = list(prompt[:self._yielded[1]]) + self._yielded = None + yields += 1 + self.ctl.release() + holding = False + with self.slot_cv: + epoch = self.ctl_epoch + ok = yield from self._take_control(cancel, len(prompt), after_epoch=epoch) + if not ok: + return + holding = True + while not self.slot_q[slot].empty(): + self.slot_q[slot].get_nowait() + head = f"BGENI {slot} {left}{keys} {embeddings}" if embeddings else f"BGEN {slot} {left}{keys}" + live = {"slot": slot, "state": "reading", "prompt_tokens": len(prompt), "generated": 0, + "started": time.time(), "first_token": None} + self.slot_live[slot] = live + self._send(f"{head} {','.join(str(int(t)) for t in prompt)}") + self.slot_held[slot] = [] # the admission overwrites what the slot held + phase = "admit" + self._ctl_mode, self._ctl_result, self._yielded = "batch", None, None + asked = False + for x in self._control(cancel, pending.append): + while pending: + t = pending.pop(0) + out.append(t) + yield t + if x is None: + if (not asked and not embeddings and yields < self.YIELDS_MAX and + self._shorter_waiting(len(prompt))): + self._send(f"BYIELD {slot}") + asked = True + yield None + cont = bool(self._ctl_result and self._ctl_result[1]) + phase = "slot" if cont else "none" + while pending: + t = pending.pop(0) + out.append(t) + yield t + if not cont and self._yielded is not None and self._yielded[0] == slot and not cancel.is_set(): + continue # gave way: again once the shorter request is in + break + self.ctl.release() + holding = False + if not cont: + return + live.update(state="decoding", first_token=time.time(), generated=len(out)) + gen0 = len(out) - 1 # the admission's own token: the slot feeds it first + going_solo = False + while True: + try: + line = self.slot_q[slot].get(timeout=10.0) + except queue.Empty: + if cancel.is_set() and not stop_sent: + self._send(f"BSTOP {slot}") + stop_sent = True + yield None + continue + if line is None: + phase = "none" + raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") + if line.startswith("BT "): + t = int(line.split()[2]) + out.append(t) + live["generated"] = len(out) + if cancel.is_set(): + if not stop_sent: + self._send(f"BSTOP {slot}") + stop_sent = True + continue + yield t + if not going_solo and not stop_sent and self._may_go_solo(int(max_new) - len(out), solo_again, + embeddings): + self._send(f"BSTOP {slot}") # alone now: on with the drafts (below) + going_solo = True + elif line.startswith("BDONE "): + phase = "none" + f = line.split() + if len(f) >= 5 and isinstance(self.last, dict): + self.last = {**self.last, "finish": f[3], "decode_ms": float(f[4]), + "generated": int(f[2]) if f[2].isdigit() else self.last.get("generated")} + # what the slot's sessions hold now: the prompt and every token fed (all but the last one) + self.slot_held[slot] = list(prompt) + out[gen0:-1] if len(out) > gen0 else [] + if (going_solo and f[3:4] == ["cancel"] and not cancel.is_set() and len(out) < int(max_new) + and not (out and out[-1] in EOS_IDS)): + # the solo path continues it: the engine copies the slot's sessions back (all but the + # last token are in them) and decodes with MTP drafts again + self.slot_live[slot] = None + self.slot_used[slot] = time.time() + with self.slot_cv: + self.slot_busy[slot] = False + self.slot_cv.notify_all() + slot, gen0 = None, None + prompt, left = list(ids) + out, int(max_new) - len(out) + solo_again += 1 + btrace("back to the solo path") + break + return + finally: + # a consumer that left early (or an error): keep the engine and this server in step + btrace("finally phase", phase, "slot", slot, "holding", holding) + try: + if phase == "solo": + self._send("STOP") + self._drain_control("DONE") + elif phase == "admit": + line = self._drain_control("BADM") + if line and line.startswith("BADM ") and line.split()[2:3] == ["1"]: + phase = "slot" + except EngineDied: + pass + if holding: + self.ctl.release() + if reserved is not None: + with self.slot_cv: + self.slot_busy[reserved] = False + self.slot_cv.notify_all() + if slot is not None: + self.slot_live[slot] = None + self.slot_used[slot] = time.time() + if phase == "slot": + self.slot_held[slot] = [] + stream = list(prompt) + out[gen0:] if gen0 is not None and len(out) > gen0 else None + self._release_slot_when_done(slot, stream) # freed at its BDONE + else: + with self.slot_cv: + self.slot_busy[slot] = False + self.slot_cv.notify_all() + + def pick_slot(self, prompt: list[int]) -> int | None: + """A free slot for `prompt` (the caller holds slot_cv): the one whose held tokens are the longest start of the + prompt (the engine then reads only the rest), else an empty one, else the one used longest ago - so the + conversations other slots hold stay for their next turns. None: every slot is busy.""" + free = [b for b in self.slot_order if not self.slot_busy[b]] + if not free: + return None + def held_prefix(b): + h = self.slot_held[b] + return len(h) if h and len(h) < len(prompt) and prompt[:len(h)] == h else 0 + best = max(free, key=held_prefix) + if held_prefix(best) > 0: + return best + return min(free, key=lambda b: (bool(self.slot_held[b]), self.slot_used[b])) + + def slots_view(self) -> list[dict]: + """/metrics: each batch slot - idle (with the tokens it holds for a next turn), reading or decoding.""" + now, view = time.time(), [] + for b in range(self.batch): + r = self.slot_live[b] + if r is None: + view.append({"slot": b, "state": "idle", "held_tokens": len(self.slot_held[b])}) + continue + ft = r.get("first_token") + view.append({"slot": b, "state": r["state"], "prompt_tokens": r["prompt_tokens"], + "generated": r["generated"], "elapsed_s": round(now - r["started"], 1), + "tok_s": round(r["generated"] / max(1e-6, now - ft), 1) if ft else None}) + return view + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + """Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt): + the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that + has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" + if getattr(self, "batch", 0): + yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings) + return + self.progress = None + self.prefill_tok_s_mean = None + # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) + head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \ + f"GEN {int(max_new)}{self.sampling_keys(sampling or {})}" + try: + self.proc.stdin.write(f"{head} {','.join(str(int(t)) for t in ids)}\n") + self.proc.stdin.flush() + except OSError: # the pipe is gone: the engine died (not the client) + raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None + done = False + # #481: how long the engine may stay silent from here. Until the first line: the request's first prompt + # chunk at the slowest prompt reading on top of silence_s; a PP line resets it to its own chunk's time. + silence = float(self.silence_s or 0) + allow = silence + min(len(ids), PP_CHUNK_MAX) / PP_FLOOR_TOK_S if silence > 0 else 0.0 + heard, read_to = time.monotonic(), 0 + try: + while True: + wait = 10.0 + if allow > 0: + wait = min(wait, allow - (time.monotonic() - heard)) + if wait <= 0: + done = True # no STOP and no drain: nothing is listening + raise self._silent(f"the engine said nothing for {time.monotonic() - heard:.0f} s during " + "the request") + try: + line = self.lines.get(timeout=wait) + except queue.Empty: + if cancel.is_set(): + return + if wait >= 10.0: + yield None # the 10 s heartbeat (the deadline's short waits are not) + continue + if line is None: + done = True + raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") + heard = time.monotonic() # any line is output: T, PP, RESUME, INFO ... + if line.startswith("T "): + allow = silence + if cancel.is_set(): + return + yield int(line[2:]) + elif line.startswith("PP "): + f = line.split() + if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): + self.progress = (int(f[1]), int(f[2])) # prompt progress, one per chunk: also a heartbeat (the + self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None + rate, chunk = self.prefill_tok_s_mean or 0.0, int(f[1]) - read_to + read_to = int(f[1]) + if silence > 0 and rate > 0 and chunk > 0: # #481: the next chunk, as long as this one + allow = max(silence, PP_SLACK * chunk / rate) + if cancel.is_set(): # lines reset the 10 s wait, so without this a long prompt + return # would send no keep-alives at all) + yield None + elif line.startswith("RESUME "): # the reused tokens: the first chunk starts after them + try: + read_to = int(line.split()[1]) + except (IndexError, ValueError): + pass + elif line.startswith("DONE"): + self._parse_done(line) + done = True + return + elif line.startswith("ERR"): + done = True + raise ValueError(line[4:].strip()) + finally: + if not done: # the consumer stopped early: stop the engine, drain to DONE + if self.can_stop: + try: + self.proc.stdin.write("STOP\n") + self.proc.stdin.flush() + except OSError: + pass + # #481: never an untimed wait here - it holds the request FIFO, and an engine that lost step never + # answers. An engine that honours STOP gets the current allowance in all (a STOP during a prompt + # chunk is seen after it); an older one runs on to max_new, so each line only has to come in time. + heard = time.monotonic() + while True: + left = allow - (time.monotonic() - heard) if allow > 0 else None + try: + if left is not None and left <= 0: + raise queue.Empty + line = self.lines.get(timeout=left) + except queue.Empty: + raise self._silent("the engine did not finish the request after it was stopped (STOP) " + f"within {allow:.0f} s") from None + if line is None or line.startswith("ERR"): + break + if line.startswith("DONE"): + self._parse_done(line) + break + if not self.can_stop: + heard = time.monotonic() + + def _silent(self, what: str) -> EngineSilent: + """#481: end an engine that lost step with the server (its main thread waits for a command the server never + sends), so the next request starts it again: killed now, its GPU and RAM go back with the process.""" + self.silent_note = ("The engine and the server lost step (issue #481; a very slow PC can raise " + "\"engine_silence_s\" in the config, 0 = wait forever). If it happens again, please add " + "the end of the engine log to github.com/Niko1221/Strata/issues/481.") + self.ended = True # not alive from now: the next request restarts it + proc = self.proc + try: + proc.kill() + proc.wait(timeout=20) # restart() -> close() handles one that is still exiting + except (OSError, AttributeError, subprocess.TimeoutExpired): + pass + return EngineSilent(f"{what}; the server ended the engine") + + def close(self): + """End the engine process: QUIT first (the engine frees its memory itself - unpinning tens of GB can take + a while), then terminate, then kill, each given 20 s. Raises EngineStuck when it still runs after all three.""" + if self.proc is None: + return + try: + if self.proc.poll() is None: + try: + self.proc.stdin.write("QUIT\n") + self.proc.stdin.flush() + self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown + self.proc.wait(timeout=20) + except (OSError, ValueError, subprocess.TimeoutExpired): + self.proc.terminate() + self.proc.wait(timeout=20) + except subprocess.TimeoutExpired: + self.proc.kill() + try: + self.proc.wait(timeout=20) + except subprocess.TimeoutExpired: + raise EngineStuck("Strata is still releasing GPU/RAM; retry unloading after it exits") from None + except OSError: + pass + finally: + if self.proc.poll() is not None: + if self.pump is not None: + self.pump.join(timeout=2) + self.proc.stdin.close() + self.proc.stdout.close() + if self.log not in (None, subprocess.DEVNULL): + self.log.close() + self.proc = None + self.ended = True + self.progress, self.last = None, {} + + +class Vision: + """The resident image encoder: `strata-vision` (llama.cpp mtmd + the mmproj file) reads `ENC ` + lines and writes each image's embeddings; results are cached by the image's hash, so a conversation that + sends the same picture again (every turn, with most clients) encodes it once.""" + + def __init__(self, cfg: dict, log=None, env: dict | None = None): + args = [cfg["exe"], "--mmproj", cfg["mmproj"], "--model", cfg["model"]] + if cfg.get("gpu"): + args.append("--gpu") + if cfg.get("threads"): + args += ["--threads", str(cfg["threads"])] + if cfg.get("max_tokens"): + args += ["--max-tokens", str(cfg["max_tokens"])] + self.dir = Path(tempfile.mkdtemp(prefix="strata-vision-")) + self.spawn = (args, log, env) # to start it again after an unload + self.stopped = False + self._start() + self.lock = threading.Lock() + self.cache: dict[str, tuple[Path, int]] = {} + + def _start(self): + args, log, env = self.spawn + self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL, + text=True, encoding="utf-8", bufsize=1, env=env) + contain(self.proc) + line = self.proc.stdout.readline() + if not line.startswith("READY"): + raise RuntimeError("the vision encoder did not start: " + line.strip()) + self.stopped = False + + def alive(self) -> bool: + return not self.stopped and self.proc.poll() is None + + def unload(self): + """Stop the encoder process (its VRAM or RAM goes back); the encoded images stay cached on disk.""" + self.close() + self.stopped = True + + def restart(self): + """Start the encoder again after an unload (or if it died); the cache of encoded images is kept.""" + try: + self.proc.kill() + except OSError: + pass + self._start() + + @staticmethod + def load(source: str) -> bytes: + if source.startswith("data:"): + return base64.b64decode(source.split(",", 1)[1]) + if source.startswith(("http://", "https://")): + req = urllib.request.Request(source, headers={"User-Agent": "strata"}) + with urllib.request.urlopen(req, timeout=60) as r: + return r.read() + path = source[7:] if source.startswith("file://") else source + if path and os.path.isfile(path): + return Path(path).read_bytes() + raise ValueError("an image must be a data: URL, an http(s) URL or a local file path") + + @staticmethod + def normalize(data: bytes) -> bytes: + """The formats strata-vision's decoder (stb_image) reads pass through; anything else is converted to PNG.""" + if data[:3] == b"\xff\xd8\xff" or data[:8] == b"\x89PNG\r\n\x1a\n" or data[:2] == b"BM" or \ + data[:6] in (b"GIF87a", b"GIF89a"): + return data + try: + import io + from PIL import Image + except ImportError: + raise ValueError("this image format needs Pillow (python -m pip install pillow); JPEG, PNG, BMP and " + "GIF work without it") from None + try: + im = Image.open(io.BytesIO(data)) + im.load() + except Exception as e: + raise ValueError(f"the image could not be read ({e})") from None + if im.mode in ("RGBA", "LA", "P") and "transparency" in im.info or im.mode in ("RGBA", "LA"): + im = im.convert("RGBA") + bg = Image.new("RGB", im.size, (255, 255, 255)) # transparent areas become white, not black + bg.paste(im, mask=im.split()[-1]) + im = bg + elif im.mode != "RGB": + im = im.convert("RGB") + out = io.BytesIO() + im.save(out, format="PNG") + return out.getvalue() + + def encode(self, source: str) -> tuple[Path, int]: + """-> (embeddings file, number of image tokens).""" + data = self.normalize(self.load(source)) + key = hashlib.sha256(data).hexdigest()[:32] + with self.lock: + if key in self.cache: + return self.cache[key] + img, out = self.dir / f"{key}.img", self.dir / f"{key}.sve" + img.write_bytes(data) + try: + self.proc.stdin.write(f"ENC {img} {out}\n") + self.proc.stdin.flush() + line = self.proc.stdout.readline().strip() + finally: # #352: also when the encoder's pipe is gone + img.unlink(missing_ok=True) + if not line.startswith("OK"): + raise ValueError("the image could not be read: " + (line[4:] if line.startswith("ERR") else + "the vision encoder stopped")) + self.cache[key] = (out, int(line.split()[1])) + if len(self.cache) > 64: # oldest first + old = next(iter(self.cache)) + self.cache.pop(old)[0].unlink(missing_ok=True) + return self.cache[key] + + def close(self): + try: + self.proc.stdin.write("QUIT\n") + self.proc.stdin.flush() + self.proc.wait(timeout=10) + except Exception: + self.proc.kill() + + +def gpu_list(cfg: dict) -> list[int]: + """The config's "gpu": one card (2), or several for a layer split ([0, 2] or "0,2"), numbered as nvidia-smi + numbers them; [] when it names none.""" + g = cfg.get("gpu") + if g is None or g == "": + return [] + items = g if isinstance(g, (list, tuple)) else str(g).split(",") + return [int(str(x).strip()) for x in items if str(x).strip() != ""] + + +def effort_end_args(cfg: dict, exe: str, tok) -> list[str] | None: + """#458 (opt-in): the engine arguments for "effort_position": "end" - the id of "system" as --tail-role-token, so + the engine checkpoints in front of the trailing effort turn - or None when the config leaves it at the top (the + default) or the engine is too old for it (said once; the prompt stays the default one). ValueError for a value + other than "start" / "end".""" + pos = cfg.get("effort_position", "start") + if pos not in ("start", "end"): + raise ValueError(f'"effort_position" must be "start" (the default) or "end", not {pos!r}') + if pos == "start": + return None + try: + with open(exe, "rb") as f: + known = b"--tail-role-token" in f.read() + except OSError: + known = False + role = tok.encode("system", parse_special=True) + if not known or len(role) != 1: + print("[strata] effort_position \"end\" needs engine 0.1.39 or newer (--tail-role-token): the reasoning " + "effort stays at the top of the prompt", flush=True) + return None + print("[strata] effort_position end: a request's non-default reasoning effort goes right before the answer, so " + "changing it keeps the cached conversation", flush=True) + return ["--tail-role-token", str(role[0])] + + +def engine_silence_s(cfg: dict) -> float: + """#481: the config's "engine_silence_s" - seconds an engine may print nothing during a request before the server + ends it (default ENGINE_SILENCE_S; 0 = wait forever). ValueError for anything but a number >= 0.""" + v = cfg.get("engine_silence_s") + if v is None: + return ENGINE_SILENCE_S + if isinstance(v, bool) or not isinstance(v, (int, float)) or v < 0: + raise ValueError(f'"engine_silence_s" must be a number of seconds >= 0 (0 = no limit), not {v!r}') + return float(v) + + +def layer_split_value(cfg: dict) -> str: + """#644: the config's "layer_split" as the engine's --layer-split value: "auto" (the default), or the FIRST LAYER of + each later GPU's share - one rising number per GPU after the first, e.g. "24,36,42" for 4 GPUs (layers 0-23 on the + first card, 24-35, 36-41, 42 to the end) - as a string or a JSON list ([24, 36, 42]). ValueError with the format + and an example for anything else, such as per-card layer counts ("24,16,12,12").""" + v = cfg.get("layer_split") + if v is None or (isinstance(v, str) and v.strip().lower() in ("", "auto")): + return "auto" + n = len(gpu_list(cfg)) + items = v if isinstance(v, (list, tuple)) else str(v).split(",") if isinstance(v, (str, int)) else None + vals = [] + for x in items or []: + try: + if isinstance(x, bool) or isinstance(x, float): + raise ValueError + vals.append(int(str(x).strip())) + except ValueError: + vals = None + break + want = max(n - 1, 1) + example = ",".join(str(round(48 * (i + 1) / (want + 1))) for i in range(want)) + hint = (f'"layer_split" is the first layer of each later GPU, one rising number per GPU after the first ' + f'({want} for {n} GPUs), not a count of layers per card - e.g. "{example}" (or [{example.replace(",", ", ")}])' + f' for an even share of 48 layers, or "auto" (the default) to place them by each card\'s free VRAM') + if not vals: + raise ValueError(f"{hint}; got {v!r}") + if n > 1 and len(vals) != n - 1: + raise ValueError(f"{hint}; got {len(vals)} number(s) ({v!r}) for {n} GPUs") + if vals[0] < 2 or any(b <= a for a, b in zip(vals, vals[1:])): + raise ValueError(f"{hint}; got {v!r}, which does not rise from 2 or more") + return ",".join(str(x) for x in vals) + + +def engine_args(cfg: dict) -> list[str]: + """The engine's arguments: the config's, and with several GPUs the layer split across them ("layer_split" in the + config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32"; see + layer_split_value).""" + args = list(cfg["args"]) + if len(gpu_list(cfg)) > 1 and "--layer-split" not in args: + args += ["--layer-split", layer_split_value(cfg)] + # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV + if len(gpu_list(cfg)) > 1 and cfg.get("split_skip_if_fits") and "--split-skip-if-fits" not in args: + args.append("--split-skip-if-fits") + # #533 (opt-in): "vram_elastic": true - the expert cache in segments, so POST /v1/vram can give VRAM back to other + # programs and take it back; "vram_segment_mib" sets the segment size (the engine's default: 512) + if cfg.get("vram_elastic") is True and "--vram-elastic" not in args: + args.append("--vram-elastic") + seg = cfg.get("vram_segment_mib") + if isinstance(seg, int) and not isinstance(seg, bool) and seg > 0 and "--vram-segment-mib" not in args: + args += ["--vram-segment-mib", str(seg)] + args += parallel_args(cfg, args) + return learned_profile_args(cfg, args) + + +PARALLEL_MAX = 8 # the engine's batch window holds at most 8 rows (kVerifyMaxT) + + +def parallel_args(cfg: dict, args: list[str]) -> list[str]: + """#465 (opt-in): "parallel": N in the config - up to N requests decode together in the engine's batch slots + (--batch N); more wait their turn. 1 or absent: one request at a time, as before. A value the engine cannot use + is said and passed on: the engine warns and adjusts (recommend, never force).""" + if "--batch" in args or "--slots" in args: + return [] + n = cfg.get("parallel") + if n is None or n is False: + return [] + if isinstance(n, bool) or not isinstance(n, int): + print(f'[strata] "parallel" must be a whole number of requests (2..{PARALLEL_MAX}), not {n!r}: ignored', + flush=True) + return [] + if n <= 1: + return [] + if n > PARALLEL_MAX: + print(f'[strata] "parallel": {n} - the engine runs at most {PARALLEL_MAX} requests together; it will use ' + f"{PARALLEL_MAX}", flush=True) + return ["--batch", str(n)] + + +def profile_shape(path: str) -> tuple[int, int] | None: + """An expert profile's (layers, experts per layer), from its header (tools/make_profile.py's format), or None + when the file is missing, is not one or is shorter than the pairs its header promises.""" + try: + with open(path, "rb") as f: + head = f.read(24) + size = os.fstat(f.fileno()).st_size + except OSError: + return None + if len(head) < 24 or head[:4] != b"STRP": + return None + _, nl, ne, _, n = struct.unpack("<5I", head[4:]) + return (nl, ne) if size >= 24 + 4 * n else None + + +def learned_profile_args(cfg: dict, args: list[str]) -> list[str]: + """#477 (opt-in): "expert_profile_save": "" in the config has the engine (0.1.36+) save what its adaptive + tier learned there - on QUIT and every "expert_profile_save_every" minutes (10 by default, 0 = at QUIT only) - + and the next start begins from it instead of the config's --expert-profile, when it is a profile of the same + model (its header's layers and experts match); otherwise from the config's own, as before. A relative path is + the engine's (the config's "cwd"). Without the key, the arguments are the config's, unchanged.""" + save = cfg.get("expert_profile_save") + if not isinstance(save, str) or not save.strip() or "--expert-profile-save" in args: + return args + args = args + ["--expert-profile-save", save] + every = cfg.get("expert_profile_save_every") + if isinstance(every, (int, float)) and not isinstance(every, bool) and every >= 0: + args += ["--expert-profile-save-every", str(every)] + if "--expert-profile" in args[:-1]: + i = args.index("--expert-profile") + 1 + here = cfg.get("cwd") or "." + learned = profile_shape(save if os.path.isabs(save) else os.path.join(here, save)) + base = profile_shape(args[i] if os.path.isabs(args[i]) else os.path.join(here, args[i])) + if learned is not None and learned == base: + args[i] = save + return args + + +def hip_visible(cfg: dict) -> list[int]: + """AMD: the devices the engine should see, as the HIP runtime numbers them (HIP_VISIBLE_DEVICES). + + On Linux setup's KFD order is HIP's order, so the config's "gpu" is it. On Windows setup finds the cards in the + display-adapter order, and an integrated Radeon that HIP also enumerates takes ordinal 0 and pushes the discrete + card to 1 (#325): setup records the ordinal `strata-device --list-devices` gave the card as "hip_ordinal", which + wins for a one-card config. Without it (a config from before), the config's "gpu".""" + ordinal = cfg.get("hip_ordinal") + if ordinal is not None and str(ordinal).strip() != "" and len(gpu_list(cfg)) <= 1: + try: + return [int(str(ordinal).strip())] + except ValueError: + pass + return gpu_list(cfg) + + +def child_env(cfg: dict) -> dict: + """The engine's environment: the CUDA libraries setup installed (pip's nvidia packages, or the toolkit that + compiled it) first on the library search path.""" + env = dict(os.environ) + if hip_visible(cfg) and cfg.get("backend") == "hip": # AMD: numbered as HIP numbers them (hip_visible) + env["HIP_VISIBLE_DEVICES"] = ",".join(str(i) for i in hip_visible(cfg)) + elif gpu_list(cfg): # issue #51: the GPU(s) to run on, numbered as nvidia-smi does; CUDA's + env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # own default order (fastest first) can number the cards otherwise + env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in gpu_list(cfg)) + for k, v in (cfg.get("env") or {}).items(): # engine settings the config carries (AMD: the GEMM tuning table) + env[str(k)] = str(v) + dirs = [d for d in cfg.get("lib_dirs") or [] if Path(d).is_dir()] + if dirs: + var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH" + env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else [])) + return env + + +def vision_env(cfg: dict, env: dict) -> dict: + """The image encoder's environment: the engine's, unless the config's vision section names its own "cuda_device" + (numbered like nvidia-smi) - then the encoder runs on that card alone, so a spare GPU can hold it while the engine + keeps all of its own cards' VRAM (#408, Efs-O). Without it, nothing changes.""" + dev = (cfg.get("vision") or {}).get("cuda_device") + if dev is None: + return env + env = dict(env) + if cfg.get("backend") == "hip": + env["HIP_VISIBLE_DEVICES"] = str(dev) + else: + env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" + env["CUDA_VISIBLE_DEVICES"] = str(dev) + return env + + +class ByteTokenizer: + """Tiny stand-in tokenizer for tests without the pack: one id per UTF-8 byte, specials as ids >= 256.""" + SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"] + + ALWAYS = () # specials matched without parse_special (type 4, as ) + + def encode(self, text, parse_special=False, plain=()): + out, i = [], 0 + while i < len(text): + for k, s in enumerate(self.SPECIALS): + if (parse_special or s in self.ALWAYS) and text.startswith(s, i) and not any( + a <= i < b for a, b in plain): + out.append(256 + k) + i += len(s) + break + else: + out.extend(text[i].encode("utf-8")) + i += 1 + return out + + def decode(self, ids, errors="replace"): + raw = bytearray() + for t in ids: + raw += self.SPECIALS[t - 256].encode() if t >= 256 else bytes([t]) + return raw.decode("utf-8", errors=errors) + + +# ------------------------------------------------------------------------------------------------ core +class Detokenizer: + """Incremental decode: each token's bytes go through an incremental UTF-8 decoder, which emits the complete + characters and holds a multi-byte character split across tokens until it is complete (invalid bytes become + U+FFFD, as a whole decode with errors="replace" makes them). Constant time per token - the old re-decode of + every generated id cost 2 ms per token after 8K tokens and 4 ms after 16K (perf-review F-1). A tokenizer + without `token_bytes` (the tests' byte tokenizer) keeps the re-decode.""" + + def __init__(self, tok): + self.tok, self.ids, self.sent = tok, [], 0 + self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") if hasattr(tok, "token_bytes") else None + + def pending(self) -> bool: + """A character is split across the tokens so far: its first bytes are held.""" + if self.inc is not None: + return bool(self.inc.getstate()[0]) + return self.tok.decode(self.ids).endswith("\ufffd") + + def push(self, t: int) -> str: + if self.inc is not None: + return self.inc.decode(self.tok.token_bytes(t)) + self.ids.append(t) + text = self.tok.decode(self.ids) + if text.endswith("�"): + return "" + delta, self.sent = text[self.sent:], len(text) + return delta + + +class Service: + def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next", + vision: Vision | None = None, sampling_defaults: dict | None = None, + fit_max_tokens: bool = False): + self.engine, self.tok, self.template, self.model, self.vision = engine, tokenizer, template, model_name, vision + self.fit_max_tokens = fit_max_tokens # --fit-max-tokens: clamp the output cap instead of 400 + self.aliases: list[str] = [] # #297: other names of the model (the config's `aliases`) + self.sampling_defaults = dict(sampling_defaults or {}) # the run config's `sampling` block + self.shared = {} # the web app's Chat settings for every client (POST /settings) + self.shared_path = None # where they are kept between starts (next to the config) + self.fifo = threading.Lock() + self.embeddings = threading.local() # the current request's image embeddings file (GENI) + self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) + # #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system + # turn before the answer instead of the top of the prompt, so switching it keeps the cached conversation + self.effort_end = False + self.conv_log = ConvCacheLog() # #596: the parked conversations, from the engine's log + self.config_path = None # #564: the run config the web page's Settings view edits + self.config_lock = threading.Lock() + # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that + # matters); empty = no CORS headers at all, as before + self.cors_origins: list[str] = [] + # #321: origins that count as Strata's own page for /settings and MCP tools, e.g. the web app reached through a + # reverse proxy or tunnel whose Host differs ("https://strata.example.com"); never a wildcard + self.trusted_origins: list[str] = [] + # DNS rebinding: extra Host names this server answers to (the config's allowed_hosts, $STRATA_ALLOWED_HOSTS; + # "*" = any), and every name it answers to, which serve() works out from the address it listens on + self.allowed_hosts: list[str] = [] + self.host_names: set[str] = set(LOOPBACK_NAMES) + self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now + self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window + # "parallel" (the engine's batch slots): every running request's own status and rate window; self.status + # then says busy while any runs and shows the newest one + self.live_reqs: dict[int, tuple[dict, collections.deque]] = {} + # #332: the API request monitor (/api-monitor) keeps the last 100 requests' prompts and answers in memory, + # so it is off unless the config's "api_monitor" (or --api-monitor) turns it on + self.api_monitor = False + self.api_requests = collections.deque(maxlen=100) # bounded I/O in memory; no headers or API keys + self.request_trace = threading.local() + self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics) + # since the server started (the Monitor's totals, issue #35) + self.totals = {"since": time.time(), "requests": 0, "prompt_tokens": 0, "reused": 0, "output_tokens": 0, + "prompt_ms": 0.0, "decode_ms": 0.0, + "drafts_offered": 0, "drafts_accepted": 0} # #457: the MTP drafts, summed where reported + self.last_timings = None # the last finished request's, llama.cpp's names (/v1/status) + self.last_request_at = None # when a request last started or finished + self.started_at = time.time() + self.status_lock = threading.Lock() + self.mcp = None # serve/mcp.py's McpHub when MCP servers are configured + # sharing the GPU with other programs (all off by default): unload the engine after this many idle seconds, + # only start it again when this much VRAM is free, and run this command first (e.g. to unload another + # server's model); the next request after an unload starts the engine again + self.idle_unload_s = 0 + self.min_free_vram_mib = 0 + self.before_load = None + self.vram_reserve = None # #533: the last POST /v1/vram reserve (None: the start's) + self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) + self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off) + self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False + self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) + + tokenizer.encode("<|endoftext|>", parse_special=True)) + + def loaded(self) -> bool: + return not hasattr(self.engine, "alive") or self.engine.alive() + + def set_aliases(self, aliases) -> None: + """#297: the config's `aliases` - a list of names (or one comma-separated string), like llama-server's --alias. + ValueError for anything else.""" + if aliases is None: + aliases = [] + if isinstance(aliases, str): + aliases = aliases.split(",") + if not isinstance(aliases, list) or not all(isinstance(x, str) for x in aliases): + raise ValueError(f"aliases={aliases!r}: expected a list of model names") + names = [] + for x in (x.strip() for x in aliases): + if x and x != self.model and x not in names: + names.append(x) + self.aliases = names + + def model_names(self) -> list[str]: + return [self.model, *self.aliases] + + def model_for(self, req) -> str: + """The name to answer with: the request's own when it is the model's name or an alias (#297), else the model's. + Other names are still served, as before.""" + asked = req.get("model") if isinstance(req, dict) else None + return asked if isinstance(asked, str) and asked in self.aliases else self.model + + def reasoning_budget(self, req) -> int | None: + """#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens`, else the + config's. 0 (or less) means no budget, so a request can turn a configured one off. ValueError (a 400) for + anything that is not a whole number.""" + value = (req or {}).get("reasoning_budget_tokens") if isinstance(req, dict) else None + if value is None: + value = self.reasoning_budget_tokens + if isinstance(value, float) and value.is_integer(): + value = int(value) + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"reasoning_budget_tokens={value!r}: expected a whole number of tokens (0: no budget)") + return value if value > 0 else None + + def _vision_down(self) -> bool: + return self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive() + + def free_vram_mib(self) -> int | None: + """Free VRAM on the engine's (first) GPU, from NVML (AMD backend: amdgpu's sysfs files, #301); None when it can't + be read (then nothing is refused).""" + try: + if getattr(self, "backend", None) == "hip": + from serve.telemetry import free_vram_mib + return free_vram_mib(int(getattr(self, "gpu_index", 0) or 0), amd=True) + from serve.telemetry import _Nvml + nv = _Nvml(int(getattr(self, "gpu_index", 0) or 0)) + if not nv.ok(): + return None + m = nv.Mem() + if nv.lib.nvmlDeviceGetMemoryInfo(nv.dev, ctypes.byref(m)) != 0: + return None + return int(m.free >> 20) + except Exception: + return None + + def ensure_loaded(self): + """Start the engine if it is not running (unloaded, or it died - issue #27), after the before_load hook and + the free-VRAM check. The caller holds self.fifo.""" + if self.loaded() and not self._vision_down(): + return + if self.before_load: + cmd = self.before_load + print(f"[strata] before loading: {cmd if isinstance(cmd, str) else ' '.join(map(str, cmd))}", flush=True) + try: + subprocess.run(cmd, shell=isinstance(cmd, str), timeout=120, stdin=subprocess.DEVNULL) + except (OSError, subprocess.SubprocessError) as e: + print(f"[strata] the before_load command failed ({e}); loading anyway", flush=True) + if self.min_free_vram_mib: + free = self.free_vram_mib() + deadline = time.time() + 15 # memory another process just gave back can take a moment + while free is not None and free < self.min_free_vram_mib and time.time() < deadline: + time.sleep(0.5) + free = self.free_vram_mib() + if free is not None and free < self.min_free_vram_mib: + raise GpuBusy(f"the GPU is in use by another program: {free} MiB of VRAM free, the model needs " + f"{self.min_free_vram_mib} (min_free_vram_mib) - it stays unloaded until that is free") + if self._vision_down(): # first, as at a start: a GPU encoder takes its VRAM before + print("[strata] starting the vision encoder again ...", flush=True) # the engine sizes its cache + self.vision.restart() + if self.loaded(): + return + if getattr(self.engine, "unloaded", False): + print("[strata] loading the model again (it was unloaded) ...", flush=True) + else: + code = self.engine.exit_code() if hasattr(self.engine, "exit_code") else None + print(f"[strata] the engine had stopped (exit code {code}); starting it again " + "(a minute or two) ...", flush=True) + self.engine.restart() + print("[strata] the engine is running again", flush=True) + if self.vram_reserve is not None and hasattr(self.engine, "vram"): # #533: the reserve asked for last + try: + self.engine.vram(self.vram_reserve) + except (ValueError, EngineDied) as e: + print(f"[strata] the VRAM reserve ({self.vram_reserve} MiB) was not applied: {e}", flush=True) + + vram_wait_s = 300.0 # #533: how long POST /v1/vram waits for a running request + + def vram(self, reserve_mib: int | None) -> dict: + """#533, POST /v1/vram: keep `reserve_mib` of VRAM free for other programs (None: the reserve the engine + started with), applied between requests - a request that is running finishes first (up to wait_s). Only an + engine started with --vram-elastic (the config's "vram_elastic": true) can do it; it never resizes on its own. + An unloaded engine applies it when it loads. -> {"status": ..., and the engine's figures}.""" + if not hasattr(self.engine, "vram"): + raise ValueError("this engine cannot resize its VRAM use") + if not self.fifo.acquire(timeout=self.vram_wait_s): + raise ModelBusy("a request is still running; try again when it has finished") + # parallel requests do not hold the fifo: the engine's control lines (a prompt being admitted) are taken too, + # and the engine refuses a resize while a slot decodes + ctl = getattr(self.engine, "ctl", None) if getattr(self.engine, "batch", 0) else None + if ctl is not None and not ctl.acquire(timeout=self.vram_wait_s): + self.fifo.release() + raise ModelBusy("a request is still running; try again when it has finished") + try: + if not self.loaded(): + self.vram_reserve = reserve_mib + return {"status": "not loaded", "reserve_mib": reserve_mib, + "note": "applied when the model loads"} + out = self.engine.vram(reserve_mib) + self.vram_reserve = reserve_mib + print(f"[strata] VRAM: {out.get('vram_free_mib')} MiB free, expert cache {out.get('expert_cache_mib')} of " + f"{out.get('expert_cache_full_mib')} MiB ({out.get('expert_slots')} experts)", flush=True) + return {"status": "ok", **out} + finally: + if ctl is not None: + ctl.release() + self.fifo.release() + + def _say_died(self, e: Exception) -> None: + """The server window's line for an engine that died (or was ended, #481) in the middle of a request.""" + note = self.engine.death_note() if hasattr(self.engine, "death_note") else "" + log = getattr(self.engine, "log_path", None) + print(f"[strata] {e}. {note} The next request starts the engine again." + f"{' Its log: ' + log if log else ''}", flush=True) + + def load(self): + """POST /load and every generation request: start the engine now if it is unloaded (raises GpuBusy).""" + # a request is on its way: the idle thread must not unload between this and the request's own start + self.last_request_at = time.time() + if self.loaded() and not self._vision_down(): + return + trace = getattr(self.request_trace, "record", None) + waiting = time.perf_counter() + with self.fifo: + loading = time.perf_counter() + if trace is not None: + with self.status_lock: + trace["queue_s"] += round(loading - waiting, 3) + trace["state"] = "loading" + try: + self.ensure_loaded() + finally: + if trace is not None: + with self.status_lock: + trace["load_s"] += round(time.perf_counter() - loading, 3) + trace["state"] = "queued" + + def unload(self, idle_for: float | None = None) -> str: + """Stop the engine between requests: "unloaded", "not loaded", "busy" (a request is running or waiting, or + with idle_for: one ran more recently than that) or "unsupported".""" + if not hasattr(self.engine, "unload"): + return "unsupported" + if not self.fifo.acquire(blocking=False): + return "busy" + try: + if not self.engine.alive(): + return "not loaded" + with self.status_lock: + if self.status.get("busy") or self.status.get("queued"): + return "busy" + if idle_for is not None and time.time() - (self.last_request_at or self.started_at) < idle_for: + return "busy" + self.engine.unload() + if self.vision is not None and hasattr(self.vision, "unload"): + self.vision.unload() + print(f"[strata] model unloaded{f' after {idle_for:.0f} s idle' if idle_for else ''}; " + "the next request loads it again", flush=True) + return "unloaded" + finally: + self.fifo.release() + + def start_idle_unload(self): + if not self.idle_unload_s or not hasattr(self.engine, "unload"): + return + print(f"[strata] the model unloads after {self.idle_unload_s} s without requests", flush=True) + + def loop(): + while True: + time.sleep(max(1.0, min(30.0, self.idle_unload_s / 4))) + try: + self.unload(idle_for=self.idle_unload_s) + except EngineStuck as e: # tried again at the next turn; the thread keeps running + print(f"[strata] idle unload: {e}", flush=True) + threading.Thread(target=loop, daemon=True).start() + + def set_shared(self, defaults) -> dict: + """The Chat settings every client gets for what it leaves out; {} / None = clients use their own again.""" + self.shared = clean_shared_defaults(defaults) + if self.shared_path: + try: + if self.shared: + Path(self.shared_path).write_text(json.dumps(self.shared, indent=1), encoding="utf-8") + else: + Path(self.shared_path).unlink(missing_ok=True) + except OSError as e: + print(f"[strata] could not save the shared settings: {e}", flush=True) + return self.shared + + def with_shared(self, req: dict, api: str) -> dict: + """The request with the shared thinking level and max tokens filled in where it has none of its own.""" + s = self.shared + if not s: + return req + req = dict(req) + if "max_tokens" in s and not req.get("max_tokens") and not req.get("max_completion_tokens"): + req["max_tokens"] = s["max_tokens"] + effort = s.get("reasoning_effort") + if effort: + if api == "openai": + ctk = req.get("chat_template_kwargs") if isinstance(req.get("chat_template_kwargs"), dict) else {} + if not req.get("reasoning_effort") and not req.get("reasoning") and \ + "enable_thinking" not in ctk and "reasoning_effort" not in ctk: + req["reasoning_effort"] = effort + elif not req.get("thinking") and not req.get("output_config"): + if effort == "none": + req["thinking"] = {"type": "disabled"} + else: + req["output_config"] = {"effort": effort} + return req + + def start_telemetry(self): + """The hardware sampler behind GET /metrics (serve/telemetry.py), recording this server's tok/s too.""" + if getattr(self, "telemetry", None) is None: + from serve.telemetry import Telemetry + self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s(), "tok_s_mean": self._tok_s_mean(), + "prefill_tok_s_mean": self._prefill_tok_s_mean()}, + gpu_index=int(getattr(self, "gpu_index", 0) or 0), + gpu_indices=getattr(self, "gpu_indices", None), + amd=getattr(self, "backend", None) == "hip") + + def _tok_s(self): + """tok/s over the last RATE_WINDOW_S seconds. Returns 0.0 while nothing is generating. With parallel requests: + the sum of theirs.""" + with self.status_lock: + many = [(dict(st), list(rt)) for st, rt in self.live_reqs.values()] + if many: + return sum(self._rate_of(st, rt) for st, rt in many) + with self.status_lock: + s = dict(self.status) + rate = list(self.rate) + return self._rate_of(s, rate) + + @staticmethod + def _rate_of(s, rate): + if not s.get("busy") or not s.get("first_token"): + return 0.0 + now = time.time() + newest = rate[-1] if rate else None + oldest = next(((t, g) for t, g in rate if now - t <= RATE_WINDOW_S), None) + if newest and oldest and newest[0] - oldest[0] >= RATE_MIN_SPAN_S: + return max(0.0, (newest[1] - oldest[1]) / (newest[0] - oldest[0])) + return s["generated"] / max(RATE_MIN_SPAN_S, now - s["first_token"]) + + def _tok_s_mean(self): + """The whole-request mean since the first token (the old formula), kept so the two can be compared.""" + with self.status_lock: + many = [dict(st) for st, _ in self.live_reqs.values()] or [dict(self.status)] + return sum(s["generated"] / max(1e-6, time.time() - s["first_token"]) for s in many + if s.get("busy") and s.get("first_token")) + + def _prefill_tok_s_mean(self): + """Engine-reported mean over newly read tokens, excluding the cached prefix.""" + with self.status_lock: + reading = self.status.get("busy") and self.status.get("first_token") is None + return getattr(self.engine, "prefill_tok_s_mean", None) if reading else 0.0 + + def begin_request(self, path, req): + """#332: a monitor record for this request, or None when the monitor is off (nothing is kept then).""" + if not self.api_monitor: + return None + raw = json.dumps(req, ensure_ascii=False, indent=2) + record = {"id": uuid.uuid4().hex[:12], "path": path, "model": req.get("model") or self.model, + "started_at": time.time(), "state": "queued", "stream": bool(req.get("stream")), + "response_format": (req.get("response_format") or {}).get("type") + if isinstance(req.get("response_format"), dict) else None, + "input": raw[:262144], "input_truncated": len(raw) > 262144, + "output": "", "reasoning": "", "output_truncated": False, "reasoning_truncated": False, + "queue_s": 0.0, "load_s": 0.0, "first_token_s": None, + "_clock": time.perf_counter()} + with self.status_lock: + self.api_requests.append(record) + self.request_trace.record = record + return record + + def request_records(self, request_id=None): + with self.status_lock: + records = list(self.api_requests) + if request_id: + record = next((r for r in records if r["id"] == request_id), None) + if record is None: + return None + return {k: v for k, v in record.items() if not k.startswith("_")} + return [{k: v for k, v in r.items() + if k not in ("input", "output", "reasoning", "response") and not k.startswith("_")} + | {"wallclock_s": r.get("wallclock_s", round(time.perf_counter() - r["_clock"], 3))} + for r in reversed(records)] + + def metrics(self, all_requests=False) -> dict: + """GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and + the hardware (with a minute of history per series).""" + with self.status_lock: + s = dict(self.status) + if self.live_reqs: # parallel requests: the newest one's status + s = {**s, **dict(list(self.live_reqs.values())[-1][0]), "queued": s.get("queued", 0)} + hist = list(self.history) + totals = dict(self.totals) + now = time.time() + progress = getattr(self.engine, "progress", None) + if s.get("busy") and s.get("first_token") is None: + state = "reading" + elif s.get("busy"): + state = "generating" + elif not self.loaded(): + state = "unloaded" + else: + state = "idle" + live = {"state": state, "queued": s.get("queued", 0), "phase": s.get("phase") if s.get("busy") else None, + "prompt_tokens": s.get("prompt_tokens") if s.get("busy") else None, + "prompt_read": None, "prompt_total": None, "generated": s.get("generated") if s.get("busy") else None, + "max_tokens": s.get("max_tokens") if s.get("busy") else None, + "elapsed_s": round(now - s["started"], 1) if s.get("busy") and s.get("started") else None, + "tok_s": round(self._tok_s(), 1) if state == "generating" else None, + "tok_s_mean": round(self._tok_s_mean(), 1) if state == "generating" else None, + "prefill_tok_s_mean": getattr(self.engine, "prefill_tok_s_mean", None) if s.get("busy") else None, + "tok_s_window_s": RATE_WINDOW_S if state == "generating" else None} + if state == "reading" and progress: + live["prompt_read"], live["prompt_total"] = progress + par = int(getattr(self.engine, "batch", 0) or 0) + if par: # #465: the requests running together, slot by slot + with self.status_lock: + running = len(self.live_reqs) + slots = self.engine.slots_view() if hasattr(self.engine, "slots_view") else [] + # the requests in flight that are not in a slot: the one alone on the solo path, or waiting their turn + in_slots = sum(1 for x in slots if x["state"] != "idle") + live.update(parallel=par, running=running, slots=slots, outside_slots=max(0, running - in_slots), + waiting=int(getattr(self.engine, "waiting", 0) or 0)) + if running and state == "idle": + live["state"] = "generating" + engine = {"model": self.model, "max_context": self.engine.max_context, "images": self.vision is not None, + **dict(getattr(self.engine, "info", {}) or {})} + tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}} + parked = self.conv_log.poll(getattr(self.engine, "log_path", None), getattr(self.engine, "log_start", None)) + return {"engine": engine, "live": live, "requests": hist[::-1][:None if all_requests else 12], + "conversation_cache": conversation_cache_view(engine, hist, totals, parked), + "requests_kept": len(hist), "totals": totals, "hardware": tel["now"], + "hardware_static": + tel["static"], "history": tel["history"], "time": now} + + def v1_status(self) -> dict: + """GET /v1/status: what this server is and does, for a client that would rather ask than guess (a front-end + that polls its OpenAI-compatible server's status, collabosm's for one): the model and its window, images, + the APIs, what is running, and the last request's timings in llama.cpp's names. /metrics has the rest.""" + with self.status_lock: + s, totals = dict(self.status), dict(self.totals) + last_t, last_at = (dict(self.last_timings) if self.last_timings else None), self.last_request_at + tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "static": {}} + hw, static = tel.get("now") or {}, tel.get("static") or {} + + def scaled(v, unit, digits=0): + return round(v / unit, digits) if isinstance(v, (int, float)) else None + + busy, ctx = bool(s.get("busy")), self.engine.max_context + images = self.vision is not None + return { + "service": "strata", "model": self.model, + "loaded": self.loaded(), "auto_load": hasattr(self.engine, "restart"), + "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", + "constrained_decoding": False, "stream_buffered": True}, + "engine": (getattr(self.engine, "info", {}) or {}).get("version"), + "started": int(self.started_at), "uptime_s": int(time.time() - self.started_at), + "cache_max_tokens": ctx, + "context": {"native": ctx, "max_positions": ctx}, + # one request at a time (more wait their turn), or "parallel": N batch slots (#465) + "concurrency": {"serving": max(1, int(getattr(self.engine, "batch", 0) or 0)), + "requested": max(1, int(getattr(self.engine, "batch", 0) or 0))}, + "dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"], + "vision": {"enabled": images, "available": images, "error": None}, + "activity": {"requests": totals["requests"] + int(busy), "in_flight": int(busy) + int(s.get("queued") or 0), + "last_request_at": int(last_at) if last_at else None}, + "last_timings": last_t, + "vram": dict((getattr(self.engine, "info", {}) or {}).get("vram") or {}, + elastic=bool((getattr(self.engine, "info", {}) or {}).get("vram_elastic"))), + "machine": { + "at": int(time.time()), + "gpu": {"name": static.get("gpu_name"), "used_mib": scaled(hw.get("gpu_mem_used"), 2 ** 20), + "total_mib": scaled(hw.get("gpu_mem_total"), 2 ** 20), "util_pct": hw.get("gpu_util"), + "temp_c": hw.get("gpu_temp"), "power_w": hw.get("gpu_power")} if static.get("gpu_name") else None, + "ram": {"used_gib": scaled(hw.get("ram_used"), 2 ** 30, 1), + "total_gib": scaled(hw.get("ram_total"), 2 ** 30, 1)} if hw.get("ram_total") else None}} + + def render_prompt(self, messages, tools, kwargs) -> str: + """The template rendered. #458: with `effort_end`, a request with a non-default effort (low, medium or no + thinking) is rendered as a default one up to the answer - the same prompt start, so the conversation cache + keeps it - and its effort follows in a short system turn right before the answer (thinking off: the template's + empty thinking block). The engine (--tail-role-token) checkpoints in front of that turn.""" + effort = kwargs.get("reasoning_effort") + off = kwargs.get("enable_thinking") is False + if not self.effort_end or (not off and effort in (None, "", "xhigh", "high")): + return self.template.render(messages, tools=tools, **kwargs) + base = {k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")} + history = self.template.render(messages, tools=tools, add_generation_prompt=False, **base) + full = self.template.render(messages, tools=tools, add_generation_prompt=True, **kwargs) + mine = self.template.render(messages, tools=tools, add_generation_prompt=False, **kwargs) + if not full.startswith(mine): # a template this cannot take apart: rendered as asked + return full + tail = "" if off else EFFORT_TURN.format(EFFORT_TEXT.get(effort, EFFORT_TEXT["medium"])) + return history + tail + full[len(mine):] + + def encode_prompt(self, messages, tools, kwargs) -> list[int]: + """The request's prompt: the template rendered and tokenized. #537: a / written inside a + message's text is encoded as the text it is, not as the model's reasoning markers (the template's own are).""" + marked, marked_tools, changed = mark_think_literals(messages, tools) + prompt = self.render_prompt(marked, marked_tools, kwargs) + if not changed: + return self.tok.encode(prompt, parse_special=True) + prompt, plain = unmark_think_literals(prompt) + return self.tok.encode(prompt, parse_special=True, plain=plain) + + def prepare(self, messages, tools, kwargs, max_new=None): + """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": + the rest of the context.""" + ids = self.encode_prompt(messages, tools, kwargs) + self.embeddings.path = None + images = images_of(messages) + if images: + if self.vision is None: + raise ValueError("this server was started without the vision encoder (run setup again and choose " + "'vision'), so it cannot read images") + pad = self.tok.encode(IMAGE_PAD, parse_special=True)[0] + start = self.tok.encode(VISION_START, parse_special=True)[0] + # Encode only while the engine is idle: the engine and the image encoder (a separate process) must not + # run on the GPU at the same time - an encode during a running request left that request stuck at + # "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the + # same FIFO as the requests. + with self.fifo: + encoded = [self.vision.encode(src) for src in images] + # one <|image_pad|> per image -> one per image token. Only the markers the template writes for an image + # (right after <|vision_start|>) are images: the same text inside a message (an agent reading these docs, + # #150) is kept as plain text, or it took an image's place and the counts no longer matched. + literal = self.tok.encode(IMAGE_PAD, parse_special=False) + out, k = [], 0 + for j, t in enumerate(ids): + if t == pad and j > 0 and ids[j - 1] == start and k < len(encoded): + out += [pad] * encoded[k][1] + k += 1 + elif t == pad: + out += literal + else: + out.append(t) + if k != len(encoded): + raise ValueError("the prompt and its images do not match") + ids = out + combined = self.vision.dir / f"req-{uuid.uuid4().hex[:12]}.sve" + with open(combined, "wb") as f: + for path, _ in encoded: + f.write(path.read_bytes()) + self.embeddings.path = combined + ctx = self.engine.max_context + if ctx <= 0: + if getattr(self.engine, "starting", False): # #344: (re)starting, not a prompt that is too long + raise EngineStarting("the engine is starting (a minute or two); try again shortly") + # a failed restart leaves max_context 0: check against the last known context, so the request reaches + # run() - which starts the engine again - instead of failing with "exceeds the context (0)" forever + ctx = getattr(self.engine, "known_ctx", 0) + if ctx <= 0: + raise EngineStarting("the engine is starting (a minute or two); try again shortly") + room = ctx - CTX_SLACK - len(ids) + if max_new is None or max_new <= 0 or (self.fit_max_tokens and room < 1): + if room < 1: + raise ValueError(f"prompt ({len(ids)} tokens) leaves no room to answer in the context " + f"({ctx}); requests are never truncated") + max_new = room + elif max_new > room: + if not self.fit_max_tokens: + raise ValueError(f"prompt ({len(ids)} tokens) + max tokens ({max_new}) exceeds the context " + f"({ctx}); requests are never truncated. Send a smaller " + f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the " + "model's strata-.json to shorten it to the room left (#545)") + max_new = max(1, room) # --fit-max-tokens: a shorter completion beats a 400 + return ids, kwargs.get("enable_thinking", True) is not False, max_new + + def _note(self, n, evs, st=None, rate=None): + with self.status_lock: + s = self.status if st is None else st + s["generated"] = n + if s.get("first_token") is None: + s["first_token"] = time.time() + (self.rate if rate is None else rate).append((time.time(), n)) # the live rate's window (RATE_WINDOW_S) + for ev in evs: + if ev.kind == "reasoning": + s["phase"] = "thinking" + elif ev.kind == "content": + s["phase"] = "answering" + elif ev.kind == "tool_start": + s["phase"], s["tool"] = f"writing a tool call: {ev.call.name}", ev.call.name + elif ev.kind == "tool_call": + s["phase"] = "tool call complete" + s["tail"] = ((s.get("tail") or "") + (ev.text or ""))[-600:] + + def _progress(self, last_print, every=1.0, st=None): + """A progress line in the server window every `every` seconds while a request runs.""" + now = time.time() + if now - last_print < every: + return last_print + with self.status_lock: + s = dict(self.status if st is None else st) + el = now - s.get("started", now) + if s.get("first_token") is None: + pr = getattr(self.engine, "progress", None) # (position reached, prompt tokens): a reused prefix counts + done = f"{pr[0]:,} of {pr[1]:,}" if pr and pr[1] else f"{s.get('prompt_tokens', 0):,}" # as read (#29) + print(f"[strata] reading the prompt: {done} tokens, {el:.0f} s so far", flush=True) + else: + rate = s["generated"] / max(1e-6, now - s["first_token"]) + print(f"[strata] {s['phase']}: {s['generated']} of max {s.get('max_tokens')} tokens, {rate:.1f} tok/s, " + f"{el:.0f} s", flush=True) + return now + + def run(self, ids, thinking, tools, max_new, sampling, cancel) -> Iterator[tuple[str, object]]: + """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}).""" + budget = self.reasoning_budget(sampling) if thinking else None # #123: opt-in, off by default + defaults = {**self.sampling_defaults, **self.shared} # the config's, then the Chat settings shared with apps + if defaults: # the request's own fields win (explicit 0 stays greedy) + req_values = {k: v for k, v in (sampling or {}).items() if v is not None} + sampling = {**defaults, **req_values} + parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True) + detok, n, finish = Detokenizer(self.tok), 0, "length" + run_tok, run_len, repeated = None, 0, False # #606: the current run of one repeated token + thinking_n = 0 # tokens written while thinking (Responses' reasoning_tokens) + timings, before = None, None # this request's timings; the engine's `last` before it + raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) + emb = getattr(self.embeddings, "path", None) + # Identity token: only a DONE line replaces engine.last, so a request that died, errored or was + # disconnected must not have the PREVIOUS request's decode figures recorded as its own. + engine_last0 = getattr(self.engine, "last", None) + trace = getattr(self.request_trace, "record", None) + waiting = time.perf_counter() + # #465: with "parallel" (the engine's batch slots) requests run at once: each keeps its own status and rate + # window (self.status says busy while any runs); one at a time they are self.status / self.rate, as before + par = bool(getattr(self.engine, "batch", 0)) + st = {} if par else self.status + rate = collections.deque(maxlen=32) if par else self.rate + with self.status_lock: + self.status["queued"] += 1 + try: + # --batch: the engine runs several requests at once (StrataEngine.generate_batched orders them) + with (contextlib.nullcontext() if getattr(self.engine, "batch", 0) else self.fifo): + try: + with self.status_lock: + if trace is not None: + trace["queue_s"] += round(time.perf_counter() - waiting, 3) + trace["state"] = "generating" + self.status["queued"] -= 1 + # issue #27: it died in an earlier request (or was unloaded) - start it again instead of failing + # (parallel requests do not hold the fifo: one of them starts it, the others wait for that) + with (self.fifo if par else contextlib.nullcontext()): + self.ensure_loaded() + with self.status_lock: + st.update(busy=True, phase="reading the prompt", prompt_tokens=len(ids), + generated=0, started=time.time(), first_token=None, tool=None, tail="", + max_tokens=max_new) + if par: + self.live_reqs[id(st)] = (st, rate) + self.status.update(st) + self.last_request_at = time.time() + rate.clear() # the previous request's samples must not leak into this one + before = getattr(self.engine, "last", None) + last_print = time.time() + prompt, thought = ids, 0 # thought: the reasoning tokens so far (the budget's count) + while True: + gen = self.engine.generate(prompt, max_new - n, sampling, cancel, embeddings=emb) if emb \ + else self.engine.generate(prompt, max_new - n, sampling, cancel) + seg, wrap, leaving = [], False, False # this pass's tokens; the budget is reached; closed + try: + for t in gen: + if t is None: # heartbeat while the engine is quiet + last_print = self._progress(last_print, st=st) + yield "ping", None + continue + n += 1 + if trace is not None and trace["first_token_s"] is None: + with self.status_lock: + trace["first_token_s"] = round(time.perf_counter() - trace["_clock"], 3) + if t in self.stop_ids: + finish = "stop" + raw_ids.append(t) + break + raw_ids.append(t) + seg.append(t) + thinking_n += parser.state == "reasoning" + run_len = run_len + 1 if t == run_tok else 1 + run_tok = t + if self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens: + repeated = True # #606: a degenerate output, not an answer: end it here + break + evs = parser.feed(detok.push(t)) + self._note(n, evs, st, rate) + last_print = self._progress(last_print, st=st) + for ev in evs: + yield "event", ev + if budget and parser.state == "reasoning": + thought += 1 + # at a clean point: no tag held back, no character split across tokens + if thought >= budget and not parser.buf and not detok.pending(): + wrap = True + break + except EngineDied as e: + finish = "error" + self._say_died(e) + raise + except ValueError as e: # the engine's ERR line (it may have ended after it) + finish = "error" + print(f"[strata] the engine reported an error: {e}", flush=True) + raise + except GeneratorExit: # the client went away: an engine that never acknowledges + leaving = True # the STOP below is ended, but no error replaces this + raise + finally: + try: + gen.close() # STOP+drain to THIS request's DONE while still holding the + # fifo, so a stop-token break can't leave the shared engine + # queue mid-drain for the next request to read as its own DONE + except EngineSilent as e: # #481: the STOP was never acknowledged: the engine is ended + finish = "error" + self._say_died(e) + if not leaving and not cancel.is_set(): + raise + if not wrap or cancel.is_set(): + break + # #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a + # short wrap-up and ) and let it answer: the next pass's prompt is this one plus what + # was generated plus the wrap-up, so the engine continues from the prefix it already holds. + budget = None + extra = self.tok.encode(REASONING_WRAP_UP, parse_special=True) + if max_new - n - len(extra) < 1: + break # no room left to answer: "length", as without a budget + print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking", + flush=True) + for t in extra: + n += 1 + raw_ids.append(t) + thinking_n += parser.state == "reasoning" + evs = parser.feed(detok.push(t)) + self._note(n, evs, st, rate) + for ev in evs: + yield "event", ev + prompt = prompt + seg + extra + if cancel.is_set(): + finish = "cancel" + elif repeated: + print(f"[strata] the reply repeated one token ({self.tok.decode([run_tok])!r}) " + f"{run_len} times in a row: ended as \"length\" (repeat_stop_tokens in " + "strata-.json; 0 turns this off). If a new request with a short prompt does the " + "same, restart the server and report it (#606)", flush=True) + except GeneratorExit: # the client disconnected mid-stream + finish = "disconnect" + raise + finally: + # #266: settle this request's status, history and totals while still holding the fifo: once + # it is released the next request sets its own status, which this must not record or clear + with self.status_lock: + if st.get("busy"): + # only this request's DONE counts: same object means no DONE arrived (death, error, + # disconnect) + last = dict(getattr(self.engine, "last", {}) or {}) \ + if getattr(self.engine, "last", None) is not engine_last0 else {} + started = st.get("started", time.time()) + cvec = (getattr(self.engine, "info", {}) or {}).get("cvec", 0) + loaded = str(cvec) not in ("0", "", "None") + hit_rate = round(last["hits"] / last["lookups"], 3) if last.get("lookups") else None + # #588: the share the GPU read over PCIe (--pcie-frac) or another GPU computed - not in + # the hit rate's lookups, which is the VRAM share of the rest (None: an older engine) + routed = (last.get("lookups") or 0) + (last.get("offloaded") or 0) + pcie_share = round(last["offloaded"] / routed, 3) \ + if last.get("offloaded") is not None and routed else None + seen = prompt_tokens_seen(len(ids), last) # #471: < len(ids) when cancelled mid-read + self.history.append({ + "projection": (sampling or {}).get("experimental_speed_projection") is not False + if loaded else None, + "time": started, "duration_s": round(time.time() - started, 1), "finish": finish, + "prompt_tokens": seen, "reused": last.get("reused"), "output_tokens": n, + # the request's whole prompt, and the tokens read of it (None: an older engine) + "prompt_total": len(ids), "prompt_read": last.get("prompt_read"), + "engine_generated": last.get("generated"), + "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"), + "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1) + if n and last.get("generated") and last.get("decode_ms") else None, + "hit_rate": hit_rate, "pcie_share": pcie_share, "ram_blobs": last.get("ram_blobs"), + "file_blobs": last.get("file_blobs"), "file_mb": last.get("file_mb"), + # #457: the speculative drafts from the DONE line (None: the engine did not say) + "drafts_offered": last.get("drafts_offered"), + "drafts_accepted": last.get("drafts_accepted")}) + t = self.totals + t["requests"] += 1 + t["prompt_tokens"] += seen + t["reused"] += last.get("reused") or 0 + t["output_tokens"] += n + t["prompt_ms"] += last.get("prompt_ms") or 0.0 + t["decode_ms"] += last.get("decode_ms") or 0.0 + t["drafts_offered"] += last.get("drafts_offered") or 0 + t["drafts_accepted"] += last.get("drafts_accepted") or 0 + fresh = getattr(self.engine, "last", None) + if fresh is not None and fresh is not before: # the engine's clock for THIS request + timings = request_timings(seen, n, last) + self.last_timings = dict(timings, at=int(time.time())) if timings else None + self.last_request_at = time.time() + now = time.time() + el = now - st.get("started", now) + ft = st.get("first_token") + rate = n / max(1e-6, now - ft) if ft else 0.0 + hit_msg = f", expert cache {hit_rate*100:.1f}% hit" if hit_rate is not None else "" + if hit_msg and pcie_share: + hit_msg += f" (+{pcie_share*100:.1f}% of the routed experts over PCIe)" + print(f"[strata] done: {n} tokens in {el:.0f} s ({rate:.1f} tok/s) " + f"({finish}, cancel={cancel.is_set()}){hit_msg}", flush=True) + if finish == "length" and parser.state == "reasoning": # #530 + print("[strata] the reply reached max tokens while still thinking, so it has no " + "answer: a thinking budget (reasoning_budget_tokens, in the request or in " + "strata-.json for every request) leaves room to answer", flush=True) + if os.environ.get("STRATA_DEBUG") and raw_ids: + print(f"[strata] raw: {self.tok.decode(raw_ids)!r}", flush=True) + st["busy"] = False + st.pop("tail", None) # #212: the answer's end is not kept once it is done + st.pop("tool", None) + if par: + self.live_reqs.pop(id(st), None) + if self.live_reqs: # the newest request still running + self.status.update(list(self.live_reqs.values())[-1][0]) + else: + self.status.update(busy=False) + self.status.pop("tail", None) + self.status.pop("tool", None) + finally: + if emb: + Path(emb).unlink(missing_ok=True) + for ev in parser.finish(): + yield "event", ev + yield "done", {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), + "timings": timings, "reasoning_tokens": thinking_n} + + +def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int: + """#471: the prompt tokens a request got through - all of them, unless the engine's DONE line says a cancel stopped + its prompt read part-way (then the reused ones plus those read). /metrics' history and totals count these, so a + cancelled read is neither recorded as the whole prompt nor given a rate from tokens it never read. An engine + before 0.1.36 does not say (no `prompt_read`): the whole prompt, as before.""" + read = last.get("prompt_read") + if read is None or last.get("finish") != "cancel": + return prompt_tokens + return min(prompt_tokens, int(last.get("reused") or 0) + int(read)) + + +def request_timings(prompt_tokens: int, generated: int, last: dict) -> dict | None: + """One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's own clock + (StrataEngine.last): prompt_n is what was read, cache_n what the conversation cache already held. None when the + engine keeps no clock (MockEngine).""" + if last.get("prompt_ms") is None: + return None + cache_n = int(last.get("reused") or 0) + prompt_n, prompt_ms, decode_ms = max(0, prompt_tokens - cache_n), float(last["prompt_ms"]), float(last.get("decode_ms") or 0) + decoded = int(last.get("generated") or generated) # the engine's count gives its rate, as /metrics does + return {"cache_n": cache_n, "prompt_n": prompt_n, "prompt_ms": round(prompt_ms, 1), + "prompt_per_token_ms": round(prompt_ms / prompt_n, 3) if prompt_n else None, + "prompt_per_second": round(prompt_n / (prompt_ms / 1000), 1) if prompt_n and prompt_ms > 0 else None, + "predicted_n": generated, "predicted_ms": round(decode_ms, 1), + "predicted_per_token_ms": round(decode_ms / decoded, 3) if decoded else None, + "predicted_per_second": round(decoded / (decode_ms / 1000), 1) if decoded and decode_ms > 0 else None, + # the speculative drafts, as llama.cpp names them (from PR #83, @mikicvi): only when the engine reported them + **({"draft_n": int(last["drafts_offered"]), "draft_n_accepted": int(last["drafts_accepted"])} + if last.get("drafts_offered") is not None else {})} + + +def _debug_req(api, req, messages, tools, max_new, thinking, prompt_tokens): + """One compact line per request while diagnosing blank/empty turns. Set STRATA_DEBUG=1 to enable.""" + if not os.environ.get("STRATA_DEBUG"): + return + last = messages[-1] if messages else {} + body = last.get("content") + if isinstance(body, list): + body = " ".join(p.get("text", "") for p in body if isinstance(p, dict)) + preview = (str(body or "")[:80]).replace("\n", " ") + print(f"[strata] req {api}: msgs={len(messages)} tools={len(tools or [])} " + f"max_tokens_raw={req.get('max_tokens')!r}/{req.get('max_completion_tokens')!r} " + f"max_new={max_new} thinking={thinking} stream={bool(req.get('stream'))} " + f"prompt_tokens={prompt_tokens} last={last.get('role')!r}:{preview!r}", flush=True) + + +# ------------------------------------------------------------------------------------------------ MCP tool loop +def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, max_req, sampling, cancel, + mcp_names): + """Service.run with the MCP tools executed here: the model writes a call to an MCP tool, the server runs it, adds + the call and its result to the conversation and lets the model continue - up to `max_rounds` times. Yields what + Service.run yields (text, thinking, the request's own tool calls) plus ("mcp", {...}) for the tool activity, and + one ("done", ...) at the very end with the output tokens of every round. + + `mcp_names`: the MCP tools this request offered; any other call is one of the request's own tools and ends the + turn as always (the client answers it). MCP calls written in the same answer are then not run (their results + could not reach the model before the client's).""" + max_rounds = int(hub.settings["max_rounds"]) + total, rounds, done = 0, 0, None + messages = list(messages) + while True: + text, reasoning, calls, own_calls = [], [], [], 0 + for kind, x in svc.run(ids, thinking, tools, max_new, sampling, cancel): + if kind == "done": + done = x + continue + if kind == "event": + ev: Event = x + if ev.call is not None and ev.call.name in mcp_names: + if ev.kind == "tool_start": # the model has started writing a call: say so at once + yield "mcp", {"event": "start", "id": ev.call.id, "name": ev.call.name} + elif ev.kind == "tool_call": + calls.append(ev.call) + continue # its argument pieces are not streamed to the client + if ev.kind == "tool_call": + own_calls += 1 + elif ev.kind == "content": + text.append(ev.text) + elif ev.kind == "reasoning": + reasoning.append(ev.text) + yield kind, x + total += done["completion_tokens"] + run_them = calls and not own_calls and done["finish"] == "stop" and not cancel.is_set() + if run_them and rounds >= max_rounds: + yield "mcp", {"event": "limit", "max_rounds": max_rounds} + run_them = False + if not run_them: + for c in calls: # announced, never run: close them in the client's view + yield "mcp", {"event": "result", "id": c.id, "ok": False, "skipped": True, "text": "not run", + "chars": 0, "truncated": False, "ms": 0} + break + rounds += 1 + results = [] + for c in calls: + s, tool = hub.routes().get(c.name, (None, c.name)) + yield "mcp", {"event": "call", "id": c.id, "name": c.name, "server": s.name if s else None, + "tool": tool, "arguments": c.arguments, "round": rounds} + # The call runs on a thread while this generator keeps yielding heartbeats: they reach the client as + # keep-alives, which is how a client that went away (the web app's Stop) is noticed during a slow tool. + box = {} + + def work(c=c, box=box): + try: + box["r"] = hub.call(c.name, c.arguments, cancel) + except McpCancelled: + box["cancelled"] = True + worker = threading.Thread(target=work, daemon=True) + worker.start() + try: + while worker.is_alive(): + worker.join(1.0) + if worker.is_alive(): + yield "ping", None + except GeneratorExit: + cancel.set() # the client is gone: stop the tool too + raise + if "r" not in box: + break + r = box["r"] + print(f"[strata] tool {c.name}: {'ok' if r['ok'] else 'error'}, {r['chars']:,} characters in " + f"{r['ms'] / 1000:.1f} s{' (truncated for the model)' if r['truncated'] else ''}", flush=True) + results.append(r["text"]) + yield "mcp", {"event": "result", "id": c.id, **{k: r[k] for k in ("ok", "text", "chars", "truncated", "ms")}} + if cancel.is_set() or len(results) < len(calls): + done = {**done, "finish": "cancel"} + break + messages.append({"role": "assistant", "content": "".join(text).strip(), + **({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}), + "tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]}) + messages += [{"role": "tool", "content": r} for r in results] + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req) + yield "done", {**done, "completion_tokens": total, "prompt_tokens": len(ids)} + + +# ------------------------------------------------------------------------------------------------ OpenAI +def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None): + """`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with + an empty delta and a `strata_mcp` field, which only the web app reads.""" + cid, created = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time()) + model = svc.model_for(req) + + def chunk(delta, finish=None): + return {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model, + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]} + + yield chunk({"role": "assistant", "content": ""}) + calls = 0 + streamed = {} # tool call id -> index, for calls sent piece by piece + finished = set() # ... and the ones whose final tool_call came (#211) + for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel): + if kind == "ping": + yield None + elif kind == "mcp": + c = chunk({}) + c["strata_mcp"] = x + yield c + elif kind == "event": + ev: Event = x + if ev.kind == "reasoning" and ev.text: + yield chunk({"reasoning_content": ev.text}) + elif ev.kind == "content" and ev.text: + yield chunk({"content": ev.text}) + elif ev.kind == "tool_start": + streamed[ev.call.id] = calls + calls += 1 + yield chunk({"tool_calls": [{"index": streamed[ev.call.id], "id": ev.call.id, "type": "function", + "function": {"name": ev.call.name, "arguments": ""}}]}) + elif ev.kind == "tool_args": + yield chunk({"tool_calls": [{"index": streamed[ev.call.id], "function": {"arguments": ev.text}}]}) + elif ev.kind == "tool_call" and ev.call.id in streamed: + finished.add(ev.call.id) + elif ev.kind == "tool_call": + yield chunk({"tool_calls": [{"index": calls, "id": ev.call.id, "type": "function", + "function": {"name": ev.call.name, + "arguments": json.dumps(ev.call.arguments, ensure_ascii=False)}}]}) + calls += 1 + else: + # a streamed call without its final tool_call is one the output ended inside: not "tool_calls" (#211) + whole = calls and streamed.keys() <= finished + finish = "tool_calls" if whole and x["finish"] == "stop" else {"cancel": "stop"}.get(x["finish"], x["finish"]) + last = chunk({}, finish) + pt = x.get("prompt_tokens", len(ids)) # after MCP rounds: the last round's prompt + last["usage"] = {"prompt_tokens": pt, "completion_tokens": x["completion_tokens"], + "total_tokens": pt + x["completion_tokens"], + # the part of the prompt the conversation cache already held (OpenAI's field) + "prompt_tokens_details": {"cached_tokens": x.get("reused") or 0}} + if x.get("timings"): + last["timings"] = x["timings"] # llama.cpp's field: the speed its clients show + yield last + + +def _is_json(text: str) -> bool: + try: + json.loads(text) + return True + except ValueError: + return False + + +def openai_collect(chunks) -> dict: + content, reasoning, by_index, last, mcp = [], [], {}, None, [] + for c in chunks: + if c is None: # a heartbeat + continue + if c.get("strata_mcp"): + mcp.append(c["strata_mcp"]) + d = c["choices"][0]["delta"] + content.append(d.get("content") or "") + reasoning.append(d.get("reasoning_content") or "") + for tc in d.get("tool_calls") or []: # streamed calls arrive in pieces: merge them by index + cur = by_index.setdefault(tc.get("index", len(by_index)), {"id": None, "type": "function", + "function": {"name": "", "arguments": ""}}) + cur["id"] = tc.get("id") or cur["id"] + fn = tc.get("function") or {} + cur["function"]["name"] += fn.get("name") or "" + cur["function"]["arguments"] += fn.get("arguments") or "" + last = c + calls = [by_index[i] for i in sorted(by_index)] + if last["choices"][0]["finish_reason"] != "tool_calls": + calls = [c for c in calls if _is_json(c["function"]["arguments"])] # a call the output ended inside (#211) + msg = {"role": "assistant", "content": "".join(content) or None} + if "".join(reasoning): + msg["reasoning_content"] = "".join(reasoning) + if calls: + msg["tool_calls"] = calls + if mcp: + msg["strata_mcp"] = mcp + out = {"id": last["id"], "object": "chat.completion", "created": last["created"], "model": last["model"], + "choices": [{"index": 0, "message": msg, "finish_reason": last["choices"][0]["finish_reason"]}], + "usage": last["usage"]} + if last.get("timings"): + out["timings"] = last["timings"] + return out + + +def structured_chunks(chunks, validator): + """Buffer structured streams so a client never receives unvalidated content.""" + buffered = [] + heartbeat = time.monotonic() + try: + for chunk in chunks: + if chunk is not None: + buffered.append(chunk) + if chunk is None or time.monotonic() - heartbeat >= 1: + heartbeat = time.monotonic() + yield None + result = openai_collect(buffered) + choice = result["choices"][0] + content = validated_json(choice["message"]["content"], validator, choice["finish_reason"]) + yield buffered[0] + delta = {"content": content} + if choice["message"].get("reasoning_content"): + delta["reasoning_content"] = choice["message"]["reasoning_content"] + yield {**buffered[0], "choices": [{"index": 0, "delta": delta, "finish_reason": None}]} + yield buffered[-1] + finally: + chunks.close() + + +# ------------------------------------------------------------------------------------------------ Anthropic +def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel): + mid = "msg_" + uuid.uuid4().hex[:24] + yield "message_start", {"type": "message_start", "message": { + "id": mid, "type": "message", "role": "assistant", "model": svc.model_for(req), "content": [], + "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": len(ids), "output_tokens": 0}}} + index, open_kind, used_tool = -1, None, False + + def close(): + return ("content_block_stop", {"type": "content_block_stop", "index": index}) + + streamed, finished = set(), set() # calls sent piece by piece; those whose final tool_call came (#211) + for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel): + if kind == "ping": + yield None + continue + if kind == "event": + ev: Event = x + if ev.kind == "tool_args": + yield "content_block_delta", {"type": "content_block_delta", "index": index, + "delta": {"type": "input_json_delta", "partial_json": ev.text}} + continue + if ev.kind == "tool_call" and ev.call.id in streamed: + finished.add(ev.call.id) + continue + want = {"reasoning": "thinking", "content": "text", "tool_call": "tool_use", "tool_start": "tool_use"}[ev.kind] + if ev.kind not in ("tool_call", "tool_start") and not ev.text: + continue + if ev.kind == "tool_start": + streamed.add(ev.call.id) + used_tool = True + if open_kind != want or want == "tool_use": + if open_kind is not None: + yield close() + index += 1 + open_kind = want + block = {"thinking": {"type": "thinking", "thinking": "", "signature": ""}, + "text": {"type": "text", "text": ""}, + "tool_use": {"type": "tool_use", "id": ev.call.id if ev.call else "", "name": + ev.call.name if ev.call else "", "input": {}}}[want] + yield "content_block_start", {"type": "content_block_start", "index": index, "content_block": block} + if want == "thinking": + yield "content_block_delta", {"type": "content_block_delta", "index": index, + "delta": {"type": "thinking_delta", "thinking": ev.text}} + elif want == "text": + yield "content_block_delta", {"type": "content_block_delta", "index": index, + "delta": {"type": "text_delta", "text": ev.text}} + elif ev.kind == "tool_start": + pass # its input follows as tool_args pieces + else: + used_tool = True + yield "content_block_delta", {"type": "content_block_delta", "index": index, "delta": { + "type": "input_json_delta", "partial_json": json.dumps(ev.call.arguments, ensure_ascii=False)}} + else: + if open_kind is not None: + yield close() + stop = "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ + {"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]] + # the final counts, Anthropic's way: input_tokens leaves out what the conversation cache already held, + # which is cache_read_input_tokens (message_start could only say the whole prompt) + reused = min(x.get("reused") or 0, len(ids)) + yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None}, + "usage": {"input_tokens": len(ids) - reused, "cache_read_input_tokens": reused, + "output_tokens": x["completion_tokens"]}} + yield "message_stop", {"type": "message_stop"} + + +def anthropic_collect(events) -> dict: + msg, blocks = None, [] + for item in events: + if item is None: # a heartbeat + continue + name, e = item + if name == "message_start": + msg = e["message"] + elif name == "content_block_start": + blocks.append(dict(e["content_block"])) + elif name == "content_block_delta": + d, b = e["delta"], blocks[-1] + if d["type"] == "text_delta": + b["text"] += d["text"] + elif d["type"] == "thinking_delta": + b["thinking"] += d["thinking"] + else: # input_json_delta pieces: parsed when complete + b["_json"] = b.get("_json", "") + d["partial_json"] + elif name == "content_block_stop" and blocks and "_json" in blocks[-1]: + b = blocks[-1] + try: + b["input"] = json.loads(b.pop("_json") or "{}") + except ValueError: # a call the output ended inside (#211): it has no input to give + blocks.pop() + elif name == "message_delta": + msg["stop_reason"] = e["delta"]["stop_reason"] + msg["usage"].update(e["usage"]) + msg["content"] = blocks + return msg + + +# ------------------------------------------------------------------------------------------------ HTTP +def make_handler(svc: Service): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.0" # SSE ends by closing the connection + + record = None # #332: this request's monitor record, if kept + watch_done = None # #430 #431: stops this request's disconnect watcher + + def log_message(self, fmt, *args): + pass + + def parse_request(self): + """Without an API key, every request (any method) first passes the Host check: DNS rebinding protection + (host_allowed). With a key a rebinding page cannot authenticate, so the check is skipped: tunnels and + proxies that pass their own name on keep working.""" + if not super().parse_request(): + return False + host = self.headers.get("Host") + if svc.api_key or host_allowed(host, svc.host_names, "*" in svc.allowed_hosts): + return True + print(f"[strata] refused a request for Host {host!r} from {self.client_address[0]}: not a name this server " + f"answers to (add it to \"allowed_hosts\" in the config or STRATA_ALLOWED_HOSTS, or set an API key)", + flush=True) + self._json(403, {"error": {"type": "forbidden", "message": + f"Host {host!r} is not allowed (DNS rebinding protection). Reaching Strata under this " + f"name on purpose? Add it to \"allowed_hosts\" in the config (strata-.json) or to " + f"the STRATA_ALLOWED_HOSTS environment variable, or set an API key (\"api_key\"), which " + f"turns this check off"}}) + return False + + def _foreign_page(self) -> bool: + """Without an API key, a /v1 POST from a browser page of another site (any site can POST text/plain + there without a CORS preflight) would burn GPU time: an Origin header must name an allowed page, and + then the body must be JSON. No Origin (curl, the SDKs, other servers): any content type, as before.""" + origin = self.headers.get("Origin") + if svc.api_key or not origin: + return False + if not origin_allowed(origin, self.headers.get("Host"), svc.host_names, + [*svc.trusted_origins, *svc.cors_origins]): + print(f"[strata] refused an API request from the web page {origin!r} (no API key; add its host to " + f"\"allowed_hosts\" or its origin to \"cors_origins\" in the config)", flush=True) + self._json(403, {"error": {"type": "forbidden", "message": + f"web pages of {origin} may not use this server without an API key; set \"api_key\", " + f"or add the page's host to \"allowed_hosts\" (or its origin to \"cors_origins\") " + f"in the config"}}) + return True + if not self.headers.get("Content-Type", "").startswith("application/json"): + self._json(415, {"error": {"message": "send application/json"}}) + return True + return False + + def _watch_client(self, cancel: threading.Event) -> None: + """#430 #431: cancel the request as soon as its client hangs up. A non-streamed request writes nothing + until it ends, and a streamed one only a keep-alive per prompt chunk (and the first write after a hang-up + usually still succeeds), so a dropped request kept the engine busy until its answer or the whole prompt + was done. Every 0.5 s: the socket readable with nothing to read (EOF) means the client closed it. A + request is HTTP/1.0 and fully read here, so no later bytes are expected - data is not a hang-up.""" + done = self.watch_done = threading.Event() + sock = self.connection + + def watch(): + while not done.wait(0.5) and not cancel.is_set(): + try: + readable, _, _ = select.select([sock], [], [], 0) + gone = bool(readable) and sock.recv(1, socket.MSG_PEEK) == b"" + except (ConnectionError, TimeoutError): + gone = True + except (OSError, ValueError): # the socket was closed here: the request has ended + return + if gone: + self._note(outcome="disconnected") + cancel.set() + return + + threading.Thread(target=watch, daemon=True, name="strata-client-watch").start() + + def _note(self, **values): + """#332: what the monitor shows about this request (nothing when the monitor is off).""" + if self.record is not None: + with svc.status_lock: + self.record.update(values) + + def _cors(self): + """#321: CORS headers for an API path (/v1/*) and an origin the config lists in cors_origins - nothing + otherwise, so a browser keeps every other page away from the API, /settings, /unload and the MCP tools.""" + if not svc.cors_origins or not self.path.split("?")[0].startswith("/v1/"): + return + origin = (self.headers.get("Origin") or "").rstrip("/") + if "*" in svc.cors_origins: + allow = "*" + elif origin and origin in svc.cors_origins: + allow = origin + self.send_header("Vary", "Origin") + else: + return + self.send_header("Access-Control-Allow-Origin", allow) + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + # the headers the preflight asks for (SDKs add their own; "*" does not cover Authorization) + asked = self.headers.get("Access-Control-Request-Headers") + self.send_header("Access-Control-Allow-Headers", + asked or "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta") + self.send_header("Access-Control-Max-Age", "600") + + def do_OPTIONS(self): + # a CORS preflight: no credentials come with it, so no API key; the headers only for cors_origins + self.send_response(204) + self._cors() + self.send_header("Content-Length", "0") + self.end_headers() + + def _json(self, code, obj): + if self.record is not None: + with svc.status_lock: + self.record["http_status"] = code + raw = json.dumps(obj, ensure_ascii=False, indent=2) + self.record.update(response=raw[:262144], response_truncated=len(raw) > 262144) + for key in ("error", "usage", "timings"): + if key in obj: + self.record[key] = obj[key] + body = json.dumps(obj, ensure_ascii=False).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self._cors() + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _authorized(self) -> bool: + if not svc.api_key: + return True + auth = self.headers.get("Authorization", "") + given = auth[7:].strip() if auth.lower().startswith("bearer ") else self.headers.get("x-api-key", "") + if hmac.compare_digest(given.encode(), svc.api_key.encode()): # #213: constant-time + return True + self._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong API key"}}) + return False + + def do_GET(self): + path = self.path.split("?")[0].rstrip("/") + if path.startswith("/fonts/"): + # the web app's font (Outfit, OFL: serve/web/fonts); the page falls back to the system font + name = path[len("/fonts/"):] + f = ROOT / "serve" / "web" / "fonts" / name + if "/" in name or "\\" in name or not name.endswith(".woff2") or not f.is_file(): + self._json(404, {"error": {"message": "not found"}}) + return + body = f.read_bytes() + self.send_response(200) + self.send_header("Content-Type", "font/woff2") + self.send_header("Cache-Control", "max-age=86400") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if path.startswith("/web/"): + # the web app's own files (serve/web): styles, script, icon sprite - same origin, no CDN + name = path[len("/web/"):] + types = {".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", + ".svg": "image/svg+xml"} + f = ROOT / "serve" / "web" / name + ext = os.path.splitext(name)[1] + if "/" in name or "\\" in name or ext not in types or not f.is_file(): + self._json(404, {"error": {"message": "not found"}}) + return + body = f.read_bytes() + self.send_response(200) + self.send_header("Content-Type", types[ext]) + self.send_header("Cache-Control", "no-cache") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if path == "/metrics": + if self._authorized(): + # the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35) + self._json(200, svc.metrics(all_requests="requests=all" in self.path)) + return + if path == "/api/requests" and svc.api_monitor: + if self._authorized(): + request_id = parse_qs(urlsplit(self.path).query).get("id", [None])[0] + records = svc.request_records(request_id) + self._json(404 if records is None else 200, + {"error": {"message": "request no longer retained"}} if records is None else + records if request_id else {"requests": records, "retention": 100, "persistent": False, + "loaded": svc.loaded(), "auto_load": hasattr(svc.engine, "restart")}) + return + if path == "/settings": + if self._authorized(): + self._json(200, {"shared": bool(svc.shared), "defaults": svc.shared}) + return + if path == "/config": # #564: the Settings view's keys of the run config + if self._authorized(): + self._config_get() + return + if path == "/mcp": + # the MCP servers, their state and tools (the web app's switch and Monitor card) + if self._authorized(): + self._json(200, svc.mcp.status() if svc.mcp else {"servers": [], "tools": 0}) + return + if path == "" or (path == "/api-monitor" and svc.api_monitor): + body = (ROOT / "serve" / "web" / ("monitor.html" if path else "index.html")).read_bytes() + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + elif path in ("/health", "/api/health"): + self._json(200, {"status": "ok", "max_context": svc.engine.max_context, "model": svc.model, + "images": svc.vision is not None, "api_key": bool(svc.api_key), + "loaded": svc.loaded(), "service": "strata"}) + elif path == "/status": + if not self._authorized(): # #212: it shows the end of the last answer + return + with svc.status_lock: + s = dict(svc.status) + now = time.time() + if s.get("busy"): + s["elapsed_s"] = round(now - s["started"], 1) + if s.get("first_token"): + s["tokens_per_s"] = round(svc._tok_s(), 1) + s["tokens_per_s_mean"] = round(svc._tok_s_mean(), 1) + for k in ("started", "first_token"): + s.pop(k, None) + self._json(200, s) + elif path in ("/v1/models", "/models"): + if self._authorized(): + loaded = svc.loaded() + model = {"id": svc.model, "object": "model", "status": {"value": "loaded"}, + "meta": {"n_ctx": svc.engine.max_context}, + "architecture": {"input_modalities": ["text", "image"] if svc.vision is not None else ["text"], + "output_modalities": ["text"]}} + if not loaded and (svc.idle_unload_s or getattr(svc.engine, "unloaded", False)): + model["status"] = {"value": "unloaded"} # like llama-server's router: listed, loads on use + loaded = True + if svc.aliases: # #297: the aliases, and each one listed under its own id + model["aliases"] = list(svc.aliases) + data = [model, *({**model, "id": x, "alias_of": svc.model} for x in svc.aliases)] + self._json(200, {"object": "list", "data": data if loaded else []}) + elif path == "/props": + if self._authorized(): + self._props() + elif path == "/slots": + if self._authorized(): + loaded = not hasattr(svc.engine, "alive") or svc.engine.alive() + with svc.status_lock: + busy = bool(svc.status.get("busy")) + slot = {"id": 0, "n_ctx": svc.engine.max_context, "is_processing": busy} + self._json(200, [slot] if loaded else []) + elif path == "/v1/status": + if self._authorized(): + self._json(200, svc.v1_status()) + else: + self._json(404, {"error": {"message": "not found"}}) + + def do_POST(self): + if not self._authorized(): + return + path = self.path.split("?")[0].rstrip("/") # issue #55: Claude Code posts /v1/messages?beta=true + if path.startswith("/v1/") and self._foreign_page(): + return + if path == "/settings": + self._settings() + return + if path == "/config": + self._config_post() + return + if path in ("/unload", "/load") and not self._control_body(): + return + # JSON from Strata's own page only, as /settings: else a plain form POST from any site unloads the model + if path in ("/unload", "/load") and not self._own_page("the model can be loaded or unloaded"): + return + if path == "/unload": # give the GPU back now (between requests) + try: + r = svc.unload() + except EngineStuck as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + return + self._json(409 if r == "busy" else 200, {"status": r}) + return + if path == "/load": # load now, e.g. ahead of a request + try: + svc.load() + self._json(200, {"status": "loaded"}) + except GpuBusy as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + return + try: + req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + if not isinstance(req, dict): + raise ValueError("send a JSON object") + if path.startswith("/v1/responses/"): # retrieve/delete/cancel/compact: nothing is stored + self._json(404, responses_error_body("this server keeps no responses (stateless); send the " + "whole conversation to POST /v1/responses", code="not_found")) + return + if path in ("/v1/load", "/v1/unload"): + if not self._own_page("the model can be loaded or unloaded"): + return + if req.get("model") not in (None, svc.model): + self._json(404, {"error": {"message": "model not found"}}) + return + if path == "/v1/unload": + result = svc.unload() + if result == "busy": + raise ModelBusy("a request is running or queued") + else: + if not svc.fifo.acquire(blocking=False): + raise ModelBusy("a request is running or queued") + try: + with svc.status_lock: + if svc.status.get("busy") or svc.status.get("queued"): + raise ModelBusy("a request is running or queued") + svc.ensure_loaded() + svc.last_request_at = time.time() + finally: + svc.fifo.release() + result = "loaded" + self._json(200, {"status": result, **svc.v1_status()}) + return + if path == "/v1/vram": # #533: give VRAM back to other programs, or take it + if not self._own_page("the VRAM reserve can be changed"): + return + r = req.get("reserve_mib") + if r is not None and (isinstance(r, bool) or not isinstance(r, int) or r < 0): + raise ValueError("reserve_mib: a whole number of MiB (0 or more), or null for the start's") + try: + self._json(200, svc.vram(r)) + except EngineDied as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + return + if path in ("/v1/chat/completions", "/v1/messages", "/v1/responses"): + self.record = svc.begin_request(path, req) + if path == "/v1/responses": + self._responses(req) + elif path == "/v1/chat/completions": + self._openai(req) + elif path == "/v1/messages": + self._anthropic(req) + elif path == "/v1/messages/count_tokens": + self._count_tokens(req) + else: + self._json(404, {"error": {"message": "not found"}}) + except ValueError as e: + if path == "/v1/responses": + self._json(400, responses_error_body(str(e))) + else: + self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) + except ModelBusy as e: + self._json(409, {"error": {"type": "model_busy", "message": str(e)}}) + except StructuredOutputError as e: + self._json(502, {"error": {"type": "structured_output_failed", "code": "structured_output_failed", + "message": str(e)}}) + except (GpuBusy, EngineStarting) as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + except EngineDied as e: # before the answer started (not streamed) + self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}) + except EngineStuck as e: # an unload or restart that could not end the engine + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + + except OSError: + self._note(outcome="disconnected") + raise # as before #332: the server's own handling + finally: + if self.watch_done is not None: + self.watch_done.set() + record = self.record + if record is not None: + with svc.status_lock: + record["wallclock_s"] = round(time.perf_counter() - record["_clock"], 3) + record["finished_at"] = time.time() + record["state"] = "error" if record.get("error") else record.get("outcome", "completed") + svc.request_trace.record = None + + def _props(self): + model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0] + if model not in svc.model_names(): + self._json(404, {"error": {"message": "model not found"}}) + return + if not svc.loaded() and not getattr(svc.engine, "unloaded", False): + self._json(503, {"error": {"message": "the engine is not running"}}) + return + defaults = {**svc.sampling_defaults, **svc.shared} + names = {"repetition_penalty": "repeat_penalty", "penalty_last_n": "repeat_last_n"} + params = {names.get(k, k): v for k, v in defaults.items() + if k in ("temperature", "top_p", "top_k", "min_p", "seed", "repetition_penalty", + "presence_penalty", "frequency_penalty", "penalty_last_n")} + params["n_predict"] = svc.shared.get("max_tokens", -1) + props = {"default_generation_settings": {"n_ctx": svc.engine.max_context, "params": params}, + "total_slots": 1, "model_alias": svc.model, "chat_template": svc.template.source, + "modalities": {"vision": svc.vision is not None}, "models_autoload": hasattr(svc.engine, "restart"), + "is_sleeping": not svc.loaded()} + if getattr(svc.engine, "model_path", None): + props["model_path"] = svc.engine.model_path + version = getattr(svc.engine, "info", {}).get("version") + if version: + props["build_info"] = "Strata " + str(version) + self._json(200, props) + + def _control_body(self) -> bool: + """Consume the unused control body before replying/closing (Windows otherwise sends a TCP reset).""" + try: + length = int(self.headers.get("Content-Length", "0")) + except ValueError: + self._json(400, {"error": {"message": "invalid Content-Length"}}) + return False + if not 0 <= length <= 65536: + self._json(413, {"error": {"message": "control request body is limited to 64 KiB"}}) + return False + timeout = self.connection.gettimeout() + try: + self.connection.settimeout(2.0) + complete = len(self.rfile.read(length)) == length + except OSError: + complete = False + finally: + self.connection.settimeout(timeout) + if not complete: + self._json(400, {"error": {"message": "incomplete control request body"}}) + return complete + + def _own_page(self, what) -> bool: + """Only JSON (a form or a "simple" cross-site request can't send it without a CORS preflight, which this + server never grants) and no foreign Origin: a web page elsewhere must not change settings or run tools.""" + if not self.headers.get("Content-Type", "").startswith("application/json"): + self._json(415, {"error": {"message": "send application/json"}}) + return False + # The Origin must be this server's own address (host and port), or an origin the config trusts + # (trusted_origins: the web app behind a reverse proxy or tunnel). Headers a proxy adds (X-Forwarded-*, + # CF-Ray, CF-Connecting-IP) prove nothing about the page that sent the request, so they open nothing. + origin = (self.headers.get("Origin") or "").rstrip("/") + if origin and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \ + origin not in svc.trusted_origins: + self._json(403, {"error": {"message": f"{what} only from Strata's own page (or an origin in the " + f"config's trusted_origins)"}}) + return False + return True + + def _config_get(self): + if not svc.config_path: + self._json(404, {"error": {"message": "this server was started without a run config"}}) + return + try: + cfg = runconfig.load(svc.config_path) + except (OSError, ValueError) as e: + self._json(500, {"error": {"type": "server_error", "message": f"the run config cannot be read: {e}"}}) + return + self._json(200, runconfig.view(cfg, svc.config_path)) + + def _config_post(self): + """#564: change a few documented keys of the run config - JSON from Strata's own page only, as + /settings (the key is checked before); every other key of the file stays as it is.""" + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + if not self._own_page("the run config can be changed"): + return + if not svc.config_path: + self._json(404, {"error": {"message": "this server was started without a run config"}}) + return + try: + req = json.loads(body or b"{}") + with svc.config_lock: + cfg = runconfig.load(svc.config_path) + new, changed = runconfig.apply(cfg, req.get("set") if isinstance(req, dict) else None) + if changed: + bak = runconfig.save(svc.config_path, new) + except ValueError as e: + self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) + return + except OSError as e: + self._json(500, {"error": {"type": "server_error", "message": f"the run config cannot be written: {e}"}}) + return + if changed: + print(f"[strata] the Settings view changed {', '.join(changed)} in {Path(svc.config_path).name} " + f"(the earlier file: {bak.name}); used from the next start", flush=True) + self._json(200, {**runconfig.view(new, svc.config_path), "changed": changed}) + + def _settings(self): + # They change what every client gets, so only the app's own page may set them + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + if not self._own_page("settings can be changed"): + return + try: + req = json.loads(body or b"{}") + shared = svc.set_shared(req.get("defaults") if isinstance(req, dict) else None) + except ValueError as e: + self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) + return + print("[strata] other apps now use the Chat settings: " + ", ".join(f"{k}={v}" for k, v in shared.items()) + if shared else "[strata] other apps use their own settings again", flush=True) + self._json(200, {"shared": bool(shared), "defaults": shared}) + + def _sse(self): + self._note(http_status=200) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.send_header("X-Accel-Buffering", "no") # nginx and similar proxies pass each event at once + self._cors() + self.end_headers() + + def _capture(self, items, api): + """Retain bounded input/output for the monitor without changing the API response (the items as they + are when the monitor is off).""" + if self.record is None: + return items + return self._captured(items, api) + + def _captured(self, items, api): + try: + for item in items: + if item is not None: + if api == "openai": + delta = item["choices"][0]["delta"] + content, reasoning = delta.get("content", ""), delta.get("reasoning_content", "") + usage, timings = item.get("usage"), item.get("timings") + elif api == "responses": + kind = item["type"] + content = item["delta"] if kind == "response.output_text.delta" else "" + reasoning = item["delta"] if kind == "response.reasoning_text.delta" else "" + usage, timings = (item.get("response") or {}).get("usage"), None + else: + _, event = item + delta = event.get("delta", {}) + content, reasoning = delta.get("text", ""), delta.get("thinking", "") + usage, timings = event.get("usage"), None + with svc.status_lock: + for name, value in (("output", content), ("reasoning", reasoning)): + if value: + combined = self.record[name] + value + self.record[name] = combined[:262144] + self.record[name + "_truncated"] |= len(combined) > 262144 + if usage: + self.record["usage"] = usage + if timings: + self.record["timings"] = timings + yield item + finally: + items.close() + + def _openai(self, req): + req = svc.with_shared(req, "openai") + messages, tools, kw = openai_to_messages(req) + messages, validator = prepare_format(req.get("response_format"), messages) + if validator is not None and (tools or req.get("strata_mcp")): + raise ValueError("structured response_format with tools/MCP is not supported") + svc.load() + max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest + use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py) + own = {t.get("name") for t in tools or [] if isinstance(t, dict)} # #592: a second line of defence + if use_mcp: + if not self._own_page("MCP tools can be used"): # tools run with the user's rights on this PC + return + svc.mcp.wait(10) # servers still starting (only right after start) + extra = svc.mcp.template_tools(exclude=own) # the request's own tools win a name clash + use_mcp = bool(extra) + tools = (tools or []) + extra or None + svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) + _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) + cancel = threading.Event() + self._watch_client(cancel) # #430 #431 + run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel, + {t["name"] for t in extra}) if use_mcp else None + chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run) + if validator is not None: + chunks = structured_chunks(chunks, validator) + chunks = self._capture(chunks, "openai") + if not req.get("stream"): + return self._json(200, openai_collect(chunks)) + self._sse() + try: + for c in chunks: + if c is None: + self.wfile.write(b": keep-alive\n\n") # an SSE comment: clients ignore it + else: + self.wfile.write(b"data: " + json.dumps(c, ensure_ascii=False).encode() + b"\n\n") + self.wfile.flush() + self.wfile.write(b"data: [DONE]\n\n") + except OSError: + self._note(outcome="disconnected") + cancel.set() # client went away: stop the engine + chunks.close() + except EngineDied as e: # mid-stream: say so, then end the stream properly + err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}} + self._note(error=err["error"]) + self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + except StructuredOutputError as e: + err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}} + self._note(error=err["error"]) + self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + except ValueError as e: # the engine's ERR after the stream started: the + err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now + self._note(error=err["error"]) + self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + + def _responses(self, req): + """#451: POST /v1/responses - OpenAI's Responses API, stateless (serve/responses.py), on the chat path. + Errors use the Responses format; once the stream has started they arrive as a response.failed event.""" + try: + ids, thinking, tools, max_new, asm, validator, req = self._responses_prepare(req) + except ResponsesError as e: + return self._json(e.status, e.body()) + except ModelBusy as e: + return self._json(409, responses_error_body(str(e), "server_error", code="model_busy")) + except (GpuBusy, EngineStarting, EngineStuck, EngineDied) as e: + return self._json(503, responses_error_body(str(e), "server_error", code="server_error")) + cancel = threading.Event() + self._watch_client(cancel) # #430 #431 + + def check(text, finish): + return validated_json(text, validator, finish) + + def events(): + yield from asm.start() + done = None + for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel): + if kind == "ping": + yield None + elif kind == "event": + yield from asm.feed(x) + elif kind == "done": + done = x + if done is not None and done["finish"] != "cancel" and not cancel.is_set(): + yield from asm.finish(done, check) + items = self._capture(events(), "responses") + if not req.get("stream"): + try: + result = responses_api.collect(items) + except StructuredOutputError as e: + return self._json(502, responses_error_body(str(e), "server_error", + code="structured_output_failed")) + except EngineDied as e: + return self._json(503, responses_error_body(f"{e}; the next request restarts it", "server_error", + code="server_error")) + except ValueError as e: # the engine's ERR line + return self._json(500, responses_error_body(str(e), "server_error", code="server_error")) + return self._json(200, result) + self._sse() + last = time.monotonic() + + def send(e): + self.wfile.write(f"event: {e['type']}\n".encode() + b"data: " + + json.dumps(e, ensure_ascii=False).encode() + b"\n\n") + + try: + for e in items: + if e is None: + # Codex's idle timeout (5 minutes by default) counts events, not SSE comments: while a long + # prompt is read, a response.in_progress every 15 s tells it the server is still working + if time.monotonic() - last >= 15: + send(asm.in_progress()) + last = time.monotonic() + else: + self.wfile.write(b": keep-alive\n\n") + else: + send(e) + last = time.monotonic() + self.wfile.flush() + except OSError: + self._note(outcome="disconnected") + cancel.set() # client went away: stop the engine + items.close() + except EngineDied as e: # mid-stream: response.failed, then the stream ends + self._responses_failed(asm, f"{e}; the next request restarts it", "server_error", send) + except StructuredOutputError as e: + self._responses_failed(asm, str(e), "structured_output_failed", send) + except ValueError as e: # the engine's ERR after the stream started + self._responses_failed(asm, str(e), "server_error", send) + + def _responses_failed(self, asm, message, code, send): + e = asm.failed(message, code) + self._note(error=e["response"]["error"]) + try: + send(e) + self.wfile.flush() + except OSError: + pass + + def _responses_prepare(self, req): + responses_api.check_request(req) + messages = responses_api.input_messages(req) + tools, names, skipped = responses_api.request_tools(req) + kw = responses_api.template_kwargs(req, svc.shared) + try: + messages, validator = prepare_format(responses_api.text_format(req), messages) + except ValueError as e: + raise ResponsesError(str(e).replace("response_format", "text.format"), "text.format") from None + if validator is not None and tools: + raise ResponsesError("a JSON text.format with tools is not supported", "text.format", + "unsupported_parameter") + noted = svc.__dict__.setdefault("hosted_tools_noted", set()) # said once per tool, not per request + if set(skipped) - noted: + print(f"[strata] /v1/responses: left out the hosted tools {', '.join(sorted(set(skipped) - noted))} " + f"(this server cannot run them)", flush=True) + noted.update(skipped) + if req.get("max_output_tokens") is None and "max_tokens" in svc.shared: # the shared Chat settings + req = {**req, "max_output_tokens": svc.shared["max_tokens"]} + try: + svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + except ValueError as e: + raise ResponsesError(str(e), "reasoning_budget_tokens") from None + svc.load() + try: + ids, thinking, max_new = svc.prepare(messages, tools, kw, req.get("max_output_tokens") or 0) + except ResponsesError: + raise + except ValueError as e: # too long for the context, an image without vision + raise ResponsesError(str(e), "input", "context_length_exceeded" if "context" in str(e) else None) \ + from None + _debug_req("responses", req, messages, tools, max_new, thinking, len(ids)) + include = req.get("include") if isinstance(req.get("include"), list) else [] + asm = responses_api.Assembler(req, svc.model_for(req), len(ids), names, + "reasoning.encrypted_content" in include, validator is not None) + # the request is also the sampling dict, as on the chat path (temperature, top_p, top_k, seed, ...) + return ids, thinking, tools, max_new, asm, validator, req + + def _count_tokens(self, req): + """Anthropic's token count, which Claude Code asks for its context figures: the prompt this server would + read for the same request, rendered and tokenized - the model does not run.""" + req = svc.with_shared(req, "anthropic") + messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw))}) + + def _anthropic(self, req): + svc.load() + req = svc.with_shared(req, "anthropic") + messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context + svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) + _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) + cancel = threading.Event() + self._watch_client(cancel) # #430 #431 + events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel) + events = self._capture(events, "anthropic") + if not req.get("stream"): + return self._json(200, anthropic_collect(events)) + self._sse() + try: + for item in events: + if item is None: + self.wfile.write(b": keep-alive\n\n") + else: + name, e = item + self.wfile.write(f"event: {name}\n".encode() + b"data: " + + json.dumps(e, ensure_ascii=False).encode() + b"\n\n") + self.wfile.flush() + except OSError: + self._note(outcome="disconnected") + cancel.set() + events.close() + except EngineDied as e: # mid-stream: Anthropic's error event + err = {"type": "error", "error": {"type": "api_error", "message": f"{e}; the next request restarts it"}} + self._note(error=err["error"]) + self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") + except ValueError as e: # the engine's ERR after the stream started + err = {"type": "error", "error": {"type": "api_error", "message": str(e)}} + self._note(error=err["error"]) + self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") + + return Handler + + +class Server(ThreadingHTTPServer): + # On Windows SO_REUSEADDR lets a second server bind a port that is already serving, and requests then land on + # either one (a forgotten second start of run-.bat). Without it the second start fails loudly instead. + allow_reuse_address = os.name != "nt" + + def handle_error(self, request, client_address): + if not isinstance(sys.exc_info()[1], ConnectionError): # a client that hangs up needs no stack trace + super().handle_error(request, client_address) + + +def warn_tight_ram(arena_mib) -> None: + """The model's experts live in RAM (INFO arena_mib, engine 0.1.10+). With less than ~6 GB left beside them for the + system, the engine and this server, Linux ends the engine mid-answer when memory runs out (issue #27) and Windows + pages to disk; say so at start instead of after a lost answer.""" + if not isinstance(arena_mib, int) or arena_mib <= 0: + return + try: + import psutil + total = psutil.virtual_memory().total + except Exception: # noqa: BLE001 - psutil is optional here + return + left = total / 2**30 - arena_mib / 1024 + if left < 6: + print(f"[strata] WARNING: RAM is tight - the model's experts take {arena_mib / 1024:.1f} GB of this PC's " + f"{total / 2**30:.0f} GB, leaving {left:.1f} GB for everything else. " + + ("Linux may stop the engine in the middle of an answer. " if os.name != "nt" else + "Windows will slow down (paging to disk). ") + + "Close other programs, or run START-HERE --setup and pick a smaller size (Q2_0 / IQ2_XS).", flush=True) + + +DESKTOP_FREE_MIB = 2048 # #560 #516: below this, an AMD card that also drives a Linux desktop can run out +DESKTOP_RESERVE_MIB = 3072 # what kept KDE/Wayland alive beside a full expert cache in both reports + + +def linux_desktop(env=None) -> bool: + """A graphical session on Linux (Wayland or X): its compositor, browser and apps take VRAM after the model has.""" + env = os.environ if env is None else env + return os.name != "nt" and sys.platform != "darwin" and bool(env.get("WAYLAND_DISPLAY") or env.get("DISPLAY")) + + +def desktop_vram_note(backend, vram_free_mib, args: list, desktop: bool) -> str: + """#560 #516: on Linux, when the desktop needs VRAM the AMD card does not have, amdgpu moves GPU memory (the expert + cache, ~24 GB) to system RAM, which the experts already fill - the OOM killer then ends the compositor. The + default reserve (700 MiB) is sized for a card without a desktop. A recommendation, nothing changes: "" when it + does not apply.""" + if backend != "hip" or not desktop or not isinstance(vram_free_mib, int) or vram_free_mib >= DESKTOP_FREE_MIB: + return "" + try: + reserve = int(args[args.index("--vram-reserve-mib") + 1]) if "--vram-reserve-mib" in args else 700 + except (ValueError, IndexError): + reserve = 700 + if reserve >= DESKTOP_RESERVE_MIB: + return "" + return (f"[strata] note: {vram_free_mib} MiB of VRAM free with the model loaded. If this AMD card also drives your " + "desktop and the desktop or apps crash after the start (the driver moves the expert cache to RAM and " + "the OOM killer ends the session), keep more VRAM free: ./setup.sh --vram-reserve-mib " + f"{DESKTOP_RESERVE_MIB} (remembered; the expert cache gets " + f"{(DESKTOP_RESERVE_MIB - reserve) / 1024:.1f} GB less, a few % of speed)") + + +def lan_addresses() -> list[str]: + """This PC's IPv4 addresses on its networks (what another device types in), without loopback/link-local.""" + import socket + first, ips = None, set() + try: # the address of the default route; sends nothing (UDP) + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s.connect(("10.255.255.255", 1)) + first = s.getsockname()[0] + except OSError: + pass + try: + for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET): + ips.add(info[4][0]) + except OSError: + pass + ok = lambda ip: ip and not ip.startswith(("127.", "169.254.", "0.")) + return ([first] if ok(first) else []) + sorted(ip for ip in ips if ok(ip) and ip != first) + + +def host_name(value) -> str: + """The name in a Host header (or an origin's host[:port]): "Example.com:8080" -> "example.com", + "[::1]:8095" -> "::1"; "" when it is malformed.""" + v = (value or "").strip().lower() + if v.startswith("["): + name, sep, rest = v[1:].partition("]") + return name if sep and (not rest or (rest[:1] == ":" and rest[1:].isdigit())) else "" + if v.count(":") == 1: + v, port = v.split(":") + if not port.isdigit(): + return "" + elif ":" in v: # a bare IPv6 address (a config entry) + return v + v = v.rstrip(".") + return v if v and all(c.isalnum() or c in "-._" for c in v) else "" + + +def _is_ip(name: str) -> bool: + import ipaddress + try: + ipaddress.ip_address(name) + return True + except ValueError: + return False + + +def _name_in(name: str, names) -> bool: + """`name` is one of `names`, or below an entry that starts with a dot (".example.com").""" + return name in names or any(n.startswith(".") and (name.endswith(n) or name == n[1:]) for n in names) + + +def allowed_hosts_of(value, env: str = "") -> list[str]: + """The config's allowed_hosts (a name or a list) plus $STRATA_ALLOWED_HOSTS (comma-separated): host names, "*" or + ".example.com" (it and every name below it). A scheme, port or path is dropped ("https://a.example.com:8443/" + -> "a.example.com"); a wrong entry stops the start (ValueError).""" + items = [] if value in (None, "") else [value] if isinstance(value, str) else value + if not isinstance(items, list) or not all(isinstance(x, str) for x in items): + raise ValueError("allowed_hosts: expected a host name or a list of them") + out = [] + for raw in items + [x for x in env.split(",") if x.strip()]: + x = raw.strip().lower() + if x == "*": + out.append(x) + continue + x = x.split("://", 1)[-1].split("/", 1)[0] + dot = x.startswith(".") + name = host_name(x[1:] if dot else x) + if not name: + raise ValueError(f"allowed_hosts: {raw!r} is not a host name like strata.example.com") + out.append("." + name if dot else name) + return list(dict.fromkeys(out)) + + +def host_names_for(bind_host: str, allowed_hosts=(), trusted_origins=()) -> set[str]: + """Every name this server answers to besides an IP address: localhost, the address it listens on, the config's + allowed_hosts and trusted_origins' hosts, and - listening beyond this PC (0.0.0.0 or a LAN address) - this PC's + name and LAN addresses (the LAN addresses matter for the Origin check, which takes no IP on trust).""" + names = set(LOOPBACK_NAMES) + bind = host_name(bind_host) + if bind and bind not in ("0.0.0.0", "::"): + names.add(bind) + if bind not in LOOPBACK_NAMES: + try: + pc = socket.gethostname().lower() + names.update((pc, pc + ".local")) + except OSError: + pass + names.update(("host.docker.internal", *lan_addresses())) + names.update(x for x in allowed_hosts if x != "*") + names.update(filter(None, (host_name(o.split("://", 1)[-1]) for o in trusted_origins))) + return names + + +def host_allowed(host, names, any_host=False) -> bool: + """DNS rebinding: a web page of another site whose name its DNS points at 127.0.0.1 reaches this server as the + same origin, so the browser lets it read every answer. Its requests carry that site's name in Host, so only + the names this server answers to pass. An IP address passes (a page served from an IP is that IP's own page; + rebinding needs a name), as does "*.localhost" (browsers never ask DNS for it) and a request without a Host + header (HTTP/1.0 clients; browsers always send one).""" + if any_host or not (host or "").strip(): + return True + name = host_name(host) + return bool(name) and (_is_ip(name) or name == "localhost" or name.endswith(".localhost") + or _name_in(name, names)) + + +def origin_allowed(origin: str, host, names, origins=()) -> bool: + """A browser page's Origin that may use the model without an API key: this server's own page (the Origin is the + request's own Host), a page on one of the names this server answers to (any port), or an origin the config lists + (trusted_origins, cors_origins). Unlike the Host check no IP passes on trust: a page served from any other IP is + another site. "null" (a sandboxed frame, a file:// page) does not pass: any site can send it. An origin of another + scheme (chrome-extension://, moz-extension://, an Electron app's app://) does: no web site can send one.""" + origin = (origin or "").strip().rstrip("/") + if origin in origins or "*" in origins: # cors_origins ["*"]: the config lets every page in + return True + scheme, sep, rest = origin.lower().partition("://") + if not sep or not scheme: + return False + if scheme not in ("http", "https"): + return True + if host and rest == host.strip().lower(): + return True + name = host_name(rest) + return bool(name) and (name in LOOPBACK_NAMES or name.endswith(".localhost") or _name_in(name, names)) + + +def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer: + svc.host_names = host_names_for(host, svc.allowed_hosts, svc.trusted_origins) + svc.start_telemetry() + httpd = Server((host, port), make_handler(svc)) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + return httpd + + +def origins_of(value, key: str, wildcard: bool) -> list[str]: + """#321: a config's origin list ("https://chat.example.com" or a list of them) - scheme://host[:port], no path; + "*" only where `wildcard` allows it. A wrong entry stops the start rather than opening less or more than meant.""" + if value is None or value == "" or value == []: + return [] + items = [value] if isinstance(value, str) else value + if not isinstance(items, list) or not all(isinstance(x, str) for x in items): + raise SystemExit(f"[strata] {key}: expected an origin or a list of origins") + out = [] + for x in items: + x = x.strip().rstrip("/") + if x == "*" and wildcard: + out.append(x) + continue + scheme, sep, rest = x.partition("://") + if scheme not in ("http", "https") or not sep or not rest or "/" in rest or "*" in rest: + raise SystemExit(f"[strata] {key}: {x!r} is not an origin like https://chat.example.com" + + ("" if wildcard else " (no wildcards here)")) + out.append(x) + return out + + +SHARED_KEYS = ("reasoning_effort", "temperature", "top_p", "top_k", "seed", "max_tokens", "experimental_speed_projection") + + +def clean_shared_defaults(d) -> dict: + """The Chat settings other apps get (POST /settings): only known keys, each checked; ValueError names a bad one.""" + if d is None: + return {} + if not isinstance(d, dict): + raise ValueError("defaults must be an object") + out = {} + for key, value in d.items(): + if value is None or value == "": + continue + number = isinstance(value, (int, float)) and not isinstance(value, bool) + if key == "reasoning_effort": + if value not in ("none", "low", "medium", "high"): + raise ValueError("reasoning_effort: none, low, medium or high") + elif key == "temperature": + if not number or not 0 <= value <= 2: + raise ValueError("temperature: 0..2") + elif key == "top_p": + if not number or not 0 < value <= 1: + raise ValueError("top_p: 0 < top_p <= 1") + elif key == "top_k": + if not number or value != int(value) or not 1 <= value <= 64: + raise ValueError("top_k: an integer 1..64") + value = int(value) + elif key in ("seed", "max_tokens"): + if not number or value != int(value) or value <= 0: + raise ValueError(f"{key}: a positive integer") + value = int(value) + elif key == "experimental_speed_projection": + if not isinstance(value, bool): + raise ValueError("experimental_speed_projection: true or false") + else: + raise ValueError(f"unknown setting {key!r}") + out[key] = float(value) if key in ("temperature", "top_p") else value + return out + + +def sampling_defaults_from_config(cfg: dict) -> dict: + """The run config's optional `sampling` block: defaults for the sampling fields a request leaves out, so + a plain client gets configured sampling instead of greedy. Supported: temperature, top_p, top_k, min_p, + presence_penalty, repetition_penalty, frequency_penalty, penalty_last_n, seed. The request's own fields + always win - an explicit temperature=0 still means greedy, a field set to null falls back to the default. + A bad value refuses to start the server (a typo'd config should not quietly change sampling); unknown keys + are named at startup and ignored.""" + out = {} + for key, value in (cfg.get("sampling") or {}).items(): + if value is None: + continue + number = isinstance(value, (int, float)) and not isinstance(value, bool) + if key == "temperature": + if not number or value < 0: + raise SystemExit(f"[strata] config sampling.temperature={value!r}: expected a number >= 0 (0 = greedy)") + out[key] = float(value) + elif key == "top_p": + if not number or not 0 < value <= 1: + raise SystemExit(f"[strata] config sampling.top_p={value!r}: expected 0 < top_p <= 1") + out[key] = float(value) + elif key == "min_p": + if not number or not 0 <= value <= 1: + raise SystemExit(f"[strata] config sampling.min_p={value!r}: expected 0 <= min_p <= 1") + out[key] = float(value) + elif key == "top_k": + if not number or value != int(value) or not 1 <= value <= 64: + raise SystemExit(f"[strata] config sampling.top_k={value!r}: the sampled path takes an integer 1..64") + out[key] = int(value) + elif key == "presence_penalty": + if not number or value < 0: + raise SystemExit(f"[strata] config sampling.presence_penalty={value!r}: expected a number >= 0") + out[key] = float(value) + elif key == "frequency_penalty": + if not number or value < 0: + raise SystemExit(f"[strata] config sampling.frequency_penalty={value!r}: expected a number >= 0") + out[key] = float(value) + elif key == "repetition_penalty": + if not number or value <= 0: + raise SystemExit(f"[strata] config sampling.repetition_penalty={value!r}: expected a number > 0 (1 = off)") + out[key] = float(value) + elif key == "penalty_last_n": + if not number or value != int(value) or value < 0: + raise SystemExit(f"[strata] config sampling.penalty_last_n={value!r}: expected a non-negative integer") + out[key] = int(value) + elif key == "seed": + if not number or value != int(value) or value <= 0: + raise SystemExit(f"[strata] config sampling.seed={value!r}: expected a positive integer") + out[key] = int(value) + elif key == "experimental_speed_projection": + if not isinstance(value, bool): + raise SystemExit(f"[strata] config sampling.experimental_speed_projection={value!r}: expected true or " + "false (the default for requests that leave it out, when the engine has the vector)") + out[key] = value + else: + print(f"[strata] config sampling.{key}={value!r}: unknown key, ignored", flush=True) + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--engine", choices=["mock", "strata"], default="mock") + ap.add_argument("--config", help="strata engine config (JSON: exe, args, cwd, tokenizer, model_name), " + "written by setup.py") + ap.add_argument("--host", default=None, + help="the address to listen on: 127.0.0.1 = this PC only (the default), 0.0.0.0 = also other devices " + "on your network (set an API key); also \"host\" in the config") + ap.add_argument("--script", action="append", + help="the mock engine's answer (default: a short greeting); given more than once, requests get " + "them in turn and the last one repeats") + ap.add_argument("--port", type=int, default=8095) + ap.add_argument("--gpu", help="the GPU to run on, as nvidia-smi numbers them, or several for a layer split " + "(\"0,2\"; also \"gpu\" in the config)") + ap.add_argument("--tokenizer", default=str(ROOT / "pack/full/tokenizer"), + help="pack tokenizer directory (falls back to a byte tokenizer if absent)") + ap.add_argument("--open", action="store_true", help="open the local page in the browser once the model is ready") + ap.add_argument("--fit-max-tokens", action="store_true", + help="clamp max_tokens to the remaining context instead of rejecting the request " + "(default: reject with 400, like llama.cpp; also \"fit_max_tokens\": true in the config)") + ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""), + help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY") + ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": " + "{...}}); the web app's chat can use their tools (also \"mcp_servers\" in " + "the config)") + ap.add_argument("--lazy", action="store_true", help="start the text-only API unloaded; load on first request") + ap.add_argument("--api-monitor", action="store_true", + help="the API request monitor at /api-monitor: keeps the last 100 requests' prompts and answers in " + "memory (also \"api_monitor\": true in the config; off by default)") + ap.add_argument("--idle-unload", type=float, default=None, metavar="SECONDS", + help="unload the model after this many seconds without requests, so other programs (games, other " + "model servers) can use the VRAM; the next request loads it again (also \"idle_unload_s\" " + "in the config; default: never)") + ap.add_argument("--min-free-vram-mib", type=int, default=None, + help="load an unloaded model only when this much VRAM is free, else answer 503 (also " + "\"min_free_vram_mib\" in the config; default: always load)") + ap.add_argument("--before-load", help="a command run before the model is loaded again (e.g. to unload another " + "server's model; also \"before_load\" in the config, a string or a list)") + a = ap.parse_args() + cfg = json.loads(Path(a.config).read_text(encoding="utf-8-sig")) if a.config else {} # Notepad adds a BOM + if a.gpu is not None: + cfg["gpu"] = int(a.gpu) if a.gpu.strip().isdigit() else a.gpu + a.host = a.host or cfg.get("host") or "127.0.0.1" # issue #26: the run scripts pass no --host, the config can + try: # before the minutes of loading: is the port free? + Server((a.host, a.port), BaseHTTPRequestHandler).server_close() + except OSError: + ap.error(f"port {a.port} is already in use - is Strata (or another server) already running? " + f"Close it, or start this one with a different --port") + if cfg.get("tokenizer"): + a.tokenizer = cfg["tokenizer"] + tok = ByteTokenizer() + tpath = Path(a.tokenizer) + if a.engine == "strata" and not (tpath / "vocab.json").exists(): + ap.error(f"the model's tokenizer is missing ({tpath / 'vocab.json'}); run setup again") + if (tpath / "vocab.json").exists(): + import strata_tokenizer as ST + vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8")) + tokens = [None] * len(vocab) + for t, i in vocab.items(): + tokens[i] = t + merges = (tpath / "merges.txt").read_text(encoding="utf-8").split("\n") + types = json.loads((tpath / "token_type.json").read_text()) + tok = ST.Tokenizer(tokens, merges, types) + hub = hub_from_config(cfg, a.mcp_config) # before the minutes of loading: a bad entry stops here + if a.engine == "strata": + if not cfg: + ap.error("--engine strata needs --config") + vision = None + env = child_env(cfg) + sampling_defaults = sampling_defaults_from_config(cfg) + if sampling_defaults: + pretty = ", ".join(f"{k}={v}" for k, v in sampling_defaults.items()) + print(f"[strata] sampling defaults from the config: {pretty}", flush=True) + lazy = a.lazy or cfg.get("lazy_load") is True + if lazy and cfg.get("vision"): + ap.error("lazy loading is text-only; disable vision in the config") + if cfg.get("vision"): + print("loading the vision encoder ...", flush=True) + # relative paths are the config's cwd's, as for the engine below + vcfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v)) + if k in ("exe", "mmproj", "model") and isinstance(v, str) and not os.path.isabs(v) else v) + for k, v in cfg["vision"].items()} + vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, + env=vision_env(cfg, env)) + print("model unloaded; the first request loads it ..." if lazy else + "loading the model (the first start takes a minute or two) ...", flush=True) + if len(gpu_list(cfg)) > 1: + try: + split = layer_split_value(cfg) # #644: before the (minutes-long) start + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({split})", flush=True) + # a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing + # it is told about (WinError 2), so it is made absolute here + exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"])) + try: + silence = engine_silence_s(cfg) # #481: checked before the (minutes-long) start + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + try: + effort_end = effort_end_args(cfg, exe, tok) # #458 + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + engine = StrataEngine(exe, engine_args(cfg) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"), + env=env, lazy=lazy) + engine.silence_s = silence # an attribute of its own: restart() keeps it + warn_tight_ram(engine.info.get("arena_mib")) + note = desktop_vram_note(cfg.get("backend"), engine.info.get("vram_free_mib"), engine.spawn[1], + linux_desktop()) + if note: # #560 #516: before --open starts a browser on that card + print(note, flush=True) + else: + effort_end = None + engine, vision, sampling_defaults = MockEngine(tok, a.script or [ + "Thinking about it.\n\nHello from the mock engine."]), None, {} + # the model's own chat template (exported with its tokenizer), else the original model's + tpl = tpath / "chat_template.jinja" + svc = Service(engine, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja"), + model_name=cfg.get("model_name", "qwen3.8-flash-next"), vision=vision, + sampling_defaults=sampling_defaults, + fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True) + try: + svc.set_aliases(cfg.get("aliases")) # #297: other names the model answers to + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + if svc.aliases: + print(f"[strata] model aliases: {', '.join(svc.aliases)}", flush=True) + if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or any(x == "--api-key" and i + 1 < len(sys.argv) and not sys.argv[i + 1].strip() or x.strip() == "--api-key=" + for i, x in enumerate(sys.argv)): + # #213: an empty key would switch authentication off without a word + print("[strata] an API key was given but it is empty: set a key, or leave --api-key / STRATA_API_KEY out", + file=sys.stderr) + return 2 + svc.api_key = a.api_key or cfg.get("api_key", "") + svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True) + svc.trusted_origins = origins_of(cfg.get("trusted_origins"), "trusted_origins", wildcard=False) + try: + svc.allowed_hosts = allowed_hosts_of(cfg.get("allowed_hosts"), os.environ.get("STRATA_ALLOWED_HOSTS", "")) + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + if svc.allowed_hosts: + print("[strata] Host check off: any name reaches this server (allowed_hosts \"*\")" if "*" in svc.allowed_hosts + else f"[strata] also answers to the host names {', '.join(svc.allowed_hosts)} (allowed_hosts)", flush=True) + svc.api_monitor = a.api_monitor or cfg.get("api_monitor") is True + if svc.api_monitor: + print("[strata] API request monitor on (/api-monitor): the last 100 requests' prompts and answers are kept in " + "memory" + ("" if svc.api_key else "; anyone who can reach this server can read them (no API key)"), + flush=True) + if svc.cors_origins: + print(f"[strata] CORS on /v1/* for {', '.join(svc.cors_origins)}" + + ("" if svc.api_key or "*" not in svc.cors_origins else + " - WARNING: any web page may use the model (no API key)"), flush=True) + svc.idle_unload_s = a.idle_unload if a.idle_unload is not None else float(cfg.get("idle_unload_s") or 0) + svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \ + int(cfg.get("min_free_vram_mib") or 0) + svc.before_load = a.before_load or cfg.get("before_load") or None + mode = str(cfg.get("anthropic_thinking") or "model") # #278: "on_request" = only when the request asks + if mode not in ("model", "on_request"): + raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}") + svc.anthropic_think_unasked = mode == "model" + rs = cfg.get("repeat_stop_tokens", REPEAT_STOP_TOKENS) # #606: opt-out with 0 + if isinstance(rs, bool) or not isinstance(rs, int) or rs < 0: + raise SystemExit(f"[strata] config \"repeat_stop_tokens\" must be a whole number >= 0 (0 = off), not {rs!r}") + svc.repeat_stop_tokens = rs + svc.effort_end = bool(effort_end) # #458: "effort_position": "end" with an engine that has it + if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request + try: + svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"] + budget = svc.reasoning_budget({}) + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + if budget: + print(f"[strata] thinking budget: {budget} tokens (reasoning_budget_tokens; a request can set its own)", + flush=True) + svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51) + svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112) + svc.backend = cfg.get("backend") # "hip": the AMD cards' readings come from sysfs (#301) + if a.config: + svc.config_path = a.config # #564: the web page's Settings view + if a.config: # the Chat settings shared with other apps, from last time + svc.shared_path = str(Path(a.config).with_suffix("")) + ".shared-settings.json" + try: + svc.shared = clean_shared_defaults(json.loads(Path(svc.shared_path).read_text(encoding="utf-8"))) + if svc.shared: + print("[strata] other apps use the Chat settings: " + + ", ".join(f"{k}={v}" for k, v in svc.shared.items()), flush=True) + except (OSError, ValueError): + svc.shared = {} + if hub is not None: + import atexit + svc.mcp = hub + print(f"[strata] starting {len(hub.servers)} MCP server{'s' * (len(hub.servers) != 1)} for the web app's " + f"chat: {', '.join(hub.servers)}", flush=True) + hub.start() + atexit.register(hub.close) # the servers Strata started end with it + httpd = serve(svc, host=a.host, port=a.port) + svc.start_idle_unload() + here = "127.0.0.1" if a.host in ("0.0.0.0", "", "::") else a.host + print(f"ready: http://{here}:{a.port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, " + f"context {engine.max_context} tokens{', images on' if vision else ''}" + f"{', API key required' if svc.api_key else ''})", flush=True) + print(f" open http://{here}:{a.port}/ in a browser to chat; close this window to stop the model", flush=True) + if a.host not in ("127.0.0.1", "localhost", "::1"): + # issue #26: reachable from other devices - say at which address, and what can still block it + ips = lan_addresses() + for ip in ips: + print(f" from other devices: http://{ip}:{a.port}/ (API: http://{ip}:{a.port}/v1)", flush=True) + if not ips: + print(" from other devices: http://:" + str(a.port) + "/", flush=True) + if not svc.api_key: + print(" WARNING: no API key - anyone on your network can use this model. Add \"api_key\": \"...\" " + "to the config (clients send it as their API key; the web page asks for it)", flush=True) + if os.name == "nt": + print(" nothing arrives? Windows Firewall blocks it until allowed: accept its prompt for Python, or run " + "in an admin PowerShell:\n New-NetFirewallRule -DisplayName \"Strata " + str(a.port) + "\" " + "-Direction Inbound -Protocol TCP -LocalPort " + str(a.port) + " -Action Allow -Profile Private\n" + " (and set this network to Private in Windows' network settings)", flush=True) + if a.open and cfg.get("open_browser") is not False: # #609: the config's "open_browser": false wins (an older + import webbrowser # run-.bat still passes --open) + webbrowser.open(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{a.port}/") + # #96: docker stop sends SIGTERM, which Python ignores by default, so the container's PID 1 would be killed after + # the grace period with the engine still running. SIGTERM takes Ctrl+C's path below (QUIT to the engine). + # SIGINT keeps Python's own handler, so Ctrl+C and a second Ctrl+C work as before. + def on_sigterm(signum, frame): + raise KeyboardInterrupt + try: + signal.signal(signal.SIGTERM, on_sigterm) + except (ValueError, OSError, AttributeError): # not the main thread + pass + try: + while True: + time.sleep(1) # Windows never delivers Ctrl+C to an untimed Event.wait() + except KeyboardInterrupt: + print("\n[strata] stopping (Ctrl+C again to end the engine at once) ...", flush=True) + closers = [httpd.shutdown, getattr(engine, "close", None), vision.close if vision else None, + hub.close if hub is not None else None] + for close in filter(None, closers): + try: + close() + except KeyboardInterrupt: # a second Ctrl+C: don't wait for the engine to free its memory + if getattr(engine, "proc", None): + engine.proc.kill() + print("[strata] stopped", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/serve/structured.py b/serve/structured.py new file mode 100644 index 0000000..b5f079c --- /dev/null +++ b/serve/structured.py @@ -0,0 +1,147 @@ +"""JSON response formats at the HTTP boundary: prompt once, validate before delivery. + +The native engine has no grammar decoder. Failed generations are errors, never +silently retried or returned as successful structured output. + +`jsonschema` is optional (no new hard dependency of the server): json_object needs only the standard library, and +json_schema is checked against its schema when the package is installed - without it, only that the answer is one +JSON object, and the server says so once. +""" +import json +import threading + + +class StructuredOutputError(RuntimeError): + pass + + +class _ObjectOnly: + """The validator for json_object, and for json_schema without jsonschema: one JSON object.""" + + def iter_errors(self, value): + if not isinstance(value, dict): + yield _ObjectError() + + +class _ObjectError: + absolute_path = () + message = "the answer is not a JSON object" + + +_jsonschema = None # (validators, SchemaError, Registry, NoSuchResource), False when not installed +_jsonschema_lock = threading.Lock() + + +def jsonschema_modules(): + """jsonschema, imported on first use; None when it is not installed (said once, in the server window).""" + global _jsonschema + with _jsonschema_lock: + if _jsonschema is None: + try: + from jsonschema import validators + from jsonschema.exceptions import SchemaError + from referencing import Registry + from referencing.exceptions import NoSuchResource + _jsonschema = (validators, SchemaError, Registry, NoSuchResource) + except ImportError: + _jsonschema = False + print('[strata] response_format json_schema: the Python package jsonschema is not installed, so ' + 'answers are only checked to be one JSON object (python -m pip install "jsonschema>=4.23,<5")', + flush=True) + return _jsonschema or None + + +def prepare_format(response_format, messages): + if response_format is None: + return messages, None + if not isinstance(response_format, dict): + raise ValueError("response_format must be an object") + kind = response_format.get("type") + if kind == "text": + return messages, None + if kind == "json_object": + schema = {"type": "object"} + modules = None # the standard library is enough for "one JSON object" + elif kind == "json_schema": + spec = response_format.get("json_schema") + if not isinstance(spec, dict) or not isinstance(spec.get("schema"), dict): + raise ValueError("response_format.json_schema needs a schema object") + if not isinstance(spec.get("name"), str) or not spec["name"]: + raise ValueError("response_format.json_schema needs a name") + if "strict" in spec and not isinstance(spec["strict"], bool): + raise ValueError("response_format.json_schema.strict must be boolean") + schema = spec["schema"] + if schema.get("type") != "object": + raise ValueError("response_format schema must have type object at its root") + modules = jsonschema_modules() + else: + raise ValueError("response_format.type must be text, json_object or json_schema") + + def check_refs(node): + if isinstance(node, dict): + for key, value in node.items(): + if key in ("$ref", "$dynamicRef") and isinstance(value, str) and not value.startswith("#"): + raise ValueError("response_format supports only local schema references (#...)") + check_refs(value) + elif isinstance(node, list): + for value in node: + check_refs(value) + check_refs(schema) + if modules is None: + validator = _ObjectOnly() + else: + validators, SchemaError, Registry, NoSuchResource = modules + + def no_remote(uri): + raise NoSuchResource(ref=uri) + + try: + cls = validators.validator_for(schema) + cls.check_schema(schema) + validator = cls(schema, registry=Registry(retrieve=no_remote)) + except SchemaError as exc: + raise ValueError(f"invalid response_format schema: {exc.message}") from exc + directive = ("OUTPUT FORMAT REQUIREMENT: Return exactly one JSON object matching the JSON Schema below. " + "No Markdown, headings, code fences, commentary, or text outside the JSON. " + "Use every required field, correct types, and only allowed fields. " + "Put all requested writing inside the appropriate JSON string fields.\nJSON Schema:\n" + + json.dumps(schema, ensure_ascii=False, allow_nan=False, separators=(",", ":"))) + messages = [dict(message) for message in messages] + if messages and messages[0].get("role") == "system": + content = messages[0].get("content") or "" + if isinstance(content, list): + messages[0]["content"] = content + [{"type": "text", "text": directive}] + else: + messages[0]["content"] = content + "\n\n" + directive + else: + messages.insert(0, {"role": "system", "content": directive}) + return messages, validator + + +def validated_json(text, validator, finish): + def pairs(items): + obj = {} + for key, value in items: + if key in obj: + raise ValueError(f"duplicate JSON key: {key}") + obj[key] = value + return obj + + def constant(value): + raise ValueError(f"invalid JSON constant: {value}") + + if finish != "stop": + raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget") + try: + value = json.loads(text or "", object_pairs_hook=pairs, parse_constant=constant) + canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + except (ValueError, TypeError) as exc: + raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc + try: + error = next(validator.iter_errors(value), None) + except Exception as exc: + raise StructuredOutputError(f"could not validate structured output: {exc}") from exc + if error is not None: + path = "/" + "/".join(str(part) for part in error.absolute_path) + raise StructuredOutputError(f"model output failed the JSON Schema at {path}: {error.message}") + return canonical diff --git a/serve/telemetry.py b/serve/telemetry.py new file mode 100644 index 0000000..6fc1a03 --- /dev/null +++ b/serve/telemetry.py @@ -0,0 +1,363 @@ +"""serve/telemetry.py - hardware readings for the web app's Monitor tab (idea from PR #22 by code-martin). + +A background thread samples once a second and keeps the last 60 readings of each series for the sparklines: +- GPU: NVIDIA's own NVML library (nvml.dll / libnvidia-ml.so.1, installed with every driver) through ctypes, so no + pip package is needed: load, VRAM, temperature, power, PCIe link and throughput. With the AMD backend (#301): the + amdgpu driver's Linux sysfs files - load, VRAM, temperature and power. +- CPU, RAM, disk: `psutil` when it is installed (setup installs it); without it the CPU and RAM readings fall back to + the OS (Windows GlobalMemoryStatusEx / GetSystemTimes, Linux /proc) and the disk rate is absent. +Anything that cannot be read is None; nothing here can stop the server. +""" +from __future__ import annotations + +import collections +import ctypes +import os +import platform +import sys +import threading +import time + +HISTORY = 60 + + +# ------------------------------------------------------------------------------------------------ NVML +class _Nvml: + class Util(ctypes.Structure): + _fields_ = [("gpu", ctypes.c_uint), ("memory", ctypes.c_uint)] + + class Mem(ctypes.Structure): + _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)] + + def __init__(self, index=0): + self.lib = self.dev = None + names = ["nvml.dll", os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), + "NVIDIA Corporation", "NVSMI", "nvml.dll")] if os.name == "nt" \ + else ["libnvidia-ml.so.1", "libnvidia-ml.so"] + for n in names: + try: + self.lib = ctypes.CDLL(n) + break + except OSError: + continue + if self.lib is None: + return + try: + init = getattr(self.lib, "nvmlInit_v2", None) or self.lib.nvmlInit + if init() != 0: + self.lib = None + return + h = ctypes.c_void_p() + get = getattr(self.lib, "nvmlDeviceGetHandleByIndex_v2", None) or self.lib.nvmlDeviceGetHandleByIndex + if get(ctypes.c_uint(index), ctypes.byref(h)) != 0: + self.lib = None + return + self.dev = h + except (AttributeError, OSError): + self.lib = None + + def ok(self): + return self.lib is not None and self.dev is not None + + def _uint(self, fn, *args): + v = ctypes.c_uint() + try: + return v.value if getattr(self.lib, fn)(self.dev, *args, ctypes.byref(v)) == 0 else None + except (AttributeError, OSError): + return None + + def name(self): + buf = ctypes.create_string_buffer(96) + try: + if self.lib.nvmlDeviceGetName(self.dev, buf, ctypes.c_uint(96)) == 0: + return buf.value.decode(errors="replace") + except (AttributeError, OSError): + pass + return None + + def read(self): + out = {} + u = self.Util() + try: + if self.lib.nvmlDeviceGetUtilizationRates(self.dev, ctypes.byref(u)) == 0: + out["util"] = u.gpu + except (AttributeError, OSError): + pass + m = self.Mem() + try: + if self.lib.nvmlDeviceGetMemoryInfo(self.dev, ctypes.byref(m)) == 0: + out["mem_used"], out["mem_total"] = m.used, m.total + except (AttributeError, OSError): + pass + out["temp"] = self._uint("nvmlDeviceGetTemperature", ctypes.c_uint(0)) # NVML_TEMPERATURE_GPU + mw = self._uint("nvmlDeviceGetPowerUsage") + out["power"] = mw / 1000.0 if mw is not None else None + lim = self._uint("nvmlDeviceGetEnforcedPowerLimit") + out["power_limit"] = lim / 1000.0 if lim is not None else None + out["pcie_gen"] = self._uint("nvmlDeviceGetCurrPcieLinkGeneration") # drops at idle (power saving) + out["pcie_gen_max"] = self._uint("nvmlDeviceGetMaxPcieLinkGeneration") + out["pcie_width"] = self._uint("nvmlDeviceGetCurrPcieLinkWidth") + rx = self._uint("nvmlDeviceGetPcieThroughput", ctypes.c_uint(1)) # NVML_PCIE_UTIL_RX_BYTES, KB/s + tx = self._uint("nvmlDeviceGetPcieThroughput", ctypes.c_uint(0)) + out["pcie_rx_mb"] = rx / 1024.0 if rx is not None else None + out["pcie_tx_mb"] = tx / 1024.0 if tx is not None else None + return out + + +# ------------------------------------------------------------------------------------------------ AMD (Linux sysfs) +SYSFS = "/sys" + + +def amd_device_dir(index, sysfs=None): + """The amdgpu sysfs folder (/sys/class/drm/renderD/device) of the AMD GPU that HIP numbers `index`: the KFD + topology's GPU nodes in order, the CPU nodes skipped, linked to their render node by drm_render_minor - the + numbering setup's amd_gpus() and HIP_VISIBLE_DEVICES use. None when there is no such card (or no amdgpu).""" + base = os.path.join(sysfs or SYSFS, "class", "kfd", "kfd", "topology", "nodes") + try: + nodes = sorted((n for n in os.listdir(base) if n.isdigit()), key=int) + except OSError: + return None + gpus = [] + for n in nodes: + try: + with open(os.path.join(base, n, "properties"), encoding="utf-8") as f: + props = dict(line.strip().partition(" ")[::2] for line in f if line.strip()) + if int(props.get("gfx_target_version") or 0) == 0 or int(props.get("simd_count") or 0) == 0: + continue + gpus.append(props) + except (OSError, ValueError): + continue + if not 0 <= index < len(gpus) or not gpus[index].get("drm_render_minor"): + return None + dev = os.path.join(sysfs or SYSFS, "class", "drm", "renderD" + gpus[index]["drm_render_minor"].strip(), "device") + return dev if os.path.isdir(dev) else None + + +class _Amd: + """#301: an AMD card's readings from the amdgpu driver's sysfs files (Linux; no ROCm library needed), with _Nvml's + interface: load (gpu_busy_percent), VRAM (mem_info_vram_used / _total), and from its hwmon folder the temperature + (temp1_input, the edge sensor, m°C), power (power1_average or power1_input, µW) and its cap (power1_cap).""" + + def __init__(self, index=0, sysfs=None): + self.dev = amd_device_dir(index, sysfs) + self.hwmon = None + if self.dev: + try: + hw = sorted(os.listdir(os.path.join(self.dev, "hwmon"))) + self.hwmon = os.path.join(self.dev, "hwmon", hw[0]) if hw else None + except OSError: + pass + + def ok(self): + return self.dev is not None + + @staticmethod + def _int(path): + try: + with open(path, encoding="utf-8") as f: + return int(f.read().strip()) + except (OSError, ValueError, TypeError): + return None + + def name(self): + try: + with open(os.path.join(self.dev, "product_name"), encoding="utf-8") as f: + return f.read().strip() or "AMD Radeon" + except (OSError, TypeError): + return "AMD Radeon" + + def read(self): + out = {"util": self._int(os.path.join(self.dev, "gpu_busy_percent")), + "mem_used": self._int(os.path.join(self.dev, "mem_info_vram_used")), + "mem_total": self._int(os.path.join(self.dev, "mem_info_vram_total"))} + if self.hwmon: + t = self._int(os.path.join(self.hwmon, "temp1_input")) + out["temp"] = t / 1000.0 if t is not None else None + p = self._int(os.path.join(self.hwmon, "power1_average")) + if p is None: + p = self._int(os.path.join(self.hwmon, "power1_input")) + out["power"] = p / 1e6 if p is not None else None + cap = self._int(os.path.join(self.hwmon, "power1_cap")) + out["power_limit"] = cap / 1e6 if cap is not None else None + return out + + +def gpu_reader(index=0, amd=False): + """The card's readings: NVML (NVIDIA), or the amdgpu sysfs files with the AMD backend (#301).""" + return _Amd(index) if amd else _Nvml(index) + + +def free_vram_mib(index=0, amd=False): + """Free VRAM of a card in MiB, or None when it cannot be read.""" + g = gpu_reader(index, amd) + if not g.ok(): + return None + r = g.read() + if r.get("mem_total") is None or r.get("mem_used") is None: + return None + return int((r["mem_total"] - r["mem_used"]) >> 20) + + +# ------------------------------------------------------------------------------------------------ CPU / RAM +def _cpu_name(): + if os.name == "nt": + try: + import winreg + k = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") + return winreg.QueryValueEx(k, "ProcessorNameString")[0].strip() + except OSError: + pass + elif os.path.exists("/proc/cpuinfo"): + for line in open("/proc/cpuinfo", encoding="utf-8", errors="replace"): + if line.startswith("model name"): + return line.split(":", 1)[1].strip() + return platform.processor() or None + + +class _CpuRamFallback: + """CPU load and RAM without psutil.""" + + def __init__(self): + self.prev = self._times() + + def _times(self): + if os.name == "nt": + idle, kern, user = (ctypes.c_ulonglong() for _ in range(3)) + if ctypes.windll.kernel32.GetSystemTimes(ctypes.byref(idle), ctypes.byref(kern), ctypes.byref(user)): + return idle.value, kern.value + user.value # kernel time includes idle + return None + try: + f = [int(x) for x in open("/proc/stat").readline().split()[1:]] + return f[3] + f[4], sum(f) + except (OSError, ValueError): + return None + + def cpu(self): + cur = self._times() + prev, self.prev = self.prev, cur + if not cur or not prev or cur[1] == prev[1]: + return None + return max(0.0, min(100.0, 100.0 * (1 - (cur[0] - prev[0]) / (cur[1] - prev[1])))) + + @staticmethod + def ram(): + if os.name == "nt": + class MS(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] + m = MS() + m.dwLength = ctypes.sizeof(MS) + if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)): + return m.ullTotalPhys - m.ullAvailPhys, m.ullTotalPhys + return None, None + try: + info = dict(line.split(":", 1) for line in open("/proc/meminfo")) + total = int(info["MemTotal"].split()[0]) * 1024 + avail = int(info["MemAvailable"].split()[0]) * 1024 + return total - avail, total + except (OSError, KeyError, ValueError): + return None, None + + +# ------------------------------------------------------------------------------------------------ the sampler +class Telemetry: + def __init__(self, extra=None, gpu_index=0, gpu_indices=None, amd=False): + """`extra()` -> dict of more series to record each second (the server's tok/s). `gpu_index`: the card the + engine runs on, numbered as nvidia-smi and NVML number them (by PCI bus); `gpu_indices`: all of them when + the model is split across several (issue #112) - the gpu_* readings are then their total (memory, power, + PCIe traffic), mean (load) or hottest (temperature), and "gpus" has each card's own. `amd`: the AMD backend's + cards, numbered as HIP numbers them, read from sysfs (#301).""" + self.extra = extra + self.lock = threading.Lock() + self.now: dict = {} + self.hist = collections.defaultdict(lambda: collections.deque(maxlen=HISTORY)) + idx = list(gpu_indices) if gpu_indices and len(gpu_indices) > 1 else [gpu_index] + self.gpus = [(i, gpu_reader(i, amd)) for i in idx] + self.gpus = [(i, g) for i, g in self.gpus if g.ok()] or self.gpus[:1] + self.gpu = self.gpus[0][1] + try: + import psutil # noqa: F401 + self.ps = sys.modules["psutil"] + except ImportError: + self.ps = None + self.fallback = _CpuRamFallback() + self.static = { + "gpu_name": " + ".join(g.name() or "?" for _, g in self.gpus) if self.gpu.ok() else None, + "gpu_count": len(self.gpus), + "cpu_name": _cpu_name(), + "cores": (self.ps.cpu_count(logical=False) if self.ps else None) or None, + "threads": os.cpu_count(), + "psutil": self.ps is not None, + } + self._disk_prev = None + threading.Thread(target=self._loop, daemon=True).start() + + def _disk(self): + if not self.ps: + return None, None + try: + c = self.ps.disk_io_counters() + except (OSError, RuntimeError): + return None, None + t = time.time() + prev, self._disk_prev = self._disk_prev, (t, c.read_bytes, c.write_bytes) + if prev is None or t <= prev[0]: + return None, None + dt = t - prev[0] + return (c.read_bytes - prev[1]) / dt / 2**20, (c.write_bytes - prev[2]) / dt / 2**20 + + def sample(self): + s = {} + if self.gpu.ok(): + reads = [(i, g.read()) for i, g in self.gpus] + g = dict(reads[0][1]) + if len(reads) > 1: + def vals(k): + return [r[k] for _, r in reads if r.get(k) is not None] + for k in ("mem_used", "mem_total", "power", "power_limit", "pcie_rx_mb", "pcie_tx_mb"): + v = vals(k) + g[k] = sum(v) if v else None + u = vals("util") + g["util"] = sum(u) / len(u) if u else None + t = vals("temp") + g["temp"] = max(t) if t else None + s["gpus"] = [{"index": i, "util": r.get("util"), "mem_used": r.get("mem_used"), + "mem_total": r.get("mem_total"), "temp": r.get("temp"), "power": r.get("power")} + for i, r in reads] + s.update({f"gpu_{k}": v for k, v in g.items()}) + if self.ps: + try: + s["cpu"] = self.ps.cpu_percent(interval=None) + vm = self.ps.virtual_memory() + s["ram_used"], s["ram_total"] = vm.total - vm.available, vm.total + except (OSError, RuntimeError): + pass + else: + s["cpu"] = self.fallback.cpu() + s["ram_used"], s["ram_total"] = self.fallback.ram() + s["disk_read_mb"], s["disk_write_mb"] = self._disk() + if self.extra: + try: + s.update(self.extra()) + except Exception: # noqa: BLE001 - telemetry must never take the server down + pass + return s + + def _loop(self): + while True: + s = self.sample() + with self.lock: + self.now = s + for k in ("gpu_util", "gpu_mem_used", "gpu_temp", "gpu_power", "gpu_pcie_rx_mb", "cpu", "ram_used", + "disk_read_mb", "tok_s", "prefill_tok_s_mean"): + v = s.get(k) + self.hist[k].append(round(v, 2) if isinstance(v, float) else v) + time.sleep(1.0) + + def snapshot(self): + with self.lock: + return {"now": dict(self.now), "history": {k: list(v) for k, v in self.hist.items()}, + "static": dict(self.static)} diff --git a/serve/test_detok.py b/serve/test_detok.py new file mode 100644 index 0000000..b1c6142 --- /dev/null +++ b/serve/test_detok.py @@ -0,0 +1,252 @@ +"""The streaming detokenizer (perf-review F-1): the incremental one emits exactly what the old re-decode did, token +by token, and its cost per token does not grow with the reply. + + python -m unittest serve.test_detok (needs a pack's tokenizer; skipped without one) +""" +import os +import random +import sys +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) + +from serve.server import Detokenizer # noqa: E402 + + +def find_tokenizer(): + cands = [os.environ.get("STRATA_TOKENIZER", "")] + cands += [str(p) for p in ROOT.glob("packs/*/tokenizer")] + [str(p) for p in ROOT.glob("pack/*/tokenizer")] + cands += [r"C:\Users\AI-Server\Desktop\Strata\Public\Engine\pack\full\tokenizer"] + for c in cands: + if c and (Path(c) / "vocab.json").exists(): + return Path(c) + return None + + +class OldDetokenizer: + """The pre-0.1.22 algorithm: re-decode every generated id, hold a trailing U+FFFD.""" + + def __init__(self, tok): + self.tok, self.ids, self.sent = tok, [], 0 + + def push(self, t): + self.ids.append(t) + text = self.tok.decode(self.ids) + if text.endswith("\ufffd"): + return "" + delta, self.sent = text[self.sent:], len(text) + return delta + + +@unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here") +class Detok(unittest.TestCase): + @classmethod + def setUpClass(cls): + import json + import strata_tokenizer as ST + t = find_tokenizer() + vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) + toks = [None] * len(vocab) + for s, i in vocab.items(): + toks[i] = s + cls.tok = ST.Tokenizer(toks, (t / "merges.txt").read_text(encoding="utf-8").split("\n"), + json.loads((t / "token_type.json").read_text())) + + def same_stream(self, ids): + """The same text as the old re-decode, never behind it (the old one held complete characters too while + the tail was an incomplete one; the new one holds only the incomplete bytes), and never ahead of what the + ids so far decode to.""" + a, b = OldDetokenizer(self.tok), Detokenizer(self.tok) + self.assertIsNotNone(b.inc) + old = new = "" + for i, t in enumerate(ids): + old += a.push(t) + new += b.push(t) + self.assertTrue(new.startswith(old), f"token {i} ({t}): behind the old stream") + self.assertTrue(self.tok.decode(ids[:i + 1]).startswith(new), f"token {i} ({t}): ahead of the ids") + if not self.tok.decode(ids).endswith("�"): + self.assertEqual(old, new) + + def test_text_with_split_characters(self): + text = ("Grüße aus Zürich! 你好,世界。日本語のテキスト 🌊🦊👩‍💻 and ASCII code: def f(x): return x**2\n" * 40) + self.same_stream(self.tok.encode(text)) + + def test_random_ids_and_broken_bytes(self): + rng = random.Random(5) + n = len(self.tok.tokens) + for _ in range(20): # random ids: split and invalid UTF-8 sequences everywhere (no U+FFFD token itself) + ids = [rng.randrange(n) for _ in range(300)] + ids = [t for t in ids if "\ufffd" not in self.tok.decode([t], errors="strict" if False else "replace") + or len(self.tok.token_bytes(t)) < 3] + self.same_stream(ids) + + def test_constant_cost(self): + ids = self.tok.encode("The quick brown fox jumps over the lazy dog. " * 2000)[:16384] + d = Detokenizer(self.tok) + for t in ids[:1024]: + d.push(t) + t0 = time.perf_counter() + for t in ids[1024:1124]: + d.push(t) + early = time.perf_counter() - t0 + for t in ids[1124:16000]: + d.push(t) + t0 = time.perf_counter() + for t in ids[16000:16100]: + d.push(t) + late = time.perf_counter() - t0 + self.assertLess(late / 100, 0.0002, "a token after 16K tokens costs more than 0.2 ms") + self.assertLess(late, early * 5 + 0.002) + + +# ------------------------------------------------------------------ #268: the heap BPE for long words +_REAL = [] + + +def real_tokenizer(): + """The pack's tokenizer, loaded once for every class that needs it (None when there is no pack here).""" + if not _REAL: + t = find_tokenizer() + if t is None: + _REAL.append(None) + else: + import json + import strata_tokenizer as ST + vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) + toks = [None] * len(vocab) + for s, i in vocab.items(): + toks[i] = s + _REAL.append(ST.Tokenizer(toks, (t / "merges.txt").read_text(encoding="utf-8").split("\n"), + json.loads((t / "token_type.json").read_text()))) + return _REAL[0] + + +def random_text(rng, n_pieces=40): + """Strings shaped to make one pre-token piece long or awkward: CJK and Hangul runs (syllables and conjoining + jamo), letters under stacks of combining marks, URLs, minified code, digits, emoji, whitespace, specials.""" + def run(lo, hi, k): + return "".join(chr(rng.randint(lo, hi)) for _ in range(k)) + + kinds = [ + lambda: run(0x4E00, 0x9FFF, rng.randint(1, 400)), # CJK + lambda: run(0xAC00, 0xD7A3, rng.randint(1, 200)), # Hangul syllables + lambda: "".join(chr(0x1100 + rng.randrange(19)) + chr(0x1161 + rng.randrange(21)) + for _ in range(rng.randint(1, 60))), # conjoining jamo + lambda: "".join(rng.choice("aeiouxyz") + run(0x0300, 0x036F, rng.randint(0, 4)) + for _ in range(rng.randint(1, 80))), # combining marks + lambda: "https://example.com/" + "/".join(run(0x61, 0x7A, rng.randint(1, 12)) + for _ in range(rng.randint(1, 20))) + "?q=" + run(0x30, 0x39, 8), + lambda: "".join(rng.choice(["var ", "a=", "b", "(", ")", "{", "}", ";", "function", "return", "x", "+", + "!0", "void 0", ",", ".", "[", "]", "=>", "&&"]) for _ in range(rng.randint(1, 300))), + lambda: run(0x30, 0x39, rng.randint(1, 50)), + lambda: rng.choice([" ", " ", "\n", "\n\n", "\t", "\r\n", " \n "]) * rng.randint(1, 30), + lambda: rng.choice(["\U0001f600", "\U0001f30a", "\U0001f469‍\U0001f4bb", "é", "ß"]) * rng.randint(1, 30), + lambda: rng.choice(["<|im_end|>", "<|im_start|>", "", "", "", "<|im_sta"]), + lambda: "a" * rng.randint(60, 300), + lambda: run(0x20, 0x7E, rng.randint(1, 200)), + ] + return "".join(rng.choice(kinds)() for _ in range(rng.randint(1, n_pieces))) + + +def encode_with(tok, text, parse_special, heap_min): + tok.HEAP_MIN = heap_min + try: + return tok.encode(text, parse_special=parse_special) + finally: + del tok.HEAP_MIN + + +def synthetic_tokenizer(seed=268, n_merges=1500): + """A small byte-level BPE vocabulary with merges learned (randomly) from random_text, and a few specials of + both kinds - so the parity test runs without a pack.""" + import strata_tokenizer as ST + rng = random.Random(seed) + tokens = sorted(set(ST.BYTE_TO_UNICODE.values())) + have, merges = set(tokens), [] + words = [] + for _ in range(60): + for piece in ST.regex.compile(ST.QWEN35_PATTERN).findall(random_text(rng, 10)): + words.append([ST.BYTE_TO_UNICODE[b] for b in piece.encode("utf-8")]) + words = [w for w in words if len(w) > 1] + while len(merges) < n_merges: + w = rng.choice(words) + if len(w) < 2: + continue + i = rng.randrange(len(w) - 1) + a, b = w[i], w[i + 1] + w[i:i + 2] = [a + b] # learn in place, so later merges build on earlier ones + if a + b in have or f"{a} {b}" in merges: + continue + merges.append(f"{a} {b}") + tokens.append(a + b) + have.add(a + b) + types = [1] * len(tokens) + for lit, ty in [("<|im_end|>", 3), ("<|im_start|>", 3), ("", 4), ("", 4), ("", 4)]: + tokens.append(lit) + types.append(ty) + return ST.Tokenizer(tokens, merges, types) + + +class HeapBpe(unittest.TestCase): + """#268: words longer than HEAP_MIN symbols merge with a heap; the ids must be exactly the scan's.""" + + def parity(self, tok, texts): + for k, text in enumerate(texts): + for ps in (False, True): + old = encode_with(tok, text, ps, 10 ** 9) # the scan for every word + self.assertEqual(encode_with(tok, text, ps, 0), old, f"text {k} parse_special={ps}") # the heap + self.assertEqual(tok.encode(text, parse_special=ps), old, f"text {k} parse_special={ps}") + + def test_words_directly(self): + tok = synthetic_tokenizer() + rng = random.Random(1) + import strata_tokenizer as ST + for _ in range(300): + for piece in ST.regex.compile(ST.QWEN35_PATTERN).findall(random_text(rng, 8)): + word = "".join(ST.BYTE_TO_UNICODE[b] for b in piece.encode("utf-8")) + tok.HEAP_MIN = 10 ** 9 + try: + old = tok._bpe(word) + finally: + del tok.HEAP_MIN + self.assertEqual(tok._bpe_heap(word), old, repr(piece[:40])) + + def test_synthetic_vocab(self): + tok = synthetic_tokenizer() + rng = random.Random(2) + self.parity(tok, [random_text(rng) for _ in range(60)] + ["a" * 5000, "ab" * 3000, ""]) + + @unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here") + def test_pack_vocab(self): + tok = real_tokenizer() + rng = random.Random(3) + fixed = ["你好,世界" * 150, "한국어 텍스트" * 100, + "é́̂" * 200, "x" * 5000, + "https://example.com/" + "a/b-c_d.e?f=g&h=i#j" * 60, + "!function(e){var t={};function n(r){if(t[r])return t[r].exports}}" * 30, + "<|im_start|>user\n日本語" * 40 + "<|im_end|>" + "漢" * 300] + self.parity(tok, fixed + [random_text(rng) for _ in range(40)]) + + def check_speed(self, tok): + rng = random.Random(4) + text = "".join(chr(rng.randint(0x4E00, 0x9FFF)) for _ in range(8192)) # one 24K-byte piece + t0 = time.perf_counter() + ids = tok.encode(text) + took = time.perf_counter() - t0 + self.assertEqual(tok.decode(ids), text) + self.assertLess(took, 1.0, f"an 8K-character CJK run took {took:.2f} s") + + def test_speed_synthetic(self): + self.check_speed(synthetic_tokenizer()) + + @unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here") + def test_speed_pack(self): + self.check_speed(real_tokenizer()) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_lifecycle.py b/serve/test_lifecycle.py new file mode 100644 index 0000000..1d9f58c --- /dev/null +++ b/serve/test_lifecycle.py @@ -0,0 +1,170 @@ +"""Model discovery, on-demand loading and safe unloading over the actual HTTP API.""" +import json +import io +import subprocess +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, EngineDied, EngineStuck, MockEngine, Service, StrataEngine, serve + + +class ResidentEngine(StrataEngine): + def __init__(self, tok): + self.reply = MockEngine(tok, "Hello.", max_context=4096) + self.max_context, self.info, self.last = 4096, {}, {} + self.loaded, self.starts, self.closes = False, 0, 0 + self.unloaded = True + self.progress = None + + def alive(self): + return self.loaded + + def exit_code(self): + return None + + def restart(self): + self.loaded = True + self.starts += 1 + self.unloaded = False + + def close(self): + self.loaded = False + self.closes += 1 + + def unload(self): + self.close() + self.unloaded = True + + def generate(self, *args, **kwargs): + yield from self.reply.generate(*args, **kwargs) + + +class Lifecycle(unittest.TestCase): + def test_close_sends_eof_before_waiting_for_windows_reader(self): + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.side_effect = [None, 0] + proc.wait.side_effect = lambda **kwargs: self.assertTrue(proc.stdin.closed) + engine.proc = proc + engine.close() + self.assertIsNone(engine.proc) + proc.kill.assert_not_called() + + def test_close_does_not_forget_a_process_still_exiting(self): + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.return_value = None + proc.wait.side_effect = subprocess.TimeoutExpired("engine", 2) + engine.proc = proc + with self.assertRaisesRegex(EngineStuck, "still releasing"): + engine.close() + self.assertIs(engine.proc, proc) + proc.terminate.assert_called_once() + proc.kill.assert_called_once() + + def test_close_terminates_before_it_kills(self): + # an engine that does not end on QUIT is terminated first (as the unload always did); kill is the last resort + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.side_effect = [None, 0] + proc.wait.side_effect = [subprocess.TimeoutExpired("engine", 20), 0] + engine.proc = proc + engine.close() + proc.terminate.assert_called_once() + proc.kill.assert_not_called() + self.assertIsNone(engine.proc) + + def test_native_lazy_constructor_does_not_start_a_process(self): + engine = StrataEngine("missing-executable", ["--max-context", "16384"], lazy=True) + self.assertFalse(engine.alive()) + self.assertEqual(engine.max_context, 16384) + self.assertIsNone(engine.exit_code()) + engine.close() + + def setUp(self): + tok = ByteTokenizer() + self.engine = ResidentEngine(tok) + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + data = response.read().decode() + return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data) + + def test_discover_chat_unload_and_stream_reload(self): + self.assertEqual(self.request("/api/health")[1]["service"], "strata") + self.assertFalse(self.request("/v1/status")[1]["loaded"]) + self.assertEqual(self.request("/v1/models")[1]["data"][0]["status"]["value"], "unloaded") + self.assertTrue(self.request("/props")[1]["models_autoload"]) + self.assertEqual(self.engine.starts, 0) + chat = {"messages": [{"role": "user", "content": "Hello"}], "max_tokens": 32, "reasoning_effort": "none"} + for _ in range(2): + code, answer = self.request("/v1/chat/completions", chat) + self.assertEqual(code, 200) + self.assertEqual(answer["choices"][0]["message"]["content"], "Hello.") + self.assertEqual(self.engine.starts, 1) + self.assertFalse(self.request("/v1/unload", {})[1]["loaded"]) + code, stream = self.request("/v1/chat/completions", {**chat, "stream": True}) + self.assertEqual(code, 200) + self.assertIn("data: [DONE]", stream) + self.assertEqual(self.engine.starts, 2) + + def test_busy_auth_and_foreign_origin_cannot_unload(self): + self.engine.loaded = True + with self.svc.fifo: + self.assertEqual(self.request("/v1/unload", {})[0], 409) + self.svc.api_key = "local-secret" + self.assertEqual(self.request("/v1/unload", {})[0], 401) + self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret", + "Origin": "https://other.example"})[0], 403) + self.assertEqual(self.engine.closes, 0) + self.assertTrue(self.engine.loaded) + self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret"})[0], 200) + + def test_an_engine_that_died_on_load_is_reported_as_such(self): + # EngineDied is a RuntimeError: it keeps its own answer ("the next request restarts it") + def died(): + raise EngineDied("the engine ended while it started") + self.engine.restart = died + code, body = self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "Hello"}]}) + self.assertEqual(code, 503) + self.assertIn("the next request restarts it", body["error"]["message"]) + + def test_explicit_load_and_model_matching(self): + self.assertEqual(self.request("/v1/load", {"model": "other-model"})[0], 404) + self.assertEqual(self.engine.starts, 0) + before = time.time() + code, status = self.request("/v1/load", {"model": self.svc.model}) + self.assertEqual(code, 200) + self.assertTrue(status["loaded"]) + self.assertEqual(self.engine.starts, 1) + self.assertGreaterEqual(self.svc.last_request_at, before) + self.svc.status["queued"] = 1 + self.assertEqual(self.request("/v1/load", {})[0], 409) + self.assertEqual(self.request("/v1/unload", {})[0], 409) + self.assertEqual(self.engine.closes, 0) + self.assertEqual(self.request("/v1/load", {}, {"Content-Type": "text/plain"})[0], 415) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_mcp.py b/serve/test_mcp.py new file mode 100644 index 0000000..c80c5d0 --- /dev/null +++ b/serve/test_mcp.py @@ -0,0 +1,447 @@ +"""serve/test_mcp.py - tools from MCP servers (serve/mcp.py) and the web app's tool loop, against the mock engine and +the fake MCP server in serve/mcp_fake_server.py (no GPU, no pack, no MCP SDK). + + python -m unittest serve.test_mcp -v +""" +from __future__ import annotations + +import json +import os +import sys +import tempfile +import threading +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve import mcp_fake_server as fake # noqa: E402 +from serve.frontend import ChatTemplate # noqa: E402 +from serve.mcp import McpCancelled, McpHub, hub_from_config # noqa: E402 +from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +FAKE = str(ROOT / "serve" / "mcp_fake_server.py") +CTX = 8192 + + +def stdio(*args, **extra): + return {"command": sys.executable, "args": [FAKE, *args], **extra} + + +def call_script(name, **params): + """The model's text for one tool call, as Qwen's template asks for it.""" + body = "".join(f"\n{v}\n\n" for k, v in params.items()) + return f"\n\nLet me check.\n\n\n\n{body}\n" + + +class ScriptedEngine(MockEngine): + """A mock engine with one script per call (the last one repeats): a tool call first, then the answer.""" + + def __init__(self, tok, scripts, max_context=CTX, delay_s=0.0): + super().__init__(tok, list(scripts), max_context=max_context, delay_s=delay_s) + self.prompts = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.prompts.append(list(ids)) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + def prompt_text(self, i): + return bytes(t for t in self.prompts[i] if t < 256).decode("utf-8", "replace") + + +# ------------------------------------------------------------------------------------------------ the client +class Client(unittest.TestCase): + """The stdio client against the fake server: start, pagination, calls, errors, crashes, timeouts, the cap.""" + + @classmethod + def setUpClass(cls): + cls.log = tempfile.NamedTemporaryFile(delete=False, suffix=".jsonl") + cls.log.close() + os.environ["FAKE_MCP_LOG"] = cls.log.name + cls.hub = McpHub({"fake": stdio(), "paged": stdio("--page", "4"), "broken": stdio("--crash-at-start"), + "missing": {"command": "strata-no-such-program"}}, + {"timeout_s": 1.5, "max_result_chars": 1000}) + cls.hub.start(wait=True) + + @classmethod + def tearDownClass(cls): + cls.hub.close() + del os.environ["FAKE_MCP_LOG"] + os.unlink(cls.log.name) + + def test_initialize_and_list_every_page(self): + s = self.hub.servers["fake"] + self.assertEqual(s.status, "ready") + self.assertEqual(s.info["name"], "fake") + self.assertEqual(s.info["protocol"], "2025-06-18") + want = [t["name"] for t in fake.TOOLS] + self.assertEqual([t["name"] for t in s.tools], want) # 3 pages of 2 + self.assertEqual([t["name"] for t in self.hub.servers["paged"].tools], want) # 2 pages of 4 + + def test_namespaced_openai_tools(self): + tools = self.hub.openai_tools() + names = [t["function"]["name"] for t in tools] + self.assertIn("fake__echo", names) + self.assertIn("paged__echo", names) + echo = next(t for t in tools if t["function"]["name"] == "fake__echo") + self.assertEqual(echo["type"], "function") + self.assertEqual(echo["function"]["parameters"]["properties"]["text"]["type"], "string") + + def test_a_server_that_fails_is_left_out(self): + for name, why in (("broken", "missing configuration"), ("missing", "could not start")): + with self.subTest(name=name): + s = self.hub.servers[name] + self.assertEqual(s.status, "failed") + self.assertIn(why, s.error) + self.assertFalse([t for t in self.hub.template_tools() if t["name"].startswith(name + "__")]) + st = {s["name"]: s for s in self.hub.status()["servers"]} + self.assertEqual(st["broken"]["status"], "failed") + self.assertEqual(st["fake"]["status"], "ready") + + def test_call(self): + self.hub.routes() + r = self.hub.call("fake__echo", {"text": "hello wörld"}) + self.assertEqual((r["ok"], r["text"], r["server"], r["tool"]), (True, "hello wörld", "fake", "echo")) + self.assertEqual(self.hub.call("fake__add", {"a": 2, "b": 40})["text"], "42") + + def test_errors_become_text(self): + self.hub.routes() + r = self.hub.call("fake__fail", {}) # the tool's own error (isError) + self.assertFalse(r["ok"]) + self.assertEqual(r["text"], "error: it failed on purpose") + r = self.hub.call("nobody__nothing", {}) # not a tool at all + self.assertTrue(r["text"].startswith("error: there is no tool")) + # a JSON-RPC error from the server + s = self.hub.servers["fake"] + with self.assertRaises(Exception) as ctx: + s.call("no-such-tool", {}, 5) + self.assertIn("unknown tool", str(ctx.exception)) + + def test_timeout(self): + self.hub.routes() + t0 = time.monotonic() + r = self.hub.call("fake__sleep", {"seconds": 5}) + self.assertLess(time.monotonic() - t0, 4) + self.assertFalse(r["ok"]) + self.assertIn("timed out after 1.5 s", r["text"]) + self.assertEqual(self.hub.call("fake__echo", {"text": "still here"})["text"], "still here") + + def test_truncation(self): + self.hub.routes() + r = self.hub.call("fake__big", {"n": 50000}) + self.assertTrue(r["ok"]) + self.assertTrue(r["truncated"]) + self.assertEqual(r["chars"], 50000) + self.assertTrue(r["text"].startswith("y" * 1000 + "\n\n[... truncated")) + self.assertIn("50,000 characters", r["text"]) + self.assertLess(len(r["text"]), 1200) + + def test_crash_mid_call_then_restart(self): + hub = McpHub({"solo": stdio()}, {"timeout_s": 5}) + hub.start(wait=True) + try: + hub.routes() + r = hub.call("solo__die", {}) + self.assertFalse(r["ok"]) + self.assertIn("the server stopped", r["text"]) + self.assertIn("dying on purpose", r["text"]) + self.assertEqual(hub.servers["solo"].status, "stopped") + self.assertIn("solo__echo", hub.routes()) # its tools stay: the next call restarts it + self.assertEqual(hub.call("solo__echo", {"text": "back"})["text"], "back") + self.assertEqual(hub.servers["solo"].status, "ready") + finally: + hub.close() + + def test_cancel(self): + self.hub.routes() + cancel = threading.Event() + threading.Timer(0.3, cancel.set).start() + t0 = time.monotonic() + with self.assertRaises(McpCancelled): + self.hub.call("fake__sleep", {"seconds": 1.2}, cancel) + self.assertLess(time.monotonic() - t0, 1.0) + time.sleep(0.3) + seen = [json.loads(line) for line in Path(self.log.name).read_text().splitlines()] + self.assertTrue(any("cancelled" in e for e in seen), seen) # notifications/cancelled reached the server + + +class HttpClient(unittest.TestCase): + """Streamable HTTP: JSON answers, an event-stream answer, the session id.""" + + @classmethod + def setUpClass(cls): + cls.httpd = fake.http_server(0) + url = f"http://127.0.0.1:{cls.httpd.server_address[1]}/mcp" + cls.hub = McpHub({"web": {"url": url}, "down": {"url": "http://127.0.0.1:9/mcp"}}, {"timeout_s": 1.5}) + cls.hub.start(wait=True) + + @classmethod + def tearDownClass(cls): + cls.hub.close() + cls.httpd.shutdown() + cls.httpd.server_close() + + def test_list_and_call(self): + s = self.hub.servers["web"] + self.assertEqual(s.status, "ready", s.error) + self.assertEqual(len(s.tools), len(fake.TOOLS)) # pages, with the session id on each request + self.assertEqual(s.transport.session, "s-1") + self.hub.routes() + self.assertEqual(self.hub.call("web__echo", {"text": "over http"})["text"], "over http") # event stream + self.assertEqual(self.hub.call("web__fail", {})["text"], "error: it failed on purpose") + + def test_timeout_and_unreachable(self): + self.hub.routes() + r = self.hub.call("web__sleep", {"seconds": 4}) + self.assertIn("timed out", r["text"]) + self.assertEqual(self.hub.servers["down"].status, "failed") + self.assertIn("could not reach", self.hub.servers["down"].error) + + +class Config(unittest.TestCase): + def test_both_spellings_and_the_file(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "claude_desktop_config.json") + Path(path).write_text(json.dumps({"mcpServers": {"b": {"url": "http://x/mcp"}, "a": stdio()}}), + encoding="utf-8") + hub = hub_from_config({"mcp_servers": {"a": {"command": "old"}}, + "mcpServers": {"c": stdio(), "off": {"command": "x", "disabled": True}}, + "mcp": {"timeout_s": 5, "max_result_chars": 100, "max_rounds": 3}}, path) + self.assertEqual(sorted(hub.servers), ["a", "b", "c"]) + self.assertEqual(hub.servers["a"].cfg["command"], sys.executable) # the file wins a name clash + self.assertEqual(hub.servers["b"].kind, "http") + self.assertEqual((hub.settings["timeout_s"], hub.settings["max_result_chars"], hub.settings["max_rounds"]), + (5.0, 100, 3)) + self.assertIsNone(hub_from_config({})) + self.assertEqual(McpHub({}).settings["max_result_chars"], 20000) + + def test_bad_entries_stop_the_start(self): + for cfg in ({"mcp_servers": {"x": {}}}, {"mcp_servers": {"x": {"command": "a", "args": "b"}}}, + {"mcp_servers": ["x"]}, {"mcpServers": {"x": {"url": "http://a", "type": "sse"}}}, + {"mcp_servers": {"x": {"command": "a"}}, "mcp": {"timeout_s": 0}}, + {"mcp_servers": {"x": {"command": "a"}}, "mcp": {"max_rounds": 1.5}}): + with self.subTest(cfg=cfg), self.assertRaises(SystemExit): + hub_from_config(cfg) + with self.assertRaises(SystemExit): + hub_from_config({}, os.path.join(tempfile.gettempdir(), "strata-no-such-mcp.json")) + + +# ------------------------------------------------------------------------------------------------ the tool loop +class ToolLoop(unittest.TestCase): + """The web app's chat (`"strata_mcp": true`): the model calls an MCP tool, the server runs it and the model + answers with its result; plain API requests never see the MCP tools.""" + + def setUp(self): + self.log = tempfile.NamedTemporaryFile(delete=False, suffix=".jsonl") + self.log.close() + os.environ["FAKE_MCP_LOG"] = self.log.name + self.hub = McpHub({"fake": stdio(), "broken": stdio("--crash-at-start")}, + {"timeout_s": 10, "max_result_chars": 500, "max_rounds": 2}) + self.hub.start(wait=True) + self.httpd = None + + def tearDown(self): + if self.httpd: + self.httpd.shutdown() + self.httpd.server_close() + self.hub.close() + del os.environ["FAKE_MCP_LOG"] + os.unlink(self.log.name) + + def start(self, *scripts, delay_s=0.0): + tok = ByteTokenizer() + self.engine = ScriptedEngine(tok, list(scripts), delay_s=delay_s) + self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.svc.mcp = self.hub + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def post(self, body, headers=None, stream=True): + body = {"model": "m", "messages": [{"role": "user", "content": "check it"}], "stream": stream, **body} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", **(headers or {})}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + text = r.read().decode() + return r.status, text + except urllib.error.HTTPError as e: + with e: + return e.code, e.read().decode() + + @staticmethod + def chunks(text): + return [json.loads(line[6:]) for line in text.splitlines() if line.startswith("data: {")] + + def test_tool_call_then_answer(self): + self.start(call_script("fake__echo", text="hello from the tool"), "\n\nThe tool said hello.") + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + cs = self.chunks(text) + mcp = [c["strata_mcp"] for c in cs if "strata_mcp" in c] + self.assertEqual([m["event"] for m in mcp], ["start", "call", "result"]) + self.assertEqual(mcp[1]["arguments"], {"text": "hello from the tool"}) + self.assertEqual((mcp[1]["server"], mcp[1]["tool"]), ("fake", "echo")) + self.assertEqual((mcp[2]["ok"], mcp[2]["text"]), (True, "hello from the tool")) + self.assertEqual(len({m["id"] for m in mcp}), 1) + content = "".join((c["choices"][0]["delta"].get("content") or "") for c in cs) + self.assertEqual(content, "Let me check.The tool said hello.") + self.assertFalse([c for c in cs if c["choices"][0]["delta"].get("tool_calls")]) # nothing for the client to run + self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "stop") + self.assertEqual(len(self.engine.prompts), 2) + first, second = self.engine.prompt_text(0), self.engine.prompt_text(1) + self.assertIn('"name": "fake__echo"', first) # the MCP tools are in the prompt + self.assertNotIn("broken__", first) # the server that failed is left out + self.assertIn("\n\nhello from the tool\n", second) + self.assertIn("\nhello from the tool\n", second) + self.assertEqual(cs[-1]["usage"]["prompt_tokens"], len(self.engine.prompts[1])) + + def test_a_call_the_output_ends_inside_is_not_run(self): + """#211: the model's turn ends inside an MCP call: nothing runs (it used to run with no arguments).""" + script = call_script("fake__echo", text="hello from the tool") + self.start(script[:script.index("from the tool")], "\n\nnever") + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + cs = self.chunks(text) + mcp = [c["strata_mcp"] for c in cs if "strata_mcp" in c] + self.assertEqual([m["event"] for m in mcp], ["start"]) # the web app shows it as "Not run" at the end + self.assertEqual(len(self.engine.prompts), 1) + self.assertNotIn('"call"', Path(self.log.name).read_text()) # nothing ran + self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "stop") + + def test_non_stream(self): + self.start(call_script("fake__add", a=2, b=3), "\n\n5.") + code, text = self.post({"strata_mcp": True}, stream=False) + self.assertEqual(code, 200, text) + msg = json.loads(text)["choices"][0]["message"] + self.assertEqual(msg["content"], "Let me check.5.") + self.assertEqual(msg["strata_mcp"][-1]["text"], "5") + + def test_plain_requests_get_no_mcp_tools(self): + self.start(call_script("fake__echo", text="x"), "\n\nnever") + code, text = self.post({}) + self.assertEqual(code, 200, text) + self.assertNotIn("fake__echo", self.engine.prompt_text(0)) + cs = self.chunks(text) + self.assertFalse([c for c in cs if "strata_mcp" in c]) + self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "tool_calls") # returned to the client as always + self.assertEqual(len(self.engine.prompts), 1) + self.assertNotIn('"call"', Path(self.log.name).read_text()) # nothing ran + for req in ({"strata_mcp": "yes"}, {"strata_mcp": 1}): # only a real true opts in + self.post(req) + self.assertNotIn("fake__echo", self.engine.prompt_text(-1)) + + def test_own_tools_still_go_to_the_client(self): + own = [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object", "properties": { + "q": {"type": "string"}}}}}] + self.start(call_script("lookup", q="x"), "\n\nnever") + code, text = self.post({"strata_mcp": True, "tools": own}) + cs = self.chunks(text) + calls = [tc for c in cs for tc in c["choices"][0]["delta"].get("tool_calls") or []] + self.assertEqual(calls[0]["function"]["name"], "lookup") + self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "tool_calls") + self.assertIn('"name": "lookup"', self.engine.prompt_text(0)) + self.assertIn('"name": "fake__echo"', self.engine.prompt_text(0)) + self.assertEqual(len(self.engine.prompts), 1) + + def test_tool_error_is_a_result(self): + self.start(call_script("fake__fail"), "\n\nIt failed.") + code, text = self.post({"strata_mcp": True}) + mcp = [c["strata_mcp"] for c in self.chunks(text) if "strata_mcp" in c] + self.assertEqual((mcp[-1]["ok"], mcp[-1]["text"]), (False, "error: it failed on purpose")) + self.assertIn("\nerror: it failed on purpose\n", self.engine.prompt_text(1)) + self.assertEqual(self.chunks(text)[-1]["choices"][0]["finish_reason"], "stop") + + def test_truncated_for_the_model(self): + self.start(call_script("fake__big", n=3000), "\n\nLong.") + self.post({"strata_mcp": True}) + second = self.engine.prompt_text(1) + self.assertIn("y" * 500 + "\n\n[... truncated: the tool returned 3,000 characters", second) + self.assertNotIn("y" * 501, second) + + def test_max_rounds(self): + self.start(call_script("fake__echo", text="again")) # the model never stops calling + code, text = self.post({"strata_mcp": True}) + mcp = [c["strata_mcp"] for c in self.chunks(text) if "strata_mcp" in c] + self.assertEqual(len(self.engine.prompts), 3) # 2 rounds of tools, then the limit + self.assertEqual(sum(m["event"] == "call" for m in mcp), 2) + self.assertIn({"event": "limit", "max_rounds": 2}, mcp) + self.assertTrue(mcp[-1].get("skipped")) + self.assertEqual(self.chunks(text)[-1]["choices"][0]["finish_reason"], "stop") + + def test_stop_during_a_tool(self): + """Closing the connection while a slow tool runs stops the tool (notifications/cancelled) and the loop.""" + self.start(call_script("fake__sleep", seconds=8), "\n\nnever") + body = {"model": "m", "messages": [{"role": "user", "content": "x"}], "stream": True, "strata_mcp": True} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + r = urllib.request.urlopen(req, timeout=30) + for raw in r: + if b'"event": "call"' in raw: + break + r.close() # the web app's Stop aborts the fetch + t0 = time.monotonic() + while time.monotonic() - t0 < 6 and "cancelled" not in Path(self.log.name).read_text(): + time.sleep(0.1) + self.assertIn("cancelled", Path(self.log.name).read_text()) + self.assertLess(time.monotonic() - t0, 6) + time.sleep(0.5) + self.assertEqual(len(self.engine.prompts), 1) # no second round + self.assertFalse(self.svc.status["busy"]) + + def test_only_from_the_app_s_own_page(self): + self.start("\n\nhi") + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps( + {"model": "m", "messages": [{"role": "user", "content": "x"}], "strata_mcp": True}).encode(), + headers={"Content-Type": "text/plain"}) # a cross-site "simple" request + with self.assertRaises(urllib.error.HTTPError) as ctx: + urllib.request.urlopen(req, timeout=10) + self.assertEqual(ctx.exception.code, 415) + code, _ = self.post({"strata_mcp": True}, {"Origin": "http://evil.example"}) + self.assertEqual(code, 403) + self.assertEqual(self.engine.prompts, []) + host = self.base.split("://", 1)[1] + code, _ = self.post({"strata_mcp": True}, {"Origin": "http://" + host}) + self.assertEqual(code, 200) + + def test_get_mcp(self): + self.start("\n\nhi") + with urllib.request.urlopen(self.base + "/mcp", timeout=10) as r: + st = json.loads(r.read()) + servers = {s["name"]: s for s in st["servers"]} + self.assertEqual(servers["fake"]["status"], "ready") + self.assertEqual(servers["fake"]["transport"], "stdio") + self.assertIn("fake__echo", [t["name"] for t in servers["fake"]["tools"]]) + self.assertEqual(servers["broken"]["status"], "failed") + self.assertIn("missing configuration", servers["broken"]["error"]) + self.assertEqual(st["tools"], len(fake.TOOLS)) + self.assertEqual(st["settings"]["max_rounds"], 2) + self.svc.api_key = "k" + with self.assertRaises(urllib.error.HTTPError): + urllib.request.urlopen(self.base + "/mcp", timeout=10) + self.svc.api_key = "" + + +class NoServers(unittest.TestCase): + def test_opt_in_without_servers_is_a_plain_chat(self): + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ["\n\nhi"]), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + try: + base = f"http://127.0.0.1:{httpd.server_address[1]}" + with urllib.request.urlopen(base + "/mcp", timeout=10) as r: + self.assertEqual(json.loads(r.read()), {"servers": [], "tools": 0}) + req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps( + {"model": "m", "messages": [{"role": "user", "content": "x"}], "strata_mcp": True}).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(json.loads(r.read())["choices"][0]["message"]["content"], "hi") + finally: + httpd.shutdown() + httpd.server_close() + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_monitor.py b/serve/test_monitor.py new file mode 100644 index 0000000..0c82cb0 --- /dev/null +++ b/serve/test_monitor.py @@ -0,0 +1,261 @@ +"""Request inspection through HTTP; no native model or GPU is required.""" +import json +import threading +import time +import unittest +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, EngineDied, MockEngine, Service, serve + + +class ReloadableEngine(MockEngine): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.running, self.unloaded = True, False + + def alive(self): + return self.running + + def unload(self): + self.running, self.unloaded = False, True + + def restart(self): + self.running, self.unloaded = True, False + + +class MonitorOff(unittest.TestCase): + """#332 is opt-in: by default no prompt or answer is kept, and the monitor's endpoints do not exist.""" + + def test_off_by_default(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "Hello.", max_context=4096), tok, + ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"messages": [{"role": "user", "content": "secret"}]}).encode()) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.status, 200) + self.assertEqual(len(svc.api_requests), 0) + for path in ("/api/requests", "/api-monitor"): + with self.assertRaises(urllib.error.HTTPError) as e: + urllib.request.urlopen(base + path, timeout=10) + self.assertEqual(e.exception.code, 404, path) + e.exception.close() + finally: + httpd.shutdown() + httpd.server_close() + + +class Monitor(unittest.TestCase): + def setUp(self): + self.tok = ByteTokenizer() + self.engine = ReloadableEngine(self.tok, "Thought.\nHello .", max_context=16384) + self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.svc.api_monitor = True # opt-in ("api_monitor": true / --api-monitor) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + raw = response.read().decode() + return response.status, json.loads(raw) if "application/json" in response.headers.get("Content-Type", "") else raw + + def chat(self, api="openai", **kwargs): + # Anthropic thinks only when asked (#278): "thinking" there, reasoning_effort for OpenAI + think = {"thinking": {"type": "enabled", "budget_tokens": 1024}} if api == "anthropic" else {"reasoning_effort": "low"} + return self.request("/v1/messages" if api == "anthropic" else "/v1/chat/completions", + {"messages": [{"role": "user", "content": "Say hello."}], + "max_tokens": 256, **think, **kwargs}) + + def latest(self): + summary = self.request("/api/requests")[1]["requests"][0] + return self.request("/api/requests?id=" + summary["id"])[1] + + def test_output_and_reasoning_for_both_dialects_and_stream_modes(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + code, reply = self.chat(api, stream=stream) + self.assertEqual(code, 200) + record = self.latest() + self.assertEqual(record["state"], "completed") + self.assertEqual(record["http_status"], 200) + self.assertIn("Say hello.", record["input"]) + self.assertIn("", record["output"]) + self.assertIn("Thought.", record["reasoning"]) + self.assertGreater(record["usage"].get("completion_tokens", record["usage"].get("output_tokens", 0)), 0) + self.assertGreaterEqual(record["wallclock_s"], record["first_token_s"]) + self.assertNotIn("_clock", record) + if not stream: + self.assertEqual(json.loads(record["response"]), reply) + else: + self.assertNotIn("response", record) + + def test_error_and_engine_death_are_not_successes(self): + self.assertEqual(self.chat(max_tokens=20000)[0], 400) + self.assertEqual(self.latest()["state"], "error") + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream), mock.patch.object(self.engine, "generate", side_effect=EngineDied("stopped")): + self.chat(api, stream=stream) + record = self.latest() + self.assertEqual(record["state"], "error") + self.assertIn("stopped", record["error"]["message"]) + self.assertEqual(record["output"], "") + self.assertNotIn("timings", record) + + def test_history_is_authorized_and_does_not_capture_headers(self): + self.svc.api_key = "secret" + auth = {"Authorization": "Bearer secret"} + self.assertEqual(self.request("/api/requests")[0], 401) + self.assertEqual(self.request("/api/requests?id=missing")[0], 401) + self.assertEqual(len(self.svc.api_requests), 0) + self.assertEqual(self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}, auth)[0], 200) + summary = self.request("/api/requests", headers=auth)[1]["requests"][0] + self.assertNotIn("input", summary) + self.assertNotIn("output", summary) + self.assertEqual(self.request("/api/requests?id=" + summary["id"])[0], 401) + detail = self.request("/api/requests?id=" + summary["id"], headers=auth)[1] + self.assertNotIn("secret", json.dumps(detail)) + + def test_capture_is_bounded_and_eviction_returns_404(self): + huge = "x" * 262200 + first = self.svc.begin_request("/v1/chat/completions", {"messages": [{"content": huge}]}) + self.assertEqual(len(first["input"]), 262144) + self.assertTrue(first["input_truncated"]) + for _ in range(100): + self.svc.begin_request("/v1/chat/completions", {"messages": []}) + self.assertEqual(len(self.request("/api/requests")[1]["requests"]), 100) + self.assertEqual(self.request("/api/requests?id=" + first["id"])[0], 404) + # Exercise output capture without making a mock engine emit 262K tokens. + handler = object.__new__(self.httpd.RequestHandlerClass) + handler.record = self.svc.api_requests[-1] + chunk = {"choices": [{"delta": {"content": huge, "reasoning_content": huge}}]} + list(handler._capture((item for item in [chunk]), "openai")) + for field in ("output", "reasoning"): + self.assertEqual(len(handler.record[field]), 262144) + self.assertTrue(handler.record[field + "_truncated"]) + + def test_queue_wait_and_loading_are_attributed_separately(self): + self.engine.unload() + entered, release = threading.Event(), threading.Event() + original = self.engine.restart + def restart(): + entered.set() + self.assertTrue(release.wait(5)) + original() + with mock.patch.object(self.engine, "restart", side_effect=restart), ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(self.chat) + self.assertTrue(entered.wait(5)) + second = pool.submit(self.chat) + deadline = time.monotonic() + 5 + while len(self.svc.api_requests) < 2 and time.monotonic() < deadline: + time.sleep(0.01) + self.assertEqual(len(self.svc.api_requests), 2) + history = self.request("/api/requests")[1] + self.assertEqual({r["state"] for r in history["requests"]}, {"queued", "loading"}) + self.assertFalse(history["loaded"]) + self.assertTrue(history["auto_load"]) + time.sleep(0.03) + release.set() + self.assertEqual(first.result()[0], 200) + self.assertEqual(second.result()[0], 200) + records = list(self.svc.api_requests) + self.assertGreater(records[0]["load_s"], 0.02) + self.assertGreater(records[1]["queue_s"], 0.02) + self.assertLess(records[1]["load_s"], records[0]["load_s"]) + self.assertTrue(all(r["state"] == "completed" for r in records)) + + def test_page_and_relative_assets_are_served(self): + code, html = self.request("/api-monitor") + self.assertEqual(code, 200) + self.assertIn('src="/web/monitor.js"', html) + code, script = self.request("/web/monitor.js") + self.assertEqual(code, 200) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + self.assertEqual(self.request("/web/../server.py")[0], 404) + + +class ConversationCacheCard(unittest.TestCase): + """#596: /metrics' "conversation_cache": the parked conversations from the engine's log lines, the budget and + slots from its INFO line, and how much of the prompts the cache gave back.""" + + PARK = ("strata serve: conversation cache: parked 5000 tokens in 12.0 ms; parked=1 bytes=104857600 evictions=0 " + "snapshot_bytes=104857600 reused_kv_bytes=0\n") + RESTORE = "strata serve: conversation cache: restored 4000 tokens (exact) in 30.0 ms; parked=2 bytes=209715200\n" + + def test_the_log(self): + from serve.server import ConvCacheLog + import tempfile + with tempfile.TemporaryDirectory() as d: + log = Path(d) / "strata.log" + log.write_text("an earlier run\n" + self.PARK, encoding="utf-8") + start = log.stat().st_size # this run starts here: the earlier run's park is not counted + c = ConvCacheLog() + self.assertEqual(c.poll(str(log), start)["parked"], 0) + with open(log, "a", encoding="utf-8") as f: + f.write("strata serve: something else\n" + self.PARK + self.RESTORE + "strata serve: conversation ca") + st = c.poll(str(log), start) + self.assertEqual((st["parked"], st["bytes"], st["parks"], st["restores"]), (2, 209715200, 1, 1)) + self.assertEqual((st["last_event"], st["last_tokens"]), ("restored", 4000)) + with open(log, "a", encoding="utf-8") as f: # the cut line is read once it is whole + f.write("che: dropped 1 superseded copy of this conversation; parked=1\n") + self.assertEqual(c.poll(str(log), start)["parked"], 1) + self.assertEqual(c.poll(str(log), log.stat().st_size)["parked"], 0) # the engine started again + self.assertEqual(c.poll(None, None)["parked"], 0) + + def test_metrics(self): + tok = ByteTokenizer() + engine = MockEngine(tok, "Thought.\nHello.", max_context=4096) + engine.info = {"conversation_cache_mib": 8192, "conversation_cache_slots": 4} + svc = Service(engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + c = json.loads(r.read())["conversation_cache"] + self.assertEqual((c["enabled"], c["budget_mib"], c["slots"], c["parked"], c["requests"]), + (True, 8192, 4, 0, 0)) + req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode()) + with urllib.request.urlopen(req, timeout=10) as r: + r.read() + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + c = json.loads(r.read())["conversation_cache"] + self.assertEqual(c["requests"], 1) + self.assertGreater(c["last_prompt"], 0) + engine.info = {} + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + self.assertFalse(json.loads(r.read())["conversation_cache"]["enabled"]) # off: the reuse lines only + finally: + httpd.shutdown() + httpd.server_close() + + def test_the_card_is_on_the_page(self): + web = Path(__file__).parent / "web" + html, js = (web / "index.html").read_text(encoding="utf-8"), (web / "app.js").read_text(encoding="utf-8") + for el in ("cc-card", "cc-slots-text", "cc-mem-text", "cc-facts", "cc-note"): + self.assertIn(f'id="{el}"', html) + self.assertIn(f'"{el}"', js) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_parallel.py b/serve/test_parallel.py new file mode 100644 index 0000000..a970fff --- /dev/null +++ b/serve/test_parallel.py @@ -0,0 +1,382 @@ +"""#465: "parallel": N - several requests decode together in the engine's batch slots (--batch N). + +A fake engine (a Python script speaking the engine's GEN / BGEN / BT / BDONE / BADM / BSTOP lines) runs behind the +real StrataEngine and Service, so the server's side is tested without a GPU: requests up to N run at once, more +wait for a slot, /metrics shows the slots, each request's history row is its own, and a conversation's next turn +goes back to the slot that holds it.""" +import json +import sys +import tempfile +import threading +import time +import unittest +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, Service, StrataEngine, engine_args, parallel_args, serve + +# The fake engine: one token every STEP seconds per active slot (a "window" serves every active slot at once); +# GEN (solo) streams T lines; BGEN reads the prompt (one T line, DONE), answers BADM and continues in the slot. +# Every reply is the bytes of "ok, done." then <|im_end|> (ByteTokenizer: 257). +FAKE_BATCH = r'''import queue, sys, threading, time +args = sys.argv[1:] +slots = int(args[args.index("--batch") + 1]) if "--batch" in args else 0 +fit = int(args[args.index("--fit") + 1]) if "--fit" in args else slots +STEP = 0.02 +CH = 32 +lines, stop = queue.Queue(), threading.Event() +def reader(): + for l in sys.stdin: + l = l.strip() + if l == "STOP": + stop.set() + else: + lines.put(l) + lines.put(None) +threading.Thread(target=reader, daemon=True).start() +print("INFO engine=0.1.39" + (f" batch_slots={fit}" if fit >= 2 else "") + + (" slot_cache=1" if "--slotcache" in args else ""), flush=True) +print("READY 4096 stop", flush=True) +LONG = list(b"LONGREPLY") +def reply(ids): # the rest of the reply after what the prompt already ends with (a request continued) + ids = [int(x) for x in ids] + long_one = any(ids[i:i + len(LONG)] == LONG for i in range(len(ids))) + R = list(b"ok, " + b"la " * 15 + b"done." if long_one else b"ok, done.") + [257] + k = max(k for k in range(len(R)) if k == 0 or ids[-k:] == R[:k]) + return R[k:] +active = {} # slot -> [tokens left, max_new, produced] +stopped = set() # BSTOPped slots: they end "cancel" +def window(): # one batch window: every active slot one token + for b in sorted(active): + left, max_new, produced = active[b] + t = left.pop(0) if left else 257 + produced += 1 + print(f"BT {b} {t}", flush=True) + if t == 257 or produced >= max_new: + fin = 'stop' if t == 257 else 'cancel' if b in stopped else 'length' + stopped.discard(b) + print(f"BDONE {b} {produced} {fin} 1.0", flush=True) + del active[b] + else: + active[b] = [left, max_new, produced] +log = open(args[args.index("--log") + 1], "a") if "--log" in args else None +while True: + try: + line = lines.get(timeout=STEP if active else None) + except queue.Empty: + line = "" + if line is None or line == "QUIT": + break + if line.startswith("BYIELD "): + continue # too late: the read it was for has ended + if line.startswith("BSTOP "): + b = int(line.split()[1]) + if b in active: + active[b][1] = 0 + stopped.add(b) + continue + if line.startswith(("GEN ", "BGEN ")): + f = line.split() + slot = int(f[1]) if f[0] == "BGEN" else None + max_new = int(f[2] if f[0] == "BGEN" else f[1]) + ids = f[-1].split(",") + if log: + log.write(f"{f[0]} {slot} {len(ids)} {max(len(active), 0)}\n"); log.flush() + toks = reply(ids) + stop.clear() + # the prompt read: CH tokens a chunk, a PP line each; a BYIELD gives way at a chunk boundary + given = None + for q in range(CH, len(ids) - 1, CH): + time.sleep(STEP / 2) + print(f"PP {q} {len(ids)} 1 1", flush=True) + held = [] + while True: + try: + l2 = lines.get_nowait() + except queue.Empty: + break + if l2 and l2.startswith("BYIELD "): + ys = int(l2.split()[1]) + if len(ids) - 1 - q > CH and (slot is None or ys == slot) and given is None: + given = (ys, q) + else: + held.append(l2) + for l2 in held: + lines.put(l2) + if given: + break + if active and (q // CH) % 4 == 0: # the slots decode between the prompt's chunks (as the engine) + window() + if given: + if log: + log.write(f"YIELD {given[0]} {given[1]}\n"); log.flush() + print(f"YIELDED {given[0]} {given[1]}", flush=True) + print(f"DONE 0 {len(ids)} 5.0 0.0 cancel 0 0 0", flush=True) + if slot is not None: + print(f"BADM {slot} 0", flush=True) + continue + n = 1 if slot is not None else max_new + out = 0 + for t in toks[:n]: + if stop.is_set(): + break + print(f"T {t}", flush=True) + out += 1 + time.sleep(STEP) + fin = "stop" if out and toks[out - 1] == 257 else ("cancel" if stop.is_set() else "length") + print(f"DONE {out} {len(ids)} 5.0 {out * STEP * 1000:.1f} {fin} 0 0 0", flush=True) + if slot is not None: + cont = fin == "length" and max_new > 1 + if cont: + active[slot] = [toks[1:], max_new, 1] + print(f"BADM {slot} {1 if cont else 0}", flush=True) + continue + if line: + print("ERR unknown " + line[:20], flush=True) + continue + window() +''' + + +class ParallelArgs(unittest.TestCase): + def test_parallel_config_key(self): + self.assertEqual(parallel_args({"parallel": 4}, []), ["--batch", "4"]) + self.assertEqual(parallel_args({"parallel": 1}, []), []) + self.assertEqual(parallel_args({}, []), []) + self.assertEqual(parallel_args({"parallel": 2}, ["--batch", "3"]), []) # the args' own value wins + self.assertEqual(parallel_args({"parallel": "4"}, []), []) # said and ignored + self.assertEqual(parallel_args({"parallel": True}, []), []) + self.assertEqual(parallel_args({"parallel": 12}, []), ["--batch", "12"]) # the engine warns and caps + args = engine_args({"args": ["--pack", "p"], "parallel": 2}) + self.assertEqual(args[-2:], ["--batch", "2"]) + + +class PickSlot(unittest.TestCase): + def engine(self, n): + e = StrataEngine("missing-executable", [], lazy=True) + e.batch = n + e.slot_order = list(range(n)) + e.slot_busy = [False] * n + e.slot_held = [[] for _ in range(n)] + e.slot_used = [0.0] * n + e.slot_live = [None] * n + return e + + def test_the_slot_that_holds_the_conversation(self): + e = self.engine(3) + e.slot_held = [[1, 2, 3], [], [1, 2, 3, 4, 5]] + e.slot_used = [5.0, 0.0, 9.0] + self.assertEqual(e.pick_slot([1, 2, 3, 4, 5, 6]), 2) # the longest held start + self.assertEqual(e.pick_slot([1, 2, 3, 9]), 0) + self.assertEqual(e.pick_slot([7, 8]), 1) # no match: the empty slot first + e.slot_busy[1] = True + self.assertEqual(e.pick_slot([7, 8]), 0) # then the one used longest ago + e.slot_busy = [True] * 3 + self.assertIsNone(e.pick_slot([7, 8])) + e.slot_busy = [False] * 3 + self.assertEqual(e.pick_slot([1, 2, 3]), 1) # a held prompt is never the WHOLE prompt + + def test_slots_view(self): + e = self.engine(2) + e.slot_held[1] = [1, 2] + e.slot_live[0] = {"slot": 0, "state": "decoding", "prompt_tokens": 9, "generated": 4, + "started": time.time() - 2, "first_token": time.time() - 1} + v = e.slots_view() + self.assertEqual(v[0]["state"], "decoding") + self.assertEqual(v[0]["generated"], 4) + self.assertEqual(v[1], {"slot": 1, "state": "idle", "held_tokens": 2}) + + +class ParallelService(unittest.TestCase): + """The real StrataEngine and Service over HTTP, the fake engine behind them.""" + + def start(self, slots, fit=None, slot_cache=False): + import serve.server as server + self.tmp = tempfile.TemporaryDirectory() + script = Path(self.tmp.name) / "fake_strata.py" + script.write_text(FAKE_BATCH, encoding="utf-8") + self.log = Path(self.tmp.name) / "requests.log" + real = server.subprocess.Popen + extra = ["--batch", str(slots)] + (["--fit", str(fit)] if fit is not None else []) + ["--log", str(self.log)] + extra += ["--slotcache"] if slot_cache else [] + with mock.patch.object(server.subprocess, "Popen", + lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)): + self.engine = StrataEngine("strata", extra) + tok = ByteTokenizer() + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + if getattr(self, "httpd", None): + self.httpd.shutdown() + self.httpd.server_close() + if getattr(self, "engine", None): + self.engine.unload() + if getattr(self, "tmp", None): + self.tmp.cleanup() + + def chat(self, text, max_tokens=64): + body = {"messages": [{"role": "user", "content": text}], "max_tokens": max_tokens, "reasoning_effort": "none"} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=60) as r: + return json.loads(r.read().decode()) + + def get(self, path): + with urllib.request.urlopen(self.base + path, timeout=10) as r: + return json.loads(r.read().decode()) + + def test_engine_reports_fewer_slots(self): + self.start(4, fit=2) + self.assertEqual(self.engine.batch, 2) + self.assertEqual(self.get("/v1/status")["concurrency"]["serving"], 2) + + def test_engine_turns_batching_off(self): + self.start(4, fit=0) + self.assertEqual(self.engine.batch, 0) + self.assertEqual(self.chat("hi")["choices"][0]["message"]["content"], "ok, done.") + + def test_concurrent_requests_share_the_slots(self): + self.start(2) + # the first one decodes long enough for the others to arrive while it runs (also on a busy PC) + texts = ["first question LONGREPLY", "second question, longer", "a third one waits for a slot"] + reply = {t: "ok, " + "la " * 15 + "done." if "LONGREPLY" in t else "ok, done." for t in texts} + out, errors, seen = {}, [], [] + + def go(t): + try: + out[t] = self.chat(t) + except Exception as e: # noqa: BLE001 - reported below + errors.append(e) + + threads = [threading.Thread(target=go, args=(t,)) for t in texts] + for th in threads: + th.start() + time.sleep(0.05) + deadline = time.time() + 30 + while any(th.is_alive() for th in threads) and time.time() < deadline: + m = self.get("/metrics")["live"] + seen.append(m) + time.sleep(0.01) + for th in threads: + th.join(30) + self.assertEqual(errors, []) + for t in texts: + self.assertEqual(out[t]["choices"][0]["message"]["content"], reply[t]) + # the slots were reported, and a request was admitted while another decoded in a slot (the fake logs how many + # slots were active at each admission) + self.assertTrue(any(m.get("parallel") == 2 and len(m.get("slots", [])) == 2 for m in seen)) + admitted = [int(x.split()[3]) for x in self.log.read_text().splitlines() if x.startswith("BGEN")] + self.assertIn(1, admitted) + # every request recorded its own row; nothing is left running + with self.svc.status_lock: + self.assertEqual(len(self.svc.history), 3) + self.assertEqual(self.svc.live_reqs, {}) + self.assertFalse(self.svc.status["busy"]) + self.assertEqual(sorted(r["output_tokens"] for r in self.svc.history), + sorted(len(reply[t]) + 1 for t in texts)) + # never more than two in the slots at once (the fake logs how many were active at each admission) + active = [int(x.split()[3]) for x in self.log.read_text().splitlines() if x.startswith("BGEN")] + self.assertTrue(all(a <= 1 for a in active), active) + + def race(self, first, second, delay=0.15, max_tokens=64): + """`first` sent, `second` after `delay` seconds; -> {text: (reply, seconds it took)}""" + res = {} + + def go(t): + t0 = time.time() + r = self.chat(t, max_tokens=max_tokens) + res[t] = (r["choices"][0]["message"]["content"], time.time() - t0) + a = threading.Thread(target=go, args=(first,)) + a.start() + time.sleep(delay) + go(second) + a.join(30) + return res + + def test_a_long_prompt_gives_way_to_a_short_one(self): + """#656: a long solo prompt read gives way at a chunk boundary; the short request is answered first, then the + long one goes on (in the slot its part waited in) and is answered too.""" + self.start(2) + long_q, short_q = "long " * 600, "short" + res = self.race(long_q, short_q) + self.assertEqual(res[long_q][0], "ok, done.") + self.assertEqual(res[short_q][0], "ok, done.") + # the long read takes ~1 s (3,000 tokens, 32 a chunk, 10 ms a chunk): the short one did not wait for it + self.assertLess(res[short_q][1], res[long_q][1] - 0.5, res) + log = self.log.read_text().splitlines() + self.assertTrue(any(x.startswith("YIELD ") for x in log), log) + with self.svc.status_lock: + self.assertEqual(len(self.svc.history), 2) + self.assertFalse(any(self.engine.slot_busy)) + + def test_an_admission_gives_way_too(self): + """The same while another request decodes in a slot: the long one is being admitted, a short one waits.""" + self.start(3) + bg = threading.Thread(target=lambda: self.chat("background", max_tokens=60)) + bg.start() + time.sleep(0.05) + long_q, short_q = "long " * 600, "short" + res = self.race(long_q, short_q) + bg.join(30) + self.assertEqual(res[long_q][0], "ok, done.") + self.assertLess(res[short_q][1], res[long_q][1] - 0.5, res) + log = self.log.read_text().splitlines() + self.assertTrue(any(x.startswith("YIELD ") for x in log), log) + self.assertFalse(any(self.engine.slot_busy)) + + def test_no_way_given_to_a_long_one(self): + """Two prompts of about the same length: no BYIELD (it only goes to a much shorter one).""" + self.start(2) + res = self.race("long " * 600, "lung " * 600) + self.assertEqual(sorted(r[0] for r in res.values()), ["ok, done."] * 2) + self.assertFalse(any(x.startswith("YIELD ") for x in self.log.read_text().splitlines())) + + def test_left_alone_it_goes_back_to_the_solo_path(self): + """A request decoding in a slot whose neighbour finished goes back to the solo path (MTP drafts), continued + from its slot - only with an engine that keeps the slots' conversations (INFO slot_cache=1).""" + self.start(2, slot_cache=True) + res = {} + long = threading.Thread(target=lambda: res.setdefault("long", self.chat("LONGREPLY please", max_tokens=200))) + long.start() + time.sleep(0.05) + short = self.chat("short", max_tokens=200) + long.join(30) + self.assertEqual(short["choices"][0]["message"]["content"], "ok, done.") + self.assertEqual(res["long"]["choices"][0]["message"]["content"], "ok, " + "la " * 15 + "done.") + kinds = [x.split()[0] for x in self.log.read_text().splitlines()] + # solo, then both in slots, then the long one alone again: a GEN after the BGENs + self.assertIn("BGEN", kinds) + self.assertEqual(kinds[-1], "GEN", kinds) + self.assertFalse(any(self.engine.slot_busy)) + with self.svc.status_lock: + self.assertEqual(len(self.svc.history), 2) + + def test_next_turn_goes_back_to_its_slot(self): + self.start(2) + a = "conversation A, first turn" + r1 = {} + th = threading.Thread(target=lambda: r1.setdefault("x", self.chat("blocker LONGREPLY", max_tokens=200))) + th.start() + time.sleep(0.05) + first = self.chat(a) + th.join(30) + deadline = time.time() + 10 # a slot left at its stop token is freed at its BDONE + while not [h for h in self.engine.slot_held if h] and time.time() < deadline: + time.sleep(0.02) + held = [h for h in self.engine.slot_held if h] + self.assertTrue(held, "a finished slot request keeps what its slot holds") + # the held tokens are the prompt and every token fed: all of the reply but its last token + reply = list(b"ok, done.") + [257] + mine = [h for h in held if h[-len(reply) + 1:] == reply[:-1] and bytes(x for x in h if x < 256).find(b"conversation A") >= 0] + self.assertEqual(len(mine), 1, held) + slot = self.engine.slot_held.index(mine[0]) + self.assertEqual(self.engine.pick_slot(mine[0] + [10, 11]), slot) + self.assertEqual(first["choices"][0]["message"]["content"], "ok, done.") + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_responses.py b/serve/test_responses.py new file mode 100644 index 0000000..2bae986 --- /dev/null +++ b/serve/test_responses.py @@ -0,0 +1,361 @@ +"""serve/test_responses.py - #451: the Responses API (POST /v1/responses) against the mock engine (no GPU, no pack). + + python -m unittest serve.test_responses -v +""" +from __future__ import annotations + +import base64 +import contextlib +import http.client +import io +import json +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.frontend import ChatTemplate # noqa: E402 +from serve.responses import (ENCRYPTED_PREFIX, ResponsesError, input_messages, request_tools, # noqa: E402 + template_kwargs, text_format) +from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +TEMPLATE = ChatTemplate(ROOT / "serve/chat_template.jinja") + +CALL = ("Let me look.\n\n\nChecking.\n\n\n\n\ncat a.txt\n" + "\n\n") +ANSWER = "Read it.\n\n\nThe file says before." +TOOLS = [{"type": "function", "name": "exec_command", "description": "Runs a command.", "strict": False, + "parameters": {"type": "object", "properties": {"cmd": {"type": "string"}}, "required": ["cmd"]}}] + + +# ------------------------------------------------------------------------------------------------ parsing +class Parsing(unittest.TestCase): + def test_a_string_input_is_one_user_message(self): + self.assertEqual(input_messages({"input": "hi", "instructions": "Be brief."}), + [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}]) + + def test_leading_developer_messages_join_the_system_message_later_ones_become_user(self): + msgs = input_messages({"instructions": "I", "input": [ + {"type": "message", "role": "developer", "content": [{"type": "input_text", "text": "D1"}, + {"type": "input_text", "text": "D2"}]}, + {"role": "user", "content": "u"}, + {"type": "message", "role": "developer", "content": "late"}]}) + self.assertEqual(msgs, [{"role": "system", "content": "I\n\nD1D2"}, {"role": "user", "content": "u"}, + {"role": "user", "content": "late"}]) + + def test_codex_history_becomes_one_assistant_turn_per_answer(self): + items = [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "edit it"}]}, + {"type": "reasoning", "id": "rs_1", "summary": [], + "content": [{"type": "reasoning_text", "text": "look first"}]}, + {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "Looking."}]}, + {"type": "function_call", "id": "fc_1", "call_id": "c1", "name": "exec_command", + "arguments": "{\"cmd\":\"cat a\"}"}, + {"type": "function_call", "id": "fc_2", "call_id": "c2", "name": "spawn_agent", + "namespace": "multi_agent_v1", "arguments": "{}"}, + # results in the order they finished, not the order of the calls + {"type": "function_call_output", "call_id": "c2", "output": "agent"}, + {"type": "function_call_output", "call_id": "c1", + "output": [{"type": "input_text", "text": "before"}]}, + {"type": "reasoning", "id": "rs_2", "summary": [{"type": "summary_text", "text": "s"}], + "content": [{"type": "reasoning_text", "text": "now write"}]}, + {"type": "function_call", "call_id": "c3", "name": "exec_command", "arguments": "{\"cmd\":\"w\"}"}, + {"type": "function_call_output", "call_id": "c3", "output": "ok"}] + self.assertEqual(input_messages({"input": items}), [ + {"role": "user", "content": "edit it"}, + {"role": "assistant", "content": "Looking.", "reasoning_content": "look first", "tool_calls": [ + {"function": {"name": "exec_command", "arguments": {"cmd": "cat a"}}}, + {"function": {"name": "multi_agent_v1.spawn_agent", "arguments": {}}}]}, + {"role": "tool", "content": "before"}, {"role": "tool", "content": "agent"}, + {"role": "assistant", "content": "", "reasoning_content": "now write", "tool_calls": [ + {"function": {"name": "exec_command", "arguments": {"cmd": "w"}}}]}, + {"role": "tool", "content": "ok"}]) + + def test_reasoning_comes_back_from_our_encrypted_content_and_foreign_tokens_are_ignored(self): + enc = ENCRYPTED_PREFIX + base64.b64encode(json.dumps({"text": "hidden"}).encode()).decode() + for item, want in (({"encrypted_content": enc, "summary": []}, "hidden"), + ({"encrypted_content": "gAAAAAB-someone-elses", "summary": []}, None)): + msgs = input_messages({"input": [{"role": "user", "content": "q"}, {"type": "reasoning", **item}, + {"role": "assistant", "content": "a"}]}) + self.assertEqual(msgs[1].get("reasoning_content"), want) + with self.assertRaises(ResponsesError) as e: + input_messages({"input": [{"type": "reasoning", "encrypted_content": ENCRYPTED_PREFIX + "!!"}]}) + self.assertEqual(e.exception.param, "input[0].encrypted_content") + + def test_bad_arguments_from_a_cut_off_call_do_not_refuse_the_conversation(self): + msgs = input_messages({"input": [{"role": "user", "content": "q"}, + {"type": "function_call", "call_id": "c", "name": "f", "arguments": "{\"a"}, + {"type": "function_call_output", "call_id": "c", "output": "x"}]}) + self.assertEqual(msgs[1]["tool_calls"][0]["function"]["arguments"], {"arguments": "{\"a"}) + + def test_unsupported_items_are_named(self): + for items, param in (([{"type": "item_reference", "id": "msg_1"}], "input[0]"), + ([{"type": "web_search_call"}], "input[0].type"), + ([{"role": "user", "content": [{"type": "input_file", "file_id": "f"}]}], + "input[0].content[0].type"), + ([{"role": "robot", "content": "x"}], "input[0].role")): + with self.assertRaises(ResponsesError) as e: + input_messages({"input": items}) + self.assertEqual(e.exception.param, param) + with self.assertRaises(ResponsesError): + input_messages({}) + + def test_tools_namespaces_custom_and_hosted(self): + tools, names, skipped = request_tools({"tools": [ + *TOOLS, {"type": "namespace", "name": "mcp_fs", "description": "Files.", + "tools": [{"type": "function", "name": "read", "parameters": {"type": "object"}}]}, + {"type": "custom", "name": "apply_patch", "description": "Patch.", + "format": {"type": "grammar", "syntax": "lark", "definition": "start: \"x\""}}, + {"type": "web_search"}]}) + self.assertEqual([t["name"] for t in tools], ["exec_command", "mcp_fs.read", "apply_patch"]) + self.assertEqual(tools[1]["description"], "Files.") + self.assertIn("start: \"x\"", tools[2]["description"]) + self.assertEqual(names["mcp_fs.read"], ("mcp_fs", "read", "function")) + self.assertEqual(names["apply_patch"], (None, "apply_patch", "custom")) + self.assertEqual(skipped, ["web_search"]) + self.assertIsNone(request_tools({"tools": TOOLS, "tool_choice": "none"})[0]) + + def test_effort_and_text_format(self): + self.assertEqual(template_kwargs({"reasoning": {"effort": "minimal"}}, {}), {"enable_thinking": False}) + self.assertEqual(template_kwargs({"reasoning": {"effort": "high"}}, {}), {"reasoning_effort": "xhigh"}) + self.assertEqual(template_kwargs({"reasoning": {"summary": "auto"}}, {}), {}) # Codex: the default + self.assertEqual(template_kwargs({}, {"reasoning_effort": "low"}), {"reasoning_effort": "low"}) + with self.assertRaises(ResponsesError): + template_kwargs({"reasoning": {"effort": "huge"}}, {}) + self.assertEqual(text_format({"text": {"format": {"type": "json_schema", "name": "n", "schema": {}}}}), + {"type": "json_schema", "json_schema": {"name": "n", "schema": {}}}) + self.assertIsNone(text_format({"text": {"format": {"type": "text"}}})) + + +# ------------------------------------------------------------------------------------------------ over HTTP +class Server(unittest.TestCase): + script = ANSWER + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = MockEngine(self.tok, self.script, max_context=16384) + self.svc = Service(self.engine, self.tok, TEMPLATE) + self.httpd = serve(self.svc, port=0) + self.port = self.httpd.server_address[1] + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def post(self, body, path="/v1/responses", headers=None): + """(status, parsed body: a dict, or the list of SSE events of a stream).""" + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30) + try: + with contextlib.redirect_stdout(io.StringIO()): + c.request("POST", path, body=json.dumps(body).encode(), + headers={"Content-Type": "application/json", **(headers or {})}) + r = c.getresponse() + raw = r.read().decode() + if r.getheader("Content-Type") == "text/event-stream": + events = [] + for block in raw.split("\n\n"): + lines = block.strip().splitlines() + if not lines or lines[0].startswith(":"): + continue + name = lines[0][len("event: "):] + data = json.loads(lines[1][len("data: "):]) + self.assertEqual(name, data["type"]) + events.append(data) + return r.status, events + return r.status, json.loads(raw) + finally: + c.close() + + + +class OverHttp(Server): + def test_non_streaming_text_with_reasoning(self): + code, r = self.post({"model": "m", "input": "hi", "store": False}) + self.assertEqual(code, 200) + self.assertEqual((r["object"], r["status"], r["error"]), ("response", "completed", None)) + rs, msg = r["output"] + self.assertEqual(rs["type"], "reasoning") + self.assertEqual(rs["content"], [{"type": "reasoning_text", "text": "Read it.\n"}]) + self.assertEqual(rs["summary"], []) + self.assertNotIn("encrypted_content", rs) + self.assertEqual(msg["type"], "message") + self.assertEqual(msg["content"][0]["text"], "The file says before.") + u = r["usage"] + self.assertEqual(u["output_tokens"], len(self.tok.encode(ANSWER)) + 1) # + the end-of-turn token + self.assertEqual(u["output_tokens_details"]["reasoning_tokens"], len("Read it.\n")) + self.assertEqual(u["total_tokens"], u["input_tokens"] + u["output_tokens"]) + self.assertEqual(r["store"], False) + + def test_stream_event_order(self): + code, events = self.post({"model": "m", "input": "hi", "stream": True, + "include": ["reasoning.encrypted_content"]}) + self.assertEqual(code, 200) + types = [e["type"] for e in events] + deltas_r = types.count("response.reasoning_text.delta") + deltas_t = types.count("response.output_text.delta") + self.assertGreater(deltas_r, 0) + self.assertGreater(deltas_t, 0) + self.assertEqual(types, ["response.created", "response.in_progress", + "response.output_item.added", *["response.reasoning_text.delta"] * deltas_r, + "response.reasoning_text.done", "response.output_item.done", + "response.output_item.added", "response.content_part.added", + *["response.output_text.delta"] * deltas_t, + "response.output_text.done", "response.content_part.done", + "response.output_item.done", "response.completed"]) + self.assertEqual([e["sequence_number"] for e in events], list(range(len(events)))) + final = events[-1]["response"] + self.assertEqual(final["status"], "completed") + rs, msg = final["output"] + self.assertEqual([e["item"]["id"] for e in events if e["type"] == "response.output_item.done"], + [rs["id"], msg["id"]]) + self.assertEqual("".join(e["delta"] for e in events if e["type"] == "response.output_text.delta"), + msg["content"][0]["text"]) + self.assertTrue(rs["encrypted_content"].startswith(ENCRYPTED_PREFIX)) + # the encrypted_content alone brings the thinking back into the prompt + replay = input_messages({"input": [{"role": "user", "content": "hi"}, + {"type": "reasoning", "summary": [], "encrypted_content": + rs["encrypted_content"]}, msg]}) + self.assertEqual(replay[1]["reasoning_content"], "Read it.\n") + + def test_max_output_tokens_ends_incomplete(self): + code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": 5}) + self.assertEqual(code, 200) + self.assertEqual(r["status"], "incomplete") + self.assertEqual(r["incomplete_details"], {"reason": "max_output_tokens"}) + self.assertEqual(r["output"][0]["status"], "incomplete") + code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": 5, "stream": True}) + self.assertEqual(events[-1]["type"], "response.incomplete") + + def test_effort_none_does_not_think(self): + self.engine.scripts = [self.tok.encode("Hello.<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + code, r = self.post({"model": "m", "input": "hi", "reasoning": {"effort": "none"}}) + self.assertEqual([o["type"] for o in r["output"]], ["message"]) + self.assertIn("\n\n", self.tok.decode(self.engine.last_prompt)) + + def test_errors_use_the_responses_format(self): + for body, param in (({"model": "m"}, "input"), ({"model": "m", "input": "x", "previous_response_id": "r"}, + "previous_response_id"), + ({"model": "m", "input": "x", "reasoning": {"effort": "huge"}}, "reasoning.effort")): + code, r = self.post(body) + self.assertEqual(code, 400) + self.assertEqual(set(r["error"]), {"message", "type", "param", "code"}) + self.assertEqual(r["error"]["param"], param) + code, r = self.post({}, path="/v1/responses/resp_123/cancel") + self.assertEqual(code, 404) + self.assertEqual(r["error"]["code"], "not_found") + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30) + c.request("POST", "/v1/responses", body=b"{not json", headers={"Content-Type": "application/json"}) + r = c.getresponse() + err = json.loads(r.read())["error"] + c.close() + self.assertEqual((r.status, err["type"], err["param"]), (400, "invalid_request_error", None)) + + def test_too_long_for_the_context(self): + code, r = self.post({"model": "m", "input": "x" * 20000}) + self.assertEqual(code, 400) + self.assertEqual(r["error"]["code"], "context_length_exceeded") + + def test_api_key_and_foreign_pages(self): + self.svc.api_key = "s3cret" + self.assertEqual(self.post({"model": "m", "input": "hi"})[0], 401) + self.assertEqual(self.post({"model": "m", "input": "hi"}, headers={"Authorization": "Bearer s3cret"})[0], 200) + self.svc.api_key = None + code, r = self.post({"model": "m", "input": "hi"}, headers={"Origin": "https://evil.example.com"}) + self.assertEqual(code, 403) + + def test_json_schema_text_format(self): + self.engine.scripts = [self.tok.encode("\n\n{\"n\": 3}<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + fmt = {"type": "json_schema", "name": "num", "strict": True, + "schema": {"type": "object", "properties": {"n": {"type": "integer"}}, "required": ["n"]}} + code, r = self.post({"model": "m", "input": "a number", "text": {"format": fmt}}) + self.assertEqual(code, 200, r) + self.assertEqual(r["output"][-1]["content"][0]["text"], "{\"n\":3}") + code, events = self.post({"model": "m", "input": "a number", "text": {"format": fmt}, "stream": True}) + self.assertEqual([e["delta"] for e in events if e["type"] == "response.output_text.delta"], ["{\"n\":3}"]) + self.assertEqual(events[-1]["type"], "response.completed") + # an answer that fails the schema + bad = {**fmt, "schema": {**fmt["schema"], "properties": {"n": {"type": "string"}}}} + code, r = self.post({"model": "m", "input": "a number", "text": {"format": bad}}) + self.assertEqual((code, r["error"]["code"]), (502, "structured_output_failed")) + code, events = self.post({"model": "m", "input": "a number", "text": {"format": bad}, "stream": True}) + self.assertEqual(events[-1]["type"], "response.failed") + self.assertEqual(events[-1]["response"]["error"]["code"], "structured_output_failed") + + def test_monitor_and_status(self): + self.svc.api_monitor = True + self.post({"model": "m", "input": "hi", "stream": True}) + rec = self.svc.request_records()[0] + self.assertEqual(rec["path"], "/v1/responses") + full = self.svc.request_records(rec["id"]) + self.assertEqual(full["output"], "The file says before.") + self.assertEqual(full["reasoning"], "Read it.\n") + self.assertIn("/v1/responses", self.svc.v1_status()["dialects"]) + + +class ToolRoundTrip(Server): + script = [CALL, ANSWER] + + def test_function_call_round_trip(self): + user = {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "what is in a.txt?"}]} + code, events = self.post({"model": "m", "instructions": "You are a coding agent.", "input": [user], + "tools": TOOLS, "store": False, "stream": True, + "include": ["reasoning.encrypted_content"], "reasoning": {"summary": "auto"}, + "parallel_tool_calls": True, "tool_choice": "auto"}) + self.assertEqual(code, 200) + first_prompt = self.tok.decode(self.engine.last_prompt) + types = [e["type"] for e in events] + n_args = types.count("response.function_call_arguments.delta") + self.assertGreater(n_args, 0) + call_part = types[types.index("response.output_text.done") + 2:] + self.assertEqual(call_part, ["response.output_item.done", "response.output_item.added", + *["response.function_call_arguments.delta"] * n_args, + "response.function_call_arguments.done", "response.output_item.done", + "response.completed"]) + output = events[-1]["response"]["output"] + self.assertEqual([o["type"] for o in output], ["reasoning", "message", "function_call"]) + fc = output[2] + self.assertEqual((fc["name"], json.loads(fc["arguments"]), fc["status"]), + ("exec_command", {"cmd": "cat a.txt"}, "completed")) + self.assertTrue(fc["call_id"]) + added = next(e for e in events if e["type"] == "response.output_item.added" + and e["item"]["type"] == "function_call") + self.assertEqual((added["item"]["call_id"], added["item"]["arguments"]), (fc["call_id"], "")) + # Codex sends everything back, plus the result: the prompt continues exactly where the model stopped + code, r = self.post({"model": "m", "instructions": "You are a coding agent.", "tools": TOOLS, "store": False, + "input": [user, *output, {"type": "function_call_output", "call_id": fc["call_id"], + "output": "before"}]}) + self.assertEqual(code, 200, r) + second_prompt = self.tok.decode(self.engine.last_prompt) + self.assertTrue(second_prompt.startswith(first_prompt + CALL + "<|im_end|>"), second_prompt[-600:]) + self.assertIn("\nbefore\n", second_prompt) + self.assertEqual(r["output"][-1]["content"][0]["text"], "The file says before.") + + def test_namespace_and_custom_calls_come_back_under_their_own_names(self): + self.engine.scripts = [self.tok.encode( + "\n\n\n\n\nhi\n\n" + "\n\n\n\n\n*** Begin Patch\n" + "\n\n<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + tools = [{"type": "namespace", "name": "multi_agent_v1", "description": "Agents.", "tools": [ + {"type": "function", "name": "spawn_agent", "strict": False, + "parameters": {"type": "object", "properties": {"message": {"type": "string"}}}}]}, + {"type": "custom", "name": "apply_patch", "description": "Edit files."}] + code, r = self.post({"model": "m", "input": "go", "tools": tools}) + self.assertEqual(code, 200, r) + ns, custom = r["output"] + self.assertEqual((ns["type"], ns["namespace"], ns["name"], json.loads(ns["arguments"])), + ("function_call", "multi_agent_v1", "spawn_agent", {"message": "hi"})) + self.assertEqual((custom["type"], custom["name"], custom["input"]), + ("custom_tool_call", "apply_patch", "*** Begin Patch")) + msgs = input_messages({"input": [{"role": "user", "content": "go"}, ns, custom, + {"type": "function_call_output", "call_id": ns["call_id"], "output": "1"}, + {"type": "custom_tool_call_output", "call_id": custom["call_id"], + "output": "2"}]}) + self.assertEqual([c["function"]["name"] for c in msgs[1]["tool_calls"]], + ["multi_agent_v1.spawn_agent", "apply_patch"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_runconfig.py b/serve/test_runconfig.py new file mode 100644 index 0000000..bb17119 --- /dev/null +++ b/serve/test_runconfig.py @@ -0,0 +1,165 @@ +"""serve/test_runconfig.py - #564: the web page's Settings view of the run config (GET / POST /config), against the +mock engine: only the listed keys change, every other key of the file stays, a bad value changes nothing, and only +Strata's own page may write it (JSON, no foreign Origin, the API key when one is set). + + python -m unittest serve.test_runconfig +""" +from __future__ import annotations + +import contextlib +import io +import json +import tempfile +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +from serve import runconfig +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, MockEngine, Service, serve + +ROOT = Path(__file__).resolve().parents[1] +CFG = {"exe": "engine/strata.exe", "args": ["--pack", "data/packs/q2_0", "--kv", "int8", "--spec-min-p", "0.5"], + "model_name": "qwen3.8-flash-next-q2_0", "port": 8080, "host": "0.0.0.0", "api_key": "", + "sampling": {"temperature": 0.7, "presence_penalty": 1.5}, + "mcp_servers": {"files": {"command": "npx", "args": ["-y", "server-filesystem", "."]}}, + "cors_origins": ["http://localhost:3000"]} + + +class Apply(unittest.TestCase): + def test_only_the_named_keys_change(self): + new, changed = runconfig.apply(CFG, {"sampling.top_p": 0.95, "reasoning_budget_tokens": 4096, + "vram_reserve_mib": 2048, "aliases": "qwen, local", "lazy_load": True}) + self.assertEqual(changed, ["sampling.top_p", "reasoning_budget_tokens", "vram_reserve_mib", "aliases", + "lazy_load"]) + self.assertEqual(new["sampling"], {"temperature": 0.7, "presence_penalty": 1.5, "top_p": 0.95}) + self.assertEqual(new["args"][-2:], ["--vram-reserve-mib", "2048"]) + self.assertEqual(new["aliases"], ["qwen", "local"]) + for k in ("exe", "model_name", "port", "host", "api_key", "mcp_servers", "cors_origins"): + self.assertEqual(new[k], CFG[k], k) + self.assertEqual(CFG["sampling"], {"temperature": 0.7, "presence_penalty": 1.5}) # the input is left alone + + def test_null_is_the_default_again(self): + cfg, _ = runconfig.apply(CFG, {"vram_reserve_mib": 2048, "fit_max_tokens": True}) + new, changed = runconfig.apply(cfg, {"vram_reserve_mib": None, "fit_max_tokens": None, + "sampling.temperature": None, "idle_unload_s": None}) + self.assertEqual(changed, ["vram_reserve_mib", "fit_max_tokens", "sampling.temperature"]) + self.assertEqual(new["args"], CFG["args"]) + self.assertNotIn("fit_max_tokens", new) + self.assertEqual(new["sampling"], {"presence_penalty": 1.5}) + new, _ = runconfig.apply({"sampling": {"top_k": 20}}, {"sampling.top_k": None}) + self.assertNotIn("sampling", new) # an empty block goes + + def test_refused(self): + for changes in ({"api_key": "x"}, {"host": "0.0.0.0"}, {"mcp_servers": {}}, {"before_load": "calc.exe"}, + {"args": []}, {"exe": "evil.exe"}, {"trusted_origins": ["*"]}, {"allowed_hosts": ["*"]}, + {"sampling.temperature": -1}, {"sampling.top_p": 0}, {"sampling.top_k": 65}, + {"sampling.min_p": 2}, {"reasoning_budget_tokens": 1.5}, {"fit_max_tokens": "yes"}, + {"effort_position": "middle"}, {"vram_reserve_mib": -5}, {"idle_unload_s": True}, + {"aliases": [1]}, {}, None, ["x"]): + with self.subTest(changes=changes), self.assertRaises(ValueError): + runconfig.apply(CFG, changes) + with self.assertRaises(ValueError): # one bad value: nothing is applied + runconfig.apply(CFG, {"fit_max_tokens": True, "sampling.top_k": 0}) + with self.assertRaises(ValueError): + runconfig.apply({**CFG, "vision": {"gpu": True}}, {"lazy_load": True}) + + def test_view(self): + v = runconfig.view({**CFG, "args": CFG["args"] + ["--vram-reserve-mib", "1500"]}, "x/strata-q2_0.json") + self.assertEqual(v["file"], "strata-q2_0.json") + got = {k["key"]: k for k in v["keys"]} + self.assertEqual(got["sampling.temperature"]["value"], 0.7) + self.assertEqual(got["vram_reserve_mib"]["value"], 1500) + self.assertIsNone(got["fit_max_tokens"]["value"]) + self.assertEqual(got["anthropic_thinking"]["choices"], ["model", "on_request"]) + self.assertNotIn("api_key", got) + self.assertNotIn("mcp_servers", got) + + +class Http(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.path = Path(self.dir.name) / "strata-q2_0.json" + self.path.write_text(json.dumps(CFG, indent=1), encoding="utf-8") + tok = ByteTokenizer() + self.svc = Service(MockEngine(tok, "ok", max_context=4096), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.svc.config_path = str(self.path) + self.httpd = serve(self.svc, port=0) + self.host = f"127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + self.dir.cleanup() + + def call(self, method, body=None, headers=None): + h = {"Content-Type": "application/json", **(headers or {})} + req = urllib.request.Request(f"http://{self.host}/config", method=method, headers=h, + data=None if body is None else (body if isinstance(body, bytes) + else json.dumps(body).encode())) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def saved(self): + return json.loads(self.path.read_text(encoding="utf-8")) + + def test_read_and_write_from_the_page(self): + status, v = self.call("GET") + self.assertEqual(status, 200, v) + self.assertEqual({k["key"]: k["value"] for k in v["keys"]}["sampling.temperature"], 0.7) + with contextlib.redirect_stdout(io.StringIO()): + status, v = self.call("POST", {"set": {"sampling.temperature": 1.0, "open_browser": False}}, + {"Origin": f"http://{self.host}"}) + self.assertEqual(status, 200, v) + self.assertEqual(v["changed"], ["sampling.temperature", "open_browser"]) + cfg = self.saved() + self.assertEqual(cfg["sampling"]["temperature"], 1.0) + self.assertIs(cfg["open_browser"], False) + for k in ("mcp_servers", "cors_origins", "host", "args", "exe"): + self.assertEqual(cfg[k], CFG[k], k) + self.assertEqual(json.loads((self.path.parent / "strata-q2_0.json.bak").read_text(encoding="utf-8")), CFG) + status, v = self.call("POST", {"set": {"open_browser": False}}) # no Origin (a script on this PC): allowed + self.assertEqual((status, v["changed"]), (200, [])) + + def test_only_from_strata_s_own_page(self): + before = self.path.read_bytes() + status, _ = self.call("POST", {"set": {"fit_max_tokens": True}}, {"Origin": "https://evil.example"}) + self.assertEqual(status, 403) + status, _ = self.call("POST", b'{"set": {"fit_max_tokens": true}}', {"Content-Type": "text/plain"}) + self.assertEqual(status, 415) + for body in ({"set": {"api_key": ""}}, {"set": {"mcp_servers": {"x": {"command": "calc"}}}}, + {"set": {"sampling.top_k": 0}}, {"nothing": 1}, b"not json"): + status, b = self.call("POST", body, {"Origin": f"http://{self.host}"}) + self.assertEqual(status, 400, (body, b)) + self.assertEqual(self.path.read_bytes(), before) # nothing was written + self.assertFalse((self.path.parent / "strata-q2_0.json.bak").exists()) + + def test_the_api_key(self): + self.svc.api_key = "secret" + self.assertEqual(self.call("GET")[0], 401) + self.assertEqual(self.call("POST", {"set": {"fit_max_tokens": True}})[0], 401) + with contextlib.redirect_stdout(io.StringIO()): + status, _ = self.call("POST", {"set": {"fit_max_tokens": True}}, {"Authorization": "Bearer secret"}) + self.assertEqual(status, 200) + self.assertIs(self.saved()["fit_max_tokens"], True) + + def test_without_a_run_config(self): + self.svc.config_path = None + self.assertEqual(self.call("GET")[0], 404) + self.assertEqual(self.call("POST", {"set": {"fit_max_tokens": True}})[0], 404) + + def test_the_page_has_the_view(self): + web = ROOT / "serve" / "web" + html, js = (web / "index.html").read_text(encoding="utf-8"), (web / "app.js").read_text(encoding="utf-8") + for el in ("cfg-card", "cfg-form", "cfg-save", "cfg-msg"): + self.assertIn(f'id="{el}"', html) + self.assertIn('fetch("config", {method: "POST", headers: headers(true)', js) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_security.py b/serve/test_security.py new file mode 100644 index 0000000..429c716 --- /dev/null +++ b/serve/test_security.py @@ -0,0 +1,280 @@ +"""serve/test_security.py - the Host check (DNS rebinding) and the Origin check for requests without an API key, +against the mock engine (no GPU, no pack). + + python -m unittest serve.test_security -v +""" +from __future__ import annotations + +import contextlib +import http.client +import io +import json +import socket +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.frontend import ChatTemplate # noqa: E402 +from serve.server import (ByteTokenizer, MockEngine, Service, allowed_hosts_of, host_allowed, # noqa: E402 + host_name, host_names_for, origin_allowed, serve) + +ROOT = Path(__file__).resolve().parents[1] +LOCAL = {"localhost", "127.0.0.1", "::1"} + + +class HostNames(unittest.TestCase): + def test_host_name(self): + self.assertEqual(host_name("Example.COM:8080"), "example.com") + self.assertEqual(host_name("localhost"), "localhost") + self.assertEqual(host_name("[::1]:8095"), "::1") + self.assertEqual(host_name("[::1]"), "::1") + self.assertEqual(host_name("strata.example.com."), "strata.example.com") + for bad in ("", "a:b", "[::1", "[::1]x", "a b", "evil.com/x"): + self.assertEqual(host_name(bad), "", bad) + + def test_allowed_hosts_of(self): + self.assertEqual(allowed_hosts_of(None), []) + self.assertEqual(allowed_hosts_of("Strata.Example.com"), ["strata.example.com"]) + self.assertEqual(allowed_hosts_of(["https://a.example.com:8443/x", ".example.org", "*"], "box, nas.lan "), + ["a.example.com", ".example.org", "*", "box", "nas.lan"]) + for bad in (["bad name"], 5, [3], "http://"): + with self.assertRaises(ValueError): + allowed_hosts_of(bad) + + def test_names_from_the_bind_address(self): + with mock.patch("serve.server.lan_addresses", return_value=["192.168.1.20"]): + self.assertEqual(host_names_for("127.0.0.1"), LOCAL) # this PC only: nothing else + self.assertEqual(host_names_for("localhost"), LOCAL) + names = host_names_for("0.0.0.0") # other devices too + self.assertIn(socket.gethostname().lower(), names) + self.assertIn(socket.gethostname().lower() + ".local", names) + self.assertIn("192.168.1.20", names) + self.assertIn("10.0.0.7", host_names_for("10.0.0.7")) + names = host_names_for("127.0.0.1", ["strata.example.com", "*"], ["https://chat.example.net"]) + self.assertTrue({"strata.example.com", "chat.example.net"} <= names) + self.assertNotIn("*", names) + + +class HostCheck(unittest.TestCase): + def test_accepted(self): + for host in ("localhost:8095", "LOCALHOST", "127.0.0.1:1", "[::1]:8095", "192.168.1.20:8095", "[fe80::1]", + "app.localhost:8095", None, "", "box:8095", "a.example.org", "example.org:443"): + self.assertTrue(host_allowed(host, LOCAL | {"box", ".example.org"}), host) + + def test_refused(self): + # a rebinding page sends its own name; lookalikes of allowed names stay out + for host in ("evil.example.com", "evil.example.com:8095", "localhost.evil.com", "127.0.0.1.nip.io", + "box.evil.com", "xexample.org", "bad host", "a:b:c:d:e:f:g:h:i"): + self.assertFalse(host_allowed(host, LOCAL | {"box", ".example.org"}), host) + + def test_any_host(self): + self.assertTrue(host_allowed("evil.example.com", LOCAL, any_host=True)) + + +class OriginCheck(unittest.TestCase): + def test_accepted(self): + names = LOCAL | {"box"} + self.assertTrue(origin_allowed("http://127.0.0.1:8095", "127.0.0.1:8095", names)) # Strata's own page + self.assertTrue(origin_allowed("http://192.168.1.20:8095", "192.168.1.20:8095", names)) # ... by LAN IP + self.assertTrue(origin_allowed("http://localhost:3000", "127.0.0.1:8095", names)) # a local app + self.assertTrue(origin_allowed("http://[::1]:3000/", "127.0.0.1:8095", names)) + self.assertTrue(origin_allowed("https://box", "127.0.0.1:8095", names)) + self.assertTrue(origin_allowed("https://chat.example.com", "x", names, ["https://chat.example.com"])) + self.assertTrue(origin_allowed("https://any.example.com", "x", names, ["*"])) # cors_origins ["*"] + # browser extensions and desktop apps: no web site can send another scheme than http(s) (or "null") + for origin in ("chrome-extension://abcdef", "moz-extension://1234-5678", "app://."): + self.assertTrue(origin_allowed(origin, "127.0.0.1:8095", names), origin) + + def test_refused(self): + names = LOCAL | {"box"} + for origin in ("http://evil.example.com", "http://1.2.3.4", "http://192.168.1.99:8095", "null", "", + "http://localhost.evil.com", "https://box.evil.com", "://x"): + self.assertFalse(origin_allowed(origin, "127.0.0.1:8095", names, ["https://chat.example.com"]), origin) + + +class OverHttp(unittest.TestCase): + """The checks in the running server, as a browser and as curl/the SDKs send their requests.""" + + def setUp(self): + tok = ByteTokenizer() + self.svc = Service(MockEngine(tok, "\n\nok", max_context=4096), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = None + + def start(self, **attrs): + for k, v in attrs.items(): + setattr(self.svc, k, v) + self.httpd = serve(self.svc, port=0) + self.port = self.httpd.server_address[1] + + def tearDown(self): + if self.httpd: + self.httpd.shutdown() + self.httpd.server_close() + + def req(self, method, path, body=None, headers=None, host=None): + """(status, JSON, what the server printed); `host` replaces the Host header http.client sends.""" + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30) + h = dict(headers or {}) + if host is not None: + h["Host"] = host + data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode() + out = io.StringIO() + try: + with contextlib.redirect_stdout(out): + c.request(method, path, body=data, headers=h) + r = c.getresponse() + raw = r.read() + return r.status, json.loads(raw) if raw[:1] in (b"{", b"[") else raw, out.getvalue() + finally: + c.close() + + def chat_body(self): + return {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 64} + + # --- Host + def test_rebinding_name_is_refused_everywhere(self): + self.start() + for method, path in (("GET", "/status"), ("GET", "/metrics"), ("GET", "/"), ("GET", "/health"), + ("POST", "/settings"), ("POST", "/v1/chat/completions"), ("OPTIONS", "/v1/models")): + code, body, log = self.req(method, path, {} if method == "POST" else None, + {"Content-Type": "application/json"}, host=f"evil.example.com:{self.port}") + self.assertEqual(code, 403, path) + if method != "OPTIONS": + self.assertIn("allowed_hosts", body["error"]["message"]) + self.assertEqual(log.count("\n"), 1, path) # one log line each + self.assertIn("evil.example.com", log) + + def test_local_names_and_ips_pass(self): + self.start() + for host in (f"127.0.0.1:{self.port}", f"localhost:{self.port}", f"[::1]:{self.port}", + f"192.168.1.20:{self.port}"): + self.assertEqual(self.req("GET", "/status", host=host)[0], 200, host) + + def test_no_host_header_passes(self): + self.start() + with socket.create_connection(("127.0.0.1", self.port), timeout=10) as s: # an HTTP/1.0 client + s.sendall(b"GET /health HTTP/1.0\r\n\r\n") + raw = b"" + while chunk := s.recv(65536): + raw += chunk + self.assertTrue(raw.startswith(b"HTTP/1.0 200"), raw[:40]) + + def test_allowed_hosts_and_wildcard(self): + self.start(allowed_hosts=["strata.example.com", ".home.arpa"]) + self.assertEqual(self.req("GET", "/status", host="strata.example.com")[0], 200) + self.assertEqual(self.req("GET", "/status", host="nas.home.arpa:8095")[0], 200) + self.assertEqual(self.req("GET", "/status", host="evil.example.com")[0], 403) + self.svc.allowed_hosts = ["*"] + self.assertEqual(self.req("GET", "/status", host="evil.example.com")[0], 200) + + def test_refusal_names_both_ways_out(self): + self.start() + message = self.req("GET", "/status", host="evil.example.com")[1]["error"]["message"] + self.assertIn("allowed_hosts", message) + self.assertIn("api_key", message) + + def test_with_a_key_the_host_check_is_off(self): + # a rebinding page cannot authenticate; tunnels and proxies that pass their own name on keep working + self.start(api_key="s3cret") + tunnel = "random-words.trycloudflare.com" + self.assertEqual(self.req("GET", "/status", host=tunnel)[0], 401) + self.assertEqual(self.req("GET", "/status", headers={"Authorization": "Bearer s3cret"}, host=tunnel)[0], 200) + self.assertEqual(self.req("GET", "/health", host=tunnel)[0], 200) + code, _, log = self.req("POST", "/v1/chat/completions", self.chat_body(), + {"Content-Type": "application/json", "Authorization": "Bearer s3cret"}, host=tunnel) + self.assertEqual(code, 200) + self.assertNotIn("refused", log) + + def test_a_trusted_origin_s_host_is_allowed(self): + self.start(trusted_origins=["https://strata.example.com"]) + self.assertEqual(self.req("GET", "/status", host="strata.example.com")[0], 200) + + # --- Origin on /v1 without an API key + def test_curl_and_sdks_without_origin(self): + self.start() + for ctype in ("application/json", "text/plain", None): # curl -d sends a form type + code, body, _ = self.req("POST", "/v1/chat/completions", self.chat_body(), + {"Content-Type": ctype} if ctype else {}) + self.assertEqual(code, 200, ctype) + self.assertEqual(body["choices"][0]["message"]["content"], "ok") + + def test_cross_site_page_is_refused(self): + self.start() + for path in ("/v1/chat/completions", "/v1/messages", "/v1/messages/count_tokens"): + for ctype in ("text/plain", "application/json"): + code, body, log = self.req("POST", path, self.chat_body(), + {"Content-Type": ctype, "Origin": "http://evil.example.com"}) + self.assertEqual(code, 403, (path, ctype)) + self.assertIn("api_key", body["error"]["message"]) + self.assertIn("evil.example.com", log) + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {"Content-Type": "text/plain", "Origin": "null"})[0], 403) + + def test_own_and_local_pages_pass(self): + self.start() + json_type = {"Content-Type": "application/json"} + for origin in (f"http://127.0.0.1:{self.port}", "http://localhost:3000", "chrome-extension://abcdef"): + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {**json_type, "Origin": origin})[0], 200, origin) + # a browser page sends JSON; text/plain from a page is the cross-site "simple request" shape + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {"Content-Type": "text/plain", "Origin": f"http://127.0.0.1:{self.port}"})[0], 415) + + def test_configured_origins_pass(self): + self.start(cors_origins=["https://chat.example.com"], trusted_origins=["https://strata.example.com"], + allowed_hosts=["webui.lan"]) + for origin in ("https://chat.example.com", "https://strata.example.com", "http://webui.lan:3000"): + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {"Content-Type": "application/json", "Origin": origin})[0], 200, origin) + + def test_with_a_key_the_key_decides(self): + self.start(api_key="s3cret") + headers = {"Content-Type": "text/plain", "Origin": "http://evil.example.com"} + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), headers)[0], 401) + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {**headers, "Authorization": "Bearer s3cret"})[0], 200) + + # --- /unload and /load + def test_control_body_arrives_before_the_operation_and_reply(self): + self.start() + for body, expected in ((b"{}", 200), (b"{", 400)): + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5) + try: + with mock.patch.object(self.svc, "unload", return_value="unloaded") as unload: + c.putrequest("POST", "/unload") + c.putheader("Content-Type", "application/json") + c.putheader("Content-Length", "2") + c.endheaders() + c.sock.settimeout(0.1) + with self.assertRaises(socket.timeout): + c.sock.recv(1) + unload.assert_not_called() + c.sock.settimeout(5) + c.send(body) + if len(body) < 2: + c.sock.shutdown(socket.SHUT_WR) + r = c.getresponse() + self.assertEqual(r.status, expected) + r.read() + self.assertEqual(unload.call_count, int(expected == 200)) + finally: + c.close() + + def test_unload_and_load_need_json_from_the_own_page(self): + self.start() + form = {"Content-Type": "application/x-www-form-urlencoded"} + for path in ("/unload", "/load"): + self.assertEqual(self.req("POST", path, b"a=1", form)[0], 415, path) + self.assertEqual(self.req("POST", path, b"", {})[0], 415, path) + self.assertEqual(self.req("POST", path, {}, {"Content-Type": "application/json", + "Origin": "http://evil.example.com"})[0], 403, path) + self.assertEqual(self.req("POST", "/unload", {}, {"Content-Type": "application/json"})[0], 200) + self.assertEqual(self.req("POST", "/load", {}, {"Content-Type": "application/json", + "Origin": f"http://127.0.0.1:{self.port}"})[0], 200) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_server.py b/serve/test_server.py new file mode 100644 index 0000000..0ffe2f6 --- /dev/null +++ b/serve/test_server.py @@ -0,0 +1,2685 @@ +"""serve/test_server.py - the max tokens budget over both APIs, against the mock engine (no GPU, no pack). + + python -m unittest serve.test_server -v +""" +from __future__ import annotations + +import contextlib +import io +import json +import os +import sys +import tempfile +import threading +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.frontend import ChatTemplate # noqa: E402 +from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, Service, StrataEngine, # noqa: E402 + engine_args, layer_split_value, prompt_tokens_seen, request_timings, serve, + start_failure_hint) +from types import SimpleNamespace # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +CTX = 4096 +ANSWER = "xy" * 1000 # longer than the old 1024 fallback: one token per byte (#606: not +# one token repeated, which the server ends at 256) + + +class RecordingEngine(MockEngine): + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.last_max_new = max_new + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + +class MaxTokens(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = RecordingEngine(tok, "\n\n" + ANSWER, max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def post(self, path, body): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def call(self, api, text="hi", **budget): + """-> (status, body, prompt tokens, completion tokens); `budget` is merged into the request as given.""" + msgs = [{"role": "user", "content": text}] + if api == "openai": + s, b = self.post("/v1/chat/completions", {"model": "m", "messages": msgs, **budget}) + u = b.get("usage", {}) + return s, b, u.get("prompt_tokens"), u.get("completion_tokens") + s, b = self.post("/v1/messages", {"model": "m", "messages": msgs, **budget}) + u = b.get("usage", {}) + return s, b, u.get("input_tokens"), u.get("output_tokens") + + def test_anthropic_thinks_only_when_asked(self): + # #278: Anthropic's thinking is opt-in; "thinking", an effort or a reasoning_budget_tokens (#123) asks for it + from serve.frontend import anthropic_to_messages + msgs = [{"role": "user", "content": "u"}] + kw = lambda **r: anthropic_to_messages({"messages": msgs, **r}, think_unasked=False)[2] # noqa: E731 + # the default ("anthropic_thinking": "model") renders an unasked request as 0.1.31 did + self.assertNotIn("enable_thinking", anthropic_to_messages({"messages": msgs})[2]) + self.assertEqual(kw(), {"enable_thinking": False}) + self.assertEqual(kw(thinking={"type": "disabled"}), {"enable_thinking": False}) + self.assertNotIn("enable_thinking", kw(thinking={"type": "enabled", "budget_tokens": 2048})) + self.assertNotIn("enable_thinking", kw(output_config={"effort": "high"})) + self.assertNotIn("enable_thinking", kw(reasoning_budget_tokens=30)) + + def test_count_tokens_is_the_prompt_messages_reads(self): + # /v1/messages/count_tokens renders and tokenizes the same prompt /v1/messages would read, without running it + msgs = [{"role": "user", "content": "how many tokens is this?"}] + s, b = self.post("/v1/messages/count_tokens", {"model": "m", "messages": msgs}) + self.assertEqual(s, 200) + s2, _, n_in, _ = self.call("anthropic", "how many tokens is this?", max_tokens=8) + self.assertEqual(s2, 200) + self.assertEqual(b["input_tokens"], n_in) + + def test_request_line_parses_the_engine_summary(self): + line = ("strata serve: prompt 1200 tokens = 1000 reused + 200 read in 50 ms (4000.0 tok/s), 30 generated in " + "300 ms (100.0 tok/s), drafts accepted 20 of 28, 2 checkpoints") + from serve.server import ENGINE_REQUEST + m = ENGINE_REQUEST.search(line) + self.assertIsNotNone(m) + self.assertEqual((m["prompt"], m["reused"], m["gen"], m["tg"]), ("1200", "1000", "30", "100.0")) + # #471: a request cancelled while its prompt was read says how far it got + m = ENGINE_REQUEST.search("strata serve: prompt 98179 tokens = 0 reused + 12288 of 98179 read in 17565 ms " + "(699.6 tok/s), 0 generated in 0 ms (0.0 tok/s), drafts accepted 0 of 0, " + "0 checkpoints (cancelled)") + self.assertIsNotNone(m) + self.assertEqual((m["prompt"], m["reused"], m["read"], m["pp"], m["gen"]), + ("98179", "0", "17565", "699.6", "0")) + + def test_unset_budget_is_the_rest_of_the_context(self): + cases = {"openai": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None}, + {"max_completion_tokens": -1}, {"max_completion_tokens": None, "max_tokens": None}], + "anthropic": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None}]} + for api, budgets in cases.items(): + for budget in budgets: + with self.subTest(api=api, budget=budget): + s, b, pt, ct = self.call(api, **budget) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, CTX - CTX_SLACK - pt) + self.assertGreater(ct, 1024) # the whole answer, not cut at the old 1024 fallback + + def test_explicit_budget_is_honoured(self): + for api, budget in [("openai", {"max_tokens": 50}), ("openai", {"max_completion_tokens": 50}), + ("openai", {"max_completion_tokens": 50, "max_tokens": 9}), + ("anthropic", {"max_tokens": 50}), ("openai", {"max_tokens": 1500}), + ("anthropic", {"max_tokens": 1500})]: + with self.subTest(api=api, budget=budget): + want = budget.get("max_completion_tokens") or budget["max_tokens"] + s, b, _, ct = self.call(api, **budget) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, want) + self.assertEqual(ct, want) + + def test_explicit_budget_over_the_context_is_rejected(self): + for api in ("openai", "anthropic"): + with self.subTest(api=api): + s, b, _, _ = self.call(api, max_tokens=CTX) + self.assertEqual(s, 400) + self.assertIn("exceeds the context", b["error"]["message"]) + self.assertIn("\"fit_max_tokens\": true", b["error"]["message"]) # #545: says how to get past it + self.assertRegex(b["error"]["message"], r"at most \d+ here") + + def test_unset_budget_with_a_near_full_prompt(self): + _, _, pt0, _ = self.call("openai", max_tokens=1) + overhead = pt0 - len("hi") # the template's tokens around the user text + for api in ("openai", "anthropic"): + _, _, pa, _ = self.call(api, max_tokens=1) + over = pa - pt0 # the Anthropic template may differ slightly + with self.subTest(api=api, room=5): # a few tokens left: the budget is exactly those + text = "y" * (CTX - CTX_SLACK - overhead - over - 5) + s, b, pt, ct = self.call(api, text=text, max_tokens=-1) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, 5) + self.assertEqual(ct, 5) + with self.subTest(api=api, room=0): # nothing left: rejected, not truncated + text = "y" * (CTX - CTX_SLACK - overhead - over) + s, b, _, _ = self.call(api, text=text) + self.assertEqual(s, 400, b) + self.assertIn("no room to answer", b["error"]["message"]) + + def test_debug_log_shows_the_resolved_budget(self): + import contextlib + import io + os.environ["STRATA_DEBUG"] = "1" + try: + for api in ("openai", "anthropic"): + with self.subTest(api=api): + out = io.StringIO() + with contextlib.redirect_stdout(out): + _, _, pt, _ = self.call(api, max_tokens=-1) + self.assertIn(f"max_new={CTX - CTX_SLACK - pt} ", out.getvalue()) + finally: + del os.environ["STRATA_DEBUG"] + + +class FitMaxTokens(unittest.TestCase): + """PR #24: --fit-max-tokens clamps an explicit budget that overshoots the context instead of a 400.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = RecordingEngine(tok, "\n\n" + ANSWER, max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), fit_max_tokens=True) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + post = MaxTokens.post + call = MaxTokens.call + + def test_overshoot_is_clamped_to_the_room(self): + for api in ("openai", "anthropic"): + with self.subTest(api=api): + s, b, pt, ct = self.call(api, max_tokens=CTX) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, CTX - CTX_SLACK - pt) + + def test_a_budget_that_fits_is_unchanged(self): + s, b, _, ct = self.call("openai", max_tokens=50) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, 50) + + def test_no_room_is_still_a_400(self): + _, _, pt0, _ = self.call("openai", max_tokens=1) + overhead = pt0 - len("hi") + s, b, _, _ = self.call("openai", text="y" * (CTX - CTX_SLACK - overhead), max_tokens=100) + self.assertEqual(s, 400, b) + self.assertIn("no room to answer", b["error"]["message"]) + + +class ImageMarkers(unittest.TestCase): + """#150: the text "<|image_pad|>" inside a message is text, not an image's place.""" + + class FakeVision: + def __init__(self, d): + self.dir = Path(d) + self.rows = self.dir / "img.sve" + self.rows.write_bytes(b"rows") + + def encode(self, source): + return self.rows, 3 + + def test_literal_marker_with_an_image(self): + import tempfile + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=self.FakeVision(d)) + pad = tok.encode("<|image_pad|>", parse_special=True)[0] + for text in ("the docs say <|image_pad|> marks an image", "plain"): + with self.subTest(text=text): + msgs = [{"role": "user", "content": [{"type": "text", "text": text}, + {"type": "image", "source": "x.png"}]}] + ids, _, _ = svc.prepare(msgs, None, {}) + self.assertEqual(ids.count(pad), 3) # the image's three rows, nothing else + self.assertIn("<|image_pad|> marks" if "docs" in text else "plain", tok.decode(ids)) + svc.embeddings.path.unlink(missing_ok=True) + + +class ThinkTokenizer(ByteTokenizer): + """The byte tokenizer with the model's reasoning markers as specials that are matched even without parse_special, + as the real tokenizer does (GGUF token type 4).""" + SPECIALS = ByteTokenizer.SPECIALS + ["", ""] + ALWAYS = ("", "") + + +class LiteralThinkTags(unittest.TestCase): + """#537: a / written inside a message is text, not the model's reasoning markers: a quoted + "" no longer ends the model's reasoning before it starts. The template's own markers stay special.""" + + @classmethod + def setUpClass(cls): + cls.tok = ThinkTokenizer() + cls.svc = Service(MockEngine(cls.tok, "ok", max_context=CTX), cls.tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.open, cls.close = (cls.tok.encode(t)[0] for t in ("", "")) + + def ids(self, messages, tools=None, **kw): + return self.svc.prepare(messages, tools, kw)[0] + + def old_ids(self, messages, tools=None, **kw): + return self.tok.encode(self.svc.template.render(messages, tools=tools, **kw), parse_special=True) + + def test_a_quoted_tag_in_a_user_message(self): + text = "Quote this exact literal string, then explain it: and " + ids = self.ids([{"role": "user", "content": text}]) + self.assertEqual(ids.count(self.close), 0) + self.assertEqual(ids.count(self.open), 1) # the generation prompt's own + self.assertEqual(ids[-2:], [self.open, ord("\n")]) + self.assertIn(text, self.tok.decode(ids)) # the text is all there, as text + self.assertEqual(ids.count(self.close), 0) + # thinking off: the template's empty block stays two specials, the user's tag is text + ids = self.ids([{"role": "user", "content": text}], enable_thinking=False) + self.assertEqual((ids.count(self.open), ids.count(self.close)), (1, 1)) + + def test_without_a_tag_the_prompt_is_unchanged(self): + msgs = [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "1+1?"}, + {"role": "assistant", "content": "2", "reasoning_content": "easy"}, {"role": "user", "content": "x"}] + self.assertEqual(self.ids(msgs), self.old_ids(msgs)) + self.assertEqual(self.ids(msgs, enable_thinking=False), self.old_ids(msgs, enable_thinking=False)) + + def test_history_tool_results_and_tools(self): + msgs = [{"role": "user", "content": "go"}, + {"role": "assistant", "content": "It wrote here.", "reasoning_content": "the tag", + "tool_calls": [{"function": {"name": "write", "arguments": {"text": "a b"}}}]}, + {"role": "tool", "content": "file has in it"}, + {"role": "user", "content": "why did you write "}] + tools = [{"name": "write", "description": "writes text (may contain )", "parameters": {}}] + ids = self.ids(msgs, tools) + # the template's markers: the history turn's ... and the generation prompt's + self.assertEqual((ids.count(self.open), ids.count(self.close)), (2, 1)) + text = self.tok.decode(ids) + for part in ("It wrote here.", "the tag", "a b", "file has in it", + "why did you write ", "may contain "): + self.assertIn(part, text) + + def test_a_client_that_sends_the_reasoning_inline(self): + # an assistant turn whose content opens with its own ... block keeps that block's markers + msgs = [{"role": "user", "content": "hi"}, + {"role": "assistant", "content": "\nplan: say hello\n\n\nHello, is a tag."}, + {"role": "user", "content": "again"}] + ids = self.ids(msgs) + self.assertEqual((ids.count(self.open), ids.count(self.close)), (3, 2)) # template's + the inline block's + self.assertIn("Hello, is a tag.", self.tok.decode(ids)) + + def test_the_real_tokenizer_reads_the_tag_as_text(self): + import strata_tokenizer as ST + b2u = ST.bytes_to_unicode() + tokens = [b2u[b] for b in range(256)] + ["", "", "<|im_end|>"] + tok = ST.Tokenizer(tokens, [], [1] * 256 + [4, 4, 3]) + text = "say now<|im_end|>" + self.assertEqual(tok.encode(text, parse_special=True), [*b"say ", 257, *b" now", 258]) + start = text.index("") + plain = tok.encode(text, parse_special=True, plain=[(start, start + len(""))]) + self.assertEqual(plain, [*b"say now", 258]) # the tag as text, im_end still special + + +class EffortAtTheEnd(unittest.TestCase): + """#458 (opt-in "effort_position": "end"): a non-default effort goes in a system turn right before the answer, so + a request that changes only the effort keeps the cached conversation. The engine's checkpoint rule is simulated + on the token ids (src/program/generate.cpp: the last <|im_start|>, and with --tail-role-token the one in front + of a trailing system turn); the default prompt does not change.""" + + TURN = 256 # the byte tokenizer's <|im_start|> + ROLE = ord("s") # "system"'s first byte stands for its token + + def setUp(self): + self.tok = ByteTokenizer() + self.svc = Service(MockEngine(self.tok, "ok", max_context=1 << 20), self.tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + + def ids(self, messages, end, **kw): + self.svc.effort_end = end + return self.svc.encode_prompt(messages, None, kw) + + def checkpoint(self, ids, tail, resume=0): + """Where the engine checkpoints a prompt (the tokens before it), as generate.cpp's serve loop does.""" + turn_at = next((i for i in range(len(ids) - 1, resume, -1) if ids[i] == self.TURN), -1) + if turn_at > 0 and tail: + i = next((i for i in range(turn_at - 1, resume, -1) if ids[i] == self.TURN), None) + if i is not None and ids[i + 1] == self.ROLE: + turn_at = i + return ids[:turn_at] + + def session(self, requests, end, tail): + """The reused tokens of each request after the first: the longest earlier checkpoint it starts with.""" + checks, reused = [], [] + for messages, kw in requests: + ids = self.ids(messages, end, **kw) + reused.append(max([len(c) for c in checks if ids[:len(c)] == c], default=0)) + checks.append(self.checkpoint(ids, tail)) + return reused[1:] + + CHAT = [{"role": "system", "content": "You are a careful assistant. " * 40}, + {"role": "user", "content": "Explain the conversation cache. " * 20}] + REPLY = {"role": "assistant", "content": "It keeps the prompt's state. " * 20, "reasoning_content": "ok"} + NEXT = {"role": "user", "content": "And the checkpoints?"} + + def test_the_default_prompt_is_unchanged(self): + for kw in ({}, {"reasoning_effort": "xhigh"}): + self.assertEqual(self.ids(self.CHAT, True, **kw), self.ids(self.CHAT, False, **kw)) + self.assertEqual(self.ids(self.CHAT, True, **kw), + self.tok.encode(self.svc.template.render(self.CHAT, **kw), parse_special=True)) + for kw in ({"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, {"enable_thinking": False}): + self.assertEqual(self.ids(self.CHAT, False, **kw), # off: every effort renders as before + self.tok.encode(self.svc.template.render(self.CHAT, **kw), parse_special=True)) + + def test_the_trailing_turn(self): + text = self.tok.decode(self.ids(self.CHAT, True, reasoning_effort="low")) + self.assertTrue(text.endswith("<|im_end|>\n<|im_start|>system\nReasoning effort is set to low. Keep your " + "thinking brief and focused, moving directly to the conclusion without " + "unnecessary elaboration.<|im_end|>\n<|im_start|>assistant\n\n"), text[-300:]) + self.assertIn("Reasoning effort is set to xhigh", text) # the top stays the default's + text = self.tok.decode(self.ids(self.CHAT, True, enable_thinking=False)) + self.assertTrue(text.endswith("<|im_start|>assistant\n\n\n\n\n")) + self.assertNotIn("<|im_start|>system\nReasoning effort", text[-200:]) + default = self.ids(self.CHAT, True) + for kw in ({"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, {"enable_thinking": False}): + ids = self.ids(self.CHAT, True, **kw) + head = len(self.checkpoint(default, False)) # all before the answer's turn + self.assertEqual(ids[:head], default[:head], kw) # the same prompt up to the answer + + def test_changing_the_effort_keeps_the_conversation(self): + efforts = [{}, {"reasoning_effort": "low"}, {"enable_thinking": False}, {"reasoning_effort": "medium"}, {}] + history = len(self.checkpoint(self.ids(self.CHAT, False), False)) + # at the top (the default): another effort differs a few tokens in, and the whole prompt is read again + self.assertEqual(self.session([(self.CHAT, kw) for kw in efforts], False, False)[:2], [0, 0]) + # at the end, with the engine's rule: every request reuses the whole conversation + self.assertEqual(self.session([(self.CHAT, kw) for kw in efforts], True, True), [history] * 4) + + def test_the_next_turn_reuses_the_checkpoint(self): + turn1, turn2 = self.CHAT, self.CHAT + [self.REPLY, self.NEXT] + low = {"reasoning_effort": "low"} + first = len(self.checkpoint(self.ids(turn1, True, **low), True)) + # the engine's rule: the next turn (the same effort) reuses the first turn's whole conversation + self.assertEqual(self.session([(turn1, low), (turn2, low)], True, True), [first]) + # without it the checkpoint held the effort turn and the next turn reused nothing (what #458 measured) + self.assertEqual(self.session([(turn1, low), (turn2, low)], True, False), [0]) + + def test_the_config(self): + from serve.server import effort_end_args + + class Tok: + def encode(self, text, parse_special=False): + return [8678] if text == "system" else [1, 2] + + with tempfile.TemporaryDirectory() as d: + new, old = Path(d) / "new.exe", Path(d) / "old.exe" + new.write_bytes(b"... --tail-role-token ID --serve: ...") + old.write_bytes(b"... --turn-token ID ...") + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertIsNone(effort_end_args({}, str(new), Tok())) + self.assertIsNone(effort_end_args({"effort_position": "start"}, str(new), Tok())) + self.assertEqual(effort_end_args({"effort_position": "end"}, str(new), Tok()), + ["--tail-role-token", "8678"]) + self.assertIsNone(effort_end_args({"effort_position": "end"}, str(old), Tok())) + self.assertIsNone(effort_end_args({"effort_position": "end"}, str(new), ByteTokenizer())) + self.assertIn("needs engine 0.1.39 or newer", out.getvalue()) + with self.assertRaises(ValueError): + effort_end_args({"effort_position": "middle"}, str(new), Tok()) + + +class StatusNeedsTheKey(unittest.TestCase): + """#212: /status shows the end of the answer being written, so it needs the key like /v1/*.""" + + def test_status(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc.api_key = "k3y" + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}/status" + try: + with self.assertRaises(urllib.error.HTTPError) as e: + urllib.request.urlopen(base, timeout=10) + self.assertEqual(e.exception.code, 401) + e.exception.close() + req = urllib.request.Request(base, headers={"Authorization": "Bearer k3y"}) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.status, 200) + self.assertNotIn("tail", json.loads(r.read())) + finally: + httpd.shutdown() + httpd.server_close() + + +class ToolCallTerminators(unittest.TestCase): + """#210: a value that contains or (a file documenting the call format) is kept whole.""" + CONTENT = ("Close each value with and the call with .\n" + "\nnot a parameter\n\nend") + SCHEMA = [{"name": "write", "parameters": {"properties": {"path": {"type": "string"}, + "content": {"type": "string"}}}}] + + def run_parser(self, stream_tools, step): + from serve.frontend import OutputParser + text = ("\n\n\n\n\ndoc.md\n\n" + f"\n{self.CONTENT}\n\n\n") + p = OutputParser(thinking=True, tools=self.SCHEMA, stream_tools=stream_tools) + evs = [] + for i in range(0, len(text), step): + evs += p.feed(text[i:i + step]) + evs += p.finish() + return evs + + def test_values_keep_the_terminators(self): + for stream_tools in (False, True): + for step in (1, 7, 10_000): + with self.subTest(stream_tools=stream_tools, step=step): + evs = self.run_parser(stream_tools, step) + calls = [e.call for e in evs if e.kind == "tool_call"] + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0].arguments, {"path": "doc.md", "content": self.CONTENT}) + self.assertFalse([e for e in evs if e.kind == "content" and e.text.strip()]) + if stream_tools: + streamed = "".join(e.text for e in evs if e.kind == "tool_args") + self.assertEqual(json.loads(streamed), {"path": "doc.md", "content": self.CONTENT}) + + +class UnfinishedToolCall(unittest.TestCase): + """#211: a call the output ends inside is not reported as a whole one - its streamed JSON is not closed and the + finish reason is not "tool_calls" / "tool_use" - so a client can tell it from a call to run.""" + CALL = ("\n\n\n\n\nnotes.txt\n\n" + "\n") + CUT = CALL + "first half of the fi" # the model's turn ends here + WHOLE = CALL + "all of it\n\n\n" + PROPS = {"path": {"type": "string"}, "content": {"type": "string"}} + + def test_parser(self): + from serve.frontend import OutputParser + schema = [{"name": "write", "parameters": {"properties": self.PROPS}}] + for text, content in ((self.CUT, None), (self.WHOLE, "all of it"), + (self.WHOLE[:-len("")], "all of it")): # only missing: whole + for step in (1, 7, 10_000): + with self.subTest(end=text[-12:], step=step): + p = OutputParser(thinking=True, tools=schema, stream_tools=True) + evs = [] + for i in range(0, len(text), step): + evs += p.feed(text[i:i + step]) + evs += p.finish() + streamed = "".join(e.text for e in evs if e.kind == "tool_args") + calls = [e for e in evs if e.kind == "tool_call"] + if content is None: + self.assertEqual((calls, streamed), ([], '{"path":"notes.txt","content":"first half of the fi')) + else: + self.assertEqual(len(calls), 1) + self.assertEqual(json.loads(streamed), {"path": "notes.txt", "content": content}) + + def answers(self, script, max_tokens=500): + """(finish reason, the call's arguments) from OpenAI and Anthropic, whole and streamed, for the model's `script`.""" + tok = ByteTokenizer() + svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + tools = {"openai": [{"type": "function", "function": {"name": "write", "parameters": { + "type": "object", "properties": self.PROPS}}}], + "anthropic": [{"name": "write", "input_schema": {"type": "object", "properties": self.PROPS}}]} + out = {} + try: + for api, path in (("openai", "/v1/chat/completions"), ("anthropic", "/v1/messages")): + for stream in (False, True): + body = {"model": "x", "max_tokens": max_tokens, "stream": stream, "tools": tools[api], + "messages": [{"role": "user", "content": "save my notes"}]} + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), headers={ + "Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + if stream: + evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + if api == "openai": + out[api, stream] = (evs[-1]["choices"][0]["finish_reason"], "".join( + (tc.get("function") or {}).get("arguments") or "" for e in evs + for tc in e["choices"][0]["delta"].get("tool_calls") or [])) + else: + out[api, stream] = (evs[-2]["delta"]["stop_reason"], "".join( + e["delta"]["partial_json"] for e in evs if e["type"] == "content_block_delta" + and e["delta"]["type"] == "input_json_delta")) + elif api == "openai": + c = json.loads(raw)["choices"][0] + out[api, stream] = (c["finish_reason"], [tc["function"]["arguments"] + for tc in c["message"].get("tool_calls") or []]) + else: + m = json.loads(raw) + out[api, stream] = (m["stop_reason"], [b["input"] for b in m["content"] if b["type"] == "tool_use"]) + finally: + httpd.shutdown() + httpd.server_close() + return out + + def test_a_cut_call(self): + cut = '{"path":"notes.txt","content":"first half of the fi' + self.assertEqual(self.answers(self.CUT), { + ("openai", False): ("stop", []), ("openai", True): ("stop", cut), # whole answers leave the cut + ("anthropic", False): ("end_turn", []), # call out: it has no arguments to give + ("anthropic", True): ("end_turn", cut)}) + + def test_a_call_cut_at_the_token_limit(self): + """The same cut by max_tokens: "length" / "max_tokens", and the whole (non-streamed) answers leave the call + out in both APIs.""" + a = self.answers(self.CUT + "rest of the file, never reached" * 40, max_tokens=len(self.CUT)) + self.assertEqual((a["openai", False], a["anthropic", False]), (("length", []), ("max_tokens", []))) + self.assertEqual((a["openai", True][0], a["anthropic", True][0]), ("length", "max_tokens")) + + def test_collect_keeps_calls_whose_arguments_parse(self): + from serve.server import openai_collect + + def chunk(delta, finish=None): + return {"id": "c", "created": 1, "model": "m", "usage": {}, + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]} + whole = {"index": 0, "id": "a", "type": "function", "function": {"name": "f", "arguments": '{"x": 1}'}} + cut = {"index": 1, "id": "b", "type": "function", "function": {"name": "g", "arguments": '{"y": "ha'}} + for finish, want in (("stop", ["a"]), ("length", ["a"]), ("tool_calls", ["a", "b"])): + with self.subTest(finish=finish): + msg = openai_collect([chunk({"tool_calls": [whole]}), chunk({"tool_calls": [cut]}), + chunk({}, finish)])["choices"][0]["message"] + self.assertEqual([c["id"] for c in msg["tool_calls"]], want) + msg = openai_collect([chunk({"tool_calls": [cut]}), chunk({}, "stop")])["choices"][0]["message"] + self.assertNotIn("tool_calls", msg) + + def test_a_whole_call(self): + whole = {"path": "notes.txt", "content": "all of it"} + a = self.answers(self.WHOLE) + self.assertEqual((a["openai", False][0], [json.loads(x) for x in a["openai", False][1]]), ("tool_calls", [whole])) + self.assertEqual((a["openai", True][0], json.loads(a["openai", True][1])), ("tool_calls", whole)) + self.assertEqual(a["anthropic", False], ("tool_use", [whole])) + self.assertEqual((a["anthropic", True][0], json.loads(a["anthropic", True][1])), ("tool_use", whole)) + + +class ClientShapes(unittest.TestCase): + """What real clients send: Claude Code posts /v1/messages?beta=true (issue #55) and puts hook context into the + conversation as a mid-conversation system message (issue #56); some OpenAI clients send a late developer message.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = RecordingPrompt(tok, "\n\n2", max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def post(self, path, body): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def prompt_text(self): + return bytes(i for i in self.engine.last_ids if i < 256).decode("utf-8", "replace") + + def test_query_string(self): + body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}]} + for path in ("/v1/messages?beta=true", "/v1/chat/completions?api-version=1", "/v1/messages/?beta=true"): + status, b = self.post(path, body) + self.assertEqual(status, 200, (path, b)) + status, _ = self.post("/v1/nothing?beta=true", body) + self.assertEqual(status, 404) + + def test_anthropic_mid_conversation_system(self): + status, b = self.post("/v1/messages?beta=true", { + "model": "x", "max_tokens": 50, + "system": [{"type": "text", "text": "You are terse."}], + "messages": [ + {"role": "user", "content": [{"type": "text", "text": "1+1? digits only"}]}, + {"role": "system", "content": [{"type": "text", "text": "answer in digits"}]}]}) + self.assertEqual(status, 200, b) + text = self.prompt_text() + self.assertIn("You are terse.", text) + self.assertIn("answer in digits", text) + self.assertLess(text.index("You are terse."), text.index("1+1?")) # the first system stays first + self.assertLess(text.index("1+1?"), text.index("answer in digits")) # the late one stays in place + + def test_openai_late_developer_and_system(self): + status, b = self.post("/v1/chat/completions", { + "model": "x", "max_tokens": 50, + "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hello"}, + {"role": "assistant", "content": "hi"}, {"role": "developer", "content": "Now use digits."}, + {"role": "system", "content": "Also this."}, {"role": "user", "content": "1+1?"}]}) + self.assertEqual(status, 200, b) + text = self.prompt_text() + for part in ("Be brief.", "Now use digits.", "Also this.", "1+1?"): + self.assertIn(part, text) + + def test_no_user_turn_is_a_400(self): + # #365: the template's own refusal (Qwen's "No user query found in messages." when no turn is a user's query) + # answers 400, not a dropped connection + with tempfile.TemporaryDirectory() as d: + tpl = Path(d) / "chat_template.jinja" + tpl.write_text("{% if messages[-1].role != 'user' %}{{ raise_exception('No user query found in messages.') }}" + "{% endif %}{{ messages[-1].content }}", encoding="utf-8") + template, self.svc.template = self.svc.template, ChatTemplate(tpl) + try: + status, b = self.post("/v1/chat/completions", { + "model": "x", "max_tokens": 20, "messages": [{"role": "system", "content": "Only a system."}]}) + self.assertEqual(status, 400, b) + self.assertIn("No user query found", b["error"]["message"]) + finally: + self.svc.template = template + status, b = self.post("/v1/chat/completions", {"model": "x", "max_tokens": 20, + "messages": [{"role": "user", "content": "hi"}]}) + self.assertEqual(status, 200, b) # the server goes on + + def test_messages_as_a_json_string_over_http(self): + # #460: a double-encoded "messages" is answered; one that is not a list of objects is a 400, not a 500 + encoded = json.dumps([{"role": "user", "content": "1+1?"}]) + for path in ("/v1/chat/completions", "/v1/messages"): + with self.subTest(path=path): + status, b = self.post(path, {"model": "x", "max_tokens": 20, "messages": encoded}) + self.assertEqual(status, 200, b) + self.assertIn("1+1?", self.prompt_text()) + status, b = self.post(path, {"model": "x", "max_tokens": 20, "messages": ["hi"]}) + self.assertEqual(status, 400, b) + self.assertIn("messages must be a list of objects", b["error"]["message"]) + + def test_malformed_tools_are_a_400(self): + # #592: a "tools" value that is not a list of named tool objects is a 400 naming the field, on both APIs, + # not a dropped connection (an AttributeError/TypeError in the request thread) + msgs = [{"role": "user", "content": "hi"}] + bad = ("auto", ["get_weather"], [{"description": "no name"}], {"name": "x"}, + [{"type": "function", "function": "get_weather"}], [{"type": "function", "function": {"name": ""}}]) + for path in ("/v1/chat/completions", "/v1/messages"): + for tools in bad: + with self.subTest(path=path, tools=tools): + status, b = self.post(path, {"model": "x", "max_tokens": 8, "messages": msgs, "tools": tools}) + self.assertEqual(status, 400, b) + self.assertIn("tools", b["error"]["message"]) + status, b = self.post("/v1/chat/completions", {"model": "x", "max_tokens": 8, "messages": msgs}) + self.assertEqual(status, 200, b) # the server goes on + + def test_well_formed_tools_still_work(self): + msgs = [{"role": "user", "content": "hi"}] + fn = {"name": "get_weather", "description": "the weather", "parameters": {"type": "object", "properties": {}}} + for path, tools in (("/v1/chat/completions", [{"type": "function", "function": fn}]), + ("/v1/chat/completions", [fn]), # the bare shape some clients send + ("/v1/chat/completions", json.dumps([{"type": "function", "function": fn}])), + ("/v1/chat/completions", []), ("/v1/chat/completions", None), + ("/v1/messages", [{"name": "get_weather", "input_schema": {"type": "object"}}]), + ("/v1/messages", [])): + with self.subTest(path=path, tools=tools): + status, b = self.post(path, {"model": "x", "max_tokens": 8, "messages": msgs, "tools": tools}) + self.assertEqual(status, 200, b) + if tools: + self.assertIn("get_weather", self.prompt_text()) + + def test_vision_temp_image_removed_when_the_pipe_fails(self): + # #352: the temporary image goes even when the encoder's pipe raises + from serve.server import Vision + + class Gone: + def write(self, _): + raise BrokenPipeError("the encoder is gone") + + v = Vision.__new__(Vision) + v.dir, v.lock, v.cache = Path(tempfile.mkdtemp(prefix="strata-vision-test-")), threading.Lock(), {} + v.proc = mock.Mock(stdin=Gone()) + with mock.patch.object(Vision, "load", return_value=b""), mock.patch.object(Vision, "normalize", + return_value=b"png"): + with self.assertRaises(BrokenPipeError): + v.encode("x") + self.assertEqual(list(v.dir.iterdir()), []) + v.dir.rmdir() + + def test_leading_system_unchanged(self): + from serve.frontend import anthropic_to_messages, openai_to_messages + msgs, _, _ = openai_to_messages({"messages": [{"role": "developer", "content": "D"}, {"role": "user", "content": "u"}]}) + self.assertEqual([m["role"] for m in msgs], ["system", "user"]) + msgs, _, _ = anthropic_to_messages({"system": "S", "messages": [{"role": "user", "content": "u"}]}) + self.assertEqual([m["role"] for m in msgs], ["system", "user"]) + + def test_messages_sent_as_a_json_string(self): + # #460: a client that double-encodes "messages" (and "tool_calls") as a JSON string gets them decoded; what is + # still not a list of objects is a ValueError (the server's 400), not an AttributeError on m.get + from serve.frontend import anthropic_to_messages, openai_to_messages + call = [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{\"x\": 1}"}}] + listed = [{"role": "user", "content": "u"}, {"role": "assistant", "content": "", "tool_calls": call}] + encoded = [listed[0], dict(listed[1], tool_calls=json.dumps(call))] + want = openai_to_messages({"messages": listed})[0] + self.assertEqual(want[1]["tool_calls"], [{"function": {"name": "f", "arguments": {"x": 1}}}]) + self.assertEqual(openai_to_messages({"messages": json.dumps(listed)})[0], want) + self.assertEqual(openai_to_messages({"messages": json.dumps(encoded)})[0], want) + anth = [{"role": "user", "content": "u"}] + self.assertEqual(anthropic_to_messages({"messages": json.dumps(anth)})[0], + anthropic_to_messages({"messages": anth})[0]) + self.assertEqual(openai_to_messages({})[0], []) # no field: nothing, as before + self.assertEqual(openai_to_messages({"messages": None})[0], []) + for bad in ("not json", "\"a string\"", json.dumps({"role": "user"}), ["hi"], [{"role": "user"}, 3], 5, + {"role": "user", "content": "u"}): + for fn in (openai_to_messages, anthropic_to_messages): + with self.subTest(bad=bad, fn=fn.__name__): + with self.assertRaisesRegex(ValueError, "messages must be a list of objects"): + fn({"messages": bad}) + for calls in (["f"], "[1]", [{"function": "f"}], "{"): + with self.subTest(calls=calls), self.assertRaisesRegex(ValueError, "tool_calls must be a list of objects"): + openai_to_messages({"messages": [{"role": "assistant", "content": "", "tool_calls": calls}]}) + + +class SamplingKeys(unittest.TestCase): + """The GEN line's sampling keys: top_k 0 ("off") or wider than the engine's 64 get the widest list, 64 (they used + to fall back to the engine default 20); a penalty always carries its window.""" + + def keys(self, **sampling): + return StrataEngine.sampling_keys(sampling).split() + + def test_top_k(self): + self.assertIn("top_k=10", self.keys(temperature=0.7, top_k=10)) + self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=64)) + self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=0)) + self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=100)) + for bad in (-1, True, 2.5, "20"): + self.assertFalse([k for k in self.keys(temperature=0.7, top_k=bad) if k.startswith("top_k=")], bad) + + def test_tune_keys(self): + k = self.keys(temperature=0, strata_tune={"pcie_frac": 0.2, "spec_min_p": 0.7}) + self.assertIn("pcie_frac=0.2", k) + self.assertIn("spec_min_p=0.7", k) + bad = self.keys(strata_tune={"pcie_frac": 3, "spec_min_p": True, "pool_workers": 2}) + self.assertFalse([x for x in bad if x.split("=")[0] in ("pcie_frac", "spec_min_p", "pool_workers")]) + + def test_penalty_window(self): + self.assertIn("penalty_last_n=64", self.keys(presence_penalty=1.5)) + self.assertIn("penalty_last_n=4096", self.keys(repetition_penalty=1.1, penalty_last_n=4096)) + self.assertFalse([k for k in self.keys(temperature=0.7) if k.startswith("penalty")]) + + +class GpuChoice(unittest.TestCase): + """Issue #51: the config's \"gpu\" reaches the engine as CUDA_VISIBLE_DEVICES, numbered like nvidia-smi.""" + + def test_env(self): + from serve.server import child_env + env = child_env({"gpu": 1}) + self.assertEqual(env["CUDA_VISIBLE_DEVICES"], "1") + self.assertEqual(env["CUDA_DEVICE_ORDER"], "PCI_BUS_ID") + plain = child_env({}) # no choice: the environment as it was (existing installs) + self.assertEqual(plain.get("CUDA_VISIBLE_DEVICES"), os.environ.get("CUDA_VISIBLE_DEVICES")) + self.assertEqual(plain.get("CUDA_DEVICE_ORDER"), os.environ.get("CUDA_DEVICE_ORDER")) + + def test_vision_device(self): + # #408: the image encoder on its own card; the engine's environment stays as it was + from serve.server import child_env, vision_env + cfg = {"gpu": [0, 1], "vision": {"exe": "v", "cuda_device": 2}} + env = child_env(cfg) + venv = vision_env(cfg, env) + self.assertEqual(venv["CUDA_VISIBLE_DEVICES"], "2") + self.assertEqual(venv["CUDA_DEVICE_ORDER"], "PCI_BUS_ID") + self.assertEqual(env["CUDA_VISIBLE_DEVICES"], "0,1") + plain = {"gpu": [0, 1], "vision": {"exe": "v"}} + self.assertIs(vision_env(plain, env), env) # no cuda_device: the engine's environment, unchanged + + def test_hip_ordinal(self): + """#325: on Windows the HIP ordinal setup resolved wins over the config's "gpu" (an iGPU takes HIP's 0).""" + from serve.server import child_env + self.assertEqual(child_env({"backend": "hip", "gpu": 1})["HIP_VISIBLE_DEVICES"], "1") # Linux: KFD order + self.assertEqual(child_env({"backend": "hip", "hip_ordinal": 1})["HIP_VISIBLE_DEVICES"], "1") + self.assertEqual(child_env({"backend": "hip", "gpu": 0, "hip_ordinal": 1})["HIP_VISIBLE_DEVICES"], "1") + self.assertEqual(child_env({"backend": "hip", "gpu": [1, 0], "hip_ordinal": 2})["HIP_VISIBLE_DEVICES"], + "1,0") # a layer split keeps its list + self.assertEqual(child_env({"backend": "hip", "gpu": 0, "hip_ordinal": "x"})["HIP_VISIBLE_DEVICES"], "0") + plain = child_env({"backend": "hip"}) + self.assertEqual(plain.get("HIP_VISIBLE_DEVICES"), os.environ.get("HIP_VISIBLE_DEVICES")) + + +class RecordingPrompt(MockEngine): + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.last_ids = list(ids) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + +class DyingEngine(MockEngine): + """Issue #27: an engine that dies after a few tokens of its first answer, and comes back when restarted.""" + + def __init__(self, tok, script, max_context): + super().__init__(tok, script, max_context=max_context) + self.dead, self.restarts, self.die_after = False, 0, 5 + + def alive(self): + return not self.dead + + def restart(self): + self.dead, self.die_after = False, None + self.restarts += 1 + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if self.die_after is not None and i == self.die_after: + self.dead = True + raise EngineDied("the engine stopped unexpectedly (exit code -9)") + yield t + + +class SlowPromptEngine(MockEngine): + """Reads a "long prompt" for up to 20 s without a token (the engine sends nothing then), stopping on cancel.""" + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.cancelled_after = None + t0 = time.monotonic() + while time.monotonic() - t0 < 20: + if cancel.is_set(): + self.cancelled_after = time.monotonic() - t0 + return + time.sleep(0.05) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + +class ClientHangUp(unittest.TestCase): + """#430 #431: a client that hangs up during a long prompt read cancels the request within about a second - + non-streamed (which writes nothing until the end) and streamed (one keep-alive per prompt chunk) alike.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = SlowPromptEngine(tok, "\n\nOK", max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.port = cls.httpd.server_address[1] + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def hang_up(self, stream): + import socket as so + body = json.dumps({"model": "x", "max_tokens": 20, "stream": stream, + "messages": [{"role": "user", "content": "a long prompt"}]}).encode() + c = so.create_connection(("127.0.0.1", self.port)) + c.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n" + b"Content-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body) + time.sleep(1.0) + c.close() + t0 = time.monotonic() + while self.engine.cancelled_after is None and time.monotonic() - t0 < 10: + time.sleep(0.05) + self.assertIsNotNone(self.engine.cancelled_after, "the request was not cancelled") + self.assertLess(self.engine.cancelled_after, 3.0) + + def test_non_streamed(self): + self.hang_up(False) + + def test_streamed(self): + self.hang_up(True) + + +class EngineDeath(unittest.TestCase): + """Issue #27: a dead engine is an error (not "length"), and the next request starts it again.""" + + def test_error_then_restart(self): + tok = ByteTokenizer() + eng = DyingEngine(tok, "\n\n" + ANSWER, max_context=CTX) + svc = Service(eng, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + def post(body): + req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, r.read().decode() + except urllib.error.HTTPError as e: + with e: + return e.code, e.read().decode() + msgs = [{"role": "user", "content": "hi"}] + code, text = post({"model": "m", "messages": msgs, "max_tokens": 50, "stream": True}) + self.assertEqual(code, 200) + self.assertIn('"error"', text) + self.assertIn("stopped unexpectedly", text) + self.assertTrue(text.rstrip().endswith("data: [DONE]")) + self.assertEqual(svc.metrics()["requests"][0]["finish"], "error") + code, text = post({"model": "m", "messages": msgs, "max_tokens": 50}) + self.assertEqual(code, 200, text) + self.assertEqual(eng.restarts, 1) + self.assertEqual(json.loads(text)["usage"]["completion_tokens"], 50) + finally: + httpd.shutdown() + httpd.server_close() + + def test_engine_err_mid_stream(self): + """The engine's ERR line after the stream started reaches the client as an error event (it used to be a + 400 written into the open stream, which clients read as an empty answer).""" + class ErrEngine(MockEngine): + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + yield None # a prompt-progress heartbeat: the stream has started + raise ValueError("verify: layer 31 never rang (an illegal memory access was encountered)") + + tok = ByteTokenizer() + svc = Service(ErrEngine(tok, ANSWER, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + for path, body in [("/v1/chat/completions", {"model": "m", "stream": True, "max_tokens": 20, + "messages": [{"role": "user", "content": "hi"}]}), + ("/v1/messages", {"model": "m", "stream": True, "max_tokens": 20, + "messages": [{"role": "user", "content": "hi"}]})]: + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + text = r.read().decode() + self.assertIn("illegal memory access", text, path) + self.assertNotIn("HTTP/1", text, path) + self.assertEqual(svc.metrics()["requests"][0]["finish"], "error") + finally: + httpd.shutdown() + httpd.server_close() + + +class DoneLineEngine(MockEngine): + """The mock engine whose `last` comes from a DONE line, parsed as StrataEngine parses it.""" + + def __init__(self, *a, done_lines=(), **kw): + super().__init__(*a, **kw) + self.done_lines = list(done_lines) + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + try: + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + finally: + StrataEngine._parse_done(self, self.done_lines.pop(0)) + + +class DraftCounts(unittest.TestCase): + """#457: GET /metrics gives each request's speculative draft counts (offered / accepted, from the engine's DONE + line; None when the line has no such fields) and their running sums in the totals.""" + + def test_drafts_in_history_and_totals(self): + tok = ByteTokenizer() + engine = DoneLineEngine(tok, "\n\nok", max_context=CTX, done_lines=[ + "DONE 4 20 40.0 30.0 stop 7 12 0", # 7 of 12 drafts accepted + "DONE 4 20 40.0 30.0 stop", # an engine that reports no drafts + "DONE 4 20 40.0 30.0 stop 3 5 0 9 10"]) + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.assertEqual((svc.totals["drafts_offered"], svc.totals["drafts_accepted"]), (0, 0)) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + for _ in range(3): + body = json.dumps({"model": "m", "max_tokens": 10, "messages": [{"role": "user", "content": "hi"}]}) + with urllib.request.urlopen(urllib.request.Request(base + "/v1/chat/completions", data=body.encode(), + headers={"Content-Type": "application/json"}), + timeout=30) as r: + self.assertEqual(r.status, 200) + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + m = json.loads(r.read()) + finally: + httpd.shutdown() + httpd.server_close() + rows = m["requests"] # newest first + self.assertEqual([(r["drafts_offered"], r["drafts_accepted"]) for r in rows], [(5, 3), (None, None), (12, 7)]) + self.assertEqual((m["totals"]["drafts_offered"], m["totals"]["drafts_accepted"]), (17, 10)) + + +class PcieShare(unittest.TestCase): + """#588: the hit rate stays the VRAM share of the lookups; the routed experts the GPU read over PCIe (the DONE + line's 16th field, engine 0.1.39+) are given as their own share of all routed experts.""" + + def test_history(self): + tok = ByteTokenizer() + engine = DoneLineEngine(tok, "\n\nok", max_context=CTX, done_lines=[ + "DONE 4 20 40.0 30.0 stop 3 5 0 60 100 0 0 0.0 20 25", # 25 more over PCIe: 20% of 125 routed + "DONE 4 20 40.0 30.0 stop 3 5 0 60 100 0 0 0.0 20 0", + "DONE 4 20 40.0 30.0 stop 3 5 0 60 100 0 0 0.0 20"]) # an older engine + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + with contextlib.redirect_stdout(io.StringIO()) as out: + for _ in range(3): + list(svc.run(tok.encode("hi"), False, None, 10, {}, threading.Event())) + rows = list(svc.history) + self.assertEqual([r["hit_rate"] for r in rows], [0.6, 0.6, 0.6]) + self.assertEqual([r["pcie_share"] for r in rows], [0.2, 0.0, None]) + self.assertIn("expert cache 60.0% hit (+20.0% of the routed experts over PCIe)", out.getvalue()) + + +class LearnedProfile(unittest.TestCase): + """#477: "expert_profile_save" in the config: the engine saves its learned profile there, and the next start + begins from it when it is a profile of the same model; without the key the arguments are unchanged.""" + + def write(self, path, nl=48, ne=512, n=4): + sys.path.insert(0, str(ROOT / "tools")) + import make_profile + old = make_profile.N_LAYER + make_profile.N_LAYER = nl + try: + make_profile.write_profile(path, [(i % nl, i // nl) for i in range(n)], n_expert=ne) + finally: + make_profile.N_LAYER = old + + def test_without_the_key_nothing_changes(self): + args = ["--native", "x", "--expert-profile", "data/expert-profile.bin", "--adapt-every", "4"] + self.assertEqual(engine_args({"args": list(args)}), args) + self.assertEqual(engine_args({"args": list(args), "expert_profile_save": ""}), args) + + def test_save_and_start_from_it(self): + d = Path(tempfile.mkdtemp()) + self.write(d / "base.bin") + cfg = {"args": ["--expert-profile", "base.bin"], "cwd": str(d), "expert_profile_save": "learned.bin", + "expert_profile_save_every": 5} + # nothing saved yet: the config's profile, and the engine is told where to save + self.assertEqual(engine_args(cfg), ["--expert-profile", "base.bin", "--expert-profile-save", "learned.bin", + "--expert-profile-save-every", "5"]) + self.write(d / "learned.bin") + self.assertEqual(engine_args(cfg)[:2], ["--expert-profile", "learned.bin"]) + self.write(d / "learned.bin", ne=256) # another model's: not used + self.assertEqual(engine_args(cfg)[:2], ["--expert-profile", "base.bin"]) + (d / "learned.bin").write_bytes(b"STRP" + bytes(20)) # not a whole profile + self.assertEqual(engine_args(cfg)[:2], ["--expert-profile", "base.bin"]) + self.write(d / "learned.bin") + (d / "learned.bin").write_bytes((d / "learned.bin").read_bytes()[:30]) # truncated + self.assertEqual(engine_args(cfg)[:2], ["--expert-profile", "base.bin"]) + + def test_no_profile_in_the_args(self): + cfg = {"args": ["--native", "x"], "expert_profile_save": "learned.bin"} + self.assertEqual(engine_args(cfg), ["--native", "x", "--expert-profile-save", "learned.bin"]) + + +class RepeatStop(unittest.TestCase): + """#606: one token repeated repeat_stop_tokens times in a row ends the reply as "length"; 0 turns it off.""" + + def run_reply(self, script, limit=None): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + if limit is not None: + svc.repeat_stop_tokens = limit + ids = tok.encode("hi") + with contextlib.redirect_stdout(io.StringIO()) as out: + done = [x for kind, x in svc.run(ids, False, None, 3000, {}, threading.Event()) if kind == "done"][0] + return done, out.getvalue() + + def test_a_long_run_is_ended(self): + done, log = self.run_reply("ok " + "!" * 1000 + " never") + self.assertEqual(done["finish"], "length") + self.assertEqual(done["completion_tokens"], 3 + 256) + self.assertIn("repeated one token ('!') 256 times", log) + + def test_short_runs_and_off(self): + done, _ = self.run_reply("=" * 255 + " fine") + self.assertEqual(done["finish"], "stop") + done, log = self.run_reply("!" * 1000, limit=0) + self.assertEqual((done["finish"], done["completion_tokens"]), ("stop", 1001)) + self.assertNotIn("repeated one token", log) + done, _ = self.run_reply("ab" * 400, limit=8) # alternating tokens are not one run + self.assertEqual(done["finish"], "stop") + + +class LayerSplit(unittest.TestCase): + """#644: "layer_split" is the first layer of each later GPU; a list is accepted, counts per card are not.""" + + def cfg(self, split, gpus=(2, 0, 1, 3)): + c = {"args": ["--native", "x"], "gpu": list(gpus)} + if split is not ...: + c["layer_split"] = split + return c + + def test_auto_and_absent(self): + for v in (..., None, "", "auto", "AUTO"): + self.assertEqual(engine_args(self.cfg(v))[-2:], ["--layer-split", "auto"]) + + def test_string_and_list(self): + self.assertEqual(engine_args(self.cfg("24,36,42"))[-2:], ["--layer-split", "24,36,42"]) + self.assertEqual(engine_args(self.cfg(" 24, 36 ,42 "))[-2:], ["--layer-split", "24,36,42"]) + self.assertEqual(engine_args(self.cfg([24, 36, 42]))[-2:], ["--layer-split", "24,36,42"]) + self.assertEqual(engine_args(self.cfg(18, gpus=(0, 1)))[-2:], ["--layer-split", "18"]) + self.assertEqual(engine_args(self.cfg([18], gpus=(0, 1)))[-2:], ["--layer-split", "18"]) + + def test_counts_per_card_are_refused_with_the_format(self): + for bad in ("24,16,12,12", [24, 16, 12, 12], "24,16,12", "24,36", "x", [24.5, 30, 40], "1,20,30", [True]): + with self.assertRaises(ValueError) as e: + layer_split_value(self.cfg(bad)) + self.assertIn("first layer of each later GPU", str(e.exception)) + self.assertIn('"12,24,36"', str(e.exception)) # the example for 4 GPUs + + def test_one_gpu_ignores_it(self): + self.assertEqual(engine_args({"args": ["--native", "x"], "gpu": [0], "layer_split": "24,16"}), + ["--native", "x"]) + + +class DraftHeadHint(unittest.TestCase): + """#474: a start that stopped at "the draft head does not fit" says what to change, from this start's log lines.""" + + def log(self, text, before=""): + d = tempfile.mkdtemp() + p = Path(d) / "engine.log" + p.write_text(before + text, encoding="utf-8") + return str(p), len(before.encode()) + + def test_the_engines_hint_is_relayed(self): + p, off = self.log("strata mtp: the draft head over 106299 tokens needs 348 MiB of VRAM and 120 MiB is free.\n" + "strata mtp: hint: a smaller draft vocabulary needs less VRAM: --draft-vocab en (...)\n" + "strata serve: mtp: the draft head does not fit\n") + h = start_failure_hint(p, off) + self.assertIn("the draft head does not fit", h) + self.assertIn("348 MiB", h) + self.assertIn("--draft-vocab en", h) + + def test_an_older_engine_gets_the_advice_in_words(self): + p, off = self.log("strata serve: mtp: the draft head does not fit\n") + self.assertIn("--draft-vocab en", start_failure_hint(p, off)) + + def test_other_failures_and_earlier_starts_add_nothing(self): + p, off = self.log("strata serve: cannot open the pack\n") + self.assertEqual(start_failure_hint(p, off), "") + # an earlier start's failure (before this start's offset) is not this one's + p, off = self.log("strata serve: cannot open the pack\n", + before="strata serve: mtp: the draft head does not fit\n") + self.assertEqual(start_failure_hint(p, off), "") + self.assertEqual(start_failure_hint(None, 0), "") + self.assertEqual(start_failure_hint(str(Path(tempfile.mkdtemp()) / "missing.log"), 0), "") + + +class DesktopVramNote(unittest.TestCase): + """#560 #516: an AMD card on a Linux desktop with little VRAM left after the start gets a recommended reserve.""" + + def test_when_it_applies(self): + from serve.server import desktop_vram_note + note = desktop_vram_note("hip", 624, ["--kv", "int8"], True) + self.assertIn("624 MiB of VRAM free", note) + self.assertIn("--vram-reserve-mib 3072", note) + self.assertIn("2.3 GB less", note) + + def test_when_it_does_not(self): + from serve.server import desktop_vram_note + self.assertEqual(desktop_vram_note(None, 624, [], True), "") # NVIDIA + self.assertEqual(desktop_vram_note("hip", 624, [], False), "") # no desktop session + self.assertEqual(desktop_vram_note("hip", 2994, [], True), "") # room left + self.assertEqual(desktop_vram_note("hip", None, [], True), "") # lazy start: no INFO yet + self.assertEqual(desktop_vram_note("hip", 900, ["--vram-reserve-mib", "4000"], True), "") # already raised + + def test_desktop_detection(self): + from serve import server + with mock.patch.object(server.os, "name", "posix"), mock.patch.object(server.sys, "platform", "linux"): + self.assertTrue(server.linux_desktop({"WAYLAND_DISPLAY": "wayland-0"})) + self.assertFalse(server.linux_desktop({})) + + +class StartFailureLog(unittest.TestCase): + """#496: whatever stopped the engine before READY, the error carries this start's last log lines.""" + + def test_the_last_lines_of_this_start(self): + from serve.server import start_log_tail + d = tempfile.mkdtemp() + p = Path(d) / "engine.log" + before = "strata serve: an earlier start's line\n" + p.write_text(before + "".join(f"strata serve: line {i}\n" for i in range(30)) + "\n" + "strata serve: cannot open the pack\n", encoding="utf-8") + tail = start_log_tail(str(p), len(before.encode())) + self.assertIn("the engine log's last lines:", tail) + self.assertIn("cannot open the pack", tail) + self.assertIn("line 29", tail) + self.assertNotIn("line 10\n", tail + "\n") # 20 lines: 11..29 and the last one + self.assertIn("line 11", tail) + self.assertNotIn("earlier start", tail) + short = start_log_tail(str(p), len(before.encode()), n=3) + self.assertEqual(short.count("\n "), 3) + self.assertEqual(start_log_tail(str(p), p.stat().st_size), "") # nothing from this start + self.assertEqual(start_log_tail(None, 0), "") + self.assertEqual(start_log_tail(str(Path(d) / "missing.log"), 0), "") + + def test_the_start_error_has_them(self): + import serve.server as server + fake = "import sys\nsys.stderr.write('strata serve: cannot open the pack packs/x\\n')\nsys.exit(2)\n" + with tempfile.TemporaryDirectory() as d: + script, log = Path(d) / "fake_strata.py", Path(d) / "strata.log" + script.write_text(fake, encoding="utf-8") + log.write_text("an earlier start\n", encoding="utf-8") + real = server.subprocess.Popen + with mock.patch.object(server.subprocess, "Popen", + lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)), \ + mock.patch.object(server, "narrate_start", lambda *a, **k: None): + with self.assertRaises(RuntimeError) as cm: + StrataEngine("strata", [], log=str(log)) + text = str(cm.exception) + self.assertIn("exited before it was ready", text) + self.assertIn("cannot open the pack packs/x", text) + self.assertNotIn("an earlier start", text) + + +class StartNarrator(unittest.TestCase): + """#505: the start's words say what happens to the experts - --mmap-experts loads nothing into RAM up front.""" + + def test_the_words_follow_the_flags(self): + from serve.server import experts_loading_words + self.assertIn("loading the experts into RAM (about 38 GB)", experts_loading_words([], "about 38 GB")) + mapped = experts_loading_words(["--mmap-experts"], "about 47 GB") + self.assertIn("mapping the experts from the model files (about 47 GB", mapped) + self.assertIn("not loaded into RAM", mapped) + self.assertIn("the GPU does not hold", experts_loading_words(["--resident-experts"], "about 47 GB")) + budget = experts_loading_words(["--mmap-experts", "--resident-budget-gib", "71"], "about 50 GB") + self.assertIn("up to 71 GiB", budget) + self.assertNotIn("about 50 GB", budget) + + def narrate(self, args, lines): + import contextlib + import io + from serve.server import narrate_start + d = tempfile.mkdtemp() + log = Path(d) / "engine.log" + log.write_text("".join(x + "\n" for x in lines), encoding="utf-8") + done, out = threading.Event(), io.StringIO() + with contextlib.redirect_stdout(out): + t = threading.Thread(target=narrate_start, args=(str(log), 0, args, done)) + t.start() + time.sleep(0.8) + done.set() + t.join(5) + return out.getvalue() + + def test_a_mapped_start(self): + said = self.narrate(["--mmap-experts"], ["strata generate: experts via mmap (--mmap-experts; the GGUF shards " + "in place, no experts.bin)"]) + self.assertIn("mapping the experts from the model files", said) + self.assertNotIn("loading the experts into RAM", said) + + def test_an_arena_start(self): + said = self.narrate([], ["strata generate: expert arena: resident, 31.64 GiB", + "strata generate: loaded 31.64 GiB at 3.17 GiB/s"]) + self.assertIn("loading the experts into RAM (tens of GB)", said) + self.assertIn("experts loaded: 31.64 GiB at 3.17 GiB/s", said) + + +class CancelledRead(unittest.TestCase): + """#471: a request cancelled while its prompt was read is recorded with the tokens the engine read (the DONE + line's 15th field), not the whole prompt; an older engine's line (no such field) keeps the whole prompt.""" + + def test_parse_done_read_field(self): + e = SimpleNamespace() + StrataEngine._parse_done(e, "DONE 0 98179 17565.0 0.0 cancel 0 0 0 0 0 0 0 0.0 12288") + self.assertEqual((e.last["prompt_tokens"], e.last["prompt_read"], e.last["finish"]), (98179, 12288, "cancel")) + StrataEngine._parse_done(e, "DONE 0 98179 17565.0 0.0 cancel 0 0 0 0 0 0 0 0.0") + self.assertNotIn("prompt_read", e.last) + + def test_prompt_tokens_seen(self): + last = {"finish": "cancel", "reused": 1000, "prompt_read": 2000} + self.assertEqual(prompt_tokens_seen(98179, last), 3000) + self.assertEqual(prompt_tokens_seen(98179, {**last, "finish": "stop"}), 98179) # read in full: all of it + self.assertEqual(prompt_tokens_seen(98179, {"finish": "cancel", "reused": 0}), 98179) # an older engine + self.assertEqual(prompt_tokens_seen(98179, {}), 98179) # no DONE at all + self.assertEqual(prompt_tokens_seen(10, {**last, "prompt_read": 50}), 10) # never past the prompt + + def test_history_and_totals(self): + tok = ByteTokenizer() + engine = DoneLineEngine(tok, "\n\nok", max_context=CTX, done_lines=[ + "DONE 0 20 400.0 0.0 cancel 0 0 0 0 0 0 0 0.0 8", # stopped after 8 prompt tokens + "DONE 4 20 40.0 30.0 stop 0 0 0 0 0 0 0 0.0 20", + "DONE 0 20 400.0 0.0 cancel 0 0 0"]) # an older engine: no read count + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + for _ in range(3): + body = json.dumps({"model": "m", "max_tokens": 10, "messages": [{"role": "user", "content": "hi"}]}) + with urllib.request.urlopen(urllib.request.Request(base + "/v1/chat/completions", data=body.encode(), + headers={"Content-Type": "application/json"}), + timeout=30) as r: + self.assertEqual(r.status, 200) + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + m = json.loads(r.read()) + finally: + httpd.shutdown() + httpd.server_close() + rows = m["requests"][::-1] # oldest first + total = rows[0]["prompt_total"] + self.assertGreater(total, 8) + self.assertEqual([r["prompt_total"] for r in rows], [total] * 3) + self.assertEqual([(r["prompt_tokens"], r["prompt_read"]) for r in rows], [(8, 8), (total, 20), (total, None)]) + self.assertEqual(m["totals"]["prompt_tokens"], 8 + 2 * total) + + +class LiveRate(unittest.TestCase): + """The Monitor's Speed readout: live.tok_s is a rate, and a request that never got a DONE keeps no counters. + + It used to be `generated / (now - first_token)` - the mean since the first token, whose first sample is + 1/elapsed. Against a paced engine that reads five-digit numbers for the first instant of every answer and + undershoots for the first second after that. It is now the rate over the last RATE_WINDOW_S, with the mean + still available as `live.tok_s_mean` for anyone who wants it.""" + + PACE_S = 0.02 # 50 tokens/s: a 30-token answer takes about 0.6 s + TOKENS = 30 + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = MockEngine(self.tok, "x" * self.TOKENS, max_context=CTX, delay_s=self.PACE_S) + self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def metrics(self): + with urllib.request.urlopen(self.base + "/metrics", timeout=10) as r: + return json.loads(r.read()) + + def test_prefill_rate_excludes_cached_tokens(self): + import io + import queue + from types import SimpleNamespace + engine = StrataEngine.__new__(StrataEngine) + engine.proc = SimpleNamespace(stdin=io.StringIO(), poll=lambda: None) # alive() asks it (#208) + engine.lines = queue.Queue() + engine.can_stop = False + engine.max_context = 262144 + engine.prefill_tok_s_mean = 9999.0 + engine.lines.put("PP 10000 12000 2000 1000.0") # 8000 cached, 2000 newly read in two seconds + engine.lines.put("DONE 1 12000 4000 10 stop 0 0 8000") + gen = engine.generate([1], 1, {}, threading.Event()) + self.assertIsNone(next(gen)) + self.assertEqual(engine.progress, (10000, 12000)) + self.assertEqual(engine.prefill_tok_s_mean, 1000.0) + self.svc.engine = engine + self.svc.status.update(busy=True, first_token=None) + self.assertEqual(self.metrics()["live"]["prefill_tok_s_mean"], 1000.0) + self.assertNotIn("prefill_tok_s", self.metrics()["live"]) + self.assertEqual(self.svc._prefill_tok_s_mean(), 1000.0) + self.svc.status.update(first_token=time.time(), generated=1) + self.assertEqual(self.svc._prefill_tok_s_mean(), 0.0) + self.assertEqual(list(gen), []) + timings = request_timings(12000, 1, engine.last) + self.assertEqual(timings["prompt_per_second"], 1000.0) + engine.lines.put("PP 8000 12000") + engine.lines.put("DONE 0 12000 0 0 stop 0 0 12000") + gen = engine.generate([1], 1, {}, threading.Event()) + next(gen) + self.assertIsNone(engine.prefill_tok_s_mean) + list(gen) + self.svc.status["busy"] = False + self.assertIsNone(self.metrics()["live"]["prefill_tok_s_mean"]) + + def test_the_live_number_is_a_rate(self): + live_samples, stop = [], threading.Event() + + def poll(): # what the Monitor polls, at 10 ms + while not stop.is_set(): + live = self.metrics()["live"] + if live["state"] == "generating" and live["tok_s"] is not None: + live_samples.append((live["generated"], live["tok_s"], live["tok_s_mean"])) + time.sleep(0.01) + + body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "temperature": 0, + "messages": [{"role": "user", "content": "hi"}]}).encode() + watcher = threading.Thread(target=poll, daemon=True) + watcher.start() + t0 = time.time() + try: + with urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}), + timeout=30) as r: + usage = json.loads(r.read())["usage"] + finally: + stop.set() + watcher.join(2) + true_rate = usage["completion_tokens"] / (time.time() - t0) + self.assertGreaterEqual(len(live_samples), 3, "too few live readings to judge the readout") + self.assertLess(max(s for _g, s, _m in live_samples), 4 * true_rate, + f"live.tok_s peaked at {max(s for _g, s, _m in live_samples):.1f} tok/s " + f"for a {true_rate:.1f} tok/s engine") + self.assertEqual(self.metrics()["live"]["state"], "idle") + self.assertIsNone(self.metrics()["live"]["tok_s"]) + + def test_a_request_without_a_done_keeps_no_engine_counters(self): + """An engine that dies mid-answer: the previous request's `last` must not become this row's decode rate.""" + class HalfDead(MockEngine): + last = {"generated": 99, "prompt_tokens": 9, "prompt_ms": 10.0, "decode_ms": 100.0, "finish": "stop"} + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if i == 3: + raise EngineDied("the engine stopped unexpectedly (exit code -9)") + yield t + + tok = ByteTokenizer() + svc = Service(HalfDead(tok, "x" * self.TOKENS, max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "stream": True, + "messages": [{"role": "user", "content": "hi"}]}).encode() + with urllib.request.urlopen(urllib.request.Request(base + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}), + timeout=30) as r: + text = r.read().decode() + self.assertIn('"error"', text) + row = svc.metrics()["requests"][0] + self.assertEqual(row["finish"], "error") + self.assertEqual(row["output_tokens"], 3) + self.assertIsNone(row["decode_tok_s"], "the previous request's counters were recorded as this one's") + self.assertIsNone(row["engine_generated"]) + finally: + httpd.shutdown() + httpd.server_close() + + +class SharedSettings(unittest.TestCase): + """The web app's "Use for other apps too": POST /settings makes its Chat settings every client's defaults.""" + + @classmethod + def setUpClass(cls): + import tempfile + + class Sampled(RecordingEngine): + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.last_sampling = dict(sampling or {}) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + tok = ByteTokenizer() + cls.engine = Sampled(tok, "\n\nhello", max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.tmp = tempfile.TemporaryDirectory() + cls.svc.shared_path = os.path.join(cls.tmp.name, "strata-x.shared-settings.json") + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + cls.tmp.cleanup() + + def req(self, path, body, headers=None, raw=None): + h = {"Content-Type": "application/json", **(headers or {})} + r = urllib.request.Request(self.base + path, data=raw if raw is not None else json.dumps(body).encode(), headers=h) + try: + with urllib.request.urlopen(r, timeout=30) as resp: + return resp.status, json.loads(resp.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def chat(self, **extra): + return self.req("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}], **extra}) + + def tearDown(self): + self.svc.set_shared(None) + + def test_other_apps_get_the_chat_settings(self): + d = {"temperature": 0.3, "top_p": 0.9, "top_k": 10, "seed": 7, "max_tokens": 77, + "reasoning_effort": "low", "experimental_speed_projection": False} + code, b = self.req("/settings", {"defaults": d}) + self.assertEqual(code, 200, b) + self.assertTrue(b["shared"]) + self.assertTrue(os.path.exists(self.svc.shared_path)) + code, _ = self.chat() # a client that sets nothing + self.assertEqual(code, 200) + got = self.engine.last_sampling + for k in ("temperature", "top_p", "top_k", "seed", "experimental_speed_projection"): + self.assertEqual(got[k], d[k], k) + self.assertEqual(self.engine.last_max_new, 77) + code, _ = self.chat(temperature=0.9, max_tokens=5) # its own values win + self.assertEqual(self.engine.last_sampling["temperature"], 0.9) + self.assertEqual(self.engine.last_max_new, 5) + r = self.svc.with_shared({"messages": []}, "openai") + self.assertEqual(r["reasoning_effort"], "low") + self.assertEqual(self.svc.with_shared({"reasoning_effort": "high"}, "openai")["reasoning_effort"], "high") + self.assertEqual(self.svc.with_shared({}, "anthropic")["output_config"], {"effort": "low"}) + + def test_off_again(self): + self.req("/settings", {"defaults": {"temperature": 0.3}}) + code, b = self.req("/settings", {"defaults": None}) + self.assertEqual((code, b["shared"]), (200, False)) + self.assertFalse(os.path.exists(self.svc.shared_path)) + self.chat() + self.assertNotIn("temperature", self.engine.last_sampling) + + def test_only_strata_s_own_page_may_set_them(self): + code, _ = self.req("/settings", None, {"Content-Type": "text/plain"}, raw=b'{"defaults": {"temperature": 1}}') + self.assertEqual(code, 415) + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://evil.example"}) + self.assertEqual(code, 403) + code, b = self.req("/settings", {"defaults": {"temperature": 9}}) + self.assertEqual(code, 400) + self.assertIn("temperature", b["error"]["message"]) + self.assertEqual(self.svc.shared, {}) + host = self.base.split("://", 1)[1] + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://" + host}) + self.assertEqual(code, 200) + + def test_they_need_the_key_when_one_is_set(self): + self.svc.api_key = "secret" + try: + self.assertEqual(self.req("/settings", {"defaults": {"temperature": 1}})[0], 401) + self.assertEqual(self.req("/settings", {"defaults": {"temperature": 1}}, + {"Authorization": "Bearer secret"})[0], 200) + finally: + self.svc.api_key = "" + + def test_proxy_headers_do_not_make_a_page_strata_s_own(self): + # #321: X-Forwarded-*, CF-Ray or CF-Connecting-IP say nothing about the page that sent the request - any web + # page behind any proxy would otherwise change the settings (or run MCP tools) + for extra in ({"X-Forwarded-Host": "proxy.example.com"}, {"CF-Ray": "1234567890"}, + {"X-Forwarded-For": "203.0.113.9"}, {"CF-Connecting-IP": "203.0.113.9"}): + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, + {"Origin": "https://proxy.example.com", **extra}) + self.assertEqual(code, 403, extra) + # another port on the same host is another site (a local dev server's page) + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://127.0.0.1:1"}) + self.assertEqual(code, 403) + + def test_a_trusted_origin_is_strata_s_own_page(self): + # the web app behind a reverse proxy or tunnel: the config's trusted_origins + self.svc.trusted_origins = ["https://strata.example.com"] + try: + code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://strata.example.com"}) + self.assertEqual(code, 200) + code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://evil.example.com"}) + self.assertEqual(code, 403) + finally: + self.svc.trusted_origins = [] + + +class WebApp(unittest.TestCase): + """The web app (PR #22's dashboard idea, rebuilt): its page and files, and GET /metrics.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(RecordingEngine(tok, "\n\nhello", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + + def get(self, path, headers=None): + req = urllib.request.Request(self.base + path, headers=headers or {}) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, r.headers.get("Content-Type", ""), r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers.get("Content-Type", ""), e.read() + + def test_page_and_files(self): + code, ctype, body = self.get("/") + self.assertEqual(code, 200) + self.assertIn("text/html", ctype) + self.assertIn(b"\"web/app.js\"", body) # relative since #82 (works behind a path-prefixed proxy) + for path, want in (("/web/app.js", "javascript"), ("/web/app.css", "text/css"), ("/web/tokens.css", "text/css"), + ("/web/components.css", "text/css"), ("/web/sprite.svg", "image/svg+xml")): + with self.subTest(path=path): + code, ctype, _ = self.get(path) + self.assertEqual(code, 200) + self.assertIn(want, ctype) + + def test_only_the_app_files_are_served(self): + for path in ("/web/..%2Fserver.py", "/web/index.html", "/web/test.py", "/fonts/..%2F..%2Fsetup.py", + "/fonts/missing.woff2", "/fonts/x.ttf"): + with self.subTest(path=path): + self.assertEqual(self.get(path)[0], 404) + + def test_metrics(self): + data = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 5}).encode() + urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=data, + headers={"Content-Type": "application/json"}), timeout=10).read() + code, ctype, body = self.get("/metrics") + self.assertEqual(code, 200) + m = json.loads(body) + for key in ("engine", "live", "requests", "hardware", "hardware_static", "history"): + self.assertIn(key, m) + self.assertEqual(m["engine"]["max_context"], CTX) + self.assertEqual(m["live"]["state"], "idle") + self.assertEqual(m["requests"][0]["output_tokens"], 5) + + def test_model_discovery_and_props(self): + svc = self.svc + previous = svc.engine.max_context, svc.vision, svc.sampling_defaults, svc.shared + try: + svc.engine.max_context = 262144 + svc.sampling_defaults = {"temperature": 1.0, "repetition_penalty": 1.1} + svc.shared = {"temperature": 0.7, "max_tokens": 4096} + for vision in (None, object()): + svc.vision = vision + for path in ("/models", "/v1/models"): + code, _, body = self.get(path) + self.assertEqual(code, 200) + models = json.loads(body)["data"] + self.assertEqual(len(models), 1) + model = models[0] + self.assertEqual(model["id"], svc.model) + self.assertEqual(model["status"]["value"], "loaded") + self.assertEqual(model["meta"]["n_ctx"], 262144) + self.assertEqual(model["architecture"]["input_modalities"], + ["text", "image"] if vision else ["text"]) + code, _, body = self.get("/props?model=" + svc.model + "&autoload=false") + self.assertEqual(code, 200) + props = json.loads(body) + self.assertEqual(props["default_generation_settings"]["n_ctx"], 262144) + self.assertEqual(props["default_generation_settings"]["params"], + {"temperature": 0.7, "repeat_penalty": 1.1, "n_predict": 4096}) + self.assertEqual(props["chat_template"], (ROOT / "serve/chat_template.jinja").read_text(encoding="utf-8")) + self.assertEqual(props["modalities"]["vision"], vision is not None) + self.assertEqual(props["total_slots"], 1) + self.assertFalse(props["models_autoload"]) + svc.shared = {} + props = json.loads(self.get("/props")[2]) + self.assertEqual(props["default_generation_settings"]["params"]["n_predict"], -1) + self.assertEqual(self.get("/props?model=not-loaded&autoload=true")[0], 404) + finally: + svc.engine.max_context, svc.vision, svc.sampling_defaults, svc.shared = previous + + def test_discovery_needs_the_api_key(self): + self.svc.api_key = "secret" + try: + for path in ("/models", "/v1/models", "/props", "/slots"): + self.assertEqual(self.get(path)[0], 401) + self.assertEqual(self.get(path, {"Authorization": "Bearer secret"})[0], 200) + finally: + self.svc.api_key = "" + + def test_build_model_path_and_slot_status(self): + engine = self.svc.engine + engine.model_path = "models/example.gguf" + engine.info = {"version": "0.1.21"} + try: + props = json.loads(self.get("/props")[2]) + self.assertEqual(props["model_path"], engine.model_path) + self.assertEqual(props["build_info"], "Strata 0.1.21") + for busy in (True, False): + with self.svc.status_lock: + self.svc.status["busy"] = busy + code, _, body = self.get("/slots") + self.assertEqual(code, 200) + self.assertEqual(json.loads(body), [{"id": 0, "n_ctx": CTX, "is_processing": busy}]) + finally: + with self.svc.status_lock: + self.svc.status["busy"] = False + del engine.model_path, engine.info + props = json.loads(self.get("/props")[2]) + self.assertNotIn("build_info", props) + self.assertNotIn("model_path", props) + + def test_discovery_does_not_restart_a_dead_engine(self): + self.svc.engine.alive = lambda: False + try: + for path in ("/models", "/v1/models"): + code, _, body = self.get(path) + self.assertEqual(code, 200) + self.assertEqual(json.loads(body)["data"], []) + self.assertEqual(self.get("/props")[0], 503) + self.assertEqual(json.loads(self.get("/slots")[2]), []) + finally: + del self.svc.engine.alive + + def test_metrics_need_the_key_when_one_is_set(self): + self.svc.api_key = "secret" + try: + self.assertEqual(self.get("/metrics")[0], 401) + self.assertEqual(self.get("/metrics", {"Authorization": "Bearer secret"})[0], 200) + self.assertEqual(self.get("/")[0], 200) # the page itself asks for the key + finally: + self.svc.api_key = "" + + +class ClockedEngine(MockEngine): + """The mock engine with StrataEngine's clock: `last` as the engine's DONE line gives it, the conversation cache + holding the first REUSED tokens of every prompt.""" + REUSED = 5 + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + n = 0 + try: + for t in super().generate(ids, max_new, sampling, cancel, embeddings): + n += 1 + yield t + finally: # as StrataEngine reads its DONE line: also when the server closes the request at a stop token + self.last = {"generated": n, "prompt_tokens": len(ids), "prompt_ms": 40.0, "decode_ms": 20.0 * n, + "finish": "stop", "reused": min(self.REUSED, len(ids)), "hits": 9, "lookups": 10} + + +class UsageAndStatus(unittest.TestCase): + """What clients read besides the text: the part of the prompt the conversation cache held (OpenAI's + prompt_tokens_details.cached_tokens, Anthropic's cache_read_input_tokens), llama.cpp's timings, GET /v1/status.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = ClockedEngine(tok, "\n\nok", max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def request(self, path, body=None): + req = urllib.request.Request(self.base + path, data=None if body is None else json.dumps(body).encode(), + headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, r.read() + + def chat(self, path, stream=False): + body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}], "stream": stream} + status, raw = self.request(path, body) + self.assertEqual(status, 200) + if not stream: + return json.loads(raw) + return [json.loads(line[6:]) for line in raw.decode().splitlines() + if line.startswith("data: {")] + + def preflight(self, path, origin="https://chat.example.com"): + req = urllib.request.Request(self.base + path, method="OPTIONS", + headers={"Origin": origin, "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "authorization, content-type"}) + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, r.headers + + def test_cors_is_off_by_default(self): + # #321: OPTIONS is answered, but without cors_origins no page of another origin is let in + status, h = self.preflight("/v1/chat/completions") + self.assertEqual(status, 204) + self.assertIsNone(h.get("Access-Control-Allow-Origin")) + with urllib.request.urlopen(self.base + "/health", timeout=10) as r: + self.assertIsNone(r.headers.get("Access-Control-Allow-Origin")) + + def test_cors_for_the_configured_origins_on_the_api_only(self): + self.svc.cors_origins = ["https://chat.example.com"] + try: + status, h = self.preflight("/v1/chat/completions") + self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (204, "https://chat.example.com")) + self.assertIn("OPTIONS", h.get("Access-Control-Allow-Methods", "")) + self.assertIn("authorization", h.get("Access-Control-Allow-Headers", "")) + self.assertIsNone(self.preflight("/v1/chat/completions", "https://evil.example.com")[1] + .get("Access-Control-Allow-Origin")) + # never on the app's own endpoints (/settings, /unload, ...) + self.assertIsNone(self.preflight("/settings")[1].get("Access-Control-Allow-Origin")) + req = urllib.request.Request(self.base + "/v1/models", headers={"Origin": "https://chat.example.com"}) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "https://chat.example.com") + self.svc.cors_origins = ["*"] + self.assertEqual(self.preflight("/v1/messages", "https://any.example.com")[1] + .get("Access-Control-Allow-Origin"), "*") + finally: + self.svc.cors_origins = [] + + def test_sse_is_not_buffered_by_proxies(self): + req = urllib.request.Request(self.base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"model": "m", "stream": True, + "messages": [{"role": "user", "content": "hi"}]}).encode()) + with urllib.request.urlopen(req, timeout=30) as r: + self.assertEqual(r.headers.get("X-Accel-Buffering"), "no") + r.read() + + def test_origin_lists_are_checked(self): + from serve.server import origins_of + self.assertEqual(origins_of(None, "k", True), []) + self.assertEqual(origins_of("https://a.example.com/", "k", False), ["https://a.example.com"]) + self.assertEqual(origins_of(["*", "http://localhost:3000"], "k", True), ["*", "http://localhost:3000"]) + for bad in ("*", "a.example.com", "https://a.example.com/path", "https://*.example.com", 5): + with self.assertRaises(SystemExit): + origins_of(bad, "k", False) + + def test_openai(self): + b = self.chat("/v1/chat/completions") + u, t = b["usage"], b["timings"] + self.assertEqual(u["prompt_tokens_details"]["cached_tokens"], ClockedEngine.REUSED) + self.assertEqual(t["cache_n"], ClockedEngine.REUSED) + self.assertEqual(t["prompt_n"] + t["cache_n"], u["prompt_tokens"]) + self.assertEqual(t["predicted_n"], u["completion_tokens"]) + self.assertAlmostEqual(t["prompt_per_second"], t["prompt_n"] / 0.040, delta=0.1) + self.assertAlmostEqual(t["predicted_per_second"], 50.0, delta=0.1) # 20 ms a token + + def test_openai_stream(self): + last = self.chat("/v1/chat/completions", stream=True)[-1] + self.assertEqual(last["usage"]["prompt_tokens_details"]["cached_tokens"], ClockedEngine.REUSED) + self.assertEqual(last["timings"]["cache_n"], ClockedEngine.REUSED) + + def test_anthropic(self): + u = self.chat("/v1/messages")["usage"] + self.assertEqual(u["cache_read_input_tokens"], ClockedEngine.REUSED) + self.assertEqual(u["input_tokens"] + u["cache_read_input_tokens"], len(self.engine.last_prompt)) + self.assertGreater(u["output_tokens"], 0) + + def test_v1_status(self): + self.chat("/v1/chat/completions") + status, raw = self.request("/v1/status") + self.assertEqual(status, 200) + s = json.loads(raw) + self.assertEqual(s["model"], self.svc.model) + self.assertEqual(s["context"]["max_positions"], CTX) + self.assertEqual(s["concurrency"]["serving"], 1) + self.assertFalse(s["vision"]["available"]) + self.assertEqual(s["activity"]["in_flight"], 0) + self.assertGreaterEqual(s["activity"]["requests"], 1) + self.assertEqual(s["last_timings"]["cache_n"], ClockedEngine.REUSED) + self.assertIn("at", s["last_timings"]) + + def test_no_clock(self): + """An engine without a clock (MockEngine): no timings, nothing cached.""" + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + try: + data = json.dumps({"model": "x", "max_tokens": 5, "messages": [{"role": "user", "content": "hi"}]}).encode() + req = urllib.request.Request(f"http://127.0.0.1:{httpd.server_address[1]}/v1/chat/completions", data=data, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + b = json.loads(r.read()) + self.assertNotIn("timings", b) + self.assertEqual(b["usage"]["prompt_tokens_details"]["cached_tokens"], 0) + self.assertIsNone(svc.v1_status()["last_timings"]) + finally: + httpd.shutdown() + httpd.server_close() + + +class TimingsDrafts(unittest.TestCase): + """`timings` carries the speculative draft counts (PR #83's fields) only when the engine reported them.""" + + def test_draft_fields(self): + base = {"prompt_ms": 100.0, "decode_ms": 200.0, "generated": 20, "reused": 4} + t = request_timings(24, 20, dict(base, drafts_offered=15, drafts_accepted=11)) + self.assertEqual((t["draft_n"], t["draft_n_accepted"]), (15, 11)) + self.assertEqual((t["prompt_n"], t["cache_n"]), (20, 4)) + self.assertNotIn("draft_n", request_timings(24, 20, base)) + self.assertIsNone(request_timings(24, 20, {})) + + +class UnloadableEngine(MockEngine): + """A mock engine that can be stopped and started again like StrataEngine (alive / unload / restart).""" + + def __init__(self, *a, **kw): + super().__init__(*a, **kw) + self.running, self.unloaded, self.starts = True, False, 0 + + def alive(self): + return self.running + + def unload(self): + self.running, self.unloaded = False, True + + def restart(self): + self.running, self.unloaded = True, False + self.starts += 1 + + +class SharingTheGpu(unittest.TestCase): + """Idle unload, POST /unload and /load, the free-VRAM guard and the before_load hook (all off by default).""" + + def setUp(self): + tok = ByteTokenizer() + self.engine = UnloadableEngine(tok, "\n\nok", max_context=CTX) + self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def req(self, path, body=None): + r = urllib.request.Request(self.base + path, data=None if body is None else json.dumps(body).encode(), + headers={"Content-Type": "application/json"}, method="GET" if body is None else "POST") + try: + with urllib.request.urlopen(r, timeout=30) as resp: + return resp.status, json.loads(resp.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def chat(self): + return self.req("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}]}) + + def test_unload_then_the_next_request_loads(self): + self.assertEqual(self.req("/unload", {}), (200, {"status": "unloaded"})) + self.assertFalse(self.engine.alive()) + self.assertEqual(self.req("/health")[1]["loaded"], False) + self.assertEqual(self.req("/v1/models")[1]["data"][0]["status"]["value"], "unloaded") + self.assertEqual(self.req("/unload", {}), (200, {"status": "not loaded"})) + s, b = self.chat() + self.assertEqual(s, 200) + self.assertEqual(b["choices"][0]["message"]["content"], "ok") + self.assertEqual(self.engine.starts, 1) + self.assertEqual(self.req("/health")[1]["loaded"], True) + + def test_load_endpoint(self): + self.svc.unload() + self.assertEqual(self.req("/load", {}), (200, {"status": "loaded"})) + self.assertTrue(self.engine.alive()) + self.assertEqual(self.req("/load", {}), (200, {"status": "loaded"})) + self.assertEqual(self.engine.starts, 1) + + def test_unload_refused_while_a_request_runs(self): + with self.svc.fifo: + self.assertEqual(self.svc.unload(), "busy") + self.assertTrue(self.engine.alive()) + + def test_idle_unload(self): + self.svc.idle_unload_s = 1 + self.svc.last_request_at = time.time() + self.assertEqual(self.svc.unload(idle_for=1), "busy") # a request just now: not idle yet + self.svc.start_idle_unload() + deadline = time.time() + 10 + while self.engine.alive() and time.time() < deadline: + time.sleep(0.1) + self.assertFalse(self.engine.alive()) + self.assertEqual(self.chat()[0], 200) + + def test_min_free_vram_refuses_to_load(self): + self.svc.min_free_vram_mib = 8000 + self.svc.free_vram_mib = lambda: 2000 + self.svc.unload() + t0 = time.time() + s, b = self.chat() + self.assertEqual(s, 503) + self.assertIn("in use by another program", b["error"]["message"]) + self.assertFalse(self.engine.alive()) + self.assertGreater(time.time() - t0, 10) # waited for memory being given back first + self.svc.free_vram_mib = lambda: 9000 + self.assertEqual(self.chat()[0], 200) + + def test_min_free_vram_unreadable_loads(self): + self.svc.min_free_vram_mib = 8000 + self.svc.free_vram_mib = lambda: None # no NVML: never refuse + self.svc.unload() + self.assertEqual(self.chat()[0], 200) + + def test_before_load_runs_first(self): + mark = Path(tempfile.mkdtemp()) / "ran" + self.svc.before_load = [sys.executable, "-c", f"open({str(mark)!r}, 'w').close()"] + self.svc.unload() + self.assertFalse(mark.exists()) + self.assertEqual(self.chat()[0], 200) + self.assertTrue(mark.exists()) + + def test_vision_encoder_unloads_and_starts_first(self): + order = [] + + class FakeVision: + running = True + + def alive(self): + return self.running + + def unload(self): + self.running = False + + def restart(self): + order.append("vision") + self.running = True + + engine_restart = self.engine.restart + self.engine.restart = lambda: (order.append("engine"), engine_restart()) + self.svc.vision = FakeVision() + self.assertEqual(self.svc.unload(), "unloaded") + self.assertFalse(self.svc.vision.alive()) + self.assertEqual(self.chat()[0], 200) + self.assertEqual(order, ["vision", "engine"]) # the encoder first, as at a start + self.assertTrue(self.svc.vision.alive()) + + def test_off_by_default(self): + self.assertEqual((self.svc.idle_unload_s, self.svc.min_free_vram_mib, self.svc.before_load), (0, 0, None)) + self.assertEqual(self.req("/health")[1]["loaded"], True) + + +class ThinkingEngine(MockEngine): + """Thinks THOUGHT, then answers; a prompt that already ends its thinking (the budget's wrap-up) gets the answer + at once, the way the model continues after . Records every prompt it is given.""" + THOUGHT = "Let me think step by step about two plus two. " * 4 # 184 reasoning tokens (one per byte) + ANSWER = "The answer is 4." + + def __init__(self, tok): + super().__init__(tok, "x", max_context=CTX) + self.prompts = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.prompts.append(list(ids)) + done = self.tok.decode(ids).endswith("\n\n") + text = self.ANSWER if done else self.THOUGHT + "\n\n" + self.ANSWER + for t in (self.tok.encode(text) + self.tok.encode("<|im_end|>", parse_special=True))[:max_new]: + if cancel.is_set(): + return + yield t + + +class ThinkingBudget(unittest.TestCase): + """#123: reasoning_budget_tokens (opt-in): at the budget the thinking is wrapped up and the model answers, + continuing from the prompt plus what it generated plus the wrap-up (a prefix the engine already holds).""" + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = ThinkingEngine(self.tok) + self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def post(self, path, body): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={ + "Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + return r.status, (json.loads(raw) if not body.get("stream") else raw) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def openai(self, **extra): + return self.post("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "2+2?"}], + "max_tokens": 400, **extra}) + + def test_off_by_default(self): + code, b = self.openai() + self.assertEqual(code, 200, b) + msg = b["choices"][0]["message"] + self.assertEqual((msg["reasoning_content"], msg["content"]), (ThinkingEngine.THOUGHT, ThinkingEngine.ANSWER)) + self.assertEqual(len(self.engine.prompts), 1) + + def test_the_budget_wraps_up_the_thinking(self): + from serve.server import REASONING_WRAP_UP + code, b = self.openai(reasoning_budget_tokens=20) + self.assertEqual(code, 200, b) + msg = b["choices"][0]["message"] + wrap = REASONING_WRAP_UP.split("")[0] + self.assertEqual(msg["reasoning_content"], ThinkingEngine.THOUGHT[:20] + wrap) + self.assertEqual(msg["content"], ThinkingEngine.ANSWER) + self.assertEqual(b["choices"][0]["finish_reason"], "stop") + first, second = self.engine.prompts + extra = self.tok.encode(REASONING_WRAP_UP, parse_special=True) + self.assertEqual(second, first + self.tok.encode(ThinkingEngine.THOUGHT[:20]) + extra) # a prefix + more + self.assertEqual(b["usage"]["completion_tokens"], 20 + len(extra) + len(ThinkingEngine.ANSWER) + 1) + self.assertEqual(b["usage"]["prompt_tokens"], len(first)) + + def test_anthropic_stream(self): + from serve.server import REASONING_WRAP_UP + code, raw = self.post("/v1/messages", {"model": "m", "max_tokens": 400, "stream": True, + "reasoning_budget_tokens": 30, + "messages": [{"role": "user", "content": "2+2?"}]}) + self.assertEqual(code, 200) + evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + thinking = "".join(e["delta"].get("thinking", "") for e in evs if e["type"] == "content_block_delta") + text = "".join(e["delta"].get("text", "") for e in evs if e["type"] == "content_block_delta") + self.assertEqual(thinking, ThinkingEngine.THOUGHT[:30] + REASONING_WRAP_UP.split("")[0]) + self.assertEqual(text, ThinkingEngine.ANSWER) + self.assertEqual(evs[-2]["delta"]["stop_reason"], "end_turn") + + def test_a_budget_the_thinking_stays_under(self): + code, b = self.openai(reasoning_budget_tokens=10_000) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT) + self.assertEqual(len(self.engine.prompts), 1) + + def test_the_config_default_and_a_request_that_turns_it_off(self): + self.svc.reasoning_budget_tokens = 20 + code, b = self.openai() + self.assertEqual(len(self.engine.prompts), 2) + self.assertTrue(b["choices"][0]["message"]["reasoning_content"].startswith(ThinkingEngine.THOUGHT[:20] + "\n")) + code, b = self.openai(reasoning_budget_tokens=0) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT) + self.assertEqual(len(self.engine.prompts), 3) + + def test_without_thinking_there_is_nothing_to_limit(self): + self.engine.THOUGHT = "" + code, b = self.openai(reasoning_budget_tokens=5, reasoning_effort="none") + self.assertEqual(code, 200, b) + self.assertEqual(len(self.engine.prompts), 1) + + def test_no_room_left_to_answer(self): + code, b = self.openai(reasoning_budget_tokens=20, max_tokens=40) # 20 thought + the wrap-up > 40 + self.assertEqual(b["choices"][0]["finish_reason"], "length") + self.assertEqual(len(self.engine.prompts), 1) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT[:20]) + + def test_a_reply_cut_while_thinking_is_named_in_the_log(self): + """#530: max tokens reached inside the thinking gives an empty answer; the server log says what helps.""" + hint = "reached max tokens while still thinking" + for extra, said in (({"max_tokens": 10}, True), ({}, False)): + with self.subTest(extra=extra): + out = io.StringIO() + with contextlib.redirect_stdout(out): + code, b = self.openai(**extra) + self.assertEqual(code, 200, b) + self.assertEqual(b["choices"][0]["finish_reason"], "length" if said else "stop") + self.assertEqual(hint in out.getvalue(), said, out.getvalue()) + if said: + self.assertIn("reasoning_budget_tokens", out.getvalue()) + + def test_a_bad_value_is_a_400(self): + for bad in ("lots", 2.5, True, [1]): + with self.subTest(value=bad): + code, b = self.openai(reasoning_budget_tokens=bad) + self.assertEqual(code, 400) + self.assertIn("reasoning_budget_tokens", b["error"]["message"]) + self.assertEqual(self.engine.prompts, []) + + +class StatusHandover(unittest.TestCase): + """#266: a stream aborted mid-way and the next request, which was waiting for the fifo. The aborted request's + status/history block ran after the fifo was released, so the waiting request could start in that gap: the old + request then recorded the NEW request's status as its own, set busy=False and popped `tail`, and the new request + crashed in _note (KeyError 'tail'). The fifo below lets the waiting request run to its first token as soon as + it is released, before the releasing thread goes on - the worst case of that gap, every time.""" + + def test_abort_then_the_next_request(self): + tok = ByteTokenizer() + second_running = threading.Event() + + class Engine(MockEngine): + calls = 0 + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + Engine.calls += 1 + me = Engine.calls + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if me == 2 and i == 2: + second_running.set() # the second request has its status and two tokens noted + yield t + + class SlowRelease: + """A Lock whose release waits (briefly) until the thread it let in has started generating.""" + + def __init__(self): + self.lock, self.armed = threading.Lock(), False + + def acquire(self, blocking=True): + return self.lock.acquire(blocking) + + def __enter__(self): + self.lock.acquire() + + def __exit__(self, *exc): + self.lock.release() + if self.armed: + self.armed = False + second_running.wait(5) + + def release(self): + self.lock.release() + + svc = Service(Engine(tok, "\n\n" + "y" * 40, max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc.fifo = SlowRelease() + ids = tok.encode("hi") + first = svc.run(ids, True, None, 30, {}, threading.Event()) + for _ in range(5): + next(first) # mid-answer + out, errors = [], [] + + def second(): + try: + out.extend(svc.run(ids, True, None, 20, {}, threading.Event())) + except Exception as e: # noqa: BLE001 - the crash this test is about + errors.append(e) + + waiter = threading.Thread(target=second) + waiter.start() + deadline = time.time() + 5 + while svc.status.get("queued") != 1 and time.time() < deadline: + time.sleep(0.005) + self.assertEqual(svc.status.get("queued"), 1, "the second request never queued") + svc.fifo.armed = True + first.close() # the client went away: GeneratorExit in the first request + waiter.join(10) + self.assertFalse(waiter.is_alive()) + self.assertEqual(errors, []) + self.assertEqual(out[-1][0], "done") + self.assertEqual(out[-1][1]["completion_tokens"], 20) + rows = list(svc.history) + self.assertEqual([r["finish"] for r in rows], ["disconnect", "length"]) + self.assertTrue(0 < rows[0]["output_tokens"] < 30, rows) # where the first one stopped, not the second's + self.assertEqual(rows[1]["output_tokens"], 20) + self.assertEqual(svc.totals["requests"], 2) + self.assertEqual(svc.totals["output_tokens"], rows[0]["output_tokens"] + 20) + self.assertFalse(svc.status["busy"]) + self.assertNotIn("tail", svc.status) + + +FAKE_STRATA = '''import pathlib, sys, time +gate = pathlib.Path(sys.argv[sys.argv.index("--gate") + 1]) +print("INFO engine=0.0.0", flush=True) +while not gate.exists(): # the test says when the engine is "ready" + time.sleep(0.01) +print("READY 4096 stop", flush=True) +for line in sys.stdin: + if line.startswith("QUIT"): + break +''' + +FAKE_STRATA_FAIL_ONCE = '''import pathlib, sys, time +fail = pathlib.Path(sys.argv[sys.argv.index("--fail") + 1]) +if fail.exists(): # this start fails before READY (as one next to a dying engine did) + fail.unlink() + sys.exit(1) +''' + FAKE_STRATA.split("\n", 1)[1] + + +class RestartWindow(unittest.TestCase): + """#344: while the engine restarts it is not alive (a request waits for the restart instead of reading + max_context 0), and a request that still meets max_context 0 gets a 503 "starting", not a 400 about its prompt.""" + + def test_not_alive_until_ready(self): + from unittest import mock + import serve.server as server + with tempfile.TemporaryDirectory() as d: + script, gate = Path(d) / "fake_strata.py", Path(d) / "ready" + script.write_text(FAKE_STRATA, encoding="utf-8") + real = server.subprocess.Popen + with mock.patch.object(server.subprocess, "Popen", + lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)): + gate.touch() + eng = StrataEngine("strata", ["--gate", str(gate)]) + try: + self.assertEqual(eng.max_context, 4096) + self.assertTrue(eng.alive()) + gate.unlink() + old = eng.proc + old.kill() + old.wait(10) + deadline = time.time() + 10 + while not getattr(eng, "ended", False) and time.time() < deadline: + time.sleep(0.01) # the server has noticed: its output closed + self.assertFalse(eng.alive()) + t = threading.Thread(target=eng.restart) + t.start() + deadline = time.time() + 10 + while eng.proc is old and time.time() < deadline: + time.sleep(0.005) + self.assertIsNot(eng.proc, old, "restart never started the engine") + time.sleep(0.2) # the new engine is up, but has not said READY + self.assertEqual(eng.max_context, 0) + self.assertFalse(eng.alive(), "alive before READY: a request would plan with context 0") + gate.touch() + t.join(10) + self.assertFalse(t.is_alive()) + self.assertTrue(eng.alive()) + self.assertEqual(eng.max_context, 4096) + # restart() of a running engine kills it first: that engine's output thread ends after the new + # one is up, and must not mark it dead (it did: every request after restarted it again) + eng.restart() + time.sleep(0.5) + self.assertTrue(eng.alive()) + self.assertEqual(eng.max_context, 4096) + finally: + gate.touch() + eng.unload() + + def test_restart_retries_a_start_that_fails(self): + """A dead engine's VRAM is freed only when its process is gone, so a new engine started at once can exit + before READY; restart() tries again (3 times) instead of leaving the server with max_context 0.""" + from unittest import mock + import serve.server as server + with tempfile.TemporaryDirectory() as d: + script, gate, fail = Path(d) / "fake_strata.py", Path(d) / "ready", Path(d) / "fail_once" + script.write_text(FAKE_STRATA_FAIL_ONCE, encoding="utf-8") + real = server.subprocess.Popen + with mock.patch.object(server.subprocess, "Popen", + lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)), \ + mock.patch.object(StrataEngine, "RESTART_RETRY_S", 0.0): + gate.touch() + eng = StrataEngine("strata", ["--gate", str(gate), "--fail", str(fail)]) + try: + self.assertEqual(eng.max_context, 4096) + self.assertEqual(eng.known_ctx, 4096) + fail.touch() # the next start exits before READY, the one after works + eng.proc.kill() + eng.proc.wait(10) + eng.restart() + self.assertFalse(fail.exists(), "the failing start never ran") + self.assertTrue(eng.alive()) + self.assertEqual(eng.max_context, 4096) + self.assertFalse(eng.starting) + finally: + gate.touch() + eng.unload() + + def test_failed_restart_keeps_the_known_context(self): + """After a restart that failed, max_context is 0 but the engine is not starting: a request is checked against + the last known context and reaches run() (which starts the engine again), not a 400 about context 0.""" + tok = ByteTokenizer() + eng = MockEngine(tok, "\n\nok", max_context=0) + eng.known_ctx, eng.starting = 4096, False + svc = Service(eng, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + req = urllib.request.Request(base + "/v1/chat/completions", + data=json.dumps({"model": "m", "max_tokens": 16, + "messages": [{"role": "user", "content": "hi"}]}).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + self.assertEqual(r.status, 200) + finally: + httpd.shutdown() + + def test_context_zero_is_503(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "\n\nok", max_context=0), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + for path, body in (("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}], + "max_tokens": 16}), + ("/v1/messages", {"model": "m", "max_tokens": 16, + "messages": [{"role": "user", "content": "hi"}]})): + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with self.assertRaises(urllib.error.HTTPError) as cm: + urllib.request.urlopen(req, timeout=30) + with cm.exception as e: + self.assertEqual(e.code, 503, path) + text = e.read().decode() + self.assertIn("starting", text) + self.assertNotIn("leaves no room", text) + finally: + httpd.shutdown() + httpd.server_close() + + +class ModelAliases(unittest.TestCase): + """#297: the config's `aliases` are listed by /v1/models and accepted as model names (answered under that name).""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja"), model_name="qwen3.8-flash-next-iq3_xxs") + cls.svc.set_aliases(["qwen", "local-model", "qwen", " ", "qwen3.8-flash-next-iq3_xxs"]) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def get(self, path): + with urllib.request.urlopen(self.base + path, timeout=30) as r: + return json.loads(r.read()) + + def post(self, path, body): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + return r.read().decode() + + def test_set_aliases(self): + self.assertEqual(self.svc.aliases, ["qwen", "local-model"]) # duplicates, blanks and the name itself + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "x", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc.set_aliases("a, b") + self.assertEqual(svc.aliases, ["a", "b"]) + svc.set_aliases(None) + self.assertEqual(svc.aliases, []) + for bad in (3, ["a", 1], {"a": 1}): + with self.assertRaises(ValueError): + svc.set_aliases(bad) + + def test_models_lists_them(self): + data = self.get("/v1/models")["data"] + self.assertEqual([m["id"] for m in data], ["qwen3.8-flash-next-iq3_xxs", "qwen", "local-model"]) + self.assertEqual(data[0]["aliases"], ["qwen", "local-model"]) + self.assertEqual(data[1]["alias_of"], "qwen3.8-flash-next-iq3_xxs") + self.assertEqual(self.get("/props?model=local-model")["model_alias"], "qwen3.8-flash-next-iq3_xxs") + + def test_requests_are_answered_under_the_alias(self): + msgs = [{"role": "user", "content": "hi"}] + for asked, want in (("qwen", "qwen"), ("local-model", "local-model"), + ("qwen3.8-flash-next-iq3_xxs", "qwen3.8-flash-next-iq3_xxs"), + ("something-else", "qwen3.8-flash-next-iq3_xxs")): # still served, as before + with self.subTest(asked=asked): + out = json.loads(self.post("/v1/chat/completions", {"model": asked, "messages": msgs, "max_tokens": 8})) + self.assertEqual(out["model"], want) + text = self.post("/v1/chat/completions", {"model": asked, "messages": msgs, "max_tokens": 8, + "stream": True}) + first = json.loads(text.split("data: ", 2)[1].strip()) + self.assertEqual(first["model"], want) + out = json.loads(self.post("/v1/messages", {"model": asked, "messages": msgs, "max_tokens": 8})) + self.assertEqual(out["model"], want) + + def test_without_aliases_nothing_changes(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "x", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + try: + with urllib.request.urlopen(f"http://127.0.0.1:{httpd.server_address[1]}/v1/models", timeout=30) as r: + data = json.loads(r.read())["data"] + self.assertEqual(len(data), 1) + self.assertNotIn("aliases", data[0]) + self.assertEqual(svc.model_for({"model": "x"}), svc.model) + finally: + httpd.shutdown() + httpd.server_close() + + +class AmdTelemetry(unittest.TestCase): + """#301: the AMD backend's readings from a fake amdgpu sysfs tree: KFD node -> render node, as setup numbers the + cards (the CPU node skipped), and free_vram_mib on HIP.""" + + def tree(self, d): + nodes = Path(d) / "class/kfd/kfd/topology/nodes" + for n, props in ((0, "cpu_cores_count 16\nsimd_count 0\ngfx_target_version 0\ndrm_render_minor 0\n"), + (1, "simd_count 128\ngfx_target_version 120001\ndrm_render_minor 129\n"), + (2, "simd_count 128\ngfx_target_version 120001\ndrm_render_minor 128\n")): + (nodes / str(n)).mkdir(parents=True) + (nodes / str(n) / "properties").write_text(props) + for minor, used, busy, temp, power in ((129, 2 << 30, 37, 51000, 85000000), (128, 6 << 30, 99, 64000, None)): + dev = Path(d) / f"class/drm/renderD{minor}/device" + hw = dev / "hwmon" / "hwmon4" + hw.mkdir(parents=True) + (dev / "gpu_busy_percent").write_text(f"{busy}\n") + (dev / "mem_info_vram_used").write_text(f"{used}\n") + (dev / "mem_info_vram_total").write_text(f"{32 << 30}\n") + (dev / "product_name").write_text("AMD Radeon AI PRO R9700\n") + (hw / "temp1_input").write_text(f"{temp}\n") + if power is not None: + (hw / "power1_average").write_text(f"{power}\n") + else: + (hw / "power1_input").write_text("120000000\n") + (hw / "power1_cap").write_text("300000000\n") + + def test_readings(self): + from serve import telemetry + with tempfile.TemporaryDirectory() as d: + self.tree(d) + with mock.patch.object(telemetry, "SYSFS", d): + self.assertTrue(telemetry.amd_device_dir(0).endswith(os.path.join("renderD129", "device"))) + self.assertTrue(telemetry.amd_device_dir(1).endswith(os.path.join("renderD128", "device"))) + self.assertIsNone(telemetry.amd_device_dir(2)) + g = telemetry.gpu_reader(0, amd=True) + self.assertTrue(g.ok()) + self.assertEqual(g.name(), "AMD Radeon AI PRO R9700") + self.assertEqual(g.read(), {"util": 37, "mem_used": 2 << 30, "mem_total": 32 << 30, "temp": 51.0, + "power": 85.0, "power_limit": 300.0}) + r = telemetry.gpu_reader(1, amd=True).read() + self.assertEqual((r["util"], r["temp"], r["power"]), (99, 64.0, 120.0)) # power1_input + self.assertEqual(telemetry.free_vram_mib(0, amd=True), 30 << 10) + self.assertIsNone(telemetry.free_vram_mib(5, amd=True)) + t = telemetry.Telemetry(gpu_index=0, gpu_indices=[0, 1], amd=True) + s = t.sample() + self.assertEqual(t.static["gpu_name"], "AMD Radeon AI PRO R9700 + AMD Radeon AI PRO R9700") + self.assertEqual((s["gpu_mem_used"], s["gpu_util"], s["gpu_temp"], s["gpu_power"]), + (8 << 30, 68.0, 64.0, 205.0)) + with tempfile.TemporaryDirectory() as d: # no amdgpu: nothing, and nothing breaks + with mock.patch.object(telemetry, "SYSFS", d): + self.assertFalse(telemetry.gpu_reader(0, amd=True).ok()) + self.assertIsNone(telemetry.free_vram_mib(0, amd=True)) + + def test_free_vram_on_hip(self): + from serve import telemetry + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "x", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc.backend, svc.gpu_index = "hip", 1 + with tempfile.TemporaryDirectory() as d: + self.tree(d) + with mock.patch.object(telemetry, "SYSFS", d): + self.assertEqual(svc.free_vram_mib(), 26 << 10) + + +class SilentEngine(unittest.TestCase): + """#481: an engine that prints nothing for engine_silence_s during a request (or never acknowledges a STOP) has + lost step with the server: it is ended and the request fails with EngineDied, instead of waiting forever.""" + + def bare(self, silence, can_stop=False): + import io + import queue + engine = StrataEngine.__new__(StrataEngine) + engine.proc = mock.Mock() + engine.proc.stdin = io.StringIO() + engine.proc.poll.return_value = None + engine.lines, engine.can_stop, engine.max_context = queue.Queue(), can_stop, 4096 + engine.silence_s, engine.log_path = silence, None + return engine + + def later(self, engine, delay, *lines): + def put(): + time.sleep(delay) + for x in lines: + engine.lines.put(x) + threading.Thread(target=put, daemon=True).start() + + def test_silence_mid_answer_ends_the_engine(self): + from serve.server import EngineSilent + engine = self.bare(0.3) + engine.lines.put("T 5") + gen = engine.generate([1], 10, {}, threading.Event()) + self.assertEqual(next(gen), 5) + t0 = time.monotonic() + with self.assertRaises(EngineSilent) as cm: + next(gen) + self.assertIsInstance(cm.exception, EngineDied) # every EngineDied path handles it + self.assertLess(time.monotonic() - t0, 5) + engine.proc.kill.assert_called_once() + self.assertFalse(engine.alive()) # the next request restarts it + self.assertIn("#481", engine.death_note()) + self.assertNotIn("STOP", engine.proc.stdin.getvalue()) # nothing is listening: no STOP, no drain + + def test_prompt_chunks_set_the_wait(self): + # a PP line every second, at 100 tok/s: far over a 0.3 s silence, but each chunk is on time for its size + engine = self.bare(0.3) + engine.lines.put("RESUME 0") + engine.lines.put("PP 100 300 1000 100.0") + self.later(engine, 1.0, "PP 200 300 2000 100.0", "T 7", "DONE 1 300 2000 1 length") + self.assertEqual(list(engine.generate([1], 10, {}, threading.Event())), [None, None, 7]) + engine.proc.kill.assert_not_called() + + def test_a_long_first_chunk_is_allowed(self): + # 100 prompt tokens at the slowest prompt reading (50 tok/s): 2 s on top of the silence before the first PP + engine = self.bare(0.3) + self.later(engine, 1.0, "PP 100 100 1000 100.0", "DONE 0 100 1000 0 length") + self.assertEqual(list(engine.generate([1] * 100, 10, {}, threading.Event())), [None]) + engine.proc.kill.assert_not_called() + + def test_a_stop_never_acknowledged(self): + from serve.server import EngineSilent + engine = self.bare(0.3, can_stop=True) + engine.lines.put("T 5") + gen = engine.generate([1], 10, {}, threading.Event()) + self.assertEqual(next(gen), 5) + with self.assertRaises(EngineSilent): + gen.close() # the consumer stopped: STOP, then the drain + self.assertIn("STOP", engine.proc.stdin.getvalue()) + engine.proc.kill.assert_called_once() + self.assertFalse(engine.alive()) + + def test_zero_waits_as_before(self): + engine = self.bare(0) + self.later(engine, 0.5, "T 5", "DONE 1 1 1 1 length") + self.assertEqual(list(engine.generate([1], 10, {}, threading.Event())), [5]) + + def test_config(self): + from serve.server import ENGINE_SILENCE_S, engine_silence_s + self.assertEqual(engine_silence_s({}), ENGINE_SILENCE_S) + self.assertEqual(engine_silence_s({"engine_silence_s": 0}), 0.0) + self.assertEqual(engine_silence_s({"engine_silence_s": 900}), 900.0) + for bad in (-1, "300", True): + with self.assertRaises(ValueError): + engine_silence_s({"engine_silence_s": bad}) + + +FAKE_LOST_STEP = '''import pathlib, sys, time +mark = pathlib.Path(sys.argv[sys.argv.index("--mark") + 1]) +mode = sys.argv[sys.argv.index("--mode") + 1] +print("READY 4096 stop", flush=True) +for line in sys.stdin: + if line.startswith("QUIT"): + break + if line.startswith("GEN"): + if not mark.exists(): # the first engine loses step (#481): it never says DONE + mark.touch() + print("T 104", flush=True) + if mode == "stop": + print("T 257", flush=True) # <|im_end|>: the server STOPs and drains, and the engine is silent + time.sleep(3600) + print("T 111", flush=True) + print("T 107", flush=True) + print("DONE 2 5 1.0 1.0 length", flush=True) +''' + + +class LostStep(unittest.TestCase): + """#481 over HTTP, with a real process: the request with the silent engine ends with an error, and the next one + starts the engine again and is answered (the server used to wait forever, holding the request FIFO).""" + + def run_mode(self, mode, stream): + import serve.server as server + with tempfile.TemporaryDirectory() as d: + script, mark = Path(d) / "fake_strata.py", Path(d) / "lost" + script.write_text(FAKE_LOST_STEP, encoding="utf-8") + real = server.subprocess.Popen + with mock.patch.object(server.subprocess, "Popen", + lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)): + eng = StrataEngine("strata", ["--mark", str(mark), "--mode", mode]) + eng.silence_s = 0.5 + tok = ByteTokenizer() + svc = Service(eng, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + body = {"model": "m", "max_tokens": 2, "reasoning_effort": "none", "stream": stream, + "messages": [{"role": "user", "content": "hi"}]} + try: + first = eng.proc + req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=60) as r: + text = r.read().decode() + except urllib.error.HTTPError as e: + self.assertEqual(e.code, 503) + text = e.read().decode() + self.assertIn("the next request restarts it", text) + self.assertIsNotNone(first.poll(), "the silent engine still runs") + self.assertEqual(svc.history[-1]["finish"], "error") + with urllib.request.urlopen(req, timeout=60) as r: + text = r.read().decode() + self.assertIsNot(eng.proc, first) + if stream: + answer = "".join(json.loads(x[6:])["choices"][0]["delta"].get("content") or "" + for x in text.splitlines() if x.startswith("data: {") and "choices" in x) + else: + answer = json.loads(text)["choices"][0]["message"]["content"] + self.assertEqual(answer, "ok") + finally: + httpd.shutdown() + httpd.server_close() + eng.unload() + + def test_silent_mid_answer(self): + self.run_mode("silent", stream=False) + + def test_silent_mid_stream(self): + self.run_mode("silent", stream=True) + + def test_stop_never_acknowledged(self): + self.run_mode("stop", stream=False) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_structured.py b/serve/test_structured.py new file mode 100644 index 0000000..cc157a7 --- /dev/null +++ b/serve/test_structured.py @@ -0,0 +1,167 @@ +"""Exercise the JSON contract through HTTP, including H3's strict Story shape.""" +import json +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve import structured +from serve.server import ByteTokenizer, MockEngine, Service, serve + +try: + import jsonschema # noqa: F401 + HAVE_JSONSCHEMA = True +except ImportError: # optional: json_schema answers are then only checked to be one object + HAVE_JSONSCHEMA = False + + +STORY = {"title": "Photobooth", "sheet": "A single continuous shot.", "cast": [], + "boxes": [{"box": 1, "duration_ms": 15000, "new_shot": True, "beat": "Hailee changes poses.", + "on_screen": ["Hailee"], "references": [], "ends": "She smiles."}], "suggestions": []} + + +def object_schema(properties): + return {"type": "object", "properties": properties, "required": list(properties), "additionalProperties": False} + + +TEXT = {"type": "string"} +STORY_SCHEMA = object_schema({ + "title": TEXT, "sheet": TEXT, "cast": {"type": "array", "items": object_schema({"name": TEXT, + "references": {"type": "array", "items": TEXT, "maxItems": 0}})}, + "boxes": {"type": "array", "minItems": 1, "maxItems": 1, "items": object_schema({ + "box": {"type": "integer", "minimum": 1, "maximum": 1}, + "duration_ms": {"type": "integer", "minimum": 1, "maximum": 15000}, "new_shot": {"type": "boolean"}, + "beat": TEXT, "on_screen": {"type": "array", "items": TEXT}, + "references": {"type": "array", "items": TEXT, "maxItems": 0}, "ends": TEXT})}, + "suggestions": {"type": "array", "items": object_schema({"what": TEXT, "why": TEXT, + "boxes": {"type": "array", "items": {"type": "integer"}}, "description": TEXT})}}) +FORMAT = {"type": "json_schema", "json_schema": {"name": "h3_story", "strict": True, "schema": STORY_SCHEMA}} + + +class Structured(unittest.TestCase): + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + data = response.read().decode() + return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data) + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = MockEngine(self.tok, json.dumps(STORY), max_context=16384) + self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def chat(self, script=None, **kwargs): + if script is not None: + self.engine = self.svc.engine = MockEngine(self.tok, script, max_context=16384) + req = {"messages": [{"role": "system", "content": "Write a film plan."}, + {"role": "user", "content": "Photobooth. 15 seconds."}], + "response_format": FORMAT, "reasoning_effort": "none", **kwargs} + return self.request("/v1/chat/completions", req) + + def test_h3_schema_success_and_stream_with_reasoning(self): + code, reply = self.chat() + self.assertEqual(code, 200) + self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]), STORY) + prompt = self.tok.decode(self.engine.last_prompt) + self.assertIn("OUTPUT FORMAT REQUIREMENT", prompt) + self.assertIn('"duration_ms"', prompt) + code, raw = self.chat("Consider the shot.\n" + json.dumps(STORY), stream=True, reasoning_effort="low") + self.assertEqual(code, 200) + chunks = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + content = "".join(c["choices"][0]["delta"].get("content", "") for c in chunks) + self.assertEqual(json.loads(content), STORY) + self.assertIn("reasoning_content", raw) + self.assertIn("data: [DONE]", raw) + + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") + def test_invalid_generation_is_an_error_and_never_streams_content(self): + for script in ("## Film Plan - Photobooth", '{"title":"Only a title"}', + json.dumps({**STORY, "extra": True}), + json.dumps({**STORY, "boxes": [{**STORY["boxes"][0], "duration_ms": "15000"}]})): + with self.subTest(script=script): + code, reply = self.chat(script) + self.assertEqual(code, 502) + self.assertEqual(reply["error"]["code"], "structured_output_failed") + _, raw = self.chat(script, stream=True) + self.assertIn('"structured_output_failed"', raw) + self.assertNotIn('"delta"', raw) + self.assertIn("data: [DONE]", raw) + + def test_object_mode_strict_json_and_truncation(self): + fmt = {"type": "json_object"} + self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) + for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', '```json\n{}\n```'): + self.assertEqual(self.chat(script, response_format=fmt)[0], 502) + self.assertEqual(self.chat('{"answer":4}', response_format=fmt, max_tokens=5)[0], 502) + # Plain text callers retain normal streaming, without a JSON validation gate. + self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200) + + def test_rejected_schema_does_not_load_the_engine_or_retry(self): + with mock.patch.object(self.svc, "load") as load: + code, _ = self.chat(response_format={"type": "json_schema"}) + self.assertEqual(code, 400) + load.assert_not_called() + self.engine = self.svc.engine = MockEngine(self.tok, "Markdown is not JSON", max_context=16384) + with mock.patch.object(self.engine, "generate", wraps=self.engine.generate) as generate: + self.assertEqual(self.chat()[0], 502) + self.assertEqual(generate.call_count, 1) + + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") + def test_invalid_schema_is_400_and_local_refs_work(self): + for schema in ({"type": "object", "properties": {"x": {"type": "invalid"}}}, + {"type": "object", "$ref": "https://other.example/schema"}): + fmt = {"type": "json_schema", "json_schema": {"name": "test", "strict": True, "schema": schema}} + self.assertEqual(self.chat(response_format=fmt)[0], 400) + schema = object_schema({"answer": {"$ref": "#/$defs/n"}}) + schema["$defs"] = {"n": {"type": "integer"}} + fmt = {"type": "json_schema", "json_schema": {"name": "local", "schema": schema}} + self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) + + def test_malformed_formats_and_tools_are_rejected_before_loading(self): + formats = ([], {"type": "unsupported"}, + {"type": "json_schema", "json_schema": {"schema": {"type": "object"}}}, + {"type": "json_schema", "json_schema": {"name": "x", "strict": "true", "schema": {"type": "object"}}}) + with mock.patch.object(self.svc, "load") as load: + for fmt in formats: + with self.subTest(fmt=fmt): + self.assertEqual(self.chat(response_format=fmt)[0], 400) + self.assertEqual(self.chat(tools=[{"type": "function", "function": {"name": "search", "parameters": {"type": "object"}}}])[0], 400) + self.assertEqual(self.chat(strata_mcp=True)[0], 400) + self.assertEqual(self.request("/v1/chat/completions", [])[0], 400) + load.assert_not_called() + + def test_without_jsonschema_an_object_is_still_required(self): + # jsonschema is optional: without it json_schema answers are checked to be one JSON object, json_object + # never needs it, and nothing is imported at server start + with mock.patch.object(structured, "_jsonschema", False): + self.assertEqual(self.chat()[0], 200) + for script in ("## Film Plan - Photobooth", "[1, 2]"): + code, reply = self.chat(script) + self.assertEqual(code, 502, script) + self.assertEqual(reply["error"]["code"], "structured_output_failed") + self.assertEqual(self.chat('{"answer":4}', response_format={"type": "json_object"})[0], 200) + + def test_the_server_does_not_import_jsonschema_at_start(self): + import subprocess + import sys + code = ("import sys; import serve.server; " + "sys.exit(1 if any(m == 'jsonschema' or m.startswith('jsonschema.') for m in sys.modules) else 0)") + r = subprocess.run([sys.executable, "-c", code], cwd=str(Path(__file__).resolve().parents[1])) + self.assertEqual(r.returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_vram.py b/serve/test_vram.py new file mode 100644 index 0000000..e1abe0b --- /dev/null +++ b/serve/test_vram.py @@ -0,0 +1,136 @@ +"""#533: POST /v1/vram (opt-in hot VRAM resize) - the engine command, the route, the config key, a reserve kept for +an unloaded engine and applied when it loads again.""" +import io +import json +import queue +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, EngineDied, Service, StrataEngine, engine_args, serve +from serve.test_lifecycle import ResidentEngine + + +class VramEngine(ResidentEngine): + """The resident test engine with an elastic cache: VRAM n frees what the reserve asks for, None takes the + start's (700 MiB).""" + def __init__(self, tok, elastic=True): + super().__init__(tok) + self.elastic, self.calls = elastic, [] + + def vram(self, reserve_mib, timeout=120.0): + self.calls.append(reserve_mib) + if not self.elastic: + raise ValueError("VRAM needs an engine started with --vram-elastic (one NVIDIA GPU, --serve)") + r = 700 if reserve_mib is None else reserve_mib + out = {"reserve_mib": r, "expert_slots": max(100, 4000 - r), "expert_cache_mib": max(500, 6000 - r), + "expert_cache_full_mib": 6000, "vram_free_mib": r, "prompt_chunk": 4096} + self.info["vram"] = out + return out + + +class EngineCommand(unittest.TestCase): + def engine(self, replies): + e = StrataEngine("missing-executable", [], lazy=True) + e.proc = mock.Mock() + e.proc.poll.return_value = None + e.proc.stdin = io.StringIO() + e.ended = False + e.lines = queue.Queue() + for r in replies: + e.lines.put(r) + return e + + def test_the_line_and_the_answer(self): + e = self.engine(["strata serve: something else\n", + "VRAM reserve_mib=6000 expert_slots=1200 expert_slots_full=3700 expert_cache_mib=1536 " + "expert_cache_full_mib=4900 vram_free_mib=6100 prompt_chunk=2048\n"]) + out = e.vram(6000) + self.assertEqual(e.proc.stdin.getvalue(), "VRAM 6000\n") + self.assertEqual(out["expert_slots"], 1200) + self.assertEqual(out["prompt_chunk"], 2048) + self.assertEqual(e.info["expert_slots"], 1200) + e = self.engine(["VRAM reserve_mib=700 expert_slots=3700\n"]) + e.vram(None) + self.assertEqual(e.proc.stdin.getvalue(), "VRAM\n") + + def test_refused_and_died(self): + e = self.engine(["ERR VRAM needs an engine started with --vram-elastic\n"]) + with self.assertRaisesRegex(ValueError, "--vram-elastic"): + e.vram(100) + e = self.engine([None]) + with self.assertRaises(EngineDied): + e.vram(100) + + def test_config_key(self): + cfg = {"args": ["--max-context", "8192"]} + self.assertEqual(engine_args(cfg), ["--max-context", "8192"]) # off unless asked + self.assertEqual(engine_args({**cfg, "vram_elastic": True, "vram_segment_mib": 256}), + ["--max-context", "8192", "--vram-elastic", "--vram-segment-mib", "256"]) + self.assertEqual(engine_args({**cfg, "vram_elastic": "yes"}), ["--max-context", "8192"]) + + +class Route(unittest.TestCase): + def setUp(self): + tok = ByteTokenizer() + self.engine = VramEngine(tok) + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + return response.status, json.loads(response.read().decode()) + + def test_resize_and_status(self): + self.engine.loaded = True + code, body = self.request("/v1/vram", {"reserve_mib": 4000}) + self.assertEqual(code, 200, body) + self.assertEqual(body["status"], "ok") + self.assertEqual(body["expert_cache_mib"], 2000) + self.assertEqual(self.request("/v1/status")[1]["vram"]["expert_cache_mib"], 2000) + code, body = self.request("/v1/vram", {"reserve_mib": None}) # back to the start's reserve + self.assertEqual(code, 200) + self.assertEqual(self.engine.calls, [4000, None]) + + def test_bad_input_busy_and_foreign_pages(self): + self.engine.loaded = True + for bad in ({"reserve_mib": -1}, {"reserve_mib": "8 GiB"}, {"reserve_mib": True}, {"reserve_mib": 1.5}): + self.assertEqual(self.request("/v1/vram", bad)[0], 400, bad) + self.assertEqual(self.request("/v1/vram", {"reserve_mib": 1}, {"Origin": "https://other.example"})[0], 403) + self.assertEqual(self.request("/v1/vram", {"reserve_mib": 1}, {"Content-Type": "text/plain"})[0], 415) + self.svc.vram_wait_s = 0.2 + with self.svc.fifo: # a request is running + self.assertEqual(self.request("/v1/vram", {"reserve_mib": 1})[0], 409) + self.assertEqual(self.engine.calls, []) + + def test_an_engine_without_the_flag_says_so(self): + self.engine.loaded, self.engine.elastic = True, False + code, body = self.request("/v1/vram", {"reserve_mib": 3000}) + self.assertEqual(code, 400) + self.assertIn("--vram-elastic", body["error"]["message"]) + + def test_unloaded_keeps_the_reserve_for_the_next_load(self): + code, body = self.request("/v1/vram", {"reserve_mib": 5000}) + self.assertEqual(code, 200) + self.assertEqual(body["status"], "not loaded") + self.assertEqual(self.engine.calls, []) + self.assertEqual(self.request("/v1/load", {})[0], 200) + self.assertEqual(self.engine.calls, [5000]) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_winjob.py b/serve/test_winjob.py new file mode 100644 index 0000000..31b617a --- /dev/null +++ b/serve/test_winjob.py @@ -0,0 +1,67 @@ +"""serve/winjob.py: a contained child - and whatever it starts - ends when the process that contained it ends, even +when that process is killed outright (the console window closed, Task Manager), with no cleanup of its own. + + python -m unittest serve.test_winjob (Windows only; skipped elsewhere) +""" +import os +import subprocess +import sys +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +# stands in for the server: contains a child that starts a grandchild, prints both pids, then waits to be killed +PARENT = f""" +import subprocess, sys, time +sys.path.insert(0, {str(ROOT)!r}) +from serve.winjob import contain +code = ("import subprocess, sys, time; g = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)']); " + "print(g.pid, flush=True); time.sleep(120)") +child = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, text=True) +ok = contain(child) +print(ok, child.pid, child.stdout.readline().strip(), flush=True) +time.sleep(120) +""" + + +def running(pid: int) -> bool: + out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True).stdout + return str(pid) in out + + +@unittest.skipUnless(os.name == "nt", "job objects are Windows-only") +class TestWinJob(unittest.TestCase): + def test_children_end_with_a_killed_server(self): + # a venv's python.exe is a launcher that runs the real interpreter as its child: kill() must reach the latter + python = getattr(sys, "_base_executable", None) or sys.executable + parent = subprocess.Popen([python, "-c", PARENT], stdout=subprocess.PIPE, text=True) + child = grandchild = None + try: + ok, child, grandchild = parent.stdout.readline().split() + child, grandchild = int(child), int(grandchild) + self.assertEqual(ok, "True") + self.assertTrue(running(child) and running(grandchild)) + parent.kill() # TerminateProcess: no atexit, no finally - like closing the window + parent.wait(10) + deadline = time.monotonic() + 10 + while (running(child) or running(grandchild)) and time.monotonic() < deadline: + time.sleep(0.2) + self.assertFalse(running(child), "the child outlived the server") + self.assertFalse(running(grandchild), "the grandchild outlived the server") + finally: + if parent.poll() is None: + parent.kill() + for pid in (child, grandchild): # on a failure, don't leave them sleeping + if pid and running(pid): + subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True) + + def test_elsewhere_or_without_a_process_it_is_a_no_op(self): + from serve.winjob import contain + self.assertFalse(contain(None)) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/app.css b/serve/web/app.css new file mode 100644 index 0000000..dd9a3e1 --- /dev/null +++ b/serve/web/app.css @@ -0,0 +1,184 @@ +/* Strata web app - layout on top of tokens.css + components.css (the Strata UI kit). Colours, type, radii and + shadows come only from the kit's tokens. */ +[hidden] { display: none !important; } +html, body { height: 100%; } +body { display: flex; flex-direction: column; overflow: hidden; } +main { flex: 1; min-height: 0; display: flex; } +.view { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.view[hidden] { display: none; } +.muted { color: var(--st-ink-muted); } +.small { font-size: var(--st-fs-xs); } +.card-title { font-weight: var(--st-fw-bold); font-size: var(--st-fs-base); color: var(--st-ink); } +.st-header { position: relative; z-index: 2; flex: none; } +.st-header .st-tabs { margin-left: var(--st-s-4); } +#drawer-close .st-icon { transform: rotate(-90deg); } + +/* ---------------------------------------------------------------- chat */ +.chat-scroll { flex: 1; min-height: 0; overflow-y: auto; } +.chat { max-width: 860px; margin: 0 auto; padding: var(--st-s-8) var(--st-s-6) var(--st-s-6); display: flex; + flex-direction: column; gap: var(--st-s-6); } +.chat-empty { margin: 12vh auto 0; text-align: center; } +.chat-empty__title { font-weight: var(--st-fw-black); font-size: var(--st-fs-display); line-height: var(--st-lh-tight); + letter-spacing: -.02em; } +.chat-empty__sub { margin-top: var(--st-s-3); color: var(--st-ink-muted); } +.st-msg { width: 100%; } +.st-msg--assistant { align-self: flex-start; } +.st-msg--assistant .st-bubble { width: 100%; } +.st-msg--user .st-bubble { white-space: pre-wrap; overflow-wrap: anywhere; } +.st-bubble > :first-child { margin-top: 0; } +.st-bubble > :last-child { margin-bottom: 0; } +.st-bubble p, .st-bubble ul, .st-bubble ol { margin: 0 0 var(--st-s-3); } +.st-bubble ul, .st-bubble ol { padding-left: var(--st-s-6); } +.st-bubble li + li { margin-top: var(--st-s-1); } +.st-bubble h3 { font-size: var(--st-fs-lg); margin: var(--st-s-4) 0 var(--st-s-2); color: var(--st-ink); } +.st-bubble h4 { font-size: var(--st-fs-base); margin: var(--st-s-3) 0 var(--st-s-2); color: var(--st-ink); } +.st-bubble code.inline { font: 400 .9em var(--st-font-mono); background: var(--st-surface-2); border: 1px solid var(--st-line-soft); + border-radius: 6px; padding: 1px 5px; } +.st-bubble .st-code { margin: var(--st-s-3) 0; } +.st-bubble blockquote { margin: 0 0 var(--st-s-3); padding-left: var(--st-s-3); border-left: 3px solid var(--st-line); + color: var(--st-ink-muted); } +.st-bubble hr { border: 0; border-top: 1px solid var(--st-line); margin: var(--st-s-4) 0; } +.st-bubble table { border-collapse: collapse; margin: 0 0 var(--st-s-3); font-size: var(--st-fs-md); } +.st-bubble th, .st-bubble td { border: 1px solid var(--st-line); padding: 6px 10px; text-align: left; } +.msg-images { display: flex; flex-wrap: wrap; gap: var(--st-s-2); justify-content: flex-end; } +.msg-images img { max-width: 220px; max-height: 180px; border-radius: var(--st-r-md); border: 1px solid var(--st-line); } +.st-msg .st-collapse { width: 100%; } +.st-collapse__body.thinking { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 420px; overflow-y: auto; } +.st-msg__meta .st-btn--icon { width: 28px; height: 28px; } +.st-msg__meta .st-btn--icon .st-icon { width: 16px; height: 16px; } +.cursor::after { content: ""; display: inline-block; width: 8px; height: 1.1em; margin-left: 2px; vertical-align: -3px; + border-radius: 2px; background: var(--st-accent); animation: blink 1s steps(2) infinite; } +@keyframes blink { 50% { opacity: 0; } } +.msg-error { color: var(--st-danger-text); background: var(--st-danger-tint); border-radius: var(--st-r-md); padding: 10px 14px; + font-size: var(--st-fs-md); } +/* MCP tool calls inside an answer: one compact collapsible block per call */ +.st-bubble .tool-call { margin: var(--st-s-3) 0; } +.tool-call > summary { min-width: 0; padding: 8px 12px; } +.tool-call__name { font: 500 var(--st-fs-sm)/1.2 var(--st-font-mono); color: var(--st-ink); white-space: nowrap; } +.tool-call__preview { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--st-fs-xs); } +.tool-call .st-badge, .tool-call summary .small { flex: none; } +.tool-call[data-state="error"] { border-color: color-mix(in srgb, var(--st-danger) 35%, var(--st-line)); } +.tool-call[data-state="running"] .st-badge::before, .tool-call[data-state="writing"] .st-badge::before { animation: blink 1s steps(2) infinite; } +.tool-call__label { font-size: var(--st-fs-xs); font-weight: var(--st-fw-medium); color: var(--st-ink-muted); margin: var(--st-s-2) 0 var(--st-s-1); } +.tool-call__pre { margin: 0; padding: 10px 12px; max-height: 320px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; + font: 400 12.5px/1.5 var(--st-font-mono); color: var(--st-ink-soft); background: var(--st-surface); + border: 1px solid var(--st-line-soft); border-radius: var(--st-r-sm); } + +.composer-wrap { flex: none; padding: 0 var(--st-s-6) var(--st-s-6); } +.st-composer { max-width: 860px; margin: 0 auto; } +.st-composer textarea { max-height: 40vh; } +.st-btn--send { width: 42px; padding: 0; } +.composer-hint { font-size: var(--st-fs-xs); color: var(--st-ink-muted); margin-right: var(--st-s-2); font-variant-numeric: tabular-nums; } +.attachments { display: flex; flex-wrap: wrap; gap: var(--st-s-2); padding: 2px 4px 0; } +.st-composer.dragging { outline: 2px dashed var(--st-accent); outline-offset: 3px; } +.chip { display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 6px 0 10px; border-radius: var(--st-r-pill); + background: var(--st-surface-2); border: 1px solid var(--st-line); font-size: var(--st-fs-xs); color: var(--st-ink-soft); } +.chip .st-btn--icon { width: 22px; height: 22px; border-radius: 50%; } +.chip .st-btn--icon .st-icon { width: 14px; height: 14px; } + +/* ---------------------------------------------------------------- monitor */ +.view--monitor, .view--about { overflow-y: auto; } +.monitor, .about { max-width: 1240px; width: 100%; margin: 0 auto; padding: var(--st-s-6); display: flex; flex-direction: column; + gap: var(--st-s-5); } +.state-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.state-card__head { display: flex; align-items: center; gap: var(--st-s-4); flex-wrap: wrap; } +.badges { display: flex; gap: var(--st-s-2); flex-wrap: wrap; } +.badges .st-badge { opacity: .38; transition: opacity var(--st-dur); } +.badges .st-badge.on { opacity: 1; } +.state-card__row { display: flex; justify-content: space-between; gap: var(--st-s-4); font-size: var(--st-fs-sm); + font-weight: var(--st-fw-medium); font-variant-numeric: tabular-nums; } +.metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: var(--st-s-4); } +.metric-card { padding: var(--st-s-4) var(--st-s-5); } +.st-metric__value small { font-size: var(--st-fs-md); font-weight: var(--st-fw-medium); color: var(--st-ink-muted); margin-left: 4px; } +.st-metric__sub { font-size: var(--st-fs-xs); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; min-height: 1em; } +.st-metric__spark { display: block; overflow: visible; } +.speed-values { display: flex; justify-content: space-between; gap: var(--st-s-3); } +.speed-values > div { display: flex; flex-direction: column; gap: 10px; min-width: 0; } +.speed-values > div:last-child { text-align: right; } +.speed-values .st-metric__value { font-size: clamp(20px, 2.2vw, var(--st-fs-stat)); } +.st-metric__spark .speed-prefill { color: color-mix(in srgb, var(--st-accent) 65%, black); } +.st-metric__spark[data-tone="warn"] { color: var(--st-warn); } +.st-metric__spark[data-tone="info"] { color: var(--st-info); } +.monitor-row { display: grid; grid-template-columns: minmax(260px, 1fr) minmax(0, 2.4fr); gap: var(--st-s-4); } +.ctx-card { display: flex; flex-direction: column; gap: var(--st-s-2); } +.ctx-gauge { position: relative; width: 150px; height: 150px; margin: var(--st-s-2) auto var(--st-s-3); } +.ctx-gauge .st-gauge { width: 150px; height: 150px; } +.ctx-gauge .st-gauge__fill { transition: stroke-dasharray 400ms var(--st-ease); } +.ctx-gauge__label { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; + font-size: var(--st-fs-xs); } +.ctx-gauge__pct { font-weight: var(--st-fw-black); font-size: var(--st-fs-xl); line-height: 1.1; font-variant-numeric: tabular-nums; } +.bar-row { display: flex; justify-content: space-between; font-size: var(--st-fs-sm); font-weight: var(--st-fw-medium); + margin-top: var(--st-s-2); font-variant-numeric: tabular-nums; } +.req-card { display: flex; flex-direction: column; gap: var(--st-s-3); min-width: 0; } +.table-wrap { overflow-x: auto; } +.req-head { display: flex; align-items: center; justify-content: space-between; gap: var(--st-s-2); } +.table-wrap.all { max-height: 420px; overflow-y: auto; } +.req-totals { margin: 0; font-size: var(--st-fs-sm); } +.req-totals:empty { display: none; } +.cc-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.cc-bars { display: grid; grid-template-columns: 1fr 1fr; gap: var(--st-s-2) var(--st-s-6); } +.cc-bars[hidden] { display: none; } +.cc-note { margin: 0; } +.cc-note:empty { display: none; } +.mcp-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.cfg-form { display: grid; grid-template-columns: minmax(180px, max-content) minmax(0, 1fr); gap: var(--st-s-3) var(--st-s-4); + align-items: center; } +.cfg-form label { font-size: var(--st-fs-sm); font-weight: var(--st-fw-medium); } +.cfg-form label code { font: 400 12px var(--st-font-mono); color: var(--st-ink-muted); display: block; } +.cfg-form .st-input { height: 38px; width: 100%; max-width: 360px; } +.cfg-actions { display: flex; align-items: center; gap: var(--st-s-3); } +.mcp-server { display: flex; flex-direction: column; gap: var(--st-s-2); padding-top: var(--st-s-3); border-top: 1px solid var(--st-line-soft); } +.mcp-server:first-child { padding-top: 0; border-top: 0; } +.mcp-server__head { display: flex; align-items: center; gap: var(--st-s-2); flex-wrap: wrap; font-size: var(--st-fs-sm); } +.mcp-server__tools { display: flex; flex-wrap: wrap; gap: 6px; } +.mcp-server__tools .chip { height: 26px; padding: 0 10px; font-family: var(--st-font-mono); } +.mcp-note { margin: 0; } + +/* ---------------------------------------------------------------- about */ +.about { max-width: 860px; } +.about .st-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.about p { margin: 0; } +.facts { display: grid; grid-template-columns: minmax(140px, max-content) 1fr; gap: 10px var(--st-s-6); margin: 0; font-size: var(--st-fs-md); } +.facts dt { color: var(--st-ink-muted); } +.facts dd { margin: 0; color: var(--st-ink-soft); font-variant-numeric: tabular-nums; display: flex; align-items: center; gap: 6px; + overflow-wrap: anywhere; } +.facts dd code { font: 400 13px var(--st-font-mono); } +.facts .st-btn--icon { width: 28px; height: 28px; } +.facts .st-btn--icon .st-icon { width: 16px; height: 16px; } +.toggle-row { display: flex; align-items: center; justify-content: space-between; gap: var(--st-s-4); font-size: var(--st-fs-sm); + font-weight: var(--st-fw-medium); color: var(--st-ink-soft); } +.toggle-row .st-toggle { flex: none; } /* a long label must not squeeze the switch */ + +/* ---------------------------------------------------------------- drawer */ +.st-drawer { z-index: 40; } +.scrim { position: fixed; inset: 0; background: rgba(15, 23, 42, .18); z-index: 39; } +.seg { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; padding: 4px; background: var(--st-surface-2); + border: 1px solid var(--st-line); border-radius: var(--st-r-md); } +.seg button { height: 32px; border: 0; border-radius: 10px; background: transparent; color: var(--st-ink-muted); + font: 500 var(--st-fs-sm)/1 var(--st-font); cursor: pointer; } +.seg button[aria-checked="true"] { background: var(--st-surface); color: var(--st-ink); font-weight: var(--st-fw-bold); + box-shadow: var(--st-sh-card); } +.drawer-actions { display: grid; grid-template-columns: 1fr 1fr; gap: var(--st-s-3); margin-top: var(--st-s-2); } +.st-toast { animation: toast-in 180ms var(--st-ease); } +@keyframes toast-in { from { opacity: 0; transform: translateY(6px); } } + +/* ---------------------------------------------------------------- narrow screens */ +@media (max-width: 1000px) { + .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .monitor-row { grid-template-columns: 1fr; } + .cc-bars { grid-template-columns: 1fr; } + .cfg-form { grid-template-columns: 1fr; gap: 4px; } + .cfg-form .st-input { margin-bottom: var(--st-s-2); } +} +@media (max-width: 640px) { + .st-header { padding: 0 var(--st-s-3); gap: var(--st-s-2); } + .st-header .st-tabs { margin-left: 0; } + .st-tab { padding: 0 10px; } + .st-tab .st-icon { display: none; } + #pill-text { display: none; } + .chat { padding: var(--st-s-5) var(--st-s-4); } + .composer-wrap { padding: 0 var(--st-s-3) var(--st-s-3); } + .monitor, .about { padding: var(--st-s-4); } + .facts { grid-template-columns: 1fr; gap: 2px; } + .facts dd { margin-bottom: var(--st-s-2); } +} diff --git a/serve/web/app.js b/serve/web/app.js new file mode 100644 index 0000000..ade1901 --- /dev/null +++ b/serve/web/app.js @@ -0,0 +1,1073 @@ +// serve/web/app.js - the Strata web app: Chat, Monitor, About. No framework, no network beyond this server. +// The Monitor tab rebuilds PR #22's dashboard idea (code-martin) on the server's own /metrics. +"use strict"; + +const $ = (id) => document.getElementById(id); +const SPRITE = "web/sprite.svg"; +const icon = (name, cls = "st-icon") => ``; +const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); +const fmt = (n, d = 0) => (n == null || Number.isNaN(n) ? "–" : Number(n).toLocaleString(undefined, {maximumFractionDigits: d, minimumFractionDigits: d})); +const kfmt = (n) => (n == null ? "–" : n >= 1000 ? `${fmt(n / 1000, n >= 10000 ? 0 : 1)}k` : fmt(n)); +// a context size: 32768 -> "32K" (powers of two), else like kfmt +const ctxfmt = (n) => (n && n % 1024 === 0 ? `${fmt(n / 1024)}K` : kfmt(n)); +const gb = (b, d = 1) => (b == null ? "–" : fmt(b / 1073741824, d)); // memory: binary GB, as Windows shows it + +const store = { + get(k, d) { try { const v = localStorage.getItem("strata." + k); return v === null ? d : JSON.parse(v); } catch (e) { return d; } }, + set(k, v) { try { localStorage.setItem("strata." + k, JSON.stringify(v)); } catch (e) { /* private mode: in memory only */ } }, +}; + +// ------------------------------------------------------------------ toasts +function toast(kind, title, text = "", ms = 3500, action = null) { + const names = {info: "info", success: "check", warn: "warning", error: "error"}; + const el = document.createElement("div"); + el.className = `st-toast st-toast--${kind}`; + el.innerHTML = `${icon(names[kind] || "info")}
`; + el.querySelector(".st-toast__title").textContent = title; + el.querySelector(".t-text").textContent = text; + if (action) { + const b = document.createElement("button"); + b.className = "st-btn st-btn--secondary"; + b.style.height = "32px"; + b.style.marginLeft = "auto"; + b.textContent = action.label; + b.onclick = () => { action.run(); el.remove(); }; + el.appendChild(b); + } + $("toasts").appendChild(el); + setTimeout(() => el.remove(), ms); +} + +async function copyText(text, btn) { + try { + await navigator.clipboard.writeText(text); + } catch (e) { // http on another host: no async clipboard + const ta = document.createElement("textarea"); + ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove(); + } + if (btn) { + const use = btn.querySelector("use"); + use.setAttribute("href", `${SPRITE}#i-check`); + setTimeout(() => use.setAttribute("href", `${SPRITE}#i-copy`), 1500); + } + toast("success", "Copied to clipboard", "", 1800); +} + +// ------------------------------------------------------------------ theme and tabs +// the system's theme until the user picks one (only a click is saved) +function setTheme(t, save) { + document.documentElement.dataset.theme = t; + if (save) try { localStorage.setItem("strata.theme", t); } catch (e) { /* ignore */ } + $("theme-icon").setAttribute("href", `${SPRITE}#i-${t === "dark" ? "sun" : "moon"}`); + $("dark-toggle").setAttribute("aria-checked", String(t === "dark")); +} +const flipTheme = () => setTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark", true); +$("theme-btn").onclick = flipTheme; +$("dark-toggle").onclick = flipTheme; +setTheme(document.documentElement.dataset.theme || "light", false); +matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => { + let saved = null; + try { saved = localStorage.getItem("strata.theme"); } catch (err) { /* ignore */ } + if (!saved) setTheme(e.matches ? "dark" : "light", false); +}); + +let tab = "chat"; +function showTab(name) { + tab = ["chat", "monitor", "about"].includes(name) ? name : "chat"; + for (const b of document.querySelectorAll(".st-tab")) b.setAttribute("aria-selected", String(b.dataset.tab === tab)); + for (const v of ["chat", "monitor", "about"]) $(`view-${v}`).hidden = v !== tab; + if (location.hash.slice(1) !== tab) history.replaceState(null, "", tab === "chat" ? location.pathname : `#${tab}`); + if (tab === "chat") $("input").focus(); + if (tab === "monitor") loadMcp(); + if (tab === "about") loadConfig(); + if (lastMetrics) render(lastMetrics); +} +for (const b of document.querySelectorAll(".st-tab")) b.onclick = () => showTab(b.dataset.tab); +window.addEventListener("hashchange", () => showTab(location.hash.slice(1))); + +// ------------------------------------------------------------------ server access +function headers(json = false) { + const h = {}; + const key = store.get("apikey", ""); + if (key) h.Authorization = "Bearer " + key; + if (json) h["Content-Type"] = "application/json"; + return h; +} +$("api-key").value = store.get("apikey", ""); +$("api-key").onchange = () => { store.set("apikey", $("api-key").value.trim()); toast("success", "API key saved", "Kept in this browser only."); }; + +let health = {model: "strata", images: false, max_context: 0}; +async function loadHealth() { + try { + health = await (await fetch("health")).json(); + $("attach-btn").title = health.images ? "Attach a text file or a picture (or drop it here)" + : "Attach a text file (or drop it here)"; + $("chat-empty-sub").textContent = `${health.model} runs on this PC. Nothing leaves it.`; + } catch (e) { + setTimeout(loadHealth, 2000); + } +} + +// ------------------------------------------------------------------ Monitor +const METRICS = [ + {key: "speed", label: "Speed", icon: "gauge", unit: "t/s", series: "tok_s"}, + {key: "gpu", label: "GPU load", icon: "gpu", unit: "%", series: "gpu_util", max: 100}, + {key: "vram", label: "VRAM", icon: "layers", unit: "GB", series: "gpu_mem_used"}, + {key: "temp", label: "GPU temp", icon: "thermometer", unit: "°C", series: "gpu_temp", tone: "warn"}, + {key: "power", label: "Power", icon: "bolt", unit: "W", series: "gpu_power"}, + {key: "pcie", label: "PCIe", icon: "link", unit: "", series: "gpu_pcie_rx_mb", tone: "info"}, + {key: "cpu", label: "CPU", icon: "cpu", unit: "%", series: "cpu", max: 100}, + {key: "disk", label: "Disk read", icon: "disk", unit: "MB/s", series: "disk_read_mb", tone: "info"}, +]; +$("metrics").innerHTML = METRICS.map((m) => ` +
+ ${icon(m.icon, "st-icon st-icon--sm")}${esc(m.label)} + ${m.key === "speed" ? `
+
-Decode
+
-Prefill
+
` : `– + `} + + + ${m.key === "speed" ? ` + ` : ""} +
`).join(""); + +function spark(id, values, max) { + const svg = $(id); + const v = (values || []).map((x) => (x == null ? 0 : x)); + if (v.length < 2) { svg.querySelector(".line").setAttribute("d", ""); svg.querySelector(".area").setAttribute("d", ""); return; } + const top = Math.max(max || 0, ...v, 1e-9); + const pts = v.map((x, i) => [(i / (v.length - 1)) * 100, 30 - (x / top) * 26]); + const line = pts.map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(2)},${p[1].toFixed(2)}`).join(""); + svg.querySelector(".line").setAttribute("d", line); + svg.querySelector(".area").setAttribute("d", `${line}L100,32L0,32Z`); +} +function setMetric(key, value, unit, sub) { + $(`mv-${key}`).innerHTML = value == null ? "–" : `${esc(value)}${unit ? `${esc(unit)}` : ""}`; + $(`ms-${key}`).textContent = sub || ""; +} + +let lastMetrics = null, metricsFailures = 0, keyWarned = false, mcpTick = 0; +let reqShowAll = false; // the Monitor's request table: the last 12, or every one the server keeps (issue #35) +async function poll() { + try { + const r = await fetch(reqShowAll ? "metrics?requests=all" : "metrics", {headers: headers()}); + if (r.status === 401) { + setPill("error", "API key needed"); + if (!keyWarned) { keyWarned = true; toast("warn", "API key needed", "This server needs a key: add it under About > Settings.", 6000); } + } else if (r.ok) { + lastMetrics = await r.json(); + metricsFailures = 0; + render(lastMetrics); + } else { + throw new Error(`HTTP ${r.status}`); + } + } catch (e) { + if (++metricsFailures === 3) setPill("error", "Server not reachable"); + } + if (tab === "monitor" && ++mcpTick % 10 === 0) loadMcp(); // server states change rarely: every 10 s + setTimeout(poll, 1000); +} + +function setPill(state, text) { + $("pill").dataset.state = state === "error" ? "queued" : state; + $("pill-text").textContent = text; +} + +function render(m) { + const live = m.live || {}, hw = m.hardware || {}, st = m.hardware_static || {}, eng = m.engine || {}, h = m.history || {}; + const last = (m.requests || [])[0]; + // the header pill + if (live.state === "reading") { + const pct = live.prompt_total ? Math.round((100 * live.prompt_read) / live.prompt_total) : null; + setPill("reading", pct != null ? `Reading prompt · ${pct}%` : "Reading prompt"); + } else if (live.state === "generating") { + setPill("generating", `Generating · ${fmt(live.tok_s, 1)} tok/s`); + } else { + setPill("idle", "Idle"); + } + if (live.queued > 0) setPill("queued", `${live.queued} queued`); + if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || [], m.totals, m.requests_kept); + if (tab === "monitor") renderConvCache(m.conversation_cache); + if (tab === "about") renderAbout(eng, hw, st); +} + +// #596: the conversation cache - the prompt's state the engine keeps between requests (always), and the whole +// conversations it parks in RAM when "--conversation-cache-mib N" is in the run config's args (opt-in) +function since(t) { + if (!t) return ""; + const s = Math.max(0, Date.now() / 1000 - t); + return s < 60 ? "just now" : s < 3600 ? `${fmt(s / 60)} min ago` : `${fmt(s / 3600, 1)} h ago`; +} +function renderConvCache(c) { + $("cc-card").hidden = !c; + if (!c) return; // an older server + const pct = (a, b) => (b ? `${Math.min(100, (100 * a) / b)}%` : "0%"); + $("cc-bars").hidden = !c.enabled; + if (c.enabled) { + $("cc-slots-text").textContent = `${fmt(c.parked)} / ${fmt(c.slots)}`; + $("cc-slots-bar").style.width = pct(c.parked, c.slots); + const budget = c.budget_mib * 1048576; + $("cc-mem-text").textContent = `${gb(c.bytes)} / ${gb(budget)} GB`; + $("cc-mem-bar").style.width = pct(c.bytes, budget); + } + $("cc-sum").textContent = c.requests ? `${fmt(c.requests_reused)} of ${fmt(c.requests)} requests reused part of their prompt` : ""; + const share = c.prompt_tokens ? ` (${fmt((100 * c.reused_tokens) / c.prompt_tokens)}% of all prompt tokens)` : ""; + const event = c.last_event ? `${c.last_event === "parked" ? "Parked" : "Restored"} ${fmt(c.last_tokens)} tokens, ${since(c.last_at)}` : null; + facts($("cc-facts"), [ + ["Last request", c.last_prompt != null ? `${fmt(c.last_reused || 0)} of ${fmt(c.last_prompt)} prompt tokens reused` : null], + ["Reused since start", c.requests ? `${fmt(c.reused_tokens)} tokens${share}` : null], + ["Parked / restored", c.enabled ? `${fmt(c.parks)} / ${fmt(c.restores)}${c.evictions ? ` · ${fmt(c.evictions)} evicted` : ""}` : null], + ["Last switch", c.enabled ? event : null], + ]); + $("cc-note").textContent = c.enabled + ? "A request that continues a parked conversation gets its state back instead of reading it again; the oldest goes when the slots or the memory are full." + : "The engine keeps the last conversation's state, so a follow-up reads only what is new. To keep several conversations (agents taking turns), add \"--conversation-cache-mib\", \"8192\" to the run config's args (docs/DETAILS.md)."; +} + +function renderTotals(t) { + if (!t || !t.requests) return ""; + const since = new Date(t.since * 1000).toLocaleString([], {weekday: "short", hour: "2-digit", minute: "2-digit"}); + const read = t.prompt_tokens - t.reused; + const pSpeed = t.prompt_ms > 0 && read > 0 ? ` at ${fmt(read / (t.prompt_ms / 1000))} tok/s` : ""; + const oSpeed = t.decode_ms > 0 && t.output_tokens > 0 ? ` at ${fmt(t.output_tokens / (t.decode_ms / 1000), 1)} tok/s` : ""; + return `Since ${since}: ${fmt(t.requests)} requests · ${fmt(read)} prompt tokens read${pSpeed} (${fmt(t.reused)} reused) · ` + + `${fmt(t.output_tokens)} written${oSpeed}`; +} +function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) { + // model state + const on = live.queued > 0 ? "queued" : live.state; + for (const b of document.querySelectorAll("#state-badges .st-badge")) b.classList.toggle("on", b.dataset.s === on || b.dataset.s === live.state); + const prog = $("state-progress"); + let label = "Waiting for a request", detail = "", pct = 0; + if (live.state === "reading") { + label = "Reading prompt"; + prog.dataset.tone = "info"; + if (live.prompt_total) { + pct = (100 * live.prompt_read) / live.prompt_total; + detail = `${fmt(live.prompt_read)} / ${fmt(live.prompt_total)} tokens · ${fmt(pct)}%`; + } else { + detail = `${fmt(live.prompt_tokens)} tokens`; + } + } else if (live.state === "generating") { + label = live.phase ? live.phase[0].toUpperCase() + live.phase.slice(1) : "Generating"; + delete prog.dataset.tone; + pct = live.max_tokens ? Math.min(100, (100 * live.generated) / live.max_tokens) : 0; + detail = `${fmt(live.generated)} tokens · ${fmt(live.tok_s, 1)} tok/s`; + } else if (last) { + delete prog.dataset.tone; + detail = `last: ${fmt(last.output_tokens)} tokens${last.decode_tok_s ? ` at ${fmt(last.decode_tok_s, 1)} tok/s` : ""}`; + } + $("state-label").textContent = label; + $("state-detail").textContent = detail; + $("state-bar").style.width = `${pct}%`; + + // the eight cards + const speed = live.state === "generating" ? live.tok_s : last ? last.decode_tok_s : null; + setMetric("speed", speed == null ? null : fmt(speed, 1), "t/s", + live.state === "generating" ? "Decode now" : last ? "Decode last request" : "Decode"); + const prefill = live.state !== "idle" ? live.prefill_tok_s_mean + : last && last.prompt_ms > 0 ? Math.max(0, last.prompt_tokens - (last.reused || 0)) / (last.prompt_ms / 1000) : null; + setMetric("prefill", prefill == null ? null : fmt(prefill), "t/s", + live.state === "reading" ? "Prefill now" : live.state === "generating" ? "Prefill this request" : last ? "Prefill last request" : "Prefill"); + spark("sp-speed", h.tok_s); + spark("sp-prefill", h.prefill_tok_s_mean); + // a model split across several cards (issue #112): the cards show their total / mean / hottest, and each card's own + const per = (f) => (hw.gpus || []).map((g) => `GPU ${g.index} ${f(g)}`).join(" · "); + const multi = (hw.gpus || []).length > 1; + setMetric("gpu", hw.gpu_util == null ? null : fmt(hw.gpu_util), "%", + multi ? per((g) => (g.util == null ? "–" : `${fmt(g.util)}%`)) : st.gpu_name || ""); + spark("sp-gpu", h.gpu_util, 100); + setMetric("vram", hw.gpu_mem_used == null ? null : gb(hw.gpu_mem_used), hw.gpu_mem_total ? `/ ${gb(hw.gpu_mem_total, 0)} GB` : "GB", + multi ? per((g) => (g.mem_used == null ? "–" : `${gb(g.mem_used)} GB`)) + : eng.expert_slots ? `${fmt(eng.expert_slots)} experts cached` : ""); + spark("sp-vram", h.gpu_mem_used, hw.gpu_mem_total); + setMetric("temp", hw.gpu_temp == null ? null : fmt(hw.gpu_temp), "°C", + multi ? per((g) => (g.temp == null ? "–" : `${fmt(g.temp)}°`)) : ""); + spark("sp-temp", h.gpu_temp, 90); + setMetric("power", hw.gpu_power == null ? null : fmt(hw.gpu_power), "W", hw.gpu_power_limit ? `of ${fmt(hw.gpu_power_limit)} W limit` : ""); + spark("sp-power", h.gpu_power, hw.gpu_power_limit); + const gen = hw.gpu_pcie_gen_max || hw.gpu_pcie_gen; + setMetric("pcie", gen ? `Gen${gen}` : null, hw.gpu_pcie_width ? `x${hw.gpu_pcie_width}` : "", + hw.gpu_pcie_rx_mb == null ? "" : `to GPU ${fmt(hw.gpu_pcie_rx_mb, hw.gpu_pcie_rx_mb < 10 ? 1 : 0)} MB/s` + + (hw.gpu_pcie_gen && gen && hw.gpu_pcie_gen < gen ? ` · idle Gen${hw.gpu_pcie_gen}` : "")); + spark("sp-pcie", h.gpu_pcie_rx_mb); + setMetric("cpu", hw.cpu == null ? null : fmt(hw.cpu), "%", st.threads ? `${st.cores ? `${st.cores} cores · ` : ""}${st.threads} threads` : ""); + spark("sp-cpu", h.cpu, 100); + if (hw.disk_read_mb == null) { + setMetric("disk", null, "", st.psutil ? "" : "needs psutil (setup installs it)"); + } else { + const big = hw.disk_read_mb >= 1000; + setMetric("disk", big ? fmt(hw.disk_read_mb / 1024, 2) : fmt(hw.disk_read_mb, hw.disk_read_mb < 10 ? 1 : 0), big ? "GB/s" : "MB/s", + hw.disk_write_mb == null ? "" : `write ${fmt(hw.disk_write_mb, 1)} MB/s`); + } + spark("sp-disk", h.disk_read_mb); + + // context fill: the running request, else the last one + const ctx = eng.max_context || 0; + let used = 0; + if (live.state !== "idle") used = (live.prompt_tokens || 0) + (live.generated || 0); + else if (last) used = (last.prompt_tokens || 0) + (last.output_tokens || 0); + const frac = ctx ? Math.min(1, used / ctx) : 0; + $("ctx-fill").setAttribute("stroke-dasharray", `${(235.6 * frac).toFixed(1)} 314.2`); + $("ctx-fill").style.opacity = 235.6 * frac >= 3 ? "1" : "0"; // a near-zero arc would draw just its round cap + $("ctx-pct").textContent = `${Math.round(frac * 100)}%`; + $("ctx-sub").textContent = ctx ? `${kfmt(used)} / ${ctxfmt(ctx)}` : "–"; + const cacheBytes = (eng.expert_cache_mib || 0) * 1048576; + $("slots-text").textContent = eng.expert_slots ? `${fmt(eng.expert_slots)} · ${gb(cacheBytes)} GB` : "–"; + $("slots-bar").style.width = hw.gpu_mem_total ? `${Math.min(100, (100 * cacheBytes) / hw.gpu_mem_total)}%` : "0%"; + $("ram-text").textContent = hw.ram_total ? `${gb(hw.ram_used)} / ${gb(hw.ram_total, 0)} GB` : "–"; + const ramPct = hw.ram_total ? (100 * hw.ram_used) / hw.ram_total : 0; + $("ram-bar").style.width = `${ramPct}%`; + if (ramPct > 92) $("ram-progress").dataset.tone = "danger"; else delete $("ram-progress").dataset.tone; + $("temp-text").textContent = hw.gpu_temp == null ? "–" : `${fmt(hw.gpu_temp)} °C`; + $("temp-bar").style.width = hw.gpu_temp == null ? "0%" : `${Math.min(100, hw.gpu_temp)}%`; + + // recent requests + const body = $("req-body"); + if (!requests.length) { + body.innerHTML = `No requests yet`; + } else { + const badge = {stop: ["", "Done"], length: ["", "Max tokens"], cancel: ["st-badge--queued", "Stopped"], + disconnect: ["st-badge--queued", "Closed"], error: ["st-badge--error", "Error"]}; + body.innerHTML = requests.slice(0, reqShowAll ? requests.length : 12).map((r) => { + const [cls, text] = badge[r.finish] || ["", r.finish || "–"]; + const t = new Date(r.time * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit", second: "2-digit"}); + const proj = r.projection == null ? "" : ` ${r.projection ? "ESP" : "stock"}`; + // #588: the VRAM share; the PCIe share (--pcie-frac) beside it when there is one + const hit = r.hit_rate == null ? "–" : `${(r.hit_rate * 100).toFixed(1)}%` + + (r.pcie_share ? ` +${(r.pcie_share * 100).toFixed(1)}% PCIe` : ""); + return `${esc(t)}${esc(text)}${proj}${fmt(r.prompt_tokens)} + ${fmt(r.reused)}${fmt(r.output_tokens)}${fmt(r.decode_tok_s, 1)} + ${hit}${fmt(r.duration_s, 1)} s`; + }).join(""); + } + const all = $("req-all"); + kept = kept == null ? requests.length : kept; + all.hidden = kept <= 12; + all.textContent = reqShowAll ? "Show fewer" : `Show all (${kept})`; + $("req-wrap").classList.toggle("all", reqShowAll); + $("req-totals").textContent = renderTotals(totals); +} + +function facts(el, rows) { + el.innerHTML = rows.filter((r) => r[1] != null && r[1] !== "").map(([k, v, copy]) => + `
${esc(k)}
${copy ? `${esc(v)}` : esc(v)}
`).join(""); +} +// INFO cvec=project:4-44[:singleL] | add:A-B | 0 +function projectionText(c) { + if (!c || c === "0" || c === 0) return null; + const [mode, range, single] = String(c).split(":"); + const [a, b] = (range || "").split("-"); + return `${mode === "project" ? "Projection" : "Additive"} control vector on layers ${a}–${b}` + + `${single ? ` (layer ${single.replace("single", "")}'s direction)` : ""}. Per chat in Sampling. Its package ` + + "describes the vector as a refusal-direction projection; measure the speed yourself"; +} +function renderAbout(eng, hw, st) { + const kv = {int8: "8-bit", q4_0: "4-bit (Hadamard-rotated)", fp16: "16-bit"}[eng.kv] || eng.kv; + facts($("facts-engine"), [ + ["Model", eng.model], + ["Engine", eng.version ? `v${eng.version}` : "built from source"], + ["Context", eng.max_context ? `${fmt(eng.max_context)} tokens` : null], + ["KV cache", kv ? `${kv}${eng.kv_resident ? `, streamed: ${fmt(eng.kv_resident)} positions per layer in VRAM, the rest in RAM` : ", all in VRAM"}` : null], + ["Experts in VRAM", eng.expert_slots ? `${fmt(eng.expert_slots)} (${gb((eng.expert_cache_mib || 0) * 1048576)} GB)` : null], + ["Speculation", eng.spec ? `MTP drafts up to ${Math.max(0, (eng.mtp_max || eng.spec) - 1)} tokens${eng.lookup ? ", prompt lookup on" : ""}` : null], + ["Images", eng.images ? "on" : "off"], + ["Experimental speed projection", projectionText(eng.cvec)], + ]); + facts($("facts-hw"), [ + ["GPU", st.gpu_name ? `${st.gpu_name}${hw.gpu_mem_total ? `, ${gb(hw.gpu_mem_total, 0)} GB` : ""}` : "not readable (NVML)"], + ["CPU", st.cpu_name ? `${st.cpu_name}${st.threads ? `, ${st.threads} threads` : ""}` : null], + ["RAM", hw.ram_total ? `${gb(hw.ram_total, 0)} GB` : null], + ]); + const base = location.origin; + facts($("facts-api"), [ + ["OpenAI base URL", `${base}/v1`, true], + ["Anthropic base URL", base, true], + ["Model name", eng.model, true], + ]); +} +document.addEventListener("click", (e) => { + const b = e.target.closest("[data-copy]"); + if (b) copyText(b.dataset.copy, b); +}); +$("req-all").addEventListener("click", () => { reqShowAll = !reqShowAll; if (lastMetrics) render(lastMetrics); }); + +// ------------------------------------------------------------------ MCP servers (GET /mcp) +// Tools from the MCP servers in the run config: the chat offers them to the model (opt-in per request, +// "strata_mcp": true, which only this page sends); the Monitor lists the servers and what they offer. +let mcpInfo = {servers: [], tools: 0}, mcpRetry = null; +async function loadMcp() { + try { + const r = await fetch("mcp", {headers: headers()}); + if (!r.ok) return; + mcpInfo = await r.json(); + } catch (e) { return; /* an older server: no MCP */ } + renderMcp(); + clearTimeout(mcpRetry); // right after the start, servers may still be starting (npx downloads) + if ((mcpInfo.servers || []).some((s) => s.status === "starting")) mcpRetry = setTimeout(loadMcp, 3000); +} +const MCP_STATE = {ready: ["st-badge--generating", "Connected"], starting: ["st-badge--reading", "Starting"], + failed: ["st-badge--error", "Failed"], stopped: ["st-badge--queued", "Stopped"], idle: ["", "Waiting"]}; +function renderMcp() { + const servers = mcpInfo.servers || []; + $("mcp-card").hidden = !servers.length; + $("mcp-row").hidden = !servers.length; + const ready = servers.filter((s) => s.status === "ready" || s.status === "stopped"); + $("mcp-sum").textContent = servers.length ? `${fmt(mcpInfo.tools)} tools · ${ready.length} of ${servers.length} servers connected` : ""; + $("mcp-row-sub").textContent = mcpInfo.tools ? `${fmt(mcpInfo.tools)} tools from ${ready.map((s) => s.name).join(", ")}; the model calls them when it decides to` + : "no server is connected yet (see the Monitor)"; + $("mcp-list").innerHTML = servers.map((s) => { + const [cls, text] = MCP_STATE[s.status] || ["", s.status]; + const info = s.info && s.info.name ? ` · ${s.info.name}${s.info.version ? ` ${s.info.version}` : ""}` : ""; + return `
${esc(text)}` + + `${esc(s.name)}${esc(s.transport)} · ${fmt(s.tools.length)} tools${esc(info)}
` + + (s.error ? `
${esc(s.error)}
` : "") + + (s.tools.length ? `
${s.tools.map((t) => `${esc(t.tool)}`).join("")}
` : "") + + `
`; + }).join(""); +} + +// ------------------------------------------------------------------ Model settings (GET / POST /config, #564) +// A few documented keys of the run config (strata-.json), for every client, from the next start on. The +// server lists them, checks every value and keeps every other key of the file as it is. +let cfgKeys = []; +async function loadConfig() { + let r; + try { r = await fetch("config", {headers: headers()}); } catch (e) { return; } + if (!r.ok) { $("cfg-card").hidden = true; return; } // no run config, an older server, or no key yet + const c = await r.json(); + cfgKeys = c.keys || []; + $("cfg-file").textContent = c.file || ""; + $("cfg-form").innerHTML = cfgKeys.map((k, i) => { + const id = `cfg-${i}`, v = k.value; + let input; + if (k.kind === "bool" || k.kind === "enum") { + const opts = k.kind === "bool" ? [["true", "on"], ["false", "off"]] : k.choices.map((x) => [x, x]); + const cur = v == null ? "" : String(v); + input = ``; + } else { + const text = v == null ? "" : Array.isArray(v) ? v.join(", ") : String(v); + input = ``; + } + return `${input}`; + }).join(""); + $("cfg-card").hidden = false; +} +function configValue(k, el) { + const s = el.value.trim(); + if (s === "") return null; + if (k.kind === "bool") return s === "true"; + if (k.kind === "number") return Number(s); + return s; // enum, or names (the server splits them at commas) +} +$("cfg-save").addEventListener("click", async () => { + const set = {}; + cfgKeys.forEach((k, i) => { + const v = configValue(k, $(`cfg-${i}`)); + const old = Array.isArray(k.value) ? k.value.join(", ") : k.value; + if (JSON.stringify(v) !== JSON.stringify(old ?? null)) set[k.key] = v; + }); + if (!Object.keys(set).length) { $("cfg-msg").textContent = "Nothing changed."; return; } + try { + const r = await fetch("config", {method: "POST", headers: headers(true), body: JSON.stringify({set})}); + const b = await r.json(); + if (!r.ok) throw new Error((b.error || {}).message || `HTTP ${r.status}`); + $("cfg-msg").textContent = b.changed.length + ? `Saved (${b.changed.join(", ")}); the earlier file is ${b.file}.bak. Start the model again to use it.` : "Nothing changed."; + loadConfig(); + } catch (e) { + $("cfg-msg").textContent = ""; + toast("error", "Not saved", String(e.message || e), 6000); + } +}); + +// ------------------------------------------------------------------ Markdown (escaped first, then formatted) +function inline(s) { + const codes = []; + s = s.replace(/`([^`\n]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; }); + s = esc(s) + .replace(/\*\*([^*\n]+)\*\*/g, "$1") + .replace(/(^|[^*\w])\*([^*\n]+)\*(?![*\w])/g, "$1$2") + .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, '
$1'); + return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `${esc(codes[+i])}`); +} +function codeBlock(lang, code) { + return `
${esc(lang || "code")}` + + `
` + + `
${esc(code)}
`; +} +function blocks(text) { + const out = [], lines = text.split("\n"); + let para = [], list = null; + const flushPara = () => { if (para.length) out.push(`

${para.map(inline).join("
")}

`); para = []; }; + const flushList = () => { if (list) out.push(`<${list.tag}>${list.items.map((i) => `
  • ${inline(i)}
  • `).join("")}`); list = null; }; + for (let i = 0; i < lines.length; i++) { + const l = lines[i]; + let m; + if (!l.trim()) { flushPara(); flushList(); continue; } + if ((m = l.match(/^(#{1,6})\s+(.*)$/))) { flushPara(); flushList(); out.push(`<${m[1].length <= 2 ? "h3" : "h4"}>${inline(m[2])}`); continue; } + if (/^\s*([-*_])\s*\1\s*\1[\s\1]*$/.test(l)) { flushPara(); flushList(); out.push("
    "); continue; } + if ((m = l.match(/^>\s?(.*)$/))) { flushPara(); flushList(); out.push(`
    ${inline(m[1])}
    `); continue; } + if (/^\s*\|.*\|\s*$/.test(l) && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s|:-]*$/.test(lines[i + 1])) { + flushPara(); flushList(); + const cells = (row) => row.trim().replace(/^\||\|$/g, "").split("|").map((c) => inline(c.trim())); + let html = `${cells(l).map((c) => ``).join("")}`; + i += 2; + while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) html += `${cells(lines[i++]).map((c) => ``).join("")}`; + i--; + out.push(html + "
    ${c}
    ${c}
    "); + continue; + } + if ((m = l.match(/^\s*(?:[-*+]|(\d+)[.)])\s+(.*)$/))) { + flushPara(); + const tag = m[1] ? "ol" : "ul"; + if (!list || list.tag !== tag) { flushList(); list = {tag, items: []}; } + list.items.push(m[2]); + continue; + } + if (list && /^\s{2,}\S/.test(l)) { list.items[list.items.length - 1] += " " + l.trim(); continue; } + flushList(); + para.push(l); + } + flushPara(); flushList(); + return out.join(""); +} +function markdown(text) { + let html = "", rest = text; + for (;;) { + const m = rest.match(/(^|\n)```([^\n`]*)\n/); + if (!m) { html += blocks(rest); break; } + html += blocks(rest.slice(0, m.index)); + rest = rest.slice(m.index + m[0].length); + const end = rest.match(/(^|\n)```[ \t]*(\n|$)/); + if (!end) { html += codeBlock(m[2].trim(), rest); break; } // still streaming + html += codeBlock(m[2].trim(), rest.slice(0, end.index)); + rest = rest.slice(end.index + end[0].length); + } + return html; +} + +// ------------------------------------------------------------------ Chat +const DEFAULTS = {thinking: "high", temperature: 0.6, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true}; +let settings = {...DEFAULTS, ...store.get("sampling", {})}; +let messages = store.get("chat", []); +let attachments = []; // {name, url} +let busy = null; // {controller, msg} + +function saveChat() { + store.set("chat", messages.map((m) => ({...m, images: (m.images || []).map((i) => ({name: i.name})), + files: (m.files || []).map((f) => ({name: f.name}))}))); +} +function timeStr(t) { return new Date(t).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"}); } + +function msgEl(m, i) { + const el = document.createElement("div"); + el.className = `st-msg st-msg--${m.role}`; + el.dataset.i = i; + if (m.role === "user") { + if (m.files && m.files.length) { + const wrap = document.createElement("div"); + wrap.className = "msg-images"; + for (const f of m.files) { + const c = document.createElement("span"); + c.className = "chip"; + c.innerHTML = icon("attach", "st-icon st-icon--sm"); + c.append(f.name); + wrap.appendChild(c); + } + el.appendChild(wrap); + } + if (m.images && m.images.length) { + const wrap = document.createElement("div"); + wrap.className = "msg-images"; + for (const im of m.images) { + if (im.url) { const img = document.createElement("img"); img.src = im.url; img.alt = im.name || "image"; wrap.appendChild(img); } + else { const c = document.createElement("span"); c.className = "chip"; c.innerHTML = icon("image", "st-icon st-icon--sm"); c.append(im.name || "image"); wrap.appendChild(c); } + } + el.appendChild(wrap); + } + const b = document.createElement("div"); + b.className = "st-bubble"; + b.textContent = m.text; + el.appendChild(b); + const meta = document.createElement("div"); + meta.className = "st-msg__meta"; + meta.textContent = `You · ${timeStr(m.time)}`; + el.appendChild(meta); + } else { + el.innerHTML = `` + + `
    ` + + `
    `; + updateAssistant(el, m, false); + } + return el; +} +// One MCP tool call in the answer: a compact block (name, state, a one-line preview) that opens to the arguments and +// the result as the model read it. Its body is built only while open: a result can be 20,000 characters. +const TOOL_STATE = {writing: ["st-badge--reading", "Writing"], running: ["st-badge--generating", "Running"], done: ["", "Done"], + error: ["st-badge--error", "Error"], skipped: ["st-badge--queued", "Not run"]}; +function toolHtml(t, k) { + const [cls, label] = TOOL_STATE[t.state] || ["", t.state]; + const args = t.arguments == null ? "" : JSON.stringify(t.arguments, null, 2); + const preview = t.result != null ? t.result : args.replace(/\s+/g, " "); + let body = ""; + if (t.open) { + body = `
    Arguments
    ${esc(args || "(being written)")}
    `; + if (t.result != null) { + body += `
    ${t.ok ? "Result" : "Error"}${t.chars ? ` · ${fmt(t.chars)} characters` : ""}` + + `${t.truncated ? ", cut for the model" : ""}
    ${esc(t.result)}
    `; + } + } + return `
    ` + + `${icon("tool", "st-icon st-icon--sm")}${esc(t.tool || t.name || "tool")}` + + (t.server ? `${esc(t.server)}` : "") + + `${esc(preview.slice(0, 200))}` + + `${esc(label)}${t.ms != null && t.state !== "skipped" ? `${fmt(t.ms / 1000, 1)} s` : ""}` + + `${icon("chevron", "st-icon st-icon--sm st-chev")}
    ${body}
    `; +} +// the answer's text with the tool blocks where the model called them +function answerHtml(m) { + if (!m.tools || !m.tools.length) return markdown(m.text || ""); + let html = "", pos = 0; + m.tools.forEach((t, k) => { + const at = Math.min(Math.max(t.at || 0, pos), m.text.length); + if (at > pos) html += markdown(m.text.slice(pos, at)); + pos = at; + html += toolHtml(t, k); + }); + return html + markdown(m.text.slice(pos)); +} +// a tool event from the stream (the `strata_mcp` field of a chunk) +function onTool(m, x) { + if (x.event === "limit") { m.limit = x.max_rounds; return; } + m.tools = m.tools || []; + let t = m.tools.find((y) => y.id === x.id); + if (!t) { t = {id: x.id, name: x.name, at: m.text.length, rat: m.reasoning.length, state: "writing"}; m.tools.push(t); } + if (x.event === "call") { + Object.assign(t, {name: x.name, server: x.server, tool: x.tool, arguments: x.arguments, round: x.round, state: "running"}); + } else if (x.event === "result") { + Object.assign(t, {result: x.text, ok: x.ok, chars: x.chars, truncated: x.truncated, ms: x.ms, + state: x.skipped ? "skipped" : x.ok ? "done" : "error"}); + } +} +function updateAssistant(el, m, streaming) { + const det = el.querySelector("details.think"); + if (m.reasoning) { + det.hidden = false; + const thinkingNow = streaming && !m.text; + el.querySelector(".think-title").textContent = thinkingNow ? "Thinking…" : + m.thinkSecs != null ? `Thought for ${fmt(m.thinkSecs, 1)} s` : "Thoughts"; + const body = el.querySelector(".thinking"); + if (det.open || thinkingNow) body.textContent = m.reasoning; + else body.dataset.pending = "1"; + // open while it streams (if wanted), closed once the answer starts - unless the user toggled it themselves + if (thinkingNow && settings.show && !det.dataset.touched && !det.open) { det._auto = true; det.open = true; } + if (!thinkingNow && det.open && !det.dataset.touched) { det._auto = true; det.open = false; } + } + const bubble = el.querySelector(".st-bubble"); + if (m.error) { + bubble.innerHTML = `
    `; + bubble.firstChild.textContent = m.error; + } else if (!m.text && streaming && !(m.tools && m.tools.length)) { + bubble.innerHTML = m.reasoning ? `Writing` : ``; + } else { + bubble.innerHTML = answerHtml(m); + if (streaming) bubble.classList.add("cursor"); else bubble.classList.remove("cursor"); + } + el.querySelector(".meta-text").textContent = m.meta || (streaming ? "" : m.stopped ? "Stopped" : ""); + el.querySelector("[data-msg-copy]").hidden = streaming || !m.text; +} +function renderChat() { + const chat = $("chat"); + chat.querySelectorAll(".st-msg").forEach((e) => e.remove()); + $("chat-empty").hidden = messages.length > 0; + messages.forEach((m, i) => chat.appendChild(msgEl(m, i))); + scrollDown(true); +} +function nearBottom() { const s = $("chat-scroll"); return s.scrollHeight - s.scrollTop - s.clientHeight < 120; } +function scrollDown(force) { const s = $("chat-scroll"); if (force || nearBottom()) s.scrollTop = s.scrollHeight; } + +$("chat").addEventListener("click", (e) => { + const cc = e.target.closest("[data-code-copy]"); + if (cc) { copyText(cc.closest(".st-code").querySelector("pre").textContent, cc); return; } + const mc = e.target.closest("[data-msg-copy]"); + if (mc) { const i = +mc.closest(".st-msg").dataset.i; copyText(messages[i].text, mc); return; } + // a tool block: its open state lives in the message (the answer is rebuilt while it streams), so the click sets it + const sum = e.target.closest(".tool-call > summary"); + if (sum) { + e.preventDefault(); + const el = sum.closest(".st-msg"), m = messages[+el.dataset.i], t = m && m.tools && m.tools[+sum.parentElement.dataset.tool]; + if (!t) return; + t.open = !t.open; + updateAssistant(el, m, !!busy && busy.msg === m); + } +}); +$("chat").addEventListener("toggle", (e) => { + const d = e.target; + if (d.tagName !== "DETAILS" || !d.classList.contains("think")) return; + if (d._auto) { d._auto = false; return; } // our own open/close, not the user's + d.dataset.touched = "1"; + const body = d.querySelector(".thinking"); + if (d.open && body.dataset.pending) { body.textContent = messages[+d.closest(".st-msg").dataset.i].reasoning; delete body.dataset.pending; } +}, true); + +function apiMessages() { + const out = []; + for (const m of messages) { + if (m.role === "user") { + const imgs = (m.images || []).filter((i) => i.url); + const text = userText(m); + out.push({role: "user", content: imgs.length ? [{type: "text", text}, + ...imgs.map((i) => ({type: "image_url", image_url: {url: i.url}}))] : text}); + } else if (!m.error) { + out.push(...assistantMessages(m)); + } + } + return out; +} +// An answer that used MCP tools goes back as the model wrote it: per round the text before the calls, the calls and +// their results (as the model read them), then the rest - so the next question can build on what the tools found. +function assistantMessages(m) { + const ran = (m.tools || []).filter((t) => t.round != null && t.result != null && t.state !== "skipped"); + if (!ran.length) return m.text ? [{role: "assistant", content: m.text}] : []; + const out = []; + let pos = 0; + for (const r of [...new Set(ran.map((t) => t.round))]) { + const calls = ran.filter((t) => t.round === r); + const at = Math.min(Math.max(pos, calls[0].at || 0), m.text.length); + out.push({role: "assistant", content: m.text.slice(pos, at).trim(), + tool_calls: calls.map((t) => ({id: t.id, type: "function", function: {name: t.name, arguments: JSON.stringify(t.arguments || {})}}))}); + for (const t of calls) out.push({role: "tool", tool_call_id: t.id, content: t.result}); + pos = at; + } + const rest = m.text.slice(pos).trim(); + if (rest) out.push({role: "assistant", content: rest}); + return out; +} + +function setBusy(on) { + $("stop-btn").hidden = !on; + $("send-btn").disabled = on; + $("composer-hint").textContent = on ? "" : "Shift+Enter: new line"; +} + +async function send() { + const text = $("input").value.trim(); + if ((!text && !attachments.length) || busy) return; + messages.push({role: "user", text, images: attachments.filter((a) => a.kind !== "file"), + files: attachments.filter((a) => a.kind === "file"), time: Date.now()}); + attachments = []; + renderAttachments(); + $("input").value = ""; + autosize(); + const m = {role: "assistant", text: "", reasoning: "", time: Date.now()}; + messages.push(m); + renderChat(); + const el = $("chat").lastElementChild; + const controller = new AbortController(); + busy = {controller, msg: m}; + setBusy(true); + + const body = {model: health.model, messages: apiMessages(), stream: true, + reasoning_effort: settings.thinking}; + if (settings.temperature > 0) { + Object.assign(body, {temperature: +settings.temperature, top_p: +settings.top_p, top_k: +settings.top_k}); + } else { + body.temperature = 0; + } + if (settings.seed) body.seed = +settings.seed; + if (settings.max) body.max_tokens = +settings.max; + if (projectionLoaded()) body.experimental_speed_projection = !!settings.esp; + if (settings.mcp !== false && mcpInfo.tools > 0) body.strata_mcp = true; // this server may run MCP tools for it + + let firstAt = null, thinkStart = null, usage = null, frame = 0; + const paint = () => { frame = 0; updateAssistant(el, m, true); scrollDown(); }; + try { + const r = await fetch("v1/chat/completions", {method: "POST", headers: headers(true), body: JSON.stringify(body), + signal: controller.signal}); + if (!r.ok) { + let msg = `HTTP ${r.status}`; + try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ } + if (r.status === 401) msg = "This server needs an API key: add it under About > Settings."; + throw new Error(msg); + } + const reader = r.body.getReader(), dec = new TextDecoder(); + let buf = ""; + for (;;) { + const {value, done} = await reader.read(); + if (done) break; + buf += dec.decode(value, {stream: true}); + let nl; + while ((nl = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line.startsWith("data:")) continue; // ": keep-alive" comments while a long prompt is read + const data = line.slice(5).trim(); + if (data === "[DONE]") continue; + let j; + try { j = JSON.parse(data); } catch (e) { continue; } + if (j.error) throw new Error(j.error.message || "the engine reported an error"); + if (j.usage) usage = j.usage; + if (j.strata_mcp) onTool(m, j.strata_mcp); + const d = (j.choices && j.choices[0] && j.choices[0].delta) || {}; + const lastTool = m.tools && m.tools.length ? m.tools[m.tools.length - 1] : null; // a new round after a tool + if (d.reasoning_content) { + if (!firstAt) firstAt = performance.now(); + if (!thinkStart) thinkStart = performance.now(); + if (lastTool && m.reasoning && lastTool.rat === m.reasoning.length) m.reasoning += "\n\n"; + m.reasoning += d.reasoning_content; + } + if (d.content) { + if (!firstAt) firstAt = performance.now(); + if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000; + if (lastTool && m.text && lastTool.at === m.text.length) m.text += "\n\n"; + m.text += d.content; + } + if (!frame) frame = requestAnimationFrame(paint); + } + } + } catch (e) { + if (e.name === "AbortError") m.stopped = true; + else { m.error = e.message || String(e); toast("error", "The request failed", m.error, 6000); } + } + if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000; + const n = usage ? usage.completion_tokens : null; + if (n && firstAt) { + const secs = (performance.now() - firstAt) / 1000; + m.meta = `${fmt(n)} tokens${secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : ""}${m.stopped ? " · stopped" : ""}` + + (projectionLoaded() ? (settings.esp ? " · projection on" : " · projection off") : ""); + } else if (m.stopped) { + m.meta = "Stopped"; + } + for (const t of m.tools || []) if (t.state === "writing" || t.state === "running") { t.state = "skipped"; t.ms = null; } + const ran = (m.tools || []).filter((t) => t.state === "done" || t.state === "error").length; + if (ran) m.meta = `${m.meta ? `${m.meta} · ` : ""}${ran} tool call${ran > 1 ? "s" : ""}`; + if (m.limit) m.meta = `${m.meta || ""} · stopped at the limit of ${m.limit} tool rounds (mcp.max_rounds)`; + busy = null; + setBusy(false); + if (frame) cancelAnimationFrame(frame); + updateAssistant(el, m, false); + saveChat(); + scrollDown(); +} + +$("composer").onsubmit = (e) => { e.preventDefault(); send(); }; +$("stop-btn").onclick = () => { if (busy) busy.controller.abort(); }; +$("input").addEventListener("keydown", (e) => { + if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); } +}); +function autosize() { const t = $("input"); t.style.height = "auto"; t.style.height = `${Math.min(t.scrollHeight, innerHeight * 0.4)}px`; } +$("input").addEventListener("input", autosize); + +$("new-btn").onclick = () => { + if (busy) { toast("warn", "Still writing", "Stop the answer first."); return; } + if (!messages.length) return; + const backup = messages; + messages = []; + saveChat(); + renderChat(); + toast("info", "New chat", "The last one was cleared.", 6000, {label: "Undo", run: () => { messages = backup; saveChat(); renderChat(); }}); +}; +$("export-btn").onclick = () => { + if (!messages.length) { toast("info", "Nothing to save yet"); return; } + const tools = (m) => (m.tools || []).filter((t) => t.result != null).map((t) => + `
    Tool ${t.server ? `${t.server} / ` : ""}${t.tool || t.name}${t.ok ? "" : " (error)"}\n\n` + + `\`\`\`json\n${JSON.stringify(t.arguments || {}, null, 2)}\n\`\`\`\n\n\`\`\`\n${t.result}\n\`\`\`\n\n
    \n\n`).join(""); + const md = messages.map((m) => m.role === "user" ? `## You\n\n${m.text}\n` : + `## ${health.model}\n\n${m.reasoning ? `
    Thinking\n\n${m.reasoning}\n\n
    \n\n` : ""}${tools(m)}${m.text || m.error || ""}\n`).join("\n"); + const a = document.createElement("a"); + a.href = URL.createObjectURL(new Blob([md], {type: "text/markdown"})); + a.download = `strata-chat-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, "-")}.md`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 5000); +}; + +// pictures and text files: the attach button, dropping them on the chat, or pasting a picture (issue #30) +const TEXT_EXT = /\.(txt|md|markdown|rst|tex|py|pyi|ipynb|js|mjs|cjs|ts|tsx|jsx|vue|svelte|json|jsonl|csv|tsv|log|ya?ml|toml|ini|cfg|conf|env|xml|html?|css|scss|less|c|cc|cpp|cxx|h|hh|hpp|cu|cuh|rs|go|java|kt|kts|swift|rb|php|pl|lua|r|jl|scala|sql|sh|bash|zsh|fish|ps1|psm1|bat|cmd|diff|patch|gradle|cmake|mk|dockerfile|gitignore|proto|graphql)$/i; +const MAX_TEXT_FILE = 512 * 1024; +function isTextFile(f) { + return f.type.startsWith("text/") || /json|xml|javascript|yaml|toml|x-sh|x-python/.test(f.type) || + TEXT_EXT.test(f.name) || /(^|[\\/])(makefile|dockerfile|readme|license)$/i.test(f.name); +} +function addFiles(files) { + for (const f of files) { + if (f.type.startsWith("image/")) { + if (!health.images) { toast("warn", "Pictures are off", "This model was set up for text only."); continue; } + if (f.size > 20e6) { toast("warn", "Picture too large", `${f.name} is over 20 MB.`); continue; } + const r = new FileReader(); + r.onload = () => { attachments.push({kind: "image", name: f.name || "pasted image", url: r.result}); renderAttachments(); }; + r.readAsDataURL(f); + continue; + } + if (!isTextFile(f)) { toast("warn", "Not a text file", `${f.name}: attach text files (code, notes, logs, data)${health.images ? " or pictures" : ""}.`); continue; } + if (f.size > MAX_TEXT_FILE) { toast("warn", "File too large", `${f.name} is over 512 KB.`); continue; } + const r = new FileReader(); + r.onload = () => { + const text = String(r.result); + if (text.includes("\u0000")) { toast("warn", "Not a text file", `${f.name} looks like a binary file.`); return; } + attachments.push({kind: "file", name: f.name, text}); + renderAttachments(); + }; + r.readAsText(f); + } +} +// a file's text in the message, fenced with more backticks than it contains itself +function fileBlock(f) { + const longest = Math.max(2, ...(f.text.match(/`+/g) || []).map((s) => s.length)); + const fence = "`".repeat(longest + 1); + return `File: ${f.name}\n${fence}\n${f.text}\n${fence}`; +} +function userText(m) { + const files = (m.files || []).filter((f) => f.text != null); + return [m.text, ...files.map(fileBlock)].filter((s) => s).join("\n\n"); +} +function renderAttachments() { + const box = $("attachments"); + box.hidden = !attachments.length; + box.innerHTML = ""; + attachments.forEach((a, i) => { + const c = document.createElement("span"); + c.className = "chip"; + c.innerHTML = icon(a.kind === "file" ? "attach" : "image", "st-icon st-icon--sm"); + c.append(a.name); + const x = document.createElement("button"); + x.type = "button"; x.className = "st-btn st-btn--icon"; x.setAttribute("aria-label", "Remove"); + x.innerHTML = icon("trash"); + x.onclick = () => { attachments.splice(i, 1); renderAttachments(); }; + c.appendChild(x); + box.appendChild(c); + }); +} +$("attach-btn").onclick = () => $("file").click(); +// drop files on the chat or the message box +for (const id of ["chat", "composer"]) { + const el = $(id); + el.addEventListener("dragover", (e) => { + if (![...(e.dataTransfer || {}).types || []].includes("Files")) return; + e.preventDefault(); + $("composer").classList.add("dragging"); + }); + el.addEventListener("dragleave", () => $("composer").classList.remove("dragging")); + el.addEventListener("drop", (e) => { + $("composer").classList.remove("dragging"); + if (!e.dataTransfer || !e.dataTransfer.files.length) return; + e.preventDefault(); + addFiles(e.dataTransfer.files); + $("input").focus(); + }); +} +$("file").onchange = () => { addFiles($("file").files); $("file").value = ""; }; +$("input").addEventListener("paste", (e) => { + if (!health.images) return; + const files = [...(e.clipboardData || {}).files || []].filter((f) => f.type.startsWith("image/")); + if (files.length) { e.preventDefault(); addFiles(files); } +}); + +// ------------------------------------------------------------------ the sampling drawer +function openDrawer(open) { + $("drawer").dataset.open = String(open); + $("drawer").setAttribute("aria-hidden", String(!open)); + $("scrim").hidden = !open; + if (open) { loadDrawer(); loadShared(); loadMcp(); } +} +function loadDrawer(s = settings) { + for (const b of $("s-thinking").children) b.setAttribute("aria-checked", String(b.dataset.v === s.thinking)); + $("s-temp").value = s.temperature; $("s-topp").value = s.top_p; $("s-topk").value = s.top_k; + $("s-max").value = s.max; $("s-seed").value = s.seed; + $("s-show").setAttribute("aria-checked", String(!!s.show)); + $("s-esp").setAttribute("aria-checked", String(s.esp !== false)); + $("esp-row").hidden = !projectionLoaded(); + $("s-mcp").setAttribute("aria-checked", String(s.mcp !== false)); + $("s-share").setAttribute("aria-checked", String(sharedOn)); + outputs(); +} +// "Use for other apps too": the server keeps these settings as every client's defaults (GET/POST /settings) +let sharedOn = false; +async function loadShared() { + try { + const r = await fetch("settings", {headers: headers()}); + if (r.ok) sharedOn = !!(await r.json()).shared; + } catch (e) { /* an older server: the switch just stays off */ } + $("s-share").setAttribute("aria-checked", String(sharedOn)); +} +function sharedDefaults(s) { + const d = {reasoning_effort: s.thinking, temperature: +s.temperature}; + if (+s.temperature > 0) Object.assign(d, {top_p: +s.top_p, top_k: +s.top_k}); + if (s.seed) d.seed = +s.seed; + if (s.max) d.max_tokens = +s.max; + if (projectionLoaded()) d.experimental_speed_projection = s.esp !== false; + return d; +} +async function saveShared(on, s) { + const r = await fetch("settings", {method: "POST", headers: headers(true), + body: JSON.stringify({defaults: on ? sharedDefaults(s) : null})}); + if (!r.ok) { + let msg = `HTTP ${r.status}`; + try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ } + throw new Error(msg); + } + sharedOn = !!(await r.json()).shared; +} +// the engine was started with the experimental-speed-projection control vector (INFO cvec=...) +function projectionLoaded() { + const c = lastMetrics && lastMetrics.engine ? lastMetrics.engine.cvec : 0; + return !!c && c !== "0"; +} +function outputs() { + const t = +$("s-temp").value; + $("o-temp").textContent = t === 0 ? "0 · greedy" : t.toFixed(2); + $("o-topp").textContent = (+$("s-topp").value).toFixed(2); + $("o-topk").textContent = $("s-topk").value; + const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); + $("o-thinking").textContent = sel ? {none: "answers right away", low: "short", medium: "medium", high: "thorough (default)"}[sel.dataset.v] : ""; + for (const id of ["s-topp", "s-topk"]) $(id).disabled = t === 0; +} +for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $("s-thinking").children) x.setAttribute("aria-checked", String(x === b)); outputs(); }; +for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs; +$("s-show").onclick = () => $("s-show").setAttribute("aria-checked", String($("s-show").getAttribute("aria-checked") !== "true")); +$("s-esp").onclick = () => $("s-esp").setAttribute("aria-checked", String($("s-esp").getAttribute("aria-checked") !== "true")); +$("s-mcp").onclick = () => $("s-mcp").setAttribute("aria-checked", String($("s-mcp").getAttribute("aria-checked") !== "true")); +$("s-share").onclick = () => $("s-share").setAttribute("aria-checked", String($("s-share").getAttribute("aria-checked") !== "true")); +$("s-reset").onclick = () => loadDrawer(DEFAULTS); +$("s-apply").onclick = async () => { + const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); + settings = {thinking: sel ? sel.dataset.v : "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value, + top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(), + show: $("s-show").getAttribute("aria-checked") === "true", + esp: $("s-esp").getAttribute("aria-checked") === "true", + mcp: $("s-mcp").getAttribute("aria-checked") === "true"}; + store.set("sampling", settings); + const share = $("s-share").getAttribute("aria-checked") === "true"; + openDrawer(false); + if (share || sharedOn) { + try { + await saveShared(share, settings); + toast("success", "Sampling saved", share ? "Other apps (omp, API clients) use these settings from their next request." + : "Other apps use their own settings again."); + } catch (e) { + toast("error", "Saved here, but not for other apps", e.message, 6000); + } + return; + } + toast("success", "Sampling saved", settings.temperature === 0 ? "Greedy: the same question gives the same answer." : ""); +}; +$("sampling-btn").onclick = () => openDrawer(true); +$("drawer-close").onclick = () => openDrawer(false); +$("scrim").onclick = () => openDrawer(false); +document.addEventListener("keydown", (e) => { if (e.key === "Escape" && $("drawer").dataset.open === "true") openDrawer(false); }); + +// ------------------------------------------------------------------ start +setBusy(false); +renderChat(); +const startQuestion = new URLSearchParams(location.search).get("q"); // /?q=... starts a chat (a shortcut) +if (startQuestion) history.replaceState(null, "", location.pathname + location.hash); +loadHealth().then(loadMcp).then(() => { if (startQuestion) { $("input").value = startQuestion; send(); } }); +showTab(location.hash.slice(1) || "chat"); +poll(); diff --git a/serve/web/components.css b/serve/web/components.css new file mode 100644 index 0000000..899f525 --- /dev/null +++ b/serve/web/components.css @@ -0,0 +1,128 @@ +/* Strata UI — components. Requires tokens.css. */ +*,*::before,*::after{box-sizing:border-box} +html,body{margin:0;background:var(--st-bg);color:var(--st-ink);font-family:var(--st-font);font-size:var(--st-fs-base);line-height:var(--st-lh-body);-webkit-font-smoothing:antialiased} +a{color:var(--st-accent-text);text-decoration:none} a:hover{text-decoration:underline} +:focus-visible{outline:2px solid var(--st-focus);outline-offset:2px} + +/* icon — */ +.st-icon{width:20px;height:20px;flex:none;color:inherit} +.st-icon--sm{width:16px;height:16px} .st-icon--lg{width:24px;height:24px} + +/* header */ +.st-header{display:flex;align-items:center;gap:var(--st-s-4);height:60px;padding:0 var(--st-s-6);background:var(--st-surface);border-bottom:1px solid var(--st-line)} +.st-header__brand{font-weight:900;font-size:var(--st-fs-lg);letter-spacing:-.01em} +.st-header__spacer{flex:1} + +/* status pill */ +.st-pill{display:inline-flex;align-items:center;gap:8px;height:30px;padding:0 12px;border-radius:var(--st-r-pill);border:1px solid var(--st-line);background:var(--st-surface-2);font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-soft);font-variant-numeric:tabular-nums} +.st-pill__dot{width:8px;height:8px;border-radius:50%;background:var(--st-ink-muted)} +.st-pill[data-state="generating"] .st-pill__dot{background:var(--st-accent);box-shadow:0 0 0 4px var(--st-accent-tint)} +.st-pill[data-state="reading"] .st-pill__dot{background:var(--st-info);box-shadow:0 0 0 4px var(--st-info-tint)} +.st-pill[data-state="queued"] .st-pill__dot{background:var(--st-warn)} + +/* tabs */ +.st-tabs{display:flex;gap:4px;padding:4px;background:var(--st-surface-2);border:1px solid var(--st-line);border-radius:var(--st-r-md)} +.st-tab{display:inline-flex;align-items:center;gap:8px;height:36px;padding:0 14px;border:0;border-radius:10px;background:transparent;color:var(--st-ink-muted);font:500 var(--st-fs-md)/1 var(--st-font);cursor:pointer} +.st-tab:hover{color:var(--st-ink)} +.st-tab[aria-selected="true"]{background:var(--st-surface);color:var(--st-ink);font-weight:700;box-shadow:var(--st-sh-card)} + +/* card + metric */ +.st-card{background:var(--st-surface);border:1px solid var(--st-line);border-radius:var(--st-r-lg);box-shadow:var(--st-sh-card);padding:var(--st-s-5)} +.st-metric{display:flex;flex-direction:column;gap:10px} +.st-metric__label{display:flex;align-items:center;gap:8px;font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-muted)} +.st-metric__value{font-weight:900;font-size:var(--st-fs-stat);line-height:1;letter-spacing:-.01em;font-variant-numeric:tabular-nums} +.st-metric__unit{font-weight:500;font-size:var(--st-fs-md);color:var(--st-ink-muted);margin-left:4px} +.st-metric__spark{width:100%;height:32px;color:var(--st-accent)} + +/* progress + gauge */ +.st-progress{height:8px;border-radius:var(--st-r-pill);background:var(--st-surface-2);border:1px solid var(--st-line-soft);overflow:hidden} +.st-progress__bar{height:100%;border-radius:inherit;background:var(--st-accent);transition:width var(--st-dur) var(--st-ease)} +.st-progress[data-tone="info"] .st-progress__bar{background:var(--st-info)} +.st-progress[data-tone="warn"] .st-progress__bar{background:var(--st-warn)} +.st-progress[data-tone="danger"] .st-progress__bar{background:var(--st-danger)} +/* gauge: see README for SVG markup (stroke-dasharray on a 270° arc) */ +.st-gauge{position:relative;width:120px;height:120px} +.st-gauge__track{stroke:var(--st-surface-2)} .st-gauge__fill{stroke:var(--st-accent)} + +/* table */ +.st-table{width:100%;border-collapse:collapse;font-size:var(--st-fs-md);font-variant-numeric:tabular-nums} +.st-table th{text-align:left;font-weight:500;font-size:var(--st-fs-xs);letter-spacing:.04em;text-transform:uppercase;color:var(--st-ink-muted);padding:10px 12px;border-bottom:1px solid var(--st-line)} +.st-table td{padding:12px;border-bottom:1px solid var(--st-line-soft);color:var(--st-ink-soft)} +.st-table tr:hover td{background:var(--st-surface-2)} +.st-table .num{text-align:right} + +/* badges */ +.st-badge{display:inline-flex;align-items:center;gap:6px;height:24px;padding:0 10px;border-radius:var(--st-r-pill);font-size:var(--st-fs-xs);font-weight:700;background:var(--st-surface-2);color:var(--st-ink-muted);border:1px solid var(--st-line)} +.st-badge::before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor} +.st-badge--reading{background:var(--st-info-tint);color:var(--st-info-text);border-color:transparent} +.st-badge--generating{background:var(--st-accent-tint);color:var(--st-accent-text);border-color:transparent} +.st-badge--queued{background:var(--st-warn-tint);color:var(--st-warn-text);border-color:transparent} +.st-badge--error{background:var(--st-danger-tint);color:var(--st-danger-text);border-color:transparent} + +/* chat */ +.st-msg{display:flex;flex-direction:column;gap:6px;max-width:720px} +.st-msg--user{align-self:flex-end;align-items:flex-end} +.st-bubble{padding:12px 16px;border-radius:var(--st-r-lg);font-size:var(--st-fs-base);line-height:1.55;color:var(--st-ink-soft)} +.st-msg--user .st-bubble{background:var(--st-accent);color:var(--st-accent-ink);border-bottom-right-radius:6px} +.st-msg--assistant .st-bubble{background:var(--st-surface);border:1px solid var(--st-line);border-bottom-left-radius:6px} +.st-msg__meta{font-size:var(--st-fs-xs);color:var(--st-ink-muted);display:flex;gap:8px;align-items:center} + +/* collapsible —
    …
    …
    */ +.st-collapse{border:1px solid var(--st-line);border-radius:var(--st-r-md);background:var(--st-surface-2)} +.st-collapse>summary{list-style:none;display:flex;align-items:center;gap:8px;padding:10px 14px;cursor:pointer;font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-muted)} +.st-collapse>summary::-webkit-details-marker{display:none} +.st-collapse>summary .st-chev{margin-left:auto;transition:transform var(--st-dur) var(--st-ease)} +.st-collapse[open]>summary .st-chev{transform:rotate(180deg)} +.st-collapse__body{padding:0 14px 14px;font-size:var(--st-fs-sm);color:var(--st-ink-muted);line-height:1.6} + +/* code */ +.st-code{border-radius:var(--st-r-md);background:var(--st-code-bg);color:var(--st-code-ink);overflow:hidden} +.st-code__head{display:flex;align-items:center;justify-content:space-between;padding:8px 8px 8px 14px;font:500 var(--st-fs-xs)/1 var(--st-font);color:#9aa3ab;border-bottom:1px solid rgba(255,255,255,.06)} +.st-code pre{margin:0;padding:14px;overflow:auto;font:400 13px/1.6 var(--st-font-mono)} +.st-code .st-btn--icon{color:#9aa3ab} .st-code .st-btn--icon:hover{background:rgba(255,255,255,.08);color:#fff} + +/* composer */ +.st-composer{display:flex;flex-direction:column;gap:8px;padding:10px;background:var(--st-surface);border:1px solid var(--st-line);border-radius:var(--st-r-lg);box-shadow:var(--st-sh-bar)} +.st-composer:focus-within{border-color:var(--st-focus)} +.st-composer textarea{border:0;outline:0;resize:none;background:transparent;color:var(--st-ink);font:400 var(--st-fs-base)/1.5 var(--st-font);padding:6px 8px;min-height:48px} +.st-composer__bar{display:flex;align-items:center;gap:6px} +.st-composer__bar .spacer{flex:1} + +/* drawer */ +.st-drawer{position:fixed;top:0;right:0;bottom:0;width:360px;max-width:100vw;background:var(--st-surface);border-left:1px solid var(--st-line);box-shadow:var(--st-sh-pop);display:flex;flex-direction:column;transform:translateX(100%);transition:transform 220ms var(--st-ease)} +.st-drawer[data-open="true"]{transform:none} +.st-drawer__head{display:flex;align-items:center;justify-content:space-between;padding:18px 20px;border-bottom:1px solid var(--st-line)} +.st-drawer__body{padding:20px;display:flex;flex-direction:column;gap:22px;overflow:auto} + +/* buttons */ +.st-btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:42px;padding:0 18px;border-radius:var(--st-r-md);border:0;font:700 var(--st-fs-md)/1 var(--st-font);cursor:pointer;transition:background var(--st-dur),transform 120ms} +.st-btn:active{transform:translateY(1px)} +.st-btn--primary{background:var(--st-accent);color:var(--st-accent-ink);box-shadow:0 6px 16px rgba(16,185,129,.24),inset 0 1px 0 rgba(255,255,255,.18)} +.st-btn--primary:hover{background:var(--st-accent-hover)} +.st-btn--secondary{background:transparent;color:var(--st-ink);border:1.5px solid var(--st-line)} +.st-btn--secondary:hover{background:var(--st-surface-2)} +.st-btn--danger{background:var(--st-danger-tint);color:var(--st-danger-text)} +.st-btn--icon{width:36px;height:36px;padding:0;border-radius:10px;background:transparent;color:var(--st-ink-muted)} +.st-btn--icon:hover{background:var(--st-surface-2);color:var(--st-ink)} +.st-btn:disabled{opacity:.45;cursor:not-allowed} + +/* form controls */ +.st-field{display:flex;flex-direction:column;gap:8px} +.st-label{display:flex;justify-content:space-between;font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-soft)} +.st-label output{font-variant-numeric:tabular-nums;color:var(--st-ink-muted)} +.st-input{height:44px;padding:0 14px;border-radius:var(--st-r-md);border:1.5px solid var(--st-line);background:var(--st-surface);color:var(--st-ink);font:400 var(--st-fs-md) var(--st-font)} +.st-input:focus{outline:0;border-color:var(--st-focus);box-shadow:0 0 0 3px color-mix(in srgb,var(--st-focus) 20%,transparent)} +.st-slider{width:100%;accent-color:var(--st-accent)} +.st-toggle{position:relative;width:40px;height:24px;border-radius:var(--st-r-pill);border:0;background:var(--st-line);cursor:pointer;transition:background var(--st-dur)} +.st-toggle::after{content:"";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.2);transition:transform var(--st-dur) var(--st-ease)} +.st-toggle[aria-checked="true"]{background:var(--st-accent)} +.st-toggle[aria-checked="true"]::after{transform:translateX(16px)} + +/* toast / alert */ +.st-toast{display:flex;align-items:flex-start;gap:12px;padding:14px 16px;border-radius:var(--st-r-md);background:var(--st-surface);border:1px solid var(--st-line);box-shadow:var(--st-sh-pop);font-size:var(--st-fs-md);color:var(--st-ink-soft);max-width:420px} +.st-toast__title{font-weight:700;color:var(--st-ink)} +.st-toast--info .st-icon{color:var(--st-info)} +.st-toast--success .st-icon{color:var(--st-accent)} +.st-toast--warn .st-icon{color:var(--st-warn)} +.st-toast--error .st-icon{color:var(--st-danger)} +.st-toasts{position:fixed;right:20px;bottom:20px;display:flex;flex-direction:column;gap:10px;z-index:50} diff --git a/serve/web/fonts/OFL.txt b/serve/web/fonts/OFL.txt new file mode 100644 index 0000000..723cd44 --- /dev/null +++ b/serve/web/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2021 The Outfit Project Authors (https://github.com/Outfitio/Outfit-Fonts) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/serve/web/fonts/outfit-latin-ext-wght.woff2 b/serve/web/fonts/outfit-latin-ext-wght.woff2 new file mode 100644 index 0000000..c54ceec Binary files /dev/null and b/serve/web/fonts/outfit-latin-ext-wght.woff2 differ diff --git a/serve/web/fonts/outfit-latin-wght.woff2 b/serve/web/fonts/outfit-latin-wght.woff2 new file mode 100644 index 0000000..85e3332 Binary files /dev/null and b/serve/web/fonts/outfit-latin-wght.woff2 differ diff --git a/serve/web/index.html b/serve/web/index.html new file mode 100644 index 0000000..5c26ad8 --- /dev/null +++ b/serve/web/index.html @@ -0,0 +1,243 @@ + + + + + +Strata + + + + + + +
    + Strata + + + + Connecting… + +
    + +
    + +
    +
    +
    +
    +
    Ask anything
    +
    The model runs on this PC. Nothing leaves it.
    +
    +
    +
    +
    +
    + + +
    + + + + + + + + + +
    +
    +
    +
    + + + + + + +
    + + + + +
    + + + diff --git a/serve/web/monitor.html b/serve/web/monitor.html new file mode 100644 index 0000000..b05b29f --- /dev/null +++ b/serve/web/monitor.html @@ -0,0 +1,37 @@ + + + + +Strata API Monitor + + + + + +
    Strata Local inference
    +
    +

    API Monitor

    Model status and every request, in one place.

    + + +
    +
    Model
    Connecting…
    127.0.0.1:5001/v1
    +
    Requests retained
    —
    Waiting for server
    +
    Last wall-clock
    —
    Includes queue and model loading
    +
    Last decode speed
    —
    Engine timing · tokens / second
    +
    +

    Requests

    +
    +
    Inspect a requestSelect a request to see its input, output, and timings.
    + +
    +
    Last 100 requests kept in memory until restart. Inputs and outputs stay on this machine.Connecting…
    +
    + diff --git a/serve/web/monitor.js b/serve/web/monitor.js new file mode 100644 index 0000000..5543b94 --- /dev/null +++ b/serve/web/monitor.js @@ -0,0 +1,111 @@ +"use strict"; +const $ = id => document.getElementById(id); +let selected = null, detail = null, pane = "input", records = [], state = null, operating = false, stamp = "", actionError = ""; +let apiKey = sessionStorage.getItem("strata.monitor.key") || ""; +document.documentElement.dataset.theme = localStorage.getItem("strata.theme") || "dark"; +const seconds = n => typeof n === "number" ? `${n.toFixed(2)} s` : "—"; +const speed = n => typeof n === "number" ? n.toFixed(1) : "—"; +const active = r => !["completed", "error", "disconnected"].includes(r.state); +function text(id, value) { const el = $(id); if (el.textContent !== String(value)) el.textContent = value; } +async function api(path, body) { + const response = await fetch(path, {cache:"no-store", headers:{...(apiKey ? {Authorization:`Bearer ${apiKey}`} : {}), ...(body !== undefined ? {"Content-Type":"application/json"} : {})}, ...(body !== undefined ? {method:"POST", body:JSON.stringify(body)} : {})}); + const value = await response.json(); + if (!response.ok) { + if (response.status === 401) $("auth").hidden = false; + throw new Error(value.error?.message || `HTTP ${response.status}`); + } + return value; +} +function notice(message) { $("error").hidden = !message; text("error", message || ""); } +function list() { + const query = $("search").value.toLowerCase(), filter = $("filter").value; + const visible = records.filter(r => `${r.id} ${r.path} ${r.model}`.toLowerCase().includes(query) && (filter === "all" || (filter === "active" ? active(r) : r.state === filter))); + const nextStamp = JSON.stringify([visible, selected]); + if (stamp === nextStamp) return; + stamp = nextStamp; + const focusId = document.activeElement?.dataset.request; + $("requests").replaceChildren(); + if (!visible.length) { + const empty = document.createElement("div"); empty.className = "empty"; + empty.textContent = records.length ? "No matching requests." : "No requests yet. API calls will appear here automatically."; + $("requests").append(empty); + } + for (const r of visible) { + const button = document.createElement("button"); button.className = `request${selected === r.id ? " selected" : ""}`; + button.dataset.request = r.id; button.setAttribute("aria-label", `Request ${r.id}`); button.setAttribute("aria-pressed", String(selected === r.id)); + const row = document.createElement("div"); row.className = "row"; + const time = document.createElement("span"); time.textContent = new Date(r.started_at * 1000).toLocaleTimeString(); + const tag = document.createElement("span"); tag.className = `tag ${r.state}`; tag.textContent = r.state; + row.append(time, tag); + const endpoint = document.createElement("div"); endpoint.className = "endpoint"; endpoint.textContent = `POST ${r.path}`; + const meta = document.createElement("div"); meta.className = "small"; + meta.textContent = `${r.id} · ${seconds(r.wallclock_s)} · ${r.stream ? "stream" : "JSON response"}${r.http_status ? ` · HTTP ${r.http_status}` : ""}`; + button.append(row, endpoint, meta); + button.onclick = async () => { selected = r.id; detail = null; list(); await showDetail(); }; + $("requests").append(button); + if (focusId === r.id) button.focus({preventScroll:true}); + } +} +function content() { + if (!detail) return; + let value = detail[pane] || (pane === "response" && detail.stream ? "Streaming response: see Output and the request error, if any." : "No content."); + if (pane === "output") { try { value = JSON.stringify(JSON.parse(value), null, 2); } catch (_) {} } + text("content", value); + const note = pane === "output" && detail.error ? "Raw model output retained for diagnosis. The API returned an error." : pane === "input" ? "Original request body." : pane === "output" ? "Model answer. JSON is formatted here for readability." : pane === "reasoning" ? "Separate reasoning content, when enabled." : "API response body."; + text("content-note", note + (detail[`${pane}_truncated`] ? " Monitor capture truncated at 256K characters; the API response was not shortened." : "")); +} +async function showDetail() { + if (!selected) return; + const id = selected; + const value = await api(`/api/requests?id=${encodeURIComponent(id)}`); + if (selected !== id) return; + detail = value; $("selection").hidden = false; $("no-selection").hidden = true; + text("detail-title", `${value.id} · ${value.path}`); + text("detail-status", value.state); $("detail-status").className = `tag ${value.state}`; + text("detail-time", new Date(value.started_at * 1000).toLocaleString()); + text("detail-wall", seconds(value.wallclock_s ?? ((Date.now() / 1000) - value.started_at))); + text("detail-load", seconds(value.load_s)); text("detail-queue", seconds(value.queue_s)); text("detail-first", seconds(value.first_token_s)); + text("detail-prompt", value.usage?.prompt_tokens ?? value.usage?.input_tokens ?? "—"); + text("detail-tokens", value.usage?.completion_tokens ?? value.usage?.output_tokens ?? "—"); + text("detail-speed", speed(value.timings?.predicted_per_second)); text("detail-format", value.response_format || "text"); + $("detail-error").hidden = !value.error; text("detail-error", value.error?.message || ""); content(); +} +async function refresh() { + try { + const [status, history] = await Promise.all([api("/v1/status"), api("/api/requests")]); + state = status; records = history.requests; + status.loaded = history.loaded; status.auto_load = history.auto_load; + if (selected && !records.some(r => r.id === selected)) { + selected = detail = null; $("selection").hidden = true; $("no-selection").hidden = false; + } + const inflight = Math.max(status.activity.in_flight, records.filter(active).length); + const loading = records.some(r => r.state === "loading"); + text("loaded", loading ? "Loading…" : inflight ? "In use" : status.loaded ? "Loaded" : "Unloaded"); + $("model-state").className = `value ${inflight || loading ? "busy" : status.loaded ? "loaded" : ""}`; + text("model", status.model); text("count", records.length); + text("active", inflight ? `${inflight} active / queued` : status.auto_load ? "Loads automatically on the next request" : "No active requests"); + const last = records.find(r => !active(r)); + text("wall", last ? seconds(last.wallclock_s) : "—"); text("speed", speed(last?.timings?.predicted_per_second)); + $("load").disabled = operating || Boolean(inflight) || status.loaded; $("unload").disabled = operating || Boolean(inflight) || !status.loaded; + list(); if (selected) await showDetail(); + text("updated", `Live · updated ${new Date().toLocaleTimeString()}`); + if (!operating) notice(actionError); + } catch (error) { notice(error.message); text("updated", "Disconnected · retrying"); $("load").disabled = $("unload").disabled = true; } +} +async function control(load) { + actionError = ""; + operating = true; $("load").disabled = $("unload").disabled = true; + text("loaded", load ? "Loading…" : "Unloading…"); + try { await api(load ? "/load" : "/unload", {}); notice(""); } + catch (error) { actionError = error.message; notice(actionError); } + finally { operating = false; await refresh(); } +} +$("load").onclick = () => control(true); $("unload").onclick = () => control(false); +$("key").onclick = () => { $("auth").hidden = !$("auth").hidden; if (!$("auth").hidden) $("api-key").focus(); }; +$("auth").onsubmit = async event => { event.preventDefault(); apiKey = $("api-key").value.trim(); sessionStorage.setItem("strata.monitor.key", apiKey); $("auth").hidden = true; await refresh(); }; +$("theme").onclick = () => { const theme = document.documentElement.dataset.theme === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = theme; localStorage.setItem("strata.theme", theme); }; +$("search").oninput = list; $("filter").onchange = list; +document.querySelectorAll("[data-pane]").forEach(button => { button.onclick = () => { pane = button.dataset.pane; document.querySelectorAll("[data-pane]").forEach(b => b.setAttribute("aria-selected", String(b === button))); content(); }; }); +$("copy").onclick = async () => { try { await navigator.clipboard.writeText($("content").textContent); text("copy", "Copied"); setTimeout(() => text("copy", "Copy"), 1500); } catch (_) { notice("Clipboard unavailable; select the text to copy it."); } }; +async function poll() { await refresh(); setTimeout(poll, 2000); } +poll(); diff --git a/serve/web/sprite.svg b/serve/web/sprite.svg new file mode 100644 index 0000000..598f623 --- /dev/null +++ b/serve/web/sprite.svg @@ -0,0 +1,34 @@ +AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYToyMjRkYzc2Ny1hNTJmLTRhNTgtYmRhNi0wNjNjZjgxZDE0ZDkAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaFpCcvmnJ1xuOVFbOGxO7IQAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDpjZTVmMTYyMy1hMGY4LTRjNDgtYmQ1MC0yOGRhYTVkZGQ3OWZscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNohRiWe4A1zTyq58r9HwVbdgAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggvnkoUEWEbTHaYh6o+DzKs/DGvSaEkSiXbTkyg+EGZBWkZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaPM+mDLLCljfKcnx6K3jLsYAAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRNAAAAAAAAAAAAAAAAAGRoYXNoWCDyyT5tVoB8Cn5pGifFieqsDs7yYczybQ255HiPUQvocGRuYW1lbmp1bWJmIG1hbmlmZXN0amV4Y2x1c2lvbnOBomVzdGFydBh8Zmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOjIyNGRjNzY3LWE1MmYtNGE1OC1iZGE2LTA2M2NmODFkMTRkOS9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOjYxMTcxNDYxLWZjODUtNDNkYi05NzdkLTVhNTQ0NWMwNzY0OXJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCC+eShQRYRtMdpiHqj4PMqz8Ma9JoSRKJdtOTKD4QZkFaJjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFggzN40WhHml0Alrpq9IN+inEViO5AnmGuZkyahASHk13qiY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFgg1QfqlfahOW+5OQ+LKm+K4e2m36U3CKHsYWKitMx8+Mt0Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPZYQAWvLruRfR0RxgkmvmgF8qVD0dQ7tTCsSMumVT6Kz8rMYbOspIf18RMz8a0P6WmnC265RomT3B4qAIos8XVuMBY= + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/serve/web/tokens.css b/serve/web/tokens.css new file mode 100644 index 0000000..220cf42 --- /dev/null +++ b/serve/web/tokens.css @@ -0,0 +1,87 @@ +/* Strata UI — tokens. Derived from the Gainsty design system. + Light is default; dark via . + Values marked (derived) are not in the Gainsty source and were added for the app. */ + +/* Outfit (SIL Open Font License 1.1, serve/web/fonts/OFL.txt): one variable font, weights 100-900 */ +@font-face{font-family:"Outfit";src:url("../fonts/outfit-latin-wght.woff2") format("woff2-variations");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD} +@font-face{font-family:"Outfit";src:url("../fonts/outfit-latin-ext-wght.woff2") format("woff2-variations");font-weight:100 900;font-display:swap;unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF} + +:root{ + /* type */ + --st-font:"Outfit",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; + --st-font-mono:ui-monospace,"SF Mono","Cascadia Code",Consolas,"Liberation Mono",monospace; /* (derived) */ + --st-fs-xs:12px; --st-fs-sm:13px; --st-fs-md:14px; --st-fs-base:16px; + --st-fs-lg:18px; --st-fs-xl:24px; --st-fs-stat:32px; --st-fs-display:40px; + --st-fw-regular:400; --st-fw-medium:500; --st-fw-bold:700; --st-fw-black:900; + --st-lh-tight:1.1; --st-lh-body:1.55; + + /* spacing (4pt) */ + --st-s-1:4px; --st-s-2:8px; --st-s-3:12px; --st-s-4:16px; --st-s-5:20px; + --st-s-6:24px; --st-s-8:32px; --st-s-10:40px; --st-s-12:48px; --st-s-16:64px; + + /* radius */ + --st-r-sm:8px; --st-r-md:14px; --st-r-lg:20px; --st-r-xl:24px; --st-r-pill:9999px; + + /* motion (derived) */ + --st-ease:cubic-bezier(.2,.7,.2,1); --st-dur:160ms; + + /* color — light */ + --st-bg:#f9fafb; + --st-surface:#ffffff; + --st-surface-2:#f7f7f7; + --st-line:#dee5ee; + --st-line-soft:#eeeeee; + --st-ink:#221e1f; + --st-ink-soft:#303030; + --st-ink-muted:#6f6f6f; /* Gainsty #7a7a7a darkened slightly for 4.5:1 on white */ + --st-icon:#2F384C; /* Anron default */ + + --st-accent:#10b981; + --st-accent-hover:#0c8a60; + --st-accent-ink:#ffffff; + --st-accent-tint:#ecfdf5; + --st-accent-text:#0c8a60; /* accent used as text on light */ + --st-focus:#405de6; + + --st-info:#0f97ff; --st-info-tint:#e8f4ff; --st-info-text:#0668c2; + --st-warn:#e39b0b; --st-warn-tint:#fff6e0; --st-warn-text:#8a5a00; /* (derived) */ + --st-danger:#e0283f; --st-danger-tint:#fdecee; --st-danger-text:#b01a2e; /* (derived) */ + + --st-code-bg:#1b1f23; --st-code-ink:#e6e9ec; /* code blocks stay dark in both themes (derived) */ + + --st-sh-card:0 18px 7px rgba(0,0,0,.01),0 10px 6px rgba(0,0,0,.02),0 4px 4px rgba(0,0,0,.03),0 1px 2px rgba(0,0,0,.04); + --st-sh-bar:0 54px 21px rgba(0,0,0,.01),0 30px 18px rgba(0,0,0,.03),0 13px 13px rgba(0,0,0,.05),0 3px 7px rgba(0,0,0,.06); + --st-sh-pop:0 10px 40px rgba(15,23,42,.08),0 1px 3px rgba(15,23,42,.06); + color-scheme:light; +} + +/* color — dark (all derived) */ +[data-theme="dark"]{ + --st-bg:#0e1113; + --st-surface:#161a1d; + --st-surface-2:#1d2226; + --st-line:#2a3036; + --st-line-soft:#22272c; + --st-ink:#eef1f3; + --st-ink-soft:#c7cdd3; + --st-ink-muted:#8e979f; + --st-icon:#c7cdd3; + + --st-accent:#34d399; + --st-accent-hover:#4ade80; + --st-accent-ink:#052e20; + --st-accent-tint:rgba(52,211,153,.12); + --st-accent-text:#4ade80; + --st-focus:#7b93ff; + + --st-info:#3aa9ff; --st-info-tint:rgba(58,169,255,.12); --st-info-text:#7cc4ff; + --st-warn:#f5b53d; --st-warn-tint:rgba(245,181,61,.12); --st-warn-text:#f8c96a; + --st-danger:#ff5a6e; --st-danger-tint:rgba(255,90,110,.12);--st-danger-text:#ff8a98; + + --st-code-bg:#0a0c0e; --st-code-ink:#e6e9ec; + + --st-sh-card:0 1px 2px rgba(0,0,0,.4); + --st-sh-bar:0 12px 32px rgba(0,0,0,.45),0 2px 6px rgba(0,0,0,.35); + --st-sh-pop:0 16px 48px rgba(0,0,0,.55),0 1px 3px rgba(0,0,0,.4); + color-scheme:dark; +} diff --git a/serve/winjob.py b/serve/winjob.py new file mode 100644 index 0000000..008642a --- /dev/null +++ b/serve/winjob.py @@ -0,0 +1,74 @@ +"""serve/winjob.py - on Windows, tie the processes Strata starts to the server's own lifetime. + +Closing the console window, Task Manager or a crash end the server without running its cleanup, and the engine, +the vision encoder and the MCP servers kept running on their own. `contain(proc)` puts a child in a job object that +is set to kill everything in it when its last handle closes - and the only handle is this process's, which the OS +closes however the server ends. Processes the child starts later join the same job. The server itself stays out of +the job, so a browser that `--open` starts is not tied to it. Elsewhere, and if the job cannot be made, a no-op. +""" +from __future__ import annotations + +import os +import threading + +_job = None +_lock = threading.Lock() + +if os.name == "nt": + import ctypes + from ctypes import wintypes + + _k32 = ctypes.WinDLL("kernel32", use_last_error=True) + + class _IoCounters(ctypes.Structure): + _fields_ = [(n, ctypes.c_ulonglong) for n in ("ReadOperationCount", "WriteOperationCount", + "OtherOperationCount", "ReadTransferCount", + "WriteTransferCount", "OtherTransferCount")] + + class _BasicLimits(ctypes.Structure): + _fields_ = [("PerProcessUserTimeLimit", ctypes.c_longlong), ("PerJobUserTimeLimit", ctypes.c_longlong), + ("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t), + ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD), + ("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD), + ("SchedulingClass", wintypes.DWORD)] + + class _ExtendedLimits(ctypes.Structure): + _fields_ = [("BasicLimitInformation", _BasicLimits), ("IoInfo", _IoCounters), + ("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t), + ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)] + + _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000 + _JobObjectExtendedLimitInformation = 9 + + _k32.CreateJobObjectW.restype = wintypes.HANDLE + _k32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR) + _k32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD) + _k32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE) + + def _make_job(): + job = _k32.CreateJobObjectW(None, None) # no security attributes: the handle is not inherited + if not job: + return None + info = _ExtendedLimits() + info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + if not _k32.SetInformationJobObject(job, _JobObjectExtendedLimitInformation, ctypes.byref(info), + ctypes.sizeof(info)): + _k32.CloseHandle(job) + return None + return job + + +def contain(proc) -> bool: + """Put a started subprocess.Popen in the kill-on-close job. True if it is in; False (harmlessly) otherwise.""" + global _job + if os.name != "nt" or proc is None: + return False + with _lock: + if _job is None: + _job = _make_job() or 0 + if not _job: + return False + try: + return bool(_k32.AssignProcessToJobObject(_job, int(proc._handle))) + except (AttributeError, OSError, ValueError): + return False diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..80d1fba --- /dev/null +++ b/setup.py @@ -0,0 +1,4422 @@ +#!/usr/bin/env python3 +"""Strata one-click setup and start (Windows and Linux, NVIDIA or AMD GPUs). + + START-HERE.bat (Windows) / ./setup.sh (Linux) - they install Python if needed and run this file + +The first time it asks four questions - which model (the original Qwen3.8-Flash-Next or the Swift 1.5 fine-tune), +which size, how much context, and whether the model should also read images - then installs everything and starts the model on http://127.0.0.1:8080 (OpenAI- and Anthropic-compatible +API; a small page there shows that it runs). Every later start skips straight to running the model: nothing that +is already downloaded, installed or prepared is done again. + +What the first run does (each step is skipped when it is already done): + + 1. checks your PC: NVIDIA or AMD GPU and driver, RAM, CPU, free disk space + 2. asks the questions + 3. installs the Python packages it needs into .venv (numpy, jinja2, ..., and NVIDIA's CUDA libraries) + 4. gets the Strata engine: a ready-made build for RTX 20/30/40/50 cards (no compiler needed); if none fits your PC, + it installs the build tools (asks first) and compiles the engine for your GPU. AMD (--backend hip, chosen by + itself on a PC with no usable NVIDIA card): the ready-made HIP engine on Windows, compiled here on Linux + 5. downloads the model from Hugging Face (resumable), and the vision encoder if you want images + 6. prepares the model for Strata and fetches the MTP draft layer (~5 GB, from the original Qwen checkpoint) + 7. writes run-.bat / run-.sh and starts the model + +Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --rope-scaling none|linear|yarn +(--rope-scale F; past the trained 262144 the setup adds yarn and the factor is the final context over 262144, +at least 1 - an explicit --rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port +8080, --yes (recommended +answers, no questions), --setup (install another model / change settings instead of starting), --no-start, +--host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off +(EXPERIMENTAL, off by default), +--models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-made +engine), --check (only check this PC), --resident-budget-gib N (UD-Q4_K_XL's or UD-IQ4_XS's experts in RAM), +--kv-streaming on|off|auto. + +Setup recommends, it never forces: the recommended answers are the defaults (--yes, or Enter), and a bigger choice +than it recommends - a longer context, more GPUs, a bigger RAM budget, a size it thinks will not fit - is kept, with +what it risks. With --yes, an explicit flag (--model, --gpus, ...) is the consent to a risk setup would otherwise +stop at; --yes alone is not. +""" +from __future__ import annotations + +import argparse +import ctypes +import hashlib +import json +import math +import os +import platform +import re +import shutil +import struct +import subprocess +import sys +import textwrap +import time +import urllib.error +import urllib.request +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +WIN = os.name == "nt" +# #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of +# https://huggingface.co/api/models/ when this was pinned), so a checkout installs the same files on any +# day. A revision the repository no longer has falls back to its current files, with a message (download()). +HF_REVISIONS = { + "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "ed59f92082b1e93c0e96d60a8b11aab089b52f09", # 2026-09-29 + "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "b22d729eae29b5796f76fb70f91aef549b9fc52c", # 2026-09-24 + "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF": "5348543e0147355ac9cbcb031184a3546350988e", # 2026-09-29 + "unsloth/Qwen3.8-Flash-Next-GGUF": "38bb39ee97821de2c9009abb7e93950eec396e66", # 2026-09-30 +} + + +HF_DEFAULT = "https://huggingface.co" + + +def hf_endpoint() -> str: + """#495: the Hugging Face host - HF_ENDPOINT as huggingface_hub reads it (a mirror, e.g. https://hf-mirror.com), + else huggingface.co. The pinned revisions and the SHA-256 checks are the same whichever host serves the files.""" + return (os.environ.get("HF_ENDPOINT") or "").strip().rstrip("/") or HF_DEFAULT + + +def hf(repo: str) -> str: + """The download folder of a Hugging Face repository at its pinned revision.""" + return f"{hf_endpoint()}/{repo}/resolve/{HF_REVISIONS[repo]}/" + + +def hf_unpinned(url: str) -> str: + """The same file at the repository's current revision (main).""" + return re.sub(r"^(https?://[^/]+/.+?/resolve/)[0-9a-f]{40}/", r"\1main/", url, count=1) + + +HF = hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF") +LLAMA_CPP_COMMIT = "3cf03257f219afbe7334045ff7c6a06ac68c627d" +LLAMA_CPP_ZIP = f"https://github.com/ggml-org/llama.cpp/archive/{LLAMA_CPP_COMMIT}.zip" + +# The ready-made engine: , a zip with strata(.exe), strata-vision(.exe) and BUILD.json, built +# by tools/make_release.py. Set this to the GitHub release download folder when publishing, e.g. +# "https://github.com//Strata/releases/latest/download/" (or pass --prebuilt / set STRATA_PREBUILT_URL). +# With the default, the release of this checkout's own version (PREBUILT_TAG_URL, CMakeLists.txt's version) is +# tried first and the latest release is the fallback (#214): an older checkout keeps the engine it shipped with. +PREBUILT_URL = "https://github.com/Niko1221/Strata/releases/latest/download/" +PREBUILT_TAG_URL = "https://github.com/Niko1221/Strata/releases/download/v{version}/" +PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" +# the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages +CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"] +MIN_DRIVER = 580 # CUDA 13.0 +# Older NVIDIA GPUs (experimental): CUDA 13 dropped Pascal (sm_60/61) and Volta (sm_70), so a model whose GPUs include +# one runs a second engine, built with CUDA 12.9 (-DSTRATA_EXPERIMENTAL_SM60=ON) and kept in its own folder: the +# ready-made one is CUDA12_ASSET (Windows; on Linux it is compiled here with a CUDA 12.x toolkit). One engine runs per +# model, so the choice is per model config, by its oldest GPU; --cuda 12|13 overrides it (docs/OLDER_GPUS.md). +CUDA13_MIN_ARCH = 75 # the oldest compute capability CUDA 13 compiles for (sm_75, RTX 20) +CUDA12_ASSET = "strata-windows-x64-cuda12.zip" if WIN else "strata-linux-x64-cuda12.zip" +CUDA12_WHEELS = ["nvidia-cublas-cu12==12.9.1.4", "nvidia-cuda-runtime-cu12==12.9.79"] +# CUDA 12.x minor-version compatibility (NVIDIA's table: Linux 525.60.13, Windows 527.41); the wheels match the 12.9.1 +# toolkit the CUDA 12 zip is built with (cuBLAS 12.9.1.4, runtime 12.9.79). Not tested on such an old driver here. +CUDA12_MIN_DRIVER = 528 if WIN else 525 +ENGINE12_DIR = "engine-cuda12" +MIN_ENGINE = (0, 1, 39) # v0.1.39: the #577 file-tier regression fixed, the OpenAI Responses API (#451, Codex), a reply stuck on one token ended (#606), the head before the arena (#620), effort_position (#458), --vram-reserve hot resize opt-in (#533), PR batch; v0.1.38: prompts faster (one gather per expert group #372, the first chunk's PLE rows beside layer 0 #374, DeltaNet three heads per thread #413), --kv q4_0 prompts on tensor cores (#452), Q5_0 experts on the GPU (#473), IQ4_XS on AVX-2 (#415), unbuffered expert loading on Windows (#357 #362), --peer-device (#531), a 6 GB card starts (#496), PR batch; v0.1.37: a silent engine is restarted (#481), Windows AMD counts the desktop's VRAM (#380 #377 #497), a steadier PCIe probe (#485), fixes #496 #495 #498 #505 #493; v0.1.36: a cancelled prompt logged as read so far (#471), the draft-head hint (#474), UPDATE.bat (#475), --expert-profile-save (#477); v0.1.35: Windows AMD uses its bundled HIP runtime (#468 #461), the low-RAM resident mode on Windows 32 GB (#467), fixes #460 #459 #446 #447 #457 #448 #444; v0.1.34: AMD on Windows (a ready-made HIP engine), an MCP server for AI assistants (tools/strata_mcp.py), a shorter README; v0.1.33: a portable image encoder again (#411 #412), setup recommends instead of forcing (#406 #403 #364 #384), fixes #352 #365 #369 #371 #375 #393 #408 #414; v0.1.32: split prompts faster (#340), AMD router +12%, Unsloth Q4 in setup, faster Q4 prompts, #326/#327/#342/#344 fixes, PR batch; v0.1.31: Unsloth UD-Q4_K_XL (experimental), GGUF-in-place low-RAM mode, Windows GGUF load 2x, server race + tokenizer fixes, AMD intrinsics; v0.1.30: short prompts faster (streaming from 1024 tokens), resident low-RAM variant, multi-GPU session carve, RDNA4; v0.1.29: sampled answers faster (split top-k), #154 correctness fixes; v0.1.28: the expert cache reserves the draft head, a cancelled request no longer fails the next; v0.1.27: RTX 20 (sm_75) in the ready-made engine, the HIP build without CUDA headers; v0.1.26: the draft layer's prompt pass in batches; v0.1.25: faster prompts (grouping off the copy engine, fused hyper-connection kernels), AMD HIP backend, --kv k8v4; v0.1.24: long prompts faster (QSA select on tensor cores); v0.1.23: image requests honor sampling, 8 GB cards start, batched verify window; v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties +PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"] +REQUIREMENTS = ROOT / "requirements.txt" # the same packages and their dependencies, pinned (#214) + +MODELS = { + # the original model only for now: Swift 1.5's Q2_0 files split one layer's experts across the two shards, which + # the pack tool (tools/iq_pack.py) cannot prepare yet (#171) + "Q2_0": {"about": "2-bit, the fastest", "download_gb": 66.4, "ram_gb": 48, "arena_gb": 34.0, "families": ("qwen",)}, + "IQ2_XS": {"about": "2-bit i-quant, a little better quality, close in speed", "download_gb": 68.0, "ram_gb": 48, + "arena_gb": 35.5}, + "IQ3_XXS": {"about": "3-bit i-quant, better quality, slower (more CPU work per token)", "download_gb": 75.8, + "ram_gb": 60, "arena_gb": 42.9}, + # the original model only (Swift 1.5 has no IQ3_S): matches the full BF16 model on the published benchmarks + "IQ3_S": {"about": "3.5-bit i-quant, the best quality (matches the full model), the slowest; needs a 64 GB PC " + "with little else running", "download_gb": 83.6, "ram_gb": 62, "arena_gb": 50.3, + "families": ("qwen",)}, + # the Coder release: 256 of the 512 experts kept (the ones code, tools and vision use), IQ2_S-IQ4_XS like IQ3_S + "IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4, + "ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)}, + # EXPERIMENTAL (docs/UNSLOTH_Q4.md): Unsloth's 4-bit file; its 77 GB of experts do not fit a 64 GB PC, so the engine + # keeps a RAM budget of them (--resident-budget-gib, chosen below) and reads the rest from the GGUF on the SSD + "UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), EXPERIMENTAL: the best quality, but most experts come from the " + "SSD on a 64 GB PC (7-8.5 tokens/s measured)", "download_gb": 111.3, "ram_gb": 48, + "arena_gb": 77.0, "families": ("unsloth",), "budget": True, "nvidia_only": True, + "experimental": True}, + # #621: Unsloth's UD-IQ4_XS - IQ3_S gate/up experts with IQ4_NL (43 layers) or Q8_0 (5) downs, the dense side as + # UD-Q4_K_XL's; three shards. A regular choice from 0.1.39 (no longer experimental). Its 59.5 GB of experts: a + # RAM budget of them, like UD-Q4_K_XL, but far fewer read from the SSD on a 64 GB PC and none from ~80 GB of RAM. + # Images: the vision path has no restriction for this pack (the same base model and image encoder), so setup asks + "UD-IQ4_XS": {"about": "~4-bit i-quant (Unsloth Dynamic), between IQ3_S and UD-Q4_K_XL in quality; on a PC with " + "less than ~80 GB of RAM part of its experts are read from the SSD", + "download_gb": 93.7, "ram_gb": 48, "arena_gb": 59.5, "families": ("unsloth",), "budget": True, + "shards": 3, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00003.gguf", "engine": (0, 1, 38), + "vision": True}, +} +# The experimental Unsloth file's four shards at the pinned revision: name -> (bytes, sha256), checked after the +# download (setup trusts no other model file by name and size alone either: check_shards reads their directories). +UNSLOTH_SHARDS = { + "Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf": + (10946624, "4448186216b3af4cc558bbce2c3213f01608f8f8b2e5267a9767971dd3ec8082"), + "Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf": + (49859583136, "3f342f1c1580473f1ee94ddd5b28206e8c07a70fa1a366f59d1d6c922919a6c9"), + "Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf": + (49376141504, "56758f40269cad5cd9b0d3d6fbae0f40f6d5be6de49e4ab392dbe83157d9cbd3"), + "Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf": + (12087983520, "753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a"), +} +# #621: UD-IQ4_XS's three shards at the same revision (sizes and SHA-256: the Hub's LFS pointers) +UNSLOTH_IQ4_XS_SHARDS = { + "Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf": + (10946624, "5ce89370720f8bf90890f439361282104c1aa1482d4013bb9a50923e758e71a4"), + "Qwen3.8-Flash-Next-UD-IQ4_XS-00002-of-00003.gguf": + (49835229856, "577a38a2392b40ca2193cea502e1d92f60b8cd370675d308e0ec21885d9daaa7"), + "Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00003.gguf": + (43836407744, "d4634e6d84f0ebb0940be15c90d3790bf6464e3dea3a1cddc567dc0e83ad8833"), +} +UNSLOTH_ENGINE = (0, 1, 32) # the first engine setup configures for UD-Q4_K_XL (0.1.31 ran it by hand) +UNSLOTH_RAM_LEFT_GB = 24 # RAM beside the budget: the OS, the engine, and the file cache the rest is read through +# Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will +# serve the setup resolves the method (yarn, or one question when interactive) and derives the factor +# from the final context (final / 262144, at least 1) itself (below), keeps an explicit +# --rope-scaling/--rope-scale, and refuses an explicit --rope-scaling none there - the stock angles past +# the trained range are out of spec. +CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288] +# The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. +FAMILIES = { + "qwen": {"title": "Qwen3.8-Flash-Next", "by": "Qwen; GSQ-RCO quants by ISTA-DASLab", + "about": "the original model", + "hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF") + "{q}/", + "file": "Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "", + "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), + "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next"}, + "swift": {"title": "Swift 1.5", "by": "UkisAI's fine-tune of Qwen3.8-Flash-Next", + "about": "thinks much shorter (-63% thinking tokens, 1.8x sooner answers by its authors' numbers)", + "hf": hf("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), + "file": "Swift-Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "swift-", + "mmproj_hf": hf("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), + "mmproj": "mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf", "name": "swift-1.5", + "license": "Swift Open License 1.0: https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"}, + # ISTA-DASLab's expert-pruned release: half of each layer's experts removed, chosen for code, agentic tool use and + # vision; its shard 2 (the n-gram table) and vision encoder are the original's files, shared with it + "coder": {"title": "Qwen3.8-Flash-Next Coder", "by": "ISTA-DASLab's coding version", + "about": "half the experts (code, tools, images kept): needs ~32 GB of RAM, faster; weaker outside coding", + "hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF") + "{q}/", + "file": "Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "coder-", + "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF"), + "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-coder", + "profile": "expert-profile-coder.bin"}, + # Unsloth's UD-IQ4_XS (three shards, #621; a regular choice from 0.1.39) and the EXPERIMENTAL UD-Q4_K_XL (four) + # of the original model (docs/UNSLOTH_Q4.md); "experimental" and "vision" are per model (MODELS) + "unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "by": "Unsloth's ~4-bit quantizations", + "about": "UD-IQ4_XS: a 94 GB download; with less than ~80 GB of RAM part of its experts are read from " + "the SSD (UD-Q4_K_XL, 111 GB: experimental)", + "hf": hf("unsloth/Qwen3.8-Flash-Next-GGUF") + "{q}/", + "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf", "shards": 4, "tag": "unsloth-", + "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), + "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-unsloth", + "vision": False, "pack_args": ["--compat-bf16"], + "sha256": {**UNSLOTH_SHARDS, **UNSLOTH_IQ4_XS_SHARDS}}, +} +MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" +# EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README +ESP_VECTOR = ROOT / "data" / "experimental-speed-projection" / "Qwen3.8-Flash-Next-experimental-speed-projection.gguf" +# the image encoder on the GPU (~1.2 GB at 1024 image tokens) warms up before the engine starts, so the engine +# sizes its expert slots around it and the default reserve (700 MiB) is enough; engines before 0.1.2 need more +VISION_GPU_SMALL_RESERVE_MIB = 1000 # the tip for images on a <= 12 GB card (the engine's LOW line asked ~1003) +VISION = {"gpu": {"max_tokens": 1024, "reserve_mib": 700}, + "cpu": {"max_tokens": 300, "reserve_mib": 700}} +EXE = "strata.exe" if WIN else "strata" +VEXE = "strata-vision.exe" if WIN else "strata-vision" + + +# ------------------------------------------------------------------------------------------------ output +def say(msg=""): + print(msg, flush=True) + + +def step(n, title): + say() + say(f"=== Step {n}: {title} ===") + + +def ok(msg): + say(f" [ok] {msg}") + + +def warn(msg): + say(f" [!] {msg}") + + +def fail(msg, hint=None): + say(f"\n [X] {msg}") + if hint: + say(f" {hint}") + say("\nSetup stopped. Fix the item above and run it again - everything already done is kept and skipped.") + sys.exit(1) + + +def ask(question, choices, default, yes): + if yes: + return default + while True: + try: + a = input(f"{question} [{default}]: ").strip() + except EOFError: + fail("input ended before a setup answer was received", + "run setup in a terminal, or pass --yes to accept the recommended answers") + if not a: + return default + if a.lower() in [c.lower() for c in choices]: + return next(c for c in choices if c.lower() == a.lower()) + say(f" please answer one of: {', '.join(choices)}") + + +def run(cmd, cwd=None, env=None, check=True, quiet=False): + say(" > " + " ".join(str(c) for c in cmd)) + r = subprocess.run([str(c) for c in cmd], cwd=cwd, env=env, + stdout=subprocess.PIPE if quiet else None, stderr=subprocess.STDOUT if quiet else None, + text=True) + if check and r.returncode != 0: + if quiet and r.stdout: + say(r.stdout[-4000:]) + fail(f"command failed (exit {r.returncode}): {Path(str(cmd[0])).name}") + return r + + +def out(cmd): + try: + return subprocess.run(cmd, capture_output=True, text=True, timeout=60).stdout + except (OSError, subprocess.TimeoutExpired): + return "" + + +def done(path: Path) -> bool: + """A step's finish mark: .done exists (written only after the step completed).""" + return path.with_name(path.name + ".done").exists() + + +def mark(path: Path, text=""): + path.with_name(path.name + ".done").write_text(text or time.strftime("%Y-%m-%d %H:%M"), encoding="utf-8") + + +# ------------------------------------------------------------------------------------------------ the PC +def _memory_status(): + """Windows' GlobalMemoryStatusEx: RAM, and the commit limit (ullTotalPageFile = RAM + page file).""" + class MS(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] + m = MS() + m.dwLength = ctypes.sizeof(MS) + ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)) + return m + + +def ram_gb(): + if WIN: + return _memory_status().ullTotalPhys / 2**30 + for line in open("/proc/meminfo"): + if line.startswith("MemTotal"): + return int(line.split()[1]) * 1024 / 2**30 + return 0.0 + + +def page_file_gb(): + """The page file's current size (GB) on Windows, None elsewhere. The graphics card's memory needs room there + too: under Windows' driver model every allocation on the card is also charged to the commit (RAM + page file), + so with the page file off or tiny the engine cannot use the free VRAM (issue #60).""" + if not WIN: + return None + m = _memory_status() + return max(0.0, (m.ullTotalPageFile - m.ullTotalPhys) / 2**30) + + +def cpu_cores(): + """#642: (performance cores, efficiency cores) of a hybrid CPU (Intel 12th gen+, AMD Zen 5 + Zen 5c), counted + as the engine's pool counts them (detect_cpu_topology: physical cores, by Windows' EfficiencyClass or Linux's + cpu_capacity); None on a CPU whose cores are all alike, or when the OS does not say.""" + classes = [] # one entry per physical core: its efficiency/capacity class + try: + if WIN: + k32 = ctypes.windll.kernel32 + n = ctypes.c_ulong(0) + k32.GetLogicalProcessorInformationEx(0, None, ctypes.byref(n)) # RelationProcessorCore: the size + if not n.value: + return None + buf = ctypes.create_string_buffer(n.value) + if not k32.GetLogicalProcessorInformationEx(0, buf, ctypes.byref(n)): + return None + raw, at = buf.raw[:n.value], 0 + while at + 10 <= len(raw): # SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX: Relationship, Size, then + rel, size = struct.unpack_from(" int | None: + """#642 (Hardin22's measurement): on a hybrid CPU the expert pool runs best on the P-cores but the host loop's one + plus HALF of the E-cores - an E-core runs the expert kernels ~2.2x slower and each layer waits for its slowest + part (i9-14900KF, 8P + 16E: 15 workers decoded 165 / 116 tok/s against 106 / 84 with all 23). Only on a CPU with + more E-cores than P-cores: on an i7-13700KF (8P + 8E, docs/AMD_HIP.md's gfx1030 report) all 15 workers decoded + 38-42 tok/s against 36 with 8, so there the engine's own count stays. None: the engine's own default (one worker + per physical core but the host's) stays.""" + if not cores: + return None + p, e = cores + if e <= p: + return None + return max(1, p - 1 + e // 2) + + +def recommend_pool_workers(args: list) -> list: + """`args` with setup's recommended `--pool-workers` for a hybrid CPU, unless they set one already (a calibration's + measured count, or the user's own). A recommendation: the config line can be edited or removed.""" + n = hybrid_pool_workers(cpu_cores()) + if n is None or "--pool-workers" in args: + return args + p, e = cpu_cores() + ok(f"hybrid CPU ({p} performance + {e} efficiency cores): {n} CPU expert workers - the performance cores and half " + "of the efficiency cores (--pool-workers in the config; START-HERE --calibrate measures it on this PC)") + return [*args, "--pool-workers", str(n)] + + +def cpu_info(): + """(name, avx2, avx512): avx512 means everything Strata's fast AVX-512 kernels use (F, BW, VL, VNNI, VBMI), + the same test the engine makes (cpu_avx512_ok), not just AVX-512F.""" + name, avx2, avx512 = platform.processor() or "unknown CPU", False, False + if WIN: + pf = ctypes.windll.kernel32.IsProcessorFeaturePresent + avx2 = bool(pf(40)) or _cpuid_avx2() # PF_AVX2_INSTRUCTIONS_AVAILABLE, else the CPU itself (#159) + n = out(["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_Processor).Name"]).strip() + name = n or name + avx512 = bool(pf(41)) and _cpuid_avx512_full() + else: + try: + txt = open("/proc/cpuinfo").read() + flags = set(re.search(r"^flags\s*:\s*(.*)$", txt, re.M).group(1).split()) + avx2 = "avx2" in flags + avx512 = {"avx512f", "avx512bw", "avx512vl", "avx512_vnni", "avx512vbmi"} <= flags + m = re.search(r"^model name\s*:\s*(.*)$", txt, re.M) + name = m.group(1) if m else name + except OSError: + pass + return name, avx2, avx512 + + +def _cpuid_floor() -> str: + """Below AVX2 (Windows): "avx" when the CPU has AVX and the OS saves the YMM registers, "sse4.2" with SSE4.2 and + POPCNT, else "".""" + try: + regs = (ctypes.c_uint32 * 4)() + _run_stub(bytes([0x53, 0x49, 0x89, 0xC8, 0x89, 0xD0, 0x31, 0xC9, 0x0F, 0xA2, # push rbx; r8=rcx; eax=edx; ecx=0; cpuid + 0x41, 0x89, 0x00, 0x41, 0x89, 0x58, 0x04, 0x41, 0x89, 0x48, 0x08, # [r8]=eax, [r8+4]=ebx, [r8+8]=ecx + 0x41, 0x89, 0x50, 0x0C, 0x5B, 0xC3]), # [r8+12]=edx; pop rbx + ctypes.addressof(regs), 1) + ecx1 = regs[2] + if (ecx1 >> 27) & 1 and (ecx1 >> 28) & 1: # OSXSAVE, AVX + xcr0 = (ctypes.c_uint32 * 2)() + _run_stub(bytes([0x49, 0x89, 0xC8, 0x31, 0xC9, 0x0F, 0x01, 0xD0, # r8=rcx; ecx=0; xgetbv + 0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, 0xC3]), ctypes.addressof(xcr0)) + if xcr0[0] & 6 == 6: + return "avx" + return "sse4.2" if (ecx1 >> 20) & 1 and (ecx1 >> 23) & 1 else "" + except Exception: + return "" + + +def cpu_floor(avx2: bool) -> str: + """The experimental older-CPU build this PC needs (#394 #595 #623): "" with AVX2 (the normal engine), "avx" (Sandy / + Ivy Bridge, AMD Bulldozer), "none" (SSE4.2 + POPCNT: Nehalem, Westmere), or "unsupported". STRATA_ISA_FLOOR=avx| + none asks for that build on any PC (testing it on a newer one).""" + forced = os.environ.get("STRATA_ISA_FLOOR", "").strip().lower() + if forced in ("avx", "none"): + return forced + if avx2: + return "" + if WIN: + f = _cpuid_floor() + else: + try: + txt = open("/proc/cpuinfo").read() + flags = set(re.search(r"^flags\s*:\s*(.*)$", txt, re.M).group(1).split()) + except (OSError, AttributeError): + flags = set() + f = "avx" if "avx" in flags else "sse4.2" if {"sse4_2", "popcnt"} <= flags else "" + return {"avx": "avx", "sse4.2": "none"}.get(f, "unsupported") + + +def _cpuid_avx512_full() -> bool: + """Windows has no feature bit for VNNI / VBMI: ask the CPU (CPUID leaf 7) through a tiny machine-code stub.""" + try: + code = bytes([0x53, 0x49, 0x89, 0xC8, 0xB8, 0x07, 0x00, 0x00, 0x00, 0x31, 0xC9, 0x0F, 0xA2, # push rbx; r8=rcx; cpuid(7,0) + 0x41, 0x89, 0x18, 0x41, 0x89, 0x48, 0x04, 0x5B, 0xC3]) # [r8]=ebx,[r8+4]=ecx; pop rbx + k32 = ctypes.windll.kernel32 + k32.VirtualAlloc.restype = ctypes.c_void_p + buf = k32.VirtualAlloc(None, len(code), 0x3000, 0x40) + if not buf: + return False + ctypes.memmove(buf, code, len(code)) + regs = (ctypes.c_uint32 * 2)() + ctypes.CFUNCTYPE(None, ctypes.c_void_p)(buf)(ctypes.addressof(regs)) + ebx, ecx = regs[0], regs[1] + need_ebx = (1 << 16) | (1 << 30) | (1 << 31) # F, BW, VL + need_ecx = (1 << 1) | (1 << 11) # VBMI, VNNI + return (ebx & need_ebx) == need_ebx and (ecx & need_ecx) == need_ecx + except Exception: + return False + + +def _run_stub(code: bytes, *args) -> None: + """Runs a few bytes of x64 machine code (Windows calling convention: the arguments in rcx, rdx).""" + k32 = ctypes.windll.kernel32 + k32.VirtualAlloc.restype = ctypes.c_void_p + k32.VirtualFree.argtypes = (ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32) + buf = k32.VirtualAlloc(None, len(code), 0x3000, 0x40) + if not buf: + raise OSError("VirtualAlloc failed") + try: + ctypes.memmove(buf, code, len(code)) + ctypes.CFUNCTYPE(None, *[ctypes.c_void_p] * len(args))(buf)(*args) + finally: + k32.VirtualFree(buf, 0, 0x8000) + + +def _cpuid_avx2() -> bool: + """AVX2 asked from the CPU (CPUID leaf 7 EBX bit 5), with the OS saving the YMM registers (OSXSAVE + XCR0): + Windows' IsProcessorFeaturePresent(PF_AVX2) says no on some PCs whose CPU has it (a Ryzen 9 3950X, #159).""" + try: + def cpuid(leaf): + regs = (ctypes.c_uint32 * 4)() + _run_stub(bytes([0x53, 0x49, 0x89, 0xC8, 0x89, 0xD0, 0x31, 0xC9, 0x0F, 0xA2, # push rbx; r8=rcx; eax=edx; ecx=0; cpuid + 0x41, 0x89, 0x00, 0x41, 0x89, 0x58, 0x04, 0x41, 0x89, 0x48, 0x08, # [r8]=eax, [r8+4]=ebx, [r8+8]=ecx + 0x41, 0x89, 0x50, 0x0C, 0x5B, 0xC3]), # [r8+12]=edx; pop rbx + ctypes.addressof(regs), leaf) + return list(regs) + if cpuid(0)[0] < 7: + return False + ecx1 = cpuid(1)[2] + if not (ecx1 >> 27) & 1 or not (ecx1 >> 28) & 1: # OSXSAVE, AVX + return False + xcr0 = (ctypes.c_uint32 * 2)() + _run_stub(bytes([0x49, 0x89, 0xC8, 0x31, 0xC9, 0x0F, 0x01, 0xD0, # r8=rcx; ecx=0; xgetbv + 0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, 0xC3]), ctypes.addressof(xcr0)) + if xcr0[0] & 6 != 6: # the OS saves XMM and YMM + return False + return bool((cpuid(7)[1] >> 5) & 1) + except Exception: + return False + + +def gpus(): + """Every NVIDIA GPU, numbered as nvidia-smi numbers them (by PCI bus, the order the engine is told to use).""" + s = out(["nvidia-smi", "--query-gpu=index,name,memory.total,compute_cap,driver_version", + "--format=csv,noheader,nounits"]) + found = [] + for line in s.strip().splitlines(): + try: + idx, name, mem, cc, drv = [x.strip() for x in line.split(",")] + found.append({"index": int(idx), "name": name, "vram_gb": float(mem) / 1024.0, "arch": cc.replace(".", ""), + "driver": drv}) + except ValueError: + continue + return found + + +GPU_PICK = None # --gpu N (issue #51); None: the card with the most VRAM +SPLIT_MIN_VRAM_GB = 8 # a card sharing a model holds the dense weights and its own + # prompt buffers too (docs/MULTI_GPU.md) +SPLIT_PROMPT_VRAM_GB = 12 # #448: a split stage lends a prompt chunk's buffers from its + # own cache; below this one cannot fund a 4096-token chunk + # (a 10 GB RTX 3080 beside a 32 GB card: 512 tokens, prompts + # 6.2x slower), while the big card alone could + + +def cc(g) -> str: + return f"{g['arch'][:-1]}.{g['arch'][-1]}" + + +OLD_GPUS = None # why Pascal / Volta cards are admitted in this run (old_gpus_opt_in), None: they are not + + +def experimental_sm60() -> bool: + """#295: STRATA_EXPERIMENTAL_SM60=1 admits Pascal (6.x) and Volta (7.0) cards, run by the experimental CUDA 12 + engine (-DSTRATA_EXPERIMENTAL_SM60=ON). So does naming such a card (--gpu N / --gpus), --cuda 12, or a PC that + has no newer card (old_gpus_opt_in).""" + return os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1" or OLD_GPUS is not None + + +def sm60_card(arch) -> bool: + return 60 <= int(arch) <= 70 + + +def old_gpus_opt_in(found, named=(), cuda=None, other=False): + """Why this run may use Pascal / Volta cards (the experimental CUDA 12 engine), or None. The cards are an opt-in: + the user named one (`named`: --gpu / --gpus), asked for --cuda 12, set STRATA_EXPERIMENTAL_SM60=1, or the PC has + no card the ready-made engine runs on and no supported AMD card (`other`; it used to stop there). A PC with a + newer card keeps recommending it.""" + old = [g for g in found if sm60_card(g["arch"])] + if not old: + return None + if os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1": + return "STRATA_EXPERIMENTAL_SM60=1" + if str(cuda) == "12": + return "--cuda 12" + picked = [g for g in old if g["index"] in set(named)] + if picked: + return "you chose " + ", ".join(f"GPU {g['index']} ({g['name']})" for g in picked) + if not other and not any(int(g["arch"]) >= CUDA13_MIN_ARCH for g in found): + return "it is the only kind of NVIDIA GPU in this PC" + return None + + +def named_gpus(gpu, gpus) -> list: + """The card numbers --gpu / --gpus name (an unreadable value: none; parse_gpus says what is wrong later).""" + try: + if gpus and str(gpus).strip().lower() != "all": + return [int(x) for x in str(gpus).split(",") if x.strip()] + return [int(gpu)] if gpu is not None else [] + except ValueError: + return [] + + +def cuda_choice(archs, cuda=None): + """The CUDA toolkit of one model's engine: (12 or 13, why). 13 (the ready-made engine) unless a card is older + than CUDA 13 supports (Pascal / Volta: CUDA 13 cannot compile for them) - one engine runs per model, so its oldest + card decides. `cuda` (--cuda 12|13) overrides it; setup recommends, it does not refuse (the caller warns).""" + archs = sorted({int(x) for x in archs}) + old = [a for a in archs if a < CUDA13_MIN_ARCH] + if str(cuda) == "13": + return 13, ("--cuda 13 (as you chose)" + (f"; CUDA 13 has no code for sm_{old[0]}: the engine will not run " + "on that card" if old else "")) + if str(cuda) == "12": + return 12, "--cuda 12 (as you chose" + ("; RTX 50 (sm_120) engines built with CUDA 12.8 crashed on long " + "prompts, #220" if archs and archs[-1] >= 120 else "") + ")" + if old: + return 12, (f"sm_{old[0]} is older than CUDA 13 supports (it dropped Pascal and Volta): this model runs the " + "experimental CUDA 12 engine") + return 13, None + + +def engine_dir(toolkit=13) -> Path: + """The folder of the engine a model runs: engine/ (CUDA 13, or HIP), engine-cuda12/ (the experimental one).""" + return ROOT / (ENGINE12_DIR if int(toolkit) == 12 else "engine") + + +def config_toolkit(cfg: dict) -> int: + """12 when a model config runs the experimental CUDA 12 engine (its exe is in engine-cuda12/), else 13.""" + return 12 if cfg.get("cuda") == 12 or Path(str(cfg.get("exe", ""))).parent.name == ENGINE12_DIR else 13 + + +def gpu_problem(g, together=False): + """Why Strata cannot use this card, in plain words (None: it can).""" + if int(g["arch"]) < 75 and not (sm60_card(g["arch"]) and experimental_sm60()): + return (f"not supported - older than the RTX 20 series (compute capability {cc(g)}; Strata needs 7.5 or " + "newer" + ("; experimental: choose it with --gpu " + str(g["index"]) + " (the CUDA 12 engine, " + "docs/OLDER_GPUS.md)" if sm60_card(g["arch"]) else "") + ")") + if together and g["vram_gb"] < SPLIT_MIN_VRAM_GB - 0.5: + return (f"not supported together with other GPUs - {g['vram_gb']:.0f} GB of VRAM (a card sharing the model " + f"needs {SPLIT_MIN_VRAM_GB} GB or more)") + return None + + +def gpu_rank(g): + """The order cards share a model in: the newest generation first (it gets the first layers and most of the + work), then the most VRAM.""" + return (-int(g["arch"]), -round(g["vram_gb"]), g["index"]) + + +def gpu_name(g) -> str: + return f"GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB)" + + +def gpu_table(found) -> None: + say(" Your NVIDIA GPUs:") + for g in found: + p = gpu_problem(g) + say(f" GPU {g['index']}: {g['name']}, {g['vram_gb']:.0f} GB VRAM - " + ("can be used" if p is None else p)) + + +def together_ok(found) -> list: + """The cards that can share one model, in the order they would (empty if fewer than two).""" + ok_ = sorted([g for g in found if gpu_problem(g, together=True) is None], key=gpu_rank) + return ok_ if len(ok_) >= 2 else [] + + +def split_short(cards) -> list: + """#448: the later cards of a split that would cap its prompt chunk below what the first card alone reads (a card + under SPLIT_PROMPT_VRAM_GB beside one that has it). Empty: the split is recommended as before.""" + if len(cards) < 2 or cards[0]["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5: + return [] + return [g for g in cards[1:] if g["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5] + + +def split_short_note(g) -> str: + return (f"GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB) is too small to lend a split its prompt buffers: " + "it would cap prompt reading at 512-2048-token chunks, several times slower than the first card alone " + "(#448). It can serve as a helper expert cache instead (docs/SECOND_GPU.md)") + + +def parse_gpus(text, found) -> list: + """--gpus / --gpu with several: "0,2" or "all" (every card that can share the model).""" + if str(text).strip().lower() == "all": + sel = [g["index"] for g in together_ok(found)] + if not sel: + gpu_table(found) + fail("--gpus all: this PC does not have two GPUs Strata can use together") + return sel + try: + sel = [int(x) for x in str(text).split(",") if x.strip()] + except ValueError: + fail(f"--gpus takes GPU numbers as nvidia-smi numbers them, e.g. --gpus 0,2 (or --gpus all), not {text!r}") + if len(sel) < 2 or len(set(sel)) != len(sel): + fail("--gpus takes two or more different GPUs, e.g. --gpus 0,2 (one GPU: --gpu 0)") + return sel + + +def check_gpus(sel, found, what="", yes=False, named=False) -> None: + """Stops with a plain message when a chosen card is missing or cannot be used, and says what can. named: the user + named these cards (--gpus 0,1, or a config that has them): a card that is only short of VRAM for sharing the model + is then a risk to confirm, not a stop (the owner's rule; --yes with the named cards is the consent).""" + together = len(sel) > 1 + for i in sel: + g = next((x for x in found if x["index"] == i), None) + p = "not found on this PC" if g is None else gpu_problem(g, together) + if p is None: + continue + if named and g is not None and gpu_problem(g) is None: # it runs Strata; only its VRAM is small + confirm_risk(f"GPU {i} ({g['name']}) has {g['vram_gb']:.0f} GB of VRAM: a card sharing the model needs " + f"{SPLIT_MIN_VRAM_GB} GB or more (it holds the dense weights of its layers and its own prompt " + "buffers), so the model may not start, or run slower than without it", True, yes, + f"GPU {i} ({g['name']}) {what}is not used together with other GPUs: {p}", + "leave it out of --gpus, or answer y to use it anyway", " Use it anyway?") + warn(f"GPU {i} ({g['name']}) is used together with the others, as you chose") + continue + say() + gpu_table(found) + can = together_ok(found) + single = [x for x in found if gpu_problem(x) is None] + ones = " or ".join(f"--gpu {x['index']}" for x in single) + both = "--gpus " + ",".join(str(x["index"]) for x in can) if can else "" + hint = ((f"use these together: {both}" + (f" (or one card: {ones})" if not together else "")) if can else + f"use one card: {ones}" if single else "Strata needs an NVIDIA RTX 20 series or newer card") + fail(f"GPU {i}{'' if g is None else ' (' + g['name'] + ')'} {what}cannot be used: {p}", hint) + + +def engine_archs(toolkit=13): + """The GPU generations the installed engine has code for: (archs, ptx), or None when there is none.""" + info = engine_dir(toolkit) / "BUILD.json" + try: + meta = json.loads(info.read_text()) + except (OSError, ValueError): + return None + return [int(x) for x in meta.get("archs", [])], bool(meta.get("ptx")) + + +def engine_archs_hip(): + """The AMD architectures the installed HIP engine was compiled for ("gfx1201", ...), or None.""" + try: + meta = json.loads((ROOT / "engine" / "BUILD.json").read_text()) + except (OSError, ValueError): + return None + return [str(x) for x in meta.get("archs", [])] if meta.get("backend") == "hip" else None + + +def engine_runs_on(g, toolkit=13) -> bool: + ea = engine_archs(toolkit) + if ea is None or not ea[0]: + return True + archs, ptx = ea + return int(g["arch"]) in archs or (ptx and int(g["arch"]) > max(archs)) + + +def start_gpus(text): + """--gpus when starting an installed model: NVIDIA cards as nvidia-smi numbers them, or on a PC whose AMD cards + are the ones Strata can use, AMD cards as setup lists them ("all": every supported AMD card).""" + if not text: + return None + if str(text).strip().lower() == "all" and not WIN and not together_ok(gpus()): + amd = amd_gpus() + if len([g for g in amd if amd_problem(g) is None]) >= 2: + return [g["index"] for g in amd_parse_gpus("all", amd)] + return parse_gpus(text, gpus()) + + +def choose_gpus(a, found) -> list: + """Which cards this install uses: --gpus / --gpu, or asked when two or more can share the model (the two best + together recommended), else the supported card with the most VRAM. Returns their numbers, the main one first.""" + if a.gpus: + sel = parse_gpus(a.gpus, found) + check_gpus(sel, found, yes=a.yes, named=str(a.gpus).strip().lower() != "all") + return sel + if a.gpu is not None: + check_gpus([a.gpu], found) + return [a.gpu] + single = sorted([g for g in found if gpu_problem(g) is None], key=lambda x: (-round(x["vram_gb"]), x["index"])) + if not single: + gpu_table(found) + fail("none of your GPUs can run Strata", "it needs an NVIDIA RTX 20 series or newer (compute capability 7.5+)") + can = together_ok(found) + if not can: + return [single[0]["index"]] + say() + say(f" Strata can run the model on one GPU, or share it across {'these' if len(can) > 2 else 'both'}: then each" + " card holds the") + say(" experts of its own layers, so together they hold about twice as many, and prompts are read about 20%") + say(" faster (details: docs/MULTI_GPU.md). A much slower extra card can also make it slower.") + opts = [can[:2]] + ([can] if len(can) > 2 else []) + [[g] for g in single] + # #448: a pair whose second card cannot lend a 4096-token chunk recommends the first card alone (still offered) + short = split_short(can[:2]) + rec = next(i for i, o in enumerate(opts, 1) if o == [can[0]]) if short else 1 + for i, o in enumerate(opts, 1): + label = (" + ".join(gpu_name(g) for g in o) + " together") if len(o) > 1 else gpu_name(o[0]) + " only" + say(f" {i}) {label}" + (" (recommended)" if i == rec else "")) + for g in found: + if gpu_problem(g, together=True) is not None: + say(f" (GPU {g['index']}, {g['name']}: {gpu_problem(g, together=True)})") + for g in short: + say(f" ({split_short_note(g)})") + pick = opts[int(ask("Which GPUs?", [str(i) for i in range(1, len(opts) + 1)], str(rec), a.yes or a.check)) - 1] + return [g["index"] for g in pick] + + +def split_mmap(cfg: dict) -> bool: + """#364 #384: the low-RAM mode's resident variant (--resident-experts) has no layer split yet. A config with it + that runs on several GPUs reads the experts the GPUs do not hold through the OS file cache instead + (--mmap-experts: the placement those reports measured 1.3-1.6x faster than one GPU), said plainly - the engine + used to refuse the pair. True when the config changed.""" + a = cfg.get("args", []) + if "--resident-experts" not in a: + return False + a[a.index("--resident-experts")] = "--mmap-experts" + warn("the low-RAM mode's resident variant (--resident-experts) has no layer split yet: on several GPUs the experts " + "the GPUs do not hold are read through the OS file cache (--mmap-experts) instead, and RAM can fill up to 0 " + "free during long prompts. One GPU keeps them in RAM (steady RAM use): START-HERE --setup, or --gpu N for a " + "start") + return True + + +def model_file(fam: dict, model: str, i: int) -> str: + """Shard i's file name: the family's pattern, or the model's own (#621: UD-IQ4_XS has three shards, not four).""" + return MODELS.get(model, {}).get("file", fam["file"]).format(q=model, i=i) + + +def model_shards(fam: dict, model: str) -> int: + return MODELS.get(model, {}).get("shards", fam.get("shards", 2)) + + +def budget_model(cfg: dict) -> str: + """The Unsloth model a config with a RAM budget runs, from its --native shard's name (UD-Q4_K_XL by default).""" + a = cfg.get("args", []) + native = Path(a[a.index("--native") + 1]).name.upper() if "--native" in a and a.index("--native") + 1 < len(a) \ + else "" + return next((m for m, d in MODELS.items() if d.get("budget") and f"-{m}-" in native), "UD-Q4_K_XL") + + +def unsloth_split_need_gb(model="UD-Q4_K_XL") -> float: + """#498: the RAM UD-Q4_K_XL needs on several GPUs, where it has no RAM budget (the engine refuses + --resident-budget-gib with a layer split): its GGUF files and UNSLOTH_RAM_LEFT_GB more (~135 GB). Measured safe + at 165 GiB (2x RTX 3090: MemAvailable never under 68 GiB); the 0-free case of #384 was 47 GB with a 70 GB model.""" + return MODELS[model]["download_gb"] + UNSLOTH_RAM_LEFT_GB + + +def split_budget(cfg: dict) -> bool: + """#498: a UD-Q4_K_XL config (its RAM budget, --resident-budget-gib) started on several GPUs. The engine refuses + the budget with a layer split (it exited with code 2), so the split runs without it - all the experts loaded into + RAM at start - where the RAM holds the GGUFs and 24 GB more; else setup stops, before the config is saved. True + when the config changed.""" + a = cfg.get("args", []) + if "--resident-budget-gib" not in a: + return False + model = budget_model(cfg) + need, ram = unsloth_split_need_gb(model), ram_gb() + if ram < need: + fail(f"{model} cannot share its RAM budget across GPUs (the engine has no layer split with it), and without " + f"the budget it needs ~{need:.0f} GB of RAM (its GGUF files and {UNSLOTH_RAM_LEFT_GB} GB more); this PC " + f"has {ram:.0f} GB", "start it on one GPU: START-HERE.bat --gpu N (Linux: ./setup.sh --gpu N)") + i = a.index("--resident-budget-gib") + del a[i:i + 2] + ok(f"{model} on several GPUs: no RAM budget (the engine has none with a layer split) - all its experts are " + "loaded into RAM from the model files at start, and the files pass through the OS file cache (#498)") + return True + + +REMOTE_EXPERT_OPT = "--remote-expert-opt" + + +def recommend_remote_expert_opt(cfg: dict, off: bool = False) -> None: + """0.1.39b (#578): a config on two or more GPUs gets --remote-expert-opt - the helper expert caches + (--expert-cache-device1..3) then stay complementary to the main GPU's, return their rows already weighted and skip + the CPU's activation quantization where no expert is left to it (dual RTX 4090: +63% mixed, +132% code over the + plain helper path). The engine uses it only with a helper cache; a layer split runs as before. A recommendation: + `off` (setup's --no-remote-expert-opt) or "remote_expert_opt": false in the config keeps it out, and a single-GPU + config is not touched.""" + if not isinstance(cfg.get("gpu"), list) or len(cfg["gpu"]) < 2: + return + args = cfg.setdefault("args", []) + if off or cfg.get("remote_expert_opt") is False: + if REMOTE_EXPERT_OPT in args: + args.remove(REMOTE_EXPERT_OPT) + return + if REMOTE_EXPERT_OPT not in args: + args.append(REMOTE_EXPERT_OPT) + ok("multi-GPU: --remote-expert-opt (helper expert caches complementary to the main GPU's, #578; " + "--no-remote-expert-opt leaves it out)") + + +def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: + """Starting a model set up for one card on a PC with two or more that can share it: asked once (the answer is + saved in its config).""" + if isinstance(cfg.get("gpu"), list) or cfg.get("gpus_asked"): + return cfg + found = gpus() + can = together_ok(found) + if not can: + return cfg + # #498: UD-Q4_K_XL's RAM budget has no layer split; without it the RAM must hold the GGUFs and 24 GB more + budget = "--resident-budget-gib" in cfg.get("args", []) + if budget and ram_gb() < unsloth_split_need_gb(budget_model(cfg)): + return cfg + pair = can[:2] + cfg["gpus_asked"] = True + # #364 #384: the resident low-RAM variant stays on one card unless the user says otherwise (its RAM use is steady) + resident = "--resident-experts" in cfg.get("args", []) + say() + say(" This PC has " + " and ".join(gpu_name(g) for g in pair) + ": Strata can share the model across both.") + say(" Together they hold about twice the model's experts and read prompts about 20% faster (docs/MULTI_GPU.md).") + if resident: + say(" This model runs in the low-RAM mode with its experts kept in RAM, on one GPU (recommended: steady RAM") + say(" use). On both, the experts the GPUs do not hold are read through the OS file cache instead: faster in") + say(" two reports (#364, #384), but RAM can fill up to 0 free during long prompts.") + if budget: + say(f" This model ({budget_model(cfg)}) runs on one GPU with a RAM budget of its experts (recommended: the tested") + say(" setup). On both it has no budget: all its experts are loaded into RAM at start, which this PC's RAM") + say(" holds - about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s).") + short = split_short(pair) # #448: one card recommended (asked "n" by default), as for --resident + for g in short: + say(f" {split_short_note(g)}.") + tk = config_toolkit(cfg) + missing = [g for g in pair if not (engine_runs_on(g) if tk == 13 else engine_runs_on(g, tk))] + if missing: + say(" The installed engine has no code for " + ", ".join(g["name"] for g in missing) + ": to use them " + "together, run START-HERE.bat --setup --gpus " + ",".join(str(g["index"]) for g in pair)) + elif ask(" Use both from now on? (you can change it later: START-HERE.bat --gpu N for one card)", + ["y", "n"], "n" if resident or short or budget else "y", yes) == "y": + cfg["gpu"] = [g["index"] for g in pair] + cfg["layer_split"] = cfg.get("layer_split") or "auto" + split_mmap(cfg) + split_budget(cfg) + recommend_remote_expert_opt(cfg) + ok("from now on this model runs on " + " + ".join(gpu_name(g) for g in pair)) + else: + ok("staying on one GPU (START-HERE.bat --gpus " + ",".join(str(g["index"]) for g in pair) + " switches)") + write_config(cfg_path, cfg) + return cfg + + +def gpu_info(pick=None): + """The GPU Strata runs on: `pick` (nvidia-smi's number) if given, else the one with the most VRAM (ties: the + lower number). None when there is no NVIDIA GPU. The dict also says how many there are ("count").""" + found = gpus() + if not found: + return None + pick = GPU_PICK if pick is None else pick + if pick is not None: + g = next((x for x in found if x["index"] == pick), None) + if g is None: + fail(f"there is no GPU {pick}: " + ", ".join(f"{x['index']} = {x['name']}" for x in found)) + else: + g = max(found, key=lambda x: (round(x["vram_gb"]), -x["index"])) + return {**g, "count": len(found)} + + +def find_nvcc(below=None): + """The newest CUDA toolkit's nvcc and its (major, minor); with `below`, the newest older than that version. + #601: STRATA_NVCC= is the only one considered (a newer toolkit beside it that cannot build on this + PC - CUDA 12.9 with glibc 2.43 - is not taken instead).""" + pick = os.environ.get("STRATA_NVCC") + if pick: + if not Path(pick).exists(): + warn(f"STRATA_NVCC={pick}: no such file; looking for a CUDA toolkit as usual") + else: + v = re.search(r"release (\d+)\.(\d+)", out([pick, "--version"])) + ver = (int(v.group(1)), int(v.group(2))) if v else None + if ver and below is not None and ver >= below: + warn(f"STRATA_NVCC={pick} is CUDA {ver[0]}.{ver[1]}; this build needs one older than " + f"{below[0]}.{below[1]}") + return (None, None) + return (pick, ver) if ver else (None, None) + cands = [shutil.which("nvcc")] + for var in ("CUDA_PATH", "CUDA_HOME"): # CUDA_HOME: Linux's usual name (#601) + if os.environ.get(var): + cands.append(str(Path(os.environ[var]) / "bin" / ("nvcc.exe" if WIN else "nvcc"))) + if WIN: + base = Path(r"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA") + if base.exists(): + cands += [str(p / "bin" / "nvcc.exe") for p in sorted(base.iterdir(), reverse=True)] + else: + cands += [str(p / "bin" / "nvcc") for p in sorted(Path("/usr/local").glob("cuda*"), reverse=True)] + cands += [str(p / "bin" / "nvcc") for p in sorted(Path("/opt").glob("cuda*"), reverse=True)] # Arch (#46) + best = (None, None) + for c in dict.fromkeys(cands): # every toolkit found; the newest wins + if c and Path(c).exists(): + v = re.search(r"release (\d+)\.(\d+)", out([c, "--version"])) + ver = (int(v.group(1)), int(v.group(2))) if v else None + if ver and (below is None or ver < below) and (best[1] is None or ver > best[1]): + best = (c, ver) + return best + + +def find_vcvars(): + vswhere = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Microsoft Visual Studio/Installer/vswhere.exe" + if not vswhere.exists(): + return None + # CUDA 13 accepts Visual Studio 2019 and 2022 only: a newer one (2026 = version 18) installed next to them + # must not be picked ("unsupported Microsoft Visual Studio version"); with only a newer one there is none + p = out([str(vswhere), "-latest", "-products", "*", "-version", "[16.0,18.0)", "-requires", + "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"]).strip() + v = Path(p) / "VC/Auxiliary/Build/vcvars64.bat" if p else None + return v if v and v.exists() else None + + +def find_tool(name): + """A tool on PATH, or the one pip installed next to this Python (cmake, ninja).""" + p = shutil.which(name) + if p: + return p + for d in (Path(sys.executable).parent / "Scripts", Path(sys.executable).parent, + Path.home() / ".local" / "bin"): + c = d / (name + (".exe" if WIN else "")) + if c.exists(): + return str(c) + return None + + +def free_gb(path): + path.mkdir(parents=True, exist_ok=True) + return shutil.disk_usage(path).free / 1e9 + + +# ------------------------------------------------------------------------------------------------ downloads +def drop_archive(z: Path) -> None: + """An unpacked or refused engine archive and its .done mark go: a refused one kept them, and every later run + reused it ("already downloaded") instead of the published one (PR #324).""" + z.unlink(missing_ok=True) + z.with_name(z.name + ".done").unlink(missing_ok=True) + + +def download(url, dst: Path, what=None): + """Resumable HTTP(S) download with a progress line; `file://` and plain paths are copied (tests, mirrors). + A finished file gets a .done mark, so a later run skips it without asking the server.""" + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.exists() and done(dst): + ok(f"{what or dst.name} already downloaded") + return + if not url.startswith(("http://", "https://")): + src = Path(url[7:] if url.startswith("file://") else url) + if not src.exists(): + fail(f"not found: {src}") + shutil.copyfile(src, dst) + mark(dst) + ok(f"{what or dst.name} copied") + return + part = dst.with_name(dst.name + ".part") + total = 0 + for attempt in range(5): + try: + req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"}) + total = int(urllib.request.urlopen(req, timeout=60).headers.get("Content-Length", 0)) + break + except urllib.error.HTTPError as e: + if e.code == 404 and hf_unpinned(url) != url: # #214: the pinned revision is gone from the repository + warn(f"{what or dst.name}: not at the pinned revision any more; downloading the repository's " + "current file") + url = hf_unpinned(url) + continue + if attempt == 4: + fail(f"cannot reach {url.split('/')[2]} ({e})", "check your internet connection and run it again") + time.sleep(5) + except OSError as e: + if attempt == 4: + fail(f"cannot reach {url.split('/')[2]} ({e})", "check your internet connection and run it again") + time.sleep(5) + if dst.exists() and total and dst.stat().st_size == total: # finished by an older setup (no mark yet) + mark(dst) + ok(f"{what or dst.name} already downloaded") + return + have = part.stat().st_size if part.exists() else 0 + for attempt in range(30): + try: + req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={have}-"}) + with urllib.request.urlopen(req, timeout=60) as r, open(part, "ab" if have else "wb") as f: + if have and r.status != 206: # the server ignored the range: start over + f.seek(0) + f.truncate() + have = 0 + last = 0.0 + while True: + b = r.read(8 << 20) + if not b: + break + f.write(b) + have += len(b) + if time.time() - last > 2: + last = time.time() + size = f"{have / 1e9:6.2f} / {total / 1e9:.2f} GB ({100 * have / total:.0f}%)" if total \ + else f"{have / 1e6:7.1f} MB" + print(f"\r {what or dst.name}: {size} ", end="", flush=True) + print() + if not total or have >= total: + break + except OSError as e: + print() + warn(f"download interrupted ({e}); retrying in 10 s ...") + time.sleep(10) + if total and part.stat().st_size != total: + fail(f"could not finish downloading {dst.name}: {part.stat().st_size:,} bytes on disk, the server says {total:,}", + "check your internet connection and run it again (the download resumes where it stopped)") + part.replace(dst) + mark(dst) + ok(f"{what or dst.name} downloaded") + + +def whole_shard(s: Path) -> bool: + """A shard as long as its own tensor directory says (check_shards' test, without stopping setup).""" + sys.path.insert(0, str(ROOT / "tools")) + from gguf_reader import GGUFFile + try: + g = GGUFFile(s) + return s.stat().st_size >= g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors), + default=0) + except (OSError, ValueError, struct.error): + return False + + +SHARD_NAME = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$") + + +def gguf_dir_shards(folder: Path, fam: dict, model: str) -> list[Path]: + """--gguf-dir's shards (#305): every -0000i-of-0000N file of the model, N read from the first shard's name as the + engine and tools/iq_pack.py do. The published name first; else the one first shard in the folder whose name has + the size in it (an upload split or named differently: -00001-of-00003, Unsloth's ...-00001-of-00004.gguf). A + missing shard is check_shards' error later, as before.""" + first = folder / model_file(fam, model, 1) + if not first.exists(): + found = sorted(p for p in folder.glob("*-00001-of-*.gguf") if SHARD_NAME.search(p.name)) + mine = [p for p in found if model.lower() in p.name.lower()] + pick = mine if mine else found + if len(pick) == 1: + first = pick[0] + m = SHARD_NAME.search(first.name) + total = int(m.group(2)) if m else 1 + if not m or total < 1: + return [first] + stem = first.name[:m.start()] + return [first.with_name("%s-%05d-of-%05d.gguf" % (stem, i, total)) for i in range(1, total + 1)] + + +# #444: the quantization in a GGUF's name (Unsloth's UD-IQ3_XXS, a K-quant's Q2_K_XL, a GSQ-RCO IQ3_S, ...) +GGUF_QUANT = re.compile(r"(? str | None: + """#444: the quantization a GGUF's name says, when it is one Strata cannot run (not a setup size); else None.""" + m = GGUF_QUANT.search(name) + return m.group(1) if m and m.group(1).upper() not in MODELS and not name.lower().startswith("mmproj") else None + + +def gguf_choice(name: str) -> tuple | None: + """#444: (--family, --model) whose published first shard this file is, or None (the Coder's IQ1_M is named like + the original's sizes: the size tells them apart).""" + for f, d in FAMILIES.items(): + for m in MODELS: + if f in MODELS[m].get("families", ("qwen", "swift")) and name == model_file(d, m, 1): + return f, m + return None + + +def gguf_dir_problem(folder: Path, first: Path, fam: dict, model: str) -> tuple | None: + """#444: (message, hint) when --gguf-dir has no file setup can use for this choice: the chosen shard is a GGUF + Strata cannot run (Unsloth's UD-IQ3_XXS taken for IQ3_XXS by its name), or it is missing and the folder holds + other GGUFs - then the hint names the --family/--model of the usable ones. None otherwise (a missing shard in a + folder without GGUFs stays check_shards' "missing").""" + bad = gguf_unsupported(first.name) if first.exists() else None + if bad: + return f"{first.name} is {bad}, a GGUF Strata cannot run", SUPPORTED_GGUFS + if first.exists(): + return None + firsts = sorted(p.name for p in folder.glob("*.gguf") + if not p.name.lower().startswith("mmproj") and (not SHARD_NAME.search(p.name) + or SHARD_NAME.search(p.name).group(1) == "00001")) + usable = list(dict.fromkeys(c for c in map(gguf_choice, firsts) if c)) + unusable = [n for n in firsts if gguf_unsupported(n)] + if not usable and not unusable: + return None + hint = SUPPORTED_GGUFS + if unusable: + hint += ".\n Not usable here: " + ", ".join(unusable) + if usable: + hint += ".\n Usable here: " + ", ".join(f"--family {f} --model {m}" for f, m in usable) + return f"{folder} has no {fam['title']} {model} file", hint + + +def verify_sha256(s: Path, size: int, sha: str) -> None: + """A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark, + so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again.""" + m = s.with_name(s.name + ".done") + if m.exists() and f"sha256 {sha}" in m.read_text(encoding="utf-8", errors="replace"): + return + have = s.stat().st_size if s.exists() else -1 + if have != size: + fail(f"{s.name} is {have:,} bytes, not {size:,}", "delete it and run setup again (the download restarts)") + say(f" checking {s.name} (SHA-256, {size / 1e9:.1f} GB) ...") + h = hashlib.sha256() + with open(s, "rb") as f: + while True: + b = f.read(16 << 20) + if not b: + break + h.update(b) + if h.hexdigest() != sha: + s.unlink(missing_ok=True) + m.unlink(missing_ok=True) + fail(f"{s.name} has the wrong SHA-256 ({h.hexdigest()}, expected {sha}): deleted", + "run setup again to download it again") + mark(s, f"sha256 {sha}") + + +def resident_budget_gib(model, ram, kv_ram_gb=0.0) -> int: + """UD-Q4_K_XL: the GiB of experts the engine keeps in RAM (--resident-budget-gib): the RAM (GiB, ram_gb()) less + 24 for the OS, the engine and the file cache the other experts are read through, less a KV cache streamed to + RAM; at most all of them, at least 8. 64 GB: 40, the measured setting (docs/UNSLOTH_Q4.md).""" + gib = round(ram) - UNSLOTH_RAM_LEFT_GB - math.ceil(kv_ram_gb) + return max(8, min(gib, int(MODELS[model]["arena_gb"] / 1.073741824))) + + +def budget_choice(model, ram, asked) -> float: + """S4: UD-Q4_K_XL's RAM budget: --resident-budget-gib N as given, else the recommendation (resident_budget_gib). + More than the recommendation is kept, with what it risks (the owner's rule: setup recommends, it never forces).""" + rec = resident_budget_gib(model, ram) + if asked is None: + return rec + if asked > rec: + warn(f"a {asked:g} GiB RAM budget is more than setup recommends for this PC ({rec} GiB: the RAM less " + f"{UNSLOTH_RAM_LEFT_GB} GB for the OS, the engine and the file cache that reads the other experts). Kept " + "as you chose: the engine clamps it to the RAM it finds free at start (less 4 GB), and the file cache " + "gets less room - it may be slower, or run the PC out of RAM under load") + return int(asked) if asked == int(asked) else asked + + +def check_shards(shards): + """Every shard present and whole, or setup stops naming the file and the numbers. Whole means as long as + its own tensor directory says (the header is read, the data is not): a truncated copy (--gguf-dir, a .part + renamed by hand, a download finished by an older setup) otherwise passes as a model file and the engine + fails much later, at the first tensor that runs past the end.""" + sys.path.insert(0, str(ROOT / "tools")) + from gguf_reader import GGUFFile + for s in shards: + if not s.exists(): + fail(f"missing {s}") + try: + g = GGUFFile(s) + except (ValueError, struct.error) as e: + fail(f"{s.name} is not a whole GGUF shard ({e})", "delete it and run setup again") + need = g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors), default=0) + have = s.stat().st_size + if have < need: + fail(f"{s.name} is short: {have:,} of {need:,} bytes ({need - have:,} missing)", + "delete it and run setup again (or copy the whole file into --gguf-dir)") + + +def get_llama_cpp(): + """llama.cpp at the pinned commit (ggml for the build, gguf-py for the tools, mtmd for images), as a zip: no git.""" + llama = ROOT / "third_party" / "llama.cpp" + if (llama / "ggml" / "CMakeLists.txt").exists() and (llama / "gguf-py").is_dir(): + return llama + z = ROOT / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip" + download(LLAMA_CPP_ZIP, z, "llama.cpp source") + tmp = ROOT / "third_party" / "_unpack" + shutil.rmtree(tmp, ignore_errors=True) + with zipfile.ZipFile(z) as f: + # llama.cpp's own web UI (tools/ui) is not used, and its deep paths passed Windows' 260-character limit in a + # folder like Downloads\Strata-main\Strata-main (#206) + f.extractall(tmp, [m for m in f.namelist() if "/tools/ui/" not in m]) + top = next(tmp.iterdir()) + shutil.rmtree(llama, ignore_errors=True) + # PR #63: on Windows a rename can fail with PermissionError while an antivirus scanner still holds a file of the + # fresh unpack; shutil.move falls back to copy-and-delete, and a few retries let the scanner finish. The target + # is `llama` itself - moving into its parent would keep the zip's `llama.cpp-` folder name. + for attempt in range(5): + try: + shutil.move(str(top), str(llama)) + break + except PermissionError: + if attempt == 4: + raise + shutil.rmtree(llama, ignore_errors=True) # a partial copy from the failed attempt + time.sleep(2) + shutil.rmtree(tmp, ignore_errors=True) + z.unlink(missing_ok=True) + z.with_name(z.name + ".done").unlink(missing_ok=True) + return llama + + +def req_name(line: str) -> str: + """The distribution name of a requirement line ("numpy==2.5.3; python_version >= '3.12'" -> "numpy").""" + return re.split(r"[\s<>=!~;\[]", line.strip(), maxsplit=1)[0].lower().replace("_", "-") + + +def requirement_lines(path: Path | None = None) -> list[str]: + """requirements.txt's requirements, comments and blank lines left out.""" + lines = [] + for raw in (path or REQUIREMENTS).read_text(encoding="utf-8").splitlines(): + line = raw.split("#", 1)[0].strip() + if line: + lines.append(line) + return lines + + +def _installed(name: str) -> bool: + try: + import importlib.metadata as md + md.distribution(name) + return True + except Exception: + return False + + +def pip_install(packages, what): + """pip install into .venv, skipped when the same list was installed before. An install from before the pinned + requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the + pinned dependencies it already has count as installed.""" + stamp = Path(sys.prefix) / ".strata-pip.json" + have = json.loads(stamp.read_text()) if stamp.exists() else [] + bare = {p.lower() for p in have if req_name(p) == p.lower()} + need = [p for p in packages if p not in have and req_name(p) not in bare + and not (bare and "==" in p and _installed(req_name(p)))] + if not need: + ok(f"{what} already installed") + return + say(f" Installing {what} ...") + run([sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", *need]) + stamp.write_text(json.dumps(sorted(set(have) | set(need)), indent=0)) + ok(f"{what} installed") + + +def cuda_lib_dirs(toolkit=13): + """Where pip put NVIDIA's CUDA libraries (nvidia/cu13/bin/x86_64 on Windows, nvidia/cu13/lib on Linux). + toolkit 12: the CUDA 12 wheels' cuBLAS and runtime, in two folders (nvidia/cublas/bin, nvidia/cuda_runtime/bin).""" + if int(toolkit) == 12: + patterns = ("cublas64_12.dll", "cudart64_12.dll") if WIN else ("libcublas.so.12*", "libcudart.so.12*") + else: + patterns = ("cublas64_13.dll",) if WIN else ("libcublas.so.13*",) + dirs = [] + for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}: + for pattern in patterns: + for hit in (sp / "nvidia").rglob(pattern) if (sp / "nvidia").is_dir() else []: + if hit.parent not in dirs: + dirs.append(hit.parent) + return [str(d) for d in dirs] + + +# ------------------------------------------------------------------------------------------------ AMD +# The RX 7900 XT / XTX (gfx1100) and the RX 9070 series / Radeon AI PRO R9700 (gfx1201) on Linux, through the HIP +# backend (docs/AMD_HIP.md); the RX 7800 XT / 7700 XT (gfx1101, #254) and the RX 9060 XT (gfx1200, #256) were run by +# their owners; the RX 6800 / 6900 series (gfx1030, #311) and the RX 6700 XT (gfx1031, #524) run but are unvalidated. There is no ready-made AMD engine: ROCm comes from AMD's TheRock Python wheels into .venv (no sudo; +# a system ROCm 7 in /opt/rocm is used when it has hipcc and hipBLAS) and the engine is compiled here for the cards. +# No images yet. +ROCM_INDEXES = {"gfx1100": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", # TheRock's wheels per GPU family + "gfx1101": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", + "gfx1200": "https://rocm.nightlies.amd.com/v2/gfx120X-all/", + "gfx1201": "https://rocm.nightlies.amd.com/v2/gfx120X-all/", + "gfx1030": "https://rocm.nightlies.amd.com/v2/gfx103X-all/", + "gfx1031": "https://rocm.nightlies.amd.com/v2/gfx103X-all/"} +ROCM_VERSION = os.environ.get("STRATA_ROCM_VERSION", "7.10.0a20251120") # what Strata's HIP build was tested with +ROCM_SYSTEM_MIN = (7, 0) # an older system ROCm is passed over for the wheels (gfx1201 needs ROCm 6.4 or newer) +AMD_ARCHS = ("gfx1100", "gfx1101", "gfx1200", "gfx1201", "gfx1030", "gfx1031") +AMD_NAMES = {"gfx1100": "AMD Radeon RX 7900 series (gfx1100)", # when sysfs has no product name + "gfx1101": "AMD Radeon RX 7800 XT / 7700 XT (gfx1101)", + "gfx1200": "AMD Radeon RX 9060 series (gfx1200)", + "gfx1201": "AMD Radeon RX 9070 series / AI PRO R9700 (gfx1201)", + "gfx1030": "AMD Radeon RX 6800 / 6900 series (gfx1030)", + "gfx1031": "AMD Radeon RX 6700 XT series (gfx1031)"} +AMD_CARDS = ("the RX 7900 XT / XTX (gfx1100), RX 7800 XT / 7700 XT (gfx1101), RX 9060 XT (gfx1200) and " + "RX 9070 / 9070 XT / Radeon AI PRO R9700 (gfx1201), and the RX 6800 / 6900 series (gfx1030) and RX 6700 XT " + "(gfx1031, #524), both unvalidated") + + +def rocm_index(arch): + return os.environ.get("STRATA_ROCM_INDEX") or ROCM_INDEXES[arch] + + +def amd_gpus(sysfs="/sys"): + """AMD GPUs from the kernel's KFD topology (the amdgpu driver; no ROCm needed), numbered as HIP numbers them: + the GPU nodes in order, the CPU nodes skipped. Integrated GPUs are listed too (not supported). + sysfs: the tree to read (tools/test_setup_amd.py passes a mocked one). Windows: amd_gpus_win.""" + if WIN: + return amd_gpus_win() + base = Path(sysfs) / "class/kfd/kfd/topology/nodes" + found = [] + if not base.is_dir(): + return found + for node in sorted((p for p in base.iterdir() if p.name.isdigit()), key=lambda p: int(p.name)): + try: + props = {} + for line in (node / "properties").read_text().splitlines(): + k, _, v = line.partition(" ") + props[k] = v.strip() + ver = int(props.get("gfx_target_version") or 0) + if ver == 0 or int(props.get("simd_count") or 0) == 0: + continue + except (OSError, ValueError): + continue + arch = f"gfx{ver // 10000}{(ver // 100) % 100:x}{ver % 100:x}" + dev = Path(sysfs) / f"class/drm/renderD{props.get('drm_render_minor', '')}/device" + try: + vram = int((dev / "mem_info_vram_total").read_text()) / 2 ** 30 + except (OSError, ValueError): + vram = 0.0 + try: + name = (dev / "product_name").read_text().strip() or f"AMD Radeon ({arch})" + except OSError: + name = f"AMD Radeon ({arch})" + if name == f"AMD Radeon ({arch})" and arch in AMD_NAMES: + name = AMD_NAMES[arch] + found.append({"index": len(found), "name": name, "vram_gb": vram, "arch": arch, "driver": "amdgpu", + "vendor": "amd"}) + return found + + +def amd_problem(g): + if g["arch"] not in AMD_ARCHS: + return f"not supported - Strata's AMD backend runs on {AMD_CARDS} only, this is {g['arch']}" + if g.get("cannot_run"): # Windows: the installed engine's own check (--list-devices) + return g["cannot_run"] + return None + + +def amd_gpus_win() -> list[dict]: + """Windows: the AMD GPUs as the HIP runtime numbers them once the HIP engine is installed (hip_devices), else in + the display-adapter order (amd_gpus_windows).""" + return hip_devices() or amd_gpus_windows() + + +def amd_parse_gpus(text, amd) -> list: + """--gpus with AMD cards, numbered as HIP numbers them (setup's list): "1,0", or "all" (every supported card, the + most VRAM first). Every chosen card must be one Strata supports (AMD_ARCHS; they may be of different + architectures: the engine is compiled for each). Returns the cards, the main one first.""" + usable = [g for g in amd if amd_problem(g) is None] + if str(text).strip().lower() == "all": + sel = [g["index"] for g in sorted(usable, key=lambda x: (-round(x["vram_gb"]), x["index"]))] + else: + try: + sel = [int(x) for x in str(text).split(",") if x.strip()] + except ValueError: + fail(f"--gpus takes AMD GPU numbers as setup lists them, e.g. --gpus 1,0 (or --gpus all), not {text!r}") + if len(sel) < 2 or len(set(sel)) != len(sel): + fail("--gpus takes two or more different GPUs, e.g. --gpus 1,0 (one GPU: --gpu 1)", + "this PC has " + (f"{len(usable)} AMD card{'s' if len(usable) != 1 else ''} Strata can use" + + (": " + ", ".join(f"GPU {g['index']} ({g['name']})" for g in usable) if usable else ""))) + byid = {g["index"]: g for g in amd} + for i in sel: + g = byid.get(i) + p = "not found on this PC" if g is None else amd_problem(g) + if p is not None: + fail(f"AMD GPU {i}{'' if g is None else ' (' + g['name'] + ')'} cannot be used: {p}", + ("use these together: --gpus " + ",".join(str(x["index"]) for x in usable)) if len(usable) >= 2 else + ("use one card: --gpu " + str(usable[0]["index"])) if usable else f"the AMD backend runs on {AMD_CARDS}") + return [byid[i] for i in sel] + + +# ------------------------------------------------------------------------------------------------ AMD on Windows +# Windows has no KFD topology: the cards are found from the display adapters (Win32_VideoController: the ones present, +# with their PCI ids) and the display-class registry (each adapter's 64-bit VRAM size), before any AMD software is +# needed. The engine is the ready-made HIP one (WIN_HIP_ASSET: strata.exe, strata-device.exe and the ROCm libraries it +# loads, built by tools/hip/build_windows.bat); it needs only the AMD driver. Once it is installed, the cards are +# numbered as the HIP runtime numbers them (`strata-device --list-devices`): an integrated Radeon takes HIP's device 0 +# and pushes the discrete card to 1, which the display-adapter order does not show (#325). +WIN_HIP_ASSET = "strata-windows-x64-hip.zip" +WIN_HIP_MIN_ENGINE = max(MIN_ENGINE, (0, 1, 33)) # the first release with a Windows HIP engine +WIN_AMD_DRIVER = "https://www.amd.com/en/support/download/drivers.html" +# PCI device ids (VEN_1002) of the cards the AMD backend knows; the names below cover a card whose id is not listed +_WIN_AMD_DID = {0x744C: "gfx1100", 0x7448: "gfx1100", 0x745E: "gfx1100", # RX 7900 XTX/XT/GRE, W7900, W7800 + 0x747E: "gfx1101", # RX 7800 XT / 7700 XT + 0x7480: "gfx1102", # RX 7600 / 7600 XT + 0x7590: "gfx1200", # RX 9060 XT + 0x7550: "gfx1201", 0x7551: "gfx1201", # RX 9070 / 9070 XT, AI PRO R9700 + 0x73BF: "gfx1030", 0x73AF: "gfx1030", 0x73A5: "gfx1030"} # RX 6800 / 6800 XT / 6900 XT / 6950 XT +_WIN_AMD_NAME = ((re.compile(r"\b9070\b|R9700", re.I), "gfx1201"), + (re.compile(r"\b9060\b", re.I), "gfx1200"), + (re.compile(r"RX\s*7900|W7900|W7800", re.I), "gfx1100"), + (re.compile(r"RX\s*7800|RX\s*7700(?!\s*S)|W7700", re.I), "gfx1101"), + (re.compile(r"RX\s*7600|W7600|W7500", re.I), "gfx1102"), + (re.compile(r"RX\s*6800(?!\s*[MS])|RX\s*6900|RX\s*6950|W6800", re.I), "gfx1030")) +_DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}" + + +def _win_display_adapters() -> list[dict]: + """The display adapters present ({"name", "pnp"}), from Win32_VideoController.""" + ps = ("Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name + '|' + $_.PNPDeviceID + '|' + " + "$_.AdapterRAM }") + text = out(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps]) + found = [] + for line in text.splitlines(): + parts = line.strip().split("|") + if len(parts) >= 2 and parts[1]: + ram = parts[2] if len(parts) > 2 else "" + found.append({"name": parts[0].strip(), "pnp": parts[1].strip(), + "ram": int(ram) if ram.strip().isdigit() else 0}) + return found + + +def _win_display_registry() -> list[dict]: + """Each display driver instance's description, matching PCI id and VRAM size (the 64-bit value; the WMI one stops + at 4 GB), from the display-class registry key - readable without admin.""" + found = [] + try: + import winreg + cls = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _DISPLAY_CLASS) + except (ImportError, OSError): + return found + i = 0 + while True: + try: + sub = winreg.EnumKey(cls, i) + except OSError: + break + i += 1 + if not sub.isdigit(): + continue + try: + key = winreg.OpenKey(cls, sub) + except OSError: + continue + vals = {} + for name in ("DriverDesc", "MatchingDeviceId", "HardwareInformation.qwMemorySize", "DriverVersion"): + try: + vals[name] = winreg.QueryValueEx(key, name)[0] + except OSError: + pass + found.append(vals) + return found + + +def _pci_device_id(text: str) -> int | None: + m = re.search(r"VEN_1002&DEV_([0-9A-F]{4})", str(text or ""), re.I) + return int(m.group(1), 16) if m else None + + +def win_amd_arch(device_id: int | None, name: str) -> str: + """A Windows AMD adapter's architecture from its PCI device id, else its name; "" when it is none Strata knows + (an integrated Radeon, an older card).""" + if device_id in _WIN_AMD_DID: + return _WIN_AMD_DID[device_id] + return next((a for rx, a in _WIN_AMD_NAME if rx.search(name or "")), "") + + +def amd_gpus_windows(adapters=None, registry=None) -> list[dict]: + """The AMD display adapters present, in display-adapter order (setup's numbering until the HIP engine is + installed), with the arch Strata would run them as ("" = unknown: listed, not supported). adapters / registry: + tools/test_setup_amd.py passes mocked ones.""" + adapters = _win_display_adapters() if adapters is None else adapters + registry = _win_display_registry() if registry is None else registry + if not adapters: # no WMI answer: the registry alone (it can list removed cards) + adapters = [{"name": r.get("DriverDesc", ""), "pnp": r.get("MatchingDeviceId", ""), "ram": 0} for r in registry] + used = set() + found = [] + for ad in adapters: + did = _pci_device_id(ad.get("pnp")) + if did is None: + continue # not an AMD (VEN_1002) PCI device + vram, driver = 0.0, "" + for k, r in enumerate(registry): # the same card's driver instance: its 64-bit VRAM size + if k in used or _pci_device_id(r.get("MatchingDeviceId")) != did: + continue + if r.get("DriverDesc") and ad.get("name") and r["DriverDesc"].strip() != ad["name"].strip(): + continue + used.add(k) + mem = r.get("HardwareInformation.qwMemorySize") + if isinstance(mem, bytes): + mem = int.from_bytes(mem[:8], "little") + vram = int(mem) / 2 ** 30 if isinstance(mem, int) and mem > 0 else 0.0 + driver = str(r.get("DriverVersion") or "") + break + if vram == 0.0 and ad.get("ram", 0) > 0: + vram = ad["ram"] / 2 ** 30 # WMI's 32-bit figure (at most 4 GB) + arch = win_amd_arch(did, ad.get("name", "")) + name = ad.get("name") or AMD_NAMES.get(arch, f"AMD Radeon (device {did:04X})") + found.append({"index": len(found), "name": name, "vram_gb": vram, "arch": arch or f"unknown (PCI {did:04X})", + "driver": driver or "amd", "vendor": "amd"}) + return found + + +def hip_devices(probe: Path | None = None, text: str | None = None) -> list[dict] | None: + """The GPUs the HIP runtime enumerates, numbered as HIP_VISIBLE_DEVICES numbers them, from the installed engine's + `strata-device --list-devices`; None when there is no HIP engine here or it does not answer. text: its output + (tests).""" + if text is None: + probe = probe or ROOT / "engine" / ("strata-device.exe" if WIN else "strata-device") + try: + hip_engine = json.loads((probe.parent / "BUILD.json").read_text()).get("backend") == "hip" + except (OSError, ValueError): + hip_engine = False + if not probe.exists() or not hip_engine: + return None + try: + hip_runtime_beside_exe(probe.parent) # #468 #461: not the driver's System32 copy + env = dict(os.environ) # the ready-made engine's ROCm DLLs (rocm/bin beside it) + env["PATH"] = os.pathsep.join([str(d) for d in hip_lib_dirs(probe.parent)] + [env.get("PATH", "")]) + r = subprocess.run([str(probe), "--list-devices"], capture_output=True, text=True, timeout=120, + cwd=str(probe.parent), env=env) + except (OSError, subprocess.TimeoutExpired): + return None + if r.returncode != 0: + return None + text = r.stdout + found = [] + for line in text.splitlines(): + m = re.match(r"device\s+(\d+):\s*(.*)$", line.strip()) + if m: + found.append({"index": int(m.group(1)), "name": m.group(2).strip(), "vram_gb": 0.0, "arch": "", + "driver": "hip", "vendor": "amd"}) + continue + if not found: + continue + a = re.match(r"arch\s+(gfx[0-9a-f]+)\s*,\s*([\d.]+)\s*GiB", line.strip()) + if a and not found[-1]["arch"]: + found[-1]["arch"], found[-1]["vram_gb"] = a.group(1), float(a.group(2)) + elif line.strip().startswith("cannot run:"): + found[-1]["cannot_run"] = line.strip()[len("cannot run:"):].strip() + for g in found: + if not g["arch"]: + g["arch"] = "unknown" + if g["arch"] in AMD_NAMES and g["name"] in ("", "AMD Radeon Graphics"): + g["name"] = AMD_NAMES[g["arch"]] + return found + + +def hip_lib_dirs(eng: Path) -> list[Path]: + """Where the ready-made Windows HIP engine's ROCm DLLs are (its BUILD.json "lib_dirs", relative to engine/).""" + try: + rel = json.loads((eng / "BUILD.json").read_text()).get("lib_dirs") or [] + except (OSError, ValueError): + rel = [] + return [eng / d for d in rel if (eng / d).is_dir()] + + +# #468 #461: the HIP runtime the ready-made engine was built with, next to strata.exe. Windows looks for an imported +# DLL in the exe's folder, then System32, and only then on PATH (where rocm/bin is): an AMD driver that installs its own +# amdhip64_7.dll in System32 won, and the bundled rocBLAS/hipBLAS ran on that runtime - an access violation (W7900) or +# hipErrorInvalidDeviceFunction (7900 XTX) on the first prompt. Only the runtime and the compiler it loads by name: +# rocBLAS/hipBLASLt stay in rocm/bin, where they find their kernel libraries and ../.kpack. +HIP_RUNTIME_DLLS = ("amdhip64_*.dll", "amd_comgr*.dll") + + +def hip_runtime_beside_exe(eng: Path) -> None: + """Copy the bundled HIP runtime DLLs from rocm/bin next to the engine's exes when missing or different (a 0.1.34 + install, whose zip had them in rocm/bin only, is fixed on its next start).""" + for d in hip_lib_dirs(eng): + for pat in HIP_RUNTIME_DLLS: + for src in d.glob(pat): + dst = eng / src.name + try: + if dst.exists() and dst.stat().st_size == src.stat().st_size and \ + dst.stat().st_mtime >= src.stat().st_mtime: + continue + shutil.copy2(src, dst) + except OSError as e: # e.g. the engine is running and holds the old copy + warn(f"could not put {src.name} next to the AMD engine ({e}); if the engine stops on its first " + "request, close Strata and run START-HERE.bat again") + + +def hip_match(card: dict, listed: list[dict], hip: list[dict]) -> dict | None: + """The HIP device that is setup's `card` (from `listed`, the display-adapter order): the k-th device of the same + architecture, k = the card's rank among the listed cards of that architecture. None when HIP has no such card.""" + same = [g["index"] for g in listed if g["arch"] == card["arch"]] + k = same.index(card["index"]) if card["index"] in same else 0 + cand = [g for g in hip if g["arch"] == card["arch"]] + return cand[k] if k < len(cand) else None + + +def hip_card(eng: Path, gpu: dict, listed: list[dict]) -> dict: + """Windows: setup's chosen AMD card as the installed HIP engine numbers it (HIP_VISIBLE_DEVICES), checked by the + engine itself before the model download: an integrated Radeon is HIP's device 0 (#325), and a PC without a + working AMD driver stops here with what to install.""" + hip = hip_devices(eng / "strata-device.exe") + hint = (f"install or update the AMD driver (AMD Software: Adrenalin Edition) from {WIN_AMD_DRIVER}, restart the " + f"PC and run this again; {eng / 'strata-device.exe'} --list-devices shows what the HIP runtime sees") + if not hip: + fail("the AMD HIP runtime finds no GPU (the ready-made engine's device check)", hint) + m = hip_match(gpu, listed, hip) if gpu.get("driver") != "hip" else \ + next((x for x in hip if x["index"] == gpu["index"]), None) + if m is None: + fail(f"the HIP runtime does not list your {gpu['name']} ({gpu['arch']})", hint) + if amd_problem(m): + fail(f"HIP device {m['index']} ({m['name']}) cannot be used: {amd_problem(m)}") + if gpu.get("driver") != "hip" and m["index"] != gpu["index"]: + ok(f"HIP numbers this card {m['index']} (an integrated GPU comes first): the engine is pointed at it") + return {**gpu, "index": m["index"], "count": len(hip), "vram_gb": m["vram_gb"] or gpu["vram_gb"], "driver": "hip"} + + +def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None: + """The ready-made Windows HIP engine (WIN_HIP_ASSET) in engine/, kept between runs; None when it cannot be had + (not published for this version, no internet) or has no code for the card.""" + eng = ROOT / "engine" + info = eng / "BUILD.json" + if info.exists() and (eng / EXE).exists(): + try: + meta = json.loads(info.read_text()) + except ValueError: + meta = {} + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if meta.get("backend") == "hip" and meta.get("source") == "prebuilt" and ver >= WIN_HIP_MIN_ENGINE and \ + gpu["arch"] in meta.get("archs", []) and not updating: + ok("ready-made AMD engine already installed") + return eng + if not url_base: + return None + eng.mkdir(exist_ok=True) + z = eng / WIN_HIP_ASSET + bases = prebuilt_bases(url_base) + for i, base in enumerate(bases): + if not base.startswith(("http://", "https://")): + break + try: + req = urllib.request.Request(base + WIN_HIP_ASSET, method="HEAD", headers={"User-Agent": "strata-setup"}) + urllib.request.urlopen(req, timeout=60).close() + break + except OSError as e: + if i + 1 < len(bases): + say(f" No ready-made AMD engine for v{source_version()} ({e}): the latest release instead") + continue + warn(f"no ready-made AMD engine at {base} ({e})") + return None + say(" Downloading the ready-made Strata engine for AMD GPUs (with the ROCm libraries it uses) ...") + download(base + WIN_HIP_ASSET, z, "Strata AMD engine") + tmp = eng / "_unpack" + shutil.rmtree(tmp, ignore_errors=True) + with zipfile.ZipFile(z) as f: + f.extractall(tmp) + try: + meta = json.loads((tmp / "BUILD.json").read_text()) + except (OSError, ValueError): + meta = {} + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + why = None + if meta.get("backend") != "hip" or not (tmp / EXE).exists(): + why = "it is not a HIP engine" + elif ver < WIN_HIP_MIN_ENGINE: + why = f"it is version {meta.get('version')}; this setup needs {'.'.join(map(str, WIN_HIP_MIN_ENGINE))}" + elif gpu["arch"] not in meta.get("archs", []): + why = f"it is built for {', '.join(meta.get('archs', []))}; your GPU is {gpu['arch']}" + if why: + warn(f"the ready-made AMD engine at {base} cannot be used: {why}") + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + return None + for p in tmp.iterdir(): + dst = eng / p.name + if dst.exists(): + shutil.rmtree(dst) if dst.is_dir() else dst.unlink() + p.replace(dst) + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + hip_runtime_beside_exe(eng) # #468 #461 + ok(f"ready-made AMD engine {meta.get('version', '')} for {', '.join(meta.get('archs', []))} " + f"(ROCm {meta.get('rocm', '?')})") + return eng + + +def rocm_version(root): + """(major, minor) of a ROCm install, from rocm-core's header; None when it has none.""" + try: + text = (Path(root) / "include" / "rocm-core" / "rocm_version.h").read_text() + return tuple(int(re.search(rf"#define\s+ROCM_VERSION_{k}\s+(\d+)", text).group(1)) for k in ("MAJOR", "MINOR")) + except (OSError, AttributeError, ValueError): + return None + + +def rocm_dev_missing(sysroot: Path) -> list: + """#446: the HIP development files the engine's build needs that a system ROCm lacks (a runtime-only install has + hipcc and libhipblas but not these, and cmake's enable_language(HIP) then fails on the hip-lang package).""" + lang = "cmake/hip-lang/hip-lang-config.cmake" # where CMake's HIP support looks for it + need = {"lib/" + lang: [sysroot / d / lang for d in ("lib", "lib64", "lib/x86_64-unknown-linux-gnu")], + "include/hip/hip_runtime.h": [sysroot / "include" / "hip" / "hip_runtime.h"]} + return [name for name, paths in need.items() if not any(p.is_file() for p in paths)] + + +def rocm_root(archs): + """ROCm for compiling and running the HIP engine for `archs` (one arch or a list: the cards of a layer split): + (root, library folders). A system ROCm 7 with hipcc, hipBLAS and the HIP development files (#446), else AMD's + TheRock wheels (ROCM_VERSION, from the card family's index) installed into .venv.""" + archs = [archs] if isinstance(archs, str) else list(archs) + sysroot = Path(os.environ.get("ROCM_PATH") or "/opt/rocm") + if (sysroot / "bin" / "hipcc").exists() and list((sysroot / "lib").glob("libhipblas.so*")): + ver = rocm_version(sysroot) + missing = rocm_dev_missing(sysroot) + if (ver is None or ver >= ROCM_SYSTEM_MIN) and not missing: + return sysroot, [str(sysroot / "lib")] + if ver is not None and ver < ROCM_SYSTEM_MIN: + warn(f"the ROCm in {sysroot} is {ver[0]}.{ver[1]}; Strata needs {ROCM_SYSTEM_MIN[0]}.{ROCM_SYSTEM_MIN[1]} " + "or newer: using AMD's wheels in .venv instead") + else: # #446: a runtime-only ROCm (no -dev packages): cmake would fail + warn(f"the ROCm in {sysroot} has no HIP development files ({', '.join(missing)}): using AMD's wheels in " + ".venv instead (or install them, e.g. AMD's amdrocm-core-dev package for your ROCm and card)") + indexes = list(dict.fromkeys(rocm_index(a) for a in archs)) + if len(indexes) > 1: # TheRock's wheels hold one GPU family's libraries + fail(f"cards of two GPU families ({', '.join(archs)}) need a system ROCm 7 (in /opt/rocm): AMD's Python " + "wheels come per family", "install ROCm 7 system-wide, or use cards of one family (--gpu N for one card)") + index = indexes[0] + stamp = Path(sys.prefix) / ".strata-rocm.json" + have = json.loads(stamp.read_text()) if stamp.exists() else {} + if have.get("version") != ROCM_VERSION or have.get("index") != index: + say(f" Installing ROCm {ROCM_VERSION} for AMD GPUs into .venv (AMD's TheRock wheels, ~10 GB, no sudo) ...") + pip = [sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--index-url", index] + if have.get("version") == ROCM_VERSION: # the same version for another GPU family: its own libraries + run(pip + ["--force-reinstall", "--no-deps", f"rocm=={ROCM_VERSION}"]) + run(pip + [f"rocm[libraries,devel]=={ROCM_VERSION}"]) + stamp.write_text(json.dumps({"version": ROCM_VERSION, "index": index})) + sdk = Path(sys.executable).parent / "rocm-sdk" + root = Path(out([str(sdk), "path", "--root"]).strip()) + if not (root / "llvm" / "bin" / "clang++").exists(): + fail(f"ROCm was installed but its compiler is missing ({root})", + f"remove {stamp} and run this again; or install ROCm 7 system-wide") + # the card family's libraries only (gfx120X-all -> _rocm_sdk_libraries_gfx120X_all): another family's + # libhipblaslt.so first on the path would have no kernels for this card + family = "_rocm_sdk_libraries_" + index.rstrip("/").rsplit("/", 1)[-1].replace("-", "_") + dirs = [str(root / "lib")] + for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}: + libs = sorted(sp.glob("_rocm_sdk_libraries_*")) + libs = [d for d in libs if d.name.lower() == family.lower()] or libs + dirs += [str(d / "lib") for d in libs if (d / "lib").is_dir()] + ok(f"ROCm: {root}") + return root, list(dict.fromkeys(dirs)) + + +def hipblaslt_version(lib_dirs): + """The installed hipBLASLt's version as the engine reads it (hipblasLtGetVersion: 1.4.1 -> 100401), from the + header of the ROCm whose libraries the engine loads; None when not found.""" + for d in lib_dirs: + try: + text = (Path(d).parent / "include" / "hipblaslt" / "hipblaslt-version.h").read_text() + v = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", text).group(1)) + for k in ("MAJOR", "MINOR", "PATCH")] + except (OSError, AttributeError, ValueError): + continue + return v[0] * 100000 + v[1] * 100 + v[2] + return None + + +def hipblaslt_table(arch, lib_dirs, ver=None): + """tools/hip/-hipblaslt-.txt for this card AND the installed hipBLASLt, else None: its solution + ids are valid only for that pair (the engine refuses any other table and uses plain hipBLAS). ver: the + hipBLASLt version the ready-made Windows engine ships (its BUILD.json), else read from the installed headers.""" + ver = ver or hipblaslt_version(lib_dirs) + table = ROOT / "tools" / "hip" / f"{arch}-hipblaslt-{ver}.txt" + if ver is not None and table.exists(): + head = table.read_text().split("\n", 2)[:2] + if f"STRATA_HIPBLASLT_TUNING_V1 {arch} {ver}" in (h.strip() for h in head): + ok(f"hipBLASLt tuning table: {table.name} (faster prompts)") + return table + have = sorted(p.name for p in (ROOT / "tools" / "hip").glob(f"{arch}-hipblaslt-*.txt")) + warn(f"no hipBLASLt tuning table for {arch} with hipBLASLt {ver or '(version unknown)'}" + + (f" (have: {', '.join(have)})" if have else "") + + ": the prompt's dense matrix products use plain hipBLAS (tools/hip/tune_hipblaslt makes a table: " + "docs/AMD_HIP.md, Tuning table)") + return None + + +def build_engine_hip(gpu, llama, vision="none") -> Path: + """Compile the HIP engine for this AMD GPU into engine/ (again only when its source changed: a `git pull`). + gpu["archs"]: every architecture it needs code for (the cards of a layer split), else gpu["arch"]. vision "cpu" + (#304): the image encoder too, for the CPU (there is no HIP encoder build yet).""" + eng = ROOT / "engine" + eng.mkdir(exist_ok=True) + stamp = eng / "BUILD.json" + meta = json.loads(stamp.read_text()) if stamp.exists() else {} + src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) + archs = sorted(set(gpu.get("archs") or [gpu["arch"]])) + has_archs = set(archs) <= set(meta.get("archs", [])) + floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine + engine_ok = meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs and \ + (meta.get("isa_floor") or "") == floor + vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc) + if engine_ok and vision_ok: + ok("engine already built for this PC") + return eng + if engine_ok: + return build_vision_cpu(eng, stamp, meta, llama, vsrc) + if not (shutil.which("c++") or shutil.which("g++")) or not shutil.which("git"): + fail("a C++ compiler and git are needed to compile the AMD engine", + "Ubuntu/Debian: sudo apt install build-essential git Fedora: sudo dnf install gcc-c++ git") + root, dirs = rocm_root(archs) + libs = [str(Path(d).parent) for d in dirs[1:]] + bitcode = next((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode", root / "amdgcn" / "bitcode") if p.is_dir()), + root / "amdgcn" / "bitcode") + os.environ.update({"HIP_PLATFORM": "amd", "HIP_COMPILER": "clang", "HIP_RUNTIME": "rocclr", "ROCM_PATH": str(root), + "HIP_PATH": str(root)}) + os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep) + os.environ["PATH"] = os.pathsep.join([str(root / "bin"), str(root / "llvm" / "bin"), os.environ.get("PATH", "")]) + say(" The engine's source changed: compiling it again (only what changed, a few minutes) ..." + if meta.get("backend") == "hip" and (eng / EXE).exists() and has_archs + else f" Compiling the Strata engine for your AMD GPU{'s' if len(archs) > 1 else ''} ({', '.join(archs)}; " + "10-20 minutes, once) ...") + cmake_build(ROOT, ROOT / "build-hip", "strata", + ["-DSTRATA_ENABLE_HIP=ON", "-DSTRATA_ENABLE_CUDA=OFF", "-DSTRATA_BUILD_TESTS=OFF", + "-DSTRATA_PREFILL_MMQ=ON", "-DCMAKE_HIP_ARCHITECTURES=" + ";".join(archs), + f"-DCMAKE_HIP_COMPILER={root / 'llvm' / 'bin' / 'clang++'}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}", + "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]), + f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}", + f"-DSTRATA_GGML_DIR={llama}", *isa_floor_defs(floor, ROOT / "build-hip", meta)], None, "") + shutil.copy2(ROOT / "build-hip" / EXE, eng / EXE) + meta = {"source": "local-hip", "backend": "hip", "version": source_version(), "archs": archs, "vision": "none", + "lib_dirs": dirs, "src": src, **({"isa_floor": floor} if floor else {})} + if vision != "none": + return build_vision_cpu(eng, stamp, meta, llama, vsrc) + stamp.write_text(json.dumps(meta, indent=1)) + ok(f"engine compiled: {eng / EXE}") + return eng + + +def hip_vision(asked) -> str: + """The image encoder with the AMD backend (--vision): the CPU one when asked for (#304); a HIP (GPU) encoder build + is a later step, so `yes`/`gpu` leave images off, as before, and say how to get them.""" + if asked in ("yes", "gpu"): + warn("the AMD backend has no GPU image encoder yet: images off" + + ("" if WIN else " (--vision cpu reads them on the CPU)")) + if asked == "cpu" and WIN: + warn("images on the CPU with an AMD card are Linux-only for now (the ready-made Windows AMD engine has no " + "image encoder): images off") + return "none" + return "cpu" if asked == "cpu" else "none" + + +def build_vision_cpu(eng: Path, stamp: Path, meta: dict, llama, vsrc) -> Path: + """#304: the CPU image encoder beside the HIP engine (tools/vision without CUDA), recorded in its BUILD.json.""" + if not ((eng / VEXE).exists() and meta.get("vision_src") == vsrc): + say(" Compiling the image encoder (for the CPU) ...") + cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision", "strata-vision", + [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=OFF"], None, "") + shutil.copy2(ROOT / "build-vision" / "bin" / VEXE, eng / VEXE) + stamp.write_text(json.dumps({**meta, "vision": "cpu", "vision_src": vsrc}, indent=1)) + ok(f"engine: {eng / EXE}, image encoder (CPU): {eng / VEXE}") + return eng + + +# ------------------------------------------------------------------------------------------------ the engine +def driver_major(gpu): + try: + return int(gpu["driver"].split(".")[0]) + except (ValueError, KeyError): + return 0 + + +def prebuilt_bases(url_base) -> list[str]: + """Where to look for the ready-made engine, in order (each ending in a slash). The default: the release of this + checkout's version first, then the latest (#214); an explicit --prebuilt / STRATA_PREBUILT_URL: only that.""" + base = url_base if url_base.endswith(("/", "\\")) else url_base + "/" + if base != PREBUILT_URL: + return [base] + return [PREBUILT_TAG_URL.format(version=source_version()), base] + + +def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | None: + """The ready-made engine in engine/ (kept between runs), or None when there is none for this PC. + updating: called to replace an installed engine, which starts instead when this fails (no compile). + toolkit 12: the experimental CUDA 12 engine (CUDA12_ASSET) in engine-cuda12/.""" + eng = engine_dir(toolkit) + asset = CUDA12_ASSET if int(toolkit) == 12 else PREBUILT_ASSET + info = eng / "BUILD.json" + if info.exists() and (eng / EXE).exists() and json.loads(info.read_text()).get("backend") != "hip": + meta = json.loads(info.read_text()) + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if meta.get("source") == "local": # compiled here: build_engine checks its source and cards + return None + have = [int(a) for a in meta.get("archs", [])] + miss = [int(x) for x in gpu.get("archs", [gpu["arch"]]) + if have and int(x) not in have and not (meta.get("ptx") and int(x) > max(have))] + if miss: # a card it has no code for (#128): compiled here instead + warn(f"the installed engine is built for {', '.join(str(a) for a in have)}; your GPU is " + f"{', '.join(str(x) for x in miss)}: compiling instead") + return None + if ver >= MIN_ENGINE: + ok("ready-made engine already installed") + return eng + say(f" Updating the ready-made engine ({meta.get('version')} -> {'.'.join(map(str, MIN_ENGINE))} or newer) ...") + info.unlink() + if not url_base: + return None + eng.mkdir(exist_ok=True) + z = eng / asset + bases = prebuilt_bases(url_base) + for i, base in enumerate(bases): + if not base.startswith(("http://", "https://")): + break + try: # not published (yet), or no internet: compile instead + req = urllib.request.Request(base + asset, method="HEAD", headers={"User-Agent": "strata-setup"}) + urllib.request.urlopen(req, timeout=60).close() + break + except OSError as e: + if i + 1 < len(bases): # #214: this checkout's release is not published (yet) + say(f" No ready-made engine for v{source_version()} ({e}): the latest release instead") + continue + warn(f"no ready-made engine at {base} ({e})" + ("" if updating else ": compiling instead")) + return None + say(" Downloading the ready-made Strata engine" + (" (CUDA 12, experimental)" if int(toolkit) == 12 else "") + " ...") + download(base + asset, z, "Strata engine") + tmp = eng / "_unpack" + shutil.rmtree(tmp, ignore_errors=True) + with zipfile.ZipFile(z) as f: + f.extractall(tmp) + meta = json.loads((tmp / "BUILD.json").read_text()) + if tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) < MIN_ENGINE: + need = ".".join(map(str, MIN_ENGINE)) + if updating: # these files are newer than the published release (#58) + warn(f"engine {need} is not published yet (the release may still be uploading): run this again " + f"in a few minutes to update it") + else: + warn(f"the ready-made engine at {base} is version {meta.get('version')}; this setup needs " + f"{need}: compiling instead") + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + return None + archs = [int(a) for a in meta.get("archs", [])] + miss = [int(x) for x in gpu.get("archs", [gpu["arch"]]) + if int(x) not in archs and not (meta.get("ptx") and int(x) > max(archs))] + if miss: + warn(f"the ready-made engine is built for {', '.join(str(a) for a in archs)}; your GPU is " + f"{', '.join(str(x) for x in miss)}" + ("" if updating else ": compiling instead")) + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + return None + for p in tmp.iterdir(): + dst = eng / p.name + if dst.exists(): + shutil.rmtree(dst) if dst.is_dir() else dst.unlink() + p.replace(dst) + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + if not (eng / EXE).exists(): + fail("the ready-made engine archive has no " + EXE) + if not WIN: + for x in (EXE, VEXE): + if (eng / x).exists(): + (eng / x).chmod(0o755) + ok(f"ready-made engine {meta.get('version', '')} for {', '.join('sm_' + str(a) for a in archs)} (CUDA " + f"{meta.get('cuda', '?')})") + return eng + + +def update_installed_engine(url_base, toolkit=None) -> None: + """An installed ready-made engine older than MIN_ENGINE is replaced before the model starts, so a plain + START-HERE.bat on an existing install picks up a new release. If that cannot happen (no internet, the model + still running, no ready-made engine for this GPU) the installed engine is kept and starts as before. + toolkit None: engine/, then the experimental CUDA 12 engine in engine-cuda12/ when one is installed.""" + if toolkit is None: + update_installed_engine(url_base, 13) + if (engine_dir(12) / "BUILD.json").exists(): + update_installed_engine(url_base, 12) + return + eng = engine_dir(toolkit) + info = eng / "BUILD.json" + if not info.exists() or not (eng / EXE).exists(): + return + meta_text = info.read_text() + meta = json.loads(meta_text) + if meta.get("backend") == "hip" and WIN: # AMD on Windows: the ready-made HIP engine, when older + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if meta.get("source") == "prebuilt" and ver < WIN_HIP_MIN_ENGINE: + try: + g = next((x for x in amd_gpus() if amd_problem(x) is None), None) + if g is None: + raise RuntimeError("no supported AMD GPU found") + say(f" Updating the ready-made AMD engine ({meta.get('version')} -> " + f"{'.'.join(map(str, WIN_HIP_MIN_ENGINE))} or newer) ...") + if get_prebuilt_hip(url_base, g, updating=True) is None: + raise RuntimeError("not published yet") + except (Exception, SystemExit) as e: + warn(f"could not update the AMD engine{'' if isinstance(e, SystemExit) else f' ({e})'}: " + "starting the installed one") + return + if meta.get("backend") == "hip": # AMD: compiled here, again when its source changed + if meta.get("src") != source_hash(ENGINE_SOURCES): + try: + usable = [x for x in amd_gpus() if amd_problem(x) is None] + g = next((x for x in usable if x["arch"] in meta.get("archs", [])), usable[0] if usable else None) + if g is None: + raise RuntimeError("no supported AMD GPU found") + # every architecture it was built for (a layer split across two families keeps both) + build_engine_hip({**g, "archs": [x for x in meta.get("archs", []) if x in AMD_ARCHS] or [g["arch"]]}, + get_llama_cpp(), meta.get("vision") or "none") + except (Exception, SystemExit) as e: + warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: " + "starting the installed one") + return + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + local = meta.get("source") == "local" + vision = meta.get("vision") or "none" + if local: # compiled here: is it older than the source (a git pull)? + if meta.get("src") == source_hash(ENGINE_SOURCES) and \ + (vision == "none" or meta.get("vision_src") == source_hash(VISION_SOURCES)): + return + elif ver >= MIN_ENGINE: + return + try: # a running engine cannot be replaced (Windows keeps it locked) + for x in (EXE, VEXE): + if (eng / x).exists(): + with open(eng / x, "r+b"): + pass + except OSError: + warn(f"engine {meta.get('version') or ''} is in use: close the model window and run this again to update it") + return + gpu = gpu_info() + if local: + try: # a failed compile must not stop the model from starting + if gpu is None: + raise RuntimeError("no NVIDIA GPU found") + gpu = {**gpu, "archs": sorted({int(gpu["arch"]), *(int(x) for x in meta.get("archs", []))})} + if int(toolkit) == 12: # the cards it was compiled for (the main GPU may be newer) + gpu["archs"] = sorted({int(x) for x in meta.get("archs", [])}) or gpu["archs"] + build_engine(gpu, vision, False, get_llama_cpp(), toolkit=toolkit) + except (Exception, SystemExit) as e: + warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: starting the installed one") + return + new = None + if gpu is not None: + try: + if int(toolkit) == 12: # the cards the CUDA 12 engine serves, not the newest one + gpu = {**gpu, "archs": [x for x in (int(a) for a in meta.get("archs", [])) if x < CUDA13_MIN_ARCH] + or [int(gpu["arch"])]} + new = get_prebuilt(url_base, gpu, "gpu", updating=True, toolkit=toolkit) + except Exception as e: # a failed download must not stop the model from starting + warn(f"updating the engine failed ({e})") + if new is None: + if not info.exists(): + info.write_text(meta_text) # get_prebuilt drops it before downloading: put it back + warn(f"could not update the engine: starting the installed {meta.get('version')}") + return + pip_cuda_libs(toolkit) + + +def pip_cuda_libs(toolkit=13) -> None: + """NVIDIA's cuBLAS and CUDA runtime for a ready-made engine, from pip: CUDA 13's, or the CUDA 12 engine's.""" + if int(toolkit) == 12: + pip_install(CUDA12_WHEELS, "NVIDIA CUDA 12 libraries for the experimental engine (cuBLAS, CUDA runtime; ~0.7 GB)") + else: + pip_install(CUDA_WHEELS, "NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)") + + +def install_build_tools(gpu, yes): + """The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars).""" + archs = [int(x) for x in gpu.get("archs", [gpu["arch"]])] + # #295: Pascal / Volta need a CUDA 12.x toolkit - CUDA 13 cannot build sm_60/sm_70; gpu["toolkit"] = 12: the + # experimental CUDA 12 engine for any cards (--cuda 12, docs/OLDER_GPUS.md) + old = int(gpu.get("toolkit") or (12 if min(archs) < CUDA13_MIN_ARCH else 13)) == 12 + need12 = (12, 8) if max(archs) >= 120 else (12, 0) # sm_120 needs CUDA 12.8 or newer + if old and max(archs) >= 120: + warn("an RTX 50 card (sm_120) in a CUDA 12 engine: engines built with CUDA 12.8 crashed on long prompts there " + "(#220, #224); the RTX 50 card alone (--gpu N) runs the ready-made CUDA 13 engine") + nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc() + if old and (nvcc is None or cuda_v < need12): + fail("the experimental CUDA 12 engine (Pascal / Volta, or --cuda 12) is compiled here with the NVIDIA CUDA " + f"Toolkit {need12[0]}.{need12[1]} or a newer 12.x (CUDA 13 cannot compile for these cards)" + + (f"; found CUDA {cuda_v[0]}.{cuda_v[1]}" if nvcc else ""), + "install CUDA 12.9 (it can sit next to a newer one) from https://developer.nvidia.com/cuda-toolkit-archive " + "and run it again (STRATA_NVCC= picks one toolkit)") + # RTX 50 (sm_120): CUDA 13.0 - an engine built with 12.8 crashed in the prompt path on Linux (#220) + need_cuda = need12 if old else (13, 0) if max(archs) >= 120 else (12, 0) + vcvars = find_vcvars() if WIN else None + have_cc = vcvars is not None if WIN else shutil.which("g++") is not None + missing = [] + if not have_cc: + missing.append("Visual Studio 2022 Build Tools (C++)" if WIN else "the C++ compiler (build-essential)") + if nvcc is None or cuda_v < need_cuda: + missing.append("the NVIDIA CUDA Toolkit 13.0") + if not missing: + ok(f"build tools present (CUDA {cuda_v[0]}.{cuda_v[1]})") + return nvcc, vcvars + say(" The engine has to be compiled for your PC, which needs: " + " and ".join(missing) + ".") + say(" They can be installed now (about 8-10 GB, 15-40 minutes" + (", Windows will ask for permission" if WIN else + ", sudo will ask for your password") + ").") + if ask(" Install them now?", ["y", "n"], "y", yes) != "y": + fail("the build tools are needed", "install them yourself (see README.md) and run it again") + if WIN: + if shutil.which("winget") is None: + fail("winget (Windows package manager) is not available", + "install 'App Installer' from the Microsoft Store, or install the tools by hand (README.md)") + wg = ["winget", "install", "-e", "--source", "winget", "--accept-package-agreements", + "--accept-source-agreements", "--disable-interactivity"] + if not have_cc: + run([*wg, "--id", "Microsoft.VisualStudio.2022.BuildTools", "--override", + "--quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"], + check=False) + if nvcc is None or cuda_v < need_cuda: + run([*wg, "--id", "Nvidia.CUDA", "--version", "13.0"], check=False) + vcvars = find_vcvars() + else: + apt = shutil.which("apt-get") + if apt is None: + fail("missing: " + " and ".join(missing) + " (the automatic install is only done on Ubuntu/Debian)", + "install them with your distribution's packages (Arch: pacman -S base-devel cuda; nvcc is found on " + "PATH, in /usr/local/cuda* and in /opt/cuda*), then run it again") + if not have_cc: + run(["sudo", "apt-get", "install", "-y", "build-essential"]) + if nvcc is None or cuda_v < need_cuda: + osr = dict(line.split("=", 1) for line in open("/etc/os-release").read().splitlines() if "=" in line) + ver = osr.get("VERSION_ID", "").strip('"').replace(".", "") + if osr.get("ID") != "ubuntu" or ver not in ("2204", "2404"): + fail("the CUDA Toolkit can be installed automatically on Ubuntu 22.04 / 24.04 only", + "install it from https://developer.nvidia.com/cuda-downloads and run it again") + deb = Path("/tmp/cuda-keyring.deb") + download(f"https://developer.download.nvidia.com/compute/cuda/repos/ubuntu{ver}/x86_64/cuda-keyring_1.1-1_all.deb", + deb, "CUDA repository key") + run(["sudo", "dpkg", "-i", str(deb)]) + run(["sudo", "apt-get", "update"]) + run(["sudo", "apt-get", "install", "-y", "cuda-toolkit-13-0"]) + nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc() + if (WIN and find_vcvars() is None) or (not WIN and shutil.which("g++") is None): + fail("the C++ build tools did not install", "install them by hand (README.md) and run it again") + if nvcc is None or cuda_v < need_cuda: + fail("the CUDA Toolkit did not install", "install it from https://developer.nvidia.com/cuda-downloads, then run it again") + ok(f"build tools installed (CUDA {cuda_v[0]}.{cuda_v[1]})") + return nvcc, find_vcvars() if WIN else None + + +def cmake_build(src, bdir, target, defs, vcvars, bat_name): + cmake, ninja = find_tool("cmake"), find_tool("ninja") + if cmake is None or ninja is None: + fail("cmake / ninja not found after installing them", "run: .venv python -m pip install cmake ninja") + conf = [cmake, "-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}", "-S", str(src), "-B", str(bdir), + "-DCMAKE_BUILD_TYPE=Release", *defs] + build = [cmake, "--build", str(bdir), "--target", target, "-j", str(max(2, (os.cpu_count() or 4) // 2))] + # A failed build is tried once more: CUDA 13.0's ptxas now and then fails to parse a PTX file it just wrote, and + # the same command then gets past it (issue #45); a second attempt only compiles what is still missing. + if WIN: + bat = ROOT / bat_name + q = lambda c: " ".join(f'"{x}"' if " " in str(x) else str(x) for x in c) # noqa: E731 + bat.write_text(f'@echo off\r\ncall "{vcvars}" >nul\r\n{q(conf)} || exit /b 1\r\n{q(build)} && exit /b 0\r\n' + f'echo (the build stopped - trying it once more)\r\n{q(build)} || exit /b 1\r\n', + encoding="utf-8") + run(["cmd", "/c", str(bat)]) + else: + run(conf) + if run(build, check=False).returncode != 0: + say(" (the build stopped - trying it once more)") + run(build) + + +ENGINE_SOURCES = ("CMakeLists.txt", "src", "include", "third_party/ggml") +VISION_SOURCES = ("tools/vision",) + + +def source_hash(parts) -> str: + """A fingerprint of the files a compiled engine is built from, kept in engine/BUILD.json: when a `git pull` + changes them, the engine is compiled again (issue #31).""" + h = hashlib.sha256(LLAMA_CPP_COMMIT.encode()) + for part in parts: + base = ROOT / part + for f in [base] if base.is_file() else sorted(x for x in base.rglob("*") if x.is_file()): + h.update(f.relative_to(ROOT).as_posix().encode() + b"\0" + f.read_bytes().replace(b"\r\n", b"\n")) + return h.hexdigest()[:16] + + +def isa_floor_defs(floor: str, bdir: Path, meta: dict) -> list: + """The experimental older-CPU build's CMake definition (STRATA_ISA_FLOOR, CMakeLists.txt), none for the normal + build. A build folder configured for another floor is configured afresh: ggml's CPU options are cached there.""" + if (meta.get("isa_floor") or "") != floor and (bdir / "CMakeCache.txt").exists(): + (bdir / "CMakeCache.txt").unlink() + return [f"-DSTRATA_ISA_FLOOR={floor}"] if floor else [] + + +def engine_defs(archs, toolkit=13) -> list: + """Extra CMake definitions for the engine: the experimental Pascal/Volta build (#295) for cards below sm_75, and + for every CUDA 12 engine (the same build as the ready-made CUDA 12 one: it admits the older cards).""" + return ["-DSTRATA_EXPERIMENTAL_SM60=ON"] if min(int(x) for x in archs) < 75 or int(toolkit) == 12 else [] + + +def prebuilt_vision(meta: dict, gpu: dict, vision: str) -> str: + """The image encoder to use with a ready-made engine (`meta`: its BUILD.json). The encoder can cover fewer cards + than the engine (0.1.30/0.1.31: no RTX 20 code, #331): such a card gets the CPU encoder - the same program - instead + of compiling one, which fails on most Windows PCs (no Visual Studio / CUDA toolkit); --build compiles it.""" + if vision != "gpu": + return vision + va = [int(x) for x in meta.get("vision_archs", meta.get("archs", []))] + if va and int(gpu["arch"]) not in va and not (meta.get("ptx") and int(gpu["arch"]) > max(va)): + warn(f"the ready-made image encoder has no code for your GPU (sm_{gpu['arch']}): it runs on the CPU instead " + "(images take longer; setup --build compiles one for your GPU)") + return "cpu" + return vision + + +def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path: + """Compile the engine (and, for images, the encoder) for this GPU; the results go to engine/. A compiled + engine whose source files changed since (a `git pull`) is compiled again: only the changed files, a few minutes. + toolkit 12 (default: 12 for a card older than CUDA 13 supports): the experimental CUDA 12 engine, in + engine-cuda12/ with its own build folders.""" + if toolkit is None: + toolkit = 12 if min(int(x) for x in gpu.get("archs", [gpu["arch"]])) < CUDA13_MIN_ARCH else 13 + t12 = int(toolkit) == 12 + eng = engine_dir(toolkit) + eng.mkdir(exist_ok=True) + stamp = eng / "BUILD.json" + meta = json.loads(stamp.read_text()) if stamp.exists() else {} + want_vision = vision != "none" + local = meta.get("source") == "local" + src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) + archs = sorted({int(x) for x in gpu.get("archs", [gpu["arch"]])}) # every card the model runs on + built = {int(x) for x in meta.get("archs", [])} + # a card the engine has no code for (a GPU added with --gpus, #128) needs a compile even when the source is the + # same; the compile keeps the generations it was built for + new_arch = local and not set(archs) <= built + floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine + engine_ok = local and (eng / EXE).exists() and meta.get("src") == src and not new_arch and \ + (meta.get("isa_floor") or "") == floor + vision_ok = not want_vision or ((eng / VEXE).exists() and (not local or meta.get("vision_src") == vsrc)) + if engine_ok and vision_ok: + ok("engine already built for this PC") + return eng + if local: + archs = sorted(built | set(archs)) + nvcc, vcvars = install_build_tools({**gpu, "archs": archs, "toolkit": toolkit}, yes) + cuda_archs = ";".join(str(x) for x in archs) + bdir, vdir = (ROOT / "build-cuda12", ROOT / "build-vision-cuda12") if t12 else (ROOT / "build", ROOT / "build-vision") + if not engine_ok: + say(" Compiling the engine for " + ", ".join(f"sm_{x}" for x in archs) + " (a card it had no code for; " + "10-20 minutes, once) ..." if new_arch else + " The engine's source changed: compiling it again (only what changed, a few minutes) ..." + if local and (eng / EXE).exists() else " Compiling the Strata engine for your GPU (10-20 minutes, once) ...") + cmake_build(ROOT, bdir, "strata", + ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", + f"-DCMAKE_CUDA_COMPILER={nvcc}", f"-DSTRATA_GGML_DIR={llama}", *engine_defs(archs, toolkit), + *isa_floor_defs(floor, bdir, meta)], + vcvars, "build-strata-cuda12.bat" if t12 else "build-strata.bat") + shutil.copy2(bdir / EXE, eng / EXE) + if not vision_ok: + say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ...")) + defs = [f"-DLLAMA_DIR={llama}", f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}"] + if vision == "gpu": + defs += [f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", f"-DCMAKE_CUDA_COMPILER={nvcc}"] + cmake_build(ROOT / "tools" / "vision", vdir, "strata-vision", defs, vcvars, + "build-vision-cuda12.bat" if t12 else "build-vision.bat") + shutil.copy2(vdir / "bin" / VEXE, eng / VEXE) + bindir = Path(nvcc).parent # the toolkit's own libraries (bin, bin/x64, lib64) + dirs = [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()] + stamp.write_text(json.dumps({"source": "local", "version": source_version(), "archs": archs, + "vision": vision, **({"toolkit": 12} if t12 else {}), + "cuda_dirs": dirs, "src": src, "vision_src": vsrc if want_vision else None, + **({"isa_floor": floor} if floor else {})}, indent=1)) + ok(f"engine compiled: {eng / EXE}") + return eng + + +# ------------------------------------------------------------------------------------------------ the data folder +# The model files - the GGUFs, the prepared packs and the MTP layer, 70-120 GB - live in a data folder NEXT TO the +# Strata folder (`Strata-data`), not inside it: updating Strata by unzipping a new copy used to give a new, empty +# folder and a full download again. Where it is, and which Strata folders this user ran, is kept in a small +# per-user file, so every Strata folder on the PC finds the same files. +DATA_ITEMS = ("models", "packs", "mtp") + + +LOW_RAM_HEADROOM_GB = 10 # RAM beside the experts: the OS, the engine's other buffers, the server +RESIDENT_ENGINE = (0, 1, 30) # the first engine with --resident-experts (the low-RAM mode's resident variant) + + +def low_ram_needed(model, ram) -> bool: + """The model's experts do not fit this PC's RAM with room left for the rest: they are then mapped from the pack's + experts.bin instead of copied into RAM (the low-RAM mode).""" + return ram < MODELS[model]["arena_gb"] + LOW_RAM_HEADROOM_GB + + +def low_ram_gpu_gb(model, vram_gb, ctx=32768, kv="int8") -> float: + """About how many GB of the model's experts the GPU's cache holds: its VRAM minus ~5 GB for the dense weights, + buffers and a 32K context's KV cache, minus the KV cache of a longer context (in VRAM in the low-RAM mode: its RAM + has no room for KV streaming).""" + kv_tok = 13 * (576 if kv == "q4_0" else 1056) # bytes per context token: 12 QSA layers + the draft layer + longer = max(0, ctx - 32768) * kv_tok / 1e9 + return max(0.0, min(MODELS[model]["arena_gb"], vram_gb - 5 - longer)) + + +def low_ram_gpu_share(model, vram_gb, ctx=32768, kv="int8") -> float: + """About how much of the model's experts the GPU holds.""" + return low_ram_gpu_gb(model, vram_gb, ctx, kv) / MODELS[model]["arena_gb"] + + +def low_ram_resident(model, ram, vram_gb, ctx=32768, kv="int8") -> bool: + """In the low-RAM mode: the experts the GPU does not hold fit the RAM with the usual room beside them, so they are + copied into RAM once (the resident variant, `--resident-experts`) instead of being read through the OS file cache + (plain `--mmap-experts`, which a PC this short of RAM keeps re-reading from the SSD).""" + rest = MODELS[model]["arena_gb"] - low_ram_gpu_gb(model, vram_gb, ctx, kv) + return ram >= rest + LOW_RAM_HEADROOM_GB + + +def low_ram_fits(model, ram, vram_gb) -> bool: + """In the low-RAM mode: the experts the GPU does not hold fit the RAM left beside the rest (as file cache).""" + arena = MODELS[model]["arena_gb"] + return ram - 6 + max(0.0, vram_gb - 5) >= arena + + +def low_ram_one_gpu_why(model, ram, choice, sel=None) -> list[str]: + """#250: why the low-RAM mode recommends one GPU, with the RAM math that turned it on; #364 #384: and how to use + all of them (sel: the cards, for the --gpus example).""" + arena, need = MODELS[model]["arena_gb"], MODELS[model]["arena_gb"] + LOW_RAM_HEADROOM_GB + if choice == "auto": + why = [f"Why: {model}'s experts are {arena:.0f} GB and must fit in RAM with ~{LOW_RAM_HEADROOM_GB} GB beside " + f"them for the OS and the rest: {arena:.0f} + {LOW_RAM_HEADROOM_GB} = {need:.0f} GB, and this PC has " + f"{ram:.0f} GB.", + "So setup uses the low-RAM mode: the experts come from the model's file (copied into RAM as far as " + "it fits), the GPU holds the most-used ones."] + else: + why = [f"Why: you chose the low-RAM mode (--low-ram {choice}); without it {model} needs {arena:.0f} + " + f"{LOW_RAM_HEADROOM_GB} = {need:.0f} GB of RAM, this PC has {ram:.0f} GB."] + return why + ["Its resident variant (the experts the GPU does not hold copied into RAM once: steady RAM use) runs " + "on one GPU: the engine has no layer split for it yet.", + f"To use all the GPUs: --gpus {','.join(str(i) for i in sel) if sel else '0,1'} - the experts the " + "GPUs do not hold are then read through the OS file cache: faster in two reports (1.3-1.6x, #364 " + f"#384), but RAM can fill up to 0 free during long prompts. Or {need:.0f} GB of RAM or more, or a " + "smaller size."] + + +def low_ram_together(a, model, ram, gpu, chosen) -> bool: + """#364 #384: the low-RAM mode with several GPUs chosen. One GPU is recommended: the resident variant keeps the + experts the GPU does not hold in RAM (steady RAM use) and has no layer split. All the GPUs together read those + experts through the OS file cache instead (--mmap-experts) - 1.3-1.6x faster in those reports, but RAM can fill + up to 0 free during long prompts. An explicit --gpus (or an earlier install's cards) is kept; otherwise asked, + one GPU by default (--yes: one GPU, as before). True: all of them.""" + sel = [g["index"] for g in chosen] + names = " + ".join(gpu_name(g) for g in chosen) + if a.gpus: + warn(f"the low-RAM mode on {names}, as you chose (--gpus): the experts the GPUs do not hold are read through " + "the OS file cache (the resident variant has no layer split yet), and RAM can fill up to 0 free during " + "long prompts") + say(f" One GPU keeps them in RAM (steady RAM use, recommended): --gpu {gpu['index']}") + if a.low_ram == "resident": + warn("--low-ram resident has no layer split yet: the experts are read through the OS file cache instead") + return True + if a.low_ram != "resident" and not a.yes: + say() + for line in low_ram_one_gpu_why(model, ram, a.low_ram, sel): + say(" " + line) + say(f" 1) {gpu_name(gpu)} only: the experts it does not hold kept in RAM where they fit (recommended: " + "steady RAM use)") + say(f" 2) {names} together: the experts the GPUs do not hold read through the OS file cache - faster") + say(" in two reports (1.3-1.6x, #364 #384), but RAM can fill up to 0 free during long prompts") + if ask("Low-RAM mode: which GPUs?", ["1", "2"], "1", a.yes) == "2": + ok(f"the low-RAM mode on {names}: the experts read through the OS file cache, as you chose") + return True + warn("the low-RAM mode: using " + gpu_name(gpu) + " only") + return False + warn("the low-RAM mode: using " + gpu_name(gpu) + " only (recommended)") + for line in low_ram_one_gpu_why(model, ram, a.low_ram, sel): + say(" " + line) + return False + + +def unsloth_together(a, model, ram, gpu, chosen) -> bool: + """#498: UD-Q4_K_XL with several GPUs chosen. Its RAM budget (--resident-budget-gib) has no layer split, so a + split runs without it: all its experts loaded into RAM from the GGUFs at start, as with the 2-3-bit models - only + where the RAM holds the GGUF files and 24 GB more (unsloth_split_need_gb; 165 GiB, 2x RTX 3090: 31 -> 64-78 + tok/s). An explicit --gpus is honoured there; otherwise asked, one GPU by default (--yes: one GPU, as before); an + explicit --resident-budget-gib keeps one GPU. True: all of them.""" + names = " + ".join(gpu_name(g) for g in chosen) + need = unsloth_split_need_gb(model) + if ram < need: + warn(f"{model} runs on one GPU here: on several it has no RAM budget and needs ~{need:.0f} GB of RAM (its GGUF " + f"files and {UNSLOTH_RAM_LEFT_GB} GB more), this PC has {ram:.0f} - using {gpu_name(gpu)} only") + return False + if a.resident_budget_gib is not None: + warn(f"--resident-budget-gib has no layer split: {model} runs on one GPU with it - using {gpu_name(gpu)} only " + f"(leave the budget out to use {names} together)") + return False + note = (f"no RAM budget - all of its experts (~{MODELS[model]['arena_gb']:.0f} GB) are loaded into RAM from the " + f"model files at start, and the files pass through the OS file cache (needs ~{need:.0f} GB of RAM, this " + f"PC has {ram:.0f})") + if a.gpus: + ok(f"{model} on {names}, as you chose (--gpus): {note}") + return True + if not a.yes: + say() + say(f" {model} can run on one GPU with a RAM budget of its experts, or on {names} together without one:") + say(f" 1) {gpu_name(gpu)} only: the most-used experts kept in RAM, the rest read from the SSD (recommended: " + "the tested setup)") + say(f" 2) {names} together: {note};") + say(" about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s)") + if ask(f"{model}: which GPUs?", ["1", "2"], "1", a.yes) == "2": + ok(f"{model} on {names}: {note}") + return True + warn(f"{model} runs on one GPU: using {gpu_name(gpu)} only (--gpus " + ",".join(str(g["index"]) for g in chosen) + + f" shares it across {names} without the RAM budget: this PC's RAM holds it)") + return False + + +def confirm_risk(msg, explicit, yes, stop, hint=None, question=" Go on anyway?", default="n") -> None: + """The owner's rule: setup recommends, it never forces. A choice setup expects to fail or run badly is said + plainly (msg), then asked (default n; `default` keeps an older question's own default), or with --yes taken as + consent when it was asked for explicitly (a flag such as --model or --gpus): --yes alone keeps the stop + (stop, hint). Returns when it goes on; the caller says what it does.""" + warn(msg) + if yes and explicit: + return + if ask(question, ["y", "n"], default, yes) != "y": + fail(stop, hint) + + +def confirm_paging(model, ram, choice, yes, explicit_model=False): + """The model's experts do not fit this PC's RAM and the low-RAM mode is off. #125: a warning and a question, not + a stop - the user may accept paging. Asked "no" by default, so an unattended --yes install stops here, unless + the low-RAM mode was turned off explicitly (--low-ram off, #250) or the size was (--model): that is the choice + already made.""" + need_gb, arena = MODELS[model]["ram_gb"], MODELS[model]["arena_gb"] + off = choice == "off" + confirm_risk(f"{model} needs about {need_gb} GB of RAM and this PC has {ram:.0f} GB: its experts alone are " + f"{arena:.0f} GB and must stay in RAM, so Windows/Linux will page part of them from disk. Expect it " + "to be much slower, and it may not start at all.\n A smaller size (Q2_0 or IQ2_XS) fits; more " + "RAM fixes it.", off or explicit_model, yes, + f"{model} needs about {need_gb} GB of RAM; this PC has {ram:.0f} GB", + "choose Q2_0 or IQ2_XS, or add RAM" + ("" if off else f"; or --model {model} --yes (or --low-ram off " + "--yes) to install it anyway"), + " Install it anyway?", "y" if off else "n") + warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose" + (" (--low-ram off)" if off else + " (--model)" if explicit_model else "")) + + +def ctx_ram_need(model, ctx, low_ram=False): + """#406: the RAM (GB) setup estimates for a long context with IQ3_XXS / IQ3_S: their experts + the context's + 8-bit KV cache + 24 GB of room for everything else (the 0.1.29 arithmetic, counted). None where the context does + not count against RAM by this rule: the other sizes, and the low-RAM mode (its KV cache stays in VRAM).""" + if model not in ("IQ3_XXS", "IQ3_S") or low_ram: + return None + return MODELS[model]["arena_gb"] + ctx * 13 * 1056 / 1e9 + 24 + + +def ram_ctx(model, ram, low_ram=False) -> int: + """#406: the longest context the RAM rule recommends: 128K, or longer where the estimate fits this PC's RAM. It + is part of the recommended default (the smaller of it and the GPU's rule); a longer choice is kept, with a note.""" + return max(c for c in CONTEXTS if c <= 131072 or (ctx_ram_need(model, c, low_ram) or 0) <= ram) + + +def settings_path() -> Path: + if WIN: + return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "Strata" / "settings.json" + return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "settings.json" + + +def load_settings() -> dict: + try: + return json.loads(settings_path().read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + + +def save_settings(s: dict) -> None: + try: + settings_path().parent.mkdir(parents=True, exist_ok=True) + settings_path().write_text(json.dumps(s, indent=1), encoding="utf-8") + except OSError as e: + warn(f"could not save {settings_path()} ({e})") + + +def has_data(folder: Path) -> bool: + for d in DATA_ITEMS: + try: + if (folder / d).is_dir() and any((folder / d).iterdir()): + return True + except OSError: + pass + return False + + +def other_installs(settings: dict) -> list: + """Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* folders + next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`).""" + cands = [Path(p) for p in settings.get("installs", [])] + for base in dict.fromkeys((ROOT.parent, ROOT.parent.parent)): + try: + for d in base.iterdir(): + if d.is_dir() and d.name.lower().startswith("strata"): + cands.append(d) + cands += [c for c in d.iterdir() if c.is_dir() and c.name.lower().startswith("strata")] + except OSError: + pass + found = [] + for d in cands: + try: + d = d.resolve() + if d != ROOT and d not in found and (d / "setup.py").is_file(): + found.append(d) + except OSError: + pass + return found + + +def same_drive(a: Path, b: Path) -> bool: + try: + return os.stat(a).st_dev == os.stat(b).st_dev + except OSError: + return False + + +def move_into(src: Path, dst: Path) -> None: + """A rename into the data folder (same drive: instant); a folder merges into one already there, keeping what the + destination has. Whatever cannot be moved (a file in use) stays where it is.""" + if not dst.exists(): + try: + dst.parent.mkdir(parents=True, exist_ok=True) + os.replace(src, dst) + return + except OSError: + if not src.is_dir(): + return + dst.mkdir(parents=True, exist_ok=True) + if src.is_dir() and dst.is_dir(): + for c in list(src.iterdir()): + move_into(c, dst / c.name) + try: + src.rmdir() + except OSError: + pass + + +def repoint_config(cfg_file: Path, old: Path, new: Path) -> None: + """A config whose model files moved from `old` to `new` points at them there (each path only if its file is + now there and no longer at the old place).""" + try: + cfg = json.loads(cfg_file.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + return + + def fix(v): + if isinstance(v, list): + return [fix(x) for x in v] + if isinstance(v, dict): + return {k: fix(x) for k, x in v.items()} + if isinstance(v, str): + for d in DATA_ITEMS: + o = str(old / d) + nv, no = os.path.normcase(v), os.path.normcase(o) # Windows: C:\ and c:\ are the same place + if nv == no or nv.startswith(no + os.sep): + n = str(new / d) + v[len(o):] + if Path(n).exists() and not Path(v).exists(): + return n + return v + + new_cfg = fix(cfg) + if new_cfg != cfg: + write_config(cfg_file, new_cfg) + + +def data_folder(requested: str | None) -> tuple: + """(the data folder, folders on other drives that still hold model files). Moves the model files of this folder + and of earlier Strata folders on the same drive into the data folder, and points their configs there.""" + settings = load_settings() + dest = Path(requested).expanduser().resolve() if requested else \ + Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "Strata-data" + try: + dest.mkdir(parents=True, exist_ok=True) + except OSError as e: # e.g. no write access next to the Strata folder + warn(f"cannot use {dest} for the model files ({e}): keeping them in {ROOT}") + dest = ROOT + elsewhere = [] + # #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a Strata-data + # folder nested in any of them (an install that kept its models one level down) + sources = [ROOT, *other_installs(settings)] + if settings.get("data_dir") and Path(settings["data_dir"]) != dest: + sources.append(Path(settings["data_dir"])) + sources += [f / "Strata-data" for f in list(sources) if (f / "Strata-data") != dest] + seen = set() + for folder in sources: + key = os.path.normcase(str(folder)) + if key in seen: + continue + seen.add(key) + if folder == dest or not has_data(folder): + continue + if not same_drive(folder, dest): + elsewhere.append(folder) # another drive: used where it is (no 70 GB copy) + continue + # the downloads merge file by file (the same file wherever it came from); a prepared pack or MTP layer moves + # whole or not at all, so two copies are never mixed + if (folder / "models").is_dir(): + move_into(folder / "models", dest / "models") + for item in [*((folder / "packs").glob("*") if (folder / "packs").is_dir() else []), folder / "mtp"]: + rel = item.relative_to(folder) + if item.exists() and not (dest / rel).exists(): + move_into(item, dest / rel) + for d in ("packs",): + try: + (folder / d).rmdir() # empty now + except OSError: + pass + for c in folder.glob("strata-*.json"): + repoint_config(c, folder, dest) + if has_data(folder): + elsewhere.append(folder) # in use, or a copy the data folder already has + warn(f"some model files are still in {folder} (in use, or already in {dest})") + else: + ok(f"model files from {folder} moved to {dest} (a new copy of Strata finds them there)") + installs = [str(ROOT)] + [p for p in settings.get("installs", []) if p != str(ROOT) and Path(p).is_dir()] + save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]}) + return dest, elsewhere + + +def write_config(path: Path, cfg: dict): + """A run config, written whole or not at all (#459): to a temporary file first, then moved over the old one, so + a setup stopped half-way (a closed window, a full disk) never leaves an empty strata-*.json behind.""" + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + os.replace(tmp, path) + + +# #629: the run config's keys setup writes itself (and rewrites on every setup run); any other key is the user's - a +# "sampling" or "mcp_servers" block, "allowed_hosts", "cors_origins", "open_browser" - and is kept when setup runs again +SETUP_KEYS = frozenset({"exe", "args", "cwd", "tokenizer", "model_name", "log", "lib_dirs", "port", "backend", "env", + "gpu", "gpus_asked", "layer_split", "host", "api_key", "draft_vocab", "vision"}) +SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_RESIDENT_PIN"}) # the "env" entries setup writes +SETUP_VISION = frozenset({"exe", "mmproj", "model", "gpu", "max_tokens", "threads"}) + + +def carry_over(old: dict, cfg: dict) -> list[str]: + """#629: setup run again for an installed model keeps what the user added to its run config: every key setup does + not write (`SETUP_KEYS`), the "env" entries setup does not write, and in "vision" the keys setup does not write + plus an mmproj of their own (a Q8_0 one, #625) that still exists. `cfg` (the new config) is updated in place; + the names of what was kept are returned. Engine options added by hand to "args" are not merged (setup chooses + those): `args_dropped` names them.""" + kept = [] + for k, v in old.items(): + if k not in SETUP_KEYS and k not in cfg: + cfg[k] = v + kept.append(k) + env = {k: v for k, v in (old.get("env") or {}).items() if k not in SETUP_ENV and k not in (cfg.get("env") or {})} \ + if isinstance(old.get("env"), dict) else {} + if env: + cfg["env"] = {**(cfg.get("env") or {}), **env} + kept += [f"env {k}" for k in env] + ov, nv = old.get("vision"), cfg.get("vision") + if isinstance(ov, dict) and isinstance(nv, dict): + for k, v in ov.items(): + if k not in SETUP_VISION and k not in nv: + nv[k] = v + kept.append(f"vision {k}") + mm = ov.get("mmproj") # a file of the user's own: not the one setup downloads + if isinstance(mm, str) and Path(mm).name != Path(str(nv.get("mmproj"))).name and Path(mm).is_file(): + nv["mmproj"] = mm + kept.append("vision mmproj") + return kept + + +def args_dropped(old: dict, cfg: dict) -> list[str]: + """#629: the engine options of the earlier run config that the new one has no more (by flag name): options added + by hand, which a setup run does not carry over - the start of the line that names them.""" + def flags(c): + a = c.get("args") if isinstance(c.get("args"), list) else [] + return [str(x) for x in a if str(x).startswith("--")] + new = set(flags(cfg)) + return list(dict.fromkeys(f for f in flags(old) if f not in new)) + + +def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) -> None: + """#629: setup's run config, written over an earlier one for the same model without losing what the user added + to it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as + strata-.json.bak when it changes. `source`: an earlier install's config to carry the keys over from when + this folder has none yet (a copy set up like the last one). A line says what was kept, one what was not.""" + old_path = cfg_path if cfg_path.is_file() else source + old = None + if old_path is not None and old_path.is_file(): + try: + old = json.loads(old_path.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + pass + if not isinstance(old, dict): + old = None + kept = carry_over(old, cfg) if old is not None else [] + bak = None + if cfg_path.is_file() and old != cfg: + bak = cfg_path.with_name(cfg_path.name + ".bak") + try: + shutil.copyfile(cfg_path, bak) + except OSError as e: + warn(f"could not keep a copy of the earlier {cfg_path.name} ({e.strerror or e})") + bak = None + write_config(cfg_path, cfg) + if kept: + ok(f"kept from your earlier {old_path.name}: " + ", ".join(kept)) + if bak is not None: + dropped = args_dropped(old, cfg) if old is not None else [] + say(f" the earlier run config is kept as {bak.name}" + ( + f"; engine options it had that this one has not (setup chooses those): {' '.join(dropped)}" + if dropped else "")) + + +def readable_config(path: Path) -> bool: + """#459: a config that parses as a JSON object; any other gets a one-line warning naming it.""" + text = None + try: + text = path.read_text(encoding="utf-8-sig") + if isinstance(json.loads(text), dict): + return True + why = "not a JSON object" + except OSError as e: + why = e.strerror or str(e) + except ValueError: # JSONDecodeError, or bytes that are not UTF-8 + why = "the file is empty" if text is not None and not text.strip() else "not valid JSON" + warn(f"skipped the earlier config {path} ({why}): setting this copy up without it") + return False + + +def previous_config(elsewhere_first: list, settings: dict): + """The most recently used model config of another Strata folder on this PC, for a folder that has none yet. One + that does not parse (an empty or cut-off file, #459) is skipped with a warning: the newest readable one is used, + and with none this copy is set up as a fresh install.""" + cands = [] + for folder in [*elsewhere_first, *other_installs(settings)]: + cands += list(folder.glob("strata-*.json")) + cands = [c for c in dict.fromkeys(cands) if c.is_file()] + return next((c for c in sorted(cands, key=lambda p: p.stat().st_mtime, reverse=True) if readable_config(c)), None) + + +def choices_from_config(cfg_path: Path) -> dict: + """The setup answers a config was written with (family, size, context, KV, images, projection, network).""" + cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) + tag = cfg_path.stem[len("strata-"):] + family = next((f for f, d in FAMILIES.items() if d["tag"] and tag.startswith(d["tag"])), "qwen") + model = (tag[len(FAMILIES[family]["tag"]):] if tag.startswith(FAMILIES[family]["tag"]) else tag).upper() + if model not in MODELS: # (sizes have no dash except UD-Q4_K_XL: the old rule) + model = tag.split("-")[-1].upper() + a = cfg.get("args", []) + val = lambda k: a[a.index(k) + 1] if k in a and a.index(k) + 1 < len(a) else None # noqa: E731 + vis = cfg.get("vision") + esp = val("--control-vector-scaled") + esp_path = esp.rsplit(":", 1)[0] if esp else None + return {"family": family, "model": model if model in MODELS else None, + "context": int(val("--max-context")) if val("--max-context") else None, + "kv": val("--kv") if val("--kv") in ("int8", "q4_0") else None, + "vision": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "none", + "esp": ("on" if Path(esp_path).name == ESP_VECTOR.name else esp_path) if esp_path else "off", + "host": cfg.get("host"), "api_key": cfg.get("api_key"), "port": cfg.get("port"), "gpu": cfg.get("gpu"), + "layer_split": cfg.get("layer_split"), "cuda": 12 if config_toolkit(cfg) == 12 else None, + # #493: --vram-reserve-mib given at setup (images write the default 700 themselves) + "vram_reserve_mib": int(val("--vram-reserve-mib")) if (val("--vram-reserve-mib") or "").isdigit() and ( + vis is None or int(val("--vram-reserve-mib")) != VISION["gpu"]["reserve_mib"]) else None} + + +def find_in(roots: list, rel: str): + """The first of roots/rel that exists.""" + for r in roots: + if (r / rel).exists(): + return r / rel + return None + + +# ------------------------------------------------------------------------------------------------ start +def model_config(path: Path) -> bool: + """#549: a model's run config (a JSON object with "exe" and "args"). Any other strata-*.json in the folder (a + file of the user's own, a cut-off one) is skipped with a warning naming it instead of stopping setup.""" + try: + cfg = json.loads(path.read_text(encoding="utf-8-sig")) + if isinstance(cfg, dict) and cfg.get("exe") and isinstance(cfg.get("args"), list): + return True + why = 'no "exe" or "args"' + except OSError as e: + why = e.strerror or str(e) + except ValueError: + why = "not valid JSON" + warn(f"skipped {path.name} ({why}): it is not a Strata model config") + return False + + +def installed_configs(): + return [p for p in sorted(ROOT.glob("strata-*.json"), key=lambda p: p.stat().st_mtime, reverse=True) + if model_config(p)] + + +def source_version() -> str: + """The engine version the source tree builds (CMakeLists.txt's project version).""" + m = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8")) + return m.group(1) if m else "0" + + +def engine_version(exe: Path) -> tuple: + """The version in the engine folder's BUILD.json, or else the one compiled into the binary. A locally compiled + engine is not necessarily the source's version: when compiling a `git pull` fails, the previous engine is kept + (issue #49).""" + try: + meta = json.loads((Path(exe).parent / "BUILD.json").read_text()) + except (OSError, ValueError): + meta = {} + v = str(meta.get("version") or "") + if not v: # the version compiled into the binary: 0.1.13 and newer + try: # carry it, so a binary without it is older + m = re.search(rb"engine=(\d+\.\d+\.\d+)\n", Path(exe).read_bytes()) + v = m.group(1).decode() if m else "0.1.12" + except OSError: + v = "0" + return tuple(int(x) for x in v.split(".")[:3] if x.isdigit()) + + +def is_wsl() -> bool: + return sys.platform.startswith("linux") and "microsoft" in platform.uname().release.lower() + + +def rotational_disk(path) -> str | None: + """#605 (Linux): the disk's name when `path` is on a rotational disk (sysfs queue/rotational), else None.""" + if WIN: + return None + try: + st = os.stat(path) + p = Path(f"/sys/dev/block/{os.major(st.st_dev)}:{os.minor(st.st_dev)}").resolve() + for q in (p, p.parent): # a partition has its disk's queue + f = q / "queue" / "rotational" + if f.exists(): + return q.name if f.read_text().strip() == "1" else None + except (OSError, ValueError, AttributeError): + pass + return None + + +def hip_config_cards(sel) -> list[dict]: + """#566: the AMD cards a HIP config runs on - its "gpu" (one index or a list) in HIP's numbering, as amd_gpus + lists them; no "gpu": the supported card with the most VRAM, as setup picks it. Each card's name carries its + architecture (an RX 7900 XTX and an RX 7900 XT are both gfx1100; a card without a product name in sysfs is known + by its arch only). A card that is not found is {} (the key then says "?").""" + amd = amd_gpus() + if sel is None: + usable = [g for g in amd if amd_problem(g) is None] + sel = max(usable, key=lambda x: (round(x["vram_gb"]), -x["index"]))["index"] if usable else None + byid = {g["index"]: g for g in amd} + cards = [] + for i in (sel if isinstance(sel, list) else [sel]): + g = byid.get(i) + if g is None: + cards.append({}) + continue + arch = g.get("arch") or "" + name = g.get("name") or "?" + cards.append({**g, "name": name if not arch or arch in name else f"{name} ({arch})"}) + return cards + + +def hardware_key(cfg: dict) -> str: + """What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting + (the context's KV cache and the image encoder take VRAM from the expert cache). #566: a HIP config's cards are + AMD's (hip_config_cards) - nvidia-smi's list named them "?" (or another card with that number) before.""" + sel = cfg.get("gpu") + if cfg.get("backend") == "hip": + gl = hip_config_cards(sel) + else: + gl = [gpu_info(i) or {} for i in sel] if isinstance(sel, list) else [gpu_info(sel) or {}] + g = {"name": " + ".join(x.get("name", "?") for x in gl), "vram_gb": sum(x.get("vram_gb", 0) for x in gl)} + a = cfg.get("args", []) + ctx = a[a.index("--max-context") + 1] if "--max-context" in a else "?" + return "|".join([g.get("name", "?"), f"{g.get('vram_gb', 0):.0f}GB", cpu_info()[0], f"{ram_gb():.0f}GB", + cfg.get("model_name", "?"), ctx, "images" if "--vision" in a else "text"]) + + +def calibrate_config(cfg_path: Path) -> bool: + """Measure the engine's hardware-dependent settings on this PC (tools/calibrate.py), write them into the run + config and remember them per PC and model in the settings file, so an update or a reinstall keeps them.""" + sys.path.insert(0, str(ROOT / "tools")) + import calibrate as CAL + cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) + say() + say(" Tuning Strata for this PC: the output speed is measured with a few engine settings (the PCIe share, the") + say(" draft depth, the CPU threads). It takes about 5-10 minutes; the PC is busy meanwhile.") + try: + since = os.path.getsize(cfg["log"]) if cfg.get("log") and os.path.isfile(cfg["log"]) else 0 + except OSError: + since = 0 + try: + res = CAL.run(cfg, say=say) + except Exception as e: # never stops an install: the defaults stay + warn(f"the tuning did not finish ({e}): the default settings stay") + why = CAL.engine_error(cfg.get("log"), since) # #447: the engine's own reason, not only "see the log" + if why: + say(f" the engine said: {why}") + return False + cfg["args"] = CAL.apply(cfg["args"], res["settings"]) + write_config(cfg_path, cfg) + st = load_settings() + st.setdefault("calibration", {})[hardware_key(cfg)] = {"settings": res["settings"], "tok_s": res["report"].get("tok_s"), + "date": time.strftime("%Y-%m-%d")} + save_settings(st) + if res["settings"]: + ok("tuned for this PC: " + ", ".join(f"{k} {v}" for k, v in res["settings"].items()) + + (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else "")) + else: + ok("tuned for this PC: the default settings are already the fastest here" + + (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else "")) + return True + + +def saved_calibration(cfg: dict) -> dict | None: + """The settings an earlier calibration found for this PC and model, if any.""" + return (load_settings().get("calibration") or {}).get(hardware_key(cfg)) + + +def setup_calibration(cfg: dict, hip: bool) -> dict | None: + """The calibration a (re-)install applies to its new config: the one saved for this PC and model. #566: on Linux + HIP too - hardware_key now names the AMD cards, so a `./setup.sh --calibrate` run is matched to its card and + model. Windows HIP keeps the defaults for now (not tried there). Setup still offers the tuning itself on NVIDIA + only: each control is verified on HIP first.""" + if hip and WIN: + return None + return saved_calibration(cfg) + + +def upgrade_config(cfg_path: Path, cfg: dict) -> dict: + """Configs written before v0.1.13 read prompts in fixed 2048-token chunks; the engine now picks the chunk + itself (`--prefill auto`: up to 8192, as the free VRAM allows - about 2x faster on long prompts). Under WSL, + KV streaming is dropped: its RAM copy must be pinned, and the driver pins only about 1 GB there.""" + a = cfg.get("args", []) + changed = False + ver = engine_version(cfg["exe"]) if "--prefill" in a else (0, 0, 0) + if "--prefill" in a and a[a.index("--prefill") + 1] == "2048" and ver >= (0, 1, 13): + a[a.index("--prefill") + 1] = "auto" + changed = True + ok("prompt reading: the engine now picks its chunk size (--prefill auto)") + elif "--prefill" in a and a[a.index("--prefill") + 1] == "auto" and (0, 0, 0) < ver < (0, 1, 13): + a[a.index("--prefill") + 1] = "2048" # an older engine kept after a failed update (issue #49) + changed = True + warn(f"the installed engine is {'.'.join(map(str, ver))}: prompts are read in 2048-token chunks until it is updated") + if is_wsl() and "--kv-resident" in a: + i = a.index("--kv-resident") + del a[i:i + 2] + changed = True + ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM") + if changed: + write_config(cfg_path, cfg) + return cfg + + +def update_install(have: list, a) -> int: + """#475: `setup.py --update` (UPDATE.bat / update.sh, after their git pull): what a plain START-HERE.bat does to + an install before it starts the model, without starting it - the Python packages, the ready-made engine when this + setup needs a newer one (MIN_ENGINE; a compiled engine when its source changed), each installed model's config + upgrades and its draft subset. No question is asked and the model files are not touched; a model still running + keeps its engine (update_installed_engine says to close it and run this again).""" + have = [p for p in have if model_config(p)] # #549: a strata-*.json that is no model config is skipped + if not have: + say(" No model is installed in this Strata folder yet: run START-HERE.bat (Linux: ./setup.sh) to set it up -") + say(" it finds an earlier install's model files next to it and reuses them.") + return 0 + pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, + "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") + if not a.build: + update_installed_engine(a.prebuilt) + for cfg_path in have: + cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) + if "--mtp" in cfg["args"][:-1]: + refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) + if cfg.get("backend") == "hip" and WIN: + hip_runtime_beside_exe(Path(cfg["exe"]).parent) # #468 #461 + ok(f"{cfg.get('model_name', cfg_path.stem)}: up to date") + ver = engine_version(Path(json.loads(have[0].read_text(encoding="utf-8-sig"))["exe"])) + say() + ok("Strata is updated" + (f" (engine {'.'.join(map(str, ver))})" if any(ver) else "") + + ". Start the model with " + ("START-HERE.bat" if WIN else "./setup.sh") + " when you want it.") + return 0 + + +def settings_summary(cfg: dict, port=None) -> str: + """#564: the settings a start uses, in one line: the config's engine options (the model's file paths left out) + and the server's own fields, so a change made by hand to strata-.json can be checked without the log.""" + a, out, i = [str(x) for x in cfg.get("args") or []], [], 0 + while i < len(a): + flag = a[i] + val = a[i + 1] if i + 1 < len(a) and not a[i + 1].startswith("--") else None + i += 1 if val is None else 2 + if not flag.startswith("--"): + continue # a positional: the model file + if val is not None and ("/" in val or "\\" in val or val.lower().endswith((".gguf", ".bin"))): + continue # a path: --native, --mtp, --profile ... + out.append(flag if val is None else f"{flag} {val}") + srv = [f"{cfg.get('host', '127.0.0.1')}:{port or cfg.get('port', 8080)}"] + if cfg.get("api_key"): + srv.append("api key set") + if cfg.get("open_browser") is False: # #609 + srv.append("no browser") + for k in ("gpu", "layer_split", "draft_vocab", "fit_max_tokens", "reasoning_budget_tokens", "anthropic_thinking"): + if cfg.get(k) is not None: + v = cfg[k] + srv.append(f"{k} {','.join(map(str, v)) if isinstance(v, list) else str(v).lower() if isinstance(v, bool) else v}") + return " ".join(out) + ("; " if out else "") + "server " + ", ".join(srv) + + +def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False, + layer_split=None, keep=None) -> int: + """keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab, + --vram-reserve-mib).""" + cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) + missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()] + if missing: + fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair") + keep = {k: v for k, v in (keep or {}).items() if v is not None} + reserve = keep.pop("vram_reserve_mib", None) # #493: an engine argument, kept in the config's args + if reserve is not None: + args = cfg["args"] + if "--vram-reserve-mib" in args[:-1]: + args[args.index("--vram-reserve-mib") + 1] = str(reserve) + else: + args += ["--vram-reserve-mib", str(reserve)] + write_config(cfg_path, cfg) + ok(f"saved for this model: {reserve} MiB of VRAM kept free for other programs (--vram-reserve-mib)") + if keep and any(cfg.get(k) != v for k, v in keep.items()): # #179: a --host/--api-key on a start was ignored + cfg.update(keep) + write_config(cfg_path, cfg) + ok("saved for this model: " + ", ".join( + "api key" if k == "api_key" else ("the browser opens" if v else "no browser") if k == "open_browser" + else f"{k.replace('_', ' ')} {v}" for k, v in keep.items())) + cfg_path.touch() # the most recently used model + if "--mtp" in cfg["args"][:-1]: + refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) + cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), + "--port", str(port or cfg.get("port", 8080))] + if cfg.get("backend") == "hip": # AMD, numbered as HIP numbers them (setup's KFD order) + if WIN: + hip_runtime_beside_exe(Path(cfg["exe"]).parent) # #468 #461: also fixes a 0.1.34 install + amd = amd_gpus() + if isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on + cards = amd_parse_gpus(",".join(str(i) for i in gpu), amd) + built = (engine_archs_hip() or []) + miss = [x for x in cards if built and x["arch"] not in built] + if miss: + fail("the installed engine has no code for " + ", ".join(f"{x['name']} ({x['arch']})" for x in miss), + "set it up for these cards: ./setup.sh --setup --backend hip --gpus " + ",".join(map(str, gpu))) + cfg["gpu"], cfg["gpus_asked"] = gpu, True + cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" + split_budget(cfg) # #498: before it is saved (it stops when the RAM is short) + write_config(cfg_path, cfg) + gpu = None + elif gpu is not None: + cmd += ["--gpu", str(gpu)] + found = [] + use = gpu if gpu is not None else cfg.get("gpu") + if isinstance(use, list): + byid = {x["index"]: x for x in amd} + ok("GPUs: " + " + ".join(gpu_name(byid[i]) if i in byid else f"GPU {i} (not found)" for i in use) + + f" together, AMD (layers split {cfg.get('layer_split') or 'auto'})") + else: + g = next((x for x in amd if x["index"] == (use if use is not None else x["index"]) + and amd_problem(x) is None), None) + if g is not None: + ok(f"GPU: {g['name']} ({g['vram_gb']:.0f} GB, AMD)") + else: + found = gpus() + global OLD_GPUS # Pascal / Volta: named on this start, or this model's CUDA 12 engine + OLD_GPUS = OLD_GPUS or old_gpus_opt_in(found, gpu if isinstance(gpu, list) else [gpu] if gpu is not None else + cfg.get("gpu") if isinstance(cfg.get("gpu"), list) else [cfg.get("gpu")], + 12 if config_toolkit(cfg) == 12 else None) + if cfg.get("backend") == "hip": + pass + elif isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on + check_gpus(gpu, found, yes=yes, named=True) + cfg["gpu"], cfg["gpus_asked"] = gpu, True + cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" + split_budget(cfg) # #498: before it is saved (it stops when the RAM is short) + recommend_remote_expert_opt(cfg) + write_config(cfg_path, cfg) + gpu = None + elif gpu is not None: # --gpu N: this start only, on that card + check_gpus([gpu], found) + cmd += ["--gpu", str(gpu)] + else: + cfg = offer_together(cfg_path, cfg, yes) + use = gpu if gpu is not None else cfg.get("gpu") + # #364 #384: a resident low-RAM config on several GPUs; #498: a UD-Q4_K_XL config with its RAM budget (by hand) + if isinstance(use, list) and (split_mmap(cfg) | split_budget(cfg)): + write_config(cfg_path, cfg) + if cfg.get("backend") == "hip": + pass + elif isinstance(use, list): + check_gpus(use, found, "(chosen for this model) ", yes=True, named=True) + byid = {g["index"]: g for g in found} + cfg = ensure_engine_for([byid[i] for i in use], cfg_path, cfg, yes) + ok("GPUs: " + " + ".join(gpu_name(byid[i]) for i in use) + f" together (layers split {cfg.get('layer_split') or 'auto'})") + elif found: + g = next((x for x in found if x["index"] == use), None) if use is not None else max( + found, key=lambda x: (round(x["vram_gb"]), -x["index"])) + if g is not None: + cfg = ensure_engine_for([g], cfg_path, cfg, yes) + ok("GPU: " + gpu_name(g)) + browser = open_browser and cfg.get("open_browser") is not False # #609: "open_browser": false, --no-browser + if browser: + cmd.append("--open") + gb = 0.0 + if "--native" in cfg["args"]: + try: + gb = Path(cfg["args"][cfg["args"].index("--native") + 1]).stat().st_size / 1e9 + except (OSError, IndexError): + pass + say() + say(" " + "-" * 100) + size = f'about {gb:.0f} GB' if gb >= 1 else '34-55 GB' + a_ = cfg["args"] + if "--mmap-experts" in a_ and "--resident-budget-gib" not in a_ and "--resident-experts" not in a_: + # #505: the mapped low-RAM mode loads nothing into RAM up front (the server's narrator says the same) + say(f" Starting {cfg.get('model_name', 'the model')}: it maps {size} of experts from the model files (the OS " + "file cache reads them).") + else: + say(f" Starting {cfg.get('model_name', 'the model')}: it loads {size} into RAM and locks part of it for the " + "GPU.") + say(" While it does, YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES (longer the first time after a") + say(" restart). That is normal: please wait and don't close this window - " + ( + "the browser opens when it is ready." if browser else "the server says when it is ready.")) + say(" Later, closing this window stops the model.") + say(" " + "-" * 100) + for n, line in enumerate(textwrap.wrap(f"Settings ({cfg_path.name}): {settings_summary(cfg, port)}", 100, + break_on_hyphens=False)): # #564: what this start uses + say((" " if n == 0 else " ") + line) + if not WIN and os.environ.get("STRATA_EXECV"): + # Replace this process instead of spawning a child. The Docker image sets STRATA_EXECV=1, + # so there the server is PID 1 and docker stop's SIGTERM reaches the process that can + # answer the engine with QUIT. Normal Linux starts keep spawning the server as a child. + os.execv(cmd[0], cmd) + return subprocess.call(cmd) + + +# the draft subsets setup copied before (sha256): replaced by the current one, a subset made by hand is kept +OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens + + +DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin", "cyrillic": "draft_vocab_cyrillic.bin", + "fr": "draft_vocab_fr.bin"} + + +def saved_draft_vocab(cfg_path: Path) -> str | None: + """The draft subset a model's config chose earlier (--draft-vocab), or None: a setup run again without the flag + rewrites the config, and would otherwise put the default subset back.""" + try: + v = json.loads(cfg_path.read_text(encoding="utf-8-sig")).get("draft_vocab") + except (OSError, ValueError, AttributeError): + return None + return v if v in DRAFT_VOCABS else None + + +def vision_tokens(asked: int | None, vision: str, earlier: Path | None) -> int: + """#625: the most image tokens a picture becomes (the config's vision.max_tokens): --vision-tokens N, else what an + earlier config of this model chose for the same encoder device (a setup run again keeps it), else the device's + default (VISION). More is allowed with a note on the time it takes: setup recommends, it does not cap.""" + default = VISION[vision]["max_tokens"] + if asked is None and earlier is not None: + try: + v = json.loads(earlier.read_text(encoding="utf-8-sig")).get("vision") + except (OSError, ValueError, AttributeError): + v = None + mt = v.get("max_tokens") if isinstance(v, dict) and bool(v.get("gpu")) == (vision == "gpu") else None + if isinstance(mt, int) and mt > 0 and mt != default: + asked = mt + if asked is None: + return default + note = "" + if vision == "cpu" and asked > default: + note = (" - on the CPU a picture takes longer to encode the more tokens it gets (several seconds more at " + "1,024 than at 300)") + elif asked > VISION["gpu"]["max_tokens"]: + note = " - more than the encoder's default needs more VRAM and context per picture" + ok(f"images: up to {asked} image tokens per picture (--vision-tokens; default {default}){note}") + return asked + + +DRAFT_VOCAB_MIB = {"cjk": 348, "cyrillic": 193, "fr": 151, "en": 133} # the draft head's VRAM per subset (IQ3_S: the largest) +SMALL_DRAFT_VRAM_GB = 14 # #474: below this the default subset's head can be what does not fit + + +def draft_vocab_note(vram_gb: float, chosen: str | None) -> list[str]: + """#474: on a card under 14 GB, the default draft subset (cjk, ~348 MiB of VRAM) can be what does not fit at the + start ("the draft head does not fit"), and the engine's expert cache gets what a smaller one leaves. Setup + RECOMMENDS a smaller one here and changes nothing (the owner's rule, #403 #406): a subset chosen with + --draft-vocab, or kept from an earlier install, gets no note. [] for every other case.""" + if chosen or not 0 < vram_gb < SMALL_DRAFT_VRAM_GB: + return [] + start = "START-HERE.bat" if WIN else "./setup.sh" + return [f"Tip for a {vram_gb:.0f} GB card: the draft layer's default token subset (with Chinese, Japanese and " + f"Korean) needs up to ~{DRAFT_VOCAB_MIB['cjk']} MiB of VRAM.", + f" For English and code answers, {start} --draft-vocab en needs up to ~{DRAFT_VOCAB_MIB['en']} MiB " + f"(cyrillic: ~{DRAFT_VOCAB_MIB['cyrillic']}) and leaves the rest to the expert cache - and it is the", + " fix when the start stops with \"the draft head does not fit\". The model keeps the choice."] + + +SMALL_CARD_GB = 7.5 # #496: a card under 8 GB gets a tip (an 8 GB card lists 7.99) + + +def small_card_note(ctx: int, draft_vocab: str | None) -> list[str]: + """#496: what frees VRAM on a card under 8 GB when the start stops with "no VRAM is left for the expert cache" + (the engine already lowers its own reserve on such a card) - a recommendation, setup changes none of it. (The + draft layer stays: the server needs it.)""" + start = "START-HERE.bat --setup" if WIN else "./setup.sh" + tips = [] + if ctx > 8192: + tips.append("an 8K context (a smaller KV cache)") + if draft_vocab != "en": + tips.append(f"--draft-vocab en (a draft head of ~{DRAFT_VOCAB_MIB['en']} MiB instead of " + f"~{DRAFT_VOCAB_MIB[draft_vocab or 'cjk']})") + lines = ["If the start stops with \"no VRAM is left for the expert cache\" (the engine's log says how much is " + "short):"] + if tips: + lines.append(f" run {start} again with " + " and ".join(tips) + ", or close other programs that use the GPU.") + else: + lines.append(" close other programs that use the GPU.") + return lines + + +PARALLEL_MAX = 8 # #465: the engine's batch window holds at most 8 requests +PARALLEL_SHARE = 0.2 # #465: the slots' sessions may take this share of the VRAM the expert cache would hold +PARALLEL_HELD = 0.5 # #465: ... and only where the cache still holds this share of the experts beside them +PARALLEL_COST_NOTE = ("parallel N reduces waiting for several users but costs about 10-25% speed per request on this " + "card") + + +def parallel_slot_gb(ctx: int, kv: str, streaming: bool) -> float: + """#465: the VRAM one batch slot's session takes: its KV cache (12 QSA layers; with KV streaming only the 32K + positions the attention reads stay in VRAM) and the DeltaNet state (~0.17 GB). Measured: 0.56 GiB at 32K int8.""" + kv_tok = 12 * (576 if kv == "q4_0" else 1056) + return (min(ctx, 32768) if streaming else ctx) * kv_tok / 1e9 + 0.17 + + +def parallel_recommend(vram_gbs, arena_gb: float, ctx: int, kv: str, streaming: bool) -> int: + """#465: how many requests at once ("parallel") to recommend: 0 = none (one at a time). Only where the experts + mostly fit in VRAM - the expert cache (each card's VRAM less ~5 GB, every card of a layer split) still holds + PARALLEL_HELD of the model's experts beside the slots' sessions, which take at most PARALLEL_SHARE of it, up to 4. + Where the experts mostly run on the CPU a batch reads about as many experts as the requests one by one and every + slot's VRAM is expert cache lost: measured on a 12 GB RTX 5070 (Q2_0, 32K), a request alone 11-24% slower with 2-4 + slots, 4 requests together 63 tok/s against 71 one after the other (docs/BATCHING.md).""" + if isinstance(vram_gbs, (int, float)): + vram_gbs = [vram_gbs] + cache_gb = sum(max(0.0, v - 5) for v in vram_gbs) + slot = parallel_slot_gb(ctx, kv, streaming) + best = 0 + for n in (2, 3, 4): + if n * slot <= PARALLEL_SHARE * cache_gb and (cache_gb - n * slot) >= PARALLEL_HELD * arena_gb: + best = n + return best + + +def parallel_note(asked: int | None, vram_gbs, arena_gb: float, ctx: int, kv: str, streaming: bool) -> list[str]: + """#465: what setup says about "parallel": the recommendation (or, where it would cost speed, why it is left at + one), or how the asked count compares with it (kept as asked: recommend, never force).""" + rec = parallel_recommend(vram_gbs, arena_gb, ctx, kv, streaming) + slot = parallel_slot_gb(ctx, kv, streaming) + if asked is None or asked <= 1: + if not rec: + return [f"Several requests at once: left at one at a time - {PARALLEL_COST_NOTE} (docs/BATCHING.md)."] + return [f"Several requests at once (opt-in): --parallel {rec} decodes up to {rec} together instead of one " + f"after the other (each takes ~{slot:.1f} GB of VRAM from the expert cache; docs/BATCHING.md)."] + lines = [f"parallel requests: {asked} at once (each takes ~{slot:.1f} GB of VRAM from the expert cache, " + f"{asked * slot:.1f} GB in all)"] + if asked > PARALLEL_MAX: + lines.append(f"the engine runs at most {PARALLEL_MAX} at once; it will use {PARALLEL_MAX}") + if not rec: + lines.append(f"recommended for this card: one at a time - {PARALLEL_COST_NOTE}; kept as you chose") + elif asked > rec: + lines.append(f"recommended for this card: {rec} - more slots leave fewer experts in VRAM, which can make every " + "request slower; kept as you chose") + return lines + + +DESKTOP_RESERVE_MIB = 3072 # #560 #516: what kept a KDE/Wayland desktop alive beside a full expert cache + + +def linux_desktop(env=None) -> bool: + """A graphical session on Linux (Wayland or X).""" + env = os.environ if env is None else env + return sys.platform.startswith("linux") and bool(env.get("WAYLAND_DISPLAY") or env.get("DISPLAY")) + + +def desktop_reserve_note() -> list[str]: + """#560 #516: an AMD card that also drives a Linux desktop - with the default 700 MiB reserve the expert cache + fills it, and when the desktop needs more VRAM amdgpu moves the cache to system RAM, where the OOM killer then ends + the compositor. A recommendation, setup changes nothing.""" + return [f"If this AMD card also drives your desktop and the desktop or apps crash once the model is loaded, keep " + f"more VRAM free: ./setup.sh --vram-reserve-mib {DESKTOP_RESERVE_MIB}", + " (remembered for this model; the expert cache gets ~2.3 GB less, a few % of speed)"] + + +def mtp_corrupt(mtp: Path, env=None) -> bool: + """#327: True when the MTP tensors an install fetched are not the pinned checkpoint's (tools/mtp_fetch.py verify, + which hashes only files that changed since they last checked out). A mirror that ignored range requests left the + shards' starts there instead, and the draft layer built from them accepted nothing - with no error anywhere.""" + if not (mtp / "tensors").is_dir(): + return False + r = subprocess.run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "verify", "--out", str(mtp)], env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + return r.returncode == 3 + + +def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: + """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137), `en` + (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster) or + `cyrillic` (data/draft_vocab_cyrillic.bin: English/code and the whole Cyrillic script, for Ukrainian, Russian, + Bulgarian, Serbian... answers) or `fr` (data/draft_vocab_fr.bin: English/code and the tokens of French text, #597). + Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept.""" + new, dst = ROOT / "data" / DRAFT_VOCABS.get(choice, "draft_vocab.bin"), rt / "draft_vocab.bin" + if not new.exists() or not rt.is_dir(): + return + if dst.exists(): + old = hashlib.sha256(dst.read_bytes()).hexdigest() + shipped = OLD_DRAFT_VOCABS | {hashlib.sha256((ROOT / "data" / f).read_bytes()).hexdigest() + for f in DRAFT_VOCABS.values() if (ROOT / "data" / f).exists()} + if old not in shipped or old == hashlib.sha256(new.read_bytes()).hexdigest(): + return + ok("draft layer: the token subset " + {"cjk": "with Chinese, Japanese and Korean", + "cyrillic": "with the Cyrillic script", + "fr": "for French"}.get(choice, + "for English and code (less VRAM)")) + shutil.copyfile(new, dst) + + +def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: + """The installed engine must have code for every card the model starts on: a card added later (--gpus with an + older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a + card gets the engine compiled for all of them, before the start. A Pascal / Volta card added to a model on the + CUDA 13 engine moves the model to the experimental CUDA 12 engine (CUDA 13 has no code for it).""" + tk = config_toolkit(cfg) + if tk == 13 and any(int(g["arch"]) < CUDA13_MIN_ARCH for g in cards): + return use_cuda12(cards, cfg_path, cfg, yes) + missing = [g for g in cards if not (engine_runs_on(g) if tk == 13 else engine_runs_on(g, tk))] + if not missing: + return cfg + eng = engine_dir(tk) + info = eng / "BUILD.json" + meta = json.loads(info.read_text()) + say() + say(" The installed engine has no code for " + ", ".join(f"{g['name']} (sm_{g['arch']})" for g in missing) + + ": it is compiled for " + ("these cards" if len(cards) > 1 else "it") + " now.") + main = gpu_info(cards[0]["index"]) + archs = sorted({int(x) for x in meta.get("archs", [])} | {int(g["arch"]) for g in cards}) + vision = meta.get("vision") or ("gpu" if (eng / VEXE).exists() else "none") + build_engine({**main, "archs": archs}, vision, yes, get_llama_cpp(), toolkit=tk) + dirs = json.loads(info.read_text()).get("cuda_dirs") or [] + cfg["lib_dirs"] = dirs + [d for d in cfg.get("lib_dirs") or [] if d not in dirs] + write_config(cfg_path, cfg) + return cfg + + +def get_cuda12_engine(url_base, gpu, vision, yes, build=False) -> Path: + """The experimental CUDA 12 engine for these cards (gpu["archs"]): the ready-made one (Windows) with NVIDIA's + CUDA 12 libraries, or compiled here with a CUDA 12.x toolkit (Linux, --build, or no ready-made one).""" + eng = None if build else get_prebuilt(url_base, gpu, vision, toolkit=12) + if eng is not None and json.loads((eng / "BUILD.json").read_text()).get("source") != "local": + pip_cuda_libs(12) + if vision != "none" and not (eng / VEXE).exists(): + eng = None + return eng if eng is not None else build_engine(gpu, vision, yes, get_llama_cpp(), toolkit=12) + + +def engine_lib_dirs(eng: Path, toolkit=13) -> list: + """The library folders a CUDA engine loads from: its own (a compiled one: the toolkit's), else pip's wheels.""" + meta = json.loads((eng / "BUILD.json").read_text()) + return meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(toolkit) + + +def use_cuda12(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: + """A model on the CUDA 13 engine now has a Pascal / Volta card (a --gpus at start): the model's config moves to + the experimental CUDA 12 engine (one engine per model; its other models keep theirs).""" + old = min(int(g["arch"]) for g in cards) + say() + warn(f"sm_{old} is older than CUDA 13 supports (it dropped Pascal and Volta): this model moves to the experimental " + "CUDA 12 engine (docs/OLDER_GPUS.md; START-HERE.bat --setup --cuda 13 and newer cards only moves it back)") + main = gpu_info(cards[0]["index"]) or cards[0] + vision = "gpu" if cfg.get("vision") else "none" + eng = get_cuda12_engine(os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL), + {**main, "archs": sorted({int(g["arch"]) for g in cards})}, vision, yes) + cfg["exe"] = str(eng / EXE) + cfg["cuda"] = 12 + cfg["lib_dirs"] = engine_lib_dirs(eng, 12) + if cfg.get("vision") and (eng / VEXE).exists(): + cfg["vision"]["exe"] = str(eng / VEXE) + write_config(cfg_path, cfg) + ok(f"engine: {eng / EXE} (CUDA 12, experimental)") + return cfg + + +def write_run_script(model, cfg_path, port, open_browser=True): + """run-.bat / .sh: the server with this config; `open_browser` False (#609: --no-browser) leaves --open out.""" + serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), + "--port", str(port)] + (["--open"] if open_browser else []) + if WIN: + script = ROOT / f"run-{model.lower()}.bat" + script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" + + " ".join(f'"{x}"' for x in serve) + "\r\nif errorlevel 1 pause\r\n", encoding="utf-8") + else: + script = ROOT / f"run-{model.lower()}.sh" + script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n", + encoding="utf-8") + script.chmod(0o755) + return script + + +# ------------------------------------------------------------------------------------------------ the rope config +def derived_factor(ctx: int, trained: int = 262144) -> float: + """The automatic extension factor: the FINAL context over the trained one, at least 1. + + Factor 1 removes the automatic expansion - the trained angles stand as they are - but it is not a + switch for rope as a whole: an explicitly chosen method's settings keep their defined behavior. + """ + return max(1.0, float(ctx) / float(trained)) + + +def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): + """The rope config for the context ACTUALLY SERVED: (scaling, scale); scaling None = no scaling flags. + + An explicit --rope-scaling/--rope-scale always wins - a user-supplied factor is kept verbatim even + when a reduction changed the context. Past the trained range an omitted method defaults to yarn - + llama.cpp's extension method: the trained angles survive on the high-frequency pairs and the + magnitude correction keeps the attention temperature - and an omitted factor is derived from the + final context (final / trained, at least 1), as is an explicitly chosen method's missing factor + inside the trained range: factor 1, the trained angles, no expansion. An explicit none is refused + past the trained range (the setup will not configure a run it knows is out of spec) rather than + silently overridden. + """ + if ctx <= trained: + if scale is not None and scaling in (None, "none"): + raise ValueError("--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the " + "trained 262144, so there is nothing to scale)") + if scaling in (None, "none"): + return None, None # the stock model, by choice or by default + return scaling, scale if scale is not None else derived_factor(ctx, trained) + if scaling == "none": + raise ValueError(f"a {ctx // 1024}K context is past the model's trained 262144, and --rope-scaling none " + "keeps the stock angles there - the model has never seen those positions, so the setup " + "refuses the combination instead of quietly overriding it. Pick --rope-scaling yarn or " + "linear, or rerun with --context 262144 or lower") + return scaling or "yarn", scale if scale is not None else derived_factor(ctx, trained) + + +# ------------------------------------------------------------------------------------------------ main +def sycl_setup(argv) -> int: + """--backend sycl: the Intel Arc engine (the SYCL port in sycl/, PR #423), experimental. There is no ready-made + Intel engine: it is compiled from source on the PC (docs/INTEL_ARC.md), then sycl/setup_intel.py runs this setup + with the Intel steps swapped in. Nothing of the CUDA / HIP paths is used or changed.""" + say() + warn("Intel Arc (--backend sycl) is EXPERIMENTAL: a community port of the engine, not tested by the Strata " + "maintainers (no Intel card here). Expect rough edges; issues with your card and driver versions help.") + if WIN: + fail("the Intel Arc engine has no Windows setup yet (no ready-made Intel engine either)", + "run it on Linux (Ubuntu 24.04 with Intel's GPU driver and oneAPI): docs/INTEL_ARC.md") + say(" There is no ready-made Intel engine: it is built from source with Intel oneAPI (icpx + oneMKL),") + say(" docs/INTEL_ARC.md. Setup continues with sycl/setup_intel.py.") + rest, skip = [], False + for x in argv: # setup_intel.py drives this setup through its AMD path + if skip: + skip = False + elif x == "--backend": + skip = True + elif not x.startswith("--backend="): + rest.append(x) + script = ROOT / "sycl" / "setup_intel.py" + if not script.exists(): + fail(f"{script} is missing", "use a full Strata checkout (git clone) - docs/INTEL_ARC.md") + return subprocess.call([sys.executable, str(script), *rest]) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--family", choices=list(FAMILIES), help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5") + ap.add_argument("--model", choices=list(MODELS)) + ap.add_argument("--context", type=int) + ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"], + help="the RoPE extension for a context past the model's trained 262144: linear (position " + "interpolation) or yarn - llama.cpp's types. Omitted with a scaled context, the setup " + "picks yarn; 'none' is refused for such a context") + ap.add_argument("--rope-scale", type=float, + help="the extension factor (default: the final context over the trained 262144, at least 1 - " + "1.5 for 384K, 2 for 512K, 1 inside the trained range)") + ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"], + help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " + "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") + ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"], + help="let the model read images (yes = the encoder on the GPU)") + ap.add_argument("--vision-tokens", type=int, metavar="N", + help="the most image tokens a picture becomes (default 1024 with the encoder on the GPU, 300 on " + "the CPU): more reads small text and charts better, and takes longer to encode; remembered " + "for this model") + ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF", + help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection " + "(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md") + ap.add_argument("--port", type=int, help="the server's port (default: the one the install was set up with, 8080 for a new one)") + ap.add_argument("--gpu", help="one GPU, numbered as nvidia-smi numbers them (default: asked when several can be " + "used; with --setup it is saved, when starting it is for that start only)") + ap.add_argument("--gpus", help="several GPUs sharing one model, as nvidia-smi numbers them (AMD: as setup lists " + "them): \"0,2\", or \"all\" (every card that can); the first is the main one. " + "Saved, also when starting (see docs/MULTI_GPU.md)") + ap.add_argument("--layer-split", help="with --gpus: where each later GPU's layers start (\"18\", \"16,32\"), one " + "rising number per GPU after the first - not layers per card; default " + "auto, placed from each GPU's free VRAM") + ap.add_argument("--no-remote-expert-opt", action="store_true", + help="with two or more GPUs: leave out --remote-expert-opt, which setup adds there (#578)") + ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " + "devices on your network (issue #26; set --api-key too)") + ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)") + ap.add_argument("--no-browser", dest="browser", action="store_false", default=None, + help="do not open the chat page in the browser when the model is ready (for a harness or an app " + "that uses the API; remembered for this model, also in run-.bat/.sh)") + ap.add_argument("--browser", dest="browser", action="store_true", + help="open the chat page again when the model is ready (the default; undoes --no-browser)") + ap.add_argument("--data-dir", help="where the model files go (~70-120 GB): default Strata-data next to this folder, " + "remembered for every Strata folder on this PC") + ap.add_argument("--models-dir", help="where the GGUF files go (default: /models)") + ap.add_argument("--gguf-dir", help="use GGUF files you already have (a folder with every shard: " + "-00001-of-0000N.gguf ... -0000N-of-0000N.gguf)") + ap.add_argument("--yes", action="store_true", help="accept the recommended answers") + ap.add_argument("--setup", action="store_true", help="install another model or change settings") + ap.add_argument("--no-start", action="store_true", help="install only, do not start the model") + ap.add_argument("--update", action="store_true", + help="update the installed engine, Python packages and model settings as a start would, without " + "starting the model (UPDATE.bat / update.sh run it after a git pull)") + ap.add_argument("--build", action="store_true", help="compile the engine instead of using the ready-made one") + ap.add_argument("--cuda", choices=["12", "13", "auto"], default=os.environ.get("STRATA_CUDA") or None, + help="NVIDIA: the CUDA toolkit of this model's engine. auto (default): CUDA 13, the ready-made " + "engine; CUDA 12 (experimental) when a chosen card is older than CUDA 13 supports (Pascal, " + "Volta). 12 also runs with an older driver (Windows 528+, Linux 525+). docs/OLDER_GPUS.md") + ap.add_argument("--prebuilt", default=os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL), + help="where the ready-made engine is (a URL folder or a local folder)") + ap.add_argument("--check", action="store_true", help="only check this PC and exit") + ap.add_argument("--calibrate", action="store_true", + help="tune the engine's settings for this PC (about 5-10 minutes), then start the model") + ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS), + help="the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English " + "and code only (~110 MiB less VRAM, English answers 1-2%% faster), cyrillic = English, code " + "and the Cyrillic script (Ukrainian, Russian... answers decode ~30%% faster), fr = English, " + "code and French (French answers: 18%% more drafts accepted)") + ap.add_argument("--low-ram", choices=["auto", "on", "off", "resident", "mmap"], default="auto", + help="read the model's experts from one file in its folder instead of copying them all into RAM " + "(for a PC with a big GPU and little RAM); auto: when the experts would not fit the RAM. In " + "this mode the experts the GPU does not hold are copied into RAM once when they fit (resident), " + "else read through the OS file cache (mmap); resident / mmap force one of the two") + ap.add_argument("--resident-budget-gib", type=float, metavar="N", + help="UD-Q4_K_XL, UD-IQ4_XS: the GiB of its experts kept in RAM (default: the RAM less 24 GB, 40 on 64 GB; " + "more is kept as you choose, with a note)") + ap.add_argument("--vram-reserve-mib", type=int, metavar="N", + help="VRAM in MiB the engine leaves free for other programs (a game, another model; the engine's " + "default: 700); the expert cache takes that much less") + ap.add_argument("--parallel", type=int, metavar="N", + help="up to N requests decode together (batch slots, opt-in; default: one at a time, the others " + "wait). Each slot takes VRAM from the expert cache; setup says what it recommends") + ap.add_argument("--kv-streaming", choices=["auto", "on", "off"], default="auto", + help="from a 64K context: keep the KV cache in RAM and only the attention's window in VRAM (more " + "experts fit on the GPU); auto: when the RAM has room for it") + ap.add_argument("--backend", choices=["cuda", "hip", "sycl"], + help="cuda = NVIDIA (default), hip = AMD RX 7900 / 7800 / 7700 XT, RX 9060 XT / 9070 / AI PRO R9700 on " + "Linux or Windows (chosen by itself when the PC has no NVIDIA card Strata can use), " + "sycl = Intel Arc, EXPERIMENTAL: Linux, built from source (docs/INTEL_ARC.md)") + ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) + a = ap.parse_args() + if a.backend == "sycl": # Intel Arc: the SYCL port's own setup (sycl/setup_intel.py) + return sycl_setup(sys.argv[1:]) + if a.resident_budget_gib is not None and not a.resident_budget_gib > 0: + ap.error("--resident-budget-gib takes a number of GiB above 0, e.g. --resident-budget-gib 32") + if a.vision_tokens is not None and a.vision_tokens < 1: + ap.error("--vision-tokens takes a number of image tokens, 1 or more, e.g. --vision-tokens 768") + if a.vram_reserve_mib is not None and a.vram_reserve_mib < 0: + ap.error("--vram-reserve-mib takes a number of MiB, 0 or more, e.g. --vram-reserve-mib 2048") + if a.gpu is not None: # --gpu 0,2 means --gpus 0,2 (a user tried it: issue report) + if "," in a.gpu: + a.gpus, a.gpu = a.gpus or a.gpu, None + elif a.gpu.strip().isdigit(): + a.gpu = int(a.gpu) + else: + ap.error(f"--gpu takes a GPU number as nvidia-smi numbers them, e.g. --gpu 1 (or --gpus 0,2), not {a.gpu!r}") + say("Strata - Qwen3.8-Flash-Next on a normal PC (a GPU + system RAM + CPU)") + data, elsewhere = data_folder(a.data_dir) # the model files: in the data folder, found from any copy + roots = [data, *elsewhere] + if a.models_dir is None: + a.models_dir = str(data / "models") + + # ---- 0. already installed: just start it + have = installed_configs() + if a.update: # #475: UPDATE.bat / update.sh - never starts the model + return update_install(have, a) + explicit = a.setup or a.model or a.family or a.check or a.no_start + adopted = None # #629: the earlier install this copy is set up like + if not have and not explicit: # a new copy of Strata (an update unzipped elsewhere): set it + prev = previous_config(elsewhere, load_settings()) # up like the last one, from the files already here + if prev is not None: + ch = choices_from_config(prev) + if ch["model"]: + say(f" Found your earlier install in {prev.parent} ({prev.stem[len('strata-'):]}): setting up this " + "copy the same way - the model files are reused, nothing big is downloaded.") + a.family, a.model, a.context = ch["family"], ch["model"], a.context or ch["context"] + adopted = prev + a.kv = a.kv or ch["kv"] + a.vision = a.vision or ch["vision"] + a.experimental_speed_projection = a.experimental_speed_projection or ch["esp"] + a.host, a.api_key = a.host or ch["host"], a.api_key or ch["api_key"] + a.port = a.port or ch["port"] + if a.vram_reserve_mib is None: # #493: an explicit reserve set up before + a.vram_reserve_mib = ch.get("vram_reserve_mib") + if a.cuda is None and ch.get("cuda") == 12: # the experimental CUDA 12 engine, as before + a.cuda = "12" + if isinstance(ch.get("gpu"), list): # a layer split: set up across the same cards again + a.gpus = a.gpus or ",".join(str(g) for g in ch["gpu"]) + a.layer_split = a.layer_split or ch.get("layer_split") + else: + a.gpu = a.gpu if a.gpu is not None else ch.get("gpu") + a.yes = True + global GPU_PICK, OLD_GPUS + # starting an installed model: --gpus 0,2 (or all) saves those cards for it and starts on them (it used to start + # on the first one alone unless given with --setup), --gpu N runs this start on one card; neither: the saved + # choice, and asked once when the PC has cards that could share the model + run_gpu = start_gpus(a.gpus) or a.gpu + port = a.port or 8080 # a new install's port (issue #32: --port for an existing one) + if have and a.calibrate and not (a.setup or a.model or a.family or a.check): + if not a.build: + update_installed_engine(a.prebuilt) + pick_cfg = have[0] + if len(have) > 1: + say() + for i, c in enumerate(have, 1): + say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") + pick_cfg = have[int(ask("Tune which one?", [str(i) for i in range(1, len(have) + 1)], "1", a.yes)) - 1] + if not calibrate_config(pick_cfg): # #447: said again where it is not lost above the start + say() + warn("this PC is NOT tuned: the tuning failed (the reason is above); the model " + + ("keeps" if a.no_start else "starts with") + " the default settings") + return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, + keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab, + "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) + if have and not (a.setup or a.model or a.family or a.check or a.no_start): + if not a.build: + update_installed_engine(a.prebuilt) + if len(have) == 1: + return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, + keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab, + "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) + say() + for i, c in enumerate(have, 1): + say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") + say(f" {len(have) + 1}) install another model / change settings") + pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes)) + if pick <= len(have): + return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, + keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab, + "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) + + # ---- 1. the PC + step(1, "checking your PC") + found = gpus() + amd = amd_gpus() + amd_ok = [g for g in amd if amd_problem(g) is None] + # older NVIDIA GPUs (Pascal / Volta): the experimental CUDA 12 engine, when chosen (docs/OLDER_GPUS.md) + OLD_GPUS = OLD_GPUS or old_gpus_opt_in(found, named_gpus(a.gpu, a.gpus), a.cuda, + other=bool(amd_ok) or a.backend == "hip") + if OLD_GPUS and a.backend != "hip": + warn(f"older NVIDIA GPUs (Pascal / Volta) can be used ({OLD_GPUS}): experimental, through a second engine " + "built with CUDA 12 (docs/OLDER_GPUS.md)") + nv_ok = any(gpu_problem(g) is None for g in found) + hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok)) + if a.backend is None and nv_ok and amd_ok: + # both kinds of card: asked (a first run on such a PC used to take NVIDIA without mentioning the Radeon) + say() + say(" This PC has NVIDIA and AMD cards Strata can use:") + say(" 1) NVIDIA: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in found if gpu_problem(g) is None) + + " (recommended)") + say(" 2) AMD: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in amd_ok) + + f" ({'the ready-made AMD engine, no images' if WIN else 'compiled here, images on the CPU'}" + " - docs/AMD_HIP.md)") + hip = ask("Which cards?", ["1", "2"], "1", a.yes or a.check) == "2" + if a.check and not hip: + say(f" (the AMD card: {'START-HERE.bat' if WIN else './setup.sh'} --backend hip)") + cuda_tk = 13 # NVIDIA: the toolkit of this model's engine (cuda_choice) + if hip: # AMD: compiled here; Windows: ready-made + if WIN and a.gpus: + fail("several AMD cards sharing one model (--gpus) is Linux-only for now", "use one card: --gpu N") + say(" Your AMD GPUs:" if amd else " No AMD GPU found (" + ("Windows lists no AMD display adapter)." if WIN + else "the amdgpu driver's KFD topology is empty).")) + for g in amd: + say(f" GPU {g['index']}: {g['name']}, {g['vram_gb']:.0f} GB VRAM - " + (amd_problem(g) or "can be used")) + usable = [g for g in amd if amd_problem(g) is None] + if not usable: + fail("no AMD GPU Strata can use", f"the AMD backend runs on {AMD_CARDS}") + if a.gpus: # a layer split across these cards, the first one the main + chosen = amd_parse_gpus(a.gpus, amd) + gpu = chosen[0] + elif a.gpu is not None: + gpu = next((g for g in usable if g["index"] == a.gpu), None) + if gpu is None: + fail(f"AMD GPU {a.gpu} cannot be used", "use one of: " + ", ".join(f"--gpu {g['index']}" for g in usable)) + chosen = [gpu] + else: + gpu = max(usable, key=lambda x: (round(x["vram_gb"]), -x["index"])) + chosen = [gpu] + # the engine is compiled for every chosen card's architecture + gpu = {**gpu, "count": len(amd), "archs": sorted({g["arch"] for g in chosen})} + chosen = [gpu] + chosen[1:] + sel = [g["index"] for g in chosen] + multi = sel if len(sel) > 1 else [] + a.gpu = gpu["index"] if len(amd) > 1 else a.gpu + if multi: + ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)") + ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, {gpu['arch']} (AMD: docs/AMD_HIP.md)") + else: + if not found: + fail("no NVIDIA GPU found (nvidia-smi did not answer)", + "install the NVIDIA driver from https://www.nvidia.com/drivers and restart the PC" + + (f"; AMD ({', '.join(AMD_ARCHS)}): --backend hip" if amd else "")) + if len(found) > 1 or gpu_problem(found[0]) is not None: + gpu_table(found) + sel = choose_gpus(a, found) # asked when two or more cards can share the model + multi = sel if len(sel) > 1 else [] + a.gpu = sel[0] # the main GPU: the checks and the sizing below are its + GPU_PICK = a.gpu + gpu = gpu_info(a.gpu) + chosen = [gpu_info(i) for i in sel] + gpu["archs"] = sorted({x["arch"] for x in chosen}) # the engine needs code for every one of them + if multi: + ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)") + ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, compute capability {cc(gpu)}, driver {gpu['driver']}") + cuda_tk, why = cuda_choice(gpu["archs"], a.cuda) # one engine per model: its oldest card decides + if why: + (warn if cuda_tk == 13 or str(a.cuda) == "12" else ok)(f"CUDA {cuda_tk}: {why}") + min_driver = CUDA12_MIN_DRIVER if cuda_tk == 12 else MIN_DRIVER + if driver_major(gpu) < min_driver: + fail(f"the NVIDIA driver is too old ({gpu['driver']}; {min_driver} or newer is needed)", + "update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again" + + ("" if cuda_tk == 12 else f" (or --cuda 12: the experimental CUDA 12 engine runs with driver " + f"{CUDA12_MIN_DRIVER} or newer, docs/OLDER_GPUS.md)")) + if gpu["vram_gb"] < 11: + warn("less than 12 GB of VRAM: Strata will run, but most experts stay on the CPU and it will be slow") + ram = ram_gb() + cpu, avx2, avx512 = cpu_info() + need = min(d["ram_gb"] for d in MODELS.values()) + low_ok = low_ram_fits("IQ1_M", ram, gpu["vram_gb"]) and a.low_ram != "off" # the smallest model, mapped + if ram < need - 4 and not a.check and not low_ok: + # every model keeps ALL its experts in RAM (23+ GB); VRAM only holds a copy of the most-used ones, so a + # bigger GPU does not lower this. The owner's rule: a stop by default, a risk the user can take (--model + # with --yes, or y) + confirm_risk(f"RAM: {ram:.0f} GB - the smallest model (the Coder) needs about {need} GB: Strata keeps all of " + "the model's experts in RAM (23-50 GB, whatever the GPU), so the OS will page them from disk. " + "Expect it to be very slow, and it may not start at all.", bool(a.model), a.yes, + f"RAM: {ram:.0f} GB - the smallest model (the Coder) needs about {need} GB", + "Strata keeps all of the model's experts in RAM (23-50 GB, whatever the GPU) and the GPU holds a " + "copy of the most-used ones: it needs 32 GB of RAM or more (48 GB for the full model); --model " + "NAME --yes installs one anyway") + warn(f"going on with {ram:.0f} GB of RAM, as you chose") + ok(f"RAM: {ram:.0f} GB" if ram >= need - 4 else f"RAM: {ram:.0f} GB (less than the {need} GB the smallest model needs)" + + ("; the GPU's VRAM makes up for it (the low-RAM mode)" if ram < need - 4 and low_ok else "")) + pf = page_file_gb() + if pf is not None and pf < 4: + warn(f"Windows' page file is {pf:.1f} GB: the graphics card's memory needs room there too (issue #60), so " + "the model may not start or may use less VRAM. Set it to \"System managed\": System > About > " + "Advanced system settings > Performance > Advanced > Virtual memory") + ok(f"CPU: {cpu} ({'AVX-512' if avx512 else 'AVX2' if avx2 else 'no AVX2'})") + floor = cpu_floor(avx2) + if floor == "unsupported": + fail("this CPU has neither AVX2 nor SSE4.2; Strata needs at least SSE4.2 (Intel Nehalem, 2008, or newer)") + if not avx2: + # #394 #595 #623: the ready-made engine is AVX2; an older CPU gets one compiled here, whose CPU experts run on + # ggml-cpu's kernels for this CPU. Experimental: measured only on newer CPUs with the older path forced, and by + # users on a few Xeons. A warning, not a stop. + warn(f"this CPU has no AVX2: Strata support for it is EXPERIMENTAL and slow. Setup compiles the engine on this " + f"PC for {'AVX' if floor == 'avx' else 'SSE4.2'} (STRATA_ISA_FLOOR={floor}; 10-20 minutes, once), and the " + "CPU's share of the experts runs on ggml-cpu's kernels, a few times slower than on an AVX2 CPU. " + "See \"Older CPUs\" in docs/INSTALL.md") + if hip and WIN: + fail("the older-CPU engine is compiled from source, and setup compiles the AMD engine on Linux only", + "use Linux for an AMD card on this CPU, or an NVIDIA card") + a.build = True + if a.check: + say() + for m, d in MODELS.items(): + verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit" + if d.get("budget"): + verdict = (("EXPERIMENTAL, " if d.get("experimental") else "") + + f"fits with {resident_budget_gib(m, ram)} GiB of its experts in RAM, the rest " + "read from the SSD" if ram >= d["ram_gb"] else "does not fit") + if hip: # #429: not run on AMD yet (its prompt kernels are CUDA-only) + verdict += " - NVIDIA only so far, untested on AMD" + elif low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off": + verdict = (f"fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}% " + "of its experts, " + ("the rest stays in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"]) + else "the rest is read from the SSD as needed)")) + say(f" {m:8s} needs ~{d['ram_gb']} GB RAM: {verdict}") + say("\nThis PC can run Strata. Run it again without --check to install.") + return 0 + + # ---- 2. the questions + step(2, "your choices") + fams = list(FAMILIES) + if a.family: + family = a.family + else: + for i, f in enumerate(fams, 1): + d = FAMILIES[f] + say(f" {i}) {d['title']:20s} {d['by']} - {d['about']}" + (" [experimental]" if d.get("experimental") else "")) + family = fams[int(ask("Which model?", [str(i) for i in range(1, len(fams) + 1)], "1", a.yes)) - 1] + fam = FAMILIES[family] + ok(f"model: {fam['title']}") + if fam.get("license"): + say(f" Its license: {fam['license']}") + say() + names = [m for m in MODELS if family in MODELS[m].get("families", ("qwen", "swift"))] + names.sort(key=lambda m: bool(MODELS[m].get("experimental"))) # an experimental size last, never the default + if a.model and a.model not in names: + # #444: say which family has that size, and (with --gguf-dir) which files Strata can run at all + elsewhere_fams = [f for f in FAMILIES if f in MODELS[a.model].get("families", ("qwen", "swift"))] + fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names) + + (f" (or {a.model}: " + ", ".join(f"--family {f} --model {a.model}" for f in elsewhere_fams) + ")" + if elsewhere_fams else "") + + (f".\n {SUPPORTED_GGUFS}" if a.gguf_dir else "")) + for i, m in enumerate(names, 1): + d = MODELS[m] + fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" + if d.get("budget"): + say(f" {i}) {m} {d['about']}; download {d['download_gb']:.0f} GB, keeps ~" + f"{resident_budget_gib(m, ram)} GB of its {d['arena_gb']:.0f} GB of experts in RAM{fit}") + continue + if low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off": + fit = (f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}%, " + + ("the rest in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"]) else "the rest from the SSD)")) + say(f" {i}) {m:8s} {d['about']}; download {d['download_gb']:.0f} GB, uses ~{d['arena_gb']:.0f} GB of RAM{fit}") + rec = str(names.index("IQ3_XXS") + 1) if ram >= 60 and "IQ3_XXS" in names else "1" + model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1] + budget, q4_split = None, False + if MODELS[model].get("budget"): + # Unsloth's UD-Q4_K_XL: a RAM budget of experts, the rest from the GGUF on the SSD - not the low-RAM mode (no + # experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode has no layer split) unless + # the RAM holds the GGUFs and 24 GB more: then several, without the budget, if asked for (#498) + if MODELS[model].get("experimental"): + warn(f"{model} is EXPERIMENTAL (docs/UNSLOTH_Q4.md): most of its experts are read from the SSD while it " + "answers, so it is several times slower than the 2-3-bit models; quality checked against llama.cpp") + if hip and MODELS[model].get("nvidia_only"): + # #429 (jkuepker): checked before the 111 GB download. The HIP engine has no prompt kernels for its + # Q4_K / Q5_K experts (STRATA_MMQ_KQUANTS is CUDA-only) and it has not been run on AMD: asked, not refused + confirm_risk(f"{model} has not been run on AMD cards yet: its prompt kernels are NVIDIA-only, so on " + f"{gpu_name(gpu)} long prompts read much more slowly, and it may not work at all", + bool(a.model), a.yes, f"{model} is NVIDIA-only so far", "choose one of the 2-3-bit models, " + f"or --model {model} --yes to try it on AMD anyway", " Try it anyway?") + warn(f"installing {model} on an AMD card, as you chose (please report how it runs)") + if ram < MODELS[model]["ram_gb"]: + confirm_risk(f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB: " + f"its RAM budget would be {resident_budget_gib(model, ram)} GiB, so nearly every expert is " + "read from the SSD while it answers (very slow), and it may run out of RAM", + bool(a.model), a.yes, f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC " + f"has {ram:.0f} GB", f"choose one of the 2-3-bit models, or --model {model} --yes to " + "install it anyway", " Install it anyway?") + warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose") + budget = budget_choice(model, ram, a.resident_budget_gib) + if multi and not unsloth_together(a, model, ram, gpu, chosen): + multi, sel, chosen = [], [gpu["index"]], [gpu] + q4_split = bool(multi) # #498: on several GPUs without the RAM budget + if not q4_split: + ok(f"RAM budget: {budget:g} GiB of {model}'s experts in RAM, the rest read from the model files on the SSD") + if a.low_ram not in ("auto", "off"): + warn(f"--low-ram {a.low_ram} does not apply to {model}: it always reads part of its experts from the files") + elif a.resident_budget_gib is not None: + warn(f"--resident-budget-gib is for UD-Q4_K_XL and UD-IQ4_XS: {model} keeps all of its experts in RAM or in " + "the low-RAM mode") + low_ram = budget is None and (a.low_ram in ("on", "resident", "mmap") or + (a.low_ram == "auto" and low_ram_needed(model, ram))) + if low_ram and multi and not low_ram_together(a, model, ram, gpu, chosen): + multi, sel, chosen = [], [gpu["index"]], [gpu] + # (the low-RAM mode's variant is decided once the context is known, below; on several GPUs it is the mapped one) + if not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4: + confirm_paging(model, ram, a.low_ram, a.yes, bool(a.model)) + ok(f"size: {model}") + tag = fam["tag"] + model # names of the pack, config and start script + small = min(x["vram_gb"] for x in chosen) # each card keeps its layers' KV of the whole context + rec_ctx = 32768 if small < 14 else 65536 if small < 20 else 131072 + if budget is not None: # UD-Q4_K_XL: every GB of KV is a GB fewer of cached experts + rec_ctx = 8192 if small < 14 else 32768 + # #406: the RAM rule is part of the recommendation (the smaller of the two), no longer a cap over the user's choice + rec_ctx = min(rec_ctx, ram_ctx(model, ram, low_ram)) + if a.context: + ctx = a.context + else: + say() + say(" Context length = how much text the model can see at once (your chat, files, tool output).") + say(" Longer needs more VRAM for it, so fewer experts fit on the GPU:") + for i, c in enumerate(CONTEXTS, 1): + need_c = ctx_ram_need(model, c, low_ram) + note = (" (recommended for your GPU)" if c == rec_ctx else "") + \ + (" (experimental: setup adds rope scaling)" if c > 262144 else "") + \ + (f" (needs ~{need_c:.0f} GB RAM, this PC has {ram:.0f}: may run out of memory)" + if c > 131072 and need_c is not None and need_c > ram else "") + say(f" {i}) {c // 1024}K tokens{note}") + ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(CONTEXTS) + 1)], + str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] + # #406 #364: a context past the RAM rule (an explicit --context, a pick in the list, or the earlier install's) is + # kept, with what it risks. It used to become 128K: users ran 256K fine where setup's estimate said no. + need_gb = ctx_ram_need(model, ctx, low_ram) + if need_gb is not None and ram < need_gb and ctx > 131072: + warn(f"{ctx // 1024}K with {model} needs ~{need_gb:.0f} GB of RAM by setup's estimate " + f"({MODELS[model]['arena_gb']:.0f} GB of experts + the context + room for the rest); this PC has " + f"{ram:.0f}. Kept as you chose: it may be slower or run out of RAM under load. {rec_ctx // 1024}K is the " + "recommended size.") + scaling = a.rope_scaling + if ctx > 262144 and scaling is None and not a.yes: + # the interactive path: one question, yarn preselected (llama.cpp's extension method, recall-tested + # here at 512K). With --yes nothing prints: resolve_rope takes yarn below and the ok() line says so. + say() + say(f" A {ctx // 1024}K context runs the model past its trained 262,144 positions: the rotary angles") + say(" get rescaled (llama.cpp's RoPE extension). yarn keeps the trained angles on the high-frequency") + say(" pairs and corrects the magnitudes; linear shrinks every angle. Override any time with") + say(" --rope-scaling.") + scaling = ask("RoPE extension method?", ["yarn", "linear"], "yarn", a.yes) + try: + scaling, rope_scale = resolve_rope(ctx, scaling, a.rope_scale) + except ValueError as e: + fail(str(e)) + if scaling is not None: + origin = ("final context / trained 262144; override with --rope-scale" if a.rope_scale is None + else "as requested") + ok(f"rope scaling: {scaling}, factor {rope_scale:g} ({origin})") + ok(f"context: {ctx} tokens") + # the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21) + kv = "fp16" if ctx <= 8192 else (a.kv or "int8") + if ctx > 8192 and not a.kv and not a.yes: + say() + say(" KV cache precision (the model's memory of the conversation):") + say(" 1) 8-bit (recommended: what every published number was measured with)") + say(" 2) 4-bit half the memory (about 4% faster at 128K), but measurably less precise on long") + say(" documents; long-context lookups (needle tests) still pass") + kv = ["int8", "q4_0"][int(ask("KV cache?", ["1", "2"], "1", a.yes)) - 1] + if ctx > 8192: + ok(f"KV cache: {'8-bit' if kv == 'int8' else '4-bit (Hadamard-rotated)'}") + if MODELS[model].get("vision", fam.get("vision")) is False: # UD-IQ4_XS: images, unlike UD-Q4_K_XL + vision = "none" + if a.vision not in (None, "no", "none"): + warn(f"images are not available with {model} yet: off") + elif hip: + vision = hip_vision(a.vision) + elif a.vision: + vision = {"yes": "gpu", "no": "none"}.get(a.vision, a.vision) + else: + say() + say(" Images: the model can also read pictures (screenshots, photos, scanned pages). This adds a 0.9 GB") + say(" download and keeps ~1.4 GB of VRAM free for the image encoder, so text is a few % slower.") + vision = "gpu" if ask("Do you want images?", ["y", "n"], "n", a.yes) == "y" else "none" + ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) + # The low-RAM mode's two variants. resident: the experts the GPU's cache does not hold (and, as far as RAM allows, + # the ones the prompt path borrows cache room from) are copied from the pack's experts.bin into RAM once, so + # nothing is read from the SSD while it answers (engine 0.1.30, --resident-experts; the engine falls back to mmap + # with a warning when they do not fit the RAM it finds free). mmap: they are read through the OS file cache. + # The GPU's share: its VRAM less the dense weights and buffers, this context's KV cache and the image encoder's room. + resident = False + if low_ram: + arena = MODELS[model]["arena_gb"] + vram = gpu["vram_gb"] - (VISION[vision]["reserve_mib"] / 1024 if vision != "none" else 0) + share = low_ram_gpu_share(model, vram, ctx, kv) + rest = arena - low_ram_gpu_gb(model, vram, ctx, kv) + resident = a.low_ram == "resident" or (a.low_ram != "mmap" and low_ram_resident(model, ram, vram, ctx, kv)) + if multi: # #364 #384: every chosen card's share (the image encoder on the main one), the mapped variant + held = min(arena, low_ram_gpu_gb(model, vram, ctx, kv) + + sum(low_ram_gpu_gb(model, x["vram_gb"], ctx, kv) for x in chosen[1:])) + share, resident = held / arena, False + ok(f"low-RAM mode on {len(chosen)} GPUs: {model}'s experts ({arena:.0f} GB) are read from the model folder " + f"through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPUs hold ~{100 * share:.0f}% " + "of them") + if share < 0.6: + warn("most of the experts are read from the SSD while it answers: expect it to be much slower than " + "with enough RAM (a faster SSD and a smaller size help)") + elif resident: + ok(f"low-RAM mode: the GPU holds ~{100 * share:.0f}% of {model}'s experts ({arena:.0f} GB) and the other " + f"~{rest:.0f} GB stay in RAM ({ram:.0f} GB), read once from a copy in the model folder") + else: + ok(f"low-RAM mode: {model}'s experts ({arena:.0f} GB) are read from the model folder through the OS file " + f"cache instead of a copy in RAM ({ram:.0f} GB); the GPU holds ~{100 * share:.0f}% of them") + if share < 0.6: + warn("most of the experts are read from the SSD while it answers: expect it to be much slower than " + "with enough RAM (a faster SSD and a smaller size help)") + # EXPERIMENTAL: the experimental-speed-projection control vector (data/experimental-speed-projection), off unless + # chosen here; with it loaded, the web app and the API switch it off per request + esp = None + esp_choice = (a.experimental_speed_projection or "").strip() + if family in ("qwen", "coder"): # the Coder: the same model's residual stream + if not esp_choice: + say() + say(" EXPERIMENTAL - speed projection: a small control vector applied while the model runs (layers 4-44).") + say(" It changes how the model answers: its package describes it as a refusal-direction projection (the") + say(" model declines far fewer requests). Off unless you choose it; when on, the web app can switch it off") + say(" per chat. Details: data/experimental-speed-projection/README.md") + esp_choice = "on" if ask("Turn on the experimental speed projection?", ["y", "n"], "n", a.yes) == "y" else "off" + if esp_choice.lower() not in ("off", "no", "n", "0"): + esp = ESP_VECTOR if esp_choice.lower() in ("on", "yes", "y", "1") else Path(esp_choice).expanduser().resolve() + if not esp.is_file(): + fail(f"the experimental speed projection's vector is missing: {esp}") + ok("experimental speed projection: " + ("ON (experimental)" if esp else "off")) + elif esp_choice.lower() not in ("", "off", "no", "n", "0"): + warn("the experimental speed projection is made for the original Qwen3.8-Flash-Next, not Swift 1.5: left off" + if family == "swift" else f"the experimental speed projection is not tested with {model}: left off") + models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag + shards = gguf_dir_shards(models_dir, fam, model) if a.gguf_dir else \ + [models_dir / model_file(fam, model, i) for i in range(1, model_shards(fam, model) + 1)] + problem = gguf_dir_problem(models_dir, shards[0], fam, model) if a.gguf_dir else None + if problem: # #444: files Strata cannot run, or another choice's files + fail(*problem) + if not a.gguf_dir and not all(sh.exists() and done(sh) for sh in shards): + for r in elsewhere: # already downloaded in a Strata folder on another drive + cand = [r / "models" / tag / sh.name for sh in shards] + if all(c.exists() and done(c) for c in cand): + models_dir, shards = cand[0].parent, cand + ok(f"model files found in {models_dir}") + break + for s in shards: # #173: a whole file copied in by hand has no finish mark + if s.exists() and not done(s) and whole_shard(s): + mark(s, "whole (checked against its own tensor directory)") + have_model = all(s.exists() and (done(s) or a.gguf_dir) for s in shards) + # #425 (jctaborda): a download that resumes needs room only for what is still missing - the finished shards and + # the .part files already on the disk count + on_disk = sum(f.stat().st_size for s in shards for f in (s, s.with_name(s.name + ".part")) if f.is_file()) / 1e9 + to_fetch = 0 if a.gguf_dir or have_model else max(MODELS[model]["download_gb"] - on_disk, 0) + need = to_fetch + 8 + \ + (40 if model == "Q2_0" and avx512 and family == "qwen" else 0) + (1 if vision != "none" else 0) + \ + (MODELS[model]["arena_gb"] + 1 if low_ram and not (model == "Q2_0" and avx512 and family == "qwen") else 0) + if free_gb(models_dir) < need: + fail(f"not enough free disk space in {models_dir}: need ~{need:.0f} GB" + + (f" ({on_disk:.0f} GB of the model is already there)" if on_disk >= 1 and not have_model else ""), + "use --models-dir on a bigger drive") + + # ---- 3. python packages + step(3, "Python packages") + pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, + "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") + + # ---- 4. the engine + step(4, "the Strata engine") + llama = get_llama_cpp() + ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)") + if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler) + eng = None if a.build else get_prebuilt_hip(a.prebuilt, gpu) + if eng is None: + fail("no ready-made AMD engine for this Strata version" + (" (--build)" if a.build else ""), + "compiling it on Windows: tools\\hip\\build_windows.bat makes strata-windows-x64-hip.zip, then run " + "START-HERE.bat --backend hip --prebuilt (docs/AMD_HIP.md)") + gpu = hip_card(eng, gpu, amd) + a.gpu = gpu["index"] if gpu["count"] > 1 else a.gpu + else: + eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision, **({"toolkit": 12} if cuda_tk == 12 + else {})) + if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text()).get("source") != "local": + pip_cuda_libs(cuda_tk) + if vision != "none" and not (eng / VEXE).exists(): + warn("the ready-made engine has no image encoder: compiling it") + eng = None + else: + vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text()), gpu, vision) + if eng is None: + eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk) + meta = json.loads((eng / "BUILD.json").read_text()) + if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH + lib_dirs = [str(d) for d in hip_lib_dirs(eng)] + else: + lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk) + engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + need_engine = MODELS[model].get("engine", UNSLOTH_ENGINE) + if budget is not None and engine_ver < need_engine: # checked before the 94-111 GB download + fail(f"{model} needs engine {'.'.join(map(str, need_engine))} or newer; this one is {meta.get('version')}", + "update Strata (or compile the engine with --build) and run setup again") + ok(f"engine: {eng / EXE}") + + # ---- 5. the model files + step(5, f"downloading {fam['title']} {model}") + if not a.gguf_dir: + missing = [s.name for s in shards if not (s.exists() and done(s))] + if missing: # #495: files downloaded by hand go here, or --gguf-dir + say(f" The model files go in {models_dir}") + say(f" Files you already have: put them here with their original names ({', '.join(missing)}), or use " + "--gguf-dir .") + if hf_endpoint() != HF_DEFAULT: + say(f" Downloading from {hf_endpoint()} (HF_ENDPOINT)") + for s in shards: + if s.exists() and done(s): + ok(f"{s.name} already downloaded") + continue + # the original's shard 2 is the same file for all its sizes and the Coder: reuse one that is already here + other = [p for p in Path(a.models_dir).glob("*/Qwen3.8-Flash-Next-GSQ-RCO-*-00002-of-00002.gguf") if done(p)] + if family in ("qwen", "coder") and s.name.endswith("00002-of-00002.gguf") and other and not s.exists(): + try: + os.link(other[0], s) + mark(s) + ok(f"{s.name} shared with {other[0].parent.name} (identical file)") + continue + except OSError: + pass + download(fam["hf"].format(q=model) + s.name, s) + check_shards(shards) + for s in shards: # the Unsloth files: pinned sizes and SHA-256 + if s.name in fam.get("sha256", {}): + verify_sha256(s, *fam["sha256"][s.name]) + ok("model files present") + mmproj = Path(a.models_dir) / fam["mmproj"] + if not mmproj.exists(): + mmproj = find_in(roots, f"models/{fam['mmproj']}") or mmproj + if vision != "none": + if not mmproj.exists() and a.gguf_dir and (Path(a.gguf_dir) / fam["mmproj"]).exists(): + mmproj = Path(a.gguf_dir) / fam["mmproj"] + else: + download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder") + ok(f"vision encoder: {mmproj}") + + # ---- 6. the pack and the MTP draft layer + step(6, "preparing the model for Strata") + pack = find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower() + env = dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py")) + if model == "Q2_0" and avx512 and family == "qwen": + # the Q2_0 experts repacked for the AVX-512 kernel (the measured speed): a one-time ~40 GB conversion + if not (pack / "index.txt").exists() or not (pack / "experts.bin").exists(): # index.txt is written last + say(" Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ...") + run([sys.executable, str(ROOT / "tools" / "strata_pack.py"), "build", "--gguf", str(shards[0]), + "--out", str(pack), "--skip-hash"], env=env) + run([sys.executable, str(ROOT / "tools" / "pack_index.py"), "--pack", str(pack)], env=env) + if not (pack / "tokenizer" / "vocab.json").exists(): + run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(shards[0]), + "--out", str(pack)], env=env) # writes /tokenizer/ + elif not (pack / "native_experts.txt").exists() or not (pack / "tokenizer" / "vocab.json").exists(): + # every tensor as the GGUF stores it; the experts are read from the GGUF at start (seconds to build) + # (UD-Q4_K_XL: --compat-bf16 - its Q8_0 hyper-connection projections become BF16, the form the engine reads) + run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack), + *fam.get("pack_args", [])], env=env) + if low_ram and not (pack / "experts.bin").exists(): + say(f" Writing the experts into one file for the low-RAM mode (one time, {MODELS[model]['arena_gb']:.0f} GB) ...") + run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack), + "--experts-bin"], env=env) + ok(f"model prepared: {pack}") + mtp = (find_in(roots, "mtp/rt/experts.bin") or data / "mtp/rt/experts.bin").parent.parent + rt = mtp / "rt" + corrupt = (rt / "experts.bin").exists() and mtp_corrupt(mtp, env) + if corrupt: + warn("some MTP tensors are not the checkpoint's (a download mirror that ignored range requests, #327): " + "fetching them again and rebuilding the draft layer") + if corrupt or not (rt / "experts.bin").exists(): + say(" The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:") + say(" only its ~5 GB of MTP tensors are downloaded.") + run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "fetch", "--out", str(mtp)], env=env) + run([sys.executable, str(ROOT / "tools" / "mtp_pack.py"), "--src", str(mtp), "--experts", "q2_0", + "--out", str(mtp / "mtp-q2_0.gguf")], env=env) + run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], + env=env) + # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en) + draft_vocab = a.draft_vocab or saved_draft_vocab(ROOT / f"strata-{tag.lower()}.json") + refresh_draft_vocab(rt, draft_vocab or "cjk") + ok(f"MTP draft layer: {rt}") + for line in draft_vocab_note(gpu.get("vram_gb", 0.0), draft_vocab): # #474: a recommendation, nothing changes + say(" " + line) + + # ---- 7. the start script + step(7, "writing the start script") + sys.path.insert(0, str(ROOT / "tools")) + from gguf_reader import GGUFFile # the PLE table's shard: shard 2 (original) or 1 (Swift) + ple = next((s for s in shards if any(t.name == "per_layer_token_embd.weight" for t in GGUFFile(s).tensors)), None) + if ple is None: + fail("the model has no per_layer_token_embd tensor (is this a Qwen3.8-Flash-Next GGUF?)") + # (a 4-shard file: the engine finds the PLE table's shard itself from shard 1, the measured setup) + args = ["--pack", str(pack), "--native", str(shards[0]), *(["--ple-gguf", str(ple)] if len(shards) <= 2 else []), + "--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto", + "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt), + "--max-context", str(ctx)] + if scaling is not None: # the resolved config: explicit flags as given, or the automatic yarn+factor + args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"] + if ctx > 8192: + args += ["--kv", kv] + if resident and a.low_ram != "resident" and engine_ver < RESIDENT_ENGINE: + resident = False # an engine from before --resident-experts would refuse it + ok(f"low-RAM mode: engine {meta.get('version')} has no resident variant yet; the experts are read through " + "the OS file cache (run setup again after the next engine update)") + if low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped + args += ["--resident-experts" if resident else "--mmap-experts"] + disk = None if is_wsl() else rotational_disk(ple) # #605 (WSL's virtual disk says rotational) + if disk: + tensor = next((t for t in GGUFFile(ple).tensors if t.name == "per_layer_token_embd.weight"), None) + size = getattr(tensor, "expected_bytes", lambda: None)() + table_gb = size / 1e9 if size else 28.8 + if ram >= MODELS[model]["ram_gb"] + table_gb + 4: + args += ["--ple-io", "ram"] + ok(f"the model is on a rotational disk ({disk}): its {table_gb:.0f} GB n-gram table is kept in RAM " + "(--ple-io ram) - read from the disk at random, it can stall prompts for minutes (#605)") + else: + warn(f"the model is on a rotational disk ({disk}): its n-gram table is read from it at random, which can " + f"stall prompts for minutes (#605). An SSD is recommended; with ~{table_gb:.0f} GB more RAM, " + "--ple-io ram in the config's args keeps the table in RAM instead") + # KV streaming: from 64K up the whole KV cache lives in RAM and only the part the attention reads (32K positions + # per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It + # costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 7.5 KB with 4-bit, so only when it fits. + kv_ram_gb = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9 # 12 QSA layers + the draft layer + # Hybrid K8V4 never streams its KV (mode 0 only, layer.hpp), so it is excluded from the WHOLE streaming + # decision rather than one threshold at a time - a future tier added to this chain cannot reintroduce the + # combination the engine refuses (PR review). + # --kv-streaming on|off overrides the RAM test (the owner's rule); k8v4 and WSL stay off - they cannot stream. + stream_fits = ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1 + if kv == "k8v4": + if ctx >= 65536: + ok("KV streaming off: not supported with --kv k8v4; the KV cache stays in VRAM") + if a.kv_streaming == "on": + warn("--kv-streaming on: the engine has no KV streaming with --kv k8v4 (it refuses the pair): off") + elif is_wsl() and ctx >= 65536: + ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM") + if a.kv_streaming == "on": + warn("--kv-streaming on: WSL cannot stream the KV cache (its RAM copy must be pinned, and the driver pins " + "only about 1 GB there): off") + elif ctx >= 65536 and a.kv_streaming == "off": + ok("KV streaming off, as you chose (--kv-streaming off): the KV cache stays in VRAM") + elif ctx >= 65536 and (stream_fits or a.kv_streaming == "on"): + args += ["--kv-resident", "32768"] + ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM") + if not stream_fits: + warn(f"KV streaming needs ~{kv_ram_gb:.1f} GB of RAM beside the ~{MODELS[model]['ram_gb']} GB {model} " + f"uses; this PC has {ram:.0f}. Kept as you chose (--kv-streaming on): it may page or run out of RAM " + "under load") + if q4_split: # #498: no budget to take it out of + pass + elif budget is not None and a.resident_budget_gib is None: # its RAM comes out of the experts' budget + budget = resident_budget_gib(model, ram, kv_ram_gb) + ok(f"RAM budget: {budget} GiB (less the KV cache's RAM)") + elif budget is not None and budget > resident_budget_gib(model, ram, kv_ram_gb): + warn(f"the KV cache's {kv_ram_gb:.1f} GB of RAM come on top of your {budget:g} GiB RAM budget (setup " + f"would take them out of it: {resident_budget_gib(model, ram, kv_ram_gb)} GiB); kept as you chose") + elif ctx >= 65536: # #620: say why, so a regenerated config that lost --kv-resident is not a surprise + ok(f"KV streaming off: it needs ~{kv_ram_gb:.1f} GB of RAM beside the ~{MODELS[model]['ram_gb']} GB {model} " + f"uses, and this PC has {ram:.0f}; the KV cache stays in VRAM (fewer cached experts). --kv-streaming on " + "turns it on anyway") + elif a.kv_streaming == "on": + warn("--kv-streaming on: a context under 64K is not streamed (the attention's window holds all of it): off") + if budget is not None and not q4_split: # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N + args += ["--resident-budget-gib", f"{budget:g}"] # GiB kept in RAM (#498: a layer split has no budget) + if vision != "none": + args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])] + if vision == "gpu" and a.vram_reserve_mib is None and 0 < gpu.get("vram_gb", 0.0) <= 12.5: + # a tip only (recommend, never force): on a 12 GB card the encoder's 700 MiB can leave ~200 MiB free + print(f" tip: images on a {gpu['vram_gb']:.0f} GB card can leave little VRAM free; if a request stalls, " + f"run setup again with --vram-reserve-mib {VISION_GPU_SMALL_RESERVE_MIB}") + if a.vram_reserve_mib is not None: # #493: VRAM left free for other programs (only when given) + if "--vram-reserve-mib" in args: + i = args.index("--vram-reserve-mib") + 1 + if vision == "gpu" and a.vram_reserve_mib < int(args[i]): + warn(f"--vram-reserve-mib {a.vram_reserve_mib}: the image encoder on the GPU needs ~{args[i]} MiB of " + "it; kept as you chose (it may run out of VRAM when it reads a picture)") + args[i] = str(a.vram_reserve_mib) + else: + args += ["--vram-reserve-mib", str(a.vram_reserve_mib)] + ok(f"VRAM kept free for other programs: {a.vram_reserve_mib} MiB (--vram-reserve-mib; the expert cache takes " + "that much less)") + if not multi and 0 < gpu.get("vram_gb", 0.0) < SMALL_CARD_GB: + # #496: on a 6 GB card the expert cache can get no room at all; the engine lowers its own reserve when that + # is what it takes, and says what is short when even that is not enough. Setup only says what helps. + for line in small_card_note(ctx, draft_vocab): # a recommendation: nothing changes + say(" " + line) + elif hip and a.vram_reserve_mib is None and linux_desktop(): + for line in desktop_reserve_note(): # #560 #516: a recommendation: nothing changes + say(" " + line) + if esp is not None: + # the package's profile, with llama.cpp's flags (the engine takes the same ones) + args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44", + "--cvec-mode", "project", "--cvec-dir", "per-layer"] + cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), + "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"), + "lib_dirs": lib_dirs, "port": port} + if cuda_tk == 12: # the experimental CUDA 12 engine (engine-cuda12/) + cfg["cuda"] = 12 + if hip: + cfg["backend"] = "hip" + # the dense prompt GEMMs through hipBLASLt with kernels measured on this GPU generation (tools/hip; +40-60% + # prompt speed on the 7900 XTX): only a table for this card's arch AND the installed hipBLASLt version (the + # engine refuses any other one and falls back to plain hipBLAS) + table = hipblaslt_table(gpu["arch"], lib_dirs, meta.get("hipblaslt_version")) + if table: + cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(table)} + if resident: # ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable + cfg.setdefault("env", {})["STRATA_RESIDENT_PIN"] = "0" + if gpu["count"] > 1 or a.gpu is not None: + cfg["gpu"] = gpu["index"] # the engine is told this card (issue #51) + cfg["gpus_asked"] = True # chosen at setup: not asked again at start + if multi: # a layer split across these cards (the server adds the flag) + cfg["gpu"] = multi + cfg["layer_split"] = a.layer_split or "auto" + ok(f"layer split across GPUs {multi} ({cfg['layer_split']})") + recommend_remote_expert_opt(cfg, off=a.no_remote_expert_opt) + if a.host: + cfg["host"] = a.host + if a.api_key: + cfg["api_key"] = a.api_key + if draft_vocab: + cfg["draft_vocab"] = draft_vocab + if a.browser is not None: # #609: only when given (else an earlier choice is carried over) + cfg["open_browser"] = a.browser + # #465: requests at once - written only when given (else an earlier "parallel" is carried over); a recommendation + streaming = "--kv-resident" in args + if a.parallel is not None: + if a.parallel >= 2: + cfg["parallel"] = a.parallel + for i, line in enumerate(parallel_note(a.parallel, [g.get("vram_gb", 0.0) for g in chosen], + MODELS[model]["arena_gb"], ctx, kv, streaming)): + (ok if i == 0 else warn)(line) + else: + cfg["parallel"] = 1 + ok("parallel requests: one at a time (--parallel 1)") + if vision != "none": + old_cfg = ROOT / f"strata-{tag.lower()}.json" + vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted) + cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]), + "gpu": vision == "gpu", "max_tokens": vt} + if vision == "cpu": + cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) + elif a.vision_tokens is not None: + warn("--vision-tokens: images are off for this model, so it is not used") + cfg_path = ROOT / f"strata-{tag.lower()}.json" + cal = setup_calibration(cfg, hip) # #566: Linux HIP too; the tuning is offered on NVIDIA only + if cal is not None: + sys.path.insert(0, str(ROOT / "tools")) + import calibrate as CAL + cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) + ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) + else: # #642: measured counts (a calibration) win over the rule + cfg["args"] = recommend_pool_workers(cfg["args"]) + write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) + script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) + # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it + if cal is None and not hip and not a.no_start and not a.yes and ask( + "Tune Strata for this PC now? It measures a few engine settings (about 5-10 minutes; the PC is busy " + "meanwhile; later: START-HERE --calibrate)", ["y", "n"], "y", a.yes) == "y": + tuned = calibrate_config(cfg_path) + else: + tuned = None # not asked for: nothing to repeat below + ok(f"start script: {script.name}") + + say() + say("All set.") + say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)") + say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") + if a.host and a.host not in ("127.0.0.1", "localhost"): + say(f" Other devices: the server window prints this PC's address (http://:{port}/)" + + ("" if a.api_key else " - no API key set: anyone on your network can use it")) + say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away") + if vision != "none": + say(" Images: send them in the chat page, in chat.py (/image ) or over the API") + if a.parallel is None: # #465: the opt-in, said once (nothing changes) + for line in parallel_note(None, [g.get("vram_gb", 0.0) for g in chosen], MODELS[model]["arena_gb"], ctx, kv, + "--kv-resident" in cfg["args"]): + say(" " + line) + if tuned is False: # #447: a failed tuning is repeated here, not only above + say(" Tuning: FAILED (the reason is above): the default settings stay - " + f"{'START-HERE.bat' if WIN else './setup.sh'} --calibrate tries again") + if a.no_start: + return 0 + return start(cfg_path, port) + + +if __name__ == "__main__": + try: + sys.exit(main()) + except KeyboardInterrupt: + say("\nstopped.") + sys.exit(1) diff --git a/setup.sh b/setup.sh new file mode 100755 index 0000000..d7bac95 --- /dev/null +++ b/setup.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# Strata for Linux: the first run installs everything and starts the model; later runs just start it. +# Needs only an NVIDIA driver (or, for an AMD Radeon card, the kernel's amdgpu driver: see docs/AMD_HIP.md). +# Python (with venv) is installed through apt/dnf if it is missing (asks for sudo). +cd "$(dirname "$0")" || exit 1 +# Python 3.10+ that can make a venv WITH pip: Debian/Ubuntu ship `venv` without `ensurepip` (that is the separate +# python3-venv package), and a venv made without it has no pip +ok_py() { "$1" -c 'import sys, venv, ensurepip; sys.exit(0 if sys.version_info >= (3, 10) else 1)' 2>/dev/null; } +# a .venv from an earlier run that failed half-way has a python but no pip: start it again +if [ -x .venv/bin/python ] && ! .venv/bin/python -m pip --version >/dev/null 2>&1; then + rm -rf .venv +fi +if [ ! -x .venv/bin/python ]; then + PY="" + for c in python3 python; do + if command -v $c >/dev/null 2>&1 && ok_py $c; then + PY=$c; break + fi + done + if [ -z "$PY" ]; then + echo "Python 3.10+ with venv is needed; installing it (sudo will ask for your password) ..." + if command -v apt-get >/dev/null 2>&1; then + sudo apt-get update && sudo apt-get install -y python3 python3-venv python3-pip + elif command -v dnf >/dev/null 2>&1; then + sudo dnf install -y python3 python3-pip + elif command -v pacman >/dev/null 2>&1; then + sudo pacman -S --noconfirm python python-pip + fi + PY=python3 + if ! ok_py $PY; then + echo "Please install Python 3.10 or newer with venv (Ubuntu/Debian: sudo apt install python3-venv), then run" + echo "./setup.sh again." + exit 1 + fi + fi + # a private environment inside this folder (system Python stays untouched; newer distros refuse global pip) + $PY -m venv .venv || { rm -rf .venv; echo "could not create .venv: sudo apt install python3-venv"; exit 1; } +fi +exec .venv/bin/python setup.py "$@" diff --git a/src/artifact/dequant.cpp b/src/artifact/dequant.cpp new file mode 100644 index 0000000..ff058c0 --- /dev/null +++ b/src/artifact/dequant.cpp @@ -0,0 +1,123 @@ +// 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 new file mode 100644 index 0000000..5498ecd --- /dev/null +++ b/src/artifact/gguf_reader.cpp @@ -0,0 +1,67 @@ +// 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 new file mode 100644 index 0000000..70f1bc2 --- /dev/null +++ b/src/artifact/gguf_reader_test.cpp @@ -0,0 +1,93 @@ +// 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 new file mode 100644 index 0000000..ab5b5ad --- /dev/null +++ b/src/core/concurrent_main.cpp @@ -0,0 +1,197 @@ +// 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 new file mode 100644 index 0000000..f544dd7 --- /dev/null +++ b/src/core/conversation_cache_test.cpp @@ -0,0 +1,305 @@ +#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 new file mode 100644 index 0000000..4355dc4 --- /dev/null +++ b/src/core/conversation_checked.hpp @@ -0,0 +1,24 @@ +#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 new file mode 100644 index 0000000..bd5740f --- /dev/null +++ b/src/core/conversation_memory.cpp @@ -0,0 +1,51 @@ +#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 new file mode 100644 index 0000000..a8cb25d --- /dev/null +++ b/src/core/conversation_memory_test.cpp @@ -0,0 +1,66 @@ +#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 new file mode 100644 index 0000000..759daa6 --- /dev/null +++ b/src/core/conversation_snapshot.cpp @@ -0,0 +1,268 @@ +#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. + const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0; + // Format 3 identifies snapshot K8V4 only; never pass it to the block movers. Rotated INT8 K/V (#293, + // STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a + // snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse. + // (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 new file mode 100644 index 0000000..1f1de53 --- /dev/null +++ b/src/core/conversation_snapshot_test.cpp @@ -0,0 +1,324 @@ +#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 new file mode 100644 index 0000000..981beca --- /dev/null +++ b/src/core/conversation_state.cpp @@ -0,0 +1,332 @@ +#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 (!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); + for (size_t i = 0; i < key.size(); ++i) + if (key[i] < 0 || (i != 1 && key[i] == 0)) return fail(error, "invalid model geometry"); + size_t recurrence = 0, convolution = 0; + if (!product(recurrence, {(uint64_t) g.ssm_state_size, (uint64_t) g.ssm_v_heads, (uint64_t) g.ssm_state_size}) || + !product(convolution, {(uint64_t) g.ssm_conv_channels, (uint64_t) (g.ssm_d_conv - 1)}) || + !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 = sizeof(int32_t); + size_t total = 0; + if (!product(total, {(uint64_t) g.n_qsa_layers(), z.tail}) || + !product(total, {(uint64_t) g.n_qsa_layers(), z.dead}) || + !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 new file mode 100644 index 0000000..f993eeb --- /dev/null +++ b/src/core/conversation_validation_test.cpp @@ -0,0 +1,239 @@ +// 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 new file mode 100644 index 0000000..fbc7030 --- /dev/null +++ b/src/core/device.cu @@ -0,0 +1,344 @@ +// 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 new file mode 100644 index 0000000..c6872af --- /dev/null +++ b/src/core/device_main.cpp @@ -0,0 +1,122 @@ +// 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 new file mode 100644 index 0000000..b8df2fa --- /dev/null +++ b/src/core/expert_cache.cpp @@ -0,0 +1,696 @@ +// 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 new file mode 100644 index 0000000..98e1952 --- /dev/null +++ b/src/core/expert_source.cpp @@ -0,0 +1,2985 @@ +// 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/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 { + +bool host_available_memory(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 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; + 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; +} + +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); + 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 * H, H, d.act_multi[(size_t) t]); + else if (native) + native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * H, d.nact_multi.data() + (size_t) t * kNativeActBytes); + else + act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]); + } + } + 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 * H; + 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) H * 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 + auto worker = [&]() { + // #230: `fread` on a `FILE*`, as load_experts_ranges (#89): MSVC's `std::ifstream::read` splits a request + // into 4095-byte freads, which took this path to 0.02 GiB/s on a Windows install without experts.bin. + // The guard closes the handle on every return. + struct Closer { + FILE* f = nullptr; + ~Closer() { if (f != nullptr) std::fclose(f); } + } 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.f != nullptr) std::fclose(file.f); + file.f = std::fopen(name.c_str(), "rb"); + if (file.f == nullptr) { bad = true; return; } + open_name = name; + } + FILE* const f = file.f; + 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) { + const uint64_t n = std::min(chunk, total - done); + // 64-bit seek: a shard is tens of GB + if (STRATA_FSEEK64(f, src + done) != 0) { bad = true; return; } + if (std::fread(buf.data(), 1, (size_t) n, f) != (size_t) n) { bad = true; 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]); + } + } + } + } + }; + 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 = "short read or unreadable shard while reading the experts from the GGUF"; + 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 new file mode 100644 index 0000000..2e9c7e7 --- /dev/null +++ b/src/core/graph.cpp @@ -0,0 +1,146 @@ +// 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 new file mode 100644 index 0000000..33450f7 --- /dev/null +++ b/src/core/layer.cpp @@ -0,0 +1,1349 @@ + +// 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/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 * sigmoid(z). SIGMOID, not SiLU. +// qkv's native quantize of `mixed` is still in the shared q8_1 scratch: nothing native ran in between. +if (!gemv_quantized(*w_gate, p_gate, f_gate, b.x_q8_0, b.x_q8k, b.z, g.n_embd, g.ssm_value_dim, v.name("attn_gate.weight"), stream, err, mixed, + w_qkv->native_data != nullptr && w_gate->native_data != nullptr)) return false; +try { + if (fused_gdn) fused_gdn_step_norm(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.z, ssm_norm, RMS_EPS, b.y, + (int) g.ssm_k_heads, (int) g.ssm_v_heads, stream); + else if (native_gdn_enabled()) native_gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream); + else gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream); +} catch (const std::exception& error) { err = v.name("gdn_out_norm") + ": " + error.what(); return false; } +st_end(layer, 14, stream); +// ---- 8. out = ssm_out @ y, whose activation is whatever THIS layer's `ssm_out` asks for +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(std::string& why) { + // Plan v0.3 P6: the verify window reproduces exactly this configuration's per-token arithmetic. + if (!native_bf16_projections) why = "the native BF16 projections are off"; + else if (!g_fused_gr) why = "the fused hyper-connection read is off"; + else if (!g_fused_gdn || !strata::kernels::native_gdn_enabled()) why = "the fused native GDN kernels are off"; + else if (!g_fast_attn || native_flash_attn_short) why = "the split-K decode attention is off"; + else if (!g_fast_select) why = "the block top-k selection is off"; + else if (!strata::kernels::native_qsa_indexer_enabled()) why = "the native QSA indexer is off"; + else return true; + return false; +} +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. +QsaShapes qsa_shapes(const ModelGeometry& g) { QsaShapes s = strata::kernels::qsa_real_shapes(); s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; s.idx_dim = g.idx_key_dim; return s;} +uint64_t align_up16(uint64_t n) { return (n + 15) & ~15ull; } +/// One cursor over an arena, so every region is 16-byte aligned without a list of hand-added offsets. +struct Cursor { uint8_t* p; uint64_t used = 0; template 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 = max_cells / s.idx_block + 2; + if (g_kv_resident <= 0 || ring_cells < 0) return p; // ring_cells < 0: always fully resident + // A/B only: STRATA_KV_RING_OFF keeps the drafter fully resident, STRATA_KV_MAIN_OFF the main layers + static const bool ring_off = std::getenv("STRATA_KV_RING_OFF") != nullptr; + 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; } +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_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_width(strata::kernels::kTopkMaxCells, s); uint64_t n = 0; n += (uint64_t) q8k_bytes(g.n_embd); n += (uint64_t) (g.n_embd / 32) * 34; +// block_q8_0 +n += (uint64_t) g.n_embd * 2; n += (uint64_t) g.n_head * 2 * g.head_dim * 4; n += (uint64_t) g.n_head * g.head_dim * 4; n += (uint64_t) g.n_head_kv * g.head_dim * 4 * 2; n += (uint64_t) g.idx_key_dim * 4; n += (uint64_t) g.idx_q_heads * g.idx_key_dim * 4; 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_width(strata::kernels::kTopkMaxCells, s); Cursor c{(uint8_t*) base}; b.x_q8k = c.take_bytes(q8k_bytes(g.n_embd)); b.x_q8_0 = c.take_bytes((uint64_t) (g.n_embd / 32) * 34); b.x_bf16 = c.take((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); 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_width(kTopkMaxCells, s); +const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, int cols) { + try { + if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream); + 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 = !w_idxk ? "indexer.k_proj.weight" : !w_attnq ? "attn_q.weight" : !w_attnk ? "attn_k.weight" : !w_attnv ? "attn_v.weight" : !w_attno ? "attn_output.weight" : !w_idxq ? "indexer.q_proj.weight" : !w_qn ? "attn_q_norm.weight" : !w_kn ? "attn_k_norm.weight" : !w_iqn ? "indexer.q_norm.weight" : !w_ikn ? "indexer.k_norm.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; } if (pos < 0 || pos >= st.max_cells) { err = "qsa_layer: pos " + std::to_string(pos) + " is outside the state's 0.." + std::to_string(st.max_cells - 1); return false; } +// THE TWO BF16 PROJECTIONS: the arena holds them re-rounded to 2 B/elem, which is what `bf16_gemv` wants. +// Reading one as f32 would walk 2x its length inside the arena without faulting. +if (w_idxk->kind != WeightKind::Bf16InF32 || w_idxq->kind != WeightKind::Bf16InF32) { err = v.name("indexer.*_proj.weight") + " must be engine form 1 (bf16); they are " + std::to_string((int) w_idxk->kind) + " and " + std::to_string((int) w_idxq->kind); return false; } +// ---- 1. the three activation formats, once each +if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) { + quantize_q8_K(x, b.x_q8k, g.n_embd, stream); + quantize_q8_0(x, b.x_q8_0, g.n_embd, stream); + } + if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); +// ---- 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 +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); } { 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 +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 (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); + } + 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) { + 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); +} +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) { + // ================================ 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) { 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 new file mode 100644 index 0000000..6d1b970 --- /dev/null +++ b/src/core/layout.cpp @@ -0,0 +1,173 @@ +// src/core/layout.cpp - the shape checks. See the header for why this exists. +#include "strata/core/layout.hpp" + +#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; + 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}, + {"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 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 new file mode 100644 index 0000000..0885b76 --- /dev/null +++ b/src/core/load_main.cpp @@ -0,0 +1,122 @@ +// 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 new file mode 100644 index 0000000..e9953e3 --- /dev/null +++ b/src/core/mtp.cpp @@ -0,0 +1,993 @@ +// src/core/mtp.cpp - see include/strata/core/mtp.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/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; +} + +strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; + s.n_head_kv = g.n_head_kv; + s.head_dim = g.head_dim; + s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + return s; +} + +// 64-bit seek/tell on a `FILE*`: `fseek`/`ftell` take a 32-bit `long` on Windows and would wrap past 2 GiB. +#if defined(_WIN32) +#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 + +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; +} + +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; } + 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(); + } + // ---- the 512 routed experts, one blob each + { + const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB; + // Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under + // MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes. + FILE* f = std::fopen((rt_dir + "/experts.bin").c_str(), "rb"); + 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 512 experts 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; + } + 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) (NH * HD), 8)); + 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(strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff)); + sh_scratch_ = (float*) b.take(strata::kernels::shared_expert_scratch_bytes(g.n_ff)); + 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, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n", + (double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0, + (double) tensors_.back().off / 1048576.0, files_s, + files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) / + 1048576.0 / files_s : 0.0); + return true; +} + +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) { + 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; +} + +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 new file mode 100644 index 0000000..e0609fd --- /dev/null +++ b/src/core/native_dense.cpp @@ -0,0 +1,210 @@ +#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 new file mode 100644 index 0000000..acb4f81 --- /dev/null +++ b/src/core/native_head.cpp @@ -0,0 +1,198 @@ +#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 new file mode 100644 index 0000000..f5981c1 --- /dev/null +++ b/src/core/overlap_main.cpp @@ -0,0 +1,169 @@ +// 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 new file mode 100644 index 0000000..bf6284a --- /dev/null +++ b/src/core/peer_experts.cpp @@ -0,0 +1,325 @@ +// 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 new file mode 100644 index 0000000..fbc3b3c --- /dev/null +++ b/src/core/pinned.cu @@ -0,0 +1,725 @@ +// 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 new file mode 100644 index 0000000..c663f1a --- /dev/null +++ b/src/core/pinned_shared_test.cpp @@ -0,0 +1,61 @@ +// 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 new file mode 100644 index 0000000..229781c --- /dev/null +++ b/src/core/remote_expert_opt.cu @@ -0,0 +1,194 @@ +#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 new file mode 100644 index 0000000..1b6969e --- /dev/null +++ b/src/core/remote_experts.cpp @@ -0,0 +1,341 @@ +#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 new file mode 100644 index 0000000..40a44bd --- /dev/null +++ b/src/core/session.cpp @@ -0,0 +1,970 @@ +// src/core/session.cpp - one token through all 48 layers. See the header for why the graphs are per-layer. +#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() { + return (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof(float); +} + +uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo, int64_t layer_hi) { + 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(); // the PLE's NG_HIST normalized history rows + 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 = (float*) take(ple_hist_bytes()); + 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. + cudaMemsetAsync(s.ple_hist, 0, (size_t) ple_hist_bytes(), cs); + s.ple_prev[0] = -1; + s.ple_prev[1] = -1; + s.ple_token = -1; +} + +/// 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) { + strata::kernels::QsaShapes sh = strata::kernels::qsa_real_shapes(); + sh.n_head = g.n_head; + sh.n_head_kv = g.n_head_kv; + sh.head_dim = g.head_dim; + sh.idx_n_head = g.idx_q_heads; + sh.idx_dim = g.idx_key_dim; + for (int64_t j = 0; j < s.qsa_alloc; ++j) { + QsaState& q = s.qsa_states[s.qsa_ord0 + j]; + qsa_step_fill(q.host_step, pos, sh); + 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 new file mode 100644 index 0000000..dd5362b --- /dev/null +++ b/src/core/verify.cpp @@ -0,0 +1,2158 @@ +// src/core/verify.cpp - see include/strata/core/verify.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; +} + +strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; + s.n_head_kv = g.n_head_kv; + s.head_dim = g.head_dim; + s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + return s; +} + +const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) { + const WeightRef* r = v.get(suffix); + 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 + +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(why)) { + err = "verify: " + why + " (the verify window reproduces the default native decode path)"; + return false; + } + if (!strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr) || ss.k != 10 || g.ssm_state_size != 128 || + g.ssm_d_conv != 4) { + err = "verify: geometry differs from the artifact's"; + 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_width(strata::kernels::kTopkMaxCells, s); + max_blocks_ = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; + 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); + 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(); + auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; }; + const int G = (split_ && T >= 2 && !batch_rec_) ? 2 : 1; // a batch window is one group + static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); + auto stamp = [&](int64_t l, int i, int grp) { + 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]; + 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) + bool pending = l > 0 && !cvec().covers(l - 1); + if (l == 1 && ple_on) { + if (grp == 0) { + if (all_resident_) wait_flag_ge(m_flag_, 1, cs); + 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))); + }; + gr_read_group(0, pending, inj2_, inj_); + stamp(l, 1, grp); + float* xm = mixed_ + tb * N; + 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, y_ + (size_t) t * ZV, + (int) HK, (int) HV, 1, nullptr, cs, 0); + } + } else + gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK, + (int) HV, te, nullptr, cs, tb); + 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]; + const WeightRef *wik = need(v, "indexer.k_proj.weight", err), *wq = need(v, "attn_q.weight", err), + *wk = need(v, "attn_k.weight", err), *wv = need(v, "attn_v.weight", err), + *wo = need(v, "attn_output.weight", err), *wiq = need(v, "indexer.q_proj.weight", err), + *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err), + *wiqn = need(v, "indexer.q_norm.weight", err), *wikn = need(v, "indexer.k_norm.weight", err); + if (!wik || !wq || !wk || !wv || !wo || !wiq || !wqn || !wkn || !wiqn || !wikn) return false; + if (!native_of(wq, v.name("attn_q.weight"), err) || !native_of(wk, v.name("attn_k.weight"), err) || + !native_of(wv, v.name("attn_v.weight"), err) || !native_of(wo, v.name("attn_output.weight"), err)) + return false; + 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 (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 (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); + } + 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); // = + 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); // = + } + 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 (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); + gr_read_group(1, true, inj_, inj2_); + static const bool sh_stream_env = [] { + const char* e = std::getenv("STRATA_SH_STREAM"); + return !e || e[0] != '0'; + }(); + 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 && (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 (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 = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"), + *hu = wt.find("output_hc_up.weight"); + if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; } + if (fuse_head_gr) { + FusedGrArgs fa[kFusedGrMaxT]; + for (int t = 0; t < T; ++t) { + FusedGrArgs& a = fa[t]; + 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, y_dummy_, + (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_, (int) MT); + ++gdn_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, y_dummy_ + (size_t) t * ZV, (int) g.ssm_k_heads, + (int) HV, 1, keep, cs_); + } + ++gdn_index; + } 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 new file mode 100644 index 0000000..8b42f84 --- /dev/null +++ b/src/core/weights.cpp @@ -0,0 +1,479 @@ +// 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 new file mode 100644 index 0000000..f996463 --- /dev/null +++ b/src/kernels/bf16_bits_test.cpp @@ -0,0 +1,80 @@ +// 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 new file mode 100644 index 0000000..435c336 --- /dev/null +++ b/src/kernels/bf16_gemv_parity.cpp @@ -0,0 +1,148 @@ +// 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 new file mode 100644 index 0000000..045e3d5 --- /dev/null +++ b/src/kernels/cpu/expert.cpp @@ -0,0 +1,683 @@ +// 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 new file mode 100644 index 0000000..8b6e3bc --- /dev/null +++ b/src/kernels/cpu/expert_layout.cpp @@ -0,0 +1,341 @@ +// 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, 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) { + 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, H, FF, f, err)) return false; + if (f.bytes != blob) { + err = "native_experts.txt: layer " + std::to_string(l) + " blob is " + std::to_string(blob) + + " B but its formats make " + std::to_string(f.bytes); + 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 new file mode 100644 index 0000000..446c95f --- /dev/null +++ b/src/kernels/cpu/expert_multi_test.cpp @@ -0,0 +1,87 @@ +// 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 new file mode 100644 index 0000000..39f24a1 --- /dev/null +++ b/src/kernels/cpu/expert_parity.cpp @@ -0,0 +1,184 @@ +// 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 new file mode 100644 index 0000000..bb8849b --- /dev/null +++ b/src/kernels/cpu/iq_avx2.cpp @@ -0,0 +1,493 @@ +// 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 new file mode 100644 index 0000000..26d2c5a --- /dev/null +++ b/src/kernels/cpu/iq_avx512.cpp @@ -0,0 +1,273 @@ +// 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 new file mode 100644 index 0000000..fbdf73f --- /dev/null +++ b/src/kernels/cpu/kq_avx1.cpp @@ -0,0 +1,71 @@ +// 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 new file mode 100644 index 0000000..a347311 --- /dev/null +++ b/src/kernels/cpu/kq_avx2.cpp @@ -0,0 +1,265 @@ +// 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 new file mode 100644 index 0000000..0dc5d3a --- /dev/null +++ b/src/kernels/cpu/native_expert.cpp @@ -0,0 +1,166 @@ +// 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 % 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 new file mode 100644 index 0000000..c644629 --- /dev/null +++ b/src/kernels/cpu/pool.cpp @@ -0,0 +1,779 @@ +// 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 + const int per = mode_ == 5 ? FF : H; + const int64_t g0 = mrows_ * (int64_t) i / mtasks_, g1 = mrows_ * (int64_t) (i + 1) / mtasks_; + for (int64_t r = g0; r < g1;) { + const int e = (int) (r / per), r0 = (int) (r % per); + 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 * FF; + const auto a = std::chrono::steady_clock::now(); + run_phase(5, mtasks_); + const auto b = std::chrono::steady_clock::now(); + for (int e = 0; e < nb; ++e) + for (int t = 0; t < mjobs_[e].nt; ++t) + if (q2_native_kernels(f.d_type)) act_quant_any(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]); + else native_quant_h(f, split_multi_[(size_t) e].ff[t], split_multi_[(size_t) e].hq[t]); + const auto c = std::chrono::steady_clock::now(); + mrows_ = (int64_t) nb * H; + 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 new file mode 100644 index 0000000..0791ac5 --- /dev/null +++ b/src/kernels/cpu/pool_affinity_linux.hpp @@ -0,0 +1,69 @@ +#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 new file mode 100644 index 0000000..6b5752a --- /dev/null +++ b/src/kernels/cpu/pool_affinity_linux_test.cpp @@ -0,0 +1,290 @@ +#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 new file mode 100644 index 0000000..052ae59 --- /dev/null +++ b/src/kernels/cpu/pool_affinity_test.cpp @@ -0,0 +1,148 @@ +#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 new file mode 100644 index 0000000..6f0e402 --- /dev/null +++ b/src/kernels/cpu/pool_affinity_win.hpp @@ -0,0 +1,64 @@ +#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 new file mode 100644 index 0000000..2c9fca5 --- /dev/null +++ b/src/kernels/cpu/pool_stress.cpp @@ -0,0 +1,99 @@ +// 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 new file mode 100644 index 0000000..dbc7288 --- /dev/null +++ b/src/kernels/cpu/pool_test.cpp @@ -0,0 +1,224 @@ +// 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 new file mode 100644 index 0000000..8e276a5 --- /dev/null +++ b/src/kernels/cpu/q2_avx2.cpp @@ -0,0 +1,130 @@ +// 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 new file mode 100644 index 0000000..bd1341b --- /dev/null +++ b/src/kernels/cpu/router_dot_parity.cpp @@ -0,0 +1,70 @@ +// 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 new file mode 100644 index 0000000..04473ad --- /dev/null +++ b/src/kernels/cuda/bf16_gemv.cu @@ -0,0 +1,141 @@ +// 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 new file mode 100644 index 0000000..6682932 --- /dev/null +++ b/src/kernels/cuda/cvec.cu @@ -0,0 +1,166 @@ +// 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 new file mode 100644 index 0000000..32601d6 --- /dev/null +++ b/src/kernels/cuda/dequant_bf16.cu @@ -0,0 +1,261 @@ +// 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 new file mode 100644 index 0000000..c141b93 --- /dev/null +++ b/src/kernels/cuda/dequant_s2.cu @@ -0,0 +1,51 @@ +// 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 new file mode 100644 index 0000000..4817763 --- /dev/null +++ b/src/kernels/cuda/elementwise.cu @@ -0,0 +1,397 @@ +// 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 new file mode 100644 index 0000000..ef2e778 --- /dev/null +++ b/src/kernels/cuda/fused_gdn.cu @@ -0,0 +1,166 @@ +// 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) { + __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]; + y[head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + } +} + +__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, 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); + 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 new file mode 100644 index 0000000..71012ff --- /dev/null +++ b/src/kernels/cuda/fused_gr.cu @@ -0,0 +1,1371 @@ +// 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 new file mode 100644 index 0000000..aad247a --- /dev/null +++ b/src/kernels/cuda/gdn.cu @@ -0,0 +1,248 @@ +// 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 * sigmoid(z), one warp per head, norm over that head's S values. +__global__ void gdn_out_norm_kernel(const float* __restrict__ o, const float* __restrict__ z, + const float* __restrict__ ssm_norm, float* __restrict__ y, int S, + float eps) { + 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) + py[i] = po[i] * inv * ssm_norm[i] * sigmoid_f(pz[i]); +} + +} // 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, 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); + 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 new file mode 100644 index 0000000..7eea7f4 --- /dev/null +++ b/src/kernels/cuda/gr.cu @@ -0,0 +1,432 @@ +// 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 new file mode 100644 index 0000000..5c552fa --- /dev/null +++ b/src/kernels/cuda/iq_kernels.cu @@ -0,0 +1,2578 @@ +// 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. +constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2; + +__device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq(const int* __restrict__ v, const int* __restrict__ u, + const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, + 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); +} +// 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<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. +#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(8) +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(8) +#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(8) + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + 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, 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); + } +} +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 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 == 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 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 new file mode 100644 index 0000000..b7de61f --- /dev/null +++ b/src/kernels/cuda/kv_q4.cu @@ -0,0 +1,231 @@ +// 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 new file mode 100644 index 0000000..fb2ccec --- /dev/null +++ b/src/kernels/cuda/kv_q8.cu @@ -0,0 +1,127 @@ +// 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 new file mode 100644 index 0000000..914a836 --- /dev/null +++ b/src/kernels/cuda/kv_stream.cu @@ -0,0 +1,276 @@ +// 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 new file mode 100644 index 0000000..fdbdc94 --- /dev/null +++ b/src/kernels/cuda/native_bf16.cu @@ -0,0 +1,199 @@ +#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 new file mode 100644 index 0000000..5a4f36d --- /dev/null +++ b/src/kernels/cuda/native_flash_attn.cu @@ -0,0 +1,212 @@ +// 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 new file mode 100644 index 0000000..6661d50 --- /dev/null +++ b/src/kernels/cuda/native_gdn.cu @@ -0,0 +1,122 @@ +// 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 new file mode 100644 index 0000000..86b1045 --- /dev/null +++ b/src/kernels/cuda/native_gdn_preprocess.cu @@ -0,0 +1,199 @@ +// 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) { + 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. + const float weighted = __fmul_rn(__fmul_rn(scale, value), gamma[col]); + output[offset + col] = weighted * sigmoid(z[offset + col]); + } +} + +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, 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); + check_launch(); +} +} // namespace strata::kernels diff --git a/src/kernels/cuda/native_gr_norm.cu b/src/kernels/cuda/native_gr_norm.cu new file mode 100644 index 0000000..5abe013 --- /dev/null +++ b/src/kernels/cuda/native_gr_norm.cu @@ -0,0 +1,102 @@ +// 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 new file mode 100644 index 0000000..8616e33 --- /dev/null +++ b/src/kernels/cuda/native_gr_postops.cu @@ -0,0 +1,115 @@ +// 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 new file mode 100644 index 0000000..e0d11bf --- /dev/null +++ b/src/kernels/cuda/native_mmvq.cu @@ -0,0 +1,1619 @@ +// 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 new file mode 100644 index 0000000..7f1f91c --- /dev/null +++ b/src/kernels/cuda/native_moe.cu @@ -0,0 +1,86 @@ +// 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 new file mode 100644 index 0000000..922ae0a --- /dev/null +++ b/src/kernels/cuda/native_ple_postops.cu @@ -0,0 +1,221 @@ +// 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 new file mode 100644 index 0000000..32e2511 --- /dev/null +++ b/src/kernels/cuda/native_qsa.cu @@ -0,0 +1,127 @@ +// 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 new file mode 100644 index 0000000..8147c70 --- /dev/null +++ b/src/kernels/cuda/native_qsa_indexer.cu @@ -0,0 +1,290 @@ +// 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 new file mode 100644 index 0000000..cdcfead --- /dev/null +++ b/src/kernels/cuda/native_qsa_score.cu @@ -0,0 +1,213 @@ +// 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 new file mode 100644 index 0000000..57cbe79 --- /dev/null +++ b/src/kernels/cuda/native_rope.cu @@ -0,0 +1,147 @@ +// 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 new file mode 100644 index 0000000..3f8b69c --- /dev/null +++ b/src/kernels/cuda/native_router.cu @@ -0,0 +1,127 @@ +// 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 new file mode 100644 index 0000000..984512b --- /dev/null +++ b/src/kernels/cuda/ple.cu @@ -0,0 +1,386 @@ +// 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 new file mode 100644 index 0000000..a635e81 --- /dev/null +++ b/src/kernels/cuda/qsa.cu @@ -0,0 +1,821 @@ +// 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) { + if (s.n_head <= 0 || s.n_head_kv <= 0 || s.head_dim <= 0 || s.idx_dim <= 0 || s.idx_n_head <= 0 || + s.idx_block < 2 || s.page_size < 1) { + std::fprintf(stderr, "qsa: %s: geometry is not set up\n", who); + std::exit(1); + } + if (s.n_head % s.n_head_kv != 0) { + std::fprintf(stderr, "qsa: %s: n_head %lld is not a multiple of n_head_kv %lld\n", who, + (long long) s.n_head, (long long) s.n_head_kv); + std::exit(1); + } + if (s.head_dim % 4 != 0) { + std::fprintf(stderr, "qsa: %s: head_dim %lld must be a multiple of 4 (the gather copies uint2)\n", who, + (long long) s.head_dim); + std::exit(1); + } + if (s.n_rot <= 0 || s.n_rot % 2 != 0 || s.n_rot > s.head_dim || s.n_rot > s.idx_dim) { + std::fprintf(stderr, "qsa: %s: n_rot %lld must be even and <= head_dim %lld and idx_dim %lld\n", who, + (long long) s.n_rot, (long long) s.head_dim, (long long) s.idx_dim); + std::exit(1); + } + if (s.idx_n_head > 32) { + std::fprintf(stderr, "qsa: %s: idx_n_head %lld > 32 (one warp per indexer head)\n", who, + (long long) s.idx_n_head); + std::exit(1); + } +} + +__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(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(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 ================= + +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(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(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(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 new file mode 100644 index 0000000..f487c4f --- /dev/null +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -0,0 +1,537 @@ +// 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 + +namespace strata::kernels { +namespace { + +constexpr int HD = 256; // head_dim +constexpr int G = 12; // query heads per KV head (24 / 2) +constexpr int CHUNK = 64; // cells per block +constexpr int THREADS = 256; +constexpr int WARPS = THREADS / 32; + +__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; + ids += (size_t) blockIdx.z * (size_t) cap; + step += (size_t) blockIdx.z * kStepCount; + part_acc += (size_t) blockIdx.z * (size_t) scratch_stride; + part_m += (size_t) blockIdx.z * (size_t) scratch_stride; + part_l += (size_t) blockIdx.z * (size_t) scratch_stride; + __shared__ __align__(16) float sq[G][HD]; // 12 KB: 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) + 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[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 chunk max and exp-sum: warp w handles heads w and w+8. + for (int h = warp; h < G; h += WARPS) { + const float a = sp[h][lane], b = sp[h][lane + 32]; + const float m = warp_max(fmaxf(a, b)); + const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f; + const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f; + sp[h][lane] = ea; + sp[h][lane + 32] = eb; + const float l = warp_sum(ea + eb); + if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; } + } + __syncthreads(); + // values: thread t owns dimension t for all 12 heads. + float acc[G]; +#pragma unroll + for (int h = 0; h < G; ++h) acc[h] = 0.0f; + for (int c = 0; c < n_here; ++c) { + if (srow[c] < 0) continue; // masked above, weight 0 + float v; + if constexpr (KV_MODE == 0) { + v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t])); + } else if constexpr (KV_MODE == 1) { + const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP])); + v = (float) p.v_q[srow[c] * HD + t] * sc; + } else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back + constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0); + const int b = t / QK4_0; + const int rem = t % QK4_0; + const block_q4_0* blk = reinterpret_cast(p.v_q4 + srow[c] * bytes_per_head) + b; + const float d = __half2float(__ushort_as_half(blk->d)); + const int j = rem < 16 ? rem : (rem - 16); + const uint8_t byte = blk->qs[j]; + const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8); + v = (float) nibble * d; + } +#pragma unroll + for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]); + } +#pragma unroll + for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h]; +} + +// 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) { + // batched form: query blockIdx.z, with its own q row, selection, step and scratch + q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; + ids += (size_t) blockIdx.z * (size_t) cap; + step += (size_t) blockIdx.z * kStepCount; + part_acc += (size_t) blockIdx.z * (size_t) scratch_stride; + part_m += (size_t) blockIdx.z * (size_t) scratch_stride; + part_l += (size_t) blockIdx.z * (size_t) scratch_stride; + __shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads (dead once the scores are done) + __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[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 12 heads. + float acc[G]; +#pragma unroll + for (int h = 0; h < G; ++h) acc[h] = 0.0f; + // One cell's 12 weights (three broadcast float4 loads) into the 12 accumulators; the cells are folded in + // ascending order, so the sums are the plain loop's, bit for bit. + const auto fold = [&](int c, float v) { + const float4* w4 = reinterpret_cast(spt[c]); + const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2]; + acc[0] = fmaf(w0.x, v, acc[0]); acc[1] = fmaf(w0.y, v, acc[1]); + acc[2] = fmaf(w0.z, v, acc[2]); acc[3] = fmaf(w0.w, v, acc[3]); + acc[4] = fmaf(w1.x, v, acc[4]); acc[5] = fmaf(w1.y, v, acc[5]); + acc[6] = fmaf(w1.z, v, acc[6]); acc[7] = fmaf(w1.w, v, acc[7]); + acc[8] = fmaf(w2.x, v, acc[8]); acc[9] = fmaf(w2.y, v, acc[9]); + acc[10] = fmaf(w2.z, v, acc[10]); acc[11] = fmaf(w2.w, v, acc[11]); + }; + int c = 0; + // four cells at a time with their V loads issued together (the loop was one dependent load chain per cell); + // 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 + +__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) (pre75_attn() ? attn_chunk_kernel_pre75 : attn_chunk_kernel) +#else +#define STRATA_ATTN_CHUNK(M) attn_chunk_kernel +#endif + +} // namespace + +void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) { + if (n_q <= 0) return; + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps || + !pools.page_table || n_q > 65535) { + std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n"); + std::exit(1); + } + const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + // per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; + float* part_l = part_m + (size_t) n_chunks * s.n_head; + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); + cudaStream_t st = (cudaStream_t) stream; + if (kv_mode == 3) + STRATA_ATTN_CHUNK(3)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + else if (kv_mode == 2) + STRATA_ATTN_CHUNK(2)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + else if (kv_mode == 1) + STRATA_ATTN_CHUNK(1)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + else + STRATA_ATTN_CHUNK(0)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, + attn, stride); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_decode_attn_batch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) { + const int64_t chunks = (cap + CHUNK - 1) / CHUNK; + return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64; +} + +void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) { + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !step || + !pools.page_table) { + std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n"); + std::exit(1); + } + const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); + if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) + : (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale) + : (!pools.k_pool || !pools.v_pool)))) { + std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n"); + std::exit(1); + } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; + float* part_l = part_m + (size_t) n_chunks * s.n_head; + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv); + cudaStream_t st = (cudaStream_t) stream; + if (kv_mode == 3) + STRATA_ATTN_CHUNK(3)<<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, 0, 0); + else if (kv_mode == 2) + STRATA_ATTN_CHUNK(2)<<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, 0, 0); + else if (kv_mode == 1) + STRATA_ATTN_CHUNK(1)<<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, 0, 0); + else + STRATA_ATTN_CHUNK(0)<<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, 0, 0); + attn_merge_kernel<<<(unsigned) s.n_head, HD, 0, st>>>(part_acc, part_m, part_l, n_chunks, attn); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_decode_attn: %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 new file mode 100644 index 0000000..9b48192 --- /dev/null +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -0,0 +1,1479 @@ +// 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 +constexpr int G = 12; // query heads per KV head +#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; + 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[c0 + t]; + const long long page = (long long) p.page_table[cell / page_size]; + r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + 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; + *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 +} + +__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; + 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 ? __ldg(ids + c) : -1; }; + auto row_of = [&](int cell) -> long long { + if (cell < 0) return -1; + const long long page = (long long) __ldg(p.page_table + cell / page_size); + return (page * n_kv_heads + kvh) * page_size + (cell % page_size); + }; + auto issue = [&](long long r, int st, float& ksr, float& vsr) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3; + const long long rr = __shfl_sync(0xffffffffu, r, cell); + const bool ok = rr >= 0; + const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0; + cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok); + cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok); + } + ksr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.k_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f; + vsr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.v_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f; + }; + float ksn, vsn; + issue(row_of(cell_of(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; + *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); + } +} + +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 + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_prompt_attn_batch: %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 + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_prompt_attn_batch: %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; + 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[c0 + t]; + const long long page = (long long) p.page_table[cell / page_size]; + r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + 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 + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_prompt_attn_batch (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; +} + +__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; + 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 = __ldg(ids + c0 + lane); + const long long page = (long long) __ldg(p.page_table + cell / page_size); + if (page >= 0) myrow = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + // 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; +} + +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 + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_prompt_attn_batch (wmma): %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return true; +} +#endif + +} // 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; + } +#if defined(__HIPCC__) + // the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV + // matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel + (void) turing; (void) volta; + if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr && + pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv && + cap > 0 && ids && steps && pools.page_table && hip_wmma_usable()) + return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream); + return false; +#endif + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || !pools.page_table) + return false; + cudaStream_t st = (cudaStream_t) stream; + if (pools.k_q4 != nullptr) { // Q4_0 K and V (--kv q4_0): mode 4. STRATA_PROMPT_ATTN_Q4=0: the old kernel (A/B) + static const bool q4_off = [] { + const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4"); + return v != nullptr && v[0] == '0'; + }(); + // sm_80+ only: on Turing mode 4 would run as pairs of m16n8k8 MMAs, which no parity run has checked yet + if (q4_off || turing || pools.v_q4 == nullptr) return false; + return launch<4>(q, pools, ids, steps, cap, s, attn, n_q, st); + } + if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 V + if (!pools.k_scale) return false; + if (volta) return launch70<3>(q, pools, ids, steps, cap, s, attn, n_q, st); + return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st); + } + if (pools.k_q != nullptr) { + if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false; + // STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control + // for how far the model amplifies an FP32-level change. Turing always takes it: v2's cp.async does not + // exist before sm_80. + static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr; + if (volta) return launch70<1>(q, pools, ids, steps, cap, s, attn, n_q, st); + if (v1 || turing) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st); + return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st); + } + if (!pools.k_pool || !pools.v_pool) return false; + if (volta) return launch70<0>(q, pools, ids, steps, cap, s, attn, n_q, st); + return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st); +} + +} // namespace strata::kernels diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu new file mode 100644 index 0000000..56222c5 --- /dev/null +++ b/src/kernels/cuda/qsa_select.cu @@ -0,0 +1,1237 @@ +// 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 new file mode 100644 index 0000000..ddd14df --- /dev/null +++ b/src/kernels/cuda/quantize_act.cu @@ -0,0 +1,313 @@ +// 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 new file mode 100644 index 0000000..807545e --- /dev/null +++ b/src/kernels/cuda/rope.cu @@ -0,0 +1,136 @@ +// 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 new file mode 100644 index 0000000..720cec6 --- /dev/null +++ b/src/kernels/cuda/router_top10.cu @@ -0,0 +1,497 @@ +// 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 new file mode 100644 index 0000000..925ac3a --- /dev/null +++ b/src/kernels/cuda/s2_expert_grouped.cu @@ -0,0 +1,1190 @@ +// 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 new file mode 100644 index 0000000..c1ff5cf --- /dev/null +++ b/src/kernels/cuda/s2_gemv.cu @@ -0,0 +1,63 @@ +// 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 new file mode 100644 index 0000000..c83bd17 --- /dev/null +++ b/src/kernels/cuda/s2_gemv_fast.cu @@ -0,0 +1,153 @@ +// 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 new file mode 100644 index 0000000..386f882 --- /dev/null +++ b/src/kernels/cuda/s2_gemv_q8.cu @@ -0,0 +1,96 @@ +// 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 new file mode 100644 index 0000000..7cb7cb4 --- /dev/null +++ b/src/kernels/cuda/s2_gemv_quads.cu @@ -0,0 +1,93 @@ +// 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 new file mode 100644 index 0000000..d0db178 --- /dev/null +++ b/src/kernels/cuda/s_gemv.cu @@ -0,0 +1,694 @@ +// 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 new file mode 100644 index 0000000..8982a28 --- /dev/null +++ b/src/kernels/cuda/sampler.cu @@ -0,0 +1,1081 @@ +// 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 new file mode 100644 index 0000000..28bb7ed --- /dev/null +++ b/src/kernels/cuda/shared_expert.cu @@ -0,0 +1,384 @@ +// 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 new file mode 100644 index 0000000..f7c4843 --- /dev/null +++ b/src/kernels/cuda/verify_kernels.cu @@ -0,0 +1,682 @@ +// 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) { + __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]; + y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + } + } + if (n_keep != nullptr && n > 0) { +#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, 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); + } + 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 new file mode 100644 index 0000000..6176c63 --- /dev/null +++ b/src/kernels/cvec_parity.cpp @@ -0,0 +1,223 @@ +// 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 new file mode 100644 index 0000000..665fe6f --- /dev/null +++ b/src/kernels/decode_cluster_parity.cpp @@ -0,0 +1,424 @@ +// 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 new file mode 100644 index 0000000..80d3d53 --- /dev/null +++ b/src/kernels/dequant_bf16_test.cpp @@ -0,0 +1,108 @@ +// 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 new file mode 100644 index 0000000..58e3970 --- /dev/null +++ b/src/kernels/dequant_s2_parity.cpp @@ -0,0 +1,143 @@ +// 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 new file mode 100644 index 0000000..9a8fc3f --- /dev/null +++ b/src/kernels/elementwise_parity.cpp @@ -0,0 +1,475 @@ +// 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 new file mode 100644 index 0000000..b7b8452 --- /dev/null +++ b/src/kernels/fused_gr_bench.cpp @@ -0,0 +1,116 @@ +// 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 new file mode 100644 index 0000000..8d6a399 --- /dev/null +++ b/src/kernels/gdn_parity.cpp @@ -0,0 +1,397 @@ +// src/kernels/gdn_parity.cpp - P2.S2's test for the GDN recurrence, the conv and the two norms. +// +// `ref/gdn.py` carries eleven PROPERTY checks, several of which exist because a rival reading of the SOURCE +// produces well-formed output. The four that the kernels here can be wrong about are re-pinned below, each +// 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. +// +// 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. +#include "strata/kernels/gdn.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); + } +} + +float sigmoid_f(float x) { return 1.0f / (1.0f + std::exp(-x)); } + +/// 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. +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; +} + +/// `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); +} + +} // 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; } + } + + const int S = 128, h_k = 16, h_v = 48; // the artifact's real geometry + std::mt19937 rng(2024); + std::normal_distribution gauss(0.0f, 1.0f); + int bad = 0; + + // ================= 1. the recurrence ================= + { + // The state encodes its own coordinates, so a layout mix-up cannot pass: reading (i,j,h) where the + // buffer holds (i,h,j) gives a DIFFERENT number, not a wrong-but-plausible one. + std::vector 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); + for (auto& x : q) x = gauss(rng) * 0.1f; + for (auto& x : k) x = gauss(rng) * 0.1f; + for (auto& x : v) x = gauss(rng); + for (auto& x : gate) x = -(2.0f + 4.0f * (float) (rng() % 100) / 100.0f); // dec in (0.0025, 0.135] + for (auto& x : beta) x = (float) (rng() % 100) / 100.0f; + + std::vector want_o; + std::vector st_mod = st_ref; + ref_step(st_mod, q, k, v, gate, beta, S, h_k, h_v, want_o, true, true); + + // the traps + { + std::vector a = st_ref; + std::vector oo; + ref_step(a, q, k, v, gate, beta, S, h_k, h_v, oo, false, true); + const double rel = rel_l1(want_o, oo); + std::printf(" %-42s %-4s (%.2f%% apart)\n", "modulo vs interleave head pairing", + rel > 0.05 ? "yes" : "*** NO ***", rel * 100); + if (!(rel > 0.05)) ++bad; + } + { + std::vector a = st_ref; + std::vector oo; + ref_step(a, q, k, v, gate, beta, S, h_k, h_v, oo, true, false); + const double rel = rel_l1(want_o, oo); + std::printf(" %-42s %-4s (%.2f%% apart)\n", "decay before vs after the update", + rel > 0.05 ? "yes" : "*** NO ***", rel * 100); + // The two readings differ by exactly `k (x) (beta * v * (1 - dec))`, so the fixture is only able + // to see the trap when `dec` is far from 1 and `beta` is far from 0. The first version used + // gate in [-0.99, 0] - dec in [0.37, 1] - and managed 3.25%, which is a threshold the wrong + // reading nearly clears. Deep decay is also the realistic regime: `ssm_a = -exp(A_log) < 0` and + // softplus is positive, so gate is comfortably negative in the real model. + if (!(rel > 0.05)) ++bad; + } + + // the kernel + float *d_st = nullptr, *d_q = nullptr, *d_k = nullptr, *d_v = nullptr, *d_g = nullptr, *d_b = nullptr, + *d_o = nullptr; + check(cudaMalloc(&d_st, st_dev.size() * 4), "st"); + check(cudaMalloc(&d_q, q.size() * 4), "q"); + check(cudaMalloc(&d_k, k.size() * 4), "k"); + check(cudaMalloc(&d_v, v.size() * 4), "v"); + check(cudaMalloc(&d_g, gate.size() * 4), "g"); + check(cudaMalloc(&d_b, beta.size() * 4), "b"); + check(cudaMalloc(&d_o, (size_t) h_v * S * 4), "o"); + check(cudaMemcpy(d_st, st_dev.data(), st_dev.size() * 4, cudaMemcpyHostToDevice), "cst"); + check(cudaMemcpy(d_q, q.data(), q.size() * 4, cudaMemcpyHostToDevice), "cq"); + check(cudaMemcpy(d_k, k.data(), k.size() * 4, cudaMemcpyHostToDevice), "ck"); + check(cudaMemcpy(d_v, v.data(), v.size() * 4, cudaMemcpyHostToDevice), "cv"); + check(cudaMemcpy(d_g, gate.data(), gate.size() * 4, cudaMemcpyHostToDevice), "cg"); + check(cudaMemcpy(d_b, beta.data(), beta.size() * 4, cudaMemcpyHostToDevice), "cb"); + + strata::kernels::GdnShapes sh{S, h_k, h_v}; + strata::kernels::gdn_step(d_st, d_q, d_k, d_v, d_g, d_b, d_o, sh, nullptr); + + std::vector got_o((size_t) h_v * S), got_st(st_dev.size()); + check(cudaMemcpy(got_o.data(), d_o, got_o.size() * 4, cudaMemcpyDeviceToHost), "cgo"); + check(cudaMemcpy(got_st.data(), d_st, got_st.size() * 4, cudaMemcpyDeviceToHost), "cgst"); + + // o, and the STATE read back through the declared layout + const double rel_o = rel_l1(want_o, got_o); + double rel_st = 0, mag_st = 0; + for (int i = 0; i < S; ++i) + for (int j = 0; j < S; ++j) + for (int h = 0; h < h_v; ++h) { + const size_t dev = (size_t) (i * h_v + h) * S + j; + const double w = st_mod[(size_t) (i * S + j) * h_v + h]; + rel_st += std::fabs(w - (double) got_st[dev]); + mag_st += std::fabs(w); + } + rel_st /= (mag_st > 1e-30 ? mag_st : 1e-30); + std::printf("\n %-42s rel %.3e\n", "o vs reference", rel_o); + std::printf(" %-42s rel %.3e\n", "state (read via (S,h_v,S)) vs reference", rel_st); + // The kernel accumulates in f32 and the reference in f64, and the state is a RECURRENCE over 128 + // terms, so 1e-5 is the arithmetic's floor here and not a structural allowance. + if (!(rel_o <= 1e-5)) { std::printf(" *** o over 1e-5 ***\n"); ++bad; } + if (!(rel_st <= 1e-5)) { std::printf(" *** state over 1e-5 ***\n"); ++bad; } + + // a zero state stays zero, and a zero gate/beta leaves the state untouched (the reference's + // PROPERTY 4 setup) - a cheap independent invariant that no layout can fake + { + std::vector zero(st_dev.size(), 0.0f), zg((size_t) h_v, 0.0f), zb((size_t) h_v, 0.0f); + check(cudaMemcpy(d_st, zero.data(), zero.size() * 4, cudaMemcpyHostToDevice), "z0"); + check(cudaMemcpy(d_g, zg.data(), zg.size() * 4, cudaMemcpyHostToDevice), "z1"); + check(cudaMemcpy(d_b, zb.data(), zb.size() * 4, cudaMemcpyHostToDevice), "z2"); + strata::kernels::gdn_step(d_st, d_q, d_k, d_v, d_g, d_b, d_o, sh, nullptr); + std::vector zz(zero.size()); + check(cudaMemcpy(zz.data(), d_st, zz.size() * 4, cudaMemcpyDeviceToHost), "z3"); + double nz = 0; + for (float x : zz) nz += std::fabs(x); + const bool ok = nz == 0.0; + std::printf(" %-42s %s\n", "gate=beta=0 from a zero state is a no-op", ok ? "yes" : "*** NO ***"); + if (!ok) ++bad; + } + + // ephemeral state: unchanged when the state is untouched but beta=1 — the delta rule writing k*d + cudaFree(d_st); cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_g); cudaFree(d_b); cudaFree(d_o); + } + + // ================= 2. the conv ================= + { + 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; + }; + auto to_ref_layout = [&](const std::vector& d) { + std::vector r(d.size()); + for (int i = 0; i < dc - 1; ++i) + for (int c = 0; c < C; ++c) r[(size_t) (i * C + c)] = d[(size_t) (c * (dc - 1) + i)]; + return r; + }; + + std::vector 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; + } + const double rel = rel_l1(want, out_bad); + std::printf("\n %-42s %-4s (%.1f%% apart)\n", "conv weight layout is observable", + rel > 0.05 ? "yes" : "*** NO ***", rel * 100); + if (!(rel > 0.05)) ++bad; + } + + float *d_cs = nullptr, *d_x = nullptr, *d_w = nullptr, *d_o = nullptr; + check(cudaMalloc(&d_cs, cs.size() * 4), "cs"); + check(cudaMalloc(&d_x, x.size() * 4), "cx"); + check(cudaMalloc(&d_w, kW.size() * 4), "cw"); + check(cudaMalloc(&d_o, (size_t) C * 4), "co"); + check(cudaMemcpy(d_cs, cs.data(), cs.size() * 4, cudaMemcpyHostToDevice), "ccs"); + check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "ccx"); + check(cudaMemcpy(d_w, kW.data(), kW.size() * 4, cudaMemcpyHostToDevice), "ccw"); + strata::kernels::gdn_conv_step(d_cs, d_x, d_w, d_o, C, dc, nullptr); + std::vector got((size_t) C), got_cs(cs.size()); + check(cudaMemcpy(got.data(), d_o, got.size() * 4, cudaMemcpyDeviceToHost), "cgo"); + check(cudaMemcpy(got_cs.data(), d_cs, got_cs.size() * 4, cudaMemcpyDeviceToHost), "cgs"); + const double rel_out = rel_l1(want, got), rel_cs = rel_l1(cs_want, got_cs); + std::printf(" %-42s rel %.3e\n", "conv out vs reference", rel_out); + std::printf(" %-42s rel %.3e\n", "conv state slide (mapped) vs reference", rel_cs); + if (!(rel_out <= 1e-6)) { std::printf(" *** conv out ***\n"); ++bad; } + if (!(rel_cs <= 1e-6)) { std::printf(" *** conv state ***\n"); ++bad; } + cudaFree(d_cs); cudaFree(d_x); cudaFree(d_w); cudaFree(d_o); + } + + // ================= 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; + } + const double rel_trap = rel_l1(x_ref, x_mean); + std::printf("\n %-42s %-4s (%.1f%% apart)\n", "eps on sum vs on mean is observable", + rel_trap > 0.05 ? "yes" : "*** NO ***", rel_trap * 100); + if (!(rel_trap > 0.05)) ++bad; + + float* d_x = nullptr; + check(cudaMalloc(&d_x, x.size() * 4), "lx"); + check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "lcx"); + strata::kernels::gdn_l2_norm(d_x, rows, cols, eps, nullptr); + std::vector got(x.size()); + check(cudaMemcpy(got.data(), d_x, got.size() * 4, cudaMemcpyDeviceToHost), "lcg"); + const double rel = rel_l1(x_ref, got); + std::printf(" %-42s rel %.3e\n", "l2_norm vs reference", rel); + if (!(rel <= 1e-6)) ++bad; + cudaFree(d_x); + } + + // ================= 4. the closing norm ================= + { + const int S2 = 128, hv2 = 8; + std::vector o((size_t) hv2 * S2), z((size_t) hv2 * S2), sn((size_t) S2), y_ref((size_t) hv2 * S2); + for (auto& val : o) val = gauss(rng); + for (auto& val : z) val = gauss(rng); + for (auto& val : sn) val = 1.0f + 0.1f * gauss(rng); + const float eps = 1e-6f; + for (int h = 0; h < hv2; ++h) { + double acc = 0; + for (int i = 0; i < S2; ++i) acc += (double) o[(size_t) (h * S2 + i)] * (double) o[(size_t) (h * S2 + i)]; + const float inv = (float) (1.0 / std::sqrt(acc / S2 + (double) eps)); + for (int i = 0; i < S2; ++i) + y_ref[(size_t) (h * S2 + i)] = o[(size_t) (h * S2 + i)] * inv * sn[(size_t) i] * + sigmoid_f(z[(size_t) (h * S2 + i)]); + } + float *d_o = nullptr, *d_z = nullptr, *d_sn = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_o, o.size() * 4), "no"); + check(cudaMalloc(&d_z, z.size() * 4), "nz"); + check(cudaMalloc(&d_sn, sn.size() * 4), "ns"); + check(cudaMalloc(&d_y, y_ref.size() * 4), "ny"); + check(cudaMemcpy(d_o, o.data(), o.size() * 4, cudaMemcpyHostToDevice), "nco"); + check(cudaMemcpy(d_z, z.data(), z.size() * 4, cudaMemcpyHostToDevice), "ncz"); + check(cudaMemcpy(d_sn, sn.data(), sn.size() * 4, cudaMemcpyHostToDevice), "ncs"); + strata::kernels::gdn_out_norm(d_o, d_z, d_sn, d_y, hv2, S2, eps, nullptr); + std::vector got(y_ref.size()); + check(cudaMemcpy(got.data(), d_y, got.size() * 4, cudaMemcpyDeviceToHost), "ncy"); + const double rel = rel_l1(y_ref, got); + std::printf("\n %-42s rel %.3e\n", "out norm (rms * ssm_norm * sigmoid z)", rel); + if (!(rel <= 1e-6)) ++bad; + + // SiLU instead of sigmoid is the qwen3.5 reading; `ref/gdn.py` says this artifact does NOT use it + std::vector y_silu(y_ref.size()); + for (int h = 0; h < hv2; ++h) { + double acc = 0; + for (int i = 0; i < S2; ++i) acc += (double) o[(size_t) (h * S2 + i)] * (double) o[(size_t) (h * S2 + i)]; + const float inv = (float) (1.0 / std::sqrt(acc / S2 + (double) eps)); + for (int i = 0; i < S2; ++i) { + const float zz = z[(size_t) (h * S2 + i)]; + y_silu[(size_t) (h * S2 + i)] = + o[(size_t) (h * S2 + i)] * inv * sn[(size_t) i] * (zz / (1.0f + std::exp(-zz))); + } + } + const double rel_silu = rel_l1(y_ref, y_silu); + std::printf(" %-42s %-4s (%.2f%% apart)\n", "sigmoid vs SiLU on the gate is observable", + rel_silu > 0.05 ? "yes" : "*** NO ***", rel_silu * 100); + if (!(rel_silu > 0.05)) ++bad; + cudaFree(d_o); cudaFree(d_z); cudaFree(d_sn); cudaFree(d_y); + } + + std::printf("\ngdn: %d failures\n", bad); + 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 new file mode 100644 index 0000000..b5ceb76 --- /dev/null +++ b/src/kernels/gr_parity.cpp @@ -0,0 +1,770 @@ +// 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 new file mode 100644 index 0000000..ace6fac --- /dev/null +++ b/src/kernels/iq_multi_parity.cpp @@ -0,0 +1,414 @@ +// 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_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 new file mode 100644 index 0000000..4bc74f6 --- /dev/null +++ b/src/kernels/iq_parity.cpp @@ -0,0 +1,125 @@ +// 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 new file mode 100644 index 0000000..ca37178 --- /dev/null +++ b/src/kernels/kv_hybrid_parity.cpp @@ -0,0 +1,361 @@ +// 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 + 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 new file mode 100644 index 0000000..5d6d9d3 --- /dev/null +++ b/src/kernels/kv_q4_parity.cpp @@ -0,0 +1,346 @@ +// 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 new file mode 100644 index 0000000..733d7c7 --- /dev/null +++ b/src/kernels/kv_q8_parity.cpp @@ -0,0 +1,141 @@ +// 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 new file mode 100644 index 0000000..0755734 --- /dev/null +++ b/src/kernels/kv_stream_parity.cpp @@ -0,0 +1,234 @@ +// 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 new file mode 100644 index 0000000..fd921d3 --- /dev/null +++ b/src/kernels/mmvq_multi_parity.cpp @@ -0,0 +1,263 @@ +// 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 new file mode 100644 index 0000000..7f16e22 --- /dev/null +++ b/src/kernels/native_expert_bench.cpp @@ -0,0 +1,170 @@ +// 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 new file mode 100644 index 0000000..01133fa --- /dev/null +++ b/src/kernels/native_expert_parity.cpp @@ -0,0 +1,599 @@ +// src/kernels/native_expert_parity.cpp - plan v0.3 P6: one native expert three ways. +// +// build/native_expert_parity [layer ...] real rows (a split model's shards are found by name) +// build/native_expert_parity --synthetic GU/DOWN ... random weights quantized by ggml (e.g. q4_K/q5_1) +// build/native_expert_parity --q5_1-min the Q5_1 min term on crafted activations +// +// (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). +// 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 + +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; +constexpr int64_t H = 2560, FF = 640; + +// The three ways and the dequantizers for one expert blob; returns the number of failed checks. +int check_blob(const cpu::NativeFmt& f, const std::vector& 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); + strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got_g.data(), dout, got_g.size() * 4, cudaMemcpyDeviceToHost); + { // the kernels that decode a weight part once for the NT entries, bitwise vs the per-entry ones (#242; + // the formats without a decode-once split take the per-entry kernels either way) + std::vector 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); + const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg); + std::printf("%-9s %-8s/%-7s blob %8zu cpu rel %.2e gpu rel %.2e cpu-gpu %.2e %s\n", label.c_str(), + ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), f.bytes, ec, eg, ecg, + ok ? "ok" : "FAIL"); + return failures + (ok ? 0 : 1); +} + +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); + const std::string mode = argv[1]; + if (mode == "--q5_1-min") { + failures += check_q5_1_min(s); + } else if (mode == "--bf16-embd") { + failures += check_bf16_embd(s); + } else if (mode == "--synthetic") { + for (int i = 2; i < argc; ++i) { + const std::string arg = argv[i]; + const size_t slash = arg.find('/'); + const int gu = slash == std::string::npos ? -1 : type_of(arg.substr(0, slash)); + 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[1])); + std::vector layers; + for (int i = 2; i < argc; ++i) layers.push_back(std::atoi(argv[i])); + if (layers.empty()) layers = {0, 1, 2, 3, 20, 47}; + for (int l : layers) { + const strata::TensorInfo* t[3] = {}; + 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 new file mode 100644 index 0000000..67fa7e2 --- /dev/null +++ b/src/kernels/native_grouped_parity.cpp @@ -0,0 +1,351 @@ +// 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) +// +// 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 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) + const int e = (t == 12 || t == 13) ? 1 + ex(rng) % 4 : ex(rng); + const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng)); + std::memcpy(&w[o], &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); +} + +} // 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(316); + for (int gu : {16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 8}) // STRATA_GU_FMTS + for (int dt : {20, 23, 42, 7, 8}) check(gu, dt, 512, 256, s, rng); // STRATA_D_FMTS; IQ4_XS: n_ff % 256 + check(21, 20, 2560, 640, s, rng); // a model's shapes + check(21, 23, 2560, 768, s, rng); + if (do_bench) bench(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 new file mode 100644 index 0000000..7292dd9 --- /dev/null +++ b/src/kernels/ngram.cpp @@ -0,0 +1,506 @@ +// 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 +#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; + 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) + const uint64_t page = 4096; + const uintptr_t a0 = (uintptr_t) impl_->data & ~(uintptr_t) (page - 1); + const uintptr_t a1 = (uintptr_t) impl_->data + (uintptr_t) need; + madvise((void*) a0, a1 - a0, MADV_WILLNEED); + if (mlock((const void*) a0, a1 - a0) == 0) { + impl_->locked = true; + } else { + std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): touching its pages instead\n", + std::strerror(errno)); + volatile uint8_t sink = 0; + for (uintptr_t p = a0; p < a1; p += page) sink = sink + *(const volatile uint8_t*) p; + (void) sink; + } +#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; + 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 new file mode 100644 index 0000000..09dd199 --- /dev/null +++ b/src/kernels/ple_fp8_parity.cpp @@ -0,0 +1,84 @@ +// 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 new file mode 100644 index 0000000..60c53b3 --- /dev/null +++ b/src/kernels/ple_oracle_vectors.inc @@ -0,0 +1,105 @@ +// 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 new file mode 100644 index 0000000..20da022 --- /dev/null +++ b/src/kernels/ple_parity.cpp @@ -0,0 +1,1184 @@ +// 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 new file mode 100644 index 0000000..cd387a8 --- /dev/null +++ b/src/kernels/ple_q5_parity.cpp @@ -0,0 +1,59 @@ +// 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 new file mode 100644 index 0000000..20faf99 --- /dev/null +++ b/src/kernels/q5_projection_parity.cpp @@ -0,0 +1,62 @@ +// 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_oracle_vectors.inc b/src/kernels/qsa_oracle_vectors.inc new file mode 100644 index 0000000..0ceec33 --- /dev/null +++ b/src/kernels/qsa_oracle_vectors.inc @@ -0,0 +1,134 @@ +// 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 new file mode 100644 index 0000000..55dec2d --- /dev/null +++ b/src/kernels/qsa_parity.cpp @@ -0,0 +1,1555 @@ +// 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 new file mode 100644 index 0000000..4a0921d --- /dev/null +++ b/src/kernels/qsa_prompt_attn_parity.cpp @@ -0,0 +1,274 @@ +// 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 new file mode 100644 index 0000000..e4ccd02 --- /dev/null +++ b/src/kernels/qsa_select_bench.cpp @@ -0,0 +1,174 @@ +// 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 new file mode 100644 index 0000000..031c0d7 --- /dev/null +++ b/src/kernels/qsa_topk_active_parity.cpp @@ -0,0 +1,95 @@ +// 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 new file mode 100644 index 0000000..d14af3e --- /dev/null +++ b/src/kernels/qsa_topk_parity.cpp @@ -0,0 +1,139 @@ +// 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 new file mode 100644 index 0000000..b2cd7ee --- /dev/null +++ b/src/kernels/quantize_act_parity.cpp @@ -0,0 +1,407 @@ +// 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/rope_parity.cpp b/src/kernels/rope_parity.cpp new file mode 100644 index 0000000..39ba116 --- /dev/null +++ b/src/kernels/rope_parity.cpp @@ -0,0 +1,442 @@ +// 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 new file mode 100644 index 0000000..bb0d6b9 --- /dev/null +++ b/src/kernels/route_window_parity.cpp @@ -0,0 +1,75 @@ +// 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 new file mode 100644 index 0000000..ac7e652 --- /dev/null +++ b/src/kernels/router_top10_parity.cpp @@ -0,0 +1,167 @@ +// 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. +#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 NE = 512; // the real n_expert + const int K = 10; // the real top-k + const int NT = 64; + std::mt19937 rng(2024); + std::normal_distribution gauss(0.0f, 1.0f); + int bad = 0; + + // ---- 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 + 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); + + // ---- 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). Here k/n = 10/512 = 0.01953125, which is 320x the 2**-14 = 6.1035e-05 clamp, so no input + // whatsoever can make this model's renormalisation clamp - not an extreme one, not an adversarial one. + // Asserting the bound is worth more than a test that cannot reach it. + const double min_possible = (double) K / (double) NE; + std::printf(" %-26s top-%d sum >= k/n = %.5f, clamp is %.3e -> margin %.0fx %s\n", "clamp reachability", + K, min_possible, RENORM_CLAMP, min_possible / RENORM_CLAMP, + min_possible > RENORM_CLAMP ? "(CLAMP IS UNREACHABLE, asserted)" : "*** REACHABLE ***"); + if (min_possible <= RENORM_CLAMP) { + std::fprintf(stderr, "the clamp CAN trigger, so it needs a test\n"); + ++bad; + } + + std::printf("\nrouter_top10: %d failures over 4 distributions x %d tokens x %d experts, top-%d\n", bad, NT, NE, + K); + if (bad) return 1; + if (selftest) std::printf("router_top10_parity OK\n"); + return 0; +} diff --git a/src/kernels/s2_expert_grouped_parity.cpp b/src/kernels/s2_expert_grouped_parity.cpp new file mode 100644 index 0000000..901681f --- /dev/null +++ b/src/kernels/s2_expert_grouped_parity.cpp @@ -0,0 +1,679 @@ +// 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 new file mode 100644 index 0000000..ab69379 --- /dev/null +++ b/src/kernels/s2_gemv_parity.cpp @@ -0,0 +1,173 @@ +// 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 new file mode 100644 index 0000000..833e751 --- /dev/null +++ b/src/kernels/s2_gemv_q8_parity.cpp @@ -0,0 +1,181 @@ +// 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 new file mode 100644 index 0000000..5c0bed5 --- /dev/null +++ b/src/kernels/s_gemv_parity.cpp @@ -0,0 +1,634 @@ +// 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 new file mode 100644 index 0000000..5bfb475 --- /dev/null +++ b/src/kernels/s_gemv_q8k_parity.cpp @@ -0,0 +1,343 @@ +// 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 new file mode 100644 index 0000000..2351722 --- /dev/null +++ b/src/kernels/sampler_parity.cpp @@ -0,0 +1,1284 @@ +// 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 new file mode 100644 index 0000000..92de10a --- /dev/null +++ b/src/kernels/shared_expert_parity.cpp @@ -0,0 +1,483 @@ +// 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/f16_bits.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s_gemv.hpp" +#include "strata/kernels/shared_expert.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); + } + + // ================= 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 new file mode 100644 index 0000000..a03e4c0 --- /dev/null +++ b/src/ngram/ple_reader.cpp @@ -0,0 +1,547 @@ +// 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 new file mode 100644 index 0000000..87270fd --- /dev/null +++ b/src/ngram/ple_reader_test.cpp @@ -0,0 +1,298 @@ +// 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 new file mode 100644 index 0000000..5cf1fda --- /dev/null +++ b/src/plan/plan_main.cpp @@ -0,0 +1,73 @@ +// 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 new file mode 100644 index 0000000..cd4f6a7 --- /dev/null +++ b/src/platform/direct_file.cpp @@ -0,0 +1,365 @@ +// 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 new file mode 100644 index 0000000..f3b40e8 --- /dev/null +++ b/src/platform/memory.cpp @@ -0,0 +1,138 @@ +// 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 new file mode 100644 index 0000000..7346189 --- /dev/null +++ b/src/platform/memory_test.cpp @@ -0,0 +1,72 @@ +// 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 new file mode 100644 index 0000000..dabcc22 --- /dev/null +++ b/src/prefill/gdn_rec_parity.cu @@ -0,0 +1,886 @@ +// src/prefill/gdn_rec_parity.cu - the prompt path's DeltaNet recurrence, bit for bit and timed. +// +// src/prefill/kernels.cu runs gdn_rec_kh_kernel (the three value heads that share a key head in one thread, the +// inputs staged in blocks of 8 tokens) on CUDA sm_80+ cards that hold all 64 of its blocks at once, and +// gdn_rec_cols_pipe_kernel elsewhere and with STRATA_GDN_KEYHEAD=0. Both are copied below verbatim, with the output +// norm (gdn_out_norm_kernel) and the norm as it was before, which also stored the normalized value in FP32 although +// nothing reads it. The two recurrences do the same arithmetic in the same order per value head and column, so the +// output, the state after it and the FP16 output must be the same bits. +// +// Synthetic inputs of the model's shape (q/k L2-normalized per key head as gdn_l2_kernel leaves them), no model. +// gdn_rec_parity the bit checks (T from 1 to 4099, a non-zero state as after an earlier chunk) +// gdn_rec_parity --bench and the timings at T = 8192 and 32768 (one layer, all 48 value heads); the two +// variants' launches alternate, since a card under load steps its clock down after a +// fraction of a second (see native_grouped_parity); then both at 1 to 6 blocks per +// SM, as on cards with more or fewer SMs (scale), and both with the engine's grids on +// 32 to all of this card's SMs, the others held by a sleeping kernel (fewer_sms) +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int S = 128, HK = 16, HV = 48, C = 10240; // as kernels.cu: head size, key heads, value heads, q|k|v width +constexpr int RG = 4, RPG = S / RG; +constexpr int CB = 32, NCB = S / CB; + +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. +__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, VPK = HV / HK; // tokens per staged block, value heads per key head +__global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, + const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + constexpr int 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]; + } +} +// 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) +__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] * sigm(z[t * HV * S + head * S + col]); + y16[at] = hf(v); +} + +// ------------------------------------------------------------------ the output norm before (0.1.31) +__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] * sigm(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 +__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; +} + +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 }; +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); +} + +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"); + 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("T=%-6lld %s\n", (long long) T, fails ? "DIFFERENT" : "the same bits (output, state, FP16 output)"); + for (int v = 0; v < kRecCount; ++v) { cudaFree(state[v]); cudaFree(oc[v]); } + cudaFree(y16a); cudaFree(y16b); cudaFree(yb); + return fails; +} + +float median(std::vector v) { + std::sort(v.begin(), v.end()); + return v.empty() ? 0.0f : v[v.size() / 2]; +} + +void bench(int64_t T) { + 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 (48 value heads), medians of %d alternating runs:\n", (long long) T, rounds); + std::printf(" recurrence, before (gdn_rec_cols_pipe_kernel) %8.2f ms (%.3f us per token)\n", r0, + 1000.0f * r0 / (float) T); + std::printf(" recurrence, gdn_rec_kh_kernel %8.2f ms (%.3f us per token) %.2fx\n", r1, + 1000.0f * r1 / (float) T, r0 / r1); + std::printf(" output norm, before (FP32 and FP16 store) %8.2f ms\n", n0); + std::printf(" output norm, FP16 store only %8.2f ms %.2fx\n", n1, n0 / n1); + std::printf(" 36 DeltaNet layers per %lld-token block: recurrence + norm %.0f ms -> %.0f ms (-%.0f ms)\n", + (long long) T, 36.0f * (r0 + n0), 36.0f * (r1 + n1), 36.0f * (r0 + n0 - r1 - n1)); + cudaEventDestroy(e0); + cudaEventDestroy(e1); + cudaFree(state); cudaFree(oc); cudaFree(y16); +} + +// 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) { + 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) { + 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(); +} + +} // 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; + const int64_t Ts[] = {1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 33, 257, 1000, 4099}; + uint64_t seed = 11; + for (const int64_t T : Ts) fails += check_bits(T, seed++); + if (do_bench) { + std::printf("--bench: the prompt path's DeltaNet recurrence\n"); + bench(8192); + bench(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 new file mode 100644 index 0000000..a35daeb --- /dev/null +++ b/src/prefill/gemm.cu @@ -0,0 +1,556 @@ +// 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 new file mode 100644 index 0000000..a947005 --- /dev/null +++ b/src/prefill/gemm_bf16_parity.cu @@ -0,0 +1,155 @@ +// 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 new file mode 100644 index 0000000..1245c2b --- /dev/null +++ b/src/prefill/ggml_cuda_host.cu @@ -0,0 +1,147 @@ +// 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 new file mode 100644 index 0000000..b9d7f54 --- /dev/null +++ b/src/prefill/hipblaslt_tuning.hpp @@ -0,0 +1,123 @@ +#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 new file mode 100644 index 0000000..4ad67b1 --- /dev/null +++ b/src/prefill/kernels.cu @@ -0,0 +1,1024 @@ +// 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 { + +constexpr int N = 2560, HC = 4, D = N * HC, LR = 320; +constexpr int S = 128, HK = 16, HV = 48, C = 10240; + +__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 +__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 +__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; +__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) +__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]; +} +__global__ void gdn_l2_kernel(float* __restrict__ h, float eps) { + // block (t, head) over the 32 q/k heads, 128 threads + const int64_t t = blockIdx.y; + const int head = blockIdx.x; + float* x = h + t * C + head * S; + 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; +__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 * sigm(z[t * HV * S + head * S + col]); + y[t * HV * S + head * S + col] = v; + y16[t * HV * S + head * S + col] = hf(v); + } + } +#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; +__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. +__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, VPK = HV / HK; // tokens per staged block, value heads per key head +__global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, + const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + constexpr int 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). +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) +__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] * sigm(z[t * HV * S + head * S + col]); + y16[at] = hf(v); +} + +// ---------------------------------------------------------------- MoE +template +__global__ void route_kernel(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ wout, + int64_t T) { + const int64_t t = (int64_t) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + if (t >= T) return; + const int lane = threadIdx.x & 31; + 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 < 10; ++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 * 10 + rank] = ex; + if (rank == lane) selected = best; + } + selected_sum = fmaxf(warp_sum(selected_sum), 6.103515625e-5f); + if (lane < 10) wout[t * 10 + lane] = selected / selected_sum; +} +// 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) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * 640) return; + const int64_t r = i / 640, k = i % 640; + const float g = gu[r * 1280 + 2 * k], u = gu[r * 1280 + 2 * k + 1]; + h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u); +} +__global__ void swiglu_pair_kernel(const float* __restrict__ g, const float* __restrict__ u, uint16_t* __restrict__ h16, + int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * 640) return; + 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]; +} +__global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot, + const float* __restrict__ w, const float* __restrict__ shared, + const float* __restrict__ sg, float* __restrict__ bo, int64_t T) { + const 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 k = 0; k < 10; ++k) s = fmaf(w[t * 10 + k], Dm[(int64_t) slot[t * 10 + k] * N + d], s); + bo[i] = s + shared[i] * sigm(sg[t]); +} + +// ---------------------------------------------------------------- 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; +} +__global__ void split_q_kernel(const float* __restrict__ qf, float* __restrict__ q, int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * 24 * 256) return; + const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256; + q[i] = qf[t * 24 * 512 + h * 512 + d]; +} +__global__ void gate_attn_kernel(const float* __restrict__ a, const float* __restrict__ qf, uint16_t* __restrict__ o16, + int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * 24 * 256) return; + const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256; + o16[i] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * 24 * 512 + h * 512 + 256 + d])))); +} + +// 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"); +} +void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream) { + gdn_gates_kernel<<>>(ab, dt, ssm_a, gate, beta, T); + check("gdn_gates"); +} +void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream) { + static const bool serial = std::getenv("STRATA_GDN_CONV_SERIAL") != nullptr; // the old walk (A/B) + 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, void* stream) { + static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) + if (serial || T <= 0) { + gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); + } else { + static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); +#if !defined(__HIPCC__) + if (pipe && gdn_keyhead_ok()) // 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); + 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, void* stream) { + if (n_expert == 512) + route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T); + else if (n_expert == 256) + route_kernel<8><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T); + else + strata::kernels::router_top10(logits, (int) T, (int) n_expert, 10, ids, weights, stream); + check("route"); +} +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, void* stream) { + if (n <= 0) return; + swiglu_il_kernel<<>>(gu, h16, n); + check("swiglu_interleaved"); +} +void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream) { + swiglu_pair_kernel<<>>(g, u, h16, n); + 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, void* stream) { + moe_combine_kernel<<>>(Dm, slot, w, shared, sg, bo, T); + check("moe_combine"); +} +void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream) { + 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, void* stream) { + split_q_kernel<<>>(q_full, q, T); + check("split_q"); +} +void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream) { + gate_attn_kernel<<>>(attn, q_full, out16, T); + check("gate_attn"); +} + +} // namespace strata::prefill diff --git a/src/prefill/moe_fused.cu b/src/prefill/moe_fused.cu new file mode 100644 index 0000000..19d1c94 --- /dev/null +++ b/src/prefill/moe_fused.cu @@ -0,0 +1,465 @@ +// 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 new file mode 100644 index 0000000..b2d9908 --- /dev/null +++ b/src/prefill/moe_fused_iq.cu @@ -0,0 +1,638 @@ +// 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) +constexpr int GU_ROWS_K = 2560, D_ROWS_K = 640; // K of gate/up (n_embd) and of down (n_ff) + +// the formats (ggml type ids) +constexpr int T_IQ2_XXS = GGML_TYPE_IQ2_XXS, T_IQ2_XS = GGML_TYPE_IQ2_XS, T_IQ2_S = GGML_TYPE_IQ2_S, + 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; + constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K + constexpr int NFB = (GU ? 1280 : 2560) / WR; // weight-row blocks per tile + constexpr int ACT_LD = NS * AB; // bytes per activation row: 3200 (a token), 800 (a row's H) + constexpr int BS = block_bytes(WT); + constexpr bool K16 = per16(WT); + extern __shared__ __align__(16) uint8_t smem[]; + 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 < GU_ROWS_K / 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) * (10 * AB) + (blk >> 1) * AB; + const int hh = blk & 1; +#pragma unroll + for (int i = 0; i < 4; ++i) o[32 * hh + 8 * i + g] = (uint8_t) (int8_t) __float2int_rn(h[i] * inv); + 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) * 2560 + 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); + const unsigned g_gu = (unsigned) std::min(tiles * (1280 / weight_rows(ww)), (int64_t) d.sms * d.occ); + const unsigned g_d = (unsigned) std::min(tiles * (2560 / 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 new file mode 100644 index 0000000..c61e707 --- /dev/null +++ b/src/prefill/moe_mmq.cu @@ -0,0 +1,266 @@ +// 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) +#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; +#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 new file mode 100644 index 0000000..e76fb6d --- /dev/null +++ b/src/prefill/prefill.cpp @@ -0,0 +1,3084 @@ +// src/prefill/prefill.cpp - see include/strata/prefill/prefill.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; +constexpr int64_t N = 2560, HC = 4, D = N * HC, LR = 320, K = 10, NE = 512; +constexpr int64_t C = 10240, ZV = 6144, HV = 48; +// plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer) +inline int64_t MAXBLOB() { return (int64_t) strata::kernels::cpu::expert_layout().max_blob; } +constexpr int STAGE = 8; // host->device expert staging ring (chunks below stream_all_min()) +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) { ok = false; return nullptr; } + T* p = (T*) (base + used); + used += bytes; + return p; + } + void* p = nullptr; + if (cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; return nullptr; } + 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 / 16 + 2; + cudaEvent_t ev_grp[kGrpEv] = {}; + bool out_pending = false; // s_out may still read Dm (the next layer's products wait for it) + bool out_pipe = true; + // 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 + NE / 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; + 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) { + 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) { + 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; +} +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) { + Alloc a; a.count_only = true; bool ok = true; + a.take(T * 512, ok); a.take(T * 512, ok); a.take(T * 12288, ok); a.take(T * ZV, ok); + a.take(T * 128, ok); a.take(T * 512, ok); a.take(T * ZV, ok); a.take(T * ZV, ok); + a.take(T * (size_t) cap, ok); + 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; +} +// 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; + // #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path + if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) { p.fallback = true; continue; } + p.layer[(size_t) l] = 1; + p.any = true; + p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N)); + p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, 640)); + } + 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, int64_t n_expert, bool fused) { + if (!fused) return {T * K * 1280, T * K * 640, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) (T * K), 640)}; + const size_t ts = (size_t) std::min((int64_t) T, stream_all_min() - 1); // MMQ's last small chunk + return {std::max(ts * K * 1280, (fused::group_bytes((int64_t) (T * K), (int) n_expert) + 3) / 4), + std::max(ts * K * 640, (fused::act_bytes((int64_t) (T * K), 640) + 3) / 4), + std::max(mmq::q8_bytes((int64_t) (ts * K), N), fused::act_bytes((int64_t) T, N)), + mmq::q8_bytes((int64_t) (ts * K), 640)}; +} +uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) { + const MmqPlan& mp = mmq_plan(); + const MoeBufs mb = moe_bufs(T, n_expert, fused); + Alloc a; a.count_only = true; bool ok = true; + a.take(T * n_expert, 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 * 640, ok); + a.take(T * K * N, ok); a.take(T * 640, ok); + a.take(T * 640, ok); a.take(T * 640, 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_; + if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert < 1 || ss.k != K) { + err = "prefill: geometry differs from the artifact's"; return false; + } + cudaGetDevice(&m.device); + if (stage_le_ < 0) stage_le_ = g.n_layers; + 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_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; + bool ok = true; + m.emb = o.take(T * N, ok); m.R = o.take(T * D, ok); + m.xn = gr_unfused() ? o.take(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R) + m.grs = o.take(T * HC, ok); + m.xn16 = o.take(T * D, ok); m.lo = o.take(T * LR, ok); m.lo16 = o.take(T * LR, ok); + m.gated = o.take(T * D, ok); m.inj = o.take(T * HC, ok); + 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 (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); + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + m.cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); + m.max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; + { + // one region for the attention half's and the MoE half's scratch (see gdn_set_bytes) + const bool fz = fused_layout(T, m.src != nullptr); + const MoeBufs mb = moe_bufs(T, m.g->n_expert, fz); + const uint64_t region = std::max({gdn_set_bytes(T), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch, + m.attn_batch, s), moe_set_bytes(T, m.g->n_expert, fz)}); + uint8_t* base = o.take((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 * 512, ok); m.Vc = b.take(T * 512, ok); m.Qf = b.take(T * 12288, ok); + m.q = b.take(T * ZV, ok); m.idx_raw = b.take(T * 128, ok); m.q_idx = b.take(T * 512, ok); + m.attn = b.take(T * ZV, ok); m.attn_h = b.take(T * ZV, ok); + m.sel_ids = b.take(T * (size_t) m.cap, ok); + m.sel_scores = b.take((size_t) m.sel_batch * (size_t) m.max_blocks, ok); + 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 * m.g->n_expert, 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 * 640, ok) : nullptr; + m.Dm = c.take(T * K * N, ok); + m.sgate = c.take(T * 640, ok); m.sup = c.take(T * 640, ok); m.sh_h = c.take(T * 640, 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(1280 * 2560, ok); m.dq_d[i] = o.take(2560 * 640, 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 * (m.g->n_expert + m.g->n_expert / 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 = o.take(T * N, ok); + m.ple_norm = o.take((size_t) strata::kernels::NG_HC_DIM, ok); + 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; + constexpr int kQ8_0 = 8; // GGML_TYPE_Q8_0 + 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 + // E-9: the drafter's Q8_0 matrices through Q8_1 x Q8_0 MMQ - its own pass's integer dot products (mmvq), so + // its K/V stay close to what the drafter computes itself; STRATA_MTP_BATCH_F16=1: FP16 GEMMs (the A/B) + static const bool f16_only = [] { const char* v = std::getenv("STRATA_MTP_BATCH_F16"); return v && v[0] == '1'; }(); + const bool q8 = !f16_only && mmq::built() && mmq::fits(kQ8_0, Nn) && mmq::fits(kQ8_0, KV); // #420 + const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1) + 2 * (Nn + 2 * HCN + LR + Nn) + 64 + + (q8 ? (uint64_t) mmq::q8_bytes(g.hc, Nn) + 4 * g.hc : 0); + 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; + static const bool timing = std::getenv("STRATA_DRAFT_TIMING") != nullptr; // debug: where this pass's time goes + if (timing) cudaStreamSynchronize(m.cs); + const auto ti0 = Clock::now(); + if (!mtp.idle(err)) return false; // the drafter's own stream (its graph uploads) before this writes its K/V + const double ms_idle = ms_since(ti0); + const auto tl0 = Clock::now(); + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + 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; + 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(); + 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, 640)); + pp->GU_g = (float*) take((size_t) Gr * 1280 * 4); + pp->H_g = (float*) take((size_t) Gr * 640 * 4); + pp->Dm_b[0] = (float*) take((size_t) Gr * N * 4); + pp->Dm_b[1] = (float*) take((size_t) Gr * N * 4); + for (int b = 0; b < 2 && ok; ++b) ok = cudaEventCreateWithFlags(&pp->ev_dm[b], cudaEventDisableTiming) == cudaSuccess; + 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, 640)); + pp->GU = (float*) take((size_t) R * 1280 * 4); + pp->H = (float*) take((size_t) R * 640 * 4); + pp->Dm = (float*) take((size_t) R * N * 4); + } + const int64_t Rt = pp->cap_rows; + 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; + 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. + if (ring_bytes_on()) { + f(T * N); f(T * D); + if (gr_unfused()) f(T * D); + f(T * HC); + } else { // STRATA_RING_BYTES=0: 0.1.39's count + f(T * N); f(T * D); f(T * D); + } + 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 (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); + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); + const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; + o.take((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s), + moe_set_bytes(T, g.n_expert, fused_layout(T, true))}), ok); + for (int i = 0; i < DQ; ++i) { o.take(1280 * 2560, ok); o.take(2560 * 640, 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); + 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 auto t_start = Clock::now(); + const int64_t LB = stage_lb_, LE = stage_le_; + // The direct successor's future lives on the Prefill object. Intermediate + // stages therefore do not drain the complete remaining GPU chain here. + double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0; // STRATA_PREFILL_TIMING: the host's share + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + const 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) 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 + 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); + } + for (int half = 0; half < 2; ++half) { + // ---- 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, m.cs); + gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs); + pt.mark(kPfGdnRec, cs); + gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, 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]; + const core::WeightRef *wq = need(v, "attn_q.weight", err), *wk = need(v, "attn_k.weight", err), + *wv = need(v, "attn_v.weight", err), *wo = need(v, "attn_output.weight", err), + *wik = need(v, "indexer.k_proj.weight", err), + *wiq = need(v, "indexer.q_proj.weight", err), + *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err), + *wiqn = need(v, "indexer.q_norm.weight", err), + *wikn = need(v, "indexer.k_norm.weight", err); + if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false; + pt.mark(kPfQsa, cs); + if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; + if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false; + if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false; + if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); + rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); + // 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, m.cs); + rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); + rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); + rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs); + rope(m.q_idx, T, 4, 128, 512, p0, strata::kernels::rope_scaling(), m.cs); + // the indexer appends, token by token; then scores + selection for many queries at once: + // 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); + } + } + } + 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 * ZV, pools, m.sel_ids + t0 * m.cap, + m.steps_dev + t0 * strata::kernels::kStepCount, m.cap, + s, m.attn_scratch, m.attn + t0 * ZV, nb, m.cs); + } + if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs); + pt.mark(kPfQsa, cs); + gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs); + if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false; + ++qsa_index; + } else { + // ======================= 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, m.cs); + // the shared expert and its scalar gate + if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false; + if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false; + swiglu_pair(m.sgate, m.sup, m.sh_h, T, 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}; + 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, 1280, N) : 0; + const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0; + pt.mark(kPfGather, cs); + if (use_mmq) { + // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed` + 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 = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub; + gu.n = ngx; gu.xq = P.Xq_g; gu.bounds = rel; gu.ids = P.ident; + gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = 1280; + P.run_ctx->run(gu, ps); + mmq::swiglu(P.GU_g, P.H_g, nr, 640, !lay.native, ps); + mmq::quantize(P.H_g, nullptr, P.Hq_g, mmq_dt, 640, 640, nr, ps); + const int b = (int) (g2 & 1); + if (P.dm_live[b]) cudaStreamWaitEvent(ps, P.ev_dm[b], 0); // its last rows have left + mmq::Product dn; + dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db; + dn.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 = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub; + gu.n = ngx; gu.xq = P.Xq; gu.bounds = P.bounds + j0; gu.ids = P.ident; + gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = 1280; + P.run_ctx->run(gu, ps); + mmq::swiglu(P.GU + r0 * 1280, P.H + r0 * 640, nr, 640, !lay.native, ps); + mmq::quantize(P.H + r0 * 640, nullptr, P.Hq, mmq_dt, 640, 640, nr, ps); + mmq::Product dn; + dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db; + dn.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 = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub; + gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity; + gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280; + m.mmq_ctx->run(gu, m.cs); + mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs); + pt.mark(kPfGemmD, cs); + mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs); + mmq::Product dn; + dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db; + dn.n = ngx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1); + dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N; + dn.ld_dst = N; + 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 * 1280, ne, 1280, N); + swiglu_interleaved(m.GU + o0 * 1280, m.Hh + o0 * 640, ne, m.cs); + pt.mark(kPfGemmD, cs); + m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640); + 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, 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 * 1280), bdm = bad(m.Dm, T * K * N), + bbo = bad(m.bo, T * N); + const int64_t bh = m.H && !fused_l ? bad(m.H, T * K * 640) : -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); + } + } + } + // ---- 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 (!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 new file mode 100644 index 0000000..f4a0c2b --- /dev/null +++ b/src/program/conv_cache_test.cpp @@ -0,0 +1,67 @@ +// 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 new file mode 100644 index 0000000..085c3d8 --- /dev/null +++ b/src/program/generate.cpp @@ -0,0 +1,8361 @@ +// 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/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 +} + +// #620 #486: " (N MiB of M MiB VRAM free on this GPU)" for an allocation's failure message (clears the error first) +std::string vram_free_note() { + (void) cudaGetLastError(); + size_t free_b = 0, total_b = 0; + if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) { + (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) + /// #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; + /// 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-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" + " --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; +}; + +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 >= 48) { + std::fprintf(stderr, "strata generate: the routing trace saw layer %d, outside 0..47\n", layer_idx); + 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 < 48) { + 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; +} + +// #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); +#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; + cudaMemGetInfo(&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 == "--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 == "--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; + } + 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_ple_key = o.native_moe_combine = o.native_gdn = o.native_router = true; + o.native_qsa = o.native_qsa_indexer = o.native_rope = o.native_ple_postops = true; + 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 && + 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.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; + } + // Plan v0.3 P6: where the experts live. A native pack (tools/iq_pack.py: the IQ2_XS / IQ3_XXS files) keeps + // every quantized tensor in its GGUF form, so it needs --native (the dense projections, head and embedding + // come from the model file) and runs its experts in verify windows only (--spec). + { + const strata::core::ModelGeometry g0; + if (!strata::kernels::cpu::expert_layout_load(o.pack, g0.n_layers, g0.n_expert, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + // 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; + } + } + } + const bool native_pack = strata::kernels::cpu::expert_layout().native; + // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's + // pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs, + // and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory"). + 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)"); + strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below + int64_t K = 10; + // THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken, + // and `session_init` below builds the rope table from it and captures the kernels reading its constants + // (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats + // 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()) { + // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file + // is the authority on its own MoE shape - everything else in the geometry is unchanged + try { + strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) + 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; + } + const strata::core::ModelGeometry g0; + if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g0.n_embd, + 248320, 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; + cudaMemGetInfo(&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()) { + if (!native_dense.load(o.native_dense_gguf, wt, err, o.native_ple_key)) { + 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)); + } + + 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; + cudaMemGetInfo(&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 + cudaMemGetInfo(&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; + cudaMemGetInfo(&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 = cudaMemGetInfo(&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; + cudaMemGetInfo(&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; + cudaMemGetInfo(&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; + cudaMemGetInfo(&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()); + // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, + // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference + static const strata::core::ModelGeometry draft_geometry{}; + // 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(); + const uint64_t pin_limit = pin_env >= 0 ? (uint64_t) pin_env << 30 : pin_wddm_cap ? (8ull << 30) : 0; + 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; + cudaMemGetInfo(&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; + cudaMemGetInfo(&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; + cudaMemGetInfo(&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; + cudaMemGetInfo(&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; + cudaMemGetInfo(&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; + 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 (cudaMemGetInfo(&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; + cudaMemGetInfo(&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; + cudaMemGetInfo(&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; + cudaMemGetInfo(&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 + }; + 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; + cudaMemGetInfo(&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(); + cudaMemGetInfo(&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("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; } + 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(); }); + 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; + 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]); + 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; + } + 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); + 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 (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; + 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; + bool from_sfx = false; + int sfx_match = 0; + if (o.suffix_draft > 0 && !first_window) { + 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 (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.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; + } + x = 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.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 new file mode 100644 index 0000000..be31270 --- /dev/null +++ b/src/spec/controller.cpp @@ -0,0 +1,73 @@ +// 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 new file mode 100644 index 0000000..ee056ab --- /dev/null +++ b/src/spec/controller_test.cpp @@ -0,0 +1,74 @@ +// 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 new file mode 100644 index 0000000..1ac7719 --- /dev/null +++ b/src/spec/draft_policy.cpp @@ -0,0 +1,101 @@ +// 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 new file mode 100644 index 0000000..e04b3de --- /dev/null +++ b/src/spec/draft_policy_test.cpp @@ -0,0 +1,63 @@ +// 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 new file mode 100644 index 0000000..6f04f76 --- /dev/null +++ b/src/spec/suffix_drafter.cpp @@ -0,0 +1,88 @@ +// 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 new file mode 100644 index 0000000..9fa8611 --- /dev/null +++ b/src/spec/suffix_drafter_test.cpp @@ -0,0 +1,141 @@ +// 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/sycl/.gitignore b/sycl/.gitignore new file mode 100644 index 0000000..d73108e --- /dev/null +++ b/sycl/.gitignore @@ -0,0 +1,4 @@ +# dpct output that is not part of the port (tools/migrate.sh) +dpct_report.* +**/*.yaml +migrate.log diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt new file mode 100644 index 0000000..1b6094a --- /dev/null +++ b/sycl/CMakeLists.txt @@ -0,0 +1,241 @@ +# Strata on Intel GPUs - the SYCL build of the engine (Phase 4 of the Intel port, docs/INTEL.md). +# +# This is a separate project on purpose. The top-level build describes the CUDA engine; every source it lists is +# taken from ../src unless this directory carries a migrated copy: `src/X.cu` -> `sycl/src/X.dp.cpp`, +# `src/X.cpp` -> `sycl/src/X.cpp` (only host files that called the CUDA runtime were migrated). Headers resolve +# the same way through the include order. Upstream files are never edited, so the port is the content of this +# directory plus the tool that produced it (../../sycl/migrate.sh). +# +# cmake -S sycl -B build-sycl -G Ninja -DCMAKE_CXX_COMPILER=icpx && cmake --build build-sycl +# +# Device code is JIT-compiled from SPIR-V unless STRATA_SYCL_AOT names a device (bmg-g31 for the Arc Pro B70). +cmake_minimum_required(VERSION 3.24) +project(strata_sycl VERSION 0.1.39 LANGUAGES C CXX) # the upstream engine version this port tracks +set(STRATA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/..) +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() +add_compile_definitions(STRATA_VERSION="${PROJECT_VERSION}-sycl") + +set(STRATA_SYCL_AOT "" CACHE STRING "AOT device for the GPU code, e.g. bmg-g31 (empty: SPIR-V, JIT at run time)") +set(_sycl_flags -fsycl) +if(STRATA_SYCL_AOT) + list(APPEND _sycl_flags -fsycl-targets=spir64_gen) + # the divide/sqrt rounding option (below) must reach ocloc here: an AOT build has no spir64 backend to take it + set(_sycl_link -fsycl -fsycl-targets=spir64_gen -Xsycl-target-backend=spir64_gen + "-device ${STRATA_SYCL_AOT} -options -cl-fp32-correctly-rounded-divide-sqrt") +else() + set(_sycl_link -fsycl) +endif() +# The Intel GPU's fp32 divide is not correctly rounded by default (OpenCL allows 2.5 ulp). Strata's quantizers +# are byte-exact against ggml through `amax / 127`, so the device compiler is told to round divides and sqrt +# properly; measured: quantize_act_parity goes from 303k mismatches to byte-exact. (Same as +# SYCL_PROGRAM_COMPILE_OPTIONS=-cl-fp32-correctly-rounded-divide-sqrt at run time.) The AOT build passes it to +# ocloc above; without that the 303k mismatches came back on 2026-09-30, unnoticed since the AOT switch. +if(NOT STRATA_SYCL_AOT) + list(APPEND _sycl_link "-Xsycl-target-backend=spir64" "-cl-fp32-correctly-rounded-divide-sqrt") +endif() +# Every translation unit gets -fsycl: the migrated host files construct queues and USM, not only the kernels. +# icpx defaults to a fast floating-point model (reciprocal approximations, reassociation); the kernels are +# compared byte-for-byte against ggml's, which nvcc built value-safe, so ask for the same here. +# Every kernel was written for 32-lane warps (lane = tid & 31, warp-synchronous reductions). dpct pins the +# sub-group size only where it saw a shuffle; the rest would get Xe2's default of 16 and race. Force 32 everywhere. +list(APPEND _sycl_flags -fsycl-default-sub-group-size=32) +# One device module per kernel: the first launch of a kernel then loads only its own module. With the default +# split the first launch in the prompt path (the embedding gather) paid 245 ms for the image it shared (2026-09-30). +list(APPEND _sycl_link -fsycl-device-code-split=per_kernel) +list(APPEND _sycl_flags -fsycl-device-code-split=per_kernel) +add_compile_options("$<$:${_sycl_flags}>" -fp-model=precise -Wno-unused-parameter + -Wno-unused-variable -Wno-deprecated-declarations) +add_link_options(${_sycl_link}) + +# --- source resolution: the migrated copy when there is one, the original otherwise ------------------------------- +function(strata_resolve out) + set(r "") + foreach(f IN LISTS ARGN) + if(f MATCHES "\\.cu$") + string(REGEX REPLACE "\\.cu$" ".dp.cpp" m "${f}") + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${m}) + list(APPEND r ${CMAKE_CURRENT_SOURCE_DIR}/${m}) + else() + message(FATAL_ERROR "no migrated copy of ${f} (expected ${m})") + endif() + elseif(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${f}) + list(APPEND r ${CMAKE_CURRENT_SOURCE_DIR}/${f}) + elseif(EXISTS ${STRATA_ROOT}/${f}) + list(APPEND r ${STRATA_ROOT}/${f}) + else() + message(FATAL_ERROR "no such source: ${f}") + endif() + endforeach() + set(${out} ${r} PARENT_SCOPE) +endfunction() + +add_library(strata_includes INTERFACE) +target_include_directories(strata_includes INTERFACE + ${CMAKE_CURRENT_SOURCE_DIR}/include # migrated headers + dpct/ helpers, first + ${STRATA_ROOT}/include) +target_compile_options(strata_includes INTERFACE -Wall -Wextra) + +# --- CPU-side pieces, identical to the top-level build ------------------------------------------------------------ +strata_resolve(_spec src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp) +add_library(strata_spec STATIC ${_spec}) +target_link_libraries(strata_spec PUBLIC strata_includes) + +strata_resolve(_cpu src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp src/kernels/cpu/expert_layout.cpp + src/kernels/cpu/q2_avx2.cpp) +add_library(strata_kernels_cpu STATIC ${_cpu}) +set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/expert.cpp PROPERTIES COMPILE_OPTIONS + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") +set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/q2_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") +find_package(Threads REQUIRED) +target_link_libraries(strata_kernels_cpu PUBLIC strata_includes Threads::Threads) + +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_NATIVE_EXPERTS) + set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) + set(GGML_STATIC ON CACHE BOOL "" FORCE) + set(GGML_CUDA OFF CACHE BOOL "" FORCE) + set(GGML_SYCL 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) + set(GGML_NATIVE ON CACHE BOOL "" FORCE) + if(STRATA_GGML_DIR) + add_subdirectory(${STRATA_GGML_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL) + else() + include(FetchContent) + FetchContent_Declare(strata_llamacpp + GIT_REPOSITORY https://github.com/ggml-org/llama.cpp.git + GIT_TAG 3cf03257f219afbe7334045ff7c6a06ac68c627d + GIT_SHALLOW FALSE) + FetchContent_GetProperties(strata_llamacpp) + if(NOT strata_llamacpp_POPULATED) + FetchContent_Populate(strata_llamacpp) + endif() + add_subdirectory(${strata_llamacpp_SOURCE_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL) + endif() + strata_resolve(_cpu_native src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/iq_avx2.cpp + src/kernels/cpu/kq_avx2.cpp) # 0.1.31: the Q4_K/Q5_K/Q5_1/Q8_0 expert rows + target_sources(strata_kernels_cpu PRIVATE ${_cpu_native}) + target_include_directories(strata_kernels_cpu PRIVATE ${STRATA_ROOT}/third_party/ggml) + set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") + set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) + target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) +endif() + +# --- the GPU engine ------------------------------------------------------------------------------------------------ +strata_resolve(_core src/core/device.cu src/core/pinned.cu src/platform/memory.cpp src/core/graph.cpp + src/core/weights.cpp src/core/layout.cpp) +add_library(strata_core STATIC ${_core}) +target_link_libraries(strata_core PUBLIC strata_includes) + +set(_kernel_cu dequant_s2 s2_gemv s_gemv s2_gemv_quads s2_gemv_fast router_top10 quantize_act rope sampler s2_gemv_q8 + s2_expert_grouped shared_expert gr gdn qsa elementwise bf16_gemv native_mmvq native_bf16 native_gr_norm native_moe + native_gdn native_gr_postops native_router native_gdn_preprocess native_qsa native_rope native_ple_postops + native_flash_attn native_qsa_indexer native_qsa_score ple kv_q8 kv_stream kv_q4 fused_gr cvec qsa_decode_attn + qsa_prompt_attn fused_gdn dequant_bf16 qsa_select verify_kernels iq_kernels) +set(_kernel_files "") +foreach(k IN LISTS _kernel_cu) + list(APPEND _kernel_files src/kernels/cuda/${k}.cu) +endforeach() +strata_resolve(_kernels ${_kernel_files} src/kernels/ngram.cpp src/ngram/ple_reader.cpp src/platform/direct_file.cpp) +list(APPEND _kernels ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp) # port-only: the XMX prompt attention +add_library(strata_kernels STATIC ${_kernels}) +target_include_directories(strata_kernels PRIVATE ${STRATA_ROOT}/third_party/ggml) +target_link_libraries(strata_kernels PUBLIC strata_core) + +strata_resolve(_engine src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp + 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 # 0.1.31: the conversation snapshots (#216) + src/core/peer_experts.cpp) # 0.1.36+: --peer-device (a stub in the port: no second GPU tier yet) +add_library(strata_engine STATIC ${_engine} ${CMAKE_CURRENT_SOURCE_DIR}/src/core/gguf_expert_source.cpp) +target_include_directories(strata_engine PRIVATE ${STRATA_ROOT}/src/core) # conversation_checked.hpp (#include "...") +target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu) + +# cuBLAS -> oneMKL through dpct::blas (needs the MKL SYCL BLAS domain) +strata_resolve(_prefill src/prefill/gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp) +add_library(strata_prefill STATIC ${_prefill} + ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_fused_stub.cpp) # upstream's fused int8 kernels: not built here +target_compile_options(strata_prefill PUBLIC -qmkl=sequential) +target_link_options(strata_prefill PUBLIC -qmkl=sequential) +target_link_libraries(strata_prefill PUBLIC strata_engine) + +strata_resolve(_main src/program/generate.cpp) +add_executable(strata ${_main}) +target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec) + +# --- the kernel parity self-tests (each runs on the card and compares against a CPU reference) --------------------- +option(STRATA_SYCL_PARITY "Build the kernel parity tests" ON) +if(STRATA_SYCL_PARITY) + enable_testing() + foreach(p IN ITEMS dequant_s2 s2_gemv iq shared_expert gr gdn s2_gemv_q8 sampler rope quantize_act router_top10 + s_gemv elementwise bf16_gemv s_gemv_q8k qsa ple kv_q8 kv_stream kv_q4 cvec) + strata_resolve(_src src/kernels/${p}_parity.cpp) + add_executable(${p}_parity ${_src}) + target_include_directories(${p}_parity PRIVATE ${STRATA_ROOT}/src/kernels) # the oracle .inc fixtures + target_link_libraries(${p}_parity PRIVATE strata_kernels) + add_test(NAME ${p}_parity COMMAND ${p}_parity --selftest) + endforeach() + # 0.1.31: the IQ kernels that decode a weight part once for every column/entry, bitwise vs the per-column ones + # (no --selftest flag: it runs its checks by default), and the rewritten per-hit/grouped expert kernels vs the + # previous ones, bitwise + strata_resolve(_src src/kernels/iq_multi_parity.cpp) + add_executable(iq_multi_parity ${_src}) + target_link_libraries(iq_multi_parity PRIVATE strata_kernels) + add_test(NAME iq_multi_parity COMMAND iq_multi_parity) + strata_resolve(_src src/kernels/s2_expert_grouped_parity.cpp) + add_executable(s2_expert_grouped_parity ${_src}) + target_link_libraries(s2_expert_grouped_parity PRIVATE strata_kernels) + add_test(NAME s2_expert_grouped_parity COMMAND s2_expert_grouped_parity --selftest) + # upstream PR #363: native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the v1 launches + strata_resolve(_src src/kernels/native_grouped_parity.cpp) + add_executable(native_grouped_parity ${_src}) + target_link_libraries(native_grouped_parity PRIVATE strata_kernels) + add_test(NAME native_grouped_parity COMMAND native_grouped_parity) + # (upstream PR #413's gdn_rec_parity is an SM-holding NVIDIA bench - PTX timers, __nanosleep - not built here; the + # key-head kernel is checked through the engine: output hashes with STRATA_GDN_KEYHEAD=1 and without) + # the conversation snapshots (#216) against the engine, as upstream's STRATA_BUILD_CONVERSATION_TESTS + strata_resolve(_src src/core/conversation_snapshot_test.cpp) + add_executable(conversation_snapshot_test ${_src}) + 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) + # the prompt-attention parity takes a context length, not --selftest, and needs the tensor-core kernel (not + # ported yet: it reports "refused the pools" here). Built, not registered. + strata_resolve(_src src/kernels/qsa_prompt_attn_parity.cpp) + add_executable(qsa_prompt_attn_parity ${_src}) + target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels) + # the hybrid K8V4 KV test (upstream 0.1.27) passes its appends, gathers and attention here and fails only its + # last step, the same tensor-core prompt kernel. Built, not registered, until that kernel is ported. + strata_resolve(_src src/kernels/kv_hybrid_parity.cpp) + add_executable(kv_hybrid_parity ${_src}) + target_include_directories(kv_hybrid_parity PRIVATE ${STRATA_ROOT}/src/kernels) + target_link_libraries(kv_hybrid_parity PRIVATE strata_kernels) + add_executable(mmvq_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/mmvq_bench.cpp) # dense mmvq timing + target_link_libraries(mmvq_bench PRIVATE strata_kernels) + add_executable(mmvq_sg_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/mmvq_sg_bench.cpp) # SIMD16 vs 32 decode mmvq + target_link_libraries(mmvq_sg_bench PRIVATE strata_kernels) + add_executable(q6k_align_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/q6k_align_bench.cpp) # Q6_K block alignment + target_link_libraries(q6k_align_bench PRIVATE strata_kernels) + add_executable(gr_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/gr_bench.cpp) # fused GR read timing + target_link_libraries(gr_bench PRIVATE strata_kernels) + add_executable(xmx_gemm_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/xmx_gemm_bench.cpp) # XMX quantized GEMM vs dequant+oneMKL + target_link_libraries(xmx_gemm_bench PRIVATE strata_kernels strata_prefill) # -qmkl for the oneMKL reference + # one native expert three ways on real GGUF rows (ggml reference, CPU path, GPU native_expert_grouped): + # native_expert_parity [layer ...] + if(STRATA_NATIVE_EXPERTS) + add_executable(native_expert_parity ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/native_expert_parity.cpp) + target_include_directories(native_expert_parity PRIVATE ${STRATA_ROOT}/third_party/ggml) + target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu) + endif() +endif() diff --git a/sycl/include/dpct/LICENSE.TXT b/sycl/include/dpct/LICENSE.TXT new file mode 100644 index 0000000..a209b42 --- /dev/null +++ b/sycl/include/dpct/LICENSE.TXT @@ -0,0 +1,236 @@ +============================================================================== +The SYCLomatic (dpct) helper headers in this directory, vendored from Intel oneAPI DPC++ Compatibility Tool +2025.3 (https://github.com/oneapi-src/SYCLomatic), are under the Apache License v2.0 with LLVM Exceptions +(SPDX: Apache-2.0 WITH LLVM-exception; Copyright (C) Intel Corporation): +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the Unified Memory Framework: +============================================================================== +The Unified Memory Framework contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. diff --git a/sycl/include/dpct/atomic.hpp b/sycl/include/dpct/atomic.hpp new file mode 100644 index 0000000..2bbecc9 --- /dev/null +++ b/sycl/include/dpct/atomic.hpp @@ -0,0 +1,868 @@ +//==---- atomic.hpp -------------------------------*- C++ -*----------------==// +// +// Copyright (C) Intel Corporation +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// See https://llvm.org/LICENSE.txt for license information. +// +//===----------------------------------------------------------------------===// + +#ifndef __DPCT_ATOMIC_HPP__ +#define __DPCT_ATOMIC_HPP__ + +#include + +namespace dpct { + +/// Atomically add the value operand to the value at the addr and assign the +/// result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to add to the value at \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_add(T *addr, T operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_add(operand); +} + +template +inline T1 atomic_fetch_add(T1 *addr, T2 operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_add(operand); +} + +template +inline sycl::half2 atomic_fetch_add(sycl::half2 *addr, sycl::half2 operand) { + auto atm = sycl::atomic_ref( + *reinterpret_cast(addr)); + + union { + unsigned i; + sycl::half2 h; + } old{0}, output{0}; + + while (true) { + old.i = atm.load(); + output.h = old.h + operand; + if (atm.compare_exchange_strong(old.i, output.i)) + break; + } + + return output.h; +} + +/// Atomically add the value operand to the value at the addr and assign the +/// result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to add to the value at \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_add(T *addr, T operand, + sycl::memory_order memoryOrder) { + switch (memoryOrder) { + case sycl::memory_order::relaxed: + return atomic_fetch_add(addr, operand); + case sycl::memory_order::acq_rel: + return atomic_fetch_add(addr, operand); + case sycl::memory_order::seq_cst: + return atomic_fetch_add(addr, operand); + default: + assert(false && "Invalid memory_order for atomics. Valid memory_order for " + "atomics are: sycl::memory_order::relaxed, " + "sycl::memory_order::acq_rel, sycl::memory_order::seq_cst!"); + } +} + +template +inline T1 atomic_fetch_add(T1 *addr, T2 operand, + sycl::memory_order memoryOrder) { + atomic_fetch_add(addr, operand, memoryOrder); +} + +/// Atomically subtract the value operand from the value at the addr and assign +/// the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to subtract from the value at \p addr +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_sub(T *addr, T operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_sub(operand); +} + +template +inline T1 atomic_fetch_sub(T1 *addr, T2 operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_sub(operand); +} + +/// Atomically subtract the value operand from the value at the addr and assign +/// the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to subtract from the value at \p addr +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_sub(T *addr, T operand, + sycl::memory_order memoryOrder) { + switch (memoryOrder) { + case sycl::memory_order::relaxed: + return atomic_fetch_sub(addr, operand); + case sycl::memory_order::acq_rel: + return atomic_fetch_sub(addr, operand); + case sycl::memory_order::seq_cst: + return atomic_fetch_sub(addr, operand); + default: + assert(false && "Invalid memory_order for atomics. Valid memory_order for " + "atomics are: sycl::memory_order::relaxed, " + "sycl::memory_order::acq_rel, sycl::memory_order::seq_cst!"); + } +} + +template +inline T1 atomic_fetch_sub(T1 *addr, T2 operand, + sycl::memory_order memoryOrder) { + atomic_fetch_sub(addr, operand, memoryOrder); +} + +/// Atomically perform a bitwise AND between the value operand and the value at the addr +/// and assign the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to use in bitwise AND operation with the value at the \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_and(T *addr, T operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_and(operand); +} + +template +inline T1 atomic_fetch_and(T1 *addr, T2 operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_and(operand); +} + +/// Atomically perform a bitwise AND between the value operand and the value at the addr +/// and assign the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to use in bitwise AND operation with the value at the \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_and(T *addr, T operand, + sycl::memory_order memoryOrder) { + switch (memoryOrder) { + case sycl::memory_order::relaxed: + return atomic_fetch_and(addr, operand); + case sycl::memory_order::acq_rel: + return atomic_fetch_and(addr, operand); + case sycl::memory_order::seq_cst: + return atomic_fetch_and(addr, operand); + default: + assert(false && "Invalid memory_order for atomics. Valid memory_order for " + "atomics are: sycl::memory_order::relaxed, " + "sycl::memory_order::acq_rel, sycl::memory_order::seq_cst!"); + } +} + +template +inline T1 atomic_fetch_and(T1 *addr, T2 operand, + sycl::memory_order memoryOrder) { + atomic_fetch_and(addr, operand, memoryOrder); +} + +/// Atomically or the value at the addr with the value operand, and assign +/// the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to use in bitwise OR operation with the value at the \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_or(T *addr, T operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_or(operand); +} + +template +inline T1 atomic_fetch_or(T1 *addr, T2 operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_or(operand); +} + +/// Atomically or the value at the addr with the value operand, and assign +/// the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to use in bitwise OR operation with the value at the \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_or(T *addr, T operand, + sycl::memory_order memoryOrder) { + switch (memoryOrder) { + case sycl::memory_order::relaxed: + return atomic_fetch_or(addr, operand); + case sycl::memory_order::acq_rel: + return atomic_fetch_or(addr, operand); + case sycl::memory_order::seq_cst: + return atomic_fetch_or(addr, operand); + default: + assert(false && "Invalid memory_order for atomics. Valid memory_order for " + "atomics are: sycl::memory_order::relaxed, " + "sycl::memory_order::acq_rel, sycl::memory_order::seq_cst!"); + } +} + +template +inline T1 atomic_fetch_or(T1 *addr, T2 operand, + sycl::memory_order memoryOrder) { + atomic_fetch_or(addr, operand, memoryOrder); +} + +/// Atomically xor the value at the addr with the value operand, and assign +/// the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to use in bitwise XOR operation with the value at the \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_xor(T *addr, T operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_xor(operand); +} + +template +inline T1 atomic_fetch_xor(T1 *addr, T2 operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_xor(operand); +} + +/// Atomically xor the value at the addr with the value operand, and assign +/// the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to use in bitwise XOR operation with the value at the \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_xor(T *addr, T operand, + sycl::memory_order memoryOrder) { + switch (memoryOrder) { + case sycl::memory_order::relaxed: + return atomic_fetch_xor(addr, operand); + case sycl::memory_order::acq_rel: + return atomic_fetch_xor(addr, operand); + case sycl::memory_order::seq_cst: + return atomic_fetch_xor(addr, operand); + default: + assert(false && "Invalid memory_order for atomics. Valid memory_order for " + "atomics are: sycl::memory_order::relaxed, " + "sycl::memory_order::acq_rel, sycl::memory_order::seq_cst!"); + } +} + +template +inline T1 atomic_fetch_xor(T1 *addr, T2 operand, + sycl::memory_order memoryOrder) { + atomic_fetch_xor(addr, operand, memoryOrder); +} + +/// Atomically calculate the minimum of the value at addr and the value operand +/// and assign the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_min(T *addr, T operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_min(operand); +} + +template +inline T1 atomic_fetch_min(T1 *addr, T2 operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_min(operand); +} + +/// Atomically calculate the minimum of the value at addr and the value operand +/// and assign the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_min(T *addr, T operand, + sycl::memory_order memoryOrder) { + switch (memoryOrder) { + case sycl::memory_order::relaxed: + return atomic_fetch_min(addr, operand); + case sycl::memory_order::acq_rel: + return atomic_fetch_min(addr, operand); + case sycl::memory_order::seq_cst: + return atomic_fetch_min(addr, operand); + default: + assert(false && "Invalid memory_order for atomics. Valid memory_order for " + "atomics are: sycl::memory_order::relaxed, " + "sycl::memory_order::acq_rel, sycl::memory_order::seq_cst!"); + } +} + +template +inline T1 atomic_fetch_min(T1 *addr, T2 operand, + sycl::memory_order memoryOrder) { + atomic_fetch_min(addr, operand, memoryOrder); +} + +/// Atomically calculate the maximum of the value at addr and the value operand +/// and assign the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_max(T *addr, T operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_max(operand); +} + +template +inline T1 atomic_fetch_max(T1 *addr, T2 operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.fetch_max(operand); +} + +/// Atomically calculate the maximum of the value at addr and the value operand +/// and assign the result to the value at addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_fetch_max(T *addr, T operand, + sycl::memory_order memoryOrder) { + switch (memoryOrder) { + case sycl::memory_order::relaxed: + return atomic_fetch_max(addr, operand); + case sycl::memory_order::acq_rel: + return atomic_fetch_max(addr, operand); + case sycl::memory_order::seq_cst: + return atomic_fetch_max(addr, operand); + default: + assert(false && "Invalid memory_order for atomics. Valid memory_order for " + "atomics are: sycl::memory_order::relaxed, " + "sycl::memory_order::acq_rel, sycl::memory_order::seq_cst!"); + } +} + +template +inline T1 atomic_fetch_max(T1 *addr, T2 operand, + sycl::memory_order memoryOrder) { + atomic_fetch_max(addr, operand, memoryOrder); +} + +/// Atomically set \p operand to the value stored in \p addr, if old value stored in +/// \p addr is equal to zero or greater than \p operand, else decrease the value stored +/// in \p addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The threshold value. +/// \param memoryOrder The memory ordering used. +/// \returns The old value stored in \p addr. +template +inline unsigned int atomic_fetch_compare_dec(unsigned int *addr, + unsigned int operand) { + auto atm = sycl::atomic_ref(addr[0]); + unsigned int old; + + while (true) { + old = atm.load(); + if (old == 0 || old > operand) { + if (atm.compare_exchange_strong(old, operand)) + break; + } else if (atm.compare_exchange_strong(old, old - 1)) + break; + } + + return old; +} + +/// Atomically increment the value stored in \p addr if old value stored in \p +/// addr is less than \p operand, else set 0 to the value stored in \p addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The threshold value. +/// \param memoryOrder The memory ordering used. +/// \returns The old value stored in \p addr. +template +inline unsigned int atomic_fetch_compare_inc(unsigned int *addr, + unsigned int operand) { + auto atm = sycl::atomic_ref(addr[0]); + unsigned int old; + while (true) { + old = atm.load(); + if (old >= operand) { + if (atm.compare_exchange_strong(old, 0)) + break; + } else if (atm.compare_exchange_strong(old, old + 1)) + break; + } + return old; +} + +/// Atomically increment the value stored in \p addr if old value stored in \p +/// addr is less than \p operand, else set 0 to the value stored in \p addr. +/// \param [in, out] addr The pointer to the data. +/// \param operand The threshold value. +/// \param memoryOrder The memory ordering used. +/// \returns The old value stored in \p addr. +template +inline unsigned int +atomic_fetch_compare_inc(unsigned int *addr, unsigned int operand, + sycl::memory_order memoryOrder) { + switch (memoryOrder) { + case sycl::memory_order::relaxed: + return atomic_fetch_compare_inc(addr, + operand); + case sycl::memory_order::acq_rel: + return atomic_fetch_compare_inc(addr, + operand); + case sycl::memory_order::seq_cst: + return atomic_fetch_compare_inc(addr, + operand); + default: + assert(false && "Invalid memory_order for atomics. Valid memory_order for " + "atomics are: sycl::memory_order::relaxed, " + "sycl::memory_order::acq_rel, sycl::memory_order::seq_cst!"); + } +} + +/// Atomically exchange the value at the address addr with the value operand. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to be exchanged with the value pointed by \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_exchange(T *addr, T operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.exchange(operand); +} + +template +inline T1 atomic_exchange(T1 *addr, T2 operand) { + auto atm = + sycl::atomic_ref(addr[0]); + return atm.exchange(operand); +} + +/// Atomically exchange the value at the address addr with the value operand. +/// \param [in, out] addr The pointer to the data. +/// \param operand The value to be exchanged with the value pointed by \p addr. +/// \param memoryOrder The memory ordering used. +/// \returns The value at the \p addr before the call. +template +inline T atomic_exchange(T *addr, T operand, + sycl::memory_order memoryOrder) { + switch (memoryOrder) { + case sycl::memory_order::relaxed: + return atomic_exchange(addr, operand); + case sycl::memory_order::acq_rel: + return atomic_exchange(addr, operand); + case sycl::memory_order::seq_cst: + return atomic_exchange(addr, operand); + default: + assert(false && "Invalid memory_order for atomics. Valid memory_order for " + "atomics are: sycl::memory_order::relaxed, " + "sycl::memory_order::acq_rel, sycl::memory_order::seq_cst!"); + } +} + +template +inline T1 atomic_exchange(T1 *addr, T2 operand, + sycl::memory_order memoryOrder) { + atomic_exchange(addr, operand, memoryOrder); +} + +/// Atomically compare the value at \p addr to the value expected and exchange +/// with the value desired if the value at \p addr is equal to the value expected. +/// Returns the value at the \p addr before the call. +/// \param [in, out] addr Multi_ptr. +/// \param expected The value to compare against the value at \p addr. +/// \param desired The value to assign to \p addr if the value at \p addr is expected. +/// \param success The memory ordering used when comparison succeeds. +/// \param fail The memory ordering used when comparison fails. +/// \returns The value at the \p addr before the call. +template +T atomic_compare_exchange_strong( + sycl::multi_ptr addr, T expected, T desired, + sycl::memory_order success = sycl::memory_order::relaxed, + sycl::memory_order fail = sycl::memory_order::relaxed) { + auto atm = sycl::atomic_ref(*addr); + + atm.compare_exchange_strong(expected, desired, success, fail); + return expected; +} + +template +T1 atomic_compare_exchange_strong( + sycl::multi_ptr addr, T2 expected, T3 desired, + sycl::memory_order success = sycl::memory_order::relaxed, + sycl::memory_order fail = sycl::memory_order::relaxed) { + auto atm = + sycl::atomic_ref(*addr); + T1 expected_value = expected; + atm.compare_exchange_strong(expected_value, desired, success, fail); + return expected_value; +} + +/// Atomically compare the value at \p addr to the value expected and exchange +/// with the value desired if the value at \p addr is equal to the value expected. +/// Returns the value at the \p addr before the call. +/// \param [in] addr The pointer to the data. +/// \param expected The value to compare against the value at \p addr. +/// \param desired The value to assign to \p addr if the value at \p addr is expected. +/// \param success The memory ordering used when comparison succeeds. +/// \param fail The memory ordering used when comparison fails. +/// \returns The value at the \p addr before the call. +template +T atomic_compare_exchange_strong( + T *addr, T expected, T desired, + sycl::memory_order success = sycl::memory_order::relaxed, + sycl::memory_order fail = sycl::memory_order::relaxed) { + auto atm = + sycl::atomic_ref(addr[0]); + atm.compare_exchange_strong(expected, desired, success, fail); + return expected; +} + +template +T1 atomic_compare_exchange_strong( + T1 *addr, T2 expected, T3 desired, + sycl::memory_order success = sycl::memory_order::relaxed, + sycl::memory_order fail = sycl::memory_order::relaxed) { + T1 expected_value = expected; + auto atm = + sycl::atomic_ref(addr[0]); + atm.compare_exchange_strong(expected_value, desired, success, fail); + return expected_value; +} + +/// Atomic extension to implement standard APIs in std::atomic +namespace detail{ +template struct IsValidAtomicType { + static constexpr bool value = + (std::is_same::value || std::is_same::value || + std::is_same::value || std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value || std::is_same::value || + std::is_pointer::value); +}; +} // namespace detail + +template +class atomic { + static_assert( + detail::IsValidAtomicType::value, + "Invalid atomic type. Valid types are int, unsigned int, long, " + "unsigned long, long long, unsigned long long, float, double " + "and pointer types"); + T __d; + +public: + /// default memory synchronization order + static constexpr sycl::memory_order default_read_order = + sycl::atomic_ref::default_read_order; + static constexpr sycl::memory_order default_write_order = + sycl::atomic_ref::default_write_order; + static constexpr sycl::memory_scope default_scope = DefaultScope; + static constexpr sycl::memory_order default_read_modify_write_order = + DefaultOrder; + + /// Default constructor. + constexpr atomic() noexcept = default; + /// Constructor with initialize value. + constexpr atomic(T d) noexcept : __d(d){}; + + /// atomically replaces the value of the referenced object with a non-atomic argument + /// \param operand The value to replace the pointed value. + /// \param memoryOrder The memory ordering used. + /// \param memoryScope The memory scope used. + void store(T operand, sycl::memory_order memoryOrder = default_write_order, + sycl::memory_scope memoryScope = default_scope) noexcept { + sycl::atomic_ref atm(__d); + atm.store(operand, memoryOrder, memoryScope); + } + + /// atomically obtains the value of the referenced object + /// \param memoryOrder The memory ordering used. + /// \param memoryScope The memory scope used. + /// \returns The value of the referenced object + T load(sycl::memory_order memoryOrder = default_read_order, + sycl::memory_scope memoryScope = default_scope) const noexcept { + sycl::atomic_ref atm( + const_cast(__d)); + return atm.load(memoryOrder, memoryScope); + } + + /// atomically replaces the value of the referenced object and obtains the value held previously + /// \param operand The value to replace the pointed value. + /// \param memoryOrder The memory ordering used. + /// \param memoryScope The memory scope used. + /// \returns The value of the referenced object before the call. + T exchange(T operand, + sycl::memory_order memoryOrder = default_read_modify_write_order, + sycl::memory_scope memoryScope = default_scope) noexcept { + + sycl::atomic_ref atm(__d); + return atm.exchange(operand, memoryOrder, memoryScope); + } + + /// atomically compares the value of the referenced object with non-atomic argument + /// and performs atomic exchange if equal or atomic load if not + /// \param expected The value expected to be found in the object referenced by the atomic_ref object + /// \param desired The value to store in the referenced object if it is as expected + /// \param success The memory models for the read-modify-write + /// \param failure The memory models for load operations + /// \param memoryScope The memory scope used. + /// \returns true if the referenced object was successfully changed, false otherwise. + bool compare_exchange_weak( + T &expected, T desired, + sycl::memory_order success, sycl::memory_order failure, + sycl::memory_scope memoryScope = default_scope) noexcept { + sycl::atomic_ref atm(__d); + return atm.compare_exchange_weak(expected, desired, success, failure, memoryScope); + } + /// \param expected The value expected to be found in the object referenced by the atomic_ref object + /// \param desired The value to store in the referenced object if it is as expected + /// \param memoryOrder The memory synchronization ordering for operations + /// \param memoryScope The memory scope used. + /// \returns true if the referenced object was successfully changed, false otherwise. + bool compare_exchange_weak(T &expected, T desired, + sycl::memory_order memoryOrder = default_read_modify_write_order, + sycl::memory_scope memoryScope = default_scope) noexcept { + sycl::atomic_ref atm(__d); + return atm.compare_exchange_weak(expected, desired, memoryOrder, memoryScope); + } + + /// atomically compares the value of the referenced object with non-atomic argument + /// and performs atomic exchange if equal or atomic load if not + /// \param expected The value expected to be found in the object referenced by the atomic_ref object + /// \param desired The value to store in the referenced object if it is as expected + /// \param success The memory models for the read-modify-write + /// \param failure The memory models for load operations + /// \param memoryScope The memory scope used. + /// \returns true if the referenced object was successfully changed, false otherwise. + bool compare_exchange_strong( + T &expected, T desired, + sycl::memory_order success, sycl::memory_order failure, + sycl::memory_scope memoryScope = default_scope) noexcept { + + sycl::atomic_ref atm(__d); + return atm.compare_exchange_strong(expected, desired, success, failure, memoryScope); + } + /// \param expected The value expected to be found in the object referenced by the atomic_ref object + /// \param desired The value to store in the referenced object if it is as expected + /// \param memoryOrder The memory synchronization ordering for operations + /// \param memoryScope The memory scope used. + /// \returns true if the referenced object was successfully changed, false otherwise. + bool compare_exchange_strong(T &expected, T desired, + sycl::memory_order memoryOrder = default_read_modify_write_order, + sycl::memory_scope memoryScope = default_scope) noexcept { + sycl::atomic_ref atm(__d); + return atm.compare_exchange_strong(expected, desired, memoryOrder, memoryScope); + } + + /// atomically adds the argument to the value stored in the atomic object and obtains the value held previously + /// \param operand The other argument of arithmetic addition + /// \param memoryOrder The memory ordering used. + /// \param memoryScope The memory scope used. + /// \returns The value of the referenced object before the call. + T fetch_add(T operand, + sycl::memory_order memoryOrder = default_read_modify_write_order, + sycl::memory_scope memoryScope = default_scope) noexcept { + + sycl::atomic_ref atm(__d); + return atm.fetch_add(operand, memoryOrder, memoryScope); + } + + /// atomically subtracts the argument from the value stored in the atomic object and obtains the value held previously + /// \param operand The other argument of arithmetic subtraction + /// \param memoryOrder The memory ordering used. + /// \param memoryScope The memory scope used. + /// \returns The value of the referenced object before the call. + T fetch_sub(T operand, + sycl::memory_order memoryOrder = default_read_modify_write_order, + sycl::memory_scope memoryScope = default_scope) noexcept { + + sycl::atomic_ref atm(__d); + return atm.fetch_sub(operand, memoryOrder, memoryScope); + } +}; + +} // namespace dpct +#endif // __DPCT_ATOMIC_HPP__ diff --git a/sycl/include/dpct/bindless_images.hpp b/sycl/include/dpct/bindless_images.hpp new file mode 100644 index 0000000..042321d --- /dev/null +++ b/sycl/include/dpct/bindless_images.hpp @@ -0,0 +1,2061 @@ +//===--- bindless_images.hpp ----------------------*- C++ -*---------------===// +// +// Copyright (C) Intel Corporation +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// See https://llvm.org/LICENSE.txt for license information. +// +//===----------------------------------------------------------------------===// + +#ifndef __DPCT_BINDLESS_IMAGE_HPP__ +#define __DPCT_BINDLESS_IMAGE_HPP__ + +#ifdef _WIN32 +// DirectX headers +#include +#include +#include +#endif // _WIN32 + +namespace dpct { +namespace experimental { + +#ifdef SYCL_EXT_ONEAPI_BINDLESS_IMAGES + +/// The wrapper structure for external memory resource handle desc +class external_mem_handle_desc { +#ifdef _WIN32 + void *handle; + const void *name; +#else + int handle; +#endif // _WIN32 + sycl::ext::oneapi::experimental::external_mem_handle_type handle_type; + size_t size_in_bytes; + int flags; + +public: + external_mem_handle_desc() { +#ifdef _WIN32 + handle = nullptr; + name = nullptr; +#else + handle = -1; +#endif // _WIN32 + handle_type = + sycl::ext::oneapi::experimental::external_mem_handle_type::opaque_fd; + size_in_bytes = 0; + flags = 0; + } + +#ifdef _WIN32 + /// handle setter + /// \param [in] win32_handle The win32 NT handle of the external memory + /// resource + void set_win32_handle(void *win32_handle) { handle = win32_handle; } + + /// name setter + /// \param [in] win32_obj_name The object of the external memory resource + void set_win32_obj_name(const void *win32_obj_name) { name = win32_obj_name; } +#else + /// fd setter + /// \param [in] fd The file descriptor of the external memory resource + void set_fd_handle(int fd) { handle = fd; } +#endif // _WIN32 + + /// handle_type setter + /// \param [in] type The type of the external memory resource handle + void set_handle_type( + sycl::ext::oneapi::experimental::external_mem_handle_type type) { + handle_type = type; + } + + /// size setter + /// \param [in] size The size (in bytes) of the external memory resource + void set_res_size(unsigned long long size) { size_in_bytes = size; } + + /// flags setter + /// \param [in] flags The flags used to handle importing of external memory + /// resource + void set_flags(int flags) { this->flags = flags; } + +#ifdef _WIN32 + /// handle getter + /// \param [out] handle The win32 NT handle of the external memory resource + void *get_win32_handle() { return handle; } + + /// name getter + /// \param [out] name The object of the external memory resource + const void *get_win32_obj_name() { return name; } +#else + /// fd getter + /// \param [out] fd The file descriptor of the external memory resource + int get_fd_handle() { return handle; } +#endif // _WIN32 + + /// handle_type getter + /// \param [out] handle_type The type of the external memory resource handle + sycl::ext::oneapi::experimental::external_mem_handle_type get_handle_type() { + return handle_type; + } + + /// size getter + /// \param [out] size The size (in bytes) of the external memory resource + unsigned long long get_res_size() { return size_in_bytes; } + + /// flags getter + /// \param [out] flags The flags used to handle importing of external memory + /// resource + int get_flags() { return flags; } +}; + +/// The wrapper structure for external image memory desc +class external_mem_img_desc { + sycl::range<3> size; + image_channel channel; + unsigned int num_levels; + sycl::ext::oneapi::experimental::image_type type; + +public: + external_mem_img_desc() { + size = sycl::range<3>{0, 0, 0}; + channel = image_channel::create(); + num_levels = 1; + type = sycl::ext::oneapi::experimental::image_type::standard; + } + + /// size setter + /// \param [in] img_dims The dimensions of the imported image resource + void set_size(sycl::range<3> img_dims) { + size = img_dims; + + for (int i = 0; i < 3; i++) { + if (size[i] == 1) { + size[i] = 0; + } + } + } + + /// image_channel setter + /// \param [in] img_ch The channel info of the imported image resource + void set_image_channel(image_channel img_ch) { channel = img_ch; } + + /// num_levels setter + /// \param [in] numLevels The no. of levels in the imported image resource + void set_num_levels(unsigned int num_levels) { + this->num_levels = num_levels; + + if (num_levels > 1) { + set_image_type(sycl::ext::oneapi::experimental::image_type::mipmap); + } + } + + /// type setter + /// \param [in] img_type The type of the imported image resource + void set_image_type(sycl::ext::oneapi::experimental::image_type img_type) { + type = img_type; + } + + /// size getter + /// \param [out] size The dimensions of the imported image resource + sycl::range<3> get_size() { return size; } + + /// image_channel getter + /// \param [out] image_channel The channel info of the imported image resource + image_channel get_image_channel() { return channel; } + + /// num_levels getter + /// \param [out] num_levels The no. of levels in the imported image resource + unsigned int get_num_levels() { return num_levels; } + + /// type getter + /// \param [out] type The image type of the imported image resource + sycl::ext::oneapi::experimental::image_type get_image_type() { return type; } +}; + +/// The wrapper structure for external buffer memory desc +class external_mem_buf_desc { + uint64_t size_in_bytes; + uint64_t offset; + unsigned int flags; + +public: + external_mem_buf_desc() { + size_in_bytes = 0; + offset = 0; + flags = 0; + } + + /// size setter + /// \param [in] size The size (in bytes) of the external buffer resource + void set_res_size(uint64_t size) { size_in_bytes = size; } + + /// offset setter + /// \param [in] offset The memory offset of the external buffer resource + void set_mem_offset(uint64_t offset) { this->offset = offset; } + + /// flags setter + /// \param [in] flags The flags used to import external buffer resource + void set_flags(unsigned int flags) { this->flags = flags; } + + /// size getter + /// \param [out] size_in_bytes The size (in bytes) of the external buffer res + uint64_t get_res_size() { return size_in_bytes; } + + /// offset getter + /// \param [out] offset The memory offset of the external buffer resource + uint64_t get_mem_offset() { return offset; } + + /// flags getter + /// \param [out] flags The flags used to import external buffer resource + unsigned int get_flags() { return flags; } +}; + +/// The wrapper class for external semaphore resource handle desc +class external_sem_handle_desc { +#ifdef _WIN32 + void *handle; + const void *name; +#else + int handle; +#endif // _WIN32 + sycl::ext::oneapi::experimental::external_semaphore_handle_type handle_type; + int flags; + +public: + external_sem_handle_desc() { +#ifdef _WIN32 + handle = nullptr; + name = nullptr; +#else + handle = -1; +#endif // _WIN32 + handle_type = sycl::ext::oneapi::experimental:: + external_semaphore_handle_type::opaque_fd; + flags = 0; + } + +#ifdef _WIN32 + /// handle setter + /// \param [in] win32_handle The win32 NT handle of the external semaphore + /// resource + void set_win32_handle(void *win32_handle) { handle = win32_handle; } + + /// name setter + /// \param [in] win32_obj_name The object of the external semaphore resource + void set_win32_obj_name(const void *win32_obj_name) { name = win32_obj_name; } +#else + /// fd setter + /// \param [in] fd The file descriptor of the external semaphore resource + void set_fd_handle(int fd) { handle = fd; } +#endif // _WIN32 + + /// handle_type setter + /// \param [in] type The type of the external semaphore resource handle + void set_handle_type( + sycl::ext::oneapi::experimental::external_semaphore_handle_type type) { + handle_type = type; + } + + /// flags setter + /// \param [in] flags The flags used to handle importing of external semaphore + /// resource + void set_flags(int flags) { this->flags = flags; } + +#ifdef _WIN32 + /// handle getter + /// \param [out] handle The win32 NT handle of the external semaphore resource + void *get_win32_handle() { return handle; } + + /// name getter + /// \param [out] name The object of the external semaphore resource + const void *get_win32_obj_name() { return name; } +#else + /// fd getter + /// \param [out] fd The file descriptor of the external semaphore resource + int get_fd_handle() { return handle; } +#endif // _WIN32 + + /// handle_type getter + /// \param [out] handle_type The type of the external semaphore resource + /// handle + sycl::ext::oneapi::experimental::external_semaphore_handle_type + get_handle_type() { + return handle_type; + } + + /// flags getter + /// \param [out] flags The flags used to handle importing of external + /// semaphore + int get_flags() { return flags; } +}; + +/// The wrapper structure for external semaphore signal/wait params +class external_sem_params { + uint64_t value; + +public: + external_sem_params() { value = 0; } + + /// value setter + /// \param [in] val The state value of the semaphore + void set_value(unsigned long long val) { value = val; } + + /// value getter + /// \param [out] value The state value of the semaphore + unsigned long long get_value() { return value; } +}; + +/// The wrapper class of external semaphore +class external_sem_wrapper { + sycl::ext::oneapi::experimental::external_semaphore ext_sem; + sycl::ext::oneapi::experimental::external_semaphore_handle_type + ext_sem_handle_type; + +public: + /// Create external semaphore wrapper. + /// \param [in] ext_sem The external semaphore resource object + /// \param [in] ext_sem_handle_type The external semaphore resource handle + /// type + external_sem_wrapper( + sycl::ext::oneapi::experimental::external_semaphore ext_sem, + sycl::ext::oneapi::experimental::external_semaphore_handle_type + ext_sem_handle_type) { + this->ext_sem = ext_sem; + this->ext_sem_handle_type = ext_sem_handle_type; + } + + /// destory external semaphore resource + ~external_sem_wrapper() { + sycl::ext::oneapi::experimental::release_external_semaphore( + ext_sem, get_default_queue()); + } + + /// ext_sem getter + /// \param [out] ext_sem The external semaphore resource object + sycl::ext::oneapi::experimental::external_semaphore get() { return ext_sem; } + + /// ext_sem_handle_type getter + /// \param [out] ext_sem_handle_type The external semaphore resource handle + /// type + sycl::ext::oneapi::experimental::external_semaphore_handle_type + get_handle_type() { + return ext_sem_handle_type; + } +}; + +/// The wrapper class of bindless image memory handle. +class image_mem_wrapper { +public: + /// Create bindless image memory wrapper. + /// \tparam dimensions The dimensions of image memory. + /// \param [in] channel The image channel used to create bindless image + /// \param [in] range The sizes of each dimension of bindless image memory. + /// memory. + template + image_mem_wrapper(image_channel channel, sycl::range range, + sycl::ext::oneapi::experimental::image_type type = + sycl::ext::oneapi::experimental::image_type::standard, + unsigned int num_levels = 1) + : _channel(channel) { + unsigned array_size = 1; + if (type == sycl::ext::oneapi::experimental::image_type::array) { + assert(dimensions == 3); + array_size = range[2]; + range[2] = 0; + } + _desc = sycl::ext::oneapi::experimental::image_descriptor( + range, _channel.get_channel_num(), _channel.get_channel_type(), type, + num_levels, array_size); + auto q = get_default_queue(); + _handle = alloc_image_mem(_desc, q); + init_mip_level_wrappers(q); + } + /// Create bindless image memory wrapper. + /// \param [in] channel The image channel used to create bindless image + /// \param [in] width The width of bindless image memory. + /// \param [in] height The height of bindless image memory. + /// \param [in] depth The depth of bindless image memory. + image_mem_wrapper(image_channel channel, size_t width, size_t height = 0, + size_t depth = 0) + : image_mem_wrapper(channel, {width, height, depth}) {} + /// Create bindless image memory wrapper. + /// \param [in] desc The image descriptor used to create bindless image + image_mem_wrapper( + const sycl::ext::oneapi::experimental::image_descriptor *desc) + : _desc(*desc) { + _channel.set_channel_type(desc->channel_type); + _channel.set_channel_num(desc->num_channels); + auto q = get_default_queue(); + _handle = alloc_image_mem(_desc, q); + } + /// Create bindless image memory wrapper. + /// \param [in] desc The image descriptor of bindless image. + /// \param [in] img_mem_handle The memory handle of bindless image. + image_mem_wrapper( + sycl::ext::oneapi::experimental::image_descriptor desc, + sycl::ext::oneapi::experimental::image_mem_handle img_mem_handle) + : _desc(desc), _handle(img_mem_handle) { + _channel.set_channel_type(_desc.channel_type); +#if (__SYCL_COMPILER_VERSION && __SYCL_COMPILER_VERSION >= 20240725) + _channel.set_channel_num(_desc.num_channels); +#endif + auto q = get_default_queue(); + init_mip_level_wrappers(q); + } + /// Create bindless image memory wrapper. + /// \param [in] extMem SYCL external memory resource object. + /// \param [in] ext_img_mem_desc The img desc of the imported image resource. + image_mem_wrapper(sycl::ext::oneapi::experimental::external_mem extMem, + external_mem_img_desc *ext_img_mem_desc) { + auto q = get_default_queue(); + unsigned int array_size = 1; + + _channel = ext_img_mem_desc->get_image_channel(); + _desc = sycl::ext::oneapi::experimental::image_descriptor( + ext_img_mem_desc->get_size(), _channel.get_channel_num(), + _channel.get_channel_type(), ext_img_mem_desc->get_image_type(), + ext_img_mem_desc->get_num_levels(), array_size); + _handle = sycl::ext::oneapi::experimental::map_external_image_memory( + extMem, _desc, q); + + init_mip_level_wrappers(q); + } + /// Create bindless image memory wrapper. + /// \param [in] desc The image descriptor of bindless image. + /// \param [in] num_levels Number of mipmap levels to allocate + image_mem_wrapper(sycl::ext::oneapi::experimental::image_descriptor desc, + unsigned int num_levels) + : _desc(desc) { + _desc.type = sycl::ext::oneapi::experimental::image_type::mipmap; + _desc.num_levels = num_levels; + auto q = get_default_queue(); + _handle = alloc_image_mem(_desc, q); + init_mip_level_wrappers(q); + } + + image_mem_wrapper(const image_mem_wrapper &) = delete; + image_mem_wrapper &operator=(const image_mem_wrapper &) = delete; + /// Destroy bindless image memory wrapper. + ~image_mem_wrapper() { + if (_sub_wrappers) { + std::destroy_n(_sub_wrappers, _desc.num_levels); + std::free(_sub_wrappers); + } + free_image_mem(_handle, _desc.type, get_default_queue()); + } + /// Get the image channel of the bindless image memory. + /// \returns The image channel of bindless image memory. + image_channel get_channel() const noexcept { return _channel; } + /// Get the sizes of each dimension of the bindless image memory. + /// \returns The sizes of each dimension of bindless image memory. + sycl::range<3> get_range() const { + return {_desc.width, _desc.height, _desc.depth}; + } + /// Get the image descriptor of the bindless image memory. + /// \returns The image descriptor of bindless image memory. + const sycl::ext::oneapi::experimental::image_descriptor & + get_desc() const noexcept { + return _desc; + } + /// Get the image handle of the bindless image memory. + /// \returns The image handle of bindless image memory. + sycl::ext::oneapi::experimental::image_mem_handle + get_handle() const noexcept { + return _handle; + } + /// Get the image mip level of the bindless image memory. + /// \returns The image mip level of the bindless image memory. + image_mem_wrapper *get_mip_level(unsigned int level) { + if (_desc.type == sycl::ext::oneapi::experimental::image_type::standard) { + assert(level == 0); + return this; + } + + assert(_desc.type == sycl::ext::oneapi::experimental::image_type::mipmap); + return _sub_wrappers + level; + } + + sycl::ext::oneapi::experimental::image_type get_image_type(void) { + return _desc.type; + } + +private: + image_mem_wrapper( + const image_channel &channel, + const sycl::ext::oneapi::experimental::image_descriptor &desc, + const sycl::ext::oneapi::experimental::image_mem_handle &handle) + : _channel(channel), _desc(desc), _handle(handle) {} + + /// Initialize image mem wrappers for all the levels of mipmap image + /// \param [in] q The Queue to be used to query the mip levels + void init_mip_level_wrappers(sycl::queue q) { + auto num_levels = _desc.num_levels; + if (_desc.type == sycl::ext::oneapi::experimental::image_type::mipmap) { + assert(num_levels > 1); + _sub_wrappers = (image_mem_wrapper *)std::malloc( + sizeof(image_mem_wrapper) * num_levels); + for (unsigned i = 0; i < num_levels; ++i) + new (_sub_wrappers + i) image_mem_wrapper( + _channel, _desc.get_mip_level_desc(i), + sycl::ext::oneapi::experimental::get_mip_level_mem_handle( + _handle, i, q.get_device(), q.get_context())); + } + } + + image_channel _channel; + sycl::ext::oneapi::experimental::image_descriptor _desc; + sycl::ext::oneapi::experimental::image_mem_handle _handle; + image_mem_wrapper *_sub_wrappers{nullptr}; +}; + +/// The base wrapper class of external memory resource handle. +class external_mem_wrapper_base { +public: + /// Cleans up the external mem wrapper by releasing the SYCL external + /// memory handle + virtual ~external_mem_wrapper_base() {} + + external_mem_wrapper_base(const external_mem_wrapper_base &) = delete; + + external_mem_wrapper_base & + operator=(const external_mem_wrapper_base &) = delete; + + const sycl::ext::oneapi::experimental::external_mem + get_external_mem() const noexcept { + return _res_external_mem; + } + + /// Map the buf/texture resource memory and get its pointer/mem handle. + /// \param [in] q The queue used to map the resource with. + void map_resource(sycl::queue q) { + if (_res_is_buffer) { + if (_res_buf_ptr) { + throw std::runtime_error("Resource is already mapped! " + "Resource cannot be mapped more than once."); + } + +#if (__SYCL_COMPILER_VERSION && __SYCL_COMPILER_VERSION >= 20240823) + _res_buf_ptr = + sycl::ext::oneapi::experimental::map_external_linear_memory( + get_external_mem(), 0, _res_size_bytes, q); +#else + throw std::runtime_error( + "Mapping a buffer resoure is not yet supported!"); +#endif + } else { + if (_res_img_mem_wrapper_ptr) { + throw std::runtime_error("Resource is already mapped! " + "Resource cannot be mapped more than once."); + } + + auto img_mem_handle = + sycl::ext::oneapi::experimental::map_external_image_memory( + get_external_mem(), _res_img_desc, q); + + _res_img_mem_wrapper_ptr = + new image_mem_wrapper(_res_img_desc, img_mem_handle); + } + } + + /// Gets the pointer and size of the mapped resource + /// \param [out] ptr The pointer to the resource memory. + /// \param [out] size The size of the resource memory. + /// and resource size. + void get_mapped_pointer(void **ptr, size_t *size) { + if (!_res_is_buffer) { + throw std::runtime_error( + "Non buffer resouce cannot be accessed as a pointer!"); + } + + *ptr = _res_buf_ptr; + if (!*ptr) { + throw std::runtime_error( + "Resource is not mapped! " + "Resource should be mapped before accessing its memory"); + } + + *size = _res_size_bytes; + } + + /// Returns mapped memory as image_mem_wrapper* + image_mem_wrapper *get_mapped_mipmapped_array() { + if (_res_is_buffer) { + throw std::runtime_error( + "Buffer resource cannot be accessed as an array!"); + } + if (!_res_img_mem_wrapper_ptr) { + throw std::runtime_error( + "Resource is not mapped! " + "Resource should be mapped before accessing its memory."); + } + + return _res_img_mem_wrapper_ptr; + } + + /// Returns mapped subresource memory as image_mem_wrapper* + /// \param [in] array_index The layer of the image array to be returned. + /// \param [in] mip_level The level of the mipmap image to be returned. + image_mem_wrapper *get_sub_resource_mapped_array(unsigned int array_index, + unsigned int mip_level) { + if (_res_is_buffer) { + throw std::runtime_error( + "Buffer resouce cannot be accessed as an array!"); + } + if (array_index != 0) { + throw std::runtime_error("Retrieving a particular layer from image array " + "is not yet supported!"); + } + if (array_index >= _res_img_desc.array_size) { + throw std::runtime_error( + "Array index requested exceeds total array size in resource!"); + } + if (mip_level >= _res_img_desc.num_levels) { + throw std::runtime_error( + "Mip level requested exceeds total num of levels in resource!"); + } + if (!_res_img_mem_wrapper_ptr) { + throw std::runtime_error( + "Resouce is not mapped! " + "Resource should be mapped before accessing its memory"); + } + + return (mip_level == 0) + ? _res_img_mem_wrapper_ptr + : _res_img_mem_wrapper_ptr->get_mip_level(mip_level); + } + + /// Unmap the buf/texture resource memory and get its pointer/mem handle. + /// \param [in] q The queue used to unmap the resource with. + void unmap_resource(sycl::queue q) { + if (_res_is_buffer) { + if (!_res_buf_ptr) { + throw std::runtime_error("Resource is not mapped! " + "Resource should be mapped before unmapping."); + } + + _res_buf_ptr = nullptr; + + throw std::runtime_error( + "Unmapping a buffer resoure is not yet supported!"); + } else { + if (!_res_img_mem_wrapper_ptr) { + throw std::runtime_error("Resource is not mapped! " + "Resource should be mapped before unmapping."); + } + + delete _res_img_mem_wrapper_ptr; + _res_img_mem_wrapper_ptr = nullptr; + } + } + +protected: + /// Init external mem handle for a given resource. + external_mem_wrapper_base( + sycl::ext::oneapi::experimental::external_mem external_mem, + unsigned reg_flags) + : _res_external_mem(external_mem), _res_reg_flags(reg_flags) {} + + unsigned _res_reg_flags = 0; + bool _res_is_buffer = false; + size_t _res_size_bytes = 0; + + sycl::ext::oneapi::experimental::image_descriptor _res_img_desc; + sycl::ext::oneapi::experimental::external_mem _res_external_mem; + +private: + void *_res_buf_ptr = nullptr; + image_mem_wrapper *_res_img_mem_wrapper_ptr = nullptr; +}; + +#ifdef _WIN32 +class external_mem_wrapper : public external_mem_wrapper_base { +public: + /// Creates external memory resource wrapper for a given DX11 resource. + /// \param [in] d3d11_res Pointer to the ID3D11Resource to be wrapped. + /// \param [in] reg_flags Registration flags used for resource registration. + external_mem_wrapper(ID3D11Resource *d3d11_res, unsigned reg_flags) + : _res_D3D11(d3d11_res), + external_mem_wrapper_base( + sycl::ext::oneapi::experimental::external_mem(), reg_flags) { + // Check if the resource is already registered to prevent double + // registration. + if (_res_D3D11_set.find(_res_D3D11) != _res_D3D11_set.end()) { + throw std::runtime_error("This D3D11 resource is already registered!"); + } + + // Query the information from D3D11 resource object + query_res_info(_res_D3D11); + + // Create a shared handle for the DX11 resource to enable interoperability. + _res_win_nt_handle = create_shared_handle(_res_D3D11); + + // Prepare the external memory resource descriptor for SYCL interop. + sycl::ext::oneapi::experimental::resource_win32_handle ext_mem_win_handle{ + _res_win_nt_handle}; + + sycl::ext::oneapi::experimental::external_mem_descriptor< + sycl::ext::oneapi::experimental::resource_win32_handle> + ext_mem_desc{ext_mem_win_handle, + sycl::ext::oneapi::experimental::external_mem_handle_type:: + win32_nt_dx12_resource, + _res_size_bytes}; + + // Import resource's external memory into SYCL for use with SYCL APIs. + _res_external_mem = sycl::ext::oneapi::experimental::external_mem( + sycl::ext::oneapi::experimental::import_external_memory( + ext_mem_desc, get_default_queue())); + + // Register the resource to track its uniqueness. + _res_D3D11_set.insert(_res_D3D11); + } + + /// Cleans up the external mem wrapper by releasing the SYCL external + /// memory handle and the shared handle created for the DX11 resource. + virtual ~external_mem_wrapper() { + // Release the mutex when done + _res_keyed_mutex->ReleaseSync(0); + + // Release the keyed mutex interface + _res_keyed_mutex->Release(); + + // Close the shared handle to the DX11 resource. + CloseHandle(_res_win_nt_handle); + + // Release the resource's external memory associated with the SYCL external + // mem handle. + sycl::ext::oneapi::experimental::release_external_memory( + get_external_mem(), get_default_queue()); + + // Remove the resource from the tracking set. + if (_res_D3D11_set.find(_res_D3D11) != _res_D3D11_set.end()) { + _res_D3D11_set.erase(_res_D3D11); + } + } + +private: + inline static std::set _res_D3D11_set; + + ID3D11Resource *_res_D3D11 = nullptr; + IDXGIKeyedMutex *_res_keyed_mutex = nullptr; + HANDLE _res_win_nt_handle = nullptr; + + /// Helper function to query the properties of DX11 resource + void query_res_info(ID3D11Resource *resource) { + unsigned int res_width = 0; + unsigned int res_height = 0; + unsigned int res_depth = 0; + unsigned int res_num_levels = 1; + unsigned int res_arr_size = 1; + + image_channel channel; + + // Get the dimension info of DX11 resource + D3D11_RESOURCE_DIMENSION dimension; + resource->GetType(&dimension); + + switch (dimension) { + case D3D11_RESOURCE_DIMENSION_BUFFER: { + _res_is_buffer = true; + + D3D11_BUFFER_DESC desc; + ((ID3D11Buffer *)resource)->GetDesc(&desc); + + _res_size_bytes = desc.ByteWidth; + break; + } + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: { + D3D11_TEXTURE1D_DESC desc; + ((ID3D11Texture1D *)resource)->GetDesc(&desc); + + res_width = desc.Width; + res_arr_size = desc.ArraySize; + res_num_levels = (desc.MipLevels ? desc.MipLevels : 1); + + channel = get_img_ch_info(desc.Format); + _res_size_bytes = res_width; + break; + } + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: { + D3D11_TEXTURE2D_DESC desc; + ((ID3D11Texture2D *)resource)->GetDesc(&desc); + + res_width = desc.Width; + res_height = desc.Height; + res_arr_size = desc.ArraySize; + res_num_levels = (desc.MipLevels ? desc.MipLevels : 1); + + channel = get_img_ch_info(desc.Format); + _res_size_bytes = res_width * res_height; + break; + } + case D3D11_RESOURCE_DIMENSION_TEXTURE3D: { + D3D11_TEXTURE3D_DESC desc; + ((ID3D11Texture3D *)resource)->GetDesc(&desc); + + res_width = desc.Width; + res_height = desc.Height; + res_depth = desc.Depth; + res_num_levels = (desc.MipLevels ? desc.MipLevels : 1); + + channel = get_img_ch_info(desc.Format); + _res_size_bytes = res_width * res_height * res_depth; + break; + } + default: + throw std::runtime_error("Unsupported DX11 resource type!"); + break; + } + + if (!_res_is_buffer) { + if (res_arr_size > 1) { + throw std::runtime_error( + "Images with multiple array levels are not supported. " + "Only standard and mipmap images are supported!"); + } + + // Calculate the size of a resource in bytes by multiplyting its dims + // with arr size, num levels & channel size + _res_size_bytes *= + res_arr_size * res_num_levels * channel.get_total_size(); + + sycl::ext::oneapi::experimental::image_type img_type = + (res_num_levels > 1) + ? sycl::ext::oneapi::experimental::image_type::mipmap + : sycl::ext::oneapi::experimental::image_type::standard; + + _res_img_desc = sycl::ext::oneapi::experimental::image_descriptor{ + sycl::range<3>{res_width, res_height, res_depth}, + channel.get_channel_num(), + channel.get_channel_type(), + img_type, + res_num_levels, + res_arr_size}; + } + } + + /// Helper function to create shared handle for DXD11 resource + HANDLE create_shared_handle(ID3D11Resource *resource) { + HANDLE win_nt_handle = nullptr; + + IDXGIResource1 *pDXGIResource1; + resource->QueryInterface(__uuidof(IDXGIResource1), + reinterpret_cast(&pDXGIResource1)); + + if (_res_is_buffer) { + pDXGIResource1->GetSharedHandle(&win_nt_handle); + } else { + pDXGIResource1->CreateSharedHandle( + nullptr, DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE, + nullptr, &win_nt_handle); + } + + pDXGIResource1->Release(); + + // Query for the keyed mutex interface + resource->QueryInterface(__uuidof(IDXGIKeyedMutex), + reinterpret_cast(&_res_keyed_mutex)); + + // Use the keyed mutex to synchronize access to the shared resource + _res_keyed_mutex->AcquireSync(0, INFINITE); + + return win_nt_handle; + } + + /// Helper function to get the texture channel info of DX11 resource using + /// DXGI format + image_channel get_img_ch_info(DXGI_FORMAT format) { + image_channel channel; + + switch (format) { + case DXGI_FORMAT_R16G16B16A16_FLOAT: + channel = image_channel::create(); + break; + case DXGI_FORMAT_R8G8B8A8_UNORM: + channel = image_channel::create(); + break; + case DXGI_FORMAT_R16G16_FLOAT: + channel = image_channel::create(); + break; + case DXGI_FORMAT_R32_FLOAT: + channel = image_channel::create(); + break; + default: + throw std::runtime_error("Unsupported DX11 resource format!"); + break; + } + + return channel; + } +}; +#endif // _WIN32 + +namespace detail { +struct sampled_image_handle_compare { + template bool operator()(T L, T R) const { + return L.raw_handle < R.raw_handle; + } +}; + +inline std::pair &get_img_info_map( + const sycl::ext::oneapi::experimental::sampled_image_handle handle) { + static std::map, + sampled_image_handle_compare> + img_info_map; + return img_info_map[handle]; +} + +inline std::pair &get_img_info_map( + const sycl::ext::oneapi::experimental::unsampled_image_handle handle) { + static std::map, + sampled_image_handle_compare> + img_info_map; + return img_info_map[handle]; +} + +static inline size_t +get_ele_size(const sycl::ext::oneapi::experimental::image_descriptor &decs) { + size_t channel_size; + switch (decs.channel_type) { + case sycl::image_channel_type::signed_int8: + case sycl::image_channel_type::unsigned_int8: + channel_size = 1; + break; + case sycl::image_channel_type::fp16: + case sycl::image_channel_type::signed_int16: + case sycl::image_channel_type::unsigned_int16: + channel_size = 2; + break; + case sycl::image_channel_type::fp32: + case sycl::image_channel_type::signed_int32: + case sycl::image_channel_type::unsigned_int32: + channel_size = 4; + break; + default: + throw std::runtime_error("Unsupported channel_type in get_ele_size!"); + break; + } + return decs.num_channels * channel_size; +} + +static inline sycl::event +dpct_memcpy(sycl::ext::oneapi::experimental::image_mem_handle src, + const sycl::ext::oneapi::experimental::image_descriptor &desc_src, + size_t w_offset_src, size_t h_offset_src, void *dest, size_t p, + size_t w, size_t h, sycl::queue q) { + const auto ele_size = get_ele_size(desc_src); + const auto src_offset = + sycl::range<3>(w_offset_src / ele_size, h_offset_src, 0); + const auto dest_offset = sycl::range<3>(0, 0, 0); + const auto dest_extend = sycl::range<3>(p / ele_size, 0, 0); + const auto copy_extend = sycl::range<3>(w / ele_size, h, 0); + return q.ext_oneapi_copy(src, src_offset, desc_src, dest, dest_offset, + dest_extend, copy_extend); +} + +static inline std::vector dpct_memcpy_to_host( + sycl::ext::oneapi::experimental::image_mem_handle src, + const sycl::ext::oneapi::experimental::image_descriptor &desc_src, + size_t w_offset_src, size_t h_offset_src, void *dest_host_ptr, size_t s, + sycl::queue q) { + std::vector event_list; + const auto ele_size = get_ele_size(desc_src); + const auto w = desc_src.width * ele_size; + size_t offset_dest = 0; + while (s - offset_dest > w - w_offset_src) { + const auto src_offset = + sycl::range<3>(w_offset_src / ele_size, h_offset_src, 0); + const auto dest_offset = sycl::range<3>(offset_dest / ele_size, 0, 0); + const auto dest_extend = sycl::range<3>(0, 0, 0); + const auto copy_extend = + sycl::range<3>((w - w_offset_src) / ele_size, 1, 0); + event_list.push_back(q.ext_oneapi_copy(src, src_offset, desc_src, + dest_host_ptr, dest_offset, + dest_extend, copy_extend)); + offset_dest += w - w_offset_src; + w_offset_src = 0; + ++h_offset_src; + } + if (s - offset_dest > 0) { + const auto src_offset = + sycl::range<3>(w_offset_src / ele_size, h_offset_src, 0); + const auto dest_offset = sycl::range<3>(offset_dest / ele_size, 0, 0); + const auto dest_extend = sycl::range<3>(0, 0, 0); + const auto copy_extend = sycl::range<3>((s - offset_dest) / ele_size, 1, 0); + event_list.push_back(q.ext_oneapi_copy(src, src_offset, desc_src, + dest_host_ptr, dest_offset, + dest_extend, copy_extend)); + } + return event_list; +} + +static inline std::vector +dpct_memcpy(sycl::ext::oneapi::experimental::image_mem_handle src, + const sycl::ext::oneapi::experimental::image_descriptor &desc_src, + size_t w_offset_src, size_t h_offset_src, void *dest, size_t s, + sycl::queue q) { + if (dpct::detail::get_pointer_attribute(q, dest) == + dpct::detail::pointer_access_attribute::device_only) { + std::vector event_list; + dpct::detail::host_buffer buf(s, q, event_list); + auto copy_events = dpct_memcpy_to_host(src, desc_src, w_offset_src, + h_offset_src, buf.get_ptr(), s, q); + event_list.push_back(dpct::detail::dpct_memcpy( + q, dest, buf.get_ptr(), s, memcpy_direction::host_to_device, + copy_events)); + return event_list; + } + return dpct_memcpy_to_host(src, desc_src, w_offset_src, h_offset_src, dest, s, + q); +} + +static inline sycl::event +dpct_memcpy(const void *src, + sycl::ext::oneapi::experimental::image_mem_handle dest, + const sycl::ext::oneapi::experimental::image_descriptor &desc_dest, + size_t w_offset_dest, size_t h_offset_dest, size_t p, size_t w, + size_t h, sycl::queue q) { + const auto ele_size = get_ele_size(desc_dest); + const auto src_offset = sycl::range<3>(0, 0, 0); + const auto src_extend = sycl::range<3>(p / ele_size, 0, 0); + const auto dest_offset = + sycl::range<3>(w_offset_dest / ele_size, h_offset_dest, 0); + const auto copy_extend = sycl::range<3>(w / ele_size, h, 0); + // TODO: Remove const_cast after refining the signature of ext_oneapi_copy. + return q.ext_oneapi_copy(const_cast(src), src_offset, src_extend, + dest, dest_offset, desc_dest, copy_extend); +} + +static inline std::vector dpct_memcpy_from_host( + const void *src_host_ptr, + sycl::ext::oneapi::experimental::image_mem_handle dest, + const sycl::ext::oneapi::experimental::image_descriptor &desc_dest, + size_t w_offset_dest, size_t h_offset_dest, size_t s, sycl::queue q) { + std::vector event_list; + const auto ele_size = get_ele_size(desc_dest); + const auto w = desc_dest.width * ele_size; + size_t offset_src = 0; + while (s - offset_src >= w - w_offset_dest) { + const auto src_offset = sycl::range<3>(offset_src / ele_size, 0, 0); + const auto src_extend = sycl::range<3>(0, 0, 0); + const auto dest_offset = + sycl::range<3>(w_offset_dest / ele_size, h_offset_dest, 0); + const auto copy_extend = + sycl::range<3>((w - w_offset_dest) / ele_size, 1, 0); + // TODO: Remove const_cast after refining the signature of ext_oneapi_copy. + event_list.push_back(q.ext_oneapi_copy( + const_cast(src_host_ptr), src_offset, src_extend, dest, + dest_offset, desc_dest, copy_extend)); + offset_src += w - w_offset_dest; + w_offset_dest = 0; + ++h_offset_dest; + } + if (s - offset_src > 0) { + const auto src_offset = sycl::range<3>(offset_src / ele_size, 0, 0); + const auto src_extend = sycl::range<3>(0, 0, 0); + const auto dest_offset = + sycl::range<3>(w_offset_dest / ele_size, h_offset_dest, 0); + const auto copy_extend = sycl::range<3>((s - offset_src) / ele_size, 1, 0); + // TODO: Remove const_cast after refining the signature of ext_oneapi_copy. + event_list.push_back(q.ext_oneapi_copy( + const_cast(src_host_ptr), src_offset, src_extend, dest, + dest_offset, desc_dest, copy_extend)); + } + return event_list; +} + +static inline std::vector dpct_memcpy( + const void *src, sycl::ext::oneapi::experimental::image_mem_handle dest, + const sycl::ext::oneapi::experimental::image_descriptor &desc_dest, + size_t w_offset_dest, size_t h_offset_dest, size_t s, sycl::queue q) { + if (dpct::detail::get_pointer_attribute(q, src) == + dpct::detail::pointer_access_attribute::device_only) { + std::vector event_list; + dpct::detail::host_buffer buf(s, q, event_list); + event_list.push_back(dpct::detail::dpct_memcpy( + q, buf.get_ptr(), src, s, memcpy_direction::device_to_host)); + auto copy_events = dpct_memcpy_from_host( + buf.get_ptr(), dest, desc_dest, w_offset_dest, h_offset_dest, s, q); + event_list.insert(event_list.end(), copy_events.begin(), copy_events.end()); + return event_list; + } + return dpct_memcpy_from_host(src, dest, desc_dest, w_offset_dest, + h_offset_dest, s, q); +} + +static inline sycl::event +dpct_memcpy(const image_mem_wrapper *src, const sycl::id<3> &src_id, + const size_t src_x_offest_byte, pitched_data &dest, + const sycl::id<3> &dest_id, const size_t dest_x_offest_byte, + const sycl::range<3> &size, const size_t copy_x_size_byte, + sycl::queue q) { + const auto ele_size = get_ele_size(src->get_desc()); + const auto src_offset = sycl::range<3>( + src_x_offest_byte != 0 ? src_x_offest_byte / ele_size : src_id[0], + src_id[1], src_id[2]); + const auto dest_offset = sycl::range<3>( + dest_x_offest_byte != 0 ? dest_x_offest_byte / ele_size : dest_id[0], + dest_id[1], dest_id[2]); + const auto dest_extend = + sycl::range<3>(dest.get_pitch() / ele_size, dest.get_y(), 1); + const auto copy_extend = sycl::range<3>( + copy_x_size_byte != 0 ? copy_x_size_byte / ele_size : size[0], size[1], + size[2]); + return q.ext_oneapi_copy(src->get_handle(), src_offset, src->get_desc(), + dest.get_data_ptr(), dest_offset, dest_extend, + copy_extend); +} + +static inline sycl::event +dpct_memcpy(pitched_data src, const sycl::id<3> &src_id, + const size_t src_x_offest_byte, image_mem_wrapper *dest, + const sycl::id<3> &dest_id, const size_t dest_x_offest_byte, + const sycl::range<3> &size, const size_t copy_x_size_byte, + sycl::queue q) { + const auto ele_size = get_ele_size(dest->get_desc()); + const auto src_offset = sycl::range<3>( + src_x_offest_byte != 0 ? src_x_offest_byte / ele_size : src_id[0], + src_id[1], src_id[2]); + const auto src_extend = + sycl::range<3>(src.get_pitch() / ele_size, src.get_y(), 1); + const auto dest_offset = sycl::range<3>( + dest_x_offest_byte != 0 ? dest_x_offest_byte / ele_size : dest_id[0], + dest_id[1], dest_id[2]); + const auto copy_extend = sycl::range<3>( + copy_x_size_byte != 0 ? copy_x_size_byte / ele_size : size[0], size[1], + size[2]); + return q.ext_oneapi_copy(src.get_data_ptr(), src_offset, src_extend, + dest->get_handle(), dest_offset, dest->get_desc(), + copy_extend); +} + +static inline sycl::event +dpct_memcpy(const image_mem_wrapper *src, const sycl::id<3> &src_id, + const size_t src_x_offest_byte, image_mem_wrapper *dest, + const sycl::id<3> &dest_id, const size_t dest_x_offest_byte, + const sycl::range<3> &size, const size_t copy_x_size_byte, + sycl::queue q) { + // TODO: Need change logic when sycl support image_mem to image_mem copy. + const auto from_ele_size = get_ele_size(src->get_desc()); + const auto to_ele_size = get_ele_size(dest->get_desc()); + const auto copy_extend = sycl::range<3>( + copy_x_size_byte != 0 ? copy_x_size_byte / from_ele_size : size[0], + size[1], size[2]); + std::vector event_list; + dpct::detail::host_buffer buf( + copy_extend.size() * std::max(from_ele_size, to_ele_size), q, event_list); + auto to = pitched_data(buf.get_ptr(), copy_extend[0] * from_ele_size, + copy_extend[0], copy_extend[1]); + dpct_memcpy(src, src_id, src_x_offest_byte, to, sycl::id<3>(0, 0, 0), 0, + copy_extend, 0, q); + auto from = pitched_data(buf.get_ptr(), copy_extend[0] * to_ele_size, + copy_extend[0], copy_extend[1]); + event_list.push_back(dpct_memcpy(from, sycl::id<3>(0, 0, 0), 0, dest, dest_id, + dest_x_offest_byte, copy_extend, 0, q)); + return event_list.front(); +} + +template +inline bool check_duplicate_entries(int count, T **entries) { + std::set uniqueEntries; + + for (size_t i = 0; i < count; ++i) { + auto result = uniqueEntries.insert(entries[i]); + if (!result.second) { + return true; + } + } + + return false; +} +} // namespace detail + +/// Get image_mem_wrapper according to sampled image handle. +/// \param [in] handle The bindless image handle. +/// \returns The image_mem_wrapper of sampled image. +inline image_mem_wrapper *&get_img_mem( + const sycl::ext::oneapi::experimental::sampled_image_handle handle) { + static std::map + img_mem_map; + return img_mem_map[handle]; +} + +/// Get image_mem_wrapper according to unsampled image handle. +/// \param [in] handle The unsampled bindless image handle. +/// \returns The image_mem_wrapper of unsampled image. +inline image_mem_wrapper *&get_img_mem( + const sycl::ext::oneapi::experimental::unsampled_image_handle handle) { + static std::map + img_mem_map; + return img_mem_map[handle]; +} + +/// Associate an image memory wrapper with a bindless unsampled image handle in +/// the global registry. +/// +/// Inserts or updates an entry in the internal image memory map, using the +/// specified bindless unsampled image handle as the key and the provided image +/// memory wrapper as the mapped value. +/// \param [in] handle The unsampled bindless image handle. +/// \param [in] img_mem The image_mem_wrapper associated with the unsampled handle. +static inline void set_img_mem( + const sycl::ext::oneapi::experimental::unsampled_image_handle handle, + image_mem_wrapper *img_mem) { + dpct::experimental::get_img_mem(handle) = img_mem; +} + +/// Associate an image memory wrapper with a bindless sampled image handle in +/// the global registry. +/// +/// Inserts or updates an entry in the internal image memory map, using the +/// specified bindless unsampled image handle as the key and the provided image +/// memory wrapper as the mapped value. +/// \param [in] handle The sampled bindless image handle. +/// \param [in] img_mem The image_mem_wrapper associated with the sampled handle. +static inline void set_img_mem( + const sycl::ext::oneapi::experimental::sampled_image_handle handle, + image_mem_wrapper *img_mem) { + dpct::experimental::get_img_mem(handle) = img_mem; +} + +#ifdef _WIN32 +/// Map the resource memories to mem handles +/// \param [in] count The count of resources to map. +/// \param [in] handles The external mem wrappers used to map the resources. +/// \param [in] q The queue used to map the resource with. +inline void map_resources(int count, external_mem_wrapper **handles, + queue_ptr q_ptr = &get_default_queue()) { + if (detail::check_duplicate_entries(count, handles)) { + throw std::runtime_error( + "Duplicate handle entries found during resource mapping!"); + } + + for (int i = 0; i < count; i++) { + handles[i]->map_resource(*q_ptr); + } +} + +/// Unmap the resource memories to mem handles +/// \param [in] count The count of resources to unmap. +/// \param [in] handles The external mem wrappers used to unmap the resources. +/// \param [in] q The queue used to unmap the resource with. +inline void unmap_resources(int count, external_mem_wrapper **handles, + queue_ptr q_ptr = &get_default_queue()) { + if (detail::check_duplicate_entries(count, handles)) { + throw std::runtime_error( + "Duplicate handle entries found during resource unmapping!"); + } + + for (int i = 0; i < count; i++) { + handles[i]->unmap_resource(*q_ptr); + } +} +#endif // _WIN32 + +/// Imports resource's external memory into a SYCL external memory object. +/// \param [in] extMem SYCL external memory object ptr to be initialized. +/// \param [in] memHandleDesc Pointer to the external memory resource handle +/// descriptor. +/// \throws std::runtime_error If no valid external memory resource handle is +/// provided. +inline void +import_external_memory(sycl::ext::oneapi::experimental::external_mem *extMem, + external_mem_handle_desc *memHandleDesc) { +#ifdef _WIN32 + if (memHandleDesc->get_win32_handle()) { + *extMem = sycl::ext::oneapi::experimental::import_external_memory( + sycl::ext::oneapi::experimental::external_mem_descriptor< + sycl::ext::oneapi::experimental::resource_win32_handle>{ + {memHandleDesc->get_win32_handle()}, + memHandleDesc->get_handle_type(), + memHandleDesc->get_res_size()}, + get_default_queue()); + } else if (memHandleDesc->get_win32_obj_name()) { + throw std::runtime_error( + "Importing external memory resource using Windows NT name" + " type is not supported. Only NT handle type is" + " supported"); + } +#else + if (memHandleDesc->get_fd_handle() != -1) { + *extMem = sycl::ext::oneapi::experimental::import_external_memory( + sycl::ext::oneapi::experimental::external_mem_descriptor< + sycl::ext::oneapi::experimental::resource_fd>{ + {memHandleDesc->get_fd_handle()}, + memHandleDesc->get_handle_type(), + memHandleDesc->get_res_size()}, + get_default_queue()); + } +#endif // _WIN32 + else { + throw std::runtime_error( + "No external memory resource handle is set for importing!"); + } +} + +/// Imports external semaphore resource into a SYCL external semaphore object. +/// \param [in] extSem SYCL external semaphore object ptr to be initialized. +/// \param [in] semHandleDesc Pointer to the external semaphore resource handle +/// descriptor. +/// \throws std::runtime_error If no valid external semaphore resource handle is +/// provided. +inline void import_external_semaphore(external_sem_wrapper **extSem, + external_sem_handle_desc *semHandleDesc) { + sycl::ext::oneapi::experimental::external_semaphore extSemObj; +#ifdef _WIN32 + if (semHandleDesc->get_win32_handle()) { + extSemObj = sycl::ext::oneapi::experimental::import_external_semaphore( + sycl::ext::oneapi::experimental::external_semaphore_descriptor< + sycl::ext::oneapi::experimental::resource_win32_handle>{ + {semHandleDesc->get_win32_handle()}, + semHandleDesc->get_handle_type()}, + get_default_queue()); + } else if (semHandleDesc->get_win32_obj_name()) { + throw std::runtime_error( + "Importing external semaphore resource using Windows NT name" + " type is not supported. Only NT handle type is" + " supported"); + } +#else + if (semHandleDesc->get_fd_handle() != -1) { + extSemObj = sycl::ext::oneapi::experimental::import_external_semaphore( + sycl::ext::oneapi::experimental::external_semaphore_descriptor< + sycl::ext::oneapi::experimental::resource_fd>{ + {semHandleDesc->get_fd_handle()}, semHandleDesc->get_handle_type()}, + get_default_queue()); + } +#endif // _WIN32 + else { + throw std::runtime_error( + "No external semaphore resource handle is set for importing!"); + } + + *extSem = + new external_sem_wrapper(extSemObj, semHandleDesc->get_handle_type()); +} + +/// Signals the external semaphore resource. +/// \param [in] extSem ptr to dpct external semaphore resource ptr +/// \param [in] semSignalParams Pointer to the external semaphore signal +/// parameters. +/// \param [in] numExtSems Number of external semaphores to signal. +/// \param [in] q_ptr The queue used to signal the external semaphore resource. +inline void signal_external_semaphores(external_sem_wrapper **extSem, + external_sem_params *semSignalParams, + unsigned int numExtSems, + queue_ptr q_ptr = &get_default_queue()) { + for (int i = 0; i < numExtSems; i++) { + auto extSemType = extSem[i]->get_handle_type(); + switch (extSemType) { +#ifdef _WIN32 + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + win32_nt_dx12_fence: + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + timeline_win32_nt_handle: + q_ptr->ext_oneapi_signal_external_semaphore( + extSem[i]->get(), semSignalParams[i].get_value()); + break; + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + win32_nt_handle: + q_ptr->ext_oneapi_signal_external_semaphore(extSem[i]->get()); + break; +#else // _WIN32 + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + timeline_fd: + q_ptr->ext_oneapi_signal_external_semaphore( + extSem[i]->get(), semSignalParams[i].get_value()); + break; + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + opaque_fd: + q_ptr->ext_oneapi_signal_external_semaphore(extSem[i]->get()); + break; +#endif // _WIN32 + default: + throw std::runtime_error( + "Unsupported external semaphore resource handle type!"); + break; + } + } +} + +/// Wait for the external semaphore resource. +/// \param [in] extSem ptr to dpct external semaphore resource ptr +/// \param [in] semWaitParams Pointer to the external semaphore wait parameters. +/// \param [in] numExtSems Number of external semaphores to wait. +/// \param [in] q_ptr The queue used to wait on the external semaphore resource. +inline void wait_external_semaphores(external_sem_wrapper **extSem, + external_sem_params *semWaitParams, + unsigned int numExtSems, + queue_ptr q_ptr = &get_default_queue()) { + for (int i = 0; i < numExtSems; i++) { + auto extSemType = extSem[i]->get_handle_type(); + switch (extSemType) { +#ifdef _WIN32 + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + win32_nt_dx12_fence: + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + timeline_win32_nt_handle: + q_ptr->ext_oneapi_wait_external_semaphore(extSem[i]->get(), + semWaitParams[i].get_value()); + break; + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + win32_nt_handle: + q_ptr->ext_oneapi_wait_external_semaphore(extSem[i]->get()); + break; +#else // _WIN32 + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + timeline_fd: + q_ptr->ext_oneapi_wait_external_semaphore(extSem[i]->get(), + semWaitParams[i].get_value()); + break; + case sycl::ext::oneapi::experimental::external_semaphore_handle_type:: + opaque_fd: + q_ptr->ext_oneapi_wait_external_semaphore(extSem[i]->get()); + break; +#endif // _WIN32 + default: + throw std::runtime_error( + "Unsupported external semaphore resource handle type!"); + break; + } + } +} + +/// Create bindless image according to image data and sampling info. +/// \param [in] data The image data used to create bindless image. +/// \param [in] info The image sampling info used to create bindless image. +/// \param [in] q The queue where the image creation be executed. +/// \returns The sampled image handle of created bindless image. +static inline sycl::ext::oneapi::experimental::sampled_image_handle +create_bindless_image(image_data data, sampling_info info, + sycl::queue q = get_default_queue()) { + auto samp = sycl::ext::oneapi::experimental::bindless_image_sampler( + info.get_addressing_mode(), info.get_coordinate_normalization_mode(), + info.get_filtering_mode(), info.get_mipmap_filtering(), + info.get_min_mipmap_level_clamp(), info.get_max_mipmap_level_clamp(), + info.get_max_anisotropy()); + + switch (data.get_data_type()) { + case image_data_type::linear: { + // linear memory only use sycl::filtering_mode::nearest. + samp.filtering = sycl::filtering_mode::nearest; + // TODO: Use pointer to create image when bindless image support. + auto mem = new image_mem_wrapper( + data.get_channel(), data.get_x() / data.get_channel().get_total_size()); + auto img = sycl::ext::oneapi::experimental::create_image( + mem->get_handle(), samp, mem->get_desc(), q); + set_img_mem(img, mem); + auto ptr = data.get_data_ptr(); +#ifdef DPCT_USM_LEVEL_NONE + q.ext_oneapi_copy(get_buffer(ptr).get_host_access().get_pointer(), + mem->get_handle(), mem->get_desc()) + .wait(); +#else + q.ext_oneapi_copy(ptr, mem->get_handle(), mem->get_desc()).wait(); +#endif + detail::get_img_info_map(img) = {data, info}; + return img; + } + case image_data_type::pitch: { +#ifdef DPCT_USM_LEVEL_NONE + auto mem = + new image_mem_wrapper(data.get_channel(), data.get_x(), data.get_y()); + auto img = sycl::ext::oneapi::experimental::create_image( + mem->get_handle(), samp, mem->get_desc(), q); + set_img_mem(img, mem); + q.ext_oneapi_copy( + get_buffer(data.get_data_ptr()).get_host_access().get_pointer(), + mem->get_handle(), mem->get_desc()) + .wait(); +#else + auto desc = sycl::ext::oneapi::experimental::image_descriptor( + {data.get_x(), data.get_y()}, data.get_channel().get_channel_num(), + data.get_channel_type()); + auto img = sycl::ext::oneapi::experimental::create_image( + data.get_data_ptr(), data.get_pitch(), samp, desc, q); +#endif + detail::get_img_info_map(img) = {data, info}; + return img; + } + case image_data_type::matrix: { + const auto mem = static_cast(data.get_data_ptr()); + auto img = sycl::ext::oneapi::experimental::create_image( + mem->get_handle(), samp, mem->get_desc(), q); + detail::get_img_info_map(img) = {data, info}; + return img; + } + default: + throw std::runtime_error( + "Unsupported image_data_type in create_bindless_image!"); + break; + } + // Must not reach here. + return sycl::ext::oneapi::experimental::sampled_image_handle(); +} + +/// Create bindless image according to image data. +/// \param [in] data The image data used to create bindless image. +/// \param [in] q The queue where the image creation be executed. +/// \returns The sampled image handle of created bindless image. +static inline sycl::ext::oneapi::experimental::unsampled_image_handle +create_bindless_image(image_data data, sycl::queue q = get_default_queue()) { + switch (data.get_data_type()) { + case image_data_type::linear: { + // TODO: Use pointer to create image when bindless image support. + auto mem = new image_mem_wrapper( + data.get_channel(), data.get_x() / data.get_channel().get_total_size()); + auto img = sycl::ext::oneapi::experimental::create_image( + mem->get_handle(), mem->get_desc(), q); + set_img_mem(img, mem); + auto ptr = data.get_data_ptr(); +#ifdef DPCT_USM_LEVEL_NONE + q.ext_oneapi_copy(get_buffer(ptr).get_host_access().get_pointer(), + mem->get_handle(), mem->get_desc()) + .wait(); +#else + q.ext_oneapi_copy(ptr, mem->get_handle(), mem->get_desc()).wait(); +#endif + return img; + } + case image_data_type::pitch: { + auto mem = + new image_mem_wrapper(data.get_channel(), data.get_x(), data.get_y()); + auto img = sycl::ext::oneapi::experimental::create_image( + mem->get_handle(), mem->get_desc(), q); + set_img_mem(img, mem); +#ifdef DPCT_USM_LEVEL_NONE + q.ext_oneapi_copy( + get_buffer(data.get_data_ptr()).get_host_access().get_pointer(), + mem->get_handle(), mem->get_desc()) + .wait(); +#else + q.ext_oneapi_copy(data.get_data_ptr(), mem->get_handle(), mem->get_desc()) + .wait(); + +#endif + return img; + } + case image_data_type::matrix: { + const auto mem = static_cast(data.get_data_ptr()); + auto img = sycl::ext::oneapi::experimental::create_image( + mem->get_handle(), mem->get_desc(), q); + return img; + } + default: + throw std::runtime_error( + "Unsupported image_data_type in create_bindless_image!"); + break; + } + // Must not reach here. + return sycl::ext::oneapi::experimental::unsampled_image_handle(); +} + +/// Destroy bindless image. +/// \param [in] handle The bindless image should be destroyed. +/// \param [in] q The queue where the image destruction be executed. +template +static inline void destroy_bindless_image(T handle, + sycl::queue q = get_default_queue()) { + auto &mem = get_img_mem(handle); + if (mem) { + delete mem; + mem = nullptr; + } + sycl::ext::oneapi::experimental::destroy_image_handle(handle, q); +} + +/// Get the image data according to sampled image handle. +/// \param [in] handle The bindless image handle. +/// \returns The image data of sampled image. +template static inline image_data get_data(const T handle) { + return detail::get_img_info_map(handle).first; +} + +/// Get the sampling info according to sampled image handle. +/// \param [in] handle The bindless image handle. +/// \returns The sampling info of sampled image. +static inline sampling_info get_sampling_info( + const sycl::ext::oneapi::experimental::sampled_image_handle handle) { + return detail::get_img_info_map(handle).second; +} + +/// The base class of different template specialization bindless_image_wrapper +/// class. +class bindless_image_wrapper_base { +public: + bindless_image_wrapper_base() { + // Make sure that singleton class dev_mgr will destruct later than this. + dev_mgr::instance(); + } + + /// Destroy bindless image wrapper. + ~bindless_image_wrapper_base() { + destroy_bindless_image(_img, get_default_queue()); + } + + /// Attach linear data to bindless image. + /// \param [in] data The linear data used to create bindless image. + /// \param [in] size The size of linear data used to create bindless image. + /// \param [in] channel The image channel used to create bindless image. + /// \param [in] q The queue where the image creation be executed. + void attach(void *data, size_t size, const image_channel &channel, + sycl::queue q = get_default_queue()) { + detach(q); + auto samp = sycl::ext::oneapi::experimental::bindless_image_sampler( + _addressing_mode, _coordinate_normalization_mode, _filtering_mode); + // TODO: Use pointer to create image when bindless image support. + auto mem = new image_mem_wrapper(channel, size); + _img = sycl::ext::oneapi::experimental::create_image( + mem->get_handle(), samp, mem->get_desc(), q); + set_img_mem(_img, mem); + auto ptr = data; +#ifdef DPCT_USM_LEVEL_NONE + q.ext_oneapi_copy(get_buffer(data).get_host_access().get_pointer(), + mem->get_handle(), mem->get_desc()) + .wait(); +#else + q.ext_oneapi_copy(ptr, mem->get_handle(), mem->get_desc()).wait(); +#endif + } + + /// Attach linear data to bindless image. + /// \param [in] data The linear data used to create bindless image. + /// \param [in] size The size of linear data used to create bindless image. + /// \param [in] q The queue where the image creation be executed. + void attach(void *data, size_t size, sycl::queue q = get_default_queue()) { + attach(data, size, _channel, q); + } + + /// Attach device_ptr data to bindless image. + /// \param [in] desc The image_descriptor used to create bindless image. + /// \param [in] ptr The data pointer used to create bindless image. + /// \param [in] pitch The pitch of 2D data used to create bindless image. + /// \param [in] q The queue where the image creation be executed. + void attach(const sycl::ext::oneapi::experimental::image_descriptor *desc, + device_ptr ptr, size_t pitch, + sycl::queue q = get_default_queue()) { + detach(q); + auto samp = sycl::ext::oneapi::experimental::bindless_image_sampler( + _addressing_mode, _coordinate_normalization_mode, _filtering_mode); +#ifdef DPCT_USM_LEVEL_NONE + auto mem = new image_mem_wrapper(desc); + _img = sycl::ext::oneapi::experimental::create_image(mem->get_handle(), + samp, *desc, q); + set_img_mem(_img, mem); + q.ext_oneapi_copy(get_buffer(ptr).get_host_access().get_pointer(), + mem->get_handle(), mem->get_desc()) + .wait(); +#else + _img = sycl::ext::oneapi::experimental::create_image(ptr, pitch, samp, + *desc, q); +#endif + } + + /// Attach 2D data to bindless image. + /// \param [in] data The 2D data used to create bindless image. + /// \param [in] width The width of 2D data used to create bindless image. + /// \param [in] height The height of 2D data used to create bindless image. + /// \param [in] pitch The pitch of 2D data used to create bindless image. + /// \param [in] channel The image channel used to create bindless image. + /// \param [in] q The queue where the image creation be executed. + void attach(void *data, size_t width, size_t height, size_t pitch, + const image_channel &channel, + sycl::queue q = get_default_queue()) { + auto desc = sycl::ext::oneapi::experimental::image_descriptor( + {width, height}, channel.get_channel_num(), channel.get_channel_type()); + attach(&desc, static_cast(data), pitch, q); + } + + /// Attach 2D data to bindless image. + /// \param [in] data The 2D data used to create bindless image. + /// \param [in] width The width of 2D data used to create bindless image. + /// \param [in] height The height of 2D data used to create bindless image. + /// \param [in] pitch The pitch of 2D data used to create bindless image. + /// \param [in] q The queue where the image creation be executed. + void attach(void *data, size_t width, size_t height, size_t pitch, + sycl::queue q = get_default_queue()) { + attach(data, width, height, pitch, _channel, q); + } + + /// Attach image memory to bindless image. + /// \param [in] mem The image memory used to create bindless image. + /// \param [in] q The queue where the image creation be executed. + void attach(image_mem_wrapper *mem, const image_channel &channel, + sycl::queue q = get_default_queue()) { + detach(q); + auto samp = sycl::ext::oneapi::experimental::bindless_image_sampler( + _addressing_mode, _coordinate_normalization_mode, _filtering_mode); + _img = sycl::ext::oneapi::experimental::create_image( + mem->get_handle(), samp, mem->get_desc(), q); + set_img_mem(_img, mem); + } + + /// Attach image memory to bindless image. + /// \param [in] mem The image memory used to create bindless image. + /// \param [in] q The queue where the image creation be executed. + void attach(image_mem_wrapper *mem, sycl::queue q = get_default_queue()) { + attach(mem, _channel, q); + } + + /// Detach bindless image data. + /// \param [in] q The queue where the image destruction be executed. + void detach(sycl::queue q = get_default_queue()) { + destroy_bindless_image(_img, q); + } + + /// Set image channel of bindless image. + /// \param [in] channel The image channel used to set. + void set_channel(image_channel channel) { _channel = channel; } + /// Get image channel of bindless image. + /// \returns The image channel of bindless image. + image_channel get_channel() { return _channel; } + + /// Set channel size of image channel. + /// \param [in] channel_num The channels number to set. + /// \param [in] channel_size The size for each channel in bits. + void set_channel_size(unsigned channel_num, unsigned channel_size) { + return _channel.set_channel_size(channel_num, channel_size); + } + /// Get channel size of image channel. + /// \returns The size for each channel in bits. + unsigned get_channel_size() { return _channel.get_channel_size(); } + + /// Set image channel data type of image channel. + /// \param [in] type The image channel data type to set. + void set_channel_data_type(image_channel_data_type type) { + _channel.set_channel_data_type(type); + } + /// Get image channel data type of image channel. + /// \returns The image channel data type of image channel. + image_channel_data_type get_channel_data_type() { + return _channel.get_channel_data_type(); + } + + /// Set channel num of bindless image. + /// \param [in] filtering_mode The channel num used to set. + void set_channel_num(unsigned num) { return _channel.set_channel_num(num); } + + /// Set channel type of bindless image. + /// \param [in] filtering_mode The channel type used to set. + void set_channel_type(sycl::image_channel_type type) { + return _channel.set_channel_type(type); + } + + /// Set addressing mode of bindless image. + /// \param [in] addressing_mode The addressing mode used to set. + void set(sycl::addressing_mode addressing_mode) { + _addressing_mode = addressing_mode; + } + /// Get addressing mode of bindless image. + /// \returns The addressing mode of bindless image. + sycl::addressing_mode get_addressing_mode() { return _addressing_mode; } + + /// Set coordinate normalization mode of bindless image. + /// \param [in] coordinate_normalization_mode The coordinate normalization + /// mode used to set. + void set(sycl::coordinate_normalization_mode coordinate_normalization_mode) { + _coordinate_normalization_mode = coordinate_normalization_mode; + } + /// Set coordinate normalization mode of bindless image. + /// \param [in] is_normalized Determine whether the coordinate should be + /// normalized. + void set_coordinate_normalization_mode(int is_normalized) { + _coordinate_normalization_mode = + is_normalized ? sycl::coordinate_normalization_mode::normalized + : sycl::coordinate_normalization_mode::unnormalized; + } + /// Get coordinate normalization mode of bindless image. + /// \returns The coordinate normalization mode of bindless image. + bool is_coordinate_normalized() { + return _coordinate_normalization_mode == + sycl::coordinate_normalization_mode::normalized; + } + + /// Set filtering mode of bindless image. + /// \param [in] filtering_mode The filtering mode used to set. + void set(sycl::filtering_mode filtering_mode) { + _filtering_mode = filtering_mode; + } + /// Get filtering mode of bindless image. + /// \returns The filtering mode of bindless image. + sycl::filtering_mode get_filtering_mode() { return _filtering_mode; } + + /// Get bindless image handle. + /// \returns The sampled image handle of created bindless image. + inline sycl::ext::oneapi::experimental::sampled_image_handle get_handle() { + return _img; + } + + /// Set mipmap sample filtering mode for bindless image handle + /// \param [in] filtering_mode The mipmap filtering mode + inline void set_mip_filtering_mode(sycl::filtering_mode mode) { + auto sampling_info = get_sampling_info(_img); + sampling_info.set_mipmap_filtering(mode); + } + + /// Get mipmap sample filtering mode for bindless image handle + /// \return The mipmap filtering mode + inline sycl::filtering_mode get_mip_filtering_mode(void) { + auto sampling_info = get_sampling_info(_img); + return sampling_info.get_mipmap_filtering(); + } + + /// Get mipmap sample filtering mode for bindless image handle + /// \return The mipmap filtering mode + inline void get_mip_level_clamp(float *min_level_clamp, + float *max_level_clamp) { + auto sampling_info = get_sampling_info(_img); + *min_level_clamp = sampling_info.get_min_mipmap_level_clamp(); + *max_level_clamp = sampling_info.get_max_mipmap_level_clamp(); + } + + /// Get mipmap memory wrapper attached the bindless image + /// \return The mipmap memory wrapper + inline image_mem_wrapper *get_attached_mipmap_data(void) { + auto mem = get_img_mem(_img); + + if (mem->get_image_type() != + sycl::ext::oneapi::experimental::image_type::mipmap) + throw std::runtime_error("Bindless image data is not of mipmap type"); + + return mem; + } + +private: + image_channel _channel; + sycl::addressing_mode _addressing_mode = sycl::addressing_mode::clamp_to_edge; + sycl::coordinate_normalization_mode _coordinate_normalization_mode = + sycl::coordinate_normalization_mode::unnormalized; + sycl::filtering_mode _filtering_mode = sycl::filtering_mode::nearest; + sycl::ext::oneapi::experimental::sampled_image_handle _img{0}; +}; + +/// The wrapper class of bindless image. +template +class bindless_image_wrapper : public bindless_image_wrapper_base { +public: + /// Create bindless image wrapper according to template argument \p T. + bindless_image_wrapper() { set_channel(image_channel::create()); } +}; + +/// Asynchronously copies from the image memory to memory specified by a +/// pointer, The return of the function does NOT guarantee the copy is +/// completed. +/// \param [in] dest The destination memory address. +/// \param [in] p The pitch of destination memory. +/// \param [in] src The source image memory. +/// \param [in] w_offset_src The x offset of source image memory. +/// \param [in] h_offset_src The y offset of source image memory. +/// \param [in] w The width of matrix to be copied. +/// \param [in] h The height of matrix to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void async_dpct_memcpy(void *dest, size_t p, + const image_mem_wrapper *src, + size_t w_offset_src, size_t h_offset_src, + size_t w, size_t h, + sycl::queue q = get_default_queue()) { + detail::dpct_memcpy(src->get_handle(), src->get_desc(), w_offset_src, + h_offset_src, dest, p, w, h, q); +} + +/// Synchronously copies from the image memory to memory specified by a +/// pointer, The function will return after the copy is completed. +/// \param [in] dest The destination memory address. +/// \param [in] p The pitch of destination memory. +/// \param [in] src The source image memory. +/// \param [in] w_offset_src The x offset of source image memory. +/// \param [in] h_offset_src The y offset of source image memory. +/// \param [in] w The width of matrix to be copied. +/// \param [in] h The height of matrix to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void dpct_memcpy(void *dest, size_t p, + const image_mem_wrapper *src, + size_t w_offset_src, size_t h_offset_src, + size_t w, size_t h, + sycl::queue q = get_default_queue()) { + detail::dpct_memcpy(src->get_handle(), src->get_desc(), w_offset_src, + h_offset_src, dest, p, w, h, q) + .wait(); +} + +/// Asynchronously copies from the image memory to memory specified by a +/// pointer, The return of the function does NOT guarantee the copy is +/// completed. +/// \param [in] dest The destination memory address. +/// \param [in] src The source image memory. +/// \param [in] w_offset_src The x offset of source image memory. +/// \param [in] h_offset_src The y offset of source image memory. +/// \param [in] s The size to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void async_dpct_memcpy(void *dest, const image_mem_wrapper *src, + size_t w_offset_src, size_t h_offset_src, + size_t s, + sycl::queue q = get_default_queue()) { + detail::dpct_memcpy(src->get_handle(), src->get_desc(), w_offset_src, + h_offset_src, dest, s, q); +} + +/// Synchronously copies from the image memory to memory specified by a +/// pointer, The function will return after the copy is completed. +/// \param [in] dest The destination memory address. +/// \param [in] src The source image memory. +/// \param [in] w_offset_src The x offset of source image memory. +/// \param [in] h_offset_src The y offset of source image memory. +/// \param [in] s The size to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void dpct_memcpy(void *dest, const image_mem_wrapper *src, + size_t w_offset_src, size_t h_offset_src, + size_t s, sycl::queue q = get_default_queue()) { + sycl::event::wait(detail::dpct_memcpy(src->get_handle(), src->get_desc(), + w_offset_src, h_offset_src, dest, s, + q)); +} + +/// Asynchronously copies from memory specified by a pointer to the image +/// memory, The return of the function does NOT guarantee the copy is completed. +/// \param [in] dest The destination image memory. +/// \param [in] w_offset_dest The x offset of destination image memory. +/// \param [in] h_offset_dest The y offset of destination image memory. +/// \param [in] src The source memory address. +/// \param [in] p The pitch of source memory. +/// \param [in] w The width of matrix to be copied. +/// \param [in] h The height of matrix to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void async_dpct_memcpy(image_mem_wrapper *dest, + size_t w_offset_dest, size_t h_offset_dest, + const void *src, size_t p, size_t w, + size_t h, + sycl::queue q = get_default_queue()) { + detail::dpct_memcpy(src, dest->get_handle(), dest->get_desc(), w_offset_dest, + h_offset_dest, p, w, h, q); +} + +/// Synchronously copies from memory specified by a pointer to the image +/// memory, The function will return after the copy is completed. +/// \param [in] dest The destination image memory. +/// \param [in] w_offset_dest The x offset of destination image memory. +/// \param [in] h_offset_dest The y offset of destination image memory. +/// \param [in] src The source memory address. +/// \param [in] p The pitch of source memory. +/// \param [in] w The width of matrix to be copied. +/// \param [in] h The height of matrix to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void dpct_memcpy(image_mem_wrapper *dest, size_t w_offset_dest, + size_t h_offset_dest, const void *src, size_t p, + size_t w, size_t h, + sycl::queue q = get_default_queue()) { + detail::dpct_memcpy(src, dest->get_handle(), dest->get_desc(), w_offset_dest, + h_offset_dest, p, w, h, q) + .wait(); +} + +/// Asynchronously copies from memory specified by a pointer to the image +/// memory, The return of the function does NOT guarantee the copy is completed. +/// \param [in] dest The destination image memory. +/// \param [in] w_offset_dest The x offset of destination image memory. +/// \param [in] h_offset_dest The y offset of destination image memory. +/// \param [in] src The source memory address. +/// \param [in] s The size to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void async_dpct_memcpy(image_mem_wrapper *dest, + size_t w_offset_dest, size_t h_offset_dest, + const void *src, size_t s, + sycl::queue q = get_default_queue()) { + detail::dpct_memcpy(src, dest->get_handle(), dest->get_desc(), w_offset_dest, + h_offset_dest, s, q); +} + +/// Synchronously copies from memory specified by a pointer to the image +/// memory, The function will return after the copy is completed. +/// \param [in] dest The destination image memory. +/// \param [in] w_offset_dest The x offset of destination image memory. +/// \param [in] h_offset_dest The y offset of destination image memory. +/// \param [in] src The source memory address. +/// \param [in] s The size to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void dpct_memcpy(image_mem_wrapper *dest, size_t w_offset_dest, + size_t h_offset_dest, const void *src, size_t s, + sycl::queue q = get_default_queue()) { + sycl::event::wait(detail::dpct_memcpy(src, dest->get_handle(), + dest->get_desc(), w_offset_dest, + h_offset_dest, s, q)); +} + +/// Synchronously copies from image memory to the image memory, The function +/// will return after the copy is completed. +/// \param [in] dest The destination image memory. +/// \param [in] w_offset_dest The x offset of destination image memory. +/// \param [in] h_offset_dest The y offset of destination image memory. +/// \param [in] src The source image memory. +/// \param [in] w_offset_src The x offset of source image memory. +/// \param [in] h_offset_src The y offset of source image memory. +/// \param [in] w The width of matrix to be copied. +/// \param [in] h The height of matrix to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void dpct_memcpy(image_mem_wrapper *dest, size_t w_offset_dest, + size_t h_offset_dest, + const image_mem_wrapper *src, + size_t w_offset_src, size_t h_offset_src, + size_t w, size_t h, + sycl::queue q = get_default_queue()) { + auto temp = (void *)sycl::malloc_device(w * h, q); + // TODO: Need change logic when sycl support image_mem to image_mem copy. + dpct_memcpy(temp, w, src, w_offset_src, h_offset_src, w, h, q); + dpct_memcpy(dest, w_offset_dest, h_offset_dest, temp, w, w, h, q); + sycl::free(temp, q); +} + +/// Synchronously copies from image memory to the image memory, The function +/// will return after the copy is completed. +/// \param [in] dest The destination image memory. +/// \param [in] w_offset_dest The x offset of destination image memory. +/// \param [in] h_offset_dest The y offset of destination image memory. +/// \param [in] src The source image memory. +/// \param [in] w_offset_src The x offset of source image memory. +/// \param [in] h_offset_src The y offset of source image memory. +/// \param [in] s The size to be copied. +/// \param [in] q The queue to execute the copy task. +static inline void dpct_memcpy(image_mem_wrapper *dest, size_t w_offset_dest, + size_t h_offset_dest, + const image_mem_wrapper *src, + size_t w_offset_src, size_t h_offset_src, + size_t s, sycl::queue q = get_default_queue()) { + auto temp = (void *)sycl::malloc_device(s, q); + // TODO: Need change logic when sycl support image_mem to image_mem copy. + dpct_memcpy(temp, src, w_offset_src, h_offset_src, s, q); + dpct_memcpy(dest, w_offset_dest, h_offset_dest, temp, s, q); + sycl::free(temp, q); +} +// A wrapper for sycl fetch_image function for the byte addressing image. +template +DataT fetch_image_by_byte( + const sycl::ext::oneapi::experimental::unsampled_image_handle &imageHandle, + CoordT &&coords) { + if constexpr (std::is_scalar_v) { + return sycl::ext::oneapi::experimental::fetch_image( + imageHandle, coords / sizeof(DataT)); + } else { + coords[0] = coords[0] / sizeof(DataT); + return sycl::ext::oneapi::experimental::fetch_image( + imageHandle, coords); + } +} + +using image_mem_wrapper_ptr = image_mem_wrapper *; +#ifdef _WIN32 +using external_mem_wrapper_ptr = external_mem_wrapper *; +#else +using external_mem_wrapper_ptr = external_mem_wrapper_base *; +#endif // _WIN32 +using external_sem_wrapper_ptr = external_sem_wrapper *; +using bindless_image_wrapper_base_p = bindless_image_wrapper_base *; + +#endif + +} // namespace experimental +} // namespace dpct + +#endif // !__DPCT_BINDLESS_IMAGE_HPP__ diff --git a/sycl/include/dpct/blas_gemm_utils.hpp b/sycl/include/dpct/blas_gemm_utils.hpp new file mode 100644 index 0000000..f41fe07 --- /dev/null +++ b/sycl/include/dpct/blas_gemm_utils.hpp @@ -0,0 +1,896 @@ +//==---- blas_gemm_utils.hpp ----------------------*- C++ -*----------------==// +// +// Copyright (C) Intel Corporation +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// See https://llvm.org/LICENSE.txt for license information. +// +//===----------------------------------------------------------------------===// +// This file contains the implementation of GEneral Matrix Multiplication by +// using oneDNN. More datatype combinations and the epilogue can be supported by +// oneDNN, which is not available in blas_utils.hpp using oneMKL. +//===----------------------------------------------------------------------===// + +#ifndef __DPCT_BLAS_GEMM_UTILS_HPP__ +#define __DPCT_BLAS_GEMM_UTILS_HPP__ + +#include "compat_service.hpp" +#include "blas_utils.hpp" +#include "dnnl_utils.hpp" + +namespace dpct::blas_gemm::experimental { +enum class order_t : std::uint8_t { + col, + row, + col32, + col4_4r2_8c, + col32_2r_4r4 +}; +} // namespace dpct::blas_gemm::experimental + +#include "detail/blas_gemm_utils_detail.hpp" + +namespace dpct::blas_gemm::experimental { +enum class pointer_mode_t { + host, + device, + device_vector, + alpha_device_vector_beta_zero, + alpha_device_vector_beta_host +}; +enum class epilogue_t { + nop = 1, + relu, + bias, + gelu, + gelu_bias, + gelu_aux, + gelu_aux_bias, + dgelu, + bgradb +}; + +class descriptor; +using descriptor_ptr = descriptor *; +class matrix_layout_t; +using matrix_layout_ptr = matrix_layout_t *; +class matmul_desc_t; +using matmul_desc_ptr = matmul_desc_t *; +class transform_desc_t; +using transform_desc_ptr = transform_desc_t *; + +class descriptor { +public: + descriptor() {} + void init(sycl::queue *q_ptr) { + _engine = ::dnnl::sycl_interop::make_engine(q_ptr->get_device(), + q_ptr->get_context()); + _engine_stream = ::dnnl::sycl_interop::make_stream(_engine, *q_ptr); + } + ::dnnl::engine get_engine() const noexcept { return _engine; } + ::dnnl::stream get_engine_stream() const noexcept { return _engine_stream; }; + +private: + ::dnnl::engine _engine; + ::dnnl::stream _engine_stream; +}; + +class matrix_layout_t { +public: + enum class attribute { + type, + order, + rows, + cols, + ld, + batch_count, + strided_batch_offset + }; + + matrix_layout_t(library_data_t type, std::uint64_t rows, std::uint64_t cols, + std::int64_t ld) + : _type(type), _rows(rows), _cols(cols), _ld(ld) {} + + void set_attribute(attribute attr, const void *mem) { + get_set_attr(attr, const_cast(mem)); + } + void get_attribute(attribute attr, void *mem) { + get_set_attr(attr, mem); + } + +private: + template void get_set_attr(attribute attr, void *mem) { +#define CASE(tag) \ + case attribute::tag: \ + if constexpr (is_set) { \ + _##tag = *static_cast(mem); \ + } else { \ + *static_cast(mem) = _##tag; \ + } \ + break; + switch (attr) { + CASE(type) + CASE(order) + CASE(rows) + CASE(cols) + CASE(ld) + CASE(batch_count) + CASE(strided_batch_offset) + } +#undef CASE + } + + library_data_t _type; + order_t _order = order_t::col; + std::uint64_t _rows; + std::uint64_t _cols; + std::int64_t _ld; + std::uint64_t _batch_count = 1; + std::uint64_t _strided_batch_offset = 0; + + friend sycl::event matmul(descriptor_ptr handle, matmul_desc_ptr computeDesc, + const void *alpha, const void *a, + matrix_layout_ptr a_desc, const void *b, + matrix_layout_ptr b_desc, const void *beta, + const void *c, matrix_layout_ptr c_desc, void *d, + matrix_layout_ptr d_desc, + ::dpct::cs::queue_ptr q_ptr); + friend sycl::event + matrix_transform(transform_desc_ptr transform_desc, const void *alpha, + const void *a, matrix_layout_ptr a_desc, const void *beta, + const void *b, matrix_layout_ptr b_desc, void *c, + matrix_layout_ptr c_desc, ::dpct::cs::queue_ptr q_ptr); +}; + +class matmul_desc_t { +public: + enum class attribute { + compute_type, + scale_type, + bias_data_type, + bias_pointer, + pointer_mode, + trans_a, + trans_b, + trans_c, + epilogue, + epilogue_aux_ld, + epilogue_aux_pointer, + epilogue_aux_data_type, + a_scale_pointer, + b_scale_pointer, + d_scale_pointer, + absmax_d_pointer, + unsupport + }; + + matmul_desc_t(compute_type compute_type, library_data_t scale_type) + : _compute_type(compute_type), _scale_type(scale_type) {} + + void set_attribute(attribute attr, const void *mem) { + if (attr != attribute::unsupport) + get_set_attr(attr, const_cast(mem)); + } + void get_attribute(attribute attr, void *mem) { + if (attr != attribute::unsupport) + get_set_attr(attr, mem); + } + +private: + template void get_set_attr(attribute attr, void *mem) { +#define CASE(tag) \ + case attribute::tag: \ + if constexpr (is_set) { \ + _##tag = *static_cast(mem); \ + } else { \ + *static_cast(mem) = _##tag; \ + } \ + break; + switch (attr) { + CASE(compute_type) + CASE(scale_type) + CASE(bias_data_type) + CASE(bias_pointer) + CASE(pointer_mode) + CASE(trans_a) + CASE(trans_b) + CASE(trans_c) + CASE(epilogue) + CASE(a_scale_pointer) + CASE(b_scale_pointer) + CASE(d_scale_pointer) + CASE(absmax_d_pointer) + CASE(epilogue_aux_ld) + CASE(epilogue_aux_pointer) + CASE(epilogue_aux_data_type) + default: + break; + } +#undef CASE + } + + compute_type _compute_type; + library_data_t _scale_type; + library_data_t _bias_data_type = library_data_t::real_float; + pointer_mode_t _pointer_mode = pointer_mode_t::host; + oneapi::mkl::transpose _trans_a = oneapi::mkl::transpose::nontrans; + oneapi::mkl::transpose _trans_b = oneapi::mkl::transpose::nontrans; + oneapi::mkl::transpose _trans_c = oneapi::mkl::transpose::nontrans; + epilogue_t _epilogue = epilogue_t::nop; + library_data_t _epilogue_aux_data_type = library_data_t::real_float; + size_t _epilogue_aux_ld = 0; + void *_a_scale_pointer = nullptr; + void *_b_scale_pointer = nullptr; + void *_d_scale_pointer = nullptr; + void *_absmax_d_pointer = nullptr; + void *_bias_pointer = nullptr; + void *_epilogue_aux_pointer = nullptr; + + friend sycl::event matmul(descriptor_ptr handle, matmul_desc_ptr computeDesc, + const void *alpha, const void *a, + matrix_layout_ptr a_desc, const void *b, + matrix_layout_ptr b_desc, const void *beta, + const void *c, matrix_layout_ptr c_desc, void *d, + matrix_layout_ptr d_desc, + ::dpct::cs::queue_ptr q_ptr); +}; + +/// This function does the following operations: +/// (1) D_temp = epilogue(alpha * scale_a * op_a(A) * scale_b * op_b(B) + beta * C) +/// (2) Amax = absmax(D_temp) when matmul_desc_t::attribute::absmax_d_pointer is specified +/// (3) D = scale_d * D_temp +/// "op_a" is specified by the matmul_desc_t::attribute::trans_a +/// (default is nontrans) +/// "op_b" is specified by the matmul_desc_t::attribute::trans_b +/// (default is nontrans) +/// "scale_a" is specified by the matmul_desc_t::attribute::a_scale_pointer +/// (default is nullptr, which behaves as 1.0) +/// "scale_b" is specified by the matmul_desc_t::attribute::b_scale_pointer +/// (default is nullptr, which behaves as 1.0) +/// "scale_d" is specified by the matmul_desc_t::attribute::d_scale_pointer +/// (default is nullptr, which behaves as 1.0) +/// "alpha" can be a scalar value or a vector, which is specified by the +/// matmul_desc_tattribute::::pointer_mode +/// "epilogue" is specified by the matmul_desc_t::attribute::epilogue +/// Currently, this function only supports the following type combinations: +/// scale_type==int32 && a_type==int8 && b_type==int8 && c_type==int32; +/// scale_type==float && a_type==int8 && b_type==int8 && c_type==int8; +/// scale_type==float && a_type==int8 && b_type==int8 && c_type==int32; +/// scale_type==float && a_type==float && b_type==float && c_type==float. +/// Currently, this function only supports beta==0 or beta==1. +/// Currently, this function only supports the relu, bias, gelu, gelu_bias, +/// gelu_aux, gelu_aux_bias, dgelu and bgradb epilogue. +/// NOTE: Non-col-major matrix will be converted to col-major matrix before. +/// TODO: Impl row-major matmul without layout conversion. +/// multiplication and converted back after multiplication. +/// \param [in] handle A handle containing context info. +/// \param [in] compute_desc Describe the computation. +/// \param [in] alpha Scaling factor alpha. +/// \param [in] a Input matrix A. +/// \param [in] a_desc Describe the matrix A. +/// \param [in] b Input matrix B. +/// \param [in] b_desc Describe the matrix B. +/// \param [in] beta Scaling factor beta. +/// \param [in] c Input matrix C. +/// \param [in] c_desc Describe the matrix C. +/// \param [out] d Output matrix D. +/// \param [in] d_desc Describe the matrix D. +/// \param [in] q_ptr The queue where the routine should be executed. +inline sycl::event matmul(descriptor_ptr handle, matmul_desc_ptr compute_desc, + const void *alpha, const void *a, + matrix_layout_ptr a_desc, const void *b, + matrix_layout_ptr b_desc, const void *beta, + const void *c, matrix_layout_ptr c_desc, void *d, + matrix_layout_ptr d_desc, + ::dpct::cs::queue_ptr q_ptr) { + const size_t m = compute_desc->_trans_a == oneapi::mkl::transpose::nontrans + ? a_desc->_rows + : a_desc->_cols; + const size_t n = d_desc->_cols; + const size_t k = compute_desc->_trans_b == oneapi::mkl::transpose::nontrans + ? b_desc->_rows + : b_desc->_cols; + const library_data_t a_type = a_desc->_type; + const library_data_t b_type = b_desc->_type; + const library_data_t c_type = c_desc->_type; + const library_data_t d_type = d_desc->_type; + const library_data_t scale_type = compute_desc->_scale_type; + + if (!q_ptr) + q_ptr = &::dpct::cs::get_default_queue(); + handle->init(q_ptr); + bool vector_alpha = false; + bool device_alpha = false; + if (compute_desc->_pointer_mode == pointer_mode_t::device_vector || + compute_desc->_pointer_mode == + pointer_mode_t::alpha_device_vector_beta_zero || + compute_desc->_pointer_mode == + pointer_mode_t::alpha_device_vector_beta_host) { + vector_alpha = true; + device_alpha = true; + } else if (compute_desc->_pointer_mode == pointer_mode_t::device) { + device_alpha = true; + } + + bool beta_is_zero = true; + if (beta != nullptr) { + int beta_value = detail::type_dispatch( + compute_desc->_scale_type, beta, q_ptr); + if (beta_value != 0) { + beta_is_zero = false; + if (beta_value != 1) + throw std::runtime_error( + "dpct::blas_gemm::experimental::matmul() does " + "not support non-zero and non-one beta currently."); + } + } + + if (compute_desc->_epilogue != epilogue_t::nop && + compute_desc->_epilogue != epilogue_t::relu && + compute_desc->_epilogue != epilogue_t::bias && + compute_desc->_epilogue != epilogue_t::gelu && + compute_desc->_epilogue != epilogue_t::gelu_bias && + compute_desc->_epilogue != epilogue_t::gelu_aux && + compute_desc->_epilogue != epilogue_t::gelu_aux_bias && + compute_desc->_epilogue != epilogue_t::dgelu && + compute_desc->_epilogue != epilogue_t::bgradb) { + throw std::runtime_error( + "dpct::blas_gemm::experimental::matmul() only " + "supports relu, bias, gelu, gelu_bias, gelu_aux, " + "gelu_aux_bias, dgelu and bgradb epilogue currently."); + } + + if (!(compute_desc->_scale_type == library_data_t::real_int32 && + a_desc->_type == library_data_t::real_int8 && + b_desc->_type == library_data_t::real_int8 && + c_desc->_type == library_data_t::real_int32) && + !(compute_desc->_scale_type == library_data_t::real_float && + a_desc->_type == library_data_t::real_int8 && + b_desc->_type == library_data_t::real_int8 && + c_desc->_type == library_data_t::real_int8) && + !(compute_desc->_scale_type == library_data_t::real_float && + a_desc->_type == library_data_t::real_int8 && + b_desc->_type == library_data_t::real_int8 && + c_desc->_type == library_data_t::real_int32) && + !(compute_desc->_scale_type == library_data_t::real_float && + a_desc->_type == library_data_t::real_float && + b_desc->_type == library_data_t::real_float && + c_desc->_type == library_data_t::real_float)) { + throw std::runtime_error( + "dpct::blas_gemm::experimental::matmul() only supports data type " + "combinataions:\n scale_type==int32 && a_type==int8 && b_type==int8" + "&& c_type==int32,\n scale_type==float && a_type==int8 && " + "b_type==int8 && c_type==int8,\n scale_type==float && a_type==int8" + "&& b_type==int8 && c_type==int32 or\n scale_type==float && " + "a_type==float" + "&& b_type==float && c_type==float."); + } + + if (a_desc->_batch_count != b_desc->_batch_count || + a_desc->_batch_count != c_desc->_batch_count || + a_desc->_batch_count != d_desc->_batch_count) { + throw std::runtime_error("dpct::blas_gemm::experimental::matmul() does not " + "support different batch count."); + } + +#ifdef DPCT_USM_LEVEL_NONE + if (a_desc->_batch_count != 1) { + throw std::runtime_error( + "dpct::blas_gemm::experimental::matmul() only supports " + "batch mode with USM enabled."); + } +#endif + + size_t a_elm_size = dpct::detail::library_data_size[static_cast( + a_desc->_type)] / + 8; + size_t b_elm_size = dpct::detail::library_data_size[static_cast( + b_desc->_type)] / + 8; + size_t c_elm_size = dpct::detail::library_data_size[static_cast( + c_desc->_type)] / + 8; + size_t d_elm_size = dpct::detail::library_data_size[static_cast( + d_desc->_type)] / + 8; + + static const auto matmul_single = + [](descriptor_ptr handle, matmul_desc_ptr compute_desc, const void *alpha, + const void *a, matrix_layout_ptr a_desc, const void *b, + matrix_layout_ptr b_desc, const void *beta, const void *c, + matrix_layout_ptr c_desc, void *d, matrix_layout_ptr d_desc, + ::dpct::cs::queue_ptr q_ptr, const size_t m, const size_t n, + const size_t k, const library_data_t a_type, + const library_data_t b_type, const library_data_t c_type, + const library_data_t d_type, const library_data_t scale_type, + bool vector_alpha, bool device_alpha, bool beta_is_zero, + size_t a_elm_size, size_t b_elm_size, size_t c_elm_size, + size_t d_elm_size) -> sycl::event { + // For non-col_major matrix, convert it to col_major. + const void *new_a = a; + const void *new_b = b; + const void *new_c = c; + void *new_d = d; + bool new_b_allocated = false; + bool new_c_allocated = false; + bool new_d_allocated = false; + size_t new_lda = a_desc->_ld, new_ldb = b_desc->_ld, new_ldc = c_desc->_ld, + new_ldd = d_desc->_ld; + std::vector transform_events; + + if (a_desc->_order != order_t::col) + new_lda = a_desc->_rows; + new_a = ::dpct::cs::malloc(a_elm_size * a_desc->_cols * new_lda, *q_ptr); + sycl::event e_init; + if (a_desc->_order != order_t::col) + e_init = detail::type_dispatch( + a_desc->_type, q_ptr, a_desc->_rows, a_desc->_cols, a_desc->_ld, + a_desc->_order, (const std::int8_t *)a, new_lda, order_t::col, + (std::int8_t *)new_a, std::vector{}); + else + e_init = ::dpct::cs::memcpy( + *q_ptr, (void *)new_a, a, a_elm_size * a_desc->_cols * new_lda, + ::dpct::cs::memcpy_direction::device_to_device); + + // alpha = alpha * scale_a * scale_b + sycl::event e_scale_new_a = detail::scale_new_a( + q_ptr, m, k, (void *)new_a, a_type, alpha, scale_type, vector_alpha, + device_alpha, compute_desc->_a_scale_pointer, + compute_desc->_b_scale_pointer, {e_init}); + + transform_events.push_back(e_scale_new_a); + + if (b_desc->_order != order_t::col) { + new_ldb = b_desc->_rows; + new_b = ::dpct::cs::malloc(b_elm_size * b_desc->_cols * new_ldb, *q_ptr); + new_b_allocated = true; + sycl::event e = detail::type_dispatch( + b_desc->_type, q_ptr, b_desc->_rows, b_desc->_cols, b_desc->_ld, + b_desc->_order, b, new_ldb, order_t::col, const_cast(new_b), + std::vector{}); + transform_events.push_back(e); + } + + if (!beta_is_zero && c_desc->_order != order_t::col) { + new_ldc = c_desc->_rows; + new_c = ::dpct::cs::malloc(c_elm_size * c_desc->_cols * new_ldc, *q_ptr); + new_c_allocated = true; + sycl::event e = detail::type_dispatch( + c_desc->_type, q_ptr, c_desc->_rows, c_desc->_cols, c_desc->_ld, + c_desc->_order, c, new_ldc, order_t::col, const_cast(new_c), + std::vector{}); + transform_events.push_back(e); + } + + if (d_desc->_order != order_t::col) { + new_ldd = d_desc->_rows; + new_d = ::dpct::cs::malloc(d_elm_size * d_desc->_cols * new_ldd, *q_ptr); + new_d_allocated = true; + } + + // start to call oneDNN matmul primitive + // a,d are col_major, b is row_major + const ::dnnl::memory::dim M = m; + const ::dnnl::memory::dim N = n; + const ::dnnl::memory::dim K = k; + + ::dnnl::memory::dims src_dims = {M, K}; + ::dnnl::memory::dims weights_dims = {K, N}; + ::dnnl::memory::dims bias_dims = {M, N}; + ::dnnl::memory::dims dst_dims = {M, N}; + + const ::dnnl::memory::dims src_strides = + compute_desc->_trans_a == oneapi::mkl::transpose::nontrans + ? ::dnnl::memory::dims{1, static_cast(new_lda)} + : ::dnnl::memory::dims{static_cast(new_lda), 1}; + const ::dnnl::memory::dims weights_strides = + compute_desc->_trans_b == oneapi::mkl::transpose::nontrans + ? ::dnnl::memory::dims{1, static_cast(new_ldb)} + : ::dnnl::memory::dims{static_cast(new_ldb), 1}; + const ::dnnl::memory::dims bias_strides = + ::dnnl::memory::dims{1, static_cast(new_ldc)}; + const ::dnnl::memory::dims dst_strides = + ::dnnl::memory::dims{1, static_cast(new_ldd)}; + + auto src_md = ::dnnl::memory::desc( + src_dims, dpct::dnnl::memory_desc_ext::to_dnnl_data_type(a_type), + src_strides); + auto weights_md = ::dnnl::memory::desc( + weights_dims, dpct::dnnl::memory_desc_ext::to_dnnl_data_type(b_type), + weights_strides); + auto bias_md = ::dnnl::memory::desc( + bias_dims, dpct::dnnl::memory_desc_ext::to_dnnl_data_type(c_type), + bias_strides); + auto dst_md = ::dnnl::memory::desc( + dst_dims, dpct::dnnl::memory_desc_ext::to_dnnl_data_type(d_type), + dst_strides); + + auto *src_mem = + new ::dnnl::memory(src_md, handle->get_engine(), DNNL_MEMORY_NONE); + auto *weights_mem = + new ::dnnl::memory(weights_md, handle->get_engine(), DNNL_MEMORY_NONE); + auto *bias_mem = + new ::dnnl::memory(bias_md, handle->get_engine(), DNNL_MEMORY_NONE); + auto *dst_mem = + new ::dnnl::memory(dst_md, handle->get_engine(), DNNL_MEMORY_NONE); + +#ifdef DPCT_USM_LEVEL_NONE + detail::type_dispatch(a_type, src_mem, new_a); + detail::type_dispatch(b_type, weights_mem, new_b); + if (!beta_is_zero) + detail::type_dispatch(c_type, bias_mem, new_c); + detail::type_dispatch(d_type, dst_mem, new_d); +#else + src_mem->set_data_handle(const_cast(new_a)); + weights_mem->set_data_handle(const_cast(new_b)); + if (!beta_is_zero) + bias_mem->set_data_handle(const_cast(new_c)); + dst_mem->set_data_handle(new_d); +#endif + + std::unordered_map matmul_args; + matmul_args.insert({DNNL_ARG_SRC, *src_mem}); + matmul_args.insert({DNNL_ARG_WEIGHTS, *weights_mem}); + matmul_args.insert({DNNL_ARG_DST, *dst_mem}); + ::dnnl::primitive_attr matmul_attr; + + ::dnnl::post_ops matmul_ops; + if (!beta_is_zero) { + matmul_ops.append_binary(::dnnl::algorithm::binary_add, bias_md); + matmul_args.insert({DNNL_ARG_ATTR_MULTIPLE_POST_OP(matmul_ops.len() - 1) | + DNNL_ARG_SRC_1, + *bias_mem}); + } + + ::dnnl::memory *po_bias_mem = nullptr; + auto po_bias_md = + ::dnnl::memory::desc(::dnnl::memory::dims{M, 1}, + dpct::dnnl::memory_desc_ext::to_dnnl_data_type( + compute_desc->_bias_data_type), + ::dnnl::memory::dims{1, M}); + if (compute_desc->_epilogue == epilogue_t::bias || + compute_desc->_epilogue == epilogue_t::gelu_bias || + compute_desc->_epilogue == epilogue_t::gelu_aux_bias) { + po_bias_mem = new ::dnnl::memory(po_bias_md, handle->get_engine(), + DNNL_MEMORY_NONE); +#ifdef DPCT_USM_LEVEL_NONE + detail::type_dispatch( + compute_desc->_bias_data_type, po_bias_mem, + compute_desc->_bias_pointer); +#else + po_bias_mem->set_data_handle(compute_desc->_bias_pointer); +#endif + } + + ::dnnl::memory *po_bias_bgradb_mem = nullptr; + auto po_bias_bgradb_md = ::dnnl::memory::desc( + compute_desc->_trans_b == oneapi::mkl::transpose::nontrans + ? ::dnnl::memory::dims{N, 1} + : ::dnnl::memory::dims{1, N}, + dpct::dnnl::memory_desc_ext::to_dnnl_data_type( + compute_desc->_bias_data_type), + compute_desc->_trans_b == oneapi::mkl::transpose::nontrans + ? ::dnnl::memory::dims{1, N} + : ::dnnl::memory::dims{N, 1}); + if (compute_desc->_epilogue == epilogue_t::bgradb) { + po_bias_bgradb_mem = new ::dnnl::memory( + po_bias_bgradb_md, handle->get_engine(), DNNL_MEMORY_NONE); +#ifdef DPCT_USM_LEVEL_NONE + detail::type_dispatch( + compute_desc->_bias_data_type, po_bias_bgradb_mem, + compute_desc->_bias_pointer); +#else + po_bias_bgradb_mem->set_data_handle(compute_desc->_bias_pointer); +#endif + } + + ::dnnl::memory *po_aux_mem = nullptr; + auto po_aux_md = ::dnnl::memory::desc( + ::dnnl::memory::dims{M, N}, + dpct::dnnl::memory_desc_ext::to_dnnl_data_type( + compute_desc->_epilogue_aux_data_type), + ::dnnl::memory::dims{ + 1, static_cast(compute_desc->_epilogue_aux_ld)}); + if (compute_desc->_epilogue == epilogue_t::dgelu) { + po_aux_mem = + new ::dnnl::memory(po_aux_md, handle->get_engine(), DNNL_MEMORY_NONE); +#ifdef DPCT_USM_LEVEL_NONE + detail::type_dispatch( + compute_desc->_epilogue_aux_data_type, po_aux_mem, + compute_desc->_epilogue_aux_pointer); +#else + po_aux_mem->set_data_handle(compute_desc->_epilogue_aux_pointer); +#endif + } + + switch (compute_desc->_epilogue) { + case epilogue_t::relu: + matmul_ops.append_eltwise(::dnnl::algorithm::eltwise_relu, 0.f, 0.f); + break; + case epilogue_t::bias: + case epilogue_t::gelu_bias: { + matmul_ops.append_binary(::dnnl::algorithm::binary_add, po_bias_md); + matmul_args.insert({DNNL_ARG_ATTR_MULTIPLE_POST_OP(matmul_ops.len() - 1) | + DNNL_ARG_SRC_1, + *po_bias_mem}); + if (compute_desc->_epilogue == epilogue_t::gelu_bias) + matmul_ops.append_eltwise(::dnnl::algorithm::eltwise_gelu_tanh, 0.f, + 0.f); + break; + } + case epilogue_t::gelu: + matmul_ops.append_eltwise(::dnnl::algorithm::eltwise_gelu_tanh, 0.f, 0.f); + break; + default: + break; + } + + matmul_attr.set_post_ops(matmul_ops); + + auto matmul_pd = ::dnnl::matmul::primitive_desc( + handle->get_engine(), src_md, weights_md, dst_md, matmul_attr); + auto matmul_prim = ::dnnl::matmul(matmul_pd); + sycl::event matmul_prim_event = + ::dnnl::sycl_interop::execute(matmul_prim, handle->get_engine_stream(), + matmul_args, transform_events); + + // post-op implemented by separate primitives + sycl::event post_op_prim_event; + if (compute_desc->_epilogue == epilogue_t::gelu_aux || + compute_desc->_epilogue == epilogue_t::gelu_aux_bias) { + sycl::event prev_event = matmul_prim_event; + if (compute_desc->_epilogue == epilogue_t::gelu_aux_bias) { + auto po_bias_pd = ::dnnl::binary::primitive_desc( + handle->get_engine(), ::dnnl::algorithm::binary_add, dst_md, + po_bias_md, dst_md); + auto po_bias_prim = ::dnnl::binary(po_bias_pd); + std::unordered_map po_bias_args; + po_bias_args.insert({DNNL_ARG_SRC_0, *dst_mem}); + po_bias_args.insert({DNNL_ARG_SRC_1, *po_bias_mem}); + po_bias_args.insert({DNNL_ARG_DST, *dst_mem}); + sycl::event prev_event = ::dnnl::sycl_interop::execute( + po_bias_prim, handle->get_engine_stream(), po_bias_args, + {matmul_prim_event}); + } + size_t size_of_element = + dpct::detail::library_data_size[static_cast( + d_desc->_type)] / + 8; + sycl::event copy_e = dpct::blas::matrix_mem_copy_async( + compute_desc->_epilogue_aux_pointer, new_d, + compute_desc->_epilogue_aux_ld, d_desc->_ld, m, n, size_of_element, + ::dpct::cs::memcpy_direction::automatic, *q_ptr, {prev_event}); + + auto gelu_pd = ::dnnl::eltwise_forward::primitive_desc( + handle->get_engine(), ::dnnl::prop_kind::forward_training, + ::dnnl::algorithm::eltwise_gelu_tanh, dst_md, dst_md); + auto gelu_prim = ::dnnl::eltwise_forward(gelu_pd); + std::unordered_map gelu_args; + gelu_args.insert({DNNL_ARG_SRC, *dst_mem}); + gelu_args.insert({DNNL_ARG_DST, *dst_mem}); + post_op_prim_event = ::dnnl::sycl_interop::execute( + gelu_prim, handle->get_engine_stream(), gelu_args, {copy_e}); + } else if (compute_desc->_epilogue == epilogue_t::dgelu) { + auto gelu_pd = ::dnnl::eltwise_forward::primitive_desc( + handle->get_engine(), ::dnnl::prop_kind::forward_training, + ::dnnl::algorithm::eltwise_gelu_tanh, po_aux_md, po_aux_md); + auto dgelu_pd = ::dnnl::eltwise_backward::primitive_desc( + handle->get_engine(), ::dnnl::algorithm::eltwise_gelu_tanh, dst_md, + dst_md, po_aux_md, gelu_pd); + auto dgelu_prim = ::dnnl::eltwise_backward(dgelu_pd); + std::unordered_map dgelu_args; + dgelu_args.insert({DNNL_ARG_SRC, *po_aux_mem}); + dgelu_args.insert({DNNL_ARG_DIFF_DST, *dst_mem}); + dgelu_args.insert({DNNL_ARG_DIFF_SRC, *dst_mem}); + post_op_prim_event = + ::dnnl::sycl_interop::execute(dgelu_prim, handle->get_engine_stream(), + dgelu_args, {matmul_prim_event}); + } else if (compute_desc->_epilogue == epilogue_t::bgradb) { + auto reduction_pd = ::dnnl::reduction::primitive_desc( + handle->get_engine(), ::dnnl::algorithm::reduction_sum, weights_md, + po_bias_bgradb_md, 0.f, 0.f); + auto reduction_prim = ::dnnl::reduction(reduction_pd); + std::unordered_map reduction_args; + reduction_args.insert({DNNL_ARG_SRC, *weights_mem}); + reduction_args.insert({DNNL_ARG_DST, *po_bias_bgradb_mem}); + post_op_prim_event = ::dnnl::sycl_interop::execute( + reduction_prim, handle->get_engine_stream(), reduction_args, + {matmul_prim_event}); + } + +#ifndef DPCT_USM_LEVEL_NONE + // WA to avoid incorrect result on CPU with USM + if (q_ptr->get_device().is_cpu()) { + matmul_prim_event.wait(); + post_op_prim_event.wait(); + } +#endif + // end of calling oneDNN + + sycl::event absmax_d_event; + if (auto absmax_ptr = compute_desc->_absmax_d_pointer) { + absmax_d_event = detail::type_dispatch( + d_desc->_type, absmax_ptr, new_d, new_ldd, d_desc->_rows, + d_desc->_cols, q_ptr, + std::vector{matmul_prim_event, post_op_prim_event}); + } + + sycl::event scale_d_event; + if (auto d_scale_ptr = compute_desc->_d_scale_pointer) { + scale_d_event = detail::type_dispatch( + d_desc->_type, d_scale_ptr, new_d, new_ldd, d_desc->_rows, + d_desc->_cols, q_ptr, compute_desc->_scale_type, + std::vector{matmul_prim_event, absmax_d_event, + post_op_prim_event}); + } + + sycl::event transform_d_event; + if (d_desc->_order != order_t::col) { + transform_d_event = detail::type_dispatch( + d_desc->_type, q_ptr, d_desc->_rows, d_desc->_cols, new_ldd, + order_t::col, new_d, d_desc->_ld, d_desc->_order, d, + std::vector{matmul_prim_event, absmax_d_event, + post_op_prim_event}); + } + + sycl::event free_event = q_ptr->submit([&](sycl::handler &cgh) { + cgh.depends_on({transform_d_event, matmul_prim_event, absmax_d_event, + post_op_prim_event}); + cgh.host_task([=] { + delete src_mem; + delete weights_mem; + delete bias_mem; + delete dst_mem; + if (po_bias_mem) + delete po_bias_mem; + if (po_bias_bgradb_mem) + delete po_bias_bgradb_mem; + if (po_aux_mem) + delete po_aux_mem; + ::dpct::cs::free((void *)new_a, *q_ptr); + if (new_b_allocated) + ::dpct::cs::free((void *)new_b, *q_ptr); + if (new_c_allocated) + ::dpct::cs::free((void *)new_c, *q_ptr); + if (new_d_allocated) + ::dpct::cs::free((void *)new_d, *q_ptr); + }); + }); + return free_event; + }; + + std::vector events; + const std::byte *offsetted_a = static_cast(a); + const std::byte *offsetted_b = static_cast(b); + const std::byte *offsetted_c = static_cast(c); + std::byte *offsetted_d = static_cast(d); + for (std::uint64_t i = 0; i < a_desc->_batch_count; i++) { + sycl::event e = matmul_single( + handle, compute_desc, alpha, offsetted_a, a_desc, offsetted_b, b_desc, + beta, offsetted_c, c_desc, offsetted_d, d_desc, q_ptr, m, n, k, a_type, + b_type, c_type, d_type, scale_type, vector_alpha, device_alpha, + beta_is_zero, a_elm_size, b_elm_size, c_elm_size, d_elm_size); + events.push_back(e); + + offsetted_a += a_elm_size * a_desc->_strided_batch_offset; + offsetted_b += b_elm_size * b_desc->_strided_batch_offset; + offsetted_c += c_elm_size * c_desc->_strided_batch_offset; + offsetted_d += d_elm_size * d_desc->_strided_batch_offset; + } + + return q_ptr->single_task(events, [] {}); +} + +class transform_desc_t { +public: + enum class attribute { scale_type, pointer_mode, trans_a, trans_b }; + + transform_desc_t(library_data_t scale_type) : _scale_type(scale_type) {} + void set_attribute(attribute attr, const void *mem) { + get_set_attr(attr, const_cast(mem)); + } + void get_attribute(attribute attr, void *mem) { + get_set_attr(attr, mem); + } + +private: + template void get_set_attr(attribute attr, void *mem) { +#define CASE(tag) \ + case attribute::tag: \ + if constexpr (is_set) { \ + _##tag = *static_cast(mem); \ + } else { \ + *static_cast(mem) = _##tag; \ + } \ + break; + switch (attr) { + CASE(scale_type) + CASE(pointer_mode) + CASE(trans_a) + CASE(trans_b) + } +#undef CASE + } + + library_data_t _scale_type; + pointer_mode_t _pointer_mode = pointer_mode_t::host; + oneapi::mkl::transpose _trans_a = oneapi::mkl::transpose::nontrans; + oneapi::mkl::transpose _trans_b = oneapi::mkl::transpose::nontrans; + + friend sycl::event + matrix_transform(transform_desc_ptr transform_desc, const void *alpha, + const void *a, matrix_layout_ptr a_desc, const void *beta, + const void *b, matrix_layout_ptr b_desc, void *c, + matrix_layout_ptr c_desc, ::dpct::cs::queue_ptr q_ptr); +}; + +/// This function does operation: +/// C = alpha*transformation(A) + beta*transformation(B). +/// The "transformation" includes matrix transpose and layout conversion. +/// Currently it only supports alpha==1 && beta==0. +/// \param [in] transform_desc Describe the transformation. +/// \param [in] alpha Scaling factor alpha. +/// \param [in] a Input matrix A. +/// \param [in] a_desc Describe the matrix A. +/// \param [in] beta Scaling factor beta. +/// \param [in] b Input matrix B. +/// \param [in] b_desc Describe the matrix B. +/// \param [out] c Output matrix C. +/// \param [in] c_desc Describe the matrix C. +/// \param [in] q_ptr The queue where the routine should be executed. +inline sycl::event matrix_transform(transform_desc_ptr transform_desc, + const void *alpha, const void *a, + matrix_layout_ptr a_desc, const void *beta, + const void *b, matrix_layout_ptr b_desc, + void *c, matrix_layout_ptr c_desc, + ::dpct::cs::queue_ptr q_ptr) { + if (!q_ptr) + q_ptr = &::dpct::cs::get_default_queue(); + + if (transform_desc->_pointer_mode != pointer_mode_t::host) { + throw std::runtime_error( + "dpct::blas_gemm::experimental::matrix_transform() " + "only supports pointer_mode_t::host as pointer_mode currently."); + } + if (transform_desc->_scale_type != library_data_t::real_float) { + throw std::runtime_error( + "dpct::blas_gemm::experimental::matrix_transform() " + "only supports library_data_t::real_float as scale_type currently."); + } + + if (alpha != nullptr) { + if (1.0f != *reinterpret_cast(alpha)) + throw std::runtime_error( + "dpct::blas_gemm::experimental::matrix_transform() does not " + "support non-one alpha currently."); + } + + if (beta != nullptr) { + if (0.0f != *reinterpret_cast(beta)) + throw std::runtime_error( + "dpct::blas_gemm::experimental::matrix_transform() does not " + "support non-zero beta currently."); + } + + if (b != nullptr) { + throw std::runtime_error( + "dpct::blas_gemm::experimental::matrix_transform() does not " + "support matrix B currently."); + } + + if ((a_desc->_type != library_data_t::real_int8 || + c_desc->_type != library_data_t::real_int8) && + (a_desc->_type != library_data_t::real_int32 || + c_desc->_type != library_data_t::real_int32)) { + throw std::runtime_error( + "dpct::blas_gemm::experimental::matrix_transform() only supports " + "combinations of data types: a_type==real_int8&&c_type==real_int8, " + "a_type==real_int32&&c_type==real_int32."); + } + + return detail::type_dispatch( + a_desc->_type, q_ptr, a_desc->_rows, a_desc->_cols, a_desc->_ld, + a_desc->_order, a, c_desc->_ld, c_desc->_order, c, + std::vector{}); +} +} // namespace dpct::blas_gemm::experimental +#endif // __DPCT_BLAS_GEMM_UTILS_HPP__ diff --git a/sycl/include/dpct/blas_utils.hpp b/sycl/include/dpct/blas_utils.hpp new file mode 100644 index 0000000..4a58aad --- /dev/null +++ b/sycl/include/dpct/blas_utils.hpp @@ -0,0 +1,2599 @@ +//==---- blas_utils.hpp----------------------------*- C++ -*----------------==// +// +// Copyright (C) Intel Corporation +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// See https://llvm.org/LICENSE.txt for license information. +// +//===----------------------------------------------------------------------===// + +#ifndef __DPCT_BLAS_UTILS_HPP__ +#define __DPCT_BLAS_UTILS_HPP__ + +#include "compat_service.hpp" +#include "lib_common_utils.hpp" + +#include "detail/blas_utils_detail.hpp" + +namespace dpct { +namespace blas { + +/// Parameter input/output properties are: +/// in: input parameter +/// out: output parameter +/// in_out: input and output parameter +enum class parameter_inout_prop { in, out, in_out }; + +/// parameter_wrapper_t is a class to wrap the parameter to fit the oneMKL +/// interface. +/// E.g., +/// \code +/// void foo(sycl::queue q, int *res) { +/// // Declare the wrapper. +/// parameter_wrapper_t +/// res_wrapper(q, res); +/// // parameter_wrapper_t::get_ptr() is passed as a parameter. The result is +/// // saved into the wrapper. +/// oneapi::mkl::...(q, ..., res_wrapper.get_ptr()); +/// // The action to copy the result in the wrapper to the original variable +/// // is submitted when destructing the wrapper automatically. +/// } +/// \endcode +/// \tparam target_t Data type to fit oneMKL parameter data type. E.g., +/// get_ptr() returns \tparam target_t data type and can be used as oneMKL +/// parameter with USM memory configuration. +/// \tparam source_t Data type of the original parameter. +/// \tparam inout_prop The input/output property of the parameter. +template +class parameter_wrapper_t + : public detail::parameter_wrapper_base_t { + static_assert(inout_prop == parameter_inout_prop::out && + "Only parameter_inout_prop::out is supported if " + "target_t and source_t are not same."); + using base_t = detail::parameter_wrapper_base_t; + using base_t::_q; + using base_t::_source; + using base_t::_source_attribute; + using base_t::_target; + +public: + /// Constructor. Malloc the wrapper memory. + /// \param q The queue used for internal malloc and memcpy + /// \param source The original parameter + parameter_wrapper_t(sycl::queue q, source_t *source) : base_t(q, source, 1) {} + /// Destructor. Copy back content from wrapper memory to original memory + ~parameter_wrapper_t() { +#ifdef DPCT_USM_LEVEL_NONE + if (_source_attribute == + ::dpct::cs::detail::pointer_access_attribute::device_only) { + _q.submit([&](sycl::handler &cgh) { + auto from_acc = dpct::get_buffer(_target) + .template get_access(cgh); + auto to_acc = dpct::get_buffer(_source) + .template get_access(cgh); + cgh.single_task<::dpct::cs::kernel_name< + class parameter_wrapper_copyback, target_t, source_t>>( + [=]() { to_acc[0] = static_cast(from_acc[0]); }); + }); + } else { + source_t temp = + static_cast(dpct::get_host_ptr(_target)[0]); + *_source = temp; + } +#else + if (_source_attribute == + ::dpct::cs::detail::pointer_access_attribute::device_only) { + _q.template single_task<::dpct::cs::kernel_name< + class parameter_wrapper_copyback, target_t, source_t>>( + [t = _target, s = _source]() { *s = static_cast(*t); }); + } else { + target_t temp; + _q.memcpy(&temp, _target, sizeof(target_t)).wait(); + *_source = static_cast(temp); + } +#endif + } + /// Get the target memory of the wrapper to represent the wrapped variable + target_t *get_ptr() { return _target; } +}; + +/// parameter_wrapper_t is a class to wrap the parameter to fit the oneMKL +/// interface. +/// E.g., +/// \code +/// void foo(sycl::queue q, int *params, int ele_num) { +/// // Declare the wrapper. +/// parameter_wrapper_t params_wrapper( +/// q, params, ele_num); +/// // parameter_wrapper_t::get_ptr() is passed as a parameter. The result is +/// // saved into the wrapper. +/// oneapi::mkl::...(q, ..., params_wrapper.get_ptr()); +/// // The action to copy the result in the wrapper to the original variable +/// // is submitted when destructing the wrapper automatically. +/// } +/// \endcode +/// \tparam target_t Data type to fit oneMKL parameter data type. E.g., +/// get_ptr() returns \tparam target_t data type and can be used as oneMKL +/// parameter with USM memory configuration. +/// \tparam inout_prop The input/output property of the parameter. +template +class parameter_wrapper_t + : public detail::parameter_wrapper_base_t { + using base_t = detail::parameter_wrapper_base_t; + using base_t::_ele_num; + using base_t::_need_free; + using base_t::_q; + using base_t::_source; + using base_t::_source_attribute; + using base_t::_target; + +public: + /// Constructor. Malloc the wrapper memory. + /// \param q The queue used for internal malloc and memcpy + /// \param source The original parameter + /// \param ele_num Element number in \p source + parameter_wrapper_t(sycl::queue q, target_t *source, size_t ele_num = 1) + : base_t(q, source, ele_num) { + if constexpr (inout_prop != parameter_inout_prop::out) { + if (_need_free) { + ::dpct::cs::memcpy(_q, _target, _source, sizeof(target_t) * _ele_num, + ::dpct::cs::memcpy_direction::automatic); + } + } + } + + /// Constructor. Only vaild for parameter_inout_prop::in. + /// \param q The queue used for internal malloc and memcpy + /// \param source The original parameter + /// \param ele_num Element number in \p source + template + parameter_wrapper_t( + sycl::queue q, const target_t *source, size_t ele_num = 1, + typename std::enable_if::type * = 0) + : parameter_wrapper_t(q, const_cast(source), ele_num) {} + + /// Destructor. Copy back content from wrapper memory to original memory + ~parameter_wrapper_t() { + if constexpr (inout_prop != parameter_inout_prop::in) { + if (_need_free) { + sycl::event e = ::dpct::cs::memcpy( + _q, _source, _target, sizeof(target_t) * _ele_num, + ::dpct::cs::memcpy_direction::automatic); + (void)e; + if (_source_attribute == + ::dpct::cs::detail::pointer_access_attribute::host_only) + e.wait(); + } + } + } + /// Get the target memory of the wrapper to represent the wrapped variable + target_t *get_ptr() { return _target; } +}; + +using wrapper_int_to_int64_out = + parameter_wrapper_t; +using wrapper_int64_out = + parameter_wrapper_t; +using wrapper_float_out = + parameter_wrapper_t; +using wrapper_double_out = + parameter_wrapper_t; +using wrapper_float2_out = + parameter_wrapper_t; +using wrapper_double2_out = parameter_wrapper_t; +using wrapper_float_inout = + parameter_wrapper_t; +using wrapper_double_inout = + parameter_wrapper_t; +using wrapper_float2_inout = parameter_wrapper_t; +using wrapper_double2_inout = parameter_wrapper_t; +using wrapper_float_in = + parameter_wrapper_t; +using wrapper_double_in = + parameter_wrapper_t; + +/// Copy matrix data synchronously. The default leading dimension is column. +/// \param [out] to_ptr A pointer points to the destination location. +/// \param [in] from_ptr A pointer points to the source location. +/// \param [in] to_ld The leading dimension the destination matrix. +/// \param [in] from_ld The leading dimension the source matrix. +/// \param [in] rows The number of rows of the source matrix. +/// \param [in] cols The number of columns of the source matrix. +/// \param [in] elem_size The element size in bytes. +/// \param [in] direction The direction of the data copy. +/// \param [in] queue The queue where the routine should be executed. +/// \param [in] deps A list of events to wait for before starting copy. +inline void +matrix_mem_copy_sync(void *to_ptr, const void *from_ptr, std::int64_t to_ld, + std::int64_t from_ld, std::int64_t rows, std::int64_t cols, + std::int64_t elem_size, + ::dpct::cs::memcpy_direction direction = + ::dpct::cs::memcpy_direction::automatic, + sycl::queue &queue = ::dpct::cs::get_default_queue(), + const std::vector &deps = {}) { + if (to_ptr == from_ptr && to_ld == from_ld) + return; + if (to_ld == from_ld) { + size_t copy_size = elem_size * ((cols - 1) * (size_t)to_ld + rows); + ::dpct::cs::memcpy(queue, to_ptr, from_ptr, copy_size, direction, deps) + .wait(); + } else { + sycl::event::wait(::dpct::cs::memcpy( + queue, to_ptr, from_ptr, elem_size * to_ld, elem_size * from_ld, + elem_size * rows, cols, direction, deps)); + } +} +/// Copy matrix data asynchronously. The default leading dimension is column. +/// \return Output event to wait on to ensure copy is complete. +/// \param [out] to_ptr A pointer points to the destination location. +/// \param [in] from_ptr A pointer points to the source location. +/// \param [in] to_ld The leading dimension the destination matrix. +/// \param [in] from_ld The leading dimension the source matrix. +/// \param [in] rows The number of rows of the source matrix. +/// \param [in] cols The number of columns of the source matrix. +/// \param [in] elem_size The element size in bytes. +/// \param [in] direction The direction of the data copy. +/// \param [in] queue The queue where the routine should be executed. +/// \param [in] deps A list of events to wait for before starting copy. +inline sycl::event +matrix_mem_copy_async(void *to_ptr, const void *from_ptr, std::int64_t to_ld, + std::int64_t from_ld, std::int64_t rows, + std::int64_t cols, std::int64_t elem_size, + ::dpct::cs::memcpy_direction direction = + ::dpct::cs::memcpy_direction::automatic, + sycl::queue &queue = ::dpct::cs::get_default_queue(), + const std::vector &deps = {}) { + if (to_ptr == from_ptr && to_ld == from_ld) + return sycl::event(); + if (to_ld == from_ld) { + size_t copy_size = elem_size * ((cols - 1) * (size_t)to_ld + rows); + return ::dpct::cs::memcpy(queue, to_ptr, from_ptr, copy_size, direction, + deps); + } + auto events = ::dpct::cs::memcpy(queue, to_ptr, from_ptr, elem_size * to_ld, + elem_size * from_ld, elem_size * rows, cols, + direction, deps); + return queue.single_task(events, [] {}); +} + +/// Copy matrix data. The default leading dimension is column. +/// \param [out] to_ptr A pointer points to the destination location. +/// \param [in] from_ptr A pointer points to the source location. +/// \param [in] to_ld The leading dimension the destination matrix. +/// \param [in] from_ld The leading dimension the source matrix. +/// \param [in] rows The number of rows of the source matrix. +/// \param [in] cols The number of columns of the source matrix. +/// \param [in] elem_size The element size in bytes. +/// \param [in] direction The direction of the data copy. +/// \param [in] queue The queue where the routine should be executed. +/// \param [in] async If this argument is true, the return of the function +/// does NOT guarantee the copy is completed. +inline void +matrix_mem_copy(void *to_ptr, const void *from_ptr, std::int64_t to_ld, + std::int64_t from_ld, std::int64_t rows, std::int64_t cols, + std::int64_t elem_size, + ::dpct::cs::memcpy_direction direction = + ::dpct::cs::memcpy_direction::automatic, + sycl::queue &queue = ::dpct::cs::get_default_queue(), + bool async = false) { + if (async) + matrix_mem_copy_async(to_ptr, from_ptr, to_ld, from_ld, rows, cols, + elem_size, direction, queue); + else + matrix_mem_copy_sync(to_ptr, from_ptr, to_ld, from_ld, rows, cols, + elem_size, direction, queue); +} + +enum class math_mode : int { + mm_default, + mm_tf32, +}; + +using ::dpct::compute_type; + +class descriptor { +public: + void set_queue(::dpct::cs::queue_ptr q_ptr) noexcept { _queue_ptr = q_ptr; } + sycl::queue &get_queue() noexcept { return *_queue_ptr; } + void set_math_mode(math_mode mm) noexcept { _mm = mm; } + math_mode get_math_mode() const noexcept { return _mm; } + static inline void set_saved_queue(::dpct::cs::queue_ptr q_ptr) noexcept { + _saved_queue_ptr = q_ptr; + } + static inline sycl::queue &get_saved_queue() noexcept { + return *_saved_queue_ptr; + } + +private: + ::dpct::cs::queue_ptr _queue_ptr = &::dpct::cs::get_default_queue(); + math_mode _mm = math_mode::mm_default; + static inline ::dpct::cs::queue_ptr _saved_queue_ptr = + &::dpct::cs::get_default_queue(); +}; + +using descriptor_ptr = descriptor *; +} // namespace blas + +/// Get the value of \p s. +/// Copy the data to host synchronously, then return the data. +/// \param [in] p The pointer points the data. +/// \param [in] q The queue where the memory copy should be executed. +template inline T get_value(const T *s, sycl::queue &q) { + return detail::get_value(s, q); +} +template +inline std::complex get_value(const sycl::vec *s, sycl::queue &q) { + return detail::get_value(s, q); +} + +inline oneapi::mkl::transpose get_transpose(int t) { + if (t == 0) { + return oneapi::mkl::transpose::nontrans; + } else if (t == 1) { + return oneapi::mkl::transpose::trans; + } else { + return oneapi::mkl::transpose::conjtrans; + } +} + +/// Computes the LU factorizations of a batch of general matrices. +/// \param [in] exec_queue The queue where the routine should be executed. +/// \param [in] n The order of the matrices. +/// \param [in, out] a Array of pointers to matrices. These matrices will be +/// overwritten by lower triangulars with unit diagonal elements and upper +/// triangulars. +/// \param [in] lda The leading dimension of the matrices. +/// \param [out] ipiv An array stores the pivot indices. If \p ipiv is nullptr, +/// non-pivoting LU factorization is computed. +/// \param [out] info An array stores the error information. +/// \param [in] batch_size The size of the batch. +template +inline void getrf_batch_wrapper(sycl::queue &exec_queue, int n, T *a[], int lda, + int *ipiv, int *info, int batch_size) { + if (ipiv == nullptr) { + detail::getrfnp_batch_wrapper(exec_queue, n, a, lda, info, batch_size); + return; + } + using Ty = typename ::dpct::detail::lib_data_traits_t; + // Set the info array value to 0 + ::dpct::cs::fill(exec_queue, info, 0, + sizeof(int) * batch_size); +#ifdef DPCT_USM_LEVEL_NONE + std::int64_t stride_a = n * lda; + std::int64_t stride_ipiv = n; + std::int64_t scratchpad_size = + oneapi::mkl::lapack::getrf_batch_scratchpad_size( + exec_queue, n, n, lda, stride_a, stride_ipiv, batch_size); + + T *a_buffer_ptr; + a_buffer_ptr = (T *)::dpct::cs::malloc(stride_a * batch_size * sizeof(T)); + + T **host_a = (T **)std::malloc(batch_size * sizeof(T *)); + dpct_memcpy(host_a, a, batch_size * sizeof(T *)); + for (std::int64_t i = 0; i < batch_size; ++i) + dpct_memcpy(a_buffer_ptr + i * stride_a, host_a[i], n * lda * sizeof(T)); + + { + sycl::buffer ipiv_buf( + sycl::range<1>(batch_size * stride_ipiv)); + sycl::buffer scratchpad{sycl::range<1>(scratchpad_size)}; + auto a_buffer = get_buffer(a_buffer_ptr); + oneapi::mkl::lapack::getrf_batch(exec_queue, n, n, a_buffer, lda, stride_a, + ipiv_buf, stride_ipiv, batch_size, + scratchpad, scratchpad_size); + + auto to_buffer = get_buffer(ipiv); + exec_queue.submit([&](sycl::handler &cgh) { + auto from_acc = ipiv_buf.get_access(cgh); + auto to_acc = to_buffer.get_access(cgh); + cgh.parallel_for< + ::dpct::cs::kernel_name>( + sycl::range<2>(batch_size, n), [=](sycl::id<2> id) { + to_acc[id.get(0) * n + id.get(1)] = + static_cast(from_acc[id.get(0) * stride_ipiv + id.get(1)]); + }); + }); + } + + // Copy back to the original buffers + std::vector events; + for (std::int64_t i = 0; i < batch_size; ++i) + events.push_back(::dpct::cs::memcpy( + exec_queue, host_a[i], a_buffer_ptr + i * stride_a, n * lda * sizeof(T), + ::dpct::cs::memcpy_direction::automatic)); + + std::vector ptrs{host_a}; + std::thread mem_free_thread( + [=](std::vector pointers_array, + std::vector events_array) { + sycl::event::wait(events_array); + for (auto p : pointers_array) + std::free(p); + }, + ptrs, events); + mem_free_thread.detach(); +#else + std::int64_t *m_int64 = new std::int64_t; + std::int64_t *n_int64 = new std::int64_t; + std::int64_t *lda_int64 = new std::int64_t; + std::int64_t *group_sizes = new std::int64_t; + *m_int64 = n; + *n_int64 = n; + *lda_int64 = lda; + *group_sizes = batch_size; + std::int64_t scratchpad_size = + oneapi::mkl::lapack::getrf_batch_scratchpad_size( + exec_queue, m_int64, n_int64, lda_int64, 1, group_sizes); + + Ty *scratchpad = sycl::malloc_device(scratchpad_size, exec_queue); + std::int64_t *ipiv_int64 = + sycl::malloc_device(batch_size * n, exec_queue); + std::int64_t **ipiv_int64_ptr = + sycl::malloc_shared(batch_size, exec_queue); + T **a_shared = sycl::malloc_shared(batch_size, exec_queue); + exec_queue.memcpy(a_shared, a, batch_size * sizeof(T *)).wait(); + for (std::int64_t i = 0; i < batch_size; ++i) + ipiv_int64_ptr[i] = ipiv_int64 + n * i; + + oneapi::mkl::lapack::getrf_batch(exec_queue, m_int64, n_int64, + (Ty **)a_shared, lda_int64, ipiv_int64_ptr, + 1, group_sizes, scratchpad, scratchpad_size); + + sycl::event e = exec_queue.submit([&](sycl::handler &cgh) { + cgh.parallel_for< + ::dpct::cs::kernel_name>( + sycl::range<1>(batch_size * n), [=](sycl::id<1> idx) { + ipiv[idx] = static_cast(ipiv_int64[idx]); + }); + }); + + exec_queue.submit([&](sycl::handler &cgh) { + cgh.depends_on(e); + cgh.host_task([=] { + delete m_int64; + delete n_int64; + delete lda_int64; + delete group_sizes; + }); + }); + std::vector ptrs{scratchpad, ipiv_int64, ipiv_int64_ptr, a_shared}; + ::dpct::cs::enqueue_free(ptrs, {e}, exec_queue); +#endif +} + +/// Solves a system of linear equations with a batch of LU-factored square +/// coefficient matrices, with multiple right-hand sides. +/// \param [in] exec_queue The queue where the routine should be executed. +/// \param [in] trans Indicates the form of the linear equations. +/// \param [in] n The order of the matrices. +/// \param [in] nrhs The number of right hand sides. +/// \param [in] a Array of pointers to matrices. +/// \param [in] lda The leading dimension of the matrices in \p a. +/// \param [in] ipiv An array stores the pivots. +/// \param [in, out] b Array of pointers to matrices, whose columns are +/// the right-hand sides for the systems of equations. +/// \param [in] ldb The leading dimension of the matrices in \p b. +/// \param [out] info A value stores the error information. +/// \param [in] batch_size The size of the batch. +template +inline void getrs_batch_wrapper(sycl::queue &exec_queue, + oneapi::mkl::transpose trans, int n, int nrhs, + const T *a[], int lda, const int *ipiv, T *b[], + int ldb, int *info, int batch_size) { + using Ty = typename ::dpct::detail::lib_data_traits_t; + // Set the info value to 0 + *info = 0; +#ifdef DPCT_USM_LEVEL_NONE + std::int64_t stride_a = n * lda; + std::int64_t stride_b = nrhs * ldb; + std::int64_t stride_ipiv = n; + std::int64_t scratchpad_size = + oneapi::mkl::lapack::getrs_batch_scratchpad_size( + exec_queue, trans, n, nrhs, lda, stride_a, stride_ipiv, ldb, stride_b, + batch_size); + + T *a_buffer_ptr, *b_buffer_ptr; + a_buffer_ptr = (T *)::dpct::cs::malloc(stride_a * batch_size * sizeof(T)); + b_buffer_ptr = (T *)::dpct::cs::malloc(stride_b * batch_size * sizeof(T)); + + T **host_a = (T **)std::malloc(batch_size * sizeof(T *)); + T **host_b = (T **)std::malloc(batch_size * sizeof(T *)); + dpct_memcpy(host_a, a, batch_size * sizeof(T *)); + dpct_memcpy(host_b, b, batch_size * sizeof(T *)); + for (std::int64_t i = 0; i < batch_size; ++i) { + dpct_memcpy(a_buffer_ptr + i * stride_a, host_a[i], n * lda * sizeof(T)); + dpct_memcpy(b_buffer_ptr + i * stride_b, host_b[i], nrhs * ldb * sizeof(T)); + } + + { + auto a_buffer = get_buffer(a_buffer_ptr); + auto b_buffer = get_buffer(b_buffer_ptr); + sycl::buffer scratchpad{sycl::range<1>(scratchpad_size)}; + sycl::buffer ipiv_buf( + sycl::range<1>(batch_size * stride_ipiv)); + auto from_buf = get_buffer(ipiv); + exec_queue.submit([&](sycl::handler &cgh) { + auto from_acc = from_buf.get_access(cgh); + auto to_acc = ipiv_buf.get_access(cgh); + cgh.parallel_for< + ::dpct::cs::kernel_name>( + sycl::range<2>(batch_size, n), [=](sycl::id<2> id) { + to_acc[id.get(0) * stride_ipiv + id.get(1)] = + static_cast(from_acc[id.get(0) * n + id.get(1)]); + }); + }); + + oneapi::mkl::lapack::getrs_batch(exec_queue, trans, n, nrhs, a_buffer, lda, + stride_a, ipiv_buf, stride_ipiv, b_buffer, + ldb, stride_b, batch_size, scratchpad, + scratchpad_size); + } + + // Copy back to the original buffers + std::vector events; + for (std::int64_t i = 0; i < batch_size; ++i) + events.push_back(::dpct::cs::memcpy( + exec_queue, host_b[i], b_buffer_ptr + i * stride_b, + nrhs * ldb * sizeof(T), ::dpct::cs::memcpy_direction::automatic)); + std::vector ptrs{host_a, host_b}; + std::thread mem_free_thread( + [=](std::vector pointers_array, + std::vector events_array) { + sycl::event::wait(events_array); + for (auto p : pointers_array) + std::free(p); + }, + ptrs, events); + mem_free_thread.detach(); +#else + std::int64_t *n_int64 = new std::int64_t; + std::int64_t *nrhs_int64 = new std::int64_t; + std::int64_t *lda_int64 = new std::int64_t; + std::int64_t *ldb_int64 = new std::int64_t; + std::int64_t *group_sizes = new std::int64_t; + oneapi::mkl::transpose *trans_array = new oneapi::mkl::transpose; + *n_int64 = n; + *nrhs_int64 = nrhs; + *lda_int64 = lda; + *ldb_int64 = ldb; + *group_sizes = batch_size; + *trans_array = trans; + std::int64_t scratchpad_size = + oneapi::mkl::lapack::getrs_batch_scratchpad_size( + exec_queue, trans_array, n_int64, nrhs_int64, lda_int64, ldb_int64, 1, + group_sizes); + + Ty *scratchpad = sycl::malloc_device(scratchpad_size, exec_queue); + std::int64_t *ipiv_int64 = + sycl::malloc_device(batch_size * n, exec_queue); + std::int64_t **ipiv_int64_ptr = + sycl::malloc_shared(batch_size, exec_queue); + T **a_shared = sycl::malloc_shared(batch_size, exec_queue); + T **b_shared = sycl::malloc_shared(batch_size, exec_queue); + exec_queue.memcpy(a_shared, a, batch_size * sizeof(T *)); + exec_queue.memcpy(b_shared, b, batch_size * sizeof(T *)); + + exec_queue + .submit([&](sycl::handler &cgh) { + cgh.parallel_for< + ::dpct::cs::kernel_name>( + sycl::range<1>(batch_size * n), [=](sycl::id<1> idx) { + ipiv_int64[idx] = static_cast(ipiv[idx]); + }); + }) + .wait(); + + for (std::int64_t i = 0; i < batch_size; ++i) + ipiv_int64_ptr[i] = ipiv_int64 + n * i; + + sycl::event e = oneapi::mkl::lapack::getrs_batch( + exec_queue, trans_array, n_int64, nrhs_int64, (Ty **)a_shared, lda_int64, + ipiv_int64_ptr, (Ty **)b_shared, ldb_int64, 1, group_sizes, scratchpad, + scratchpad_size); + + exec_queue.submit([&](sycl::handler &cgh) { + cgh.depends_on(e); + cgh.host_task([=] { + delete n_int64; + delete nrhs_int64; + delete lda_int64; + delete ldb_int64; + delete group_sizes; + delete trans_array; + }); + }); + std::vector ptrs{scratchpad, ipiv_int64_ptr, ipiv_int64, a_shared, + b_shared}; + ::dpct::cs::enqueue_free(ptrs, {e}, exec_queue); +#endif +} + +/// Computes the inverses of a batch of LU-factored matrices. +/// \param [in] exec_queue The queue where the routine should be executed. +/// \param [in] n The order of the matrices. +/// \param [in] a Array of pointers to matrices. +/// \param [in] lda The leading dimension of the matrices in \p a. +/// \param [in] ipiv An array stores the pivots. +/// \param [out] b Array of pointers to inverse matrices. +/// \param [in] ldb The leading dimension of the matrices in \p b. +/// \param [out] info An array stores the error information. +/// \param [in] batch_size The size of the batch. +template +inline void getri_batch_wrapper(sycl::queue &exec_queue, int n, const T *a[], + int lda, int *ipiv, T *b[], int ldb, int *info, + int batch_size) { + using Ty = typename ::dpct::detail::lib_data_traits_t; + // Set the info array value to 0 + ::dpct::cs::fill(exec_queue, info, 0, + sizeof(int) * batch_size); +#ifdef DPCT_USM_LEVEL_NONE + std::int64_t stride_b = n * ldb; + std::int64_t stride_ipiv = n; + std::int64_t scratchpad_size = + oneapi::mkl::lapack::getri_batch_scratchpad_size( + exec_queue, n, ldb, stride_b, stride_ipiv, batch_size); + + T *b_buffer_ptr; + b_buffer_ptr = (T *)::dpct::cs::malloc(stride_b * batch_size * sizeof(T)); + + T **host_a = (T **)std::malloc(batch_size * sizeof(T *)); + T **host_b = (T **)std::malloc(batch_size * sizeof(T *)); + dpct_memcpy(host_a, a, batch_size * sizeof(T *)); + dpct_memcpy(host_b, b, batch_size * sizeof(T *)); + + for (std::int64_t i = 0; i < batch_size; ++i) { + // Need to create a copy of input matrices "a" to keep them unchanged. + // Matrices "b" (copy of matrices "a") will be used as input and output + // parameter in oneapi::mkl::lapack::getri_batch call. + blas::matrix_mem_copy(b_buffer_ptr + i * stride_b, host_a[i], ldb, lda, n, + n, sizeof(T), dpct::device_to_device, exec_queue); + } + + { + auto b_buffer = get_buffer(b_buffer_ptr); + sycl::buffer scratchpad{sycl::range<1>(scratchpad_size)}; + sycl::buffer ipiv_buf( + sycl::range<1>(batch_size * stride_ipiv)); + auto from_buf = get_buffer(ipiv); + exec_queue.submit([&](sycl::handler &cgh) { + auto from_acc = from_buf.get_access(cgh); + auto to_acc = ipiv_buf.get_access(cgh); + cgh.parallel_for< + ::dpct::cs::kernel_name>( + sycl::range<2>(batch_size, n), [=](sycl::id<2> id) { + to_acc[id.get(0) * stride_ipiv + id.get(1)] = + static_cast(from_acc[id.get(0) * n + id.get(1)]); + }); + }); + + oneapi::mkl::lapack::getri_batch(exec_queue, n, b_buffer, ldb, stride_b, + ipiv_buf, stride_ipiv, batch_size, + scratchpad, scratchpad_size); + } + + // Copy back to the original buffers + std::vector events; + for (std::int64_t i = 0; i < batch_size; ++i) + events.push_back(::dpct::cs::memcpy( + exec_queue, host_b[i], b_buffer_ptr + i * stride_b, n * ldb * sizeof(T), + ::dpct::cs::memcpy_direction::automatic)); + std::vector ptrs{host_a, host_b}; + std::thread mem_free_thread( + [=](std::vector pointers_array, + std::vector events_array) { + sycl::event::wait(events_array); + for (auto p : pointers_array) + std::free(p); + }, + ptrs, events); + mem_free_thread.detach(); +#else + std::int64_t *n_int64 = new std::int64_t; + std::int64_t *ldb_int64 = new std::int64_t; + std::int64_t *group_sizes = new std::int64_t; + *n_int64 = n; + *ldb_int64 = ldb; + *group_sizes = batch_size; + std::int64_t scratchpad_size = + oneapi::mkl::lapack::getri_batch_scratchpad_size( + exec_queue, n_int64, ldb_int64, 1, group_sizes); + + Ty *scratchpad = sycl::malloc_device(scratchpad_size, exec_queue); + std::int64_t *ipiv_int64 = + sycl::malloc_device(batch_size * n, exec_queue); + std::int64_t **ipiv_int64_ptr = + sycl::malloc_shared(batch_size, exec_queue); + + exec_queue.submit([&](sycl::handler &cgh) { + cgh.parallel_for< + ::dpct::cs::kernel_name>( + sycl::range<1>(batch_size * n), [=](sycl::id<1> idx) { + ipiv_int64[idx] = static_cast(ipiv[idx]); + }); + }); + + T **a_shared = sycl::malloc_shared(batch_size, exec_queue); + T **b_shared = sycl::malloc_shared(batch_size, exec_queue); + exec_queue.memcpy(a_shared, a, batch_size * sizeof(T *)); + exec_queue.memcpy(b_shared, b, batch_size * sizeof(T *)).wait(); + for (std::int64_t i = 0; i < batch_size; ++i) { + ipiv_int64_ptr[i] = ipiv_int64 + n * i; + // Need to create a copy of input matrices "a" to keep them unchanged. + // Matrices "b" (copy of matrices "a") will be used as input and output + // parameter in oneapi::mkl::lapack::getri_batch call. + blas::matrix_mem_copy(b_shared[i], a_shared[i], ldb, lda, n, n, sizeof(T), + ::dpct::cs::memcpy_direction::device_to_device, + exec_queue); + } + + sycl::event e = oneapi::mkl::lapack::getri_batch( + exec_queue, n_int64, (Ty **)b_shared, ldb_int64, ipiv_int64_ptr, 1, + group_sizes, scratchpad, scratchpad_size); + + exec_queue.submit([&](sycl::handler &cgh) { + cgh.depends_on(e); + cgh.host_task([=] { + delete n_int64; + delete ldb_int64; + delete group_sizes; + }); + }); + std::vector ptrs{scratchpad, ipiv_int64_ptr, ipiv_int64, a_shared, + b_shared}; + ::dpct::cs::enqueue_free(ptrs, {e}, exec_queue); +#endif +} + +/// Computes the QR factorizations of a batch of general matrices. +/// \param [in] exec_queue The queue where the routine should be executed. +/// \param [in] m The number of rows in the matrices. +/// \param [in] n The number of columns in the matrices. +/// \param [in, out] a Array of pointers to matrices. These +/// matrices will be overwritten by the factorization data. +/// \param [in] lda The leading dimension of the matrices in \p a. +/// \param [out] tau An array stores the scalars. +/// \param [out] info A value stores the error information. +/// \param [in] batch_size The size of the batch. +template +inline void geqrf_batch_wrapper(sycl::queue exec_queue, int m, int n, T *a[], + int lda, T *tau[], int *info, int batch_size) { + using Ty = typename ::dpct::detail::lib_data_traits_t; + // Set the info value to 0 + *info = 0; +#ifdef DPCT_USM_LEVEL_NONE + std::int64_t stride_a = n * lda; + std::int64_t stride_tau = (std::max)(1, (std::min)(m, n)); + std::int64_t scratchpad_size = + oneapi::mkl::lapack::geqrf_batch_scratchpad_size( + exec_queue, m, n, lda, stride_a, stride_tau, batch_size); + + T *a_buffer_ptr, *tau_buffer_ptr; + a_buffer_ptr = (T *)::dpct::cs::malloc(stride_a * batch_size * sizeof(T)); + tau_buffer_ptr = (T *)::dpct::cs::malloc(stride_tau * batch_size * sizeof(T)); + + T **host_a = (T **)std::malloc(batch_size * sizeof(T *)); + T **host_tau = (T **)std::malloc(batch_size * sizeof(T *)); + dpct_memcpy(host_a, a, batch_size * sizeof(T *)); + dpct_memcpy(host_tau, tau, batch_size * sizeof(T *)); + + for (std::int64_t i = 0; i < batch_size; ++i) + dpct_memcpy(a_buffer_ptr + i * stride_a, host_a[i], n * lda * sizeof(T)); + { + auto a_buffer = get_buffer(a_buffer_ptr); + auto tau_buffer = get_buffer(tau_buffer_ptr); + sycl::buffer scratchpad{sycl::range<1>(scratchpad_size)}; + oneapi::mkl::lapack::geqrf_batch(exec_queue, m, n, a_buffer, lda, stride_a, + tau_buffer, stride_tau, batch_size, + scratchpad, scratchpad_size); + } + + // Copy back to the original buffers + std::vector events_a; + std::vector events_tau; + for (std::int64_t i = 0; i < batch_size; ++i) { + events_a.push_back(::dpct::cs::memcpy( + exec_queue, host_a[i], a_buffer_ptr + i * stride_a, n * lda * sizeof(T), + ::dpct::cs::memcpy_direction::automatic)); + events_tau.push_back(::dpct::cs::memcpy( + exec_queue, host_tau[i], tau_buffer_ptr + i * stride_tau, + (std::max)(1, (std::min)(m, n)) * sizeof(T), + ::dpct::cs::memcpy_direction::automatic)); + } + std::vector ptr_a{host_a}; + std::vector ptr_tau{host_tau}; + std::thread mem_free_thread_a( + [=](std::vector pointers_array, + std::vector events_array) { + sycl::event::wait(events_array); + for (auto p : pointers_array) + std::free(p); + }, + ptr_a, events_a); + std::thread mem_free_thread_tau( + [=](std::vector pointers_array, + std::vector events_array) { + sycl::event::wait(events_array); + for (auto p : pointers_array) + std::free(p); + }, + ptr_tau, events_tau); + mem_free_thread_a.detach(); + mem_free_thread_tau.detach(); +#else + std::int64_t *m_int64 = new std::int64_t; + std::int64_t *n_int64 = new std::int64_t; + std::int64_t *lda_int64 = new std::int64_t; + std::int64_t *group_sizes = new std::int64_t; + *m_int64 = n; + *n_int64 = n; + *lda_int64 = lda; + *group_sizes = batch_size; + std::int64_t scratchpad_size = + oneapi::mkl::lapack::geqrf_batch_scratchpad_size( + exec_queue, m_int64, n_int64, lda_int64, 1, group_sizes); + + Ty *scratchpad = sycl::malloc_device(scratchpad_size, exec_queue); + T **a_shared = sycl::malloc_shared(batch_size, exec_queue); + T **tau_shared = sycl::malloc_shared(batch_size, exec_queue); + exec_queue.memcpy(a_shared, a, batch_size * sizeof(T *)); + exec_queue.memcpy(tau_shared, tau, batch_size * sizeof(T *)).wait(); + + sycl::event e = oneapi::mkl::lapack::geqrf_batch( + exec_queue, m_int64, n_int64, (Ty **)a_shared, lda_int64, + (Ty **)tau_shared, 1, group_sizes, scratchpad, scratchpad_size); + + exec_queue.submit([&](sycl::handler &cgh) { + cgh.depends_on(e); + cgh.host_task([=] { + delete m_int64; + delete n_int64; + delete lda_int64; + delete group_sizes; + }); + }); + std::vector ptrs{scratchpad, a_shared, tau_shared}; + ::dpct::cs::enqueue_free(ptrs, {e}, exec_queue); +#endif +} + +namespace blas { +#ifdef __INTEL_MKL__ +template +inline oneapi::mkl::blas::compute_mode +deduce_compute_mode(std::optional ct, math_mode mm) { + using Ty = typename ::dpct::detail::lib_data_traits_t; + if (ct) { + switch (ct.value()) { + case compute_type::f16_standard: + case compute_type::f32_standard: + case compute_type::f64_standard: + case compute_type::i32_standard: + return oneapi::mkl::blas::compute_mode::standard; + case compute_type::f32: + if constexpr (std::is_same_v> || + std::is_same_v>) + return oneapi::mkl::blas::compute_mode::complex_3m; + break; + case compute_type::f32_fast_bf16: + return oneapi::mkl::blas::compute_mode::float_to_bf16; + case compute_type::f32_fast_tf32: + return oneapi::mkl::blas::compute_mode::float_to_tf32; + default: + [[fallthrough]]; + } + } + if (mm == math_mode::mm_tf32) + return oneapi::mkl::blas::compute_mode::float_to_tf32; + return oneapi::mkl::blas::compute_mode::unset; +} + +inline oneapi::mkl::blas::compute_mode +deduce_compute_mode(std::optional ct, math_mode mm, + bool is_complex) { + if (is_complex) + return deduce_compute_mode>(ct, mm); + return deduce_compute_mode(ct, mm); +} +#endif + +/// Computes matrix-matrix product with general matrices. +/// \param [in] desc_ptr Descriptor. +/// \param [in] a_trans Specifies the operation applied to A. +/// \param [in] b_trans Specifies the operation applied to B. +/// \param [in] m Specifies the number of rows of the matrix op(A) and of the matrix C. +/// \param [in] n Specifies the number of columns of the matrix op(B) and of the matrix C. +/// \param [in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). +/// \param [in] alpha Scaling factor for the matrix-matrix product. +/// \param [in] a Input matrix A. +/// \param [in] a_type Data type of the matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] b Input matrix B. +/// \param [in] b_type Data type of the matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] beta Scaling factor for matrix C. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] c_type Data type of the matrix C. +/// \param [in] ldc Leading dimension of C. +/// \param [in] ct Compute type. +inline void gemm(descriptor_ptr desc_ptr, oneapi::mkl::transpose a_trans, + oneapi::mkl::transpose b_trans, std::int64_t m, std::int64_t n, + std::int64_t k, const void *alpha, const void *a, + library_data_t a_type, std::int64_t lda, const void *b, + library_data_t b_type, std::int64_t ldb, const void *beta, + void *c, library_data_t c_type, std::int64_t ldc, + std::variant ct) { +#ifndef __INTEL_MKL__ + throw std::runtime_error("The oneAPI Math Kernel Library (oneMKL) Interfaces " + "Project does not support this API."); +#else + sycl::queue q = desc_ptr->get_queue(); + oneapi::mkl::blas::compute_mode cm = oneapi::mkl::blas::compute_mode::unset; + library_data_t scaling_type; + if (auto ct_p = std::get_if(&ct)) { + cm = deduce_compute_mode(*ct_p, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); + scaling_type = detail::compute_type_to_library_data_t(*ct_p); + } else { + cm = deduce_compute_mode(std::nullopt, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); + scaling_type = std::get(ct); + } + + if (scaling_type == library_data_t::real_float && + c_type == library_data_t::complex_float) { + scaling_type = library_data_t::complex_float; + } else if (scaling_type == library_data_t::real_double && + c_type == library_data_t::complex_double) { + scaling_type = library_data_t::complex_double; + } + + std::uint64_t key = dpct::detail::get_type_combination_id( + a_type, b_type, c_type, scaling_type); + switch (key) { + case dpct::detail::get_type_combination_id( + library_data_t::real_float, library_data_t::real_float, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_double, library_data_t::real_double, + library_data_t::real_double, library_data_t::real_double): { + dpct::detail::gemm_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::complex_float, library_data_t::complex_float, + library_data_t::complex_float, library_data_t::complex_float): { + dpct::detail::gemm_impl, std::complex, + std::complex, std::complex>( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::complex_double, library_data_t::complex_double, + library_data_t::complex_double, library_data_t::complex_double): { + dpct::detail::gemm_impl, std::complex, + std::complex, std::complex>( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_half, library_data_t::real_half, + library_data_t::real_half, library_data_t::real_half): { + dpct::detail::gemm_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_bfloat16, library_data_t::real_bfloat16, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_impl(q, a_trans, b_trans, m, n, k, alpha, a, lda, + b, ldb, beta, c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_half, library_data_t::real_half, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_half, library_data_t::real_half, + library_data_t::real_half, library_data_t::real_float): { + float alpha_value = + dpct::get_value(reinterpret_cast(alpha), q); + float beta_value = + dpct::get_value(reinterpret_cast(beta), q); + sycl::half alpha_half(alpha_value); + sycl::half beta_half(beta_value); + dpct::detail::gemm_impl( + q, a_trans, b_trans, m, n, k, &alpha_half, a, lda, b, ldb, &beta_half, + c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_int8, library_data_t::real_int8, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_bfloat16, library_data_t::real_bfloat16, + library_data_t::real_bfloat16, library_data_t::real_float): { + dpct::detail::gemm_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_int8, library_data_t::real_int8, + library_data_t::real_int32, library_data_t::real_int32): { + float alpha_float = + dpct::get_value(reinterpret_cast(alpha), q); + float beta_float = + dpct::get_value(reinterpret_cast(beta), q); + dpct::detail::gemm_impl( + q, a_trans, b_trans, m, n, k, &alpha_float, a, lda, b, ldb, &beta_float, + c, ldc, cm); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +#endif +} + +/// Computes a batch of matrix-matrix product with general matrices. +/// \param [in] desc_ptr Descriptor. +/// \param [in] a_trans Specifies the operation applied to A. +/// \param [in] b_trans Specifies the operation applied to B. +/// \param [in] m Specifies the number of rows of the matrix op(A) and of the matrix C. +/// \param [in] n Specifies the number of columns of the matrix op(B) and of the matrix C. +/// \param [in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). +/// \param [in] alpha Scaling factor for the matrix-matrix product. +/// \param [in] a Input matrix A. +/// \param [in] a_type Data type of the matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] b Input matrix B. +/// \param [in] b_type Data type of the matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] beta Scaling factor for matrix C. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] c_type Data type of the matrix C. +/// \param [in] ldc Leading dimension of C. +/// \param [in] batch_size Specifies the number of matrix multiply operations to perform. +/// \param [in] scaling_type Data type of the scaling factors. +/// \param [in] ct Compute type. +inline void gemm_batch(descriptor_ptr desc_ptr, oneapi::mkl::transpose a_trans, + oneapi::mkl::transpose b_trans, std::int64_t m, + std::int64_t n, std::int64_t k, const void *alpha, + const void *a[], library_data_t a_type, std::int64_t lda, + const void *b[], library_data_t b_type, std::int64_t ldb, + const void *beta, void *c[], library_data_t c_type, + std::int64_t ldc, std::int64_t batch_size, + std::variant ct) { +#ifdef DPCT_USM_LEVEL_NONE + throw std::runtime_error("this API is unsupported when USM level is none"); +#else + sycl::queue q = desc_ptr->get_queue(); +#ifdef __INTEL_MKL__ + oneapi::mkl::blas::compute_mode cm = oneapi::mkl::blas::compute_mode::unset; +#endif + library_data_t scaling_type; + if (auto ct_p = std::get_if(&ct)) { +#ifdef __INTEL_MKL__ + cm = deduce_compute_mode(*ct_p, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); +#endif + scaling_type = detail::compute_type_to_library_data_t(*ct_p); + } else { +#ifdef __INTEL_MKL__ + cm = deduce_compute_mode(std::nullopt, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); +#endif + scaling_type = std::get(ct); + } + + if (scaling_type == library_data_t::real_float && + c_type == library_data_t::complex_float) { + scaling_type = library_data_t::complex_float; + } else if (scaling_type == library_data_t::real_double && + c_type == library_data_t::complex_double) { + scaling_type = library_data_t::complex_double; + } + + std::uint64_t key = dpct::detail::get_type_combination_id( + a_type, b_type, c_type, scaling_type); + switch (key) { + case dpct::detail::get_type_combination_id( + library_data_t::real_float, library_data_t::real_float, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, + batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_double, library_data_t::real_double, + library_data_t::real_double, library_data_t::real_double): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, + batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::complex_float, library_data_t::complex_float, + library_data_t::complex_float, library_data_t::complex_float): { + dpct::detail::gemm_batch_impl, std::complex, + std::complex, std::complex>( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, + batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::complex_double, library_data_t::complex_double, + library_data_t::complex_double, library_data_t::complex_double): { + dpct::detail::gemm_batch_impl, std::complex, + std::complex, std::complex>( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, + batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_half, library_data_t::real_half, + library_data_t::real_half, library_data_t::real_half): { + dpct::detail::gemm_batch_impl(q, a_trans, b_trans, m, n, k, + alpha, a, lda, b, ldb, beta, c, + ldc, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } +#ifdef __INTEL_MKL__ + case dpct::detail::get_type_combination_id( + library_data_t::real_bfloat16, library_data_t::real_bfloat16, + library_data_t::real_bfloat16, library_data_t::real_float): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, + batch_size, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_bfloat16, library_data_t::real_bfloat16, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_batch_impl(q, a_trans, b_trans, m, n, k, + alpha, a, lda, b, ldb, beta, c, + ldc, batch_size, cm); + break; + } +#endif + case dpct::detail::get_type_combination_id( + library_data_t::real_int8, library_data_t::real_int8, + library_data_t::real_int32, library_data_t::real_int32): { + float alpha_float = + dpct::get_value(reinterpret_cast(alpha), q); + float beta_float = + dpct::get_value(reinterpret_cast(beta), q); + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, &alpha_float, a, lda, b, ldb, &beta_float, + c, ldc, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_int8, library_data_t::real_int8, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, + batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_half, library_data_t::real_half, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, + batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_half, library_data_t::real_half, + library_data_t::real_half, library_data_t::real_float): { + float alpha_value = + dpct::get_value(reinterpret_cast(alpha), q); + float beta_value = + dpct::get_value(reinterpret_cast(beta), q); + sycl::half alpha_half(alpha_value); + sycl::half beta_half(beta_value); + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, &alpha_half, a, lda, b, ldb, &beta_half, + c, ldc, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +#endif +} + +/// Computes a batch of matrix-matrix product with general matrices. +/// \param [in] desc_ptr Descriptor. +/// \param [in] a_trans Specifies the operation applied to A. +/// \param [in] b_trans Specifies the operation applied to B. +/// \param [in] m Specifies the number of rows of the matrix op(A) and of the matrix C. +/// \param [in] n Specifies the number of columns of the matrix op(B) and of the matrix C. +/// \param [in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). +/// \param [in] alpha Scaling factor for the matrix-matrix product. +/// \param [in] a Input matrix A. +/// \param [in] a_type Data type of the matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] stride_a Stride between the different A matrices. +/// \param [in] b Input matrix B. +/// \param [in] b_type Data type of the matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] stride_b Stride between the different B matrices. +/// \param [in] beta Scaling factor for matrix C. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] c_type Data type of the matrix C. +/// \param [in] ldc Leading dimension of C. +/// \param [in] stride_c Stride between the different C matrices. +/// \param [in] batch_size Specifies the number of matrix multiply operations to perform. +/// \param [in] ct Compute type. +inline void gemm_batch(descriptor_ptr desc_ptr, oneapi::mkl::transpose a_trans, + oneapi::mkl::transpose b_trans, std::int64_t m, + std::int64_t n, std::int64_t k, const void *alpha, + const void *a, library_data_t a_type, std::int64_t lda, + long long int stride_a, const void *b, + library_data_t b_type, std::int64_t ldb, + long long int stride_b, const void *beta, void *c, + library_data_t c_type, std::int64_t ldc, + long long int stride_c, std::int64_t batch_size, + std::variant ct) { + sycl::queue q = desc_ptr->get_queue(); +#ifdef __INTEL_MKL__ + oneapi::mkl::blas::compute_mode cm = oneapi::mkl::blas::compute_mode::unset; +#endif + library_data_t scaling_type; + if (auto ct_p = std::get_if(&ct)) { +#ifdef __INTEL_MKL__ + cm = deduce_compute_mode(*ct_p, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); +#endif + scaling_type = detail::compute_type_to_library_data_t(*ct_p); + } else { +#ifdef __INTEL_MKL__ + cm = deduce_compute_mode(std::nullopt, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); +#endif + scaling_type = std::get(ct); + } + + if (scaling_type == library_data_t::real_float && + c_type == library_data_t::complex_float) { + scaling_type = library_data_t::complex_float; + } else if (scaling_type == library_data_t::real_double && + c_type == library_data_t::complex_double) { + scaling_type = library_data_t::complex_double; + } + + std::uint64_t key = dpct::detail::get_type_combination_id( + a_type, b_type, c_type, scaling_type); + switch (key) { + case dpct::detail::get_type_combination_id( + library_data_t::real_float, library_data_t::real_float, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, + beta, c, ldc, stride_c, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_double, library_data_t::real_double, + library_data_t::real_double, library_data_t::real_double): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, + beta, c, ldc, stride_c, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::complex_float, library_data_t::complex_float, + library_data_t::complex_float, library_data_t::complex_float): { + dpct::detail::gemm_batch_impl, std::complex, + std::complex, std::complex>( + q, a_trans, b_trans, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, + beta, c, ldc, stride_c, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::complex_double, library_data_t::complex_double, + library_data_t::complex_double, library_data_t::complex_double): { + dpct::detail::gemm_batch_impl, std::complex, + std::complex, std::complex>( + q, a_trans, b_trans, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, + beta, c, ldc, stride_c, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_half, library_data_t::real_half, + library_data_t::real_half, library_data_t::real_half): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, + beta, c, ldc, stride_c, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } +#ifdef __INTEL_MKL__ + case dpct::detail::get_type_combination_id( + library_data_t::real_bfloat16, library_data_t::real_bfloat16, + library_data_t::real_bfloat16, library_data_t::real_float): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, + beta, c, ldc, stride_c, batch_size, cm); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_bfloat16, library_data_t::real_bfloat16, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, + beta, c, ldc, stride_c, batch_size, cm); + break; + } +#endif + case dpct::detail::get_type_combination_id( + library_data_t::real_int8, library_data_t::real_int8, + library_data_t::real_int32, library_data_t::real_int32): { + float alpha_float = + dpct::get_value(reinterpret_cast(alpha), q); + float beta_float = + dpct::get_value(reinterpret_cast(beta), q); + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, &alpha_float, a, lda, stride_a, b, ldb, + stride_b, &beta_float, c, ldc, stride_c, + batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_int8, library_data_t::real_int8, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, + beta, c, ldc, stride_c, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_half, library_data_t::real_half, + library_data_t::real_float, library_data_t::real_float): { + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, + beta, c, ldc, stride_c, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id( + library_data_t::real_half, library_data_t::real_half, + library_data_t::real_half, library_data_t::real_float): { + float alpha_value = + dpct::get_value(reinterpret_cast(alpha), q); + float beta_value = + dpct::get_value(reinterpret_cast(beta), q); + sycl::half alpha_half(alpha_value); + sycl::half beta_half(beta_value); + dpct::detail::gemm_batch_impl( + q, a_trans, b_trans, m, n, k, &alpha_half, a, lda, stride_a, b, ldb, + stride_b, &beta_half, c, ldc, stride_c, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Performs a symmetric/hermitian rank-k update. +/// \tparam is_hermitian True means current matrix is hermitian. +/// \param [in] desc_ptr Descriptor. +/// \param [in] uplo Specifies whether matrix c is upper or lower triangular. +/// \param [in] trans Specifies op(a), the transposition operation applied to +/// matrix a. +/// \param [in] n Number of rows and columns of matrix c. +/// \param [in] k Number of columns of matrix op(a). +/// \param [in] alpha Scaling factor for the rank-k update. +/// \param [in] a Input matrix a. +/// \param [in] a_type Data type of the matrix a. +/// \param [in] lda Leading dimension of the matrix a. +/// \param [in] beta Scaling factor for the rank-k update. +/// \param [in, out] c Input/Output matrix c. +/// \param [in] c_type Data type of the matrix c. +/// \param [in] ldc Leading dimension of the matrix c. +/// \param [in] ct Compute type. +template +inline void syherk(descriptor_ptr desc_ptr, oneapi::mkl::uplo uplo, + oneapi::mkl::transpose trans, std::int64_t n, std::int64_t k, + const void *alpha, const void *a, library_data_t a_type, + std::int64_t lda, const void *beta, void *c, + library_data_t c_type, std::int64_t ldc, + std::variant ct) { + sycl::queue q = desc_ptr->get_queue(); +#ifdef __INTEL_MKL__ + oneapi::mkl::blas::compute_mode cm = oneapi::mkl::blas::compute_mode::unset; + if (auto ct_p = std::get_if(&ct)) { + cm = deduce_compute_mode(*ct_p, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); + } else { + cm = deduce_compute_mode(std::nullopt, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); + } +#endif + std::uint64_t key = dpct::detail::get_type_combination_id(a_type, c_type); + if (!is_hermitian && + dpct::detail::get_type_combination_id( + library_data_t::real_float, library_data_t::real_float) == key) { + dpct::detail::syherk_impl(q, uplo, trans, n, k, alpha, a, lda, + beta, c, ldc DPCT_COMPUTE_MODE_ARG); + } else if (!is_hermitian && dpct::detail::get_type_combination_id( + library_data_t::real_double, + library_data_t::real_double) == key) { + dpct::detail::syherk_impl(q, uplo, trans, n, k, alpha, a, + lda, beta, c, + ldc DPCT_COMPUTE_MODE_ARG); + } else if (dpct::detail::get_type_combination_id( + library_data_t::complex_float, + library_data_t::complex_float) == key) { + dpct::detail::syherk_impl>( + q, uplo, trans, n, k, alpha, a, lda, beta, c, + ldc DPCT_COMPUTE_MODE_ARG); + } else if (dpct::detail::get_type_combination_id( + library_data_t::complex_double, + library_data_t::complex_double) == key) { + dpct::detail::syherk_impl>( + q, uplo, trans, n, k, alpha, a, lda, beta, c, + ldc DPCT_COMPUTE_MODE_ARG); + } else { + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// This routines perform a special rank-k update of a symmetric matrix C by +/// general matrices A and B. +/// \param [in] desc_ptr Descriptor. +/// \param [in] uplo Specifies whether C's data is stored in its upper or lower triangle. +/// \param [in] trans Specifies the operation to apply. +/// \param [in] n The number of rows and columns in C. +/// \param [in] k The inner dimension of matrix multiplications. +/// \param [in] alpha Scaling factor for the rank-k update. +/// \param [in] a Input matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] b Input matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] beta Scaling factor for the rank-k update. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] ldc Leading dimension of C. +template +inline void syrk(descriptor_ptr desc_ptr, oneapi::mkl::uplo uplo, + oneapi::mkl::transpose trans, std::int64_t n, std::int64_t k, + const T *alpha, const T *a, std::int64_t lda, const T *b, + std::int64_t ldb, const T *beta, T *c, std::int64_t ldc) { + sycl::queue q = desc_ptr->get_queue(); +#ifdef __INTEL_MKL__ + auto cm = deduce_compute_mode(std::nullopt, desc_ptr->get_math_mode()); +#endif + dpct::detail::rk_impl(q, uplo, trans, n, k, alpha, a, lda, b, + ldb, beta, c, ldc DPCT_COMPUTE_MODE_ARG); +} + +/// This routines perform a special rank-k update of a Hermitian matrix C by +/// general matrices A and B. +/// \param [in] desc_ptr Descriptor. +/// \param [in] uplo Specifies whether C's data is stored in its upper or lower triangle. +/// \param [in] trans Specifies the operation to apply. +/// \param [in] n The number of rows and columns in C. +/// \param [in] k The inner dimension of matrix multiplications. +/// \param [in] alpha Scaling factor for the rank-k update. +/// \param [in] a Input matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] b Input matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] beta Scaling factor for the rank-k update. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] ldc Leading dimension of C. +template +inline void herk(descriptor_ptr desc_ptr, oneapi::mkl::uplo uplo, + oneapi::mkl::transpose trans, std::int64_t n, std::int64_t k, + const T *alpha, const T *a, std::int64_t lda, const T *b, + std::int64_t ldb, const Tbeta *beta, T *c, std::int64_t ldc) { + sycl::queue q = desc_ptr->get_queue(); +#ifdef __INTEL_MKL__ + auto cm = deduce_compute_mode(std::nullopt, desc_ptr->get_math_mode()); +#endif + dpct::detail::rk_impl(q, uplo, trans, n, k, alpha, a, lda, b, + ldb, beta, c, + ldc DPCT_COMPUTE_MODE_ARG); +} + +/// This routine performs a group of trsm operations. Each trsm solves an +/// equation of the form op(A) * X = alpha * B or X * op(A) = alpha * B. +/// \param [in] desc_ptr Descriptor. +/// \param [in] left_right Specifies A multiplies X on the left or on the right. +/// \param [in] upper_lower Specifies A is upper or lower triangular. +/// \param [in] trans Specifies the operation applied to A. +/// \param [in] unit_diag Specifies whether A is unit triangular. +/// \param [in] m Number of rows of the B matrices. +/// \param [in] n Number of columns of the B matrices. +/// \param [in] alpha Scaling factor for the solutions. +/// \param [in] a Input matrices A. +/// \param [in] a_type Data type of the matrices A. +/// \param [in] lda Leading dimension of the matrices A. +/// \param [in, out] b Input and output matrices B. +/// \param [in] b_type Data type of the matrices B. +/// \param [in] ldb Leading dimension of the matrices B. +/// \param [in] batch_size Specifies the number of trsm operations to perform. +/// \param [in] ct Compute type. +inline void trsm_batch(descriptor_ptr desc_ptr, oneapi::mkl::side left_right, + oneapi::mkl::uplo upper_lower, + oneapi::mkl::transpose trans, + oneapi::mkl::diag unit_diag, std::int64_t m, + std::int64_t n, const void *alpha, const void **a, + library_data_t a_type, std::int64_t lda, void **b, + library_data_t b_type, std::int64_t ldb, + std::int64_t batch_size, + std::variant ct) { +#ifdef DPCT_USM_LEVEL_NONE + throw std::runtime_error("this API is unsupported when USM level is none"); +#else + sycl::queue q = desc_ptr->get_queue(); +#ifdef __INTEL_MKL__ + oneapi::mkl::blas::compute_mode cm = oneapi::mkl::blas::compute_mode::unset; + if (auto ct_p = std::get_if(&ct)) + cm = deduce_compute_mode(*ct_p, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); + else + cm = deduce_compute_mode(std::nullopt, desc_ptr->get_math_mode(), + a_type == library_data_t::complex_float || + a_type == library_data_t::complex_double); +#endif + std::uint64_t key = dpct::detail::get_type_combination_id(a_type, b_type); + switch (key) { + case dpct::detail::get_type_combination_id(library_data_t::real_float, + library_data_t::real_float): { + dpct::detail::trsm_batch_impl( + q, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, + ldb, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id(library_data_t::real_double, + library_data_t::real_double): { + dpct::detail::trsm_batch_impl( + q, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, + ldb, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id(library_data_t::complex_float, + library_data_t::complex_float): { + dpct::detail::trsm_batch_impl, std::complex, + std::complex>( + q, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, + ldb, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + case dpct::detail::get_type_combination_id(library_data_t::complex_double, + library_data_t::complex_double): { + dpct::detail::trsm_batch_impl, std::complex, + std::complex>( + q, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, + ldb, batch_size DPCT_COMPUTE_MODE_ARG); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +#endif +} + +/// Computes a triangular matrix-general matrix product. +/// \param [in] desc_ptr Descriptor. +/// \param [in] left_right Specifies A is on the left or right side of the +/// multiplication. +/// \param [in] upper_lower Specifies A is upper or lower triangular. +/// \param [in] trans Specifies the operation applied to A. +/// \param [in] unit_diag Specifies whether A is unit triangular. +/// \param [in] m Number of rows of B. +/// \param [in] n Number of columns of B. +/// \param [in] alpha Scaling factor for the matrix-matrix product. +/// \param [in] a Input matrices A. +/// \param [in] lda Leading dimension of the matrices A. +/// \param [in] b Input matrices B. +/// \param [in] ldb Leading dimension of the matrices B. +/// \param [out] c Output matrices C. +/// \param [in] ldc Leading dimension of the matrices C. +template +inline void trmm(descriptor_ptr desc_ptr, oneapi::mkl::side left_right, + oneapi::mkl::uplo upper_lower, oneapi::mkl::transpose trans, + oneapi::mkl::diag unit_diag, std::int64_t m, std::int64_t n, + const T *alpha, const T *a, std::int64_t lda, const T *b, + std::int64_t ldb, T *c, std::int64_t ldc) { + using Ty = typename ::dpct::detail::lib_data_traits_t; + sycl::queue q = desc_ptr->get_queue(); +#ifdef __INTEL_MKL__ + auto cm = deduce_compute_mode(std::nullopt, desc_ptr->get_math_mode()); +#endif + auto alpha_val = dpct::get_value(alpha, q); + if (b != c) { + dpct::blas::matrix_mem_copy(c, b, ldc, ldb, m, n, sizeof(Ty), + ::dpct::cs::memcpy_direction::device_to_device, + q); + } + auto data_a = dpct::detail::get_memory(a); + auto data_c = dpct::detail::get_memory(c); + oneapi::mkl::blas::column_major::trmm(q, left_right, upper_lower, trans, + unit_diag, m, n, alpha_val, data_a, lda, + data_c, ldc DPCT_COMPUTE_MODE_ARG); +} + +/// Computes the Euclidean norm of a vector. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [out] result The result scalar. +/// \param [in] result_type Data type of the result. +inline void nrm2(descriptor_ptr desc_ptr, std::int64_t n, const void *x, + library_data_t x_type, std::int64_t incx, void *result, + library_data_t result_type) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = + ::dpct::detail::get_type_combination_id(x_type, result_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float, + library_data_t::real_float): { + ::dpct::detail::nrm2_impl(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double, + library_data_t::real_double): { + ::dpct::detail::nrm2_impl(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float, + library_data_t::real_float): { + ::dpct::detail::nrm2_impl, float>(q, n, x, incx, + result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_double, + library_data_t::real_double): { + ::dpct::detail::nrm2_impl, double>(q, n, x, incx, + result); + break; + } +#ifdef __INTEL_MKL__ + case ::dpct::detail::get_type_combination_id(library_data_t::real_half, + library_data_t::real_half): { + ::dpct::detail::nrm2_impl(q, n, x, incx, result); + break; + } +#endif + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Computes the dot product of two vectors. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in] y Input vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +/// \param [out] result The result scalar. +/// \param [in] result_type Data type of the result. +inline void dot(descriptor_ptr desc_ptr, std::int64_t n, const void *x, + library_data_t x_type, std::int64_t incx, const void *y, + library_data_t y_type, std::int64_t incy, void *result, + library_data_t result_type) { + sycl::queue q = desc_ptr->get_queue(); + ::dpct::detail::dotuc(q, n, x, x_type, incx, y, y_type, incy, result, + result_type); +} + +/// Computes the dot product of two vectors, conjugating the first vector. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in] y Input vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +/// \param [out] result The result scalar. +/// \param [in] result_type Data type of the result. +inline void dotc(descriptor_ptr desc_ptr, std::int64_t n, const void *x, + library_data_t x_type, std::int64_t incx, const void *y, + library_data_t y_type, std::int64_t incy, void *result, + library_data_t result_type) { + sycl::queue q = desc_ptr->get_queue(); + ::dpct::detail::dotuc(q, n, x, x_type, incx, y, y_type, incy, result, + result_type); +} + +/// Computes the product of a vector by a scalar. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] alpha The scale factor alpha. +/// \param [in] alpha_type The data type of alpha. +/// \param [in, out] x Input/Output vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +inline void scal(descriptor_ptr desc_ptr, std::int64_t n, const void *alpha, + library_data_t alpha_type, void *x, library_data_t x_type, + std::int64_t incx) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = ::dpct::detail::get_type_combination_id(x_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float): { + ::dpct::detail::scal_impl(q, n, alpha, x, incx); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double): { + ::dpct::detail::scal_impl(q, n, alpha, x, incx); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float): { + ::dpct::detail::scal_impl, std::complex>( + q, n, alpha, x, incx); + break; + } + case ::dpct::detail::get_type_combination_id( + library_data_t::complex_double): { + ::dpct::detail::scal_impl, std::complex>( + q, n, alpha, x, incx); + break; + } +#ifdef __INTEL_MKL__ + case ::dpct::detail::get_type_combination_id(library_data_t::real_half): { + float alpha_value = + dpct::get_value(reinterpret_cast(alpha), q); + sycl::half alaph_half(alpha_value); + ::dpct::detail::scal_impl(q, n, &alaph_half, x, + incx); + break; + } +#endif + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Computes a vector-scalar product and adds the result to a vector. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] alpha The scale factor alpha. +/// \param [in] alpha_type The data type of alpha. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in, out] y Input/Output vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +inline void axpy(descriptor_ptr desc_ptr, std::int64_t n, const void *alpha, + library_data_t alpha_type, const void *x, + library_data_t x_type, std::int64_t incx, void *y, + library_data_t y_type, std::int64_t incy) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = + ::dpct::detail::get_type_combination_id(x_type, alpha_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float, + library_data_t::real_float): { + ::dpct::detail::axpy_impl(q, n, alpha, x, incx, y, incy); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double, + library_data_t::real_double): { + ::dpct::detail::axpy_impl(q, n, alpha, x, incx, y, incy); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float, + library_data_t::complex_float): { + ::dpct::detail::axpy_impl, std::complex>( + q, n, alpha, x, incx, y, incy); + break; + } + case ::dpct::detail::get_type_combination_id( + library_data_t::complex_double, library_data_t::complex_double): { + ::dpct::detail::axpy_impl, std::complex>( + q, n, alpha, x, incx, y, incy); + break; + } +#ifdef __INTEL_MKL__ + case ::dpct::detail::get_type_combination_id(library_data_t::real_half, + library_data_t::real_float): { + float alpha_value = + dpct::get_value(reinterpret_cast(alpha), q); + sycl::half alaph_half(alpha_value); + ::dpct::detail::axpy_impl(q, n, &alaph_half, x, + incx, y, incy); + break; + } +#endif + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Performs rotation of points in the plane. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in, out] x Input/Output vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in, out] y Input/Output vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +/// \param [in] c Scaling factor. +/// \param [in] s Scaling factor. +/// \param [in] cs_type Data type of the scaling factors. +inline void rot(descriptor_ptr desc_ptr, std::int64_t n, void *x, + library_data_t x_type, std::int64_t incx, void *y, + library_data_t y_type, std::int64_t incy, const void *c, + const void *s, library_data_t cs_type) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = ::dpct::detail::get_type_combination_id(x_type, cs_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float, + library_data_t::real_float): { + ::dpct::detail::rot_impl(q, n, x, incx, y, incy, c, s); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double, + library_data_t::real_double): { + ::dpct::detail::rot_impl(q, n, x, incx, y, incy, c, + s); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float, + library_data_t::real_float): { + ::dpct::detail::rot_impl, float, float>(q, n, x, incx, + y, incy, c, s); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_double, + library_data_t::real_double): { + ::dpct::detail::rot_impl, double, double>( + q, n, x, incx, y, incy, c, s); + break; + } +#ifdef __INTEL_MKL__ + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float, + library_data_t::complex_float): { + ::dpct::detail::rot_impl, float, std::complex>( + q, n, x, incx, y, incy, c, s); + break; + } + case ::dpct::detail::get_type_combination_id( + library_data_t::complex_double, library_data_t::complex_double): { + ::dpct::detail::rot_impl, double, + std::complex>(q, n, x, incx, y, incy, c, + s); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_half, + library_data_t::real_half): { + ::dpct::detail::rot_impl(q, n, x, incx, + y, incy, c, s); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_bfloat16, + library_data_t::real_bfloat16): { + ::dpct::detail::rot_impl(q, n, x, incx, y, incy, c, + s); + break; + } +#endif + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Performs modified Givens rotation of points in the plane. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in, out] x Input/Output vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in, out] y Input/Output vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +/// \param [in] param Array of 5 parameters. +/// \param [in] param_type Data type of \p param. +inline void rotm(descriptor_ptr desc_ptr, std::int64_t n, void *x, + library_data_t x_type, int64_t incx, void *y, + library_data_t y_type, int64_t incy, const void *param, + library_data_t param_type) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = + ::dpct::detail::get_type_combination_id(x_type, param_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float, + library_data_t::real_float, + library_data_t::real_float): { + ::dpct::detail::rotm_impl(q, n, x, incx, y, incy, + param); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double, + library_data_t::real_double, + library_data_t::real_double): { + ::dpct::detail::rotm_impl(q, n, x, incx, y, incy, + param); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Copies a vector to another vector. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [out] y Output vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +inline void copy(descriptor_ptr desc_ptr, std::int64_t n, const void *x, + library_data_t x_type, std::int64_t incx, void *y, + library_data_t y_type, std::int64_t incy) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = ::dpct::detail::get_type_combination_id(x_type, y_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float, + library_data_t::real_float): { + ::dpct::detail::copy_impl(q, n, x, incx, y, incy); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double, + library_data_t::real_double): { + ::dpct::detail::copy_impl(q, n, x, incx, y, incy); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float, + library_data_t::complex_float): { + ::dpct::detail::copy_impl, std::complex>( + q, n, x, incx, y, incy); + break; + } + case ::dpct::detail::get_type_combination_id( + library_data_t::complex_double, library_data_t::complex_double): { + ::dpct::detail::copy_impl, std::complex>( + q, n, x, incx, y, incy); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Swaps a vector with another vector. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in, out] x Input/Output vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in, out] y Input/Output vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +inline void swap(descriptor_ptr desc_ptr, std::int64_t n, void *x, + library_data_t x_type, std::int64_t incx, void *y, + library_data_t y_type, std::int64_t incy) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = ::dpct::detail::get_type_combination_id(x_type, y_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float, + library_data_t::real_float): { + ::dpct::detail::swap_impl(q, n, x, incx, y, incy); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double, + library_data_t::real_double): { + ::dpct::detail::swap_impl(q, n, x, incx, y, incy); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float, + library_data_t::complex_float): { + ::dpct::detail::swap_impl, std::complex>( + q, n, x, incx, y, incy); + break; + } + case ::dpct::detail::get_type_combination_id( + library_data_t::complex_double, library_data_t::complex_double): { + ::dpct::detail::swap_impl, std::complex>( + q, n, x, incx, y, incy); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Computes the sum of magnitudes of the vector elements. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [out] result The scalar result. +/// \param [in] result_type Data type of \p result. +inline void asum(descriptor_ptr desc_ptr, std::int64_t n, const void *x, + library_data_t x_type, std::int64_t incx, void *result, + library_data_t result_type) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = + ::dpct::detail::get_type_combination_id(x_type, result_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float, + library_data_t::real_float): { + ::dpct::detail::asum_impl(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double, + library_data_t::real_double): { + ::dpct::detail::asum_impl(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float, + library_data_t::real_float): { + ::dpct::detail::asum_impl, float>(q, n, x, incx, + result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_double, + library_data_t::real_double): { + ::dpct::detail::asum_impl, double>(q, n, x, incx, + result); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Finds the index of the element with the largest absolute value in a vector. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [out] result The index of the maximal element. +inline void iamax(descriptor_ptr desc_ptr, std::int64_t n, const void *x, + library_data_t x_type, std::int64_t incx, + std::int64_t *result) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = ::dpct::detail::get_type_combination_id(x_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float): { + ::dpct::detail::iamax_impl(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double): { + ::dpct::detail::iamax_impl(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float): { + ::dpct::detail::iamax_impl>(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id( + library_data_t::complex_double): { + ::dpct::detail::iamax_impl>(q, n, x, incx, result); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Finds the index of the element with the smallest absolute value in a vector. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [out] result The index of the minimum element. +inline void iamin(descriptor_ptr desc_ptr, std::int64_t n, const void *x, + library_data_t x_type, std::int64_t incx, + std::int64_t *result) { + sycl::queue q = desc_ptr->get_queue(); + std::uint64_t key = ::dpct::detail::get_type_combination_id(x_type); + switch (key) { + case ::dpct::detail::get_type_combination_id(library_data_t::real_float): { + ::dpct::detail::iamin_impl(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::real_double): { + ::dpct::detail::iamin_impl(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id(library_data_t::complex_float): { + ::dpct::detail::iamin_impl>(q, n, x, incx, result); + break; + } + case ::dpct::detail::get_type_combination_id( + library_data_t::complex_double): { + ::dpct::detail::iamin_impl>(q, n, x, incx, result); + break; + } + default: + throw std::runtime_error("the combination of data type is unsupported"); + } +} + +/// Finds the index of the element with the largest absolute value in a vector. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [out] result The index of the maximal element. +inline void iamax(descriptor_ptr desc_ptr, std::int64_t n, const void *x, + library_data_t x_type, std::int64_t incx, int *result) { + dpct::blas::wrapper_int_to_int64_out wrapper(desc_ptr->get_queue(), result); + iamax(desc_ptr, n, x, x_type, incx, wrapper.get_ptr()); +} + +/// Finds the index of the element with the smallest absolute value in a vector. +/// \param [in] desc_ptr Descriptor. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [out] result The index of the minimum element. +inline void iamin(descriptor_ptr desc_ptr, std::int64_t n, const void *x, + library_data_t x_type, std::int64_t incx, int *result) { + dpct::blas::wrapper_int_to_int64_out wrapper(desc_ptr->get_queue(), result); + iamin(desc_ptr, n, x, x_type, incx, wrapper.get_ptr()); +} + +/// Finds the least squares solutions for a batch of overdetermined linear +/// systems. Uses the QR factorization to solve a grouped batch of linear +/// systems with full rank matrices. +/// \param [in] desc_ptr Descriptor. +/// \param [in] trans Operation applied to \p a. +/// \param [in] m The number of rows of \p a. +/// \param [in] n The number of columns of \p a. +/// \param [in] nrhs The number of columns of \p b. +/// \param [in, out] a Array of pointers to matrices. +/// \param [in] lda The leading dimension of \p a. +/// \param [in, out] b Array of pointers to matrices. +/// \param [in] ldb The leading dimension of \p b. +/// \param [out] info Set to 0 if no error. +/// \param [out] dev_info Optional. If it is not NULL : dev_info[i]==0 means the +/// i-th problem is successful; dev_info[i]!=0 means dev_info[i] is the first +/// zero diagonal element of the i-th \p a . +/// \param [in] batch_size The size of the batch. +template +inline sycl::event +gels_batch_wrapper(descriptor_ptr desc_ptr, oneapi::mkl::transpose trans, int m, + int n, int nrhs, T *const a[], int lda, T *const b[], + int ldb, int *info, int *dev_info, int batch_size) { +#if defined(DPCT_USM_LEVEL_NONE) || !defined(__INTEL_MKL__) +#if defined(DPCT_USM_LEVEL_NONE) + throw std::runtime_error("this API is unsupported when USM level is none"); +#else + throw std::runtime_error("The oneAPI Math Kernel Library (oneMKL) Interfaces " + "Project does not support this API."); +#endif +#else + using Ty = typename ::dpct::detail::lib_data_traits_t; + sycl::queue exec_queue = desc_ptr->get_queue(); + struct matrix_info_t { + oneapi::mkl::transpose trans_info; + std::int64_t m_info; + std::int64_t n_info; + std::int64_t nrhs_info; + std::int64_t lda_info; + std::int64_t ldb_info; + std::int64_t group_size_info; + }; + matrix_info_t *matrix_info = + (matrix_info_t *)std::malloc(sizeof(matrix_info_t)); + matrix_info->trans_info = trans; + matrix_info->m_info = m; + matrix_info->n_info = n; + matrix_info->nrhs_info = nrhs; + matrix_info->lda_info = lda; + matrix_info->ldb_info = ldb; + matrix_info->group_size_info = batch_size; + std::int64_t scratchpad_size = + oneapi::mkl::lapack::gels_batch_scratchpad_size( + exec_queue, &(matrix_info->trans_info), &(matrix_info->m_info), + &(matrix_info->n_info), &(matrix_info->nrhs_info), + &(matrix_info->lda_info), &(matrix_info->ldb_info), 1, + &(matrix_info->group_size_info)); + Ty *scratchpad = sycl::malloc_device(scratchpad_size, exec_queue); + + *info = 0; + if (dev_info) + exec_queue.memset(dev_info, 0, batch_size * sizeof(int)); + static const std::vector empty_events{}; + static const std::string api_name = "oneapi::mkl::lapack::gels_batch"; + sycl::event e = ::dpct::detail::catch_batch_error_f( + nullptr, api_name, exec_queue, info, dev_info, batch_size, + oneapi::mkl::lapack::gels_batch, exec_queue, &(matrix_info->trans_info), + &(matrix_info->m_info), &(matrix_info->n_info), &(matrix_info->nrhs_info), + (Ty **)a, &(matrix_info->lda_info), (Ty **)b, &(matrix_info->ldb_info), + (std::int64_t)1, &(matrix_info->group_size_info), (Ty *)scratchpad, + (std::int64_t)scratchpad_size, empty_events); + + return exec_queue.submit([&](sycl::handler &cgh) { + cgh.host_task([=]() mutable { + ::dpct::detail::catch_batch_error( + nullptr, api_name, exec_queue, info, dev_info, + matrix_info->group_size_info, + [](sycl::event _e) { + _e.wait_and_throw(); + return 0; + }, + e); + std::free(matrix_info); + sycl::free(scratchpad, exec_queue); + }); + }); +#endif +} +} // namespace blas + +/// Computes matrix-matrix product with general matrices. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] a_trans Specifies the operation applied to A. +/// \param [in] b_trans Specifies the operation applied to B. +/// \param [in] m Specifies the number of rows of the matrix op(A) and of the matrix C. +/// \param [in] n Specifies the number of columns of the matrix op(B) and of the matrix C. +/// \param [in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). +/// \param [in] alpha Scaling factor for the matrix-matrix product. +/// \param [in] a Input matrix A. +/// \param [in] a_type Data type of the matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] b Input matrix B. +/// \param [in] b_type Data type of the matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] beta Scaling factor for matrix C. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] c_type Data type of the matrix C. +/// \param [in] ldc Leading dimension of C. +/// \param [in] scaling_type Data type of the scaling factors. +[[deprecated("Please use dpct::blas::gemm(...) instead.")]] inline void +gemm(sycl::queue &q, oneapi::mkl::transpose a_trans, + oneapi::mkl::transpose b_trans, int m, int n, int k, const void *alpha, + const void *a, library_data_t a_type, int lda, const void *b, + library_data_t b_type, int ldb, const void *beta, void *c, + library_data_t c_type, int ldc, library_data_t scaling_type) { + blas::descriptor desc; + desc.set_queue(&q); + blas::gemm(&desc, a_trans, b_trans, m, n, k, alpha, a, a_type, lda, b, b_type, + ldb, beta, c, c_type, ldc, scaling_type); +} + +/// Computes a batch of matrix-matrix product with general matrices. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] a_trans Specifies the operation applied to A. +/// \param [in] b_trans Specifies the operation applied to B. +/// \param [in] m Specifies the number of rows of the matrix op(A) and of the matrix C. +/// \param [in] n Specifies the number of columns of the matrix op(B) and of the matrix C. +/// \param [in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). +/// \param [in] alpha Scaling factor for the matrix-matrix product. +/// \param [in] a Input matrix A. +/// \param [in] a_type Data type of the matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] b Input matrix B. +/// \param [in] b_type Data type of the matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] beta Scaling factor for matrix C. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] c_type Data type of the matrix C. +/// \param [in] ldc Leading dimension of C. +/// \param [in] batch_size Specifies the number of matrix multiply operations to perform. +/// \param [in] scaling_type Data type of the scaling factors. +[[deprecated("Please use dpct::blas::gemm_batch(...) instead.")]] inline void +gemm_batch(sycl::queue &q, oneapi::mkl::transpose a_trans, + oneapi::mkl::transpose b_trans, int m, int n, int k, + const void *alpha, const void *a[], library_data_t a_type, int lda, + const void *b[], library_data_t b_type, int ldb, const void *beta, + void *c[], library_data_t c_type, int ldc, int batch_size, + library_data_t scaling_type) { + blas::descriptor desc; + desc.set_queue(&q); + blas::gemm_batch(&desc, a_trans, b_trans, m, n, k, alpha, a, a_type, lda, b, + b_type, ldb, beta, c, c_type, ldc, batch_size, scaling_type); +} + +/// Computes a batch of matrix-matrix product with general matrices. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] a_trans Specifies the operation applied to A. +/// \param [in] b_trans Specifies the operation applied to B. +/// \param [in] m Specifies the number of rows of the matrix op(A) and of the matrix C. +/// \param [in] n Specifies the number of columns of the matrix op(B) and of the matrix C. +/// \param [in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). +/// \param [in] alpha Scaling factor for the matrix-matrix product. +/// \param [in] a Input matrix A. +/// \param [in] a_type Data type of the matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] stride_a Stride between the different A matrices. +/// \param [in] b Input matrix B. +/// \param [in] b_type Data type of the matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] stride_b Stride between the different B matrices. +/// \param [in] beta Scaling factor for matrix C. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] c_type Data type of the matrix C. +/// \param [in] ldc Leading dimension of C. +/// \param [in] stride_c Stride between the different C matrices. +/// \param [in] batch_size Specifies the number of matrix multiply operations to perform. +/// \param [in] scaling_type Data type of the scaling factors. +[[deprecated("Please use dpct::blas::gemm_batch(...) instead.")]] inline void +gemm_batch(sycl::queue &q, oneapi::mkl::transpose a_trans, + oneapi::mkl::transpose b_trans, int m, int n, int k, + const void *alpha, const void *a, library_data_t a_type, int lda, + long long int stride_a, const void *b, library_data_t b_type, + int ldb, long long int stride_b, const void *beta, void *c, + library_data_t c_type, int ldc, long long int stride_c, + int batch_size, library_data_t scaling_type) { + blas::descriptor desc; + desc.set_queue(&q); + blas::gemm_batch(&desc, a_trans, b_trans, m, n, k, alpha, a, a_type, lda, + stride_a, b, b_type, ldb, stride_b, beta, c, c_type, ldc, + stride_c, batch_size, scaling_type); +} + +/// This routines perform a special rank-k update of a symmetric matrix C by +/// general matrices A and B. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] uplo Specifies whether C's data is stored in its upper or lower triangle. +/// \param [in] trans Specifies the operation to apply. +/// \param [in] n The number of rows and columns in C. +/// \param [in] k The inner dimension of matrix multiplications. +/// \param [in] alpha Scaling factor for the rank-k update. +/// \param [in] a Input matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] b Input matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] beta Scaling factor for the rank-k update. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] ldc Leading dimension of C. +template +[[deprecated("Please use dpct::blas::syrk(...) instead.")]] inline void +syrk(sycl::queue &q, oneapi::mkl::uplo uplo, oneapi::mkl::transpose trans, + int n, int k, const T *alpha, const T *a, int lda, const T *b, int ldb, + const T *beta, T *c, int ldc) { + blas::descriptor desc; + desc.set_queue(&q); + blas::syrk(&desc, uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +/// This routines perform a special rank-k update of a Hermitian matrix C by +/// general matrices A and B. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] uplo Specifies whether C's data is stored in its upper or lower triangle. +/// \param [in] trans Specifies the operation to apply. +/// \param [in] n The number of rows and columns in C. +/// \param [in] k The inner dimension of matrix multiplications. +/// \param [in] alpha Scaling factor for the rank-k update. +/// \param [in] a Input matrix A. +/// \param [in] lda Leading dimension of A. +/// \param [in] b Input matrix B. +/// \param [in] ldb Leading dimension of B. +/// \param [in] beta Scaling factor for the rank-k update. +/// \param [in, out] c Input/Output matrix C. +/// \param [in] ldc Leading dimension of C. +template +[[deprecated("Please use dpct::blas::herk(...) instead.")]] inline void +herk(sycl::queue &q, oneapi::mkl::uplo uplo, oneapi::mkl::transpose trans, + int n, int k, const T *alpha, const T *a, int lda, const T *b, int ldb, + const Tbeta *beta, T *c, int ldc) { + blas::descriptor desc; + desc.set_queue(&q); + blas::herk(&desc, uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +/// This routine performs a group of trsm operations. Each trsm solves an +/// equation of the form op(A) * X = alpha * B or X * op(A) = alpha * B. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] left_right Specifies A multiplies X on the left or on the right. +/// \param [in] upper_lower Specifies A is upper or lower triangular. +/// \param [in] trans Specifies the operation applied to A. +/// \param [in] unit_diag Specifies whether A is unit triangular. +/// \param [in] m Number of rows of the B matrices. +/// \param [in] n Number of columns of the B matrices. +/// \param [in] alpha Scaling factor for the solutions. +/// \param [in] a Input matrices A. +/// \param [in] a_type Data type of the matrices A. +/// \param [in] lda Leading dimension of the matrices A. +/// \param [in, out] b Input and output matrices B. +/// \param [in] b_type Data type of the matrices B. +/// \param [in] ldb Leading dimension of the matrices B. +/// \param [in] batch_size Specifies the number of trsm operations to perform. +/// \param [in] scaling_type Data type of the scaling factors. +[[deprecated("Please use dpct::blas::trsm_batch(...) instead.")]] inline void +trsm_batch(sycl::queue &q, oneapi::mkl::side left_right, + oneapi::mkl::uplo upper_lower, oneapi::mkl::transpose trans, + oneapi::mkl::diag unit_diag, int m, int n, const void *alpha, + const void **a, library_data_t a_type, int lda, void **b, + library_data_t b_type, int ldb, int batch_size, + library_data_t scaling_type) { + blas::descriptor desc; + desc.set_queue(&q); + blas::trsm_batch(&desc, left_right, upper_lower, trans, unit_diag, m, n, + alpha, a, a_type, lda, b, b_type, ldb, batch_size, + scaling_type); +} + +/// Computes a triangular matrix-general matrix product. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] left_right Specifies A is on the left or right side of the +/// multiplication. +/// \param [in] upper_lower Specifies A is upper or lower triangular. +/// \param [in] trans Specifies the operation applied to A. +/// \param [in] unit_diag Specifies whether A is unit triangular. +/// \param [in] m Number of rows of B. +/// \param [in] n Number of columns of B. +/// \param [in] alpha Scaling factor for the matrix-matrix product. +/// \param [in] a Input matrices A. +/// \param [in] lda Leading dimension of the matrices A. +/// \param [in] b Input matrices B. +/// \param [in] ldb Leading dimension of the matrices B. +/// \param [out] c Output matrices C. +/// \param [in] ldc Leading dimension of the matrices C. +template +[[deprecated("Please use dpct::blas::trmm(...) instead.")]] inline void +trmm(sycl::queue &q, oneapi::mkl::side left_right, + oneapi::mkl::uplo upper_lower, oneapi::mkl::transpose trans, + oneapi::mkl::diag unit_diag, int m, int n, const T *alpha, const T *a, + int lda, const T *b, int ldb, T *c, int ldc) { + blas::descriptor desc; + desc.set_queue(&q); + blas::trmm(&desc, left_right, upper_lower, trans, unit_diag, m, n, alpha, + a, lda, b, ldb, c, ldc); +} + +/// Computes the Euclidean norm of a vector. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [out] result The result scalar. +/// \param [in] result_type Data type of the result. +[[deprecated("Please use dpct::blas::nrm2(...) instead.")]] inline void +nrm2(sycl::queue &q, int n, const void *x, library_data_t x_type, int incx, + void *result, library_data_t result_type) { + blas::descriptor desc; + desc.set_queue(&q); + blas::nrm2(&desc, n, x, x_type, incx, result, result_type); +} + +/// Computes the dot product of two vectors. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in] y Input vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +/// \param [out] result The result scalar. +/// \param [in] result_type Data type of the result. +[[deprecated("Please use dpct::blas::dot(...) instead.")]] inline void +dot(sycl::queue &q, int n, const void *x, library_data_t x_type, int incx, + const void *y, library_data_t y_type, int incy, void *result, + library_data_t result_type) { + blas::descriptor desc; + desc.set_queue(&q); + blas::dot(&desc, n, x, x_type, incx, y, y_type, incy, result, result_type); +} + +/// Computes the dot product of two vectors, conjugating the first vector. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] n Number of elements in vector x. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in] y Input vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +/// \param [out] result The result scalar. +/// \param [in] result_type Data type of the result. +[[deprecated("Please use dpct::blas::dotc(...) instead.")]] inline void +dotc(sycl::queue &q, int n, const void *x, library_data_t x_type, int incx, + const void *y, library_data_t y_type, int incy, void *result, + library_data_t result_type) { + blas::descriptor desc; + desc.set_queue(&q); + blas::dotc(&desc, n, x, x_type, incx, y, y_type, incy, result, result_type); +} + +/// Computes the product of a vector by a scalar. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] n Number of elements in vector x. +/// \param [in] alpha The scale factor alpha. +/// \param [in] alpha_type The data type of alpha. +/// \param [in, out] x Input/Output vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +[[deprecated("Please use dpct::blas::scal(...) instead.")]] inline void +scal(sycl::queue &q, int n, const void *alpha, library_data_t alpha_type, + void *x, library_data_t x_type, int incx) { + blas::descriptor desc; + desc.set_queue(&q); + blas::scal(&desc, n, alpha, alpha_type, x, x_type, incx); +} + +/// Computes a vector-scalar product and adds the result to a vector. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] n Number of elements in vector x. +/// \param [in] alpha The scale factor alpha. +/// \param [in] alpha_type The data type of alpha. +/// \param [in] x Input vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in, out] y Input/Output vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +[[deprecated("Please use dpct::blas::axpy(...) instead.")]] inline void +axpy(sycl::queue &q, int n, const void *alpha, library_data_t alpha_type, + const void *x, library_data_t x_type, int incx, void *y, + library_data_t y_type, int incy) { + blas::descriptor desc; + desc.set_queue(&q); + blas::axpy(&desc, n, alpha, alpha_type, x, x_type, incx, y, y_type, incy); +} + +/// Performs rotation of points in the plane. +/// \param [in] q The queue where the routine should be executed. +/// \param [in] n Number of elements in vector x. +/// \param [in, out] x Input/Output vector x. +/// \param [in] x_type Data type of the vector x. +/// \param [in] incx Stride of vector x. +/// \param [in, out] y Input/Output vector y. +/// \param [in] y_type Data type of the vector y. +/// \param [in] incy Stride of vector y. +/// \param [in] c Scaling factor. +/// \param [in] s Scaling factor. +/// \param [in] cs_type Data type of the scaling factors. +[[deprecated("Please use dpct::blas::rot(...) instead.")]] inline void +rot(sycl::queue &q, int n, void *x, library_data_t x_type, int incx, void *y, + library_data_t y_type, int incy, const void *c, const void *s, + library_data_t cs_type) { + blas::descriptor desc; + desc.set_queue(&q); + blas::rot(&desc, n, x, x_type, incx, y, y_type, incy, c, s, cs_type); +} +} // namespace dpct +#undef DPCT_COMPUTE_MODE_ARG +#undef DPCT_COMPUTE_MODE_PARAM +#endif // __DPCT_BLAS_UTILS_HPP__ diff --git a/sycl/include/dpct/ccl_utils.hpp b/sycl/include/dpct/ccl_utils.hpp new file mode 100644 index 0000000..b965567 --- /dev/null +++ b/sycl/include/dpct/ccl_utils.hpp @@ -0,0 +1,266 @@ +//==---- ccl_utils.hpp----------------------------*- C++ -*----------------==// +// +// Copyright (C) Intel Corporation +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// See https://llvm.org/LICENSE.txt for license information. +// +//===----------------------------------------------------------------------===// + +#ifndef __DPCT_CCL_UTILS_HPP__ +#define __DPCT_CCL_UTILS_HPP__ + +#include "compat_service.hpp" + +#include + +#include +#include + +#include "detail/ccl_utils_detail.hpp" + +namespace dpct { +namespace ccl { + +/// Get concatenated library version as an integer. +static inline int get_version() { + oneapi::ccl::init(); + auto ver = oneapi::ccl::get_library_version(); + return ver.major * 10000 + ver.minor * 100 + ver.update; +} + +/// Create main kvs and return its address. +static inline oneapi::ccl::kvs::address_type create_kvs_address() { + oneapi::ccl::init(); + auto ptr = oneapi::ccl::create_main_kvs(); + auto addr = ptr->get_address(); + detail::get_kvs(addr) = ptr; + return addr; +} + +/// Get stored kvs with /p addr if exist. Otherwise, create kvs with /p addr. +static inline std::shared_ptr +create_kvs(const oneapi::ccl::kvs::address_type &addr) { + oneapi::ccl::init(); + auto &ptr = detail::get_kvs(addr); + if (!ptr) + ptr = oneapi::ccl::create_kvs(addr); + return ptr; +} + +/// dpct communicator extension +class communicator_wrapper : public dpct::ccl::detail::ccl_init_helper { +public: + communicator_wrapper( + int size, int rank, oneapi::ccl::kvs::address_type id, + const oneapi::ccl::comm_attr &attr = oneapi::ccl::default_comm_attr) + : _device_comm(oneapi::ccl::create_device( + static_cast(::dpct::cs::get_current_device()))), + _context_comm( + oneapi::ccl::create_context(::dpct::cs::get_default_context())), + _comm(oneapi::ccl::create_communicator( + size, rank, _device_comm, _context_comm, dpct::ccl::create_kvs(id), + attr)) { + _queue_init = false; + _ccl_stream_ptr = nullptr; + } + + ~communicator_wrapper() { + delete _ccl_stream_ptr; + }; + + /// Return the rank in a oneapi::ccl::communicator + /// \returns The rank corresponding to communicator object + int rank() const { + return _comm.rank(); + } + + /// Retrieves the number of rank in oneapi::ccl::communicator + /// \returns The number of the ranks + int size() const { + return _comm.size(); + } + + /// Return underlying native device, which was used in oneapi::ccl::communicator + sycl::device get_device() const { + return _comm.get_device().get_native(); + } + + /// \brief allreduce is a collective communication operation that performs the global reduction operation + /// on values from all ranks of communicator and distributes the result back to all ranks. + /// \param sendbuff the buffer with @c count elements of @c dtype that stores local data to be reduced + /// \param recvbuff [out] the buffer to store reduced result, must have the same dimension as @c sendbuff + /// \param count the number of elements of type @c dtype in @c sendbuff and @c recvbuff + /// \param dtype the datatype of elements in @c sendbuff and @c recvbuff + /// \param rtype the type of the reduction operation to be applied + /// \param queue_ptr a sycl::queue ptr associated with the operation + /// \return @ref void + void allreduce(const void *sendbuff, void *recvbuff, size_t count, + oneapi::ccl::datatype dtype, oneapi::ccl::reduction rtype, + sycl::queue *queue_ptr) { + call_func_wrapper( + [=](const oneapi::ccl::stream &stream) { + return oneapi::ccl::allreduce(sendbuff, recvbuff, count, dtype, rtype, + _comm, stream); + }, + queue_ptr); + } + + /// \brief reduce is a collective communication operation that performs the + /// global reduction operation on values from all ranks of the communicator + /// and returns the result to the root rank. + /// \param sendbuff the buffer with @c count elements of @c dtype that stores + /// local data to be reduced + /// \param recvbuff [out] the buffer to store reduced result, + /// must have the same dimension as @c sendbuff + /// \param count the number of elements of type @c dtype in @c sendbuff and @c recvbuff + /// \param dtype the datatype of elements in @c sendbuff and @c recvbuff + /// \param root the rank that gets the result of reduction + /// \param rtype the type of the reduction operation to be applied + /// \param queue_ptr a sycl::queue ptr associated with the operation + /// \return @ref void + void reduce(const void *sendbuff, void *recvbuff, size_t count, + oneapi::ccl::datatype dtype, oneapi::ccl::reduction rtype, + int root, sycl::queue *queue_ptr) { + call_func_wrapper( + [=](const oneapi::ccl::stream &stream) { + return oneapi::ccl::reduce(sendbuff, recvbuff, count, dtype, rtype, + root, _comm, stream); + }, + queue_ptr); + } + + /// \brief broadcast is a collective communication operation that broadcasts data + /// from one rank of communicator (denoted as root) to all other ranks. + /// Only support in-place operation + /// \param sendbuff the buffer with @c count elements of @c dtype that stores + /// local data to be reduced + /// \param recvbuff [out] the buffer to store reduced result + /// \param count the number of elements of type @c dtype in @c buf + /// \param dtype thedatatype of elements in @c buf + /// \param root the rank that broadcasts @c buf + /// \param queue_ptr a sycl::queue ptr associated with the operation + /// \return @ref void + void broadcast(void *sendbuff, void *recvbuff, size_t count, + oneapi::ccl::datatype dtype, int root, + sycl::queue *queue_ptr) { + if (sendbuff != recvbuff) { + throw std::runtime_error( + "oneCCL broadcast only support in-place operation. " + "sendbuff and recvbuff must be same."); + return; + } + call_func_wrapper( + [=](const oneapi::ccl::stream &stream) { + return oneapi::ccl::broadcast(recvbuff, count, dtype, root, _comm, + stream); + }, + queue_ptr); + } + + /// \brief reduce_scatter is a collective communication operation that performs the global reduction operation + /// on values from all ranks of the communicator and scatters the result in blocks back to all ranks. + /// \param sendbuff the buffer with @c count elements of @c dtype that stores local data to be reduced + /// \param recvbuff [out] the buffer to store reduced result, must have the same dimension as @c sendbuff + /// \param recv_count the number of elements of type @c dtype in receive block + /// \param dtype the datatype of elements in @c sendbuff and @c recvbuff + /// \param rtype the type of the reduction operation to be applied + /// \param queue_ptr a sycl::queue ptr associated with the operation + /// \return @ref void + void reduce_scatter(const void *sendbuff, void *recvbuff, size_t recv_count, + oneapi::ccl::datatype dtype, oneapi::ccl::reduction rtype, + sycl::queue *queue_ptr) { + call_func_wrapper( + [=](const oneapi::ccl::stream &stream) { + return oneapi::ccl::reduce_scatter(sendbuff, recvbuff, recv_count, + dtype, rtype, _comm, stream); + }, + queue_ptr); + } + + /// \brief send is a pt2pt communication operation that sends data from one rank of communicator. + /// \param sendbuff the buffer with @c count elements of @c dtype serves as send buffer for root + /// \param count the number of elements of type @c dtype in @c sendbuff + /// \param dtype the datatype of elements in @c sendbuff + /// \param peer the rank that receives @c sendbuff + /// \param queue_ptr a sycl::queue ptr associated with the operation + /// \return @ref void + void send(void *sendbuff, size_t count, oneapi::ccl::datatype dtype, int peer, + sycl::queue *queue_ptr) { + call_func_wrapper( + [=](const oneapi::ccl::stream &stream) { + return oneapi::ccl::send(sendbuff, count, dtype, peer, _comm, stream); + }, + queue_ptr); + } + + /// \brief recv is a pt2pt communication operation that sends data from one rank of communicator. + /// \param recvbuff the buffer with @c count elements of @c dtype serves as receive buffer + /// \param count the number of elements of type @c dtype in @c recvbuff + /// \param dtype the datatype of elements in @c recvbuff + /// \param peer the rank that receives @c recvbuff + /// \param queue_ptr a sycl::queue ptr associated with the operation + /// \return @ref void + void recv(void *recvbuff, size_t count, oneapi::ccl::datatype dtype, int peer, + sycl::queue *queue_ptr) { + call_func_wrapper( + [=](const oneapi::ccl::stream &stream) { + return oneapi::ccl::recv(recvbuff, count, dtype, peer, _comm, stream); + }, + queue_ptr); + } + +private: + oneapi::ccl::device _device_comm; + oneapi::ccl::context _context_comm; + oneapi::ccl::communicator _comm; + sycl::queue _queue; + bool _queue_init; + oneapi::ccl::stream *_ccl_stream_ptr; + + template + void call_func_wrapper(Fn func, sycl::queue *qptr) { + if (_queue_init && *qptr != _queue) { + call_func_async(func, qptr); + } else { + if(!_queue_init) { + _queue = *qptr; + _queue_init = true; + _ccl_stream_ptr = new oneapi::ccl::stream(oneapi::ccl::create_stream(_queue)); + } + std::invoke(func, *_ccl_stream_ptr); + } + } + + class call_func_async { + sycl::queue *_q_ptr; + struct call_async_impl { + oneapi::ccl::stream _ccl_stream_impl; + oneapi::ccl::event _ccl_event_impl; + template + explicit call_async_impl(Fn func, sycl::queue *qptr) + : _ccl_stream_impl(oneapi::ccl::create_stream(*qptr)), + _ccl_event_impl(std::invoke(func, _ccl_stream_impl)) {} + }; + call_async_impl *_imp; + + public: + template + explicit call_func_async(Fn func, sycl::queue *qptr) + : _q_ptr(qptr), + _imp(new call_async_impl(func, qptr)) {} + ~call_func_async() { + _q_ptr->submit([&](sycl::handler &cgh) + { cgh.host_task([=] + { + _imp->_ccl_event_impl.wait(); + delete _imp; }); }); + } + }; +}; + +typedef dpct::ccl::communicator_wrapper *comm_ptr; + +} // namespace ccl +} // namespace dpct + +#endif // __DPCT_CCL_UTILS_HPP__ \ No newline at end of file diff --git a/sycl/include/dpct/codepin/codepin.hpp b/sycl/include/dpct/codepin/codepin.hpp new file mode 100644 index 0000000..59ccd65 --- /dev/null +++ b/sycl/include/dpct/codepin/codepin.hpp @@ -0,0 +1,383 @@ +//==---- codepin.hpp -------------------------*- C++ -*------------------==// +// +// Copyright (C) Intel Corporation +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// See https://llvm.org/LICENSE.txt for license information. +// +//===-------------------------------------------------------------------===// +#ifndef __DPCT_CODEPIN_HPP__ +#define __DPCT_CODEPIN_HPP__ + +#include "serialization/basic.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Random seed for data sampling. +#ifndef CODEPIN_RAND_SEED +#define CODEPIN_RAND_SEED 0 +#endif + +// Data size threshold to trigger data sampling. +// array/pointer size larger than the threshold will be sampled. +#ifndef CODEPIN_SAMPLING_THRESHOLD +#define CODEPIN_SAMPLING_THRESHOLD 20 +#endif + +// Sampling percent, interval: [0, 100] +// 0: No data will be logged. +// 100: all data will be logged. +#ifndef CODEPIN_SAMPLING_PERCENT +#define CODEPIN_SAMPLING_PERCENT 1 +#endif + +#define CODEPIN_TO_STR(x) CODEPIN_STR(x) +#define CODEPIN_STR(x) #x +#pragma message( \ + "CodePin data sampling feature is enabled for data dump. As follow list 3 configs for data sampling:") +#pragma message("CODEPIN_RAND_SEED: " CODEPIN_TO_STR(CODEPIN_RAND_SEED)) +#pragma message("CODEPIN_SAMPLING_THRESHOLD: " CODEPIN_TO_STR(CODEPIN_SAMPLING_THRESHOLD)) +#pragma message("CODEPIN_SAMPLING_PERCENT: " CODEPIN_TO_STR(CODEPIN_SAMPLING_PERCENT)) +#pragma message( \ + "Define the macros in the build command to change sampling configs. Also refer to codepin.hpp for definitions and default value of the macros.") + +namespace dpct { +namespace experimental { +namespace codepin { + +inline static std::map api_index; +inline static std::map event_map; +inline static bool rand_seed_setup = false; +namespace detail { + +inline static std::unordered_set ptr_unique; + +class logger { +public: + logger(const std::string &dump_file) + : opf(dump_file), json_ss(opf), arr(json_ss) { + auto top_obj = arr.object(); + top_obj.key("CodePin Random Seed"); + top_obj.value(CODEPIN_RAND_SEED); + top_obj.key("CodePin Sampling Threshold"); + top_obj.value(CODEPIN_SAMPLING_THRESHOLD); + top_obj.key("CodePin Sampling Percent"); + top_obj.value(CODEPIN_SAMPLING_PERCENT); + } + ~logger() {} + + detail::json_stringstream &get_stringstream() { + return this->json_ss; + } + + template + void print_CP(const std::string &cp_id, std::string device_name, + size_t free_byte, size_t total_byte, float elapse_time, + queue_t queue, Args... args) { + ptr_unique.clear(); + auto obj = arr.object(); + obj.key("ID"); + obj.value(cp_id); + obj.key("Device Name"); + obj.value(device_name); + obj.key("Device ID"); +#ifdef __NVCC__ + int device_id; + cudaGetDevice(&device_id); + obj.value(device_id); +#else + obj.value((int)dpct::get_current_device_id()); +#endif + obj.key("Stream Address"); + obj.value((void *)queue); + obj.key("Free Device Memory"); + obj.value(free_byte); + obj.key("Total Device Memory"); + obj.value(total_byte); + obj.key("Elapse Time(ms)"); + obj.value(elapse_time); + obj.key("CheckPoint"); + auto cp_obj = + obj.value(); + print_args(cp_obj, queue, 0, args...); + } + + void print_args(json_stringstream::json_obj &obj, queue_t queue, + int index = 0) {} + + template + void print_args(json_stringstream::json_obj &obj, queue_t queue, int index, + std::string_view arg_name, First &arg, RestArgs... args) { + obj.key(arg_name); + { + auto type_obj = + obj.value(); + detail::data_ser::print_type_name(type_obj); + type_obj.key("Address"); + print_address(type_obj, arg); + type_obj.key("Index"); + type_obj.value(index); + type_obj.key("Data"); + detail::data_ser::dump(json_ss, arg, queue); + } + print_args(obj, queue, index + 1, args...); + } + template + void print_address(json_stringstream::json_obj &obj, ArgT arg) { + if constexpr (std::is_pointer::value) { + obj.value((void *)arg); + } else { + obj.value((void *)&arg); + } + } + +private: + std::ofstream opf; + detail::json_stringstream json_ss; + detail::json_stringstream::json_array arr; +}; + +#ifdef __NVCC__ +inline std::string data_file_prefix = "CodePin_CUDA_"; +#else +inline std::string data_file_prefix = "CodePin_SYCL_"; +#endif + +inline std::string get_data_file_name(std::string_view data_file_prefix) { + std::time_t now_time = std::time(nullptr); + std::stringstream strs; + strs << data_file_prefix + << std::put_time(std::localtime(&now_time), "%Y-%m-%d_%H-%M-%S") + << ".json"; + return strs.str(); +} + +inline logger log(get_data_file_name(data_file_prefix)); + +inline std::map &get_ptr_size_map() { + static std::map ptr_size_map; + return ptr_size_map; +} + +inline uint32_t get_ptr_size_in_bytes(void *ptr) { + const std::map &ptr_size_map = get_ptr_size_map(); + const auto &it = ptr_size_map.find(ptr); + return (it != ptr_size_map.end()) ? it->second : 0; +} + +template +class data_ser { +public: + static void dump(detail::json_stringstream &ss, T* value, + queue_t queue) { + using PointeeType = std::remove_cv_t>; + PointeeType *non_const_value = const_cast(value); + if (ptr_unique.find(non_const_value) != ptr_unique.end()) { + return; + } + ptr_unique.insert(non_const_value); + int size = get_ptr_size_in_bytes(non_const_value); + size = size == 0 ? 1 : size / sizeof(*value); + PointeeType *dump_addr = non_const_value; + bool is_dev = is_dev_ptr(non_const_value); + if (is_dev) { + PointeeType *h_data = new PointeeType[size]; +#ifdef __NVCC__ + cudaMemcpyAsync(h_data, value, size * sizeof(PointeeType), + cudaMemcpyDeviceToHost, queue); + cudaStreamSynchronize(queue); +#else + queue->memcpy((void *)h_data, (void *)value, size * sizeof(PointeeType)) + .wait(); +#endif + dump_addr = h_data; + } + auto arr = ss.array(); + for (int i = 0; i < size; ++i) { + if (size > CODEPIN_SAMPLING_THRESHOLD && i != 0) { + float r = static_cast(rand()) / static_cast(RAND_MAX); + if (r > (float)CODEPIN_SAMPLING_PERCENT/(float)100) + continue; + } + auto obj = arr.object(); + detail::data_ser::print_type_name(obj); + obj.key("Data"); + detail::data_ser::dump( + ss, *(dump_addr + i), queue); + } + if(is_dev) + delete[] dump_addr; + } + static void print_type_name( + detail::json_stringstream::json_obj &obj) { + obj.key("Type"); + obj.value("Pointer"); + } +}; + +template +class data_ser::value>::type> { +public: + static void dump(detail::json_stringstream &ss, T value, + queue_t queue) { + auto arr = ss.array(); + size_t size = sizeof(T) / sizeof(value[0]); + for (size_t i = 0; i < size; ++i) { + if (size > CODEPIN_SAMPLING_THRESHOLD && i != 0) { + float r = static_cast(rand()) / static_cast(RAND_MAX); + if (r > (float)CODEPIN_SAMPLING_PERCENT/(float)100) + continue; + } + auto obj = arr.object(); + detail::data_ser< + std::remove_extent_t>::print_type_name(obj); + obj.key("Data"); + detail::data_ser>::dump( + ss, value[i], queue); + } + } + static void print_type_name( + detail::json_stringstream::json_obj &obj) { + obj.key("Type"); + obj.value("Array"); + } +}; + +template +void gen_log_API_CP(const std::string &cp_id, std::string device_name, + size_t free_byte, size_t total_byte, float elapse_time, + queue_t queue, Args... args) { + if (!rand_seed_setup) { + srand(CODEPIN_RAND_SEED); + rand_seed_setup = true; + std::cout << "CodePin data sampling is enabled for data dump. As follow list 3 " + "configs for data sampling:" + << std::endl; + std::cout << "CODEPIN_RAND_SEED: " << CODEPIN_RAND_SEED << std::endl; + std::cout << "CODEPIN_SAMPLING_THRESHOLD: " << CODEPIN_SAMPLING_THRESHOLD + << std::endl; + std::cout << "CODEPIN_SAMPLING_PERCENT: " << CODEPIN_SAMPLING_PERCENT + << std::endl; + } + log.print_CP(cp_id, device_name, free_byte, total_byte, elapse_time, queue, + args...); +} +} // namespace detail + +#ifdef __NVCC__ +inline void synchronize(cudaStream_t stream) { cudaStreamSynchronize(stream); } +#else +inline void synchronize(sycl::queue *q) { q->wait(); } +#endif + +/// Generate API check point prolog. +/// \param cp_id The UID of the function call. +/// \param queue The sycl queue to synchronize the command execution. +/// \param args The var name string and variable value pair list. +template +void gen_prolog_API_CP(const std::string &cp_id, + queue_t queue, Args&&... args) { + synchronize(queue); + std::string prolog_tag = cp_id + ":" + "prolog"; + if (api_index.find(cp_id) == api_index.end()) { + api_index[cp_id] = 0; + } else { + api_index[cp_id]++; + } + std::string event_id = + cp_id + ":" + std::to_string(api_index[cp_id]); + size_t free_byte, total_byte; +#ifdef __NVCC__ + int device; + cudaGetDevice(&device); + cudaDeviceProp deviceProp; + cudaGetDeviceProperties(&deviceProp, device); + std::string device_name(deviceProp.name); + cudaMemGetInfo(&free_byte, &total_byte); + cudaEvent_t event; + cudaEventCreate(&event); + cudaEventRecord(event, queue); + event_map[event_id] = event; +#else + dpct::get_current_device().get_memory_info(free_byte, total_byte); + std::string device_name = dpct::get_current_device().get_info(); +#ifdef DPCT_PROFILING_ENABLED + sycl::event event = queue->ext_oneapi_submit_barrier(); + event_map[event_id] = event; +#endif //DPCT_PROFILING_ENABLED +#endif + + detail::gen_log_API_CP(prolog_tag, device_name, free_byte, total_byte, 0.0f, + queue, args...); +} + +/// Generate API check point epilog. +/// \param cp_id The UID of the function call. +/// \param stream The sycl queue to synchronize the command execution. +/// \param args The var name string and variable value pair list. +template +void gen_epilog_API_CP(const std::string &cp_id, + queue_t queue, Args&&... args) { + synchronize(queue); + std::string epilog_tag = cp_id + ":" + "epilog"; + std::string event_id = + cp_id + ":" + std::to_string(api_index[cp_id]); + size_t free_byte, total_byte; + float kernel_elapsed_time = 0.0f; +#ifdef __NVCC__ + int device; + cudaGetDevice(&device); + cudaDeviceProp deviceProp; + cudaGetDeviceProperties(&deviceProp, device); + std::string device_name(deviceProp.name); + cudaMemGetInfo(&free_byte, &total_byte); + cudaEvent_t event; + cudaEventCreate(&event); + cudaEventRecord(event, queue); + auto pre_event = event_map[event_id]; + event_map.erase(event_id); + cudaEventSynchronize(event); + cudaEventElapsedTime(&kernel_elapsed_time, pre_event, event); +#else +#ifdef DPCT_PROFILING_ENABLED + sycl::event event = queue->ext_oneapi_submit_barrier(); + auto pre_event = event_map[event_id]; + event_map.erase(event_id); + event.wait_and_throw(); + kernel_elapsed_time = + (event.get_profiling_info() - + pre_event + .get_profiling_info()) / + 1000000.0f; +#endif //DPCT_PROFILING_ENABLED + std::string device_name = dpct::get_current_device().get_info(); + dpct::get_current_device().get_memory_info(free_byte, total_byte); +#endif + detail::gen_log_API_CP(epilog_tag, device_name, free_byte, total_byte, + kernel_elapsed_time, queue, args...); +} + +inline std::map &get_ptr_size_map() { + return detail::get_ptr_size_map(); +} +} // namespace codepin +} // namespace experimental +} // namespace dpct + +namespace dpctexp = dpct::experimental; + + +#endif // End of __DPCT_CODEPIN_HPP__ diff --git a/sycl/include/dpct/codepin/serialization/basic.hpp b/sycl/include/dpct/codepin/serialization/basic.hpp new file mode 100644 index 0000000..6be886b --- /dev/null +++ b/sycl/include/dpct/codepin/serialization/basic.hpp @@ -0,0 +1,501 @@ +//==----------- basic.hpp ----------------------------*-C++-*-------------==// +// +// Copyright (C) Intel Corporation +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// See https://llvm.org/LICENSE.txt for license information. +// +//===--------------------------------------------------------------------===// +#ifndef __DPCT_CODEPIN_SER_BASIC_HPP__ +#define __DPCT_CODEPIN_SER_BASIC_HPP__ + +#if defined(__linux__) +#include +#endif +#include +#include +#include +#include +#ifdef __NVCC__ +#include +#include +#include +#else +#include +#include +#endif + +namespace dpct { +namespace experimental { +namespace codepin { + +#ifdef __NVCC__ +typedef cudaStream_t queue_t; +#else +typedef dpct::queue_ptr queue_t; +#endif + +#ifdef __NVCC__ +typedef cudaEvent_t event_t; +#else +typedef sycl::event event_t; +#endif + +namespace detail { + +inline bool is_dev_ptr(void *p) { +#ifdef __NVCC__ + cudaPointerAttributes attr; + cudaPointerGetAttributes(&attr, p); + if (attr.type == cudaMemoryTypeDevice) + return true; + return false; +#else + dpct::pointer_attributes attributes; + attributes.init(p); + if (attributes.get_device_pointer() != nullptr) + return true; + return false; +#endif +} + +class json_stringstream { + public: + json_stringstream(std::ofstream &ofst) : os(ofst) { + if (!ofst.is_open()) { + throw std::runtime_error("Error while openning file: "); + } + } + +private: + std::string indent; + const size_t tab_length = 2; + std::ofstream &os; + +#if defined(__linux__) + const std::string newline = "\n"; +#elif defined(_WIN64) + const std::string newline = "\r\n"; +#else +#error Only support windows and Linux. +#endif + + +public: + class json_obj { + bool isFirst = true; + json_stringstream &js; + private: + friend class json_stringstream; + json_obj(json_stringstream &json_ss) : js(json_ss) { + js.os << "{" << js.newline; + js.indent.append(js.tab_length, ' '); + js.os << js.indent; + } + + public: + template T value(); + + void key(std::string_view key) { + if (!isFirst){ + js.os << "," << js.newline << js.indent; + } else { + isFirst = false; + } + js.os << "\"" << key << "\": "; + }; + + void value(std::string_view value) { js.os << "\"" << value << "\""; }; + void value(float value) { js.os << "\"" << value << "\""; }; + void value(size_t value) { js.os << "\"" << value << "\""; }; + void value(int value) { js.os << "\"" << value << "\""; }; + void value(void *value) { js.os << "\"" << value << "\""; }; + ~json_obj() { + js.indent.resize(js.indent.size() - js.tab_length); + js.os << js.newline; + js.os << js.indent; + js.os << "}"; + } + }; + + class json_array { + bool isFirst = true; + json_stringstream &js; + public: + json_array(json_stringstream &json_ss) : js(json_ss) { + if(!(js.os)) + return; + js.os << "[" << js.newline; + js.indent.append(js.tab_length, ' '); + js.os << js.indent; + } + + json_obj object() { + if(!isFirst){ + js.os << "," << js.newline << js.indent; + } else { + isFirst = false; + } + return json_obj(js); + } + + template + void member(const MemberT &t) { + if(!isFirst){ + js.os << "," << js.newline << js.indent; + } else { + isFirst = false; + } + js.os << t; + } + + ~json_array() { + js.indent.resize(js.indent.size() - js.tab_length); + js.os << js.newline; + js.os << js.indent; + js.os << "]"; + } + }; + + template >>> + json_stringstream &operator<<(T &&value) { + os << std::forward(value); + return *this; + } + + json_obj object(){ + return json_obj(*this); + } + json_array array(){ + return json_array(*this); + } +}; + +template <> +inline json_stringstream::json_obj +json_stringstream::json_obj::value() { + return js.object(); +} + +template inline std::string demangle_name() { + std::string ret_str = ""; +#if defined(__linux__) + int s; + auto mangle_name = typeid(T).name(); + auto demangle_name = abi::__cxa_demangle(mangle_name, NULL, NULL, &s); + if (s != 0) { + ret_str = "CODEPIN:ERROR:0: Unable to demangle symbol " + + std::string(mangle_name) + "."; + } else { + ret_str = demangle_name; + std::free(demangle_name); + } +#else + ret_str = typeid(T).name(); +#endif + return ret_str; +} + +#ifdef __NVCC__ +template <> inline std::string demangle_name<__half>() { return "fp16"; } +template <> inline std::string demangle_name<__nv_bfloat16>() { return "bf16"; } +#else +template <> inline std::string demangle_name() { return "fp16"; } +template <> inline std::string demangle_name() { + return "bf16"; +} +#endif + +template class data_ser { + +public: + static void dump(json_stringstream &ss, T value, queue_t queue) { + auto obj = ss.object(); + obj.key("Data"); + obj.value("CODEPIN:ERROR:1: Unable to find the corresponding serialization " + "function."); + } + static void print_type_name(json_stringstream::json_obj &obj) { + obj.key("Type"); + obj.value(std::string(demangle_name())); + } +}; + +template +class data_ser::value>::type> { +public: + static void dump(json_stringstream &ss, const T &value, queue_t queue) { + auto arr = ss.array(); + arr.member(value); + } + static void print_type_name(json_stringstream::json_obj &obj) { + obj.key("Type"); + obj.value(std::string(demangle_name())); + } +}; + +#ifdef __NVCC__ +template <> class data_ser<__half> { +public: + static void dump(json_stringstream &ss, const __half &value, queue_t queue) { + float f = __half2float(value); + auto arr = ss.array(); + arr.member(value); + } + static void print_type_name(json_stringstream::json_obj &obj) { + obj.key("Type"); + obj.value(std::string(demangle_name<__half>())); + } +}; +template <> class data_ser<__nv_bfloat16> { +public: + static void dump(json_stringstream &ss, const __nv_bfloat16 &value, + queue_t queue) { + float f = __bfloat162float(value); + auto arr = ss.array(); + arr.member(value); + } + static void print_type_name(json_stringstream::json_obj &obj) { + obj.key("Type"); + obj.value(std::string(demangle_name<__nv_bfloat16>())); + } +}; +#else +template +class data_ser::value || + std::is_same::value>::type> { +public: + static void dump(json_stringstream &ss, const T &value, queue_t queue) { + auto arr = ss.array(); + arr.member(value); + } + static void print_type_name(json_stringstream::json_obj &obj) { + obj.key("Type"); + obj.value(std::string(demangle_name())); + } + +}; +#endif + +#ifdef __NVCC__ +template <> class data_ser { +public: + static void dump(json_stringstream &ss, const int3 &value, + queue_t queue) { + auto arr = ss.array(); + { + auto obj_x = arr.object(); + obj_x.key("x"); + auto value_x = + obj_x + .value(); + data_ser::print_type_name(value_x); + value_x.key("Data"); + data_ser::dump(ss, value.x, queue); + } + { + auto obj_y = arr.object(); + obj_y.key("y"); + auto value_y = + obj_y + .value(); + data_ser::print_type_name(value_y); + value_y.key("Data"); + data_ser::dump(ss, value.y, queue); + } + { + auto obj_z = arr.object(); + obj_z.key("z"); + auto value_z = + obj_z + .value(); + data_ser::print_type_name(value_z); + value_z.key("Data"); + data_ser::dump(ss, value.z, queue); + } + } + static void print_type_name(json_stringstream::json_obj &obj){ + obj.key("Type"); + obj.value("int3"); + } +}; + +template <> class data_ser { +public: + static void dump(json_stringstream &ss, const float3 &value, + queue_t queue) { + auto arr = ss.array(); + { + auto obj_x = arr.object(); + obj_x.key("x"); + auto value_x = + obj_x + .value(); + data_ser::print_type_name(value_x); + value_x.key("Data"); + data_ser::dump(ss, value.x, queue); + } + { + auto obj_y = arr.object(); + obj_y.key("y"); + auto value_y = + obj_y + .value(); + data_ser::print_type_name(value_y); + value_y.key("Data"); + data_ser::dump(ss, value.y, queue); + } + { + auto obj_z = arr.object(); + obj_z.key("z"); + auto value_z = + obj_z + .value(); + data_ser::print_type_name(value_z); + value_z.key("Data"); + data_ser::dump(ss, value.z, queue); + } + } + static void print_type_name(json_stringstream::json_obj &obj){ + obj.key("Type"); + obj.value("float3"); + } +}; + +#else +template <> class data_ser { +public: + static void dump(json_stringstream &ss, const sycl::int3 &value, + queue_t queue) { + auto arr = ss.array(); + { + auto obj_x = arr.object(); + obj_x.key("x"); + auto value_x = + obj_x + .value(); + data_ser::print_type_name(value_x); + value_x.key("Data"); + data_ser::dump(ss, value.x(), queue); + } + { + auto obj_y = arr.object(); + obj_y.key("y"); + auto value_y = + obj_y + .value(); + data_ser::print_type_name(value_y); + value_y.key("Data"); + data_ser::dump(ss, value.y(), queue); + } + { + auto obj_z = arr.object(); + obj_z.key("z"); + auto value_z = + obj_z + .value(); + data_ser::print_type_name(value_z); + value_z.key("Data"); + data_ser::dump(ss, value.z(), queue); + } + } + static void print_type_name(json_stringstream::json_obj &obj){ + obj.key("Type"); + obj.value("sycl::int3"); + } +}; + +template <> class data_ser { +public: + static void dump(json_stringstream &ss, const sycl::float3 &value, + queue_t queue) { + auto arr = ss.array(); + { + auto obj_x = arr.object(); + obj_x.key("x"); + auto value_x = + obj_x + .value(); + data_ser::print_type_name(value_x); + value_x.key("Data"); + data_ser::dump(ss, value.x(), queue); + } + { + auto obj_y = arr.object(); + obj_y.key("y"); + auto value_y = + obj_y + .value(); + data_ser::print_type_name(value_y); + value_y.key("Data"); + data_ser::dump(ss, value.y(), queue); + } + { + auto obj_z = arr.object(); + obj_z.key("z"); + auto value_z = + obj_z + .value(); + data_ser::print_type_name(value_z); + value_z.key("Data"); + data_ser::dump(ss, value.z(), queue); + } + } + static void print_type_name(json_stringstream::json_obj &obj){ + obj.key("Type"); + obj.value("sycl::float3"); + } +}; +#endif + +template <> class data_ser { +public: + static void dump(json_stringstream &ss, const char *value, + queue_t queue) { + auto obj = ss.object(); + obj.key("Data"); + const char *dump_addr = value; + bool is_dev = is_dev_ptr((void*)value); + if (is_dev) { + const char *h_data = new char[strlen(value)]; +#ifdef __NVCC__ + cudaMemcpyAsync((void *)h_data, (void *)value, + strlen(value) * sizeof(char), cudaMemcpyDeviceToHost, + queue); + cudaStreamSynchronize(queue); +#else + queue->memcpy((void *)h_data, (void *)value, strlen(value) * sizeof(char)) + .wait(); +#endif + dump_addr = h_data; + } + obj.value(std::string(dump_addr)); + } + static void print_type_name(json_stringstream::json_obj &obj){ + obj.key("Type"); + obj.value("char *"); + } +}; + +template <> class data_ser { +public: + static void dump(json_stringstream &ss, const std::string &value, + queue_t queue) { + auto obj = ss.object(); + obj.key("Data"); + obj.value(value); + } + static void print_type_name(json_stringstream::json_obj &obj){ + obj.key("Type"); + obj.value("std::string"); + } +}; + +} // namespace detail +} // namespace codepin +} // namespace experimental +} // namespace dpct + +#endif diff --git a/sycl/include/dpct/compat_service.hpp b/sycl/include/dpct/compat_service.hpp new file mode 100644 index 0000000..c0d571e --- /dev/null +++ b/sycl/include/dpct/compat_service.hpp @@ -0,0 +1,122 @@ +//==---- compat_service.hpp -----------------------*- C++ -*----------------==// +// +// Copyright (C) Intel Corporation +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// See https://llvm.org/LICENSE.txt for license information. +// +//===----------------------------------------------------------------------===// +// This file contains some compatibility service APIs which are used by all +// library utility helper functions. The compatibility service APIs are based on +// either dpct implementation or syclcompat implementation, which is controlled +// by the macro USE_DPCT_HELPER. +//===----------------------------------------------------------------------===// + +#ifndef __DPCT_COMPAT_SERVICE_HPP__ +#define __DPCT_COMPAT_SERVICE_HPP__ + +namespace dpct { +namespace cs { +#if USE_DPCT_HELPER +namespace ns = ::dpct; +using memcpy_direction = ::dpct::memcpy_direction; +template using kernel_name = dpct_kernel_name; +using byte_t = ::dpct::byte_t; +#else +namespace ns = ::syclcompat; +using memcpy_direction = ::syclcompat::detail::memcpy_direction; +template using kernel_name = syclcompat_kernel_name; +#ifndef __dpct_inline__ +#define __dpct_inline__ __syclcompat_inline__ +#endif +using byte_t = ::syclcompat::byte_t; +#endif + +using ns::get_current_device; +using ns::get_default_context; +using ns::queue_ptr; + +namespace detail { +using ns::detail::get_pointer_attribute; +using ns::detail::pointer_access_attribute; +} // namespace detail + +inline sycl::queue &get_default_queue() { +#if USE_DPCT_HELPER + return ::dpct::get_default_queue(); +#else + return *::syclcompat::detail::dev_mgr::instance() + .current_device() + .default_queue(); +#endif +} + +inline sycl::event +memcpy(sycl::queue &q, void *to_ptr, const void *from_ptr, size_t size, + memcpy_direction direction = memcpy_direction::automatic, + const std::vector &dep_events = {}) { +#if USE_DPCT_HELPER + return ::dpct::detail::dpct_memcpy(q, to_ptr, from_ptr, size, direction, + dep_events); +#else + return ::syclcompat::detail::memcpy(q, to_ptr, from_ptr, size, dep_events); +#endif +} + +inline std::vector +memcpy(sycl::queue &q, void *to_ptr, const void *from_ptr, size_t to_pitch, + size_t from_pitch, size_t x, size_t y, + memcpy_direction direction = memcpy_direction::automatic, + const std::vector &dep_events = {}) { +#if USE_DPCT_HELPER + return ::dpct::detail::dpct_memcpy( + q, to_ptr, from_ptr, sycl::range<3>(to_pitch, y, 1), + sycl::range<3>(from_pitch, y, 1), sycl::id<3>(0, 0, 0), + sycl::id<3>(0, 0, 0), sycl::range<3>(x, y, 1), direction, dep_events); +#else + return ::syclcompat::detail::memcpy( + q, to_ptr, from_ptr, sycl::range<3>(to_pitch, y, 1), + sycl::range<3>(from_pitch, y, 1), sycl::id<3>(0, 0, 0), + sycl::id<3>(0, 0, 0), sycl::range<3>(x, y, 1), dep_events); +#endif +} + +inline void *malloc(size_t size, sycl::queue q = get_default_queue()) { +#if USE_DPCT_HELPER + return ::dpct::dpct_malloc(size, q); +#else + return ::syclcompat::malloc(size, q); +#endif +} + +template +inline sycl::event fill(sycl::queue &q, void *dev_ptr, valueT value, + size_t size) { +#if USE_DPCT_HELPER + return ::dpct::detail::dpct_memset(q, dev_ptr, value, size); +#else + return ::syclcompat::detail::fill(q, dev_ptr, value, size); +#endif +} + +inline void free(void *to_ptr, sycl::queue q) { +#if USE_DPCT_HELPER + return ::dpct::detail::dpct_free(to_ptr, q); +#else + return ::syclcompat::free(to_ptr, q); +#endif +} + +inline sycl::event enqueue_free(const std::vector &pointers, + const std::vector &events, + sycl::queue q = get_default_queue()) { +#if USE_DPCT_HELPER + return ::dpct::detail::async_dpct_free(pointers, events, q); +#else + return ::syclcompat::enqueue_free(pointers, events, q); +#endif +} + +} // namespace cs +} // namespace dpct + +#endif // __DPCT_COMPAT_SERVICE_HPP__ diff --git a/sycl/include/dpct/detail/blas_gemm_utils_detail.hpp b/sycl/include/dpct/detail/blas_gemm_utils_detail.hpp new file mode 100644 index 0000000..4506803 --- /dev/null +++ b/sycl/include/dpct/detail/blas_gemm_utils_detail.hpp @@ -0,0 +1,426 @@ +//==---- blas_gemm_utils_detail.hpp---------------------*- C++ -*-----------==// +// +// Copyright (C) Intel Corporation +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// See https://llvm.org/LICENSE.txt for license information. +// +//===----------------------------------------------------------------------===// + +#ifndef __DPCT_BLAS_GEMM_UTILS_DETAIL_HPP__ +#define __DPCT_BLAS_GEMM_UTILS_DETAIL_HPP__ + +namespace dpct::blas_gemm::experimental::detail { +/// Sacling each row of matrix D with the corresponding element of vector alpha. +template +sycl::event scale_new_a_impl(::dpct::cs::queue_ptr q_ptr, int rows, int cols, + void *a_ptr, const void *alpha_ptr, + bool vector_alpha, bool device_alpha, + const void *a_scale_ptr, const void *b_scale_ptr, + const std::vector &dependencies) { + std::vector deps = dependencies; + T *a = (T *)a_ptr; + Tscale *alpha = (Tscale *)alpha_ptr; + Tscale *a_scale = (Tscale *)a_scale_ptr; + Tscale *b_scale = (Tscale *)b_scale_ptr; + + if (!device_alpha) { + Tscale *alpha_host = alpha; + alpha = (Tscale *)::dpct::cs::malloc(sizeof(Tscale), *q_ptr); + deps.push_back( + ::dpct::cs::memcpy(*q_ptr, alpha, alpha_host, sizeof(Tscale))); + } + if (!a_scale_ptr) { + a_scale = (Tscale *)::dpct::cs::malloc(sizeof(Tscale), *q_ptr); + deps.push_back(::dpct::cs::fill(*q_ptr, a_scale, 1.0, 1)); + } + if (!b_scale_ptr) { + b_scale = (Tscale *)::dpct::cs::malloc(sizeof(Tscale), *q_ptr); + deps.push_back(::dpct::cs::fill(*q_ptr, b_scale, 1.0, 1)); + } + + sycl::event e = q_ptr->submit([&](sycl::handler &cgh) { + cgh.depends_on(deps); +#ifdef DPCT_USM_LEVEL_NONE + access_wrapper a_acc(a, cgh); + access_wrapper alpha_acc(alpha, cgh); + access_wrapper a_scale_acc(a_scale, cgh); + access_wrapper b_scale_acc(b_scale, cgh); +#endif + cgh.parallel_for< + ::dpct::cs::kernel_name>( + sycl::range<2>(rows, cols), [=](sycl::id<2> index) { +#ifdef DPCT_USM_LEVEL_NONE + T *a_data = a_acc.get_raw_pointer(); + Tscale *alpha_data = alpha_acc.get_raw_pointer(); + Tscale *a_scale_data = a_scale_acc.get_raw_pointer(); + Tscale *b_scale_data = b_scale_acc.get_raw_pointer(); +#else + T *a_data = a; + const Tscale *alpha_data = alpha; + const Tscale *a_scale_data = a_scale; + const Tscale *b_scale_data = b_scale; +#endif + size_t row_idx = index.get(0); + size_t col_idx = index.get(1); + size_t idx = rows * col_idx + row_idx; + + Tscale ab_scale = a_scale_data[0] * b_scale_data[0]; + + if (vector_alpha) + a_data[idx] = a_data[idx] * alpha_data[row_idx] * ab_scale; + else + a_data[idx] = a_data[idx] * alpha_data[0] * ab_scale; + }); + }); + return q_ptr->submit([&](sycl::handler &cgh) { + cgh.depends_on(e); + cgh.host_task([=] { + if (!device_alpha) + ::dpct::cs::free(alpha, *q_ptr); + if (!a_scale_ptr) + ::dpct::cs::free(a_scale, *q_ptr); + if (!b_scale_ptr) + ::dpct::cs::free(b_scale, *q_ptr); + }); + }); +} + +// a is col major without padding +inline sycl::event scale_new_a(::dpct::cs::queue_ptr q_ptr, int rows, int cols, + void *a, library_data_t a_type, + const void *alpha, library_data_t scale_type, + bool vector_alpha, bool device_alpha, + const void *a_scale, const void *b_scale, + const std::vector &deps) { + std::uint64_t key = dpct::detail::get_type_combination_id(a_type, scale_type); + sycl::event e; + switch (key) { +#define __SCALE_NEW_A_IMPL_CASE(A_TYPE_ENUM, SCALE_TYPE_ENUM, A_TYPE, \ + SCALE_TYPE) \ + case dpct::detail::get_type_combination_id( \ + library_data_t::A_TYPE_ENUM, library_data_t::SCALE_TYPE_ENUM): { \ + e = scale_new_a_impl(q_ptr, rows, cols, a, alpha, \ + vector_alpha, device_alpha, \ + a_scale, b_scale, deps); \ + break; \ + } + __SCALE_NEW_A_IMPL_CASE(real_int8, real_float, std::int8_t, float) + __SCALE_NEW_A_IMPL_CASE(real_int32, real_float, int, float) + __SCALE_NEW_A_IMPL_CASE(real_int8, real_int32, std::int8_t, int) + __SCALE_NEW_A_IMPL_CASE(real_float, real_float, float, float) +#undef __SCALE_NEW_A_IMPL_CASE + default: + throw std::runtime_error("dpct::blas_gemm::experimental::detail::scale_new_" + "a_impl() does not support the data " + "type combination currently."); + } + return e; +} + +/// Get a linear idx map for a 2D point (row_idx, col_idx) between src_order and +/// dst_order. +inline std::tuple +get_linear_idx_map(size_t rows, size_t cols, size_t src_ld, order_t src_order, + size_t dst_ld, order_t dst_order, size_t row_idx, + size_t col_idx) { +#define COMBINE(from, to) \ + static_cast(from) << 8 | static_cast(to) + + size_t from_linear_idx, to_linear_idx; + switch (COMBINE(src_order, dst_order)) { + case COMBINE(order_t::col, order_t::row): { + from_linear_idx = src_ld * col_idx + row_idx; + to_linear_idx = dst_ld * row_idx + col_idx; + break; + } + case COMBINE(order_t::row, order_t::col): { + from_linear_idx = src_ld * row_idx + col_idx; + to_linear_idx = dst_ld * col_idx + row_idx; + break; + } + case COMBINE(order_t::col, order_t::col32): { + from_linear_idx = src_ld * col_idx + row_idx; + to_linear_idx = dst_ld * (col_idx / 32) + 32 * row_idx + col_idx % 32; + break; + } + case COMBINE(order_t::col32, order_t::col): { + from_linear_idx = src_ld * (col_idx / 32) + 32 * row_idx + col_idx % 32; + to_linear_idx = dst_ld * col_idx + row_idx; + break; + } + case COMBINE(order_t::col, order_t::col4_4r2_8c): { + from_linear_idx = src_ld * col_idx + row_idx; + + size_t from_row_in_row8_col32 = row_idx % 8; + size_t from_col_in_row8_col32 = col_idx % 32; + + size_t to_row_in_row8_col32 = + 4 * (from_row_in_row8_col32 % 2) + from_col_in_row8_col32 / 8; + size_t to_col_in_row8_col32 = 16 * ((from_col_in_row8_col32 / 4) % 2) + + 4 * (from_row_in_row8_col32 / 2) + + from_col_in_row8_col32 % 4; + size_t to_linear_idx_in_row8_col32 = + to_row_in_row8_col32 * 32 + to_col_in_row8_col32; + + to_linear_idx = dst_ld * (col_idx / 32) + (row_idx / 8) * (32 * 8) + + to_linear_idx_in_row8_col32; + break; + } + case COMBINE(order_t::col4_4r2_8c, order_t::col): { + to_linear_idx = dst_ld * col_idx + row_idx; + + size_t to_row_in_row8_col32 = row_idx % 8; + size_t to_col_in_row8_col32 = col_idx % 32; + + size_t from_row_in_row8_col32 = + 4 * (to_row_in_row8_col32 % 2) + to_col_in_row8_col32 / 8; + size_t from_col_in_row8_col32 = 16 * ((to_col_in_row8_col32 / 4) % 2) + + 4 * (to_row_in_row8_col32 / 2) + + to_col_in_row8_col32 % 4; + size_t from_linear_idx_in_row8_col32 = + from_row_in_row8_col32 * 32 + from_col_in_row8_col32; + + from_linear_idx = src_ld * (col_idx / 32) + (row_idx / 8) * (32 * 8) + + from_linear_idx_in_row8_col32; + break; + } + case COMBINE(order_t::col, order_t::col32_2r_4r4): { + from_linear_idx = src_ld * col_idx + row_idx; + + size_t from_row_in_row32_col32 = row_idx % 32; + size_t from_col_in_row32_col32 = col_idx % 32; + + size_t to_row_in_row32_col32 = 8 * ((from_row_in_row32_col32 % 8) / 2) + + (from_row_in_row32_col32 / 8) * 2 + + from_row_in_row32_col32 % 2; + size_t to_col_in_row32_col32 = from_col_in_row32_col32; + size_t to_linear_idx_in_row32_col32 = + to_row_in_row32_col32 * 32 + to_col_in_row32_col32; + + to_linear_idx = dst_ld * (col_idx / 32) + (row_idx / 32) * (32 * 32) + + to_linear_idx_in_row32_col32; + break; + } + case COMBINE(order_t::col32_2r_4r4, order_t::col): { + to_linear_idx = dst_ld * col_idx + row_idx; + + size_t to_row_in_row32_col32 = row_idx % 32; + size_t to_col_in_row32_col32 = col_idx % 32; + + size_t from_row_in_row32_col32 = 8 * ((to_row_in_row32_col32 % 8) / 2) + + (to_row_in_row32_col32 / 8) * 2 + + to_row_in_row32_col32 % 2; + size_t from_col_in_row32_col32 = to_col_in_row32_col32; + size_t from_linear_idx_in_row32_col32 = + from_row_in_row32_col32 * 32 + from_col_in_row32_col32; + + from_linear_idx = src_ld * (col_idx / 32) + (row_idx / 32) * (32 * 32) + + from_linear_idx_in_row32_col32; + break; + } + } +#undef COMBINE + return std::make_tuple(from_linear_idx, to_linear_idx); +} + +template