diff --git a/CMakeLists.txt b/CMakeLists.txt index 8a4db48..912fd49 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1467,13 +1467,16 @@ if(STRATA_NATIVE_EXPERTS) 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 src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp - src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp) + src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp + src/kernels/cpu/tq_cpu.cpp src/kernels/cpu/tq_avx2.cpp src/kernels/cpu/tq_avx512.cpp) target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml) if(MSVC) set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_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") + set_source_files_properties(src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") + set_source_files_properties(src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") set_source_files_properties(src/kernels/cpu/nvfp4_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") @@ -1484,8 +1487,12 @@ if(STRATA_NATIVE_EXPERTS) set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") else() set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp PROPERTIES COMPILE_OPTIONS - "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mavx512vpopcntdq;-mbmi2;-mf16c;-mfma") set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + # the trellis experts' CPU lane (tq_cpu.hpp; the DeepSeek-V4.1 engine's ds4_tq_cpu.cpp), upstream v0.2.4's flags + set_source_files_properties(src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + set_source_files_properties(src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mavx512vpopcntdq;-mbmi2;-mf16c;-mfma") set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx") @@ -2127,6 +2134,88 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S endif() endif() +# ---- strata-dsv41: DeepSeek-V4.1-Flash, from Strata v0.2.4 (UPSTREAM.md "DeepSeek-V4.1 engine") ---------------- +# +# The third engine. Imported from Niko1221/Strata v0.2.4 (src/dsv41, include/strata/dsv41, tests/dsv41, tools/dsv41, +# data/dsv41; itself a port of Project Maya's maya-ds4, MIT, third_party/project-maya/NOTICE.md). Upstream's target +# block as it is, but for: no FetchContent (ggml.h / ggml-cpu.h come through strata_kernels_cpu's ggml-cpu link from the +# submodule), and no STRATA_BUILD_DSV41 default of OFF - the Makefile turns it on, it is one of the engines this fork +# builds. The vendored kernels live in strata::dsv41k, so no symbol is shared with strata_kernels. +option(STRATA_BUILD_DSV41 "Build the DeepSeek-V4.1 engine path (strata-dsv41)" OFF) +if(STRATA_BUILD_DSV41 AND STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT STRATA_HIP_GFX906) + add_library(strata_dsv41_kernels STATIC src/dsv41/vendor/exl3.cu src/dsv41/vendor/sampler.cu src/dsv41/vendor/moe_win.cu + src/dsv41/vendor/exl3_cpu.cpp) + if(NOT STRATA_ENABLE_HIP) # (the pre-sm_80 NVIDIA decode kernels exl3.cu dispatches to) + target_sources(strata_dsv41_kernels PRIVATE src/dsv41/vendor/exl3_legacy.cu) + endif() + target_include_directories(strata_dsv41_kernels PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(strata_dsv41_kernels PUBLIC ${_strata_gpu_runtime_target}) + add_executable(strata-dsv41 src/dsv41/ds4_main.cpp src/dsv41/ds4_model.cu src/dsv41/ds4_kernels.cu src/dsv41/ds4_vision.cu + src/dsv41/ds4_gguf.cu src/dsv41/ds4_gguf_cpu.cpp src/dsv41/ds4_iq.cu src/dsv41/ds4_iq_cpu.cpp + src/dsv41/ds4_tq.cu src/dsv41/ds4_tq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp src/dsv41/ds4_packinfo.cpp) + # the commit the binary was built from, readable with --version (set -DSTRATA_BUILD_ID=... for a tree without .git) + if(NOT STRATA_BUILD_ID AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/BUILD_ID) # (a git archive has no .git: the packer writes the commit here) + file(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/BUILD_ID STRATA_BUILD_ID LIMIT_COUNT 1) + endif() + if(NOT STRATA_BUILD_ID) + execute_process(COMMAND git -C ${CMAKE_CURRENT_SOURCE_DIR} rev-parse --short=9 HEAD OUTPUT_VARIABLE STRATA_BUILD_ID + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + endif() + if(NOT STRATA_BUILD_ID) + set(STRATA_BUILD_ID unknown) + endif() + set_source_files_properties(src/dsv41/ds4_main.cpp PROPERTIES COMPILE_DEFINITIONS "DS4_BUILD_ID=\"${STRATA_BUILD_ID}\"") + target_include_directories(strata-dsv41 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) + target_link_libraries(strata-dsv41 PRIVATE strata_dsv41_kernels ${_strata_gpu_runtime_target} ${_strata_gpu_blas_target}) + find_package(Threads REQUIRED) + target_link_libraries(strata-dsv41 PRIVATE Threads::Threads) + if(WIN32 AND STRATA_ENABLE_HIP) + target_link_libraries(strata-dsv41 PRIVATE strata_core) + endif() + # Strata's CPU kernels: the ggml-cpu lane for the GGUF i-quant experts (ds4_gg_cpu.cpp: iq256x_rows / iq512x_rows) and the + # trellis lane (tq_cpu.hpp) - the lane the IST-DAS sets' experts beyond VRAM are computed on + target_link_libraries(strata-dsv41 PRIVATE strata_kernels_cpu) + target_compile_definitions(strata-dsv41 PRIVATE STRATA_DSV41_TQ_CPU=1) + # the CPU lane's ggml-type rows: ggml-cpu's dots against Strata's AVX2 i-quant rows (bits and GB/s); no GPU, no model + add_executable(ds4_gg_bench tests/dsv41/gg_dot_bench.cpp src/dsv41/ds4_gg_cpu.cpp) + target_include_directories(ds4_gg_bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41 + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) + target_link_libraries(ds4_gg_bench PRIVATE strata_kernels_cpu Threads::Threads) + target_compile_definitions(ds4_gg_bench PRIVATE STRATA_DSV41_TQ_CPU=1) + # the trellis experts (device kernels ds4_tq.cu, CPU lane ds4_tq_cpu.cpp) against a double reference; needs a GPU, no model + if(STRATA_ENABLE_HIP) + set(_ds4_test_lang HIP) + else() + set(_ds4_test_lang CUDA) + endif() + set_source_files_properties(tests/dsv41/tq_expert_test.cpp PROPERTIES LANGUAGE ${_ds4_test_lang}) + add_executable(ds4_tq_test tests/dsv41/tq_expert_test.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_iq.cu src/dsv41/ds4_tq_cpu.cpp + src/dsv41/ds4_iq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp tools/trellis/tqenc.cpp) + target_include_directories(ds4_tq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) + target_link_libraries(ds4_tq_test PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) + target_compile_definitions(ds4_tq_test PRIVATE STRATA_DSV41_TQ_CPU=1) + # the i-quant experts (ds4_iq.cu) against ggml's own decode of the same blocks + a double reference, device and CPU + # lane, for every type the device takes: the gate a new type has to pass before the engine uses it + set_source_files_properties(tests/dsv41/iq_expert_test.cpp PROPERTIES LANGUAGE ${_ds4_test_lang}) + add_executable(ds4_iq_test tests/dsv41/iq_expert_test.cpp src/dsv41/ds4_iq.cu src/dsv41/ds4_iq_cpu.cpp + src/dsv41/ds4_gg_cpu.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_tq_cpu.cpp) + target_include_directories(ds4_iq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) + target_link_libraries(ds4_iq_test PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) + target_compile_definitions(ds4_iq_test PRIVATE STRATA_DSV41_TQ_CPU=1) + # the kept conversations' .meta file and prefix matching (ds4_slotmeta.hpp): no GPU, no model + add_executable(ds4_slot_test tests/dsv41/slot_test.cpp) + target_include_directories(ds4_slot_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_slot_test PRIVATE cxx_std_17) + if(STRATA_ENABLE_HIP) + foreach(_t strata_dsv41_kernels strata-dsv41 ds4_tq_test ds4_iq_test) + target_compile_options(${_t} PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endforeach() + endif() +endif() + # ---- UnbiasedStrata: llama.cpp's libraries for the C++ front end (frontend/) ------------------------------------ # The front end takes its tokenizer (llama), its Jinja chat templates, chat-format parsers and HTTP library (common, # cpp-httplib) and its image encoder (mtmd) from the same pinned checkout that ggml comes from. ggml is configured diff --git a/Makefile b/Makefile index debed9a..87320c7 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ # # git clone && cd # git submodule update --init -# make build # build/bin/{strata,strata-poly,libstrata_kq.so,unbiased-strata} +# make build # build/bin/{strata,strata-poly,strata-dsv41,libstrata_kq.so,unbiased-strata} # make test # the front end against a fake engine; no GPU needed # BUILD_DIR ?= build @@ -46,7 +46,7 @@ COMPILER_FLAGS := $(if $(HOSTCXX),-DCMAKE_C_COMPILER=$(HOSTCC) -DCMAKE_CXX_COMPI # capped: inside a container nproc reports the host's CPUs, not the container's quota JOBS ?= $(shell n=$$(nproc 2>/dev/null || echo 4); [ $$n -gt 16 ] && n=16; echo $$n) # what `make build` produces; upstream's `all` also builds about 70 parity and bench programs -TARGETS := strata strata-poly strata_kq unbiased-strata +TARGETS := strata strata-poly strata-dsv41 strata_kq unbiased-strata .PHONY: build configure clean test @@ -54,14 +54,14 @@ configure: @test -f third_party/llama.cpp/ggml/CMakeLists.txt || \ { echo "third_party/llama.cpp is empty: run 'git submodule update --init' first"; exit 1; } cmake -S . -B $(BUILD_DIR) -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON \ - -DSTRATA_MMQ_KQUANTS=ON -DSTRATA_Q6K_EXPERTS=ON -DSTRATA_BUILD_TESTS=OFF \ + -DSTRATA_MMQ_KQUANTS=ON -DSTRATA_Q6K_EXPERTS=ON -DSTRATA_BUILD_DSV41=ON -DSTRATA_BUILD_TESTS=OFF \ "-DCMAKE_CUDA_ARCHITECTURES=$(CUDA_ARCHS)" $(SM60_FLAG) $(PORTABLE_FLAG) $(COMPILER_FLAGS) -DCMAKE_CUDA_COMPILER=$(NVCC) \ -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$(abspath $(BUILD_DIR))/bin \ -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=$(abspath $(BUILD_DIR))/bin $(CMAKE_EXTRA) build: configure cmake --build $(BUILD_DIR) -j $(JOBS) --target $(TARGETS) - @echo "built:"; ls -1 $(BUILD_DIR)/bin/strata $(BUILD_DIR)/bin/strata-poly $(BUILD_DIR)/bin/libstrata_kq.so $(BUILD_DIR)/bin/unbiased-strata + @echo "built:"; ls -1 $(BUILD_DIR)/bin/strata $(BUILD_DIR)/bin/strata-poly $(BUILD_DIR)/bin/strata-dsv41 $(BUILD_DIR)/bin/libstrata_kq.so $(BUILD_DIR)/bin/unbiased-strata # The front end alone, without CUDA: for a laptop or a CI box. Needs only a C++20 compiler and CMake. .PHONY: frontend diff --git a/data/dsv41/profile-2.00.bin b/data/dsv41/profile-2.00.bin new file mode 100644 index 0000000..99f1869 Binary files /dev/null and b/data/dsv41/profile-2.00.bin differ diff --git a/data/dsv41/profile-2.00.bin.sha256 b/data/dsv41/profile-2.00.bin.sha256 new file mode 100644 index 0000000..8e68c32 --- /dev/null +++ b/data/dsv41/profile-2.00.bin.sha256 @@ -0,0 +1 @@ +8db93e483b34b15dbf63a0826601f1db2107a8cfea73774e7d21d8559e0a9568 *profile-2.00.bin diff --git a/data/dsv41/profile-2.25.bin b/data/dsv41/profile-2.25.bin new file mode 100644 index 0000000..5270c6c Binary files /dev/null and b/data/dsv41/profile-2.25.bin differ diff --git a/data/dsv41/profile-2.25.bin.sha256 b/data/dsv41/profile-2.25.bin.sha256 new file mode 100644 index 0000000..237f57b --- /dev/null +++ b/data/dsv41/profile-2.25.bin.sha256 @@ -0,0 +1 @@ +c8de062c5f3c71725ecf5328bd4ee02c71dca88478bf7f6b0f2ec258567ac6b6 *profile-2.25.bin diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md new file mode 100644 index 0000000..e3ad46c --- /dev/null +++ b/docs/DEEPSEEK41.md @@ -0,0 +1,142 @@ +# DeepSeek-V4.1-Flash + +DeepSeek-V4.1-Flash is a large mixture-of-experts model: 40 layers, 384 experts in each (6 are used for every word), and a 203 GB +n-gram table next to them. Strata runs it with its own engine, `strata-dsv41` (`src/dsv41`, ported from Project Maya's +`maya-ds4`, MIT; the notice is in `third_party/project-maya`). The file is Unsloth's UD-Q8_K_XL, pinned in `setup.py`: nine +shards, 508.4 GB, the experts as MXFP4 and the rest in BF16. The two official 2-bit sets (below) are what a normal PC runs. + +The 508 GB set is for a computer with several graphics cards and a lot of RAM. It was run on four Radeon AI PRO R9700 (32 GB each) with +251 GB of RAM. Strata does not refuse a smaller computer; it tells you what to expect first. + +## Where it goes + +| | size | where | +|---|---|---| +| routed experts (15,360 of 18.8 MB) | 288.8 GB | as many as fit in graphics memory; the rest are computed on the CPU, read in place from the model files | +| attention and other dense weights | 16.8 GB | graphics memory, one block of layers on each card (about 3.9 GB a card on four) | +| n-gram table (Engram) | 202.8 GB | the SSD. A few rows are read for each word it writes. It is not counted in RAM, but a slow disk slows every word, so keep the model files on an NVMe drive | + +Measured on the four R9700 cards: 6,197 experts (116.5 GB) in graphics memory, 9,163 (172.3 GB) on the CPU, which needs about that +much free RAM to stay cached. `strata launch --plan` and `setup.py --check` work this out for your cards and RAM +(`strata_control/dsv41_fit.py`; it predicted 6,240 experts on the R9700 box). + +With less memory than that, part of the CPU's experts are read from the SSD while the model answers. It runs, slowly. A card +that cannot hold its share of the dense weights (about 4 GB each on four cards, 16 GB on one) can make the engine stop at the start +with an out-of-memory message. Both are said before anything is downloaded. + +## The official 2-bit versions (the ones for a normal PC) + +Setup offers three official sets (ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF, pinned): **IQ1_M, 1.75 bpw** (`ist-das-1.75bpw`, 121 GB, slightly lower quality; setup recommends it where 2.00 is tight in memory or disk), **IQ2_XXS, 2.00 bpw** (138 GB) and **IQ2_XS, 2.25 bpw** (155 GB). All use the +same 111 GB n-gram table (downloaded once into `models/deepseek-v4.1-flash-shared`) and the 8 GB DSpark drafter: 257 GB of disk for +2.00, 274 GB for 2.25, 239 GB for 1.75, 533 GB for all three. Quality against the original model (4,995 positions, the final files): 2.00 has KL 0.170 and perplexity +15.5% (code +8.6%, agent work +5.3%); 2.25 has KL 0.107 and +perplexity +7.3% (code +3.2%, agent work +2.2%). IQ1_M: perplexity +21% (KL 0.217, top-1 82.5%); code +8.9%, agent work +10.2%, multilingual +14%, docs +24%, plain English prose +53%, so it is weaker on prose. ISTA-DASLab's model card says it keeps 98.7% of the base model's task average (AIME25, GPQA-Diamond, LiveCodeBench v6). + +| File | Size | What it is | +| --- | ---: | --- | +| IQ1_M shards (1.75 bpw), 4 files | 121 GB | the model, smallest set | +| IQ2_XXS shards (2.00 bpw), 4 files | 138 GB | the model, middle set | +| IQ2_XS shards (2.25 bpw), 4 files | 155 GB | the model, largest set | +| IQ4_NL: `DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf` | 111 GB | the 4-bit Engram lookup table the model reads from RAM or SSD. Not a model to pick: all three sets use this one file, and it is already in their download sizes | +| DSpark drafter (Q8_0) | 8 GB | the small draft model (Unsloth) | + +121 + 111 + 8 = 239 GB for 1.75; 138 + 111 + 8 = 257 GB for 2.00; 155 + 111 + 8 = 274 GB for 2.25. + +Measured: an RTX 5070 (12 GB) with 64 GB of RAM and a 3.6 GB/s NVMe drive answers at about 4.7 tokens/s and reads prompts at 121 +tokens/s (4K) to 231 tokens/s (8K, layer-major path); an RTX 3060 (12 GB) with 46 GB of RAM about 7.2 tokens/s; four R9700 about 31 +tokens/s. Under about 40 GB of RAM it is untested and slow; setup says so and still installs. + +Setup downloads with resume and SHA-256, packs the model with the plain recipe (`pack_gguf.py --model SET --shards ... --engram +engram-IQ4_NL.gguf --engram-meta --dspark-gguf dspark-...-Q8_0.gguf`; do not add `--skip-tensors` or `--dense-override`: +that packs without an error and gives garbage text), copies the shipped hot-expert profile (`data/dsv41/profile-2.00.bin` or `-2.25.bin`) +into the pack as `expert-profile.bin`, checks `strata-dsv41 --pack-info` (every file present) and answers a 16-token test question +(`tools/dsv41/smoke.py`, the text must name Paris). The start script passes `--dspark auto` (never `off`: `off` still loads the drafter +and its 7 GB of experts take the graphics memory); the RAM store sizes itself. Long prompts use the engine's fast chunked path on its own (no flag is written: the engine picks the chunk size for your cards). + +## Install + +``` +./setup.sh --family deepseek41 --model IST-DAS-2.00bpw # 257 GB: the official 2.00 set + Engram + drafter (resumable, SHA-256 checked) +./setup.sh --family deepseek41 --model IST-DAS-2.25bpw # 274 GB (the Engram is shared with 2.00) +./setup.sh --family deepseek41 --model IST-DAS-1.75bpw # 239 GB, the smallest +./setup.sh --family deepseek41 --model UD-Q8_K_XL # Unsloth's 508 GB set, for hundreds of GB of RAM or several cards +./setup.sh --family deepseek41 --gguf-dir DIR # files you already have: the shards (or the folder with 2.00bpw / 2.25bpw / UD-Q8_K_XL inside); the Engram and drafter are looked for beside them +strata launch --model ist-das-2.00bpw --plan # where it would go on this computer, nothing changed +strata launch --model-path DIR --model ist-das-2.00bpw # start from files you already have +``` + +Setup needs `strata-dsv41` next to the engine (or `STRATA_DSV41_EXE`) and says so before it downloads anything. Build it with +`cmake -DSTRATA_BUILD_DSV41=ON`. The default context is 8192 tokens, the size it was checked at; `--context` asks for more. +Loading takes a few minutes (the config sets `"engine_ready_s": 3600`). + +## Through the API + +The server speaks to the engine as it does for the other models, so `/v1/chat/completions`, `/v1/messages`, streaming, stop and +`/metrics` work as usual (the answer speed is the tokens the model produced over the engine's decode time). + +- Thinking is on by default, as the model's template has it. `reasoning_effort: "none"` or `chat_template_kwargs.enable_thinking: false` turns it off. + Effort words: `low` (50), `medium` (62), `high` (75, the default), `max` (100), or a whole number 1 to 100. +- Prompts are the GGUF's own chat template, the same bytes as DeepSeek's `encoding.py` on the cases checked. Project Maya's own template lost the + tool associations and later system instructions (their issue #299); Strata does not use it. +- Tool calls: the model writes DSML (`<|DSML| calls>` ... `<|DSML| invoke name="...">` ... `<|DSML| parameter name="..." string="true">`). The + server turns them into OpenAI `tool_calls` and Anthropic `tool_use`, including `tool_choice`, streamed arguments and calls written inside the thinking. + A value marked `string="true"` stays a string. +- Defaults when a request names none: temperature 1.0, top_p 1.0. +- Agents and sub-agents that take turns can skip reading their prompts again (off in this version, a switch for testing). With + `STRATA_DS4_SLOT_KEEP=1` the engine sets a conversation aside when another request takes the model (about 17 MB per 6.5K tokens) and takes it + back when the next prompt continues it, also after a restart. Slots live in `ds4-slots` next to the run log, are capped at 2 GB + (`STRATA_DS4_SLOT_GB`) and are removed after a week. `STRATA_DS4_AUTO_PIN=1` also keeps the system prompt and tools shared by an agent + and its sub-agents as a checkpoint. + +Not in this version: several requests at once (`--parallel` is ignored with a warning) and pictures (`--vision` is ignored with a warning). + +## Tuning + +`strata launch --tune quick` (or `thorough`, or the Tuning screen) works for DeepSeek with its own short tuner, `tools/dsv41/tune.py`. It starts +the engine a few times on a fixed short question and measures the answer speed: the standard settings first, then the DSpark drafter forced on, +then a shorter draft block (3), then one CPU thread for each physical core (thorough also tries every logical thread). A setting is kept only for a +gain of more than 5%, and the result is written into the launch's settings. Expect about 5 to 10 minutes (each run loads the model, which takes +1 to 3 minutes); close other heavy programs first. If a run fails or the computer is too busy to tell, the standard settings stay and one plain line +says so. The RAM store (`--ssd-cache`) sizes itself when the model starts, so the tuner does not touch it, and the context stays what you chose. + +## The engine package + +DeepSeek's engine, `strata-dsv41`, is a separate download from the Strata engine: when you choose DeepSeek, setup (or `strata launch`) fetches the +package for your computer from the signed update feed (resumable, signature and every file checked) and installs it in `engine-dsv41/` beside +`engine/`. The Qwen engine's files are never changed. If the feed has no package for your graphics card, setup says so in plain words and stops before +anything big is downloaded. + +### Getting the engine by hand + +If the automatic download does not work for you (no access to the update feed, or an offline computer), download the engine package yourself from +the release page: the file is named `strata-dsv41----.tar.gz` (Windows and Linux; pick the one for your system and +graphics card). Check it against `SHA256SUMS.txt` on the release page if you like. Then give it to Strata in either of two ways: + +``` +strata launch --model ist-das-2.00bpw --dsv41-package PATH-TO-THE-FILE +python setup.py --family deepseek41 --dsv41-package PATH-TO-THE-FILE +``` + +or put the file in the `engine-dsv41/` folder (setup tells you its exact place when it cannot find the engine) and run the same command again. +Strata checks the package before it uses it: it must be the DeepSeek engine (not the Strata engine) for your system, its manifest must be signed by a key +Strata trusts, and every file must match the hash in the manifest. A damaged or foreign file is refused with a plain line and nothing is installed. +The unpacked folder works as well as the archive. The Strata (Qwen) engine is not touched either way. + +## Compressed experts (trellis), for testing + +`strata-dsv41` reads the routed experts in the trellis types as well as the source MXFP4: TQK6 and TQK7 (agentionai's files), and the +experimental TQK5X / TQK4X (computed codebook) and TQK5T / TQK4T (table codebook), see `tools/trellis/README.md`. A layer may be converted +while the others stay MXFP4. On the GPU they run on the tensor cores of gfx12 (and in plain FMAs elsewhere), on the CPU lane on Strata's +AVX-512 / AVX2 kernels; the build needs `-DSTRATA_NATIVE_EXPERTS=ON` for the CPU lane. + +``` +# 1. the pack of the source model (also takes the DSpark and mmproj files that sit beside the model folder) +python tools/dsv41/pack_gguf.py --model DIR/UD-Q8_K_XL --out PACK +# 2. re-encode some layers (HIP encoder; one layer at K5 is 2.3 GB, the whole model 93 GB) +python tools/dsv41/tq_convert.py --pack PACK --out CONV --layers 1,7,14 --type K5 # K4 K5 K4T K5T K6 K7 +# 3. the pack that reads them +python tools/dsv41/pack_gguf.py --model DIR/UD-Q8_K_XL --out PACK2 --tq-experts CONV +strata-dsv41 --pack PACK2 --score data/quant_quality/v1/set.ids.json --score-out RUN.tsv # teacher-forced top-64 rows +``` + +The encode is plain error (no rotation, no activation weights). The tests are `ds4_tq_test` (device and CPU lane against a double +reference, needs one GPU) and `tqw_hip_test`. diff --git a/include/strata/dsv41/exl3.hpp b/include/strata/dsv41/exl3.hpp new file mode 100644 index 0000000..b080a59 --- /dev/null +++ b/include/strata/dsv41/exl3.hpp @@ -0,0 +1,187 @@ +// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). +// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. +// include/strata/kernels/exl3.hpp - EXL3 (exllamav3) quantized weights on the device: the decode GEMV, the routed +// experts, and the full reconstruction for the prompt path. +// +// The format (exllamav3, MIT, turboderp). A weight with k inputs and n outputs (y = x W) is stored as +// trellis int16 [k/16][n/16][16 K]: each 16x16 tile is a tail-biting trellis of 256 K-bit steps read MSB-first +// from its 8 K uint32 words (little-endian pairs of the int16s). Step p's state is the 16-bit window that +// ends at bit (p + 1) K, modulo the tile's 256 K bits; the codebook turns the state into a value: +// mul1 (cb 2): fp16(1024 + bytesum(state * 0x83DCD12D)) * fp16(0x1eee) + fp16(0xc931), one FP16 FMA +// mcg (cb 1): x = state * 0xCBAC1FED, 3inst (cb 0): x = state * 89226354 + 64248484; then +// x = (x & 0x8fff8fff) ^ 0x3b603b60 and the value is the FP16 sum of x's two halves. +// Step p sits at tile row (p/8 % 4) * 2 + (p & 1) + 8 (p/2 & 1), column p/32 + 8 (p/4 & 1) (the tensor- +// core fragment order). +// suh, svh FP16 [k], [n]: the input and output channel scales (signs and magnitudes). +// With H the 128-point Sylvester Hadamard over sqrt(128), applied to each 128 consecutive values: +// y = H(H(x * suh) W') * svh, W' the decoded k x n matrix. +// +// Activations enter as F32 or as the engine's q8_1 blocks; the kernels rotate them on the fly (each block rotates +// the slice it reads), so callers keep their existing buffers. +#pragma once + +#include +#include +#include + +namespace strata::dsv41k::exl3 { + +/// The weight type the engine's MvJob / WSlot carry for EXL3: their weight pointer is a (host) const Mat*. +constexpr int kTypeEXL3 = 200; + +/// One EXL3 matrix, or a column range of one (a view: trellis/svh advanced to its first column, ld the row stride). +struct Mat { + const uint32_t* trellis = nullptr; // device; 4-byte aligned + const uint16_t* suh = nullptr; // device FP16 bits [k] + const uint16_t* svh = nullptr; // device FP16 bits [n] + int k = 0, n = 0; + int K = 0; // bits per weight, 1..8 + int cb = 2; // codebook: 0 3inst, 1 mcg, 2 mul1 + int ld = 0; // tiles per 16-row slice in memory (the full matrix's n / 16); 0: n / 16 + // a GGUF's plain matrix instead (DeepSeek-V4.1's maya-ds4: fmt 1 BF16): raw = [n][ld] (row r = output r, ld + // values a row; 0: k), the EXL3 fields unused - the engine sends it to its own kernels, never to these + int fmt = 0; + const void* raw = nullptr; +}; + +/// Trellis bytes of a k x n matrix at K bits. +inline size_t trellis_bytes(int64_t k, int64_t n, int K) { return (size_t) (k / 16) * (size_t) (n / 16) * 32u * K; } +/// The columns [c0, c0 + nc) of m (c0 and nc multiples of 128: the output rotation's blocks stay whole). +Mat view(const Mat& m, int c0, int nc); +/// Whether the kernels take this matrix (k, n multiples of 128, K 1..8, cb 0..2). +bool supported(const Mat& m); + +/// y[r] = alpha * (x W)[r] + (bias ? bias[r] : 0). x: xf (F32) when given, else xq (q8_1 blocks of k values). +/// ncol > 1: as many activations (a verify window's tokens), activation c at xf + c xf_cs / xq + c xq_cs bytes, its +/// y at y + c y_cs - the weights read and decoded once for up to 8 of them, and each y bit for bit its own job's. +struct MvJob { + const Mat* m = nullptr; + const float* xf = nullptr; + const void* xq = nullptr; + float* y = nullptr; + const float* bias = nullptr; + float alpha = 1.0f; + int ncol = 1; + size_t xf_cs = 0, xq_cs = 0, y_cs = 0; +}; +constexpr int kMaxMvJobs = 8; +constexpr int kMaxMvCols = 16; // a job's activations at most +bool mv(const MvJob* jobs, int n, cudaStream_t s); +/// The calling thread's launches of mv(), moe_gate_up() and moe_down() read `flag` (a device int) first and do no work +/// while it is non-zero (glmf::set_skip's, which sets it: a pipelined window's tokens past a wrong draft); nullptr (the +/// default): no check. The flag changes only between launches (skip_gate, on the same stream). (v1.1.8's kernels +/// before sm_80 do not read it.) +void set_skip(const int* flag); +/// How many pieces mv cuts m's inputs into on the current device (0: not covered) - one piece, and every column's +/// sum is the same whatever columns the job holds (a view's, or the whole matrix's). +int mv_splits(const Mat& m); +/// How many activations a lone job of m can take with its weights read once on the current device (the input split's +/// partials of them in the scratch; 0: not covered) - a caller with more cuts them in runs of this many. +int mv_cols(const Mat& m); + +/// Allocates the per-stream scratch of mv / moe / win_experts on the current device (call once per stream before a +/// graph capture; the first use does it otherwise). +bool prepare(cudaStream_t s); + +/// One routed expert's blob: three parts (gate, up, down) at byte offsets from the blob base, each holding the FP16 +/// suh, the FP16 svh and the trellis of that matrix. +struct ExpertLayout { + size_t suh[3] = {0, 0, 0}, svh[3] = {0, 0, 0}, trellis[3] = {0, 0, 0}; + int K[3] = {0, 0, 0}; + int cb = 2; + int fmt = 0; // 2: a GGUF's MXFP4 expert (maya-ds4's own kernels): trellis[r] = matrix r's offset, [out][in / 32] +}; +/// The routed experts of one token (the engine's device plan: plan_ptr[i] = the blob in VRAM, 0 = not on the device; +/// plan_w[i] its weight). gate/up over x (n_embd F32) -> clamped swiglu -> h (F32 [k][n_ff], scratch the caller +/// owns), then down over h, the weighted sum in plan order, + cpu_part when *cpu_flag, + sh_out when given -> out. +struct MoeArgs { + const unsigned long long* plan_ptr = nullptr; + const float* plan_w = nullptr; + const float* cpu_part = nullptr; + const int* cpu_flag = nullptr; + ExpertLayout lay; + int k = 8, n_embd = 4096, n_ff = 2048; + float limit = 0.0f; // 0: no clamp +}; +void moe_gate_up(const MoeArgs& a, const float* x, float* h, cudaStream_t s); +void moe_down(const MoeArgs& a, const float* h, const float* sh_out, float* out, cudaStream_t s); + +/// A verify window's routed experts, each distinct expert read once for all the tokens it serves (after exllamav3's +/// fused MoE, which runs the slots that picked one expert as the rows of one tile): T tokens' plans [T][8] grouped by +/// expert (glmf::moe_win_group: group g's blob at grp_ptr[g], its entries e = t * 8 + i at grp_ent[grp_start[g] .. +/// grp_start[g + 1])), token t's F32 input at x + t x_stride, its output at out + t out_stride (plus the CPU lane's +/// part when cpu_flag[t], plus sh_out's row t) - every token's output is moe_gate_up + moe_down's for it alone, bit for +/// bit. h [T * 8][n_ff] and part [T * 8][n_embd] are the caller's scratch. +struct WinArgs { + const unsigned long long* grp_ptr = nullptr; + const int *grp_start = nullptr, *grp_ent = nullptr, *n_groups = nullptr; + const unsigned long long* plan_ptr = nullptr; // [T][8] + const float* plan_w = nullptr; // [T][8] + const float* cpu_part = nullptr; // [T][n_embd] (rows cpu_stride apart when given) + size_t cpu_stride = 0; + const int* cpu_flag = nullptr; // [T] + const float* x = nullptr; + size_t x_stride = 0; + float* h = nullptr; + float* part = nullptr; + const float* sh_out = nullptr; // [T][n_embd] or null + float* out = nullptr; + size_t out_stride = 0; + ExpertLayout lay; + int T = 0, k = 8, n_embd = 4096, n_ff = 2048; + float limit = 0.0f; + // (given) the combine first waits on the device until *wait_ptr == wait_val (the host's answer to the CPU lane's + // part arrives while the device computes the experts); cpu_flag may be null (no CPU part) + const unsigned* wait_ptr = nullptr; + unsigned wait_val = 0; +}; +bool win_experts(const WinArgs& a, cudaStream_t s); +/// Whether the current device runs the several-activation kernels (win_experts; mv's ncol > 1): every device does +/// (they take ~10 KB of shared memory a block). +bool several_ok(); + +/// The prompt path's tensor-core GEMMs (sm_80 and later; mma_supported() says whether this device runs them). +bool mma_supported(); +/// A set of n_exp routed experts in VRAM, expert e's blob at wbase + e * stride (the layout in lay), owning the sorted +/// rows [bounds[e], bounds[e + 1]) (device, n_exp + 1 entries); a sorted row's LOCAL row is bounds[e] - row0 + r. +struct SetArgs { + const uint8_t* wbase = nullptr; + size_t stride = 0; + ExpertLayout lay; + int n_exp = 0; + const int* bounds = nullptr; + int row0 = 0; + int max_rows = 0; // the most rows one expert of the set has + int n_embd = 4096, n_ff = 2048; + float limit = 0.0f; +}; +/// h[local row] = FP16 clamped swiglu of gate and up over x[row_idx[local row]] (F32 rows, ldx floats apart). +void set_gate_up(const SetArgs& a, const float* x, int ldx, const int* row_idx, uint16_t* h16, int ldh, cudaStream_t s); +/// y[local row] = down(h[local row]) (F32 rows, ldy floats apart). +void set_down(const SetArgs& a, const uint16_t* h16, int ldh, float* y, int ldy, cudaStream_t s); +/// Y[r] = beta Y[r] + (X[r] W) for r < rows: one matrix over FP16 rows (ldx), F32 output rows (ldy). +void gemm_rows(const Mat& m, const uint16_t* x16, int ldx, int rows, float* y, int ldy, float beta, cudaStream_t s); + +/// The full weight in the engine's row layout: dst[r][c] = W[c][r] (n rows of k values), BF16 or F16 bits. +void reconstruct_rows(const Mat& m, uint16_t* dst, bool bf16, cudaStream_t s); +/// The decoded W' alone in that layout: dst[c][r] = W'[r][c], F16 bits (exactly the decoded values) - for a product +/// that rotates its activations and outputs instead of the weight (x W = H(H(x * suh) W') * svh): rows_rot_f16 before +/// the GEMM, rows_rot_out after it. No Hadamard over the k x n weight: a plain decode, at the memory's speed. +void reconstruct_inner_rows(const Mat& m, uint16_t* dst, cudaStream_t s); +/// out[r][c] = FP16(H(x_r * suh)[c]) for r < nrows, c < ncols (ncols % 128 == 0), x_r = x[idx ? idx[r] : r] (F32, ldx +/// floats a row): an EXL3 matrix's rotated input rows, as the decode kernels rotate theirs. +void rows_rot_f16(const float* x, int ldx, const int* idx, int nrows, int ncols, const uint16_t* suh, uint16_t* out, + cudaStream_t s); +/// y[r][c] = H(y_r)[c] * svh[c] in place for r < nrows, c < ncols (each 128 values one block; ldy floats a row). +void rows_rot_out(float* y, int ldy, int nrows, int ncols, const uint16_t* svh, cudaStream_t s); +/// The decoded W' alone, row-major [k][n] F16 bits (tests). +void reconstruct_inner(const Mat& m, uint16_t* dst, cudaStream_t s); + +/// out[r][c] = FP16(x[idx ? idx[r] : r][c]) for r < nrows, c < ncols (x: ldx floats a row): the prompt path's rows of +/// one expert, gathered for its GEMMs. +void rows_f16(const float* x, int ldx, const int* idx, int nrows, int ncols, uint16_t* out, cudaStream_t s); + +/// Launch failures of this family since the process started (each is also printed). +int launch_errors(); + +} // namespace strata::dsv41k::exl3 diff --git a/include/strata/dsv41/exl3_cpu.hpp b/include/strata/dsv41/exl3_cpu.hpp new file mode 100644 index 0000000..2c81a2b --- /dev/null +++ b/include/strata/dsv41/exl3_cpu.hpp @@ -0,0 +1,69 @@ +// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). +// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. +// include/strata/kernels/cpu/exl3_cpu.hpp - EXL3 routed experts on the CPU (the fast path's CPU lane). +// +// The mul1 codebook is affine in the byte sum of state * 0x83DCD12D: w = fp16(1024 + s) * k_inv + k_bias (one FP16 +// FMA on the device). The CPU keeps the affine form without the FP16 rounding, so a 128-output band is +// y' = k_inv * sum_k xh_k s_kc + (1024 k_inv + k_bias) * sum_k xh_k, xh = H(x * suh) +// and y = H(y') * svh. The byte sums come from AVX-512 (permutes and funnel shifts pull 16 columns' states at once, +// vpmaddubsw / vpmaddwd add the bytes up, an F32 FMA takes the activation), or from AVX2 + FMA the same way 8 columns +// at a time - the same FMAs in the same order, so the two give the same bits; a CPU with neither runs a scalar loop. +// The format: include/strata/kernels/exl3.hpp. +#pragma once + +#include +#include + +namespace strata::dsv41k::cpu { + +/// One EXL3 matrix (mul1 codebook): k inputs, n outputs, K bits (1..8), tiles in exllamav3's natural layout. +struct Exl3Part { + const uint32_t* trellis = nullptr; + const uint16_t* suh = nullptr; // FP16 bits [k] + const uint16_t* svh = nullptr; // FP16 bits [n] + int k = 0, n = 0, K = 0; +}; +/// Whether a vector kernel runs here (AVX-512F/BW or AVX2 + FMA); the scalar one otherwise. +bool exl3_cpu_vector(); +/// The kernel the functions below run here: 2 AVX-512 (F, BW), 1 AVX2 + FMA (+ F16C), 0 scalar. STRATA_FORCE_AVX2=1 +/// keeps an AVX-512 CPU on AVX2 (to compare the two; they give the same bits). +int exl3_cpu_tier(); +/// xh = H(x * suh) (k values, k % 128 == 0); returns the sum of xh. +float exl3_cpu_prepare(const Exl3Part& m, const float* x, float* xh); +/// One 128-value block of that: xh[i] = H(x * suh)[i] for i < 128 (suh: the block's 128 scales); returns its sum. +float exl3_cpu_prepare_block(const uint16_t* suh, const float* x, float* xh); +/// The 128 outputs from column c0 (a multiple of 128) of y = H(x W') * svh, from exl3_cpu_prepare's xh and sum. +void exl3_cpu_band(const Exl3Part& m, const float* xh, float xsum, int c0, float* y); +/// The same in parts: the byte-sum products of the 16-row slices [ks0, ks1) (xh from slice 0) ... +void exl3_cpu_band_acc(const Exl3Part& m, const float* xh, int c0, int ks0, int ks1, float* acc); +/// exl3_cpu_band_acc for n activations of the same matrix at once (xh[i] -> acc[i], each 128 floats): each tile row is +/// decoded once for up to kExl3CpuMaxN of them, and acc[i] is exl3_cpu_band_acc's for xh[i] alone, bit for bit. +constexpr int kExl3CpuMaxN = 8; +void exl3_cpu_band_acc_n(const Exl3Part& m, const float* const* xh, int n, int c0, int ks0, int ks1, + float* const* acc); +/// The byte-sum products of the slices [ks0, ks1) for EVERY column (acc: m.n floats, overwritten) - a split-K piece, +/// whose tile rows lie in memory order where a band's are 1 KB runs a whole tile row apart (from DRAM, ~1.5x the +/// bands' speed). Each column's sums are exl3_cpu_band_acc's over the same slices, bit for bit. +void exl3_cpu_rows_acc(const Exl3Part& m, const float* xh, int ks0, int ks1, float* acc); +/// ... for n activations at once (xh[i] -> acc[i]), each tile row decoded once; acc[i] is the call for xh[i] alone. +void exl3_cpu_rows_acc_n(const Exl3Part& m, const float* const* xh, int n, int ks0, int ks1, float* const* acc); +/// ... over the columns [c0, c1) alone (multiples of 128; acc[i] indexed by column, only those overwritten): a piece cut +/// by columns too, for more jobs than pieces - each column's sums are the whole piece's, bit for bit. +void exl3_cpu_rows_acc_cols_n(const Exl3Part& m, const float* const* xh, int n, int ks0, int ks1, int c0, int c1, + float* const* acc); +/// The byte-sum products of nb bands from c0 (128 nb columns; acc[i]: 128 nb floats) over every input for any n +/// activations, as a GEMM: each 256-input chunk of a band decoded once into F32 in `wc` (exl3_cpu_gemm_scratch() +/// floats, 64-byte aligned, the caller's), then multiplied for all n, the chunk of the activations kept in L2 across +/// the nb bands - for many tokens an expert (the prompt path), where the band kernels decode a tile row again every +/// kExl3CpuMaxN. The same sums as exl3_cpu_band_acc, in its order. +size_t exl3_cpu_gemm_scratch(); +void exl3_cpu_band_gemm(const Exl3Part& m, const float* const* xh, int n, int c0, int nb, float* const* acc, + float* wc); +/// exl3_cpu_band_acc_n on a given tier (0, 1, 2 as exl3_cpu_tier) - tests and benchmarks; false (nothing computed) +/// where this CPU cannot run it. +bool exl3_cpu_band_acc_on(int tier, const Exl3Part& m, const float* const* xh, int n, int c0, int ks0, int ks1, + float* const* acc); +/// ... and, with the parts' acc summed over every slice, the outputs (the codebook's affine form, H, svh). +void exl3_cpu_band_out(const Exl3Part& m, const float* acc, float xsum, int c0, float* y); + +} // namespace strata::dsv41k::cpu diff --git a/include/strata/dsv41/hip_extra.h b/include/strata/dsv41/hip_extra.h new file mode 100644 index 0000000..bb9d911 --- /dev/null +++ b/include/strata/dsv41/hip_extra.h @@ -0,0 +1,50 @@ +// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). +// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. +// include/strata/dsv41/hip_extra.h - CUDA runtime names the DeepSeek-V4.1 engine path uses that Strata's HIP shim +// (include/strata/hip_compat) does not map. Force-included into the dsv41 targets only, so no other target changes. +// The mappings are Project Maya's include/strata/hip_compat (MIT, third_party/project-maya/NOTICE.md). +#pragma once +#include +#include +#ifndef __grid_constant__ +#define __grid_constant__ +#endif +#ifndef cudaDevAttrMemoryClockRate +#define cudaDevAttrMemoryClockRate hipDeviceAttributeMemoryClockRate +#endif +#ifndef cudaDevAttrGlobalMemoryBusWidth +#define cudaDevAttrGlobalMemoryBusWidth hipDeviceAttributeMemoryBusWidth +#endif +#ifndef cudaDevAttrCanUseHostPointerForRegisteredMem +#define cudaDevAttrCanUseHostPointerForRegisteredMem hipDeviceAttributeCanUseHostPointerForRegisteredMem +#endif +#ifndef cudaDeviceGetPCIBusId +#define cudaDeviceGetPCIBusId hipDeviceGetPCIBusId +#endif +#ifndef cudaDeviceGetStreamPriorityRange +#define cudaDeviceGetStreamPriorityRange hipDeviceGetStreamPriorityRange +#endif +#ifndef cudaOccupancyMaxActiveBlocksPerMultiprocessor +#define cudaOccupancyMaxActiveBlocksPerMultiprocessor hipOccupancyMaxActiveBlocksPerMultiprocessor +#endif +#ifndef cudaErrorUnknown +#define cudaErrorUnknown hipErrorUnknown +#endif +#ifndef cudaErrorInvalidConfiguration +#define cudaErrorInvalidConfiguration hipErrorInvalidConfiguration +#endif +#ifndef cudaMemcpy2D +#define cudaMemcpy2D hipMemcpy2D +#endif +#ifndef cudaStreamCreateWithPriority +#define cudaStreamCreateWithPriority hipStreamCreateWithPriority +#endif +#ifndef cudaStreamLegacy +#define cudaStreamLegacy hipStreamLegacy +#endif +#ifndef CUBLAS_GEMM_DEFAULT_TENSOR_OP +#define CUBLAS_GEMM_DEFAULT_TENSOR_OP HIPBLAS_GEMM_DEFAULT +#endif +#ifndef cudaDataType +#define cudaDataType hipDataType +#endif diff --git a/include/strata/dsv41/hip_or_cuda.h b/include/strata/dsv41/hip_or_cuda.h new file mode 100644 index 0000000..fb5630d --- /dev/null +++ b/include/strata/dsv41/hip_or_cuda.h @@ -0,0 +1,45 @@ +// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). +// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. +// include/strata/dsv41/hip_or_cuda.h - the runtime the dsv41 *tests* need, whichever backend the build has. +// +// The engine's own sources take their runtime from the backend's headers (ds4_*.cu compile as HIP or as CUDA). The tests +// are plain .cpp files that launch kernels and copy buffers, and they used to include unconditionally, +// which no CUDA toolkit ships: every CUDA box had to pass a shim on -I to build them (found on l620 and z440, 2026-10-23). +// This header is that shim, in the tree: HIP names on a HIP build, mapped onto the CUDA runtime otherwise. +// +// Two details that a first version got wrong (z440, 2026-10-23): HIP's hipMalloc is a *template* taking T**, so a plain +// void** overload does not bind `hipMalloc(&uint8_ptr)`; and hipMemset has no CUDA counterpart under that name. +#pragma once + +#if defined(__HIP_PLATFORM_AMD__) || defined(__HIPCC__) +#include +#else +#include + +using hipError_t = cudaError_t; +using hipEvent_t = cudaEvent_t; +using hipStream_t = cudaStream_t; +constexpr hipError_t hipSuccess = cudaSuccess; +constexpr int hipMemcpyHostToDevice = cudaMemcpyHostToDevice; +constexpr int hipMemcpyDeviceToHost = cudaMemcpyDeviceToHost; + +inline hipError_t hipMalloc(void** p, size_t n) { return cudaMalloc(p, n); } +template +inline hipError_t hipMalloc(T** p, size_t n) { return cudaMalloc(reinterpret_cast(p), n); } +inline hipError_t hipFree(void* p) { return cudaFree(p); } +inline hipError_t hipMemcpy(void* dst, const void* src, size_t n, int kind) { + return cudaMemcpy(dst, src, n, static_cast(kind)); +} +template +inline hipError_t hipMemcpy(T* dst, const T* src, size_t n, int kind) { + return cudaMemcpy(static_cast(dst), static_cast(src), n, static_cast(kind)); +} +inline hipError_t hipMemset(void* p, int v, size_t n) { return cudaMemset(p, v, n); } +inline hipError_t hipDeviceSynchronize() { return cudaDeviceSynchronize(); } +inline hipError_t hipSetDevice(int d) { return cudaSetDevice(d); } +inline const char* hipGetErrorString(hipError_t e) { return cudaGetErrorString(e); } +inline hipError_t hipEventCreate(hipEvent_t* e) { return cudaEventCreate(e); } +inline hipError_t hipEventRecord(hipEvent_t e, hipStream_t s = nullptr) { return cudaEventRecord(e, s); } +inline hipError_t hipEventSynchronize(hipEvent_t e) { return cudaEventSynchronize(e); } +inline hipError_t hipEventElapsedTime(float* ms, hipEvent_t a, hipEvent_t b) { return cudaEventElapsedTime(ms, a, b); } +#endif diff --git a/include/strata/dsv41/moe_win.hpp b/include/strata/dsv41/moe_win.hpp new file mode 100644 index 0000000..41da8db --- /dev/null +++ b/include/strata/dsv41/moe_win.hpp @@ -0,0 +1,33 @@ +// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). +// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. +// include/strata/dsv41/moe_win.hpp - a verify window's MoE entries grouped by expert (the grouping alone). +// Extracted from Project Maya's include/strata/kernels/glm_fast.hpp (MIT, see third_party/project-maya/NOTICE.md). +#pragma once +#include +#include + +namespace strata::dsv41k::glmf { +constexpr int kMaxMvCols = 16; +struct MoeWin { + const unsigned long long* plan_ptr = nullptr; // [T][8] the tokens' plans (0: an entry the GPU does not compute) + const float* plan_w = nullptr; // [T][8] + const float* cpu_part = nullptr; // [T][n_embd] the host's answers to disk misses, when flagged + const int* cpu_flag = nullptr; // [T] + const void* xq = nullptr; // the tokens' FFN inputs (q8_1), xq_stride bytes apart + size_t xq_stride = 0; + void* hq = nullptr; // scratch: [T * 8][n_ff / 32] q8_1 + float* part = nullptr; // scratch: [T * 8][n_embd] + const float* sh_out = nullptr; // [T][n_embd] the shared expert's down rows, or null + float* out = nullptr; // [T][n_embd], out_stride floats apart + size_t out_stride = 0; + unsigned long long* grp_ptr = nullptr; // scratch: [T * 8] + int* grp_start = nullptr; // scratch: [T * 8 + 1] + int* grp_ent = nullptr; // scratch: [T * 8] + int* n_groups = nullptr; // scratch: [1] + int T = 0, k = 0, n_embd = 0, n_ff = 0; + float limit = 0.0f; + size_t down_off = 0; +}; +constexpr int kMaxWinTokens = kMaxMvCols; // the window's tokens moe_win_experts groups (16 x 8 entries) +void moe_win_group(const MoeWin& w, cudaStream_t s); +} // namespace strata::dsv41k::glmf diff --git a/include/strata/dsv41/sampler.hpp b/include/strata/dsv41/sampler.hpp new file mode 100644 index 0000000..edfbde8 --- /dev/null +++ b/include/strata/dsv41/sampler.hpp @@ -0,0 +1,94 @@ +// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). +// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. +// 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 +#include + +namespace strata::dsv41k { + +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; + // a request's logit_bias: a DEVICE array of n_vocab floats on the sampling device, added to every row's logits + // before the penalties and the filters (-inf bans a token); nullptr = none + const float* logit_bias = nullptr; + // the GLM engine's penalty history, on the HOST (never read by a kernel): every token the request's state has been + // fed so far, oldest first - its prompt, then each token it wrote. Glm5Model::pick_tokens hands each pick the last + // penalty_last_n of them (a verify window's row t: these, then the window's drafts 1..t). nullptr = none + const std::vector* host_history = nullptr; +}; + +// 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); + +// SPECULATIVE SAMPLING (Leviathan et al. 2023, Chen et al. 2023) for the pipelined NextN decode - opt-in +// (STRATA_GLM_SPEC_SAMPLE=1). The draft is DRAWN from the draft block's own distribution q (this chain on its logits, +// a Philox stream of its own) and its kept list is stored; the model's token is then the draft with probability +// min(1, p(d) / q(d)), else a draw from the residual max(0, p - q) renormalised - so it is distributed exactly as the +// plain draw from p, and a draft stands whenever the token is the draft (sum over x of min(p(x), q(x)) of the time +// instead of p(argmax q)). Same (seed, counter): the same tokens - but not the plain draw's tokens. +struct SpecList { + int n = 0; // the kept list's length (1..64) + int ids[64]; // descending, as the selection produced them + double p[64]; // q over the kept list (sums to 1) +}; + +// draft rows: logits (n_tokens, n_vocab) -> out[t] drawn through this chain, q[t] its kept list. DEVICE pointers, +// like sample_tokens; a sampled request without penalties only (greedy keeps the argmax draft). +void sample_draft(const float* logits, int n_tokens, int n_vocab, const SamplerParams& p, SpecList* q, int* out, + void* stream); +// verify rows: the model's logits (n_tokens, n_vocab), the draft draft[t] drawn from q[t] (same p.seed / p.counter as +// its sample_draft) -> out[t], distributed as sample_tokens' draw. A draft q[t] does not hold gets the plain draw. +void sample_verify(const float* logits, int n_tokens, int n_vocab, const SamplerParams& p, const SpecList* q, + const int* draft, int* out, 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::dsv41k diff --git a/include/strata/kernels/cpu/iq_avx2.hpp b/include/strata/kernels/cpu/iq_avx2.hpp index 3147ed5..ca5fa25 100644 --- a/include/strata/kernels/cpu/iq_avx2.hpp +++ b/include/strata/kernels/cpu/iq_avx2.hpp @@ -23,6 +23,13 @@ void iq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_ 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); +/// The DeepSeek-V4.1 CPU lane's rows (src/dsv41/ds4_gg_cpu.cpp). The same loops as iq256_rows / iq256_gu_rows with ggml's float +/// order, so a token's dot is ggml-cpu's vec_dot bit for bit at any number of tokens (the main engine's iq256_* are unchanged), +/// and IQ1_M (29), whose ggml dot is single-token. The caller checks AVX2 support. +bool iq256x_supported(int ggml_type) noexcept; +void iq256x_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); + /// The kernels' variants, a mask. Every variant computes the same bits; they differ in speed from core to core. /// kIq256Gather: IQ3_XXS, IQ3_S and IQ2_S read their grid entries with one gather (STRATA_IQ256_GATHER). /// kIq256Vnni: AVX-VNNI's vpdpwssd / vpdpbusd, every format and iq4nl256_down_rows (cpu_avxvnni_ok). diff --git a/include/strata/kernels/cpu/iq_avx512.hpp b/include/strata/kernels/cpu/iq_avx512.hpp index a9a71c4..ae21dfd 100644 --- a/include/strata/kernels/cpu/iq_avx512.hpp +++ b/include/strata/kernels/cpu/iq_avx512.hpp @@ -15,4 +15,11 @@ void iq512_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_ 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); +/// The DeepSeek-V4.1 CPU lane's rows (src/dsv41/ds4_gg_cpu.cpp): the same 64-value decode, summed in ggml's order, so a token's +/// dot is ggml-cpu's AVX2 vec_dot bit for bit at any number of tokens (1-6 in one pass, 7 and more as a prompt chunk's tiles). +/// The caller checks cpu_avx512_ok() (AVX-512 F/BW/VL/DQ/VNNI/VBMI). +bool iq512x_supported(int ggml_type) noexcept; +void iq512x_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/tq_cpu.hpp b/include/strata/kernels/cpu/tq_cpu.hpp new file mode 100644 index 0000000..7555fcc --- /dev/null +++ b/include/strata/kernels/cpu/tq_cpu.hpp @@ -0,0 +1,95 @@ +// include/strata/kernels/cpu/tq_cpu.hpp - the trellis expert formats (TQ2_T / TQK6 / TQK7, ggml types 144-146 of the +// agention llama.cpp fork) on the CPU: decode-and-dot against Q8_0 activations (ggml's block_q8_0), one or several +// tokens per call, on AVX-512, AVX2 or plain C++. +// +// THE FORMAT (third_party/ggml/ggml-common-tq.h): a 128-weight block is {fp16 d; 32 steps of K bits} (K = 8 / 6 / 7). +// Step t has a 15-bit state; the state's hash picks two points (pairs) of a 2048-point fp16 codebook, which are +// weights 4t..4t+3, times d. +// +// THE DECODE: a 32768 x 4 int16 table maps a state straight to its four weights at scale 2^13 (256 KiB, the +// approach of the fork's ggml-cpu vec_dot): one 8-byte lookup per four weights, no hash. The int16 rounding is +// exact for codebook values >= 2^-3 in magnitude and within 2^-14 below that; it is the same table, rounded the +// same way, as the fork's ggml-cpu kernels. +// +// THE ARITHMETIC, identical on every ISA so every path gives the same bits (and so does any token-group size): +// S[i][k] = sum_j w16[i][32k + j] * q8[i][k][j] exact in int32 (|w16| < 2^15, |q8| <= 127) +// acc[k] = fma((float) S[i][k], d_w[i] * d_a[i][k], acc[k]) for blocks i in order, k = 0..3 +// dot = ((acc[0] + acc[1]) + (acc[2] + acc[3])) * 2^-13 +// i.e. four float accumulators, one per Q8_0 sub-block position, each a fixed sequential chain. It differs from +// ggml-cpu's vec_dot (same integers, other float summation order) by float rounding only. +// +// THE KERNELS: `tq_isa()` picks AVX-512 (F/BW/VL/VBMI/VNNI, cpu_avx512_ok) or AVX2 (cpu_avx2_ok) at run time; the +// scalar kernel is the reference (on a CPU without AVX2 the engine keeps ggml-cpu's vec_dot, see tq_kernels_enabled). +// STRATA_TQ_ISA=scalar|avx2|avx512 caps the choice (tests, A/B); STRATA_NO_TQ_KERNELS=1 makes native_expert.cpp use +// ggml-cpu's vec_dot instead (the previous path). +#pragma once + +#include +#include + +namespace strata::kernels::cpu { + +enum class TqIsa : int { scalar = 0, avx2 = 1, avx512 = 2 }; + +/// EXPERIMENTAL lower-rate versions of the TQK rule (tools/trellis/tqenc.hpp, version 1; Strata-internal ids, not ggml +/// types, not in any GGUF): TQK5X = 22 bytes / 128 weights (1.375 bpw), TQK4X = 18 bytes (1.125 bpw). Same hash, +/// codebook, 15-bit mask, LSB-first circular stream and fp16 scale as TQK6/7 with K = 5 / 4. +inline constexpr int kTqTypeK5X = 224; ///< version 2: K = 5 with the computed codebook (tq_computed.hpp) +inline constexpr int kTqTypeK4X = 225; ///< version 2: K = 4, computed codebook +inline constexpr int kTqTypeK5T = 226; ///< version 1: K = 5 with the fork's point table (the first pilots) +inline constexpr int kTqTypeK4T = 227; ///< version 1: K = 4, point table +/// TQ2_T (144), TQK6 (145), TQK7 (146) and the experimental TQK5X / TQK4X / TQK5T / TQK4T. +bool tq_supported(int ggml_type) noexcept; +/// Bits per step: 8, 6, 7, 5, 4 (0 for any other type). +int tq_kbits(int ggml_type) noexcept; +/// Values per block of the trellis types, and bytes per block (2 + 4 * bits: 34, 26, 30, 22, 18). +constexpr int kTqBlock = 128; +inline size_t tq_block_bytes(int ggml_type) noexcept { return (size_t) (2 + 4 * tq_kbits(ggml_type)); } +/// The best ISA this CPU runs (capped by STRATA_TQ_ISA). +TqIsa tq_isa(); +/// Whether this CPU can run `isa` at all (scalar: always). +bool tq_isa_ok(TqIsa isa); +/// Whether STRATA_NO_TQ_KERNELS=1 is absent. The engine's native expert rows take these kernels for the trellis types +/// on every CPU (AVX-512 or AVX2 where the CPU has them, else the scalar kernel: a ggml from upstream has no trellis +/// type to fall back to, and the AVX code is only reached behind tq_isa_ok). STRATA_NO_TQ_KERNELS=1 asks for +/// ggml-cpu's vec_dot instead, honoured only by a ggml that has the types (the agentionai fork; tests, A/B). +bool tq_kernels_enabled(); +const char* tq_isa_name(TqIsa isa); + +/// The 32768 x 4 int16 state table of the fork's types (filled on first use; thread-safe). +const int16_t* tq_state_table(); +/// The same for the computed codebook of TQK5X / TQK4X (tq_computed.hpp). +const int16_t* tq_state_table_computed(); +/// The table a type decodes with. +const int16_t* tq_state_table_for(int ggml_type); + +/// Rows [r0, r1) of a trellis matrix (`row_bytes` per row, `n` weights per row) against `nt` (<= 8) Q8_0 +/// activations of n values: out[t][r] = w_r . a[t]. +void tq_rows(TqIsa isa, 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); +/// Gate and up rows [r0, r1) (gate at blob, up at blob + up_off): ff[t][r] = silu(g) * u, the SwiGLU expression +/// of native_gu_rows. +void tq_gu_rows(TqIsa isa, 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); + +/// Largest token group per call and widest row the kernels take. +inline constexpr int kTqMaxTokens = 8; +inline constexpr int kTqMaxN = 5120; // (DeepSeek-V4.1 hidden width; was 4096) + +namespace tq_detail { +/// One token's Q8_0 activation unpacked for the kernels: the int8 values widened to int16 and the scales as floats. +struct TqAct { + alignas(64) int16_t q[kTqMaxN]; + alignas(64) float d[kTqMaxN / 32]; +}; +void unpack_act(const void* q8_0, int n, TqAct& a); +// the per-ISA row kernels (dot products only; `out[t][r]` for rows [r0, r1)) +void tq_rows_scalar(int kb, const int16_t* tab, const uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt, + float* const* out, int r0, int r1); +void tq_rows_avx2(int kb, const int16_t* tab, const uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt, + float* const* out, int r0, int r1); +void tq_rows_avx512(int kb, const int16_t* tab, const uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt, + float* const* out, int r0, int r1); +} // namespace tq_detail + +} // namespace strata::kernels::cpu diff --git a/src/dsv41/ds4_attn_split.cuh b/src/dsv41/ds4_attn_split.cuh new file mode 100644 index 0000000..959830b --- /dev/null +++ b/src/dsv41/ds4_attn_split.cuh @@ -0,0 +1,206 @@ +// Split-KV sparse attention: Strata (dsv41 CUDA lab), used with the DeepSeek attention of Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). +// (the surrounding types, AttnRows and the packed-row formats, are theirs; see third_party/project-maya/NOTICE.md). +// src/dsv41/ds4_attn_split.cuh - split-KV ("flash-decoding") version of DeepSeek's sparse attention for a few queries +// (decode T = 1, DSpark verify T = 2..5): 64 heads x d 512, MQA (K = V), window rows (BF16) + selected compressed rows (kKvFp4: +// E2M1 codes + E4M3 scales per 16) + a learned sink logit per head. Same inputs and outputs as strata::ds4::sparse_attn +// (AttnRows gen 0, ckv kKvFp4); the shipped kernel runs one 256-thread block per (head, query) = 64 blocks on 48 SMs and takes +// ~125 us per query; this one splits the keys over R-row chunks and groups G heads per block, which share the decoded rows. +// phase 1: block (head group, chunk, query): decode R rows to BF16 in shared memory (exact: window rows are BF16, packed +// rows have <= 7 significant bits), scores for G heads (warp per row, lanes 16 values, shuffle reduction), local +// softmax, partial output (thread = 2 output values) -> scratch {m, l, o[512]} per (query, head, chunk) +// phase 2: block (head, query): merge the chunks and the sink. +// Plain C++ (no PTX), shuffles and shared memory only: the HIP port is a rename. +#pragma once +#include "ds4_kernels.cuh" +#include "ds4_numerics.cuh" +#include + +namespace strata::ds4 { +namespace attnsplit { + + + +__device__ __forceinline__ float bf2f_(uint16_t b) { return __uint_as_float((uint32_t) b << 16); } +__device__ __forceinline__ uint16_t f2bf_exact(float f) { return (uint16_t) (__float_as_uint(f) >> 16); } // exact values only +__device__ __forceinline__ float e2m1_x2p14(uint32_t c) { + return __half2float(__ushort_as_half((unsigned short) (((c & 8u) << 12) | ((c & 7u) << 9)))); +} +__device__ __forceinline__ float wsum(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} +__device__ __forceinline__ float wmax(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); + return v; +} + +// d = 512 only (a thread owns 2 output values, a lane 16 values of a row) +template +__global__ void __launch_bounds__(256) attn_part(const float* __restrict__ q, const uint16_t* __restrict__ win, + const uint8_t* __restrict__ ckv, size_t ckv_row_bytes, const int* __restrict__ sel, + int sel_stride, AttnRows ar, int heads, float scale, float* __restrict__ part, + float* __restrict__ ml, int nsplit) { + constexpr int D = 512; + __shared__ __align__(16) uint16_t rows[R][D]; + __shared__ float sc[G][R]; + __shared__ float4 pr[R][(G + 3) / 4]; + __shared__ float mloc[G], lloc[G]; + const int hg = blockIdx.x, chunk = blockIdx.y, t = blockIdx.z; + const int n_win = ar.nwin[t], n_sel = ar.nsel[t], total = n_win + n_sel; + const int j0 = chunk * R; + if (j0 >= total) return; + const int nr = min(R, total - j0); + const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5; + // q of this block's heads: lane's 16 values per head in registers (issued first: its latency overlaps the row loads) + float qv[G][16]; +#pragma unroll + for (int g = 0; g < G; ++g) { + const float4* qp = (const float4*) (q + ((size_t) t * heads + hg * G + g) * D + lane * 16); +#pragma unroll + for (int i = 0; i < 4; ++i) { const float4 v = qp[i]; qv[g][4 * i] = v.x; qv[g][4 * i + 1] = v.y; qv[g][4 * i + 2] = v.z; qv[g][4 * i + 3] = v.w; } + } + // ---- stage rows: warp per row, lane = 16 values; all of a warp's row loads are issued before any is converted + constexpr int RPW = (R + 7) / 8; + uint4 wa[RPW][2]; + uint2 cwv[RPW]; + uint32_t sbv[RPW]; + int rowoff[RPW]; +#pragma unroll + for (int i = 0; i < RPW; ++i) { + const int jj = wp + 8 * i, j = j0 + jj; + rowoff[i] = -1; + if (jj < nr) { + if (j < n_win) { + const uint4* src = (const uint4*) (win + (size_t) (ar.win0[t] + j) * D + lane * 16); + wa[i][0] = src[0]; + wa[i][1] = src[1]; + } else { + rowoff[i] = sel[(size_t) t * sel_stride + (j - n_win)]; + } + } + } +#pragma unroll + for (int i = 0; i < RPW; ++i) + if (rowoff[i] >= 0) { + const uint8_t* r = ckv + (size_t) rowoff[i] * ckv_row_bytes; + cwv[i] = *(const uint2*) (r + lane * 8); + sbv[i] = r[D / 2 + lane]; + } +#pragma unroll + for (int i = 0; i < RPW; ++i) { + const int jj = wp + 8 * i; + if (jj >= nr) continue; + uint4* dst = (uint4*) &rows[jj][lane * 16]; + if (rowoff[i] < 0) { + dst[0] = wa[i][0]; + dst[1] = wa[i][1]; + } else { + const float s = e4m3_value((uint8_t) sbv[i]) * 16384.0f; // (the nibbles decode to value * 2^-14) + uint32_t o[8]; +#pragma unroll + for (int w = 0; w < 2; ++w) { + const uint32_t c = w ? cwv[i].y : cwv[i].x; +#pragma unroll + for (int x = 0; x < 4; ++x) { + const uint32_t b = c >> (8 * x); + const uint16_t lo = f2bf_exact(e2m1_x2p14(b) * s), hi = f2bf_exact(e2m1_x2p14(b >> 4) * s); + o[4 * w + x] = (uint32_t) lo | ((uint32_t) hi << 16); + } + } + dst[0] = make_uint4(o[0], o[1], o[2], o[3]); + dst[1] = make_uint4(o[4], o[5], o[6], o[7]); + } + } + __syncthreads(); + // ---- scores + for (int jj = wp; jj < nr; jj += 8) { + const uint4 a = *(const uint4*) &rows[jj][lane * 16], b = *(const uint4*) &rows[jj][lane * 16 + 8]; + float kv[16]; + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; +#pragma unroll + for (int i = 0; i < 8; ++i) { kv[2 * i] = __uint_as_float(w[i] << 16); kv[2 * i + 1] = __uint_as_float(w[i] & 0xffff0000u); } +#pragma unroll + for (int g = 0; g < G; ++g) { + float s = 0.f; +#pragma unroll + for (int i = 0; i < 16; ++i) s += qv[g][i] * kv[i]; + s = wsum(s); + if (lane == 0) sc[g][jj] = s * scale; + } + } + __syncthreads(); + // ---- local softmax: warp g handles head g + if (wp < G) { + float m = -INFINITY; + for (int j = lane; j < nr; j += 32) m = fmaxf(m, sc[wp][j]); + m = wmax(m); + float l = 0.f; + for (int j = lane; j < nr; j += 32) { const float p = __expf(sc[wp][j] - m); sc[wp][j] = p; l += p; } + l = wsum(l); + if (lane == 0) { mloc[wp] = m; lloc[wp] = l; } + } + __syncthreads(); + for (int i = threadIdx.x; i < nr * G; i += 256) { const int j = i / G, g = i % G; ((float*) &pr[j][0])[g] = sc[g][j]; } + __syncthreads(); + // ---- partial output: thread = values 2 tid, 2 tid + 1 of every head + float o0[G], o1[G]; +#pragma unroll + for (int g = 0; g < G; ++g) o0[g] = o1[g] = 0.f; + const int c = threadIdx.x * 2; + for (int j = 0; j < nr; ++j) { + const uint32_t kw = *(const uint32_t*) &rows[j][c]; + const float k0 = __uint_as_float(kw << 16), k1 = __uint_as_float(kw & 0xffff0000u); + const float* p = (const float*) &pr[j][0]; +#pragma unroll + for (int g = 0; g < G; ++g) { o0[g] += p[g] * k0; o1[g] += p[g] * k1; } + } +#pragma unroll + for (int g = 0; g < G; ++g) { + const size_t bi = ((size_t) t * heads + hg * G + g) * nsplit + chunk; + *(float2*) (part + bi * D + c) = make_float2(o0[g], o1[g]); + if (threadIdx.x == 0) { ml[bi * 2] = mloc[g]; ml[bi * 2 + 1] = lloc[g]; } + } +} + +__global__ void __launch_bounds__(256) attn_merge(const float* __restrict__ part, const float* __restrict__ ml, const float* __restrict__ sink, + int heads, int nsplit, int R, AttnRows ar, float* __restrict__ out) { + constexpr int D = 512; + const int h = blockIdx.x, t = blockIdx.y; + const int total = ar.nwin[t] + ar.nsel[t]; + const int ns = (total + R - 1) / R; + const size_t base = ((size_t) t * heads + h) * nsplit; + float M = sink[h]; + for (int s = 0; s < ns; ++s) M = fmaxf(M, ml[(base + s) * 2]); + float den = __expf(sink[h] - M); + for (int s = 0; s < ns; ++s) den += ml[(base + s) * 2 + 1] * __expf(ml[(base + s) * 2] - M); + const int c = threadIdx.x * 2; + float a0 = 0.f, a1 = 0.f; + for (int s = 0; s < ns; ++s) { + const float w = __expf(ml[(base + s) * 2] - M); + const float2 v = *(const float2*) (part + (base + s) * D + c); + a0 += w * v.x; + a1 += w * v.y; + } + *(float2*) (out + ((size_t) t * heads + h) * D + c) = make_float2(a0 / den, a1 / den); +} + +struct AttnSplitScratch { + float* part = nullptr; // [T][heads][nsplit][512] + float* ml = nullptr; // [T][heads][nsplit][2] + int nsplit = 0, max_t = 0; +}; + +// total_max = the largest nwin + nsel of the T queries +template +void sparse_attn_split(const float* q, const uint16_t* win, const uint8_t* ckv, size_t ckv_row_bytes, const int* sel, int sel_stride, + const AttnRows& ar, const float* sink, int heads, int T, float scale, float* out, const AttnSplitScratch& sc, + int total_max, cudaStream_t s) { + const int nsplit = (total_max + R - 1) / R; + attn_part<<>>(q, win, ckv, ckv_row_bytes, sel, sel_stride, ar, heads, scale, sc.part, sc.ml, sc.nsplit); + attn_merge<<>>(sc.part, sc.ml, sink, heads, sc.nsplit, R, ar, out); +} + +} // namespace attnsplit +} // namespace strata::ds4 diff --git a/src/dsv41/ds4_engram_io.hpp b/src/dsv41/ds4_engram_io.hpp new file mode 100644 index 0000000..b68919d --- /dev/null +++ b/src/dsv41/ds4_engram_io.hpp @@ -0,0 +1,275 @@ +// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). +// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. +// src/ds4/ds4_engram_io.hpp - DeepSeek's Engram (n-gram memory) rows read off the decode's critical path. +// +// A token's Engram rows depend only on the token ids, so they are asked for as soon as the window's tokens are known +// and collected only right before the layer that adds them (layer 1's hide behind the embedding and layer 0, layer +// 14's behind layers 0-13). The reads run on the reader's own threads, each with its own handles to the model's files +// (on Windows the ReadFile calls on one synchronous handle run one at a time), FIFO: the first Engram layer's rows +// first. A bounded row cache (clock eviction) keeps rows already fetched: a row that recurs (the same n-gram again, +// in the prompt or later) is a copy, not a read. The rows are the file's bytes either way, so the output is the same. +#pragma once + +#include "ds4_os.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::ds4 { + +inline int64_t now_ns() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count(); +} + +/// Rows already fetched: key -> `bytes` of payload, at most `cap` rows (grown on demand in blocks), clock eviction. +/// Not thread-safe (the caller locks). +class EgRowCache { +public: + void init(size_t cap, size_t bytes) { + cap_ = cap; + bytes_ = bytes; + map_.reserve(std::min(cap, 1u << 20)); + } + size_t capacity() const { return cap_; } + size_t size() const { return keys_.size(); } + /// The row's payload, or nullptr (a hit marks it recently used). + const uint8_t* find(uint64_t key) { + const auto it = map_.find(key); + if (it == map_.end()) return nullptr; + ref_[it->second] = 1; + return at(it->second); + } + /// Room for key's payload (the caller fills it): a new slot while below capacity, else the clock's victim. + uint8_t* put(uint64_t key) { + if (cap_ == 0 || bytes_ == 0) return nullptr; + const auto it = map_.find(key); + if (it != map_.end()) return at(it->second); + uint32_t s; + if (keys_.size() < cap_) { + s = (uint32_t) keys_.size(); + if (s % kBlock == 0) blocks_.emplace_back(new uint8_t[(size_t) kBlock * bytes_]); + keys_.push_back(key); + ref_.push_back(0); + } else { + while (ref_[hand_]) { // (a second chance for rows used since the hand last passed) + ref_[hand_] = 0; + hand_ = (hand_ + 1) % (uint32_t) cap_; + } + s = hand_; + hand_ = (hand_ + 1) % (uint32_t) cap_; + map_.erase(keys_[s]); + keys_[s] = key; + ref_[s] = 0; + } + map_.emplace(key, s); + return at(s); + } + +private: + static constexpr uint32_t kBlock = 4096; + uint8_t* at(uint32_t s) { return blocks_[s / kBlock].get() + (size_t) (s % kBlock) * bytes_; } + size_t cap_ = 0, bytes_ = 0; + uint32_t hand_ = 0; + std::unordered_map map_; + std::vector keys_; + std::vector ref_; + std::vector> blocks_; +}; + +/// One row to fetch: its bytes to dst, its scales to scales. mx8: n bytes at off of a file, [scale, 32 codes] blocks +/// (a GGUF's MXFP8 row); else n row bytes at off and n2 scale bytes at off2 of file2 (two reads; n2 0: none - a GGUF's +/// Q6_K or IQ4_NL row, their scales inside their n bytes: 210 a 256 values, 18 a 32). +struct EgRead { + int file = -1; + uint64_t off = 0; + uint32_t n = 0; + uint8_t* dst = nullptr; + uint8_t* scales = nullptr; + bool mx8 = false; + int file2 = -1; + uint64_t off2 = 0; + uint32_t n2 = 0; + uint64_t key = 0; +}; + +/// A batch of rows (one Engram layer of a window): reads, the other places a row read once goes, and its state. +struct EgBatch { + std::vector reads; + std::vector>> dups; // read i -> another (codes, scales) + std::vector ok; // per read: 1 read whole + std::atomic left{0}; // reads not yet done + std::atomic post{0}; // 0 pending, 1 finishing, 2 finished + int64_t t0 = 0; // submitted (now_ns()) + std::atomic t1{0}; // the last read done + bool live = false; // submitted and not yet finished + void clear() { + reads.clear(); + dups.clear(); + ok.clear(); + left.store(0); + post.store(0); + live = false; + } +}; + +/// The reader's threads: each read on whichever is free, in submission order, with that thread's own file handles. +class EgReader { +public: + ~EgReader() { stop(); } + /// direct[i]: file i read unbuffered (Windows, a file nothing maps: os::open_unbuffered), else buffered + void start(const std::vector& paths, int threads, std::vector direct = {}) { + paths_ = paths; + direct_ = std::move(direct); + for (int i = 0; i < threads; ++i) th_.emplace_back([this] { loop(); }); + } + void stop() { + { + std::lock_guard lk(mu_); + quit_ = true; + } + cv_.notify_all(); + for (auto& t : th_) t.join(); + th_.clear(); + if (check_n_.load() > 0) + std::fprintf(stderr, "ds4 Engram check (DS4_EG_CHECK): %lld rows read unbuffered, %lld differed from a buffered read\n", + (long long) check_n_.load(), (long long) check_bad_.load()); + } + int threads() const { return (int) th_.size(); } + void submit(EgBatch& b) { + b.ok.assign(b.reads.size(), 0); + b.post.store(0); + b.t0 = now_ns(); + b.t1.store(b.t0); + b.live = true; + b.left.store((int) b.reads.size(), std::memory_order_release); + const int n = (int) b.reads.size(); + if (n == 0) return; + // a token's rows one job each; a prompt chunk's in runs (fewer trips through the queue's lock) + const int step = std::max(1, std::min(32, n / (int) (th_.size() * 4))); + int jobs = 0; + { + std::lock_guard lk(mu_); + for (int i = 0; i < n; i += step, ++jobs) q_.push_back({&b, i, std::min(n, i + step)}); + } + if (jobs >= (int) th_.size()) cv_.notify_all(); + else + for (int i = 0; i < jobs; ++i) cv_.notify_one(); + } + /// Until every read of b is done. + void wait(EgBatch& b) { + if (b.left.load(std::memory_order_acquire) == 0) return; + std::unique_lock lk(done_mu_); + done_cv_.wait(lk, [&] { return b.left.load(std::memory_order_acquire) == 0; }); + } + +private: + void loop() { + std::vector fds(paths_.size(), os::kBadFd); // this thread's own handles, opened on first use + std::vector ufds(paths_.size(), os::kBadFd); // (and its unbuffered ones) + std::vector buf, abuf(3 * os::kDirectAlign); + uint8_t* al = abuf.data() + (os::kDirectAlign - (uintptr_t) abuf.data() % os::kDirectAlign) % os::kDirectAlign; + for (;;) { + Job job; + { + std::unique_lock lk(mu_); + cv_.wait(lk, [&] { return quit_ || !q_.empty(); }); + if (quit_ && q_.empty()) break; + job = q_.front(); + q_.pop_front(); + } + EgBatch& b = *job.b; + for (int i = job.i0; i < job.i1; ++i) b.ok[(size_t) i] = read(fds, ufds, al, b.reads[(size_t) i], buf) ? 1 : 0; + const int64_t t = now_ns(); + for (int64_t prev = b.t1.load(); t > prev && !b.t1.compare_exchange_weak(prev, t);) { + } + if (b.left.fetch_sub(job.i1 - job.i0, std::memory_order_acq_rel) == job.i1 - job.i0) { // (b is the waiter's again) + std::lock_guard lk(done_mu_); + done_cv_.notify_all(); + } + } + for (os::fd_t f : fds) os::close_fd(f); + for (os::fd_t f : ufds) os::close_fd(f); + } + bool read(std::vector& fds, std::vector& ufds, uint8_t* al, const EgRead& r, + std::vector& buf) { + if ((r.mx8 || r.n2 == 0) && r.file >= 0 && (size_t) r.file < direct_.size() && direct_[(size_t) r.file] && + os::direct_span(r.off, r.n) <= 2 * os::kDirectAlign) { + os::fd_t& u = ufds[(size_t) r.file]; + if (u == os::kBadFd) u = os::open_unbuffered(paths_[(size_t) r.file]); + if (u != os::kBadFd && os::pread_unbuffered(u, al, r.n, r.off)) { + const uint8_t* src = al + r.off % os::kDirectAlign; + static const bool check = std::getenv("DS4_EG_CHECK") != nullptr; // (each row read buffered too) + if (check) { + std::vector ref(r.n); + os::fd_t& f2 = fds[(size_t) r.file]; + if (f2 == os::kBadFd) f2 = os::open_ro(paths_[(size_t) r.file]); + const bool ok = f2 != os::kBadFd && os::pread_full(f2, ref.data(), r.n, r.off); + if (!ok || std::memcmp(ref.data(), src, r.n) != 0) ++check_bad_; + ++check_n_; + } + if (!r.mx8) { // (a GGUF's Q6_K / IQ4_NL row: its bytes as they are, the scales inside) + std::memcpy(r.dst, src, r.n); + return true; + } + for (uint32_t k = 0; k < r.n / 33; ++k) { // [scale, 32 codes] -> codes | scales + r.scales[k] = src[(size_t) k * 33]; + std::memcpy(r.dst + (size_t) k * 32, src + (size_t) k * 33 + 1, 32); + } + return true; + } // (else buffered, below) + } + auto fd = [&](int file) { + if (file < 0 || file >= (int) fds.size()) return os::kBadFd; + if (fds[(size_t) file] == os::kBadFd) fds[(size_t) file] = os::open_ro(paths_[(size_t) file]); + return fds[(size_t) file]; + }; + const os::fd_t f = fd(r.file); + if (f == os::kBadFd) return false; + if (!r.mx8) { + if (!os::pread_full(f, r.dst, r.n, r.off)) return false; + if (r.n2 == 0) return true; + const os::fd_t f2 = fd(r.file2); + return f2 != os::kBadFd && os::pread_full(f2, r.scales, r.n2, r.off2); + } + buf.resize(r.n); + if (!os::pread_full(f, buf.data(), r.n, r.off)) return false; + for (uint32_t k = 0; k < r.n / 33; ++k) { // [scale, 32 codes] -> codes | scales + r.scales[k] = buf[(size_t) k * 33]; + std::memcpy(r.dst + (size_t) k * 32, buf.data() + (size_t) k * 33 + 1, 32); + } + return true; + } + + std::vector paths_; + std::vector direct_; + +public: + std::atomic check_n_{0}, check_bad_{0}; // (DS4_EG_CHECK: rows compared, rows that differed) + std::vector th_; + std::mutex mu_; + std::condition_variable cv_; + struct Job { + EgBatch* b = nullptr; + int i0 = 0, i1 = 0; // reads [i0, i1) + }; + std::deque q_; + bool quit_ = false; + std::mutex done_mu_; + std::condition_variable done_cv_; +}; + +} // namespace strata::ds4 diff --git a/src/dsv41/ds4_gg_cpu.cpp b/src/dsv41/ds4_gg_cpu.cpp new file mode 100644 index 0000000..e303694 --- /dev/null +++ b/src/dsv41/ds4_gg_cpu.cpp @@ -0,0 +1,293 @@ +// Strata. The CPU lane of the DeepSeek-V4.1 engine path for ggml's block types (IQ2_XXS .. Q4_K, the experts of a requantized model): +// ggml-cpu's own row dots (type traits: vec_dot over the Q8_K / Q8_0 activation of vec_dot_type), one row at a time. Maya's lane for +// these types (native_expert split-base rows) is not in Strata's tree; this one is plain and complete, not tuned. +#include "ds4_gguf_cpu.hpp" + +#include +#include +#include +#include +#include + +#if defined(STRATA_DSV41_TQ_CPU) +#include "ggml-cpu.h" +#include "ggml.h" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/iq_avx2.hpp" +#include "strata/kernels/cpu/iq_avx512.hpp" + +#include +#include +#if defined(_MSC_VER) +#include +#elif defined(__x86_64__) +#include +#endif + +namespace strata::ds4::gguf { +namespace { +void init_once() { + static std::once_flag f; + std::call_once(f, [] { ggml_cpu_init(); }); +} +size_t row_size(int type, int64_t k) { return ggml_row_size((ggml_type) type, k); } +} // namespace + +bool gg_cpu_type(int type) { + // every type ggml-cpu has a row dot for (ds4_gguf.cu's known types); the i-quants with a device kernel are usually + // placed in VRAM, but a pack may hand any of them to this lane + switch (type) { + case 10: case 11: case 12: case 13: case 14: case 16: case 17: case 18: case 19: case 20: case 21: case 22: + case 23: case 29: return true; + default: return false; + } +} + +static bool dbg() { static const bool on = std::getenv("DS4_DBG_GG") != nullptr; return on; } +bool gg_cpu_fmt(int tg, int td, int n_embd, int n_ff, IqCpu& f, std::string& err) { + if (dbg()) std::fprintf(stderr, "gg_cpu_fmt %d %d\n", tg, td); + init_once(); + if (!gg_cpu_type(tg) || !gg_cpu_type(td)) { + err = "not ggml block types"; + return false; + } + const ggml_type_traits_cpu* a = ggml_get_type_traits_cpu((ggml_type) tg); + const ggml_type_traits_cpu* b = ggml_get_type_traits_cpu((ggml_type) td); + if (a == nullptr || b == nullptr || a->vec_dot == nullptr || b->vec_dot == nullptr) { + err = "ggml-cpu has no row dot for these types"; + return false; + } + f.tg = tg; + f.td = td; + f.n_embd = n_embd; + f.n_ff = n_ff; + f.gu_act = (int) a->vec_dot_type; + f.d_act = (int) b->vec_dot_type; + f.gu_row = row_size(tg, n_embd); + f.d_row = row_size(td, n_ff); + f.act_bytes = row_size(f.gu_act, n_embd); + f.h_bytes = row_size(f.d_act, n_ff); + return true; +} + +// x (k values) -> the activation type (Q8_K, Q8_0 ..) ggml-cpu's dot takes +void gg_cpu_quant(int act, const float* x, int k, void* dst) { + init_once(); + if (dbg()) std::fprintf(stderr, "gg_cpu_quant act %d k %d\n", act, k); + const ggml_type_traits_cpu* tc = ggml_get_type_traits_cpu((ggml_type) act); + if (tc != nullptr && tc->from_float != nullptr) { + tc->from_float(x, dst, k); + return; + } + const ggml_type_traits* t = ggml_get_type_traits((ggml_type) act); + if (dbg()) std::fprintf(stderr, "gg_cpu_quant: no cpu from_float, ref %p\n", (void*) (t ? t->from_float_ref : nullptr)); + t->from_float_ref(x, dst, k); +} + +// Strata's AVX2 multi-token rows for the i-quants (iq256x_rows: each 32-value chunk decoded once, every token applies it). They +// are ggml-cpu's vec_dot bit for bit (the integer sums are ggml's and the float additions come in ggml's order: ds4_gg_bench --exact, +// and own_ok() below checks it once per type on this CPU against the ggml-cpu build in use), so taking them or not never changes an +// answer, at any number of tokens - the choice is speed only. Measured on the rows alone: no faster than ggml's dot at one token +// (both wait for the codebook lookups), x1.7-2.9 at 2-4 tokens, x1.4 on IQ3_S already at one; so by default ggml's dot below +// min_tokens(type) and these rows from there. DS4_GG_IQ256=0 never takes them, =1 always (the old opt-in). +static int g_iq256 = -1; // -1: from the environment and the CPU, 0 off, 1 always, 2 from min_tokens(type) +void gg_cpu_set_iq256(int mode) { g_iq256 = mode; } +static int min_tokens(int type) { return type == 21 ? 1 : type == 29 ? 3 : 2; } +static bool own_ok(int type, int impl) { + static std::once_flag once[2][32]; + static bool ok[2][32]; + const int k = type & 31; + std::call_once(once[impl][k], [&] { + ok[impl][k] = false; + const ggml_type_traits_cpu* tc = ggml_get_type_traits_cpu((ggml_type) type); + const ggml_type_traits_cpu* q8 = tc ? ggml_get_type_traits_cpu(tc->vec_dot_type) : nullptr; + if (tc == nullptr || tc->vec_dot == nullptr || q8 == nullptr || q8->from_float == nullptr) return; + const int n = 1024, rows = 7; + const size_t rb = ggml_row_size((ggml_type) type, n), bb = ggml_type_size((ggml_type) type), ab = ggml_row_size(tc->vec_dot_type, n); + uint64_t st = 0x9E3779B97F4A7C15ull + (uint64_t) type; + auto next = [&st] { st ^= st << 13; st ^= st >> 7; st ^= st << 17; return st; }; + std::vector w(rb * rows); + for (auto& b : w) b = (uint8_t) next(); + for (size_t o = 0; o < w.size(); o += bb) { + const ggml_fp16_t d = ggml_fp32_to_fp16(0.002f + 0.001f * (float) (next() % 16)); + if (type == 29) { // IQ1_M keeps its f16 in the top nibbles of the four scale words + uint16_t sc[4]; + std::memcpy(sc, &w[o + 48], 8); + for (int j = 0; j < 4; ++j) sc[j] = (uint16_t) ((sc[j] & 0x0fff) | ((d >> (4 * j)) & 0xf) << 12); + std::memcpy(&w[o + 48], sc, 8); + } else { + std::memcpy(&w[o], &d, sizeof d); + } + } + for (int nt : {1, 2, 3, 4, 5, 6, 8, 16, 33}) { + std::vector> a((size_t) nt, std::vector(ab)); + std::vector ap((size_t) nt); + std::vector> o0((size_t) nt, std::vector(rows)), o1 = o0; + std::vector p1((size_t) nt); + for (int t = 0; t < nt; ++t) { + std::vector x((size_t) n); + for (auto& v : x) v = ((float) (next() % 2001) - 1000.0f) * 1e-3f; + q8->from_float(x.data(), a[(size_t) t].data(), n); + ap[(size_t) t] = a[(size_t) t].data(); + p1[(size_t) t] = o1[(size_t) t].data(); + for (int r = 0; r < rows; ++r) tc->vec_dot(n, &o0[(size_t) t][(size_t) r], 0, w.data() + (size_t) r * rb, 0, ap[(size_t) t], 0, 1); + } + if (impl == 1) strata::kernels::cpu::iq512x_rows(type, w.data(), rb, n, ap.data(), nt, p1.data(), 0, rows); + else strata::kernels::cpu::iq256x_rows(type, w.data(), rb, n, ap.data(), nt, p1.data(), 0, rows); + for (int t = 0; t < nt; ++t) + if (std::memcmp(o0[(size_t) t].data(), o1[(size_t) t].data(), rows * sizeof(float)) != 0) { + if (dbg() || std::getenv("DS4_GG_VERBOSE")) std::fprintf(stderr, "ds4: CPU lane type %d: AVX2 rows differ from ggml-cpu's dot at %d tokens, not used\n", type, nt); + return; + } + } + ok[impl][k] = true; + }); + return ok[impl][k]; +} +// the AMD family (0x19 Zen 3/4, 0x1A Zen 5), 0 on any other vendor or if it cannot be read +static int amd_family() { + static const int fam = [] { +#if defined(_MSC_VER) + int r[4]; + __cpuid(r, 0); + char v[13]; + std::memcpy(v, &r[1], 4); std::memcpy(v + 4, &r[3], 4); std::memcpy(v + 8, &r[2], 4); + v[12] = 0; + if (std::strcmp(v, "AuthenticAMD") != 0) return 0; + __cpuid(r, 1); + const unsigned eax = (unsigned) r[0]; +#elif defined(__x86_64__) + unsigned a, b, c, d; + if (!__get_cpuid(0, &a, &b, &c, &d)) return 0; + char v[13]; + std::memcpy(v, &b, 4); std::memcpy(v + 4, &d, 4); std::memcpy(v + 8, &c, 4); + v[12] = 0; + if (std::strcmp(v, "AuthenticAMD") != 0) return 0; + if (!__get_cpuid(1, &a, &b, &c, &d)) return 0; + const unsigned eax = a; +#else + return 0; +#endif + const unsigned base = (eax >> 8) & 0xF; + return (int) (base == 0xF ? base + ((eax >> 20) & 0xFF) : base); + }(); + return fam; +} +// DS4_GG_IQ512: 1 takes the AVX-512 rows (bit-identical too) where the CPU has AVX-512 F/BW/VL/DQ/VNNI/VBMI, 0 never; unset: the rule +// below, from the measurements on Zen 4. +static int g_iq512 = -1; +static bool want_512(int type, int nt) { + if (g_iq512 < 0) { + const char* v = std::getenv("DS4_GG_IQ512"); + g_iq512 = !strata::kernels::cpu::cpu_avx512_ok() ? 0 : v == nullptr ? 2 : std::atoi(v) != 0 ? 1 : 0; + } + if (g_iq512 == 0 || !strata::kernels::cpu::iq512x_supported(type)) return false; + if (g_iq512 == 1) return true; + // by CPU (measured, ds4_gg_bench --expert; the rows are bit-identical to ggml's dot everywhere): + // Zen 5 (AMD family 0x1A, Strix Halo, 16 threads, GB/s of weights ggml -> AVX-512 rows): one token IQ2_XXS 35 -> 44, IQ2_XS 37 -> 48, + // IQ1_M 32 -> 36 (the sign masks by popcount, IQ1_M's indices by pdep: no table loads), IQ3_XXS 43 -> 45; 4 tokens x2.5-3.5; 16 tokens x4.4-4.8; + // Zen 4 (family 0x19, Ryzen 5 7600, 6 threads): one token IQ2_XXS 15.9 -> 19.7, IQ2_XS 20.6 -> 24.2, IQ1_M 16.7 -> 17.6-18.2, IQ3_XXS 22.4 -> 23.8 + // (noise-level); 2 tokens x1.5-2.2; 4 tokens x2.4-3.3; 16 tokens x2.8-4.6; + // anything else with AVX-512 (Intel): not measured, so the AVX2 rows + const int fam = amd_family(); + if (fam < 0x19) return false; + if (type == 16 || type == 17) return true; + if (type == 18) return nt >= 2; + if (type == 29) return nt >= 2 || fam >= 0x1A; + return false; +} +// 0: ggml-cpu's dot, 1: the AVX2 rows, 2: the AVX-512 rows +static int use_iq256(int type, int nt) { + if (g_iq256 < 0) { + const char* v = std::getenv("DS4_GG_IQ256"); + // (ggml-cpu's own answer: built with AVX2 + FMA + F16C, which is also what makes its dots the AVX2 ones these rows match) + const bool avx2 = ggml_cpu_has_avx2() && ggml_cpu_has_fma() && ggml_cpu_has_f16c(); + g_iq256 = !avx2 ? 0 : v == nullptr ? 2 : std::atoi(v) != 0 ? 1 : 0; + } + if (g_iq256 == 0) return 0; + if (want_512(type, nt) && own_ok(type, 1)) return 2; + if (!strata::kernels::cpu::iq256x_supported(type)) return 0; + if (g_iq256 == 2 && nt < min_tokens(type)) return 0; + return own_ok(type, 0) ? 1 : 0; +} + +static void dots(int type, const uint8_t* w, size_t rb, int n, const void* const* act, int nt, float* const* out, int r0, int r1) { + if (nt > 0) { + const int impl = use_iq256(type, nt); + if (impl == 2) { + strata::kernels::cpu::iq512x_rows(type, w, rb, n, act, nt, out, r0, r1); + return; + } + if (impl == 1) { + strata::kernels::cpu::iq256x_rows(type, w, rb, n, act, nt, out, r0, r1); + return; + } + } + const ggml_type_traits_cpu* tc = ggml_get_type_traits_cpu((ggml_type) type); + if (dbg()) std::fprintf(stderr, "gg dots type %d n %d rows %d..%d nt %d\n", type, n, r0, r1, nt); + for (int r = r0; r < r1; ++r) + for (int t = 0; t < nt; ++t) tc->vec_dot(n, &out[t][r], 0, w + (size_t) r * rb, 0, act[t], 0, 1); +} + +void gg_cpu_gate_up(const IqCpu& f, const uint8_t* gate, const uint8_t* up, const void* const* act, int nt, float* const* ff, int r0, + int r1, float limit) { + constexpr int kMaxTok = 64; // (the prompt path: a chunk's tokens an expert) + static thread_local std::vector tmp[kMaxTok]; + float* uo[kMaxTok]; + if (nt > kMaxTok) { // (more than a pass takes: in pieces) + for (int t0 = 0; t0 < nt; t0 += kMaxTok) + gg_cpu_gate_up(f, gate, up, act + t0, nt - t0 < kMaxTok ? nt - t0 : kMaxTok, ff + t0, r0, r1, limit); + return; + } + for (int t = 0; t < nt; ++t) { + tmp[t].resize((size_t) r1); + uo[t] = tmp[t].data(); + } + dots(f.tg, gate, f.gu_row, f.n_embd, act, nt, ff, r0, r1); + dots(f.tg, up, f.gu_row, f.n_embd, act, nt, uo, r0, r1); + for (int t = 0; t < nt; ++t) + for (int r = r0; r < r1; ++r) { + float g = ff[t][r], u = uo[t][r]; + if (limit > 0.0f) { + g = g < limit ? g : limit; + u = u < -limit ? -limit : (u > limit ? limit : u); + } + ff[t][r] = g / (1.0f + std::exp(-g)) * u; + } +} + +void gg_cpu_down(const IqCpu& f, const uint8_t* down, const void* const* hq, int nt, float* const* out, int r0, int r1) { + dots(f.td, down, f.d_row, f.n_ff, hq, nt, out, r0, r1); +} + +// a row of any ggml block type -> BF16 on the host (the embedding table's reader; Q5_K / Q4_K / Q6_K / Q8_0 rows of a +// GGUF whose dense tensors are not BF16): ggml's own to_float, then the same round-to-nearest-even to BF16 the Q8_0 path uses +bool gg_row_to_bf16(int type, const uint8_t* row, int k, uint16_t* out) { + init_once(); + const ggml_type_traits* t = ggml_get_type_traits((ggml_type) type); + if (t == nullptr || t->to_float == nullptr) return false; + static thread_local std::vector f; + f.resize((size_t) k); + t->to_float(row, f.data(), k); + for (int i = 0; i < k; ++i) { + uint32_t u; + std::memcpy(&u, &f[(size_t) i], 4); + u += 0x7fffu + ((u >> 16) & 1u); + out[i] = (uint16_t) (u >> 16); + } + return true; +} +} // namespace strata::ds4::gguf +#else +namespace strata::ds4::gguf { +bool gg_cpu_type(int) { return false; } +bool gg_cpu_fmt(int, int, int, int, IqCpu&, std::string& err) { + err = "this build has no ggml-cpu lane (STRATA_NATIVE_EXPERTS=OFF)"; + return false; +} +void gg_cpu_quant(int, const float*, int, void*) {} +void gg_cpu_gate_up(const IqCpu&, const uint8_t*, const uint8_t*, const void* const*, int, float* const*, int, int, float) {} +void gg_cpu_down(const IqCpu&, const uint8_t*, const void* const*, int, float* const*, int, int) {} +bool gg_row_to_bf16(int, const uint8_t*, int, uint16_t*) { return false; } +} // namespace strata::ds4::gguf +#endif diff --git a/src/dsv41/ds4_gguf.cu b/src/dsv41/ds4_gguf.cu new file mode 100644 index 0000000..5bee588 --- /dev/null +++ b/src/dsv41/ds4_gguf.cu @@ -0,0 +1,1469 @@ +// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). +// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. +// src/ds4/ds4_gguf.cu - a GGUF's BF16 matrices and MXFP4 experts on the device (see ds4_gguf.cuh). +#include "ds4_gguf.cuh" + +#include "ds4_iq.cuh" +#include "ds4_numerics.cuh" + +#include +#if !defined(STRATA_USE_HIP) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::ds4::gguf { +namespace { + +std::atomic g_errors{0}; + +void check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "ds4 gguf %s: %s\n", what, cudaGetErrorString(e)); + g_errors.fetch_add(1, std::memory_order_relaxed); + } +} +void fail(const char* what) { + std::fprintf(stderr, "ds4 gguf %s\n", what); + g_errors.fetch_add(1, std::memory_order_relaxed); +} + +constexpr int kWarps = 8, kThreads = kWarps * 32; +constexpr int kMaxEnt = 16; // a group's entries in one pass (a window's tokens at most) + +__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; +} + +// ---------------------------------------------------------------- BF16 matrices +struct BfJob { + const void* w; + size_t ld; // values a row (BF16), bytes a row (MXFP4) + const float* x; + size_t xcs; + float* y; + size_t ycs; + const float* bias; + float alpha; + int k, n, ncol; + const int8_t* xq; // (Q8_0: the activations rounded to int8, q8_quant's) + const float* xd; +}; +struct BfJobs { + BfJob j[x3::kMaxMvJobs]; +}; + +// grid (max rows / 8, jobs): a warp a row, each of its activations' dot in F32 - a lane 8 BF16 weights (16 bytes) and +// 8 activations a step (VEC), or one of each (rows or activations not 16-byte aligned) +template +__global__ void __launch_bounds__(kThreads) bf16_mv_kernel(const BfJobs J) { + const BfJob& b = J.j[blockIdx.y]; + const int row = blockIdx.x * kWarps + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (row >= b.n) return; + const uint16_t* w = (const uint16_t*) b.w + (size_t) row * b.ld; + float acc[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) acc[c] = 0.0f; + if (VEC) { + for (int i = lane * 8; i < b.k; i += 256) { + const uint4 q = *(const uint4*) (w + i); + const float wf[8] = {__uint_as_float(q.x << 16), __uint_as_float(q.x & 0xffff0000u), + __uint_as_float(q.y << 16), __uint_as_float(q.y & 0xffff0000u), + __uint_as_float(q.z << 16), __uint_as_float(q.z & 0xffff0000u), + __uint_as_float(q.w << 16), __uint_as_float(q.w & 0xffff0000u)}; +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < b.ncol) { + const float4* xp = (const float4*) (b.x + c * b.xcs + i); + const float4 x0 = __ldg(xp), x1 = __ldg(xp + 1); + float a = acc[c]; + a = fmaf(wf[0], x0.x, a); + a = fmaf(wf[1], x0.y, a); + a = fmaf(wf[2], x0.z, a); + a = fmaf(wf[3], x0.w, a); + a = fmaf(wf[4], x1.x, a); + a = fmaf(wf[5], x1.y, a); + a = fmaf(wf[6], x1.z, a); + a = fmaf(wf[7], x1.w, a); + acc[c] = a; + } + } + } else { + for (int i = lane; i < b.k; i += 32) { + const float wf = __uint_as_float((uint32_t) w[i] << 16); +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < b.ncol) acc[c] = fmaf(wf, b.x[c * b.xcs + i], acc[c]); + } + } +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < b.ncol) { + const float v = warp_sum(acc[c]); + if (lane == 0) b.y[c * b.ycs + row] = b.alpha * v + (b.bias != nullptr ? b.bias[row] : 0.0f); + } +} + + +__global__ void q8_rows_kernel(const uint8_t* __restrict__ w, size_t ld, int k, int n, uint16_t* __restrict__ dst, + bool bf16) { + const size_t total = (size_t) n * (size_t) k; + for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (size_t) gridDim.x * blockDim.x) { + const size_t r = i / (size_t) k, c = i - r * (size_t) k; + const uint8_t* p = w + r * ld + (c / 32) * kQ8Bytes; + const float v = __half2float(__ushort_as_half(*(const uint16_t*) p)) * (float) (int8_t) p[2 + c % 32]; + dst[i] = bf16 ? strata::ds4::bf16_rn(v) : __half_as_ushort(__float2half_rn(v)); + } +} + +__global__ void bf16_rows_kernel(const uint16_t* __restrict__ w, size_t ld, int k, int n, uint16_t* __restrict__ dst, + bool bf16) { + const size_t total = (size_t) n * (size_t) k; + for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (size_t) gridDim.x * blockDim.x) { + const size_t r = i / (size_t) k, c = i - r * (size_t) k; + const uint16_t b = w[r * ld + c]; + dst[i] = bf16 ? b : __half_as_ushort(__float2half_rn(__uint_as_float((uint32_t) b << 16))); + } +} + +// ---------------------------------------------------------------- MXFP4 experts +__device__ __forceinline__ float e8m0_half(uint32_t e) { // 2^(e - 128), ggml's GGML_E8M0_TO_FP32_HALF + return __uint_as_float(e < 2 ? 0x00200000u << e : (e - 1) << 23); +} +__device__ __forceinline__ void lut_init(float* lut) { + if (threadIdx.x < 16) { + const float v[8] = {0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 6.0f, 8.0f, 12.0f}; + lut[threadIdx.x] = threadIdx.x < 8 ? v[threadIdx.x] : -v[threadIdx.x - 8]; + } +} +// block p's 32 values, exactly (a code times a power of two) +__device__ __forceinline__ void mx_block(const uint8_t* __restrict__ p, const float* lut, float* w) { + const float d = e8m0_half(p[0]); +#pragma unroll + for (int j = 0; j < 16; ++j) { + const uint32_t q = p[1 + j]; + w[j] = lut[q & 15u] * d; + w[j + 16] = lut[q >> 4] * d; + } +} +__device__ __forceinline__ float swiglu(float gv, float uv, float limit) { + if (limit > 0.0f) { + gv = fminf(gv, limit); + uv = fminf(fmaxf(uv, -limit), limit); + } + return __fmul_rn(__fdiv_rn(gv, __fadd_rn(1.0f, expf(-gv))), uv); +} +__device__ __forceinline__ float combine(const float* plan_w, const float* p, int k, const float* cpu_part, float sh) { + float m = 0.0f; + for (int i = 0; i < k; ++i) m = __fmaf_rn(plan_w[i], p[i], m); + if (cpu_part != nullptr) m = __fadd_rn(m, *cpu_part); + return __fadd_rn(m, sh); +} + +// a Q8_0 block's 32 values, exactly (an FP16 scale times an int8; the block is only 2-byte aligned) +__device__ __forceinline__ void q8_block(const uint8_t* __restrict__ p, float* w) { + const float d = __half2float(__ushort_as_half(*(const uint16_t*) p)); + const uint16_t* q = (const uint16_t*) (p + 2); +#pragma unroll + for (int j = 0; j < 16; ++j) { + const uint16_t v = q[j]; + w[2 * j] = d * (float) (int8_t) (v & 0xff); + w[2 * j + 1] = d * (float) (int8_t) (v >> 8); + } +} + +// ---- int8 activations (llama.cpp's MMVQ: its q8_1 blocks' rounding) +// rows of k F32 values (row r at x + r ldx; k % 32 == 0) -> q[r][k] int8 and d[r][k / 32] = max|x| / 127 per 32 +__global__ void __launch_bounds__(kThreads) q8_quant_kernel(const float* __restrict__ x, size_t ldx, int k, + int8_t* __restrict__ q, float* __restrict__ d) { + const int r = blockIdx.y, b = blockIdx.x * kWarps + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (b * 32 >= k) return; + const float v = x[(size_t) r * ldx + (size_t) b * 32 + lane]; + float am = fabsf(v); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o)); + const float sc = am / 127.0f; + q[(size_t) r * k + (size_t) b * 32 + lane] = (int8_t) (am > 0.0f ? __float2int_rn(v / sc) : 0); + if (lane == 0) d[(size_t) r * (k / 32) + b] = sc; +} +void q8_quant(const float* x, size_t ldx, int rows, int k, int8_t* q, float* d, cudaStream_t s) { + const dim3 grid((unsigned) ((k / 32 + kWarps - 1) / kWarps), (unsigned) rows); + q8_quant_kernel<<>>(x, ldx, k, q, d); +} + +// 8 E2M1 codes (a word of 4 code bytes) -> their values as int8: .x the low nibbles' (values 0..3 of the word's bytes), +// .y the high nibbles' - llama.cpp's get_int_from_table_16 (MIT), the table kvalues_mxfp4 +__device__ __forceinline__ int2 e2m1_x8(uint32_t q4) { + const uint32_t t0 = 0x03020100u, t1 = 0x0C080604u, t2 = 0xFDFEFF00u, t3 = 0xF4F8FAFCu; + const uint32_t sel = 0x32103210u | ((q4 & 0x88888888u) >> 1); + uint32_t tmp[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const uint32_t idx = (q4 >> (16 * i)) & 0x7777u; + const uint32_t lo = __byte_perm(t0, t1, idx), hi = __byte_perm(t2, t3, idx); + tmp[i] = __byte_perm(lo, hi, sel >> (16 * i)); + } + return make_int2((int) __byte_perm(tmp[0], tmp[1], 0x6420), (int) __byte_perm(tmp[0], tmp[1], 0x7531)); +} +// an MXFP4 block's codes (4 words) against 32 int8 activations (xa: values 0..15, xb: 16..31) +__device__ __forceinline__ int mx_dot(const uint4& q, const int4& xa, const int4& xb) { + int sum = 0; + int2 v = e2m1_x8(q.x); + sum = __dp4a(v.x, xa.x, sum); + sum = __dp4a(v.y, xb.x, sum); + v = e2m1_x8(q.y); + sum = __dp4a(v.x, xa.y, sum); + sum = __dp4a(v.y, xb.y, sum); + v = e2m1_x8(q.z); + sum = __dp4a(v.x, xa.z, sum); + sum = __dp4a(v.y, xb.z, sum); + v = e2m1_x8(q.w); + sum = __dp4a(v.x, xa.w, sum); + sum = __dp4a(v.y, xb.w, sum); + return sum; +} +// the warp copies the blocks [b0, b0 + nbk) of a row (BB bytes each; the row 4-byte aligned, nbk BB % 4 == 0) into its +// stage in 4-byte words; every lane calls it +template +__device__ __forceinline__ void stage_chunk(const uint8_t* row, int b0, int nbk, uint32_t* st) { + const uint32_t* src = (const uint32_t*) (row + (size_t) b0 * BB); + __syncwarp(); // (the lanes are done with the chunk before) + for (int i = threadIdx.x & 31; i < nbk * BB / 4; i += 32) st[i] = src[i]; + __syncwarp(); +} +// a row's next chunk of 32 blocks (BB bytes each) in the lanes' registers, then into the warp's stage +template +struct Fetch { + static constexpr int W = (32 * BB / 4 + 31) / 32; // words a lane + uint32_t r[W]; + int n = 0; + __device__ __forceinline__ void load(const uint8_t* row, int b0, int nbk) { + const uint32_t* src = (const uint32_t*) (row + (size_t) b0 * BB); + n = nbk * BB / 4; +#pragma unroll + for (int j = 0; j < W; ++j) { + const int i = (int) (threadIdx.x & 31) + 32 * j; + r[j] = i < n ? src[i] : 0u; + } + } + __device__ __forceinline__ void store(uint32_t* st) const { + __syncwarp(); // (the lanes are done with the chunk before) +#pragma unroll + for (int j = 0; j < W; ++j) { + const int i = (int) (threadIdx.x & 31) + 32 * j; + if (i < n) st[i] = r[j]; + } + __syncwarp(); + } +}; + +// MXFP4 block i of a stage (17-byte blocks from a 4-byte aligned start): its scale byte, its 16 code bytes as 4 words +__device__ __forceinline__ uint32_t mx_words_s(const uint32_t* st, int i, uint4& q) { + const int o = 17 * i, w = o >> 2, sh = (o & 3) * 8; + const uint32_t a0 = st[w], a1 = st[w + 1], a2 = st[w + 2], a3 = st[w + 3], a4 = st[w + 4]; + const uint32_t s0 = __funnelshift_r(a0, a1, sh), s1 = __funnelshift_r(a1, a2, sh), s2 = __funnelshift_r(a2, a3, sh), + s3 = __funnelshift_r(a3, a4, sh), s4 = a4 >> sh; + q.x = __funnelshift_r(s0, s1, 8); + q.y = __funnelshift_r(s1, s2, 8); + q.z = __funnelshift_r(s2, s3, 8); + q.w = __funnelshift_r(s3, s4, 8); + return s0 & 0xffu; +} +// ... the same from global memory, byte by byte (rows not 4-byte aligned) +__device__ __forceinline__ uint32_t mx_words_g(const uint8_t* __restrict__ p, uint4& q) { + uint32_t w[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) + w[j] = (uint32_t) p[1 + 4 * j] | (uint32_t) p[2 + 4 * j] << 8 | (uint32_t) p[3 + 4 * j] << 16 | + (uint32_t) p[4 + 4 * j] << 24; + q = make_uint4(w[0], w[1], w[2], w[3]); + return p[0]; +} +// Q8_0 block i of a stage (34-byte blocks): its scale, its 32 int8 as 8 words +__device__ __forceinline__ float q8_words_s(const uint32_t* st, int i, int* v) { + const int o = 34 * i, w = o >> 2, sh = (o & 3) * 8; + uint32_t a[9]; +#pragma unroll + for (int j = 0; j < 9; ++j) a[j] = st[w + j]; + uint32_t sw[9]; +#pragma unroll + for (int j = 0; j < 8; ++j) sw[j] = __funnelshift_r(a[j], a[j + 1], sh); + sw[8] = a[8] >> sh; +#pragma unroll + for (int j = 0; j < 8; ++j) v[j] = (int) __funnelshift_r(sw[j], sw[j + 1], 16); + return __half2float(__ushort_as_half((uint16_t) (sw[0] & 0xffffu))); +} +__device__ __forceinline__ float q8_words_g(const uint8_t* __restrict__ p, int* v) { +#pragma unroll + for (int j = 0; j < 8; ++j) + v[j] = (int) ((uint32_t) p[2 + 4 * j] | (uint32_t) p[3 + 4 * j] << 8 | (uint32_t) p[4 + 4 * j] << 16 | + (uint32_t) p[5 + 4 * j] << 24); + return __half2float(__ushort_as_half((uint16_t) (p[0] | p[1] << 8))); +} + +// grid (max rows / 8, jobs): a Q8_0 matrix's rows against the jobs' int8 activations (q8_quant's: activation c of job +// j at xq + c k, its scales at xd + c k / 32) - a warp a row, a lane a block a step, the blocks staged (ST) or read +template +__global__ void __launch_bounds__(kThreads) q8_mv_kernel(const BfJobs J) { + __shared__ __align__(16) uint32_t stage[kWarps][32 * kQ8Bytes / 4]; + const BfJob& b = J.j[blockIdx.y]; + const int row = blockIdx.x * kWarps + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (row >= b.n) return; + const uint8_t* w = (const uint8_t*) b.w + (size_t) row * b.ld; + const int nb = b.k / 32; + float acc[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) acc[c] = 0.0f; + Fetch F; + if (ST) F.load(w, 0, min(32, nb)); + for (int b0 = 0; b0 < nb; b0 += 32) { + const int nbk = min(32, nb - b0), kb = b0 + lane; + if (ST) { + F.store(stage[threadIdx.x >> 5]); + if (b0 + 32 < nb) F.load(w, b0 + 32, min(32, nb - b0 - 32)); + } + if (lane >= nbk) continue; + int v[8]; + const float dw = ST ? q8_words_s(stage[threadIdx.x >> 5], lane, v) : q8_words_g(w + (size_t) kb * kQ8Bytes, v); +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < b.ncol) { + const int4* xp = (const int4*) (b.xq + (size_t) c * b.k + (size_t) kb * 32); + const int4 xa = xp[0], xb = xp[1]; + int sum = __dp4a(v[0], xa.x, 0); + sum = __dp4a(v[1], xa.y, sum); + sum = __dp4a(v[2], xa.z, sum); + sum = __dp4a(v[3], xa.w, sum); + sum = __dp4a(v[4], xb.x, sum); + sum = __dp4a(v[5], xb.y, sum); + sum = __dp4a(v[6], xb.z, sum); + sum = __dp4a(v[7], xb.w, sum); + acc[c] = fmaf(dw * b.xd[(size_t) c * nb + kb], (float) sum, acc[c]); + } + } +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < b.ncol) { + const float v = warp_sum(acc[c]); + if (lane == 0) b.y[c * b.ycs + row] = b.alpha * v + (b.bias != nullptr ? b.bias[row] : 0.0f); + } +} + +// grid (max rows / 8, jobs): bf16_mv_kernel for MXFP4 (Q8 false) or Q8_0 (Q8 true) matrices - a lane a 32-value block +// a step, dequantised once for the job's activations +template +__global__ void __launch_bounds__(kThreads) mx_mv_kernel(const BfJobs J) { + __shared__ float lut[16]; + lut_init(lut); + __syncthreads(); + const BfJob& b = J.j[blockIdx.y]; + const int row = blockIdx.x * kWarps + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (row >= b.n) return; + const uint8_t* w = (const uint8_t*) b.w + (size_t) row * b.ld; + float acc[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) acc[c] = 0.0f; + for (int kb = lane; kb < b.k / kMxBlock; kb += 32) { + float wv[32]; + if (Q8) q8_block(w + (size_t) kb * kQ8Bytes, wv); + else mx_block(w + (size_t) kb * kMxBytes, lut, wv); +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < b.ncol) { + const float* x = b.x + c * b.xcs + kb * kMxBlock; + float a = acc[c]; + if (VEC) { +#pragma unroll + for (int q = 0; q < 8; ++q) { + const float4 xv = __ldg((const float4*) x + q); + a = fmaf(wv[4 * q], xv.x, a); + a = fmaf(wv[4 * q + 1], xv.y, a); + a = fmaf(wv[4 * q + 2], xv.z, a); + a = fmaf(wv[4 * q + 3], xv.w, a); + } + } else { +#pragma unroll + for (int j = 0; j < 32; ++j) a = fmaf(wv[j], x[j], a); + } + acc[c] = a; + } + } +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < b.ncol) { + const float v = warp_sum(acc[c]); + if (lane == 0) b.y[c * b.ycs + row] = b.alpha * v + (b.bias != nullptr ? b.bias[row] : 0.0f); + } +} + +// a token's experts (grp_ptr null: group i = expert i of the plan, plan_ptr[i] its blob or 0 off the device, its one +// entry i, every entry's input x) or a window's groups (group g: one expert, blob grp_ptr[g], entries e = t * 8 + i at +// grp_ent[grp_start[g] ..), entry e's input x + (e >> 3) x_stride) +struct MxArgs { + const unsigned long long* plan_ptr; + const unsigned long long* grp_ptr; + const int *grp_start, *grp_ent, *n_groups; + const float* x; + size_t x_stride; + float* h; // [entries][n_ff] + float* part; // [entries][n_embd] + size_t tr[3]; + int n_embd, n_ff; + float limit; + const int8_t* xq; // x rounded to int8 (a token's: row 0; a window's: row t), q8_quant's rows of n_embd + const float* xd; + const int8_t* hq; // h rounded to int8, row e = the entry, rows of n_ff + const float* hd; +}; + +__device__ __forceinline__ bool mx_group(const MxArgs& a, int grp, const uint8_t*& blob, int& m0, int& m1) { + if (a.grp_ptr == nullptr) { + const unsigned long long p = a.plan_ptr[grp]; + if (p == 0ull) return false; + blob = (const uint8_t*) p; + m0 = grp; + m1 = grp + 1; + return true; + } + if (grp >= *a.n_groups) return false; + blob = (const uint8_t*) a.grp_ptr[grp]; + m0 = a.grp_start[grp]; + m1 = a.grp_start[grp + 1]; + return true; +} + +// grid (n_ff / 8, groups): a warp a row of the gate and of the up, for NE of the group's entries a pass (each weight +// block decoded once for them) against the entries' int8 x -> h = the clamped swiglu +template +__global__ void __launch_bounds__(kThreads) mx_gate_up_kernel(const MxArgs a) { + __shared__ __align__(16) uint32_t stage[kWarps][2][32 * kMxBytes / 4]; + __shared__ int es[NE], xr[NE]; + const uint8_t* blob; + int m0, m1; + if (!mx_group(a, blockIdx.y, blob, m0, m1)) return; // (uniform) + const int row = blockIdx.x * kWarps + (threadIdx.x >> 5), lane = threadIdx.x & 31, wp = threadIdx.x >> 5; + const size_t rb = mx_row_bytes(a.n_embd); + const uint8_t* g = blob + a.tr[0] + (size_t) row * rb; + const uint8_t* u = blob + a.tr[1] + (size_t) row * rb; + const int nb = a.n_embd / kMxBlock; + for (int mm = m0; mm < m1; mm += NE) { + const int ne = min(NE, m1 - mm); + __syncthreads(); + if ((int) threadIdx.x < ne) { + const int e = a.grp_ptr != nullptr ? a.grp_ent[mm + threadIdx.x] : mm + threadIdx.x; + es[threadIdx.x] = e; + xr[threadIdx.x] = a.grp_ptr != nullptr ? e >> 3 : 0; + } + __syncthreads(); + if (row >= a.n_ff) continue; + float ag[NE], au[NE]; +#pragma unroll + for (int i = 0; i < NE; ++i) ag[i] = au[i] = 0.0f; + Fetch FG, FU; + if (ST) { + FG.load(g, 0, min(32, nb)); + FU.load(u, 0, min(32, nb)); + } + for (int b0 = 0; b0 < nb; b0 += 32) { + const int nbk = min(32, nb - b0), b = b0 + lane; + if (ST) { + FG.store(stage[wp][0]); + FU.store(stage[wp][1]); + if (b0 + 32 < nb) { + FG.load(g, b0 + 32, min(32, nb - b0 - 32)); + FU.load(u, b0 + 32, min(32, nb - b0 - 32)); + } + } + if (lane >= nbk) continue; + uint4 qg, qu; + const uint32_t eg = ST ? mx_words_s(stage[wp][0], lane, qg) : mx_words_g(g + (size_t) b * kMxBytes, qg); + const uint32_t eu = ST ? mx_words_s(stage[wp][1], lane, qu) : mx_words_g(u + (size_t) b * kMxBytes, qu); + const float dg = e8m0_half(eg), du = e8m0_half(eu); +#pragma unroll + for (int i = 0; i < NE; ++i) + if (i < ne) { + const int4* xp = (const int4*) (a.xq + (size_t) xr[i] * a.n_embd + (size_t) b * kMxBlock); + const int4 xa = xp[0], xb = xp[1]; + const float dx = a.xd[(size_t) xr[i] * nb + b]; + ag[i] = fmaf(dg * dx, (float) mx_dot(qg, xa, xb), ag[i]); + au[i] = fmaf(du * dx, (float) mx_dot(qu, xa, xb), au[i]); + } + } +#pragma unroll + for (int i = 0; i < NE; ++i) + if (i < ne) { + const float gv = warp_sum(ag[i]), uv = warp_sum(au[i]); + if (lane == 0) a.h[(size_t) es[i] * a.n_ff + row] = swiglu(gv, uv, a.limit); + } + } +} + +// grid (n_embd / 8, groups): a warp a row of the down for NE entries a pass, against their int8 h -> part +template +__global__ void __launch_bounds__(kThreads) mx_down_kernel(const MxArgs a) { + __shared__ __align__(16) uint32_t stage[kWarps][32 * kMxBytes / 4]; + __shared__ int es[NE]; + const uint8_t* blob; + int m0, m1; + if (!mx_group(a, blockIdx.y, blob, m0, m1)) return; + const int row = blockIdx.x * kWarps + (threadIdx.x >> 5), lane = threadIdx.x & 31, wp = threadIdx.x >> 5; + const uint8_t* d = blob + a.tr[2] + (size_t) row * mx_row_bytes(a.n_ff); + const int nb = a.n_ff / kMxBlock; + for (int mm = m0; mm < m1; mm += NE) { + const int ne = min(NE, m1 - mm); + __syncthreads(); + if ((int) threadIdx.x < ne) es[threadIdx.x] = a.grp_ptr != nullptr ? a.grp_ent[mm + threadIdx.x] : mm + threadIdx.x; + __syncthreads(); + if (row >= a.n_embd) continue; + float ad[NE]; +#pragma unroll + for (int i = 0; i < NE; ++i) ad[i] = 0.0f; + Fetch FD; + if (ST) FD.load(d, 0, min(32, nb)); + for (int b0 = 0; b0 < nb; b0 += 32) { + const int nbk = min(32, nb - b0), b = b0 + lane; + if (ST) { + FD.store(stage[wp]); + if (b0 + 32 < nb) FD.load(d, b0 + 32, min(32, nb - b0 - 32)); + } + if (lane >= nbk) continue; + uint4 q; + const float dd = e8m0_half(ST ? mx_words_s(stage[wp], lane, q) : mx_words_g(d + (size_t) b * kMxBytes, q)); +#pragma unroll + for (int i = 0; i < NE; ++i) + if (i < ne) { + const int4* hp = (const int4*) (a.hq + (size_t) es[i] * a.n_ff + (size_t) b * kMxBlock); + const int4 ha = hp[0], hb = hp[1]; + ad[i] = fmaf(dd * a.hd[(size_t) es[i] * nb + b], (float) mx_dot(q, ha, hb), ad[i]); + } + } +#pragma unroll + for (int i = 0; i < NE; ++i) + if (i < ne) { + const float v = warp_sum(ad[i]); + if (lane == 0) a.part[(size_t) es[i] * a.n_embd + row] = v; + } + } +} + +struct CombArgs { + const unsigned long long* plan_ptr; // [T][8] + const float* plan_w; // [T][8] + const float* part; // [T * 8][n_embd] + const float* cpu_part; + size_t cpu_stride; + const int* cpu_flag; + const float* sh_out; // [T][n_embd] + float* out; + size_t out_stride; + int k, n_embd; +}; +// grid (n_embd / 128, T): each token's outputs - the experts in plan order (an expert off the device adds 0), then +// the CPU lane's part and the shared expert's (x3's combine) +__global__ void __launch_bounds__(128) mx_combine_kernel(const CombArgs a) { + const int t = blockIdx.y, r = blockIdx.x * 128 + threadIdx.x; + if (r >= a.n_embd) return; + float p[8]; + for (int i = 0; i < a.k; ++i) { + const int e = t * 8 + i; + p[i] = a.plan_ptr[e] != 0ull ? a.part[(size_t) e * a.n_embd + r] : 0.0f; + } + a.out[(size_t) t * a.out_stride + r] = + combine(a.plan_w + t * 8, p, a.k, + a.cpu_flag != nullptr && a.cpu_flag[t] ? a.cpu_part + (size_t) t * a.cpu_stride + r : nullptr, + a.sh_out != nullptr ? a.sh_out[(size_t) t * a.n_embd + r] : 0.0f); +} + +__global__ void mx_wait_kernel(const unsigned* p, unsigned v) { + if (threadIdx.x != 0) return; + while (*(volatile const unsigned*) p != v) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 + __nanosleep(200); +#endif + } + __threadfence_system(); +} + +// ---------------------------------------------------------------- the prompt path's expert sets +// a set's expert i (blob wbase + i stride) owns the sorted rows [bounds[i], bounds[i + 1]); local row = sorted row - +// row0. A block: BM of its rows x BN outputs, the weights dequantised a 32-value block at a time into shared memory, +// F32 FMAs (each thread TM x TN outputs) +constexpr int BM = 64, BN = 64, TM = 4, TN = 4; +static_assert((BM / TM) * (BN / TN) == kThreads, "one output tile a thread"); + +struct SetK { + const uint8_t* wbase; + size_t stride; + size_t tr[3]; + const int* bounds; + int row0; + int n_embd, n_ff; + float limit; + const float* xf; // gate / up: F32 input rows x[idx[local]] (ldx) + const int* idx; + const __half* xh; // down: F16 rows (ldx) + int ldx; + __half* h; // gate / up: F16 out + float* y; // down: F32 out + int ldo; + int skip_le; // the experts of at most this many rows left out (the light kernels took them; ds4_iq.cuh) +}; + +// one 32-value block of BN weight rows (rows c0 .., row bytes rb, block kb) -> ws[32][BN + 1] +__device__ __forceinline__ void mx_tile(const uint8_t* w, size_t rb, int c0, int kb, const float* lut, + float (*ws)[BN + 1]) { + const int r = threadIdx.x >> 2, q = threadIdx.x & 3; // row r of the tile, values [8 q, 8 q + 8) + const uint8_t* p = w + (size_t) (c0 + r) * rb + (size_t) kb * kMxBytes; + const float d = e8m0_half(p[0]); + const int b0 = (q & 1) * 8, hi = q >> 1; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint32_t c = p[1 + b0 + j]; + ws[q * 8 + j][r] = lut[hi ? (c >> 4) : (c & 15u)] * d; + } +} + +template +__global__ void __launch_bounds__(kThreads) mx_set_kernel(const SetK a) { + __shared__ float lut[16]; + __shared__ float wg[32][BN + 1]; + __shared__ float wu[GATE_UP ? 32 : 1][BN + 1]; + __shared__ float xs[BM][33]; + __shared__ int src[BM]; + lut_init(lut); + const int e = blockIdx.z; + const int lo = a.bounds[e] - a.row0, hi = a.bounds[e + 1] - a.row0; + const int r0 = lo + blockIdx.x * BM; + if (r0 >= hi || hi - lo <= a.skip_le) return; // (uniform: before any barrier but lut_init's writes, which nobody + // reads then; skip_le: the light kernels' experts) + const int nr = min(BM, hi - r0); + const int c0 = blockIdx.y * BN; + const uint8_t* blob = a.wbase + (size_t) e * a.stride; + const int K = GATE_UP ? a.n_embd : a.n_ff; + const size_t rb = mx_row_bytes(K); + const int tid = (int) threadIdx.x; + if (tid < BM) src[tid] = tid < nr ? (GATE_UP ? a.idx[r0 + tid] : r0 + tid) : -1; + __syncthreads(); + const int ty = threadIdx.x / (BN / TN), tx = threadIdx.x % (BN / TN); + float ag[TM][TN], au[TM][TN]; +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) ag[i][j] = au[i][j] = 0.0f; + for (int kb = 0; kb < K / kMxBlock; ++kb) { + mx_tile(blob + a.tr[GATE_UP ? 0 : 2], rb, c0, kb, lut, wg); + if (GATE_UP) mx_tile(blob + a.tr[1], rb, c0, kb, lut, wu); + for (int i = threadIdx.x; i < BM * kMxBlock; i += kThreads) { // the rows' 32 inputs + const int r = i / kMxBlock, c = i % kMxBlock, sr = src[r]; + float v = 0.0f; + if (sr >= 0) { + const size_t at = (size_t) sr * a.ldx + (size_t) kb * kMxBlock + c; + v = GATE_UP ? a.xf[at] : __half2float(a.xh[at]); + } + xs[r][c] = v; + } + __syncthreads(); +#pragma unroll 8 + for (int kk = 0; kk < kMxBlock; ++kk) { + float xv[TM], gw[TN], uw[TN]; +#pragma unroll + for (int i = 0; i < TM; ++i) xv[i] = xs[ty * TM + i][kk]; +#pragma unroll + for (int j = 0; j < TN; ++j) { + gw[j] = wg[kk][tx * TN + j]; + if (GATE_UP) uw[j] = wu[kk][tx * TN + j]; + } +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) { + ag[i][j] = fmaf(xv[i], gw[j], ag[i][j]); + if (GATE_UP) au[i][j] = fmaf(xv[i], uw[j], au[i][j]); + } + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < TM; ++i) { + const int r = ty * TM + i; + if (r >= nr) continue; + const size_t lr = (size_t) (r0 + r); +#pragma unroll + for (int j = 0; j < TN; ++j) { + const int c = c0 + tx * TN + j; + if (GATE_UP) a.h[lr * a.ldo + c] = __float2half_rn(swiglu(ag[i][j], au[i][j], a.limit)); + else a.y[lr * a.ldo + c] = ag[i][j]; + } + } +} + +// the same on the tensor cores: a block BM rows x BN outputs, 8 warps each 16 rows x 32 outputs (2 fragments, gate and +// up: 4), a 32-value MXFP4 block of K a step (2 WMMA k-steps), the tiles in shared memory as F16 +#if !defined(STRATA_USE_HIP) +namespace wm = nvcuda::wmma; +constexpr int kLdT = 40; // halves a tile row (32 + 8: WMMA wants a multiple of 8; the pad spreads the banks) +template +__global__ void __launch_bounds__(kThreads) mx_set_tc_kernel(const SetK a) { + struct Tiles { + __half x[BM][kLdT], wg[BN][kLdT], wu[GATE_UP ? BN : 1][kLdT]; + }; + struct Out { + float g[BM][BN + 4], u[GATE_UP ? BM : 1][BN + 4]; + }; + __shared__ __align__(32) unsigned char smem[sizeof(Tiles) > sizeof(Out) ? sizeof(Tiles) : sizeof(Out)]; + __shared__ float lut[16]; + __shared__ int src[BM]; + Tiles& T = *reinterpret_cast(smem); + Out& O = *reinterpret_cast(smem); + lut_init(lut); + const int e = blockIdx.z; + const int lo = a.bounds[e] - a.row0, hi = a.bounds[e + 1] - a.row0; + const int r0 = lo + blockIdx.x * BM; + if (r0 >= hi || hi - lo <= a.skip_le) return; // (uniform; skip_le: the light kernels' experts) + const int nr = min(BM, hi - r0); + const int c0 = blockIdx.y * BN; + const uint8_t* blob = a.wbase + (size_t) e * a.stride; + const int K = GATE_UP ? a.n_embd : a.n_ff; + const size_t rb = mx_row_bytes(K); + const int tid = (int) threadIdx.x, warp = tid >> 5; + if (tid < BM) src[tid] = tid < nr ? (GATE_UP ? a.idx[r0 + tid] : r0 + tid) : -1; + __syncthreads(); + const int wm_ = warp >> 1, wn = (warp & 1) * 2; // the warp's 16 rows, its 2 x 16 outputs + wm::fragment fg[2], fu[2]; + for (int j = 0; j < 2; ++j) { + wm::fill_fragment(fg[j], 0.0f); + wm::fill_fragment(fu[j], 0.0f); + } + const int tr = tid >> 2, tq = tid & 3; // the thread's tile row, its 8 values [8 tq, 8 tq + 8) + for (int kb = 0; kb < K / kMxBlock; ++kb) { + { // the weights: row tr of the outputs, values 8 tq .. + for (int m = 0; m < (GATE_UP ? 2 : 1); ++m) { + const uint8_t* q = blob + a.tr[GATE_UP ? m : 2] + (size_t) (c0 + tr) * rb + (size_t) kb * kMxBytes; + const float d = e8m0_half(q[0]); + const int b0 = (tq & 1) * 8, hn = tq >> 1; + __half* dst = m == 0 ? &T.wg[tr][tq * 8] : &T.wu[tr][tq * 8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint32_t c = q[1 + b0 + j]; + dst[j] = __float2half_rn(lut[hn ? (c >> 4) : (c & 15u)] * d); + } + } + // the inputs: row tr, values 8 tq .. + const int sr = src[tr]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + __half v = __float2half_rn(0.0f); + if (sr >= 0) { + const size_t at = (size_t) sr * a.ldx + (size_t) kb * kMxBlock + tq * 8 + j; + v = GATE_UP ? __float2half_rn(a.xf[at]) : a.xh[at]; + } + T.x[tr][tq * 8 + j] = v; + } + } + __syncthreads(); +#pragma unroll + for (int kk = 0; kk < 32; kk += 16) { + wm::fragment fa; + wm::load_matrix_sync(fa, &T.x[wm_ * 16][kk], kLdT); +#pragma unroll + for (int j = 0; j < 2; ++j) { + wm::fragment fb; + wm::load_matrix_sync(fb, &T.wg[(wn + j) * 16][kk], kLdT); + wm::mma_sync(fg[j], fa, fb, fg[j]); + if (GATE_UP) { + wm::load_matrix_sync(fb, &T.wu[(wn + j) * 16][kk], kLdT); + wm::mma_sync(fu[j], fa, fb, fu[j]); + } + } + } + __syncthreads(); + } + for (int j = 0; j < 2; ++j) { + wm::store_matrix_sync(&O.g[wm_ * 16][(wn + j) * 16], fg[j], BN + 4, wm::mem_row_major); + if (GATE_UP) wm::store_matrix_sync(&O.u[wm_ * 16][(wn + j) * 16], fu[j], BN + 4, wm::mem_row_major); + } + __syncthreads(); + for (int i = tid; i < BM * BN; i += kThreads) { + const int r = i / BN, c = i % BN; + if (r >= nr) continue; + const size_t lr = (size_t) (r0 + r); + if (GATE_UP) a.h[lr * a.ldo + c0 + c] = __float2half_rn(swiglu(O.g[r][c], O.u[r][c], a.limit)); + else a.y[lr * a.ldo + c0 + c] = O.g[r][c]; + } +} +#endif +#if defined(STRATA_USE_HIP) +// the same on an AMD wave32 GPU's WMMA (RDNA3 / RDNA3.5 gfx11, RDNA4 gfx12): 8 waves each 16 rows x 32 outputs, the +// tiles in shared memory as F16, F32 accumulation - each lane gives its row / column's 16 values of a k-step (gfx12: +// its half of them), and holds 8 of the 16 x 16 results (rows 2 i + hi on gfx11, 8 hi + i on gfx12; column lane % 16) +using h16v = _Float16 __attribute__((ext_vector_type(16))); +using f8v = float __attribute__((ext_vector_type(8))); +__device__ __forceinline__ f8v set_wmma(h16v a, h16v b, f8v c) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \ + defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#elif defined(__gfx1200__) || defined(__gfx1201__) + using h8 = _Float16 __attribute__((ext_vector_type(8))); + const int k0 = (threadIdx.x & 31) / 16 * 8; + h8 aa, bb; +#pragma unroll + for (int i = 0; i < 8; ++i) { + aa[i] = a[k0 + i]; + bb[i] = b[k0 + i]; + } + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(aa, bb, c); +#else + __builtin_trap(); + return c; +#endif +} +__device__ __forceinline__ int set_wmma_row(int i, int hi) { +#if defined(__gfx1200__) || defined(__gfx1201__) + return 8 * hi + i; +#else + return 2 * i + hi; +#endif +} +constexpr int kLdH = 40; // halves a tile row (32 + 8: the pad spreads the banks) +template +__global__ void __launch_bounds__(kThreads) mx_set_wmma_kernel(const SetK a) { + struct Tiles { + _Float16 x[BM][kLdH], wg[BN][kLdH], wu[GATE_UP ? BN : 1][kLdH]; + }; + struct Out { + float g[BM][BN + 4], u[GATE_UP ? BM : 1][BN + 4]; + }; + __shared__ __align__(16) unsigned char smem[sizeof(Tiles) > sizeof(Out) ? sizeof(Tiles) : sizeof(Out)]; + __shared__ float lut[16]; + __shared__ int src[BM]; + Tiles& T = *reinterpret_cast(smem); + Out& O = *reinterpret_cast(smem); + lut_init(lut); + const int e = blockIdx.z; + const int lo = a.bounds[e] - a.row0, hi_r = a.bounds[e + 1] - a.row0; + const int r0 = lo + blockIdx.x * BM; + if (r0 >= hi_r || hi_r - lo <= a.skip_le) return; // (uniform; skip_le: the light kernels' experts) + const int nr = min(BM, hi_r - r0); + const int c0 = blockIdx.y * BN; + const uint8_t* blob = a.wbase + (size_t) e * a.stride; + const int K = GATE_UP ? a.n_embd : a.n_ff; + const size_t rb = mx_row_bytes(K); + const int tid = (int) threadIdx.x, warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4; + if (tid < BM) src[tid] = tid < nr ? (GATE_UP ? a.idx[r0 + tid] : r0 + tid) : -1; + __syncthreads(); + const int wm_ = warp >> 1, wn = (warp & 1) * 2; // the wave's 16 rows, its 2 x 16 outputs + f8v fg[2], fu[2]; +#pragma unroll + for (int j = 0; j < 2; ++j) +#pragma unroll + for (int i = 0; i < 8; ++i) fg[j][i] = fu[j][i] = 0.0f; + const int tr = tid >> 2, tq = tid & 3; // the thread's tile row, its 8 values [8 tq, 8 tq + 8) + for (int kb = 0; kb < K / kMxBlock; ++kb) { + for (int m = 0; m < (GATE_UP ? 2 : 1); ++m) { + const uint8_t* q = blob + a.tr[GATE_UP ? m : 2] + (size_t) (c0 + tr) * rb + (size_t) kb * kMxBytes; + const float d = e8m0_half(q[0]); + const int b0 = (tq & 1) * 8, hn = tq >> 1; + _Float16* dst = m == 0 ? &T.wg[tr][tq * 8] : &T.wu[tr][tq * 8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint32_t cc = q[1 + b0 + j]; + dst[j] = (_Float16) (lut[hn ? (cc >> 4) : (cc & 15u)] * d); + } + } + const int sr = src[tr]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + float v = 0.0f; + if (sr >= 0) { + const size_t at = (size_t) sr * a.ldx + (size_t) kb * kMxBlock + tq * 8 + j; + v = GATE_UP ? a.xf[at] : __half2float(a.xh[at]); + } + T.x[tr][tq * 8 + j] = (_Float16) v; + } + __syncthreads(); +#pragma unroll + for (int kk = 0; kk < 32; kk += 16) { + h16v av; +#pragma unroll + for (int i = 0; i < 16; ++i) av[i] = T.x[wm_ * 16 + l16][kk + i]; +#pragma unroll + for (int j = 0; j < 2; ++j) { + h16v bv; +#pragma unroll + for (int i = 0; i < 16; ++i) bv[i] = T.wg[(wn + j) * 16 + l16][kk + i]; + fg[j] = set_wmma(av, bv, fg[j]); + if (GATE_UP) { +#pragma unroll + for (int i = 0; i < 16; ++i) bv[i] = T.wu[(wn + j) * 16 + l16][kk + i]; + fu[j] = set_wmma(av, bv, fu[j]); + } + } + } + __syncthreads(); + } +#pragma unroll + for (int j = 0; j < 2; ++j) +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int r = wm_ * 16 + set_wmma_row(i, hi), cc = (wn + j) * 16 + l16; + O.g[r][cc] = fg[j][i]; + if (GATE_UP) O.u[r][cc] = fu[j][i]; + } + __syncthreads(); + for (int i = tid; i < BM * BN; i += kThreads) { + const int r = i / BN, cc = i % BN; + if (r >= nr) continue; + const size_t lr = (size_t) (r0 + r); + if (GATE_UP) a.h[lr * a.ldo + c0 + cc] = __float2half_rn(swiglu(O.g[r][cc], O.u[r][cc], a.limit)); + else a.y[lr * a.ldo + c0 + cc] = O.g[r][cc]; + } +} +#endif +bool tc_ok() { // sm_70 and later (WMMA F16) / AMD gfx11, gfx12 (wave32 WMMA); STRATA_DS4_NO_TC=1 keeps the F32 kernel +#if defined(STRATA_USE_HIP) + static const bool ok = [] { + int dev = 0; + cudaGetDevice(&dev); + cudaDeviceProp prop{}; + if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess) return false; + const char* v = std::getenv("STRATA_DS4_NO_TC"); + if (v != nullptr && v[0] == '1') return false; + const char* arch = prop.gcnArchName; + for (const char* p : {"gfx1100", "gfx1101", "gfx1102", "gfx1103", "gfx1150", "gfx1151", "gfx1152", "gfx1200", "gfx1201"}) + if (std::strncmp(arch, p, 7) == 0) return true; + return false; + }(); + return ok; +#else + static const bool ok = [] { + int dev = 0, major = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + const char* v = std::getenv("STRATA_DS4_NO_TC"); + return major >= 7 && !(v != nullptr && v[0] == '1'); + }(); + return ok; +#endif +} + +// ---------------------------------------------------------------- scratch +constexpr int kMaxEmbd = 8192; +constexpr int kMaxQK = 32768; // a Q8_0 GEMV's inputs at most +struct Scratch { + float* part = nullptr; // [8][kMaxEmbd]: a token's experts' down outputs + int8_t *xq = nullptr, *hq = nullptr, *mq = nullptr; // int8 rows: x [kMaxEnt], h [kMaxEnt * 8], the GEMVs' + float *xd = nullptr, *hd = nullptr, *md = nullptr; // [kMaxMvJobs * kMaxMvCols] inputs; their scales +}; +std::mutex g_mu; +std::unordered_map g_scratch; + +Scratch* scratch(cudaStream_t s) { + std::lock_guard lk(g_mu); + auto it = g_scratch.find(s); + if (it != g_scratch.end()) return &it->second; + Scratch sc; + const size_t nx = (size_t) kMaxEnt * kMaxEmbd, nh = (size_t) kMaxEnt * 8 * kMaxEmbd, + nm = (size_t) x3::kMaxMvJobs * x3::kMaxMvCols * kMaxQK; + if (cudaMalloc(&sc.part, (size_t) 8 * kMaxEmbd * sizeof(float)) != cudaSuccess || + cudaMalloc(&sc.xq, nx) != cudaSuccess || cudaMalloc(&sc.xd, nx / 32 * 4) != cudaSuccess || + cudaMalloc(&sc.hq, nh) != cudaSuccess || cudaMalloc(&sc.hd, nh / 32 * 4) != cudaSuccess || + cudaMalloc(&sc.mq, nm) != cudaSuccess || cudaMalloc(&sc.md, nm / 32 * 4) != cudaSuccess) { + fail("scratch: cudaMalloc failed"); + return nullptr; + } + return &g_scratch.emplace(s, sc).first->second; +} + +bool mx_geometry(const char* who, int k, int n_embd, int n_ff) { + if (k < 1 || k > 8 || n_embd % BN != 0 || n_ff % BN != 0 || n_embd > kMaxEmbd || n_ff % kMxBlock != 0) { + std::fprintf(stderr, "ds4 gguf %s: geometry not covered (k %d n_embd %d n_ff %d)\n", who, k, n_embd, n_ff); + g_errors.fetch_add(1, std::memory_order_relaxed); + return false; + } + return true; +} + +} // namespace + +// ---------------------------------------------------------------- entry points +bool prepare(cudaStream_t s) { return scratch(s) != nullptr; } + +int launch_errors() { return g_errors.load(std::memory_order_relaxed); } + +size_t type_row_bytes(int type, int64_t k) { + if (type == kTypeMXFP4) return k % kMxBlock == 0 ? mx_row_bytes(k) : 0; + // known(), not supported(): a type with no device kernel still has a layout, and its rows are read by the CPU lane + return iq::known(type) && k % iq::block_values(type) == 0 ? iq::row_bytes(type, k) : 0; +} +int type_block(int type) { return type == kTypeMXFP4 ? kMxBlock : iq::known(type) ? iq::block_values(type) : 0; } +const char* type_name(int type) { return type == kTypeMXFP4 ? "MXFP4" : iq::name(type); } +bool type_on_device(int type) { return type == kTypeMXFP4 || iq::supported(type); } + +namespace { +size_t row_stride(const x3::Mat& m) { // values (BF16) or bytes (MXFP4, Q8_0, a low-bit type) a row + if (m.ld > 0) return (size_t) m.ld; + return m.fmt == kFmtMXFP4 ? mx_row_bytes(m.k) + : m.fmt == kFmtQ8_0 ? q8_row_bytes(m.k) + : m.fmt == kFmtGG ? type_row_bytes(m.K, m.k) + : (size_t) m.k; +} +// a layer's low-bit experts as ds4_iq's arguments (false: its types not covered - printed) +bool iq_args(const x3::ExpertLayout& lay, int n_embd, int n_ff, float limit, iq::Args& ia, const char* who) { + ia = iq::Args{}; + for (int r = 0; r < 3; ++r) ia.tr[r] = lay.trellis[r]; + ia.n_embd = n_embd; + ia.n_ff = n_ff; + ia.limit = limit; + ia.tg = expert_type(lay, 0); + ia.td = expert_type(lay, 2); + if (ia.tg != expert_type(lay, 1) || !iq::supported(ia.tg) || !iq::supported(ia.td) || n_embd % iq::block_values(ia.tg) != 0 || + n_ff % iq::block_values(ia.td) != 0) { + std::fprintf(stderr, "ds4 gguf %s: expert types %s / %s / %s (n_embd %d, n_ff %d) not covered\n", who, + type_name(expert_type(lay, 0)), type_name(expert_type(lay, 1)), type_name(expert_type(lay, 2)), + n_embd, n_ff); + g_errors.fetch_add(1, std::memory_order_relaxed); + return false; + } + return true; +} +template +void mv_launch(int f, const BfJobs& J, int nj, int max_n, bool vec, cudaStream_t s) { + const dim3 grid((unsigned) ((max_n + kWarps - 1) / kWarps), (unsigned) nj); + if (f == 1) { + if (vec) mx_mv_kernel<<>>(J); + else mx_mv_kernel<<>>(J); + } else if (f == 2) { // (vec here: every row 4-byte aligned, so staged) + if (vec) q8_mv_kernel<<>>(J); + else q8_mv_kernel<<>>(J); + } else { + if (vec) bf16_mv_kernel<<>>(J); + else bf16_mv_kernel<<>>(J); + } +} +void mv_set(int f, const BfJobs& J, int nj, int max_n, int max_c, bool vec, cudaStream_t s) { + if (nj == 0) return; + if (max_c <= 1) mv_launch<1>(f, J, nj, max_n, vec, s); + else if (max_c <= 2) mv_launch<2>(f, J, nj, max_n, vec, s); + else if (max_c <= 4) mv_launch<4>(f, J, nj, max_n, vec, s); + else if (max_c <= 8) mv_launch<8>(f, J, nj, max_n, vec, s); + else mv_launch<16>(f, J, nj, max_n, vec, s); +} +} // namespace + +x3::Mat view(const x3::Mat& m, int c0, int nc) { + x3::Mat v = m; + const size_t ld = row_stride(m); + v.ld = (int) ld; + v.raw = m.fmt != kFmtBF16 ? (const void*) ((const uint8_t*) m.raw + (size_t) c0 * ld) + : (const void*) ((const uint16_t*) m.raw + (size_t) c0 * ld); + v.n = nc; + return v; +} + +bool mv(const x3::MvJob* jobs, int n, cudaStream_t s) { + if (n <= 0 || n > x3::kMaxMvJobs) return false; + BfJobs J[3] = {}; // the BF16 jobs, the MXFP4 ones, the Q8_0 ones: a launch each + int nj[3] = {0, 0, 0}, max_n[3] = {0, 0, 0}, max_c[3] = {1, 1, 1}; + bool vec[3] = {true, true, true}; + iq::MvJob IJ[x3::kMaxMvJobs]; // the low-bit ones (ds4_iq: a launch a type) + int nij = 0; + for (int i = 0; i < n; ++i) { + const x3::MvJob& q = jobs[i]; + const x3::Mat& m = *q.m; + if (m.fmt == kFmtGG) { // the activations rounded to int8 (job i's rows of the scratch), then ds4_iq's GEMV + Scratch* sc = scratch(s); + if (sc == nullptr || m.raw == nullptr || q.xf == nullptr || q.y == nullptr || q.ncol < 1 || + q.ncol > x3::kMaxMvCols || m.k > kMaxQK || type_row_bytes(m.K, m.k) == 0) { + std::fprintf(stderr, "ds4 gguf mv: job %d unsupported (type %s k %d n %d)\n", i, type_name(m.K), m.k, m.n); + g_errors.fetch_add(1, std::memory_order_relaxed); + return false; + } + const size_t at = (size_t) i * x3::kMaxMvCols * kMaxQK; + q8_quant(q.xf, q.ncol > 1 ? q.xf_cs : (size_t) m.k, q.ncol, m.k, sc->mq + at, sc->md + at / 32, s); + iq::MvJob& b = IJ[nij++]; + b.w = (const uint8_t*) m.raw; + b.ld = row_stride(m); + b.type = m.K; + b.k = m.k; + b.n = m.n; + b.ncol = q.ncol; + b.xq = sc->mq + at; + b.xd = sc->md + at / 32; + b.y = q.y; + b.ycs = q.y_cs; + b.bias = q.bias; + b.alpha = q.alpha; + continue; + } + const int f = m.fmt == kFmtMXFP4 ? 1 : m.fmt == kFmtQ8_0 ? 2 : 0; + if ((m.fmt != kFmtBF16 && m.fmt != kFmtMXFP4 && m.fmt != kFmtQ8_0) || m.raw == nullptr || q.xf == nullptr || + q.y == nullptr || q.ncol < 1 || q.ncol > x3::kMaxMvCols || m.k <= 0 || m.n <= 0 || + (f != 0 && m.k % kMxBlock != 0)) { + std::fprintf(stderr, "ds4 gguf mv: job %d unsupported (fmt %d k %d n %d, %d activations)\n", i, m.fmt, m.k, + m.n, q.ncol); + g_errors.fetch_add(1, std::memory_order_relaxed); + return false; + } + BfJob& b = J[f].j[nj[f]++]; + b.w = m.raw; + b.ld = row_stride(m); + b.x = q.xf; + b.xcs = q.xf_cs; + b.y = q.y; + b.ycs = q.y_cs; + b.bias = q.bias; + b.alpha = q.alpha; + b.k = m.k; + b.n = m.n; + b.ncol = q.ncol; + max_n[f] = std::max(max_n[f], m.n); + max_c[f] = std::max(max_c[f], q.ncol); + const bool xa = ((uintptr_t) b.x & 15u) == 0 && (q.ncol == 1 || b.xcs % 4 == 0); + if (f == 2) { // the activations rounded to int8 first (each job its own rows of the scratch) + Scratch* sc = scratch(s); + if (sc == nullptr || m.k > kMaxQK) { + fail("mv: Q8_0 inputs past the scratch"); + return false; + } + const size_t at = (size_t) i * x3::kMaxMvCols * kMaxQK; + b.xq = sc->mq + at; + b.xd = sc->md + at / 32; + q8_quant(q.xf, q.ncol > 1 ? q.xf_cs : (size_t) m.k, q.ncol, m.k, sc->mq + at, sc->md + at / 32, s); + vec[f] = vec[f] && b.ld % 4 == 0 && ((uintptr_t) b.w & 3u) == 0 && (m.k / 32) % 2 == 0; + } else { + vec[f] = vec[f] && xa && (f != 0 || (m.k % 8 == 0 && b.ld % 8 == 0 && ((uintptr_t) b.w & 15u) == 0)); + } + } + for (int f = 0; f < 3; ++f) mv_set(f, J[f], nj[f], max_n[f], max_c[f], vec[f], s); + if (nij > 0 && !iq::mv(IJ, nij, s)) { + fail("mv: a low-bit job not covered"); + return false; + } + check("mv"); + return true; +} + +void rows(const x3::Mat& m, uint16_t* dst, bool bf16, cudaStream_t s) { + if (m.fmt == kFmtGG && m.raw != nullptr) { // a K-quant / i-quant dense matrix (the IST-DAS sets' Q5_K): its own dequantizer + if (!iq::dequant_rows(m.K, m.raw, row_stride(m), m.k, m.n, dst, bf16, s)) fail("rows: a low-bit type not covered"); + return; + } + if ((m.fmt != kFmtBF16 && m.fmt != kFmtQ8_0) || m.raw == nullptr) { + fail("rows: not a BF16 or Q8_0 matrix"); + return; + } + const size_t ld = row_stride(m); + const size_t total = (size_t) m.n * (size_t) m.k; + const unsigned blocks = (unsigned) std::min((total + 255) / 256, 65535); + if (m.fmt == kFmtQ8_0) q8_rows_kernel<<>>((const uint8_t*) m.raw, ld, m.k, m.n, dst, bf16); + else bf16_rows_kernel<<>>((const uint16_t*) m.raw, ld, m.k, m.n, dst, bf16); + check("rows"); +} + +namespace { +// (staged when the matrix's rows are 4-byte aligned: 17 nb % 4 == 0; the blobs' offsets are) +template +struct GateUpK { + static void run(const MxArgs& m, dim3 grid, cudaStream_t s) { + if (mx_row_bytes(m.n_embd) % 4 == 0) mx_gate_up_kernel<<>>(m); + else mx_gate_up_kernel<<>>(m); + } +}; +template +struct DownK { + static void run(const MxArgs& m, dim3 grid, cudaStream_t s) { + if (mx_row_bytes(m.n_ff) % 4 == 0) mx_down_kernel<<>>(m); + else mx_down_kernel<<>>(m); + } +}; +template