Import Strata v0.2.4's DeepSeek-V4.1 engine (strata-dsv41) and the CPU kernels it needs

From Niko1221/Strata tag v0.2.4 (commit 96ca4383, 2026-10-24), unmodified: src/dsv41/ (the engine and its vendored
EXL3 / sampler / window kernels), include/strata/dsv41/, tests/dsv41/, tools/dsv41/{pack_gguf,smoke,tune}.py,
data/dsv41/ (the shipped hot-expert profiles), tools/trellis/tqenc.{cpp,hpp} (the tests' encoder),
third_party/project-maya/ (the MIT notice: the engine is a port of Project Maya's maya-ds4),
third_party/ggml/ggml-common-tq.h, docs/DEEPSEEK41.md (upstream's text, to be rewritten for this fork).

src/kernels/cpu: upstream's iq_avx2.{cpp,hpp}, iq_avx2_rows.inl, iq_avx512.{cpp,hpp} replace this fork's
(v0.1.45-poly.1) copies - they add the engine's CPU lane rows iq256x_rows / iq512x_rows and leave the main engine's
iq256_* / iq512_* as they were (upstream's statement; iq_avx2_parity is the check) - and the trellis CPU lane
tq_cpu.{hpp,cpp}, tq_avx2.cpp, tq_avx512.cpp, tq_states.hpp, tq_computed.hpp is new.  expert_layout.hpp stays at
layout version 4 (upstream's 5 adds Hadamard-folded packs this fork has no use for yet).

CMakeLists.txt: upstream's strata-dsv41 block, with ggml.h / ggml-cpu.h coming through strata_kernels_cpu's ggml-cpu
link from the submodule (no FetchContent), the tq sources and flags in strata_kernels_cpu, and iq_avx512.cpp built
with -mavx512vpopcntdq -mbmi2 as upstream does (iq512x_rows uses them).  Makefile: STRATA_BUILD_DSV41=ON and
strata-dsv41 among the targets `make build` produces.

Target: ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF (IQ1_M / IQ2_XXS + the IQ4_NL Engram) on the A6000 VM.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Robert KarlandClaude Fable 5.1 committed 2026-10-23 20:14:35 -07:00
1 parent a4ad0a4650
commit bd2dbb92f1
79 files changed
+35780 -58

No files matched your search

+91 -2
View File
@@ -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 "$<$<COMPILE_LANGUAGE:HIP,CXX>: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
+4 -4
View File
@@ -3,7 +3,7 @@
#
# git clone <repo> && cd <repo>
# 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
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
8db93e483b34b15dbf63a0826601f1db2107a8cfea73774e7d21d8559e0a9568 *profile-2.00.bin
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
c8de062c5f3c71725ecf5328bd4ee02c71dca88478bf7f6b0f2ec258567ac6b6 *profile-2.25.bin
+142
View File
@@ -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 <UD shard 1> --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-<version>-<system>-<backend>-<variant>.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`.
+187
View File
@@ -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 <cstddef>
#include <cstdint>
#include <cuda_runtime.h>
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
+69
View File
@@ -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 <cstddef>
#include <cstdint>
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
+50
View File
@@ -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 <hip/hip_runtime.h>
#include <hipblas/hipblas.h>
#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
+45
View File
@@ -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 <hip/hip_runtime.h> 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 <hip/hip_runtime.h>
#else
#include <cuda_runtime.h>
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 <typename T>
inline hipError_t hipMalloc(T** p, size_t n) { return cudaMalloc(reinterpret_cast<void**>(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<cudaMemcpyKind>(kind));
}
template <typename T>
inline hipError_t hipMemcpy(T* dst, const T* src, size_t n, int kind) {
return cudaMemcpy(static_cast<void*>(dst), static_cast<const void*>(src), n, static_cast<cudaMemcpyKind>(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
+33
View File
@@ -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 <cstddef>
#include <cuda_runtime.h>
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
+94
View File
@@ -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 <algorithm>
#include <cstddef>
#include <cstdint>
#include <vector>
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<int32_t>* 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<int64_t>(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
+7
View File
@@ -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).
+7
View File
@@ -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
+95
View File
@@ -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 <cstddef>
#include <cstdint>
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
+206
View File
@@ -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 <cuda_fp16.h>
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 <int G, int R>
__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 <int G, int R>
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<G, R><<<dim3(heads / G, nsplit, T), 256, 0, s>>>(q, win, ckv, ckv_row_bytes, sel, sel_stride, ar, heads, scale, sc.part, sc.ml, sc.nsplit);
attn_merge<<<dim3(heads, T), 256, 0, s>>>(sc.part, sc.ml, sink, heads, sc.nsplit, R, ar, out);
}
} // namespace attnsplit
} // namespace strata::ds4
+275
View File
@@ -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 <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
namespace strata::ds4 {
inline int64_t now_ns() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(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<size_t>(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<uint64_t, uint32_t> map_;
std::vector<uint64_t> keys_;
std::vector<uint8_t> ref_;
std::vector<std::unique_ptr<uint8_t[]>> 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<EgRead> reads;
std::vector<std::pair<int, std::pair<uint8_t*, uint8_t*>>> dups; // read i -> another (codes, scales)
std::vector<uint8_t> ok; // per read: 1 read whole
std::atomic<int> left{0}; // reads not yet done
std::atomic<int> post{0}; // 0 pending, 1 finishing, 2 finished
int64_t t0 = 0; // submitted (now_ns())
std::atomic<int64_t> 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<std::string>& paths, int threads, std::vector<char> direct = {}) {
paths_ = paths;
direct_ = std::move(direct);
for (int i = 0; i < threads; ++i) th_.emplace_back([this] { loop(); });
}
void stop() {
{
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> lk(done_mu_);
done_cv_.wait(lk, [&] { return b.left.load(std::memory_order_acquire) == 0; });
}
private:
void loop() {
std::vector<os::fd_t> fds(paths_.size(), os::kBadFd); // this thread's own handles, opened on first use
std::vector<os::fd_t> ufds(paths_.size(), os::kBadFd); // (and its unbuffered ones)
std::vector<uint8_t> 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<std::mutex> 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<std::mutex> 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<os::fd_t>& fds, std::vector<os::fd_t>& ufds, uint8_t* al, const EgRead& r,
std::vector<uint8_t>& 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<uint8_t> 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<std::string> paths_;
std::vector<char> direct_;
public:
std::atomic<int64_t> check_n_{0}, check_bad_{0}; // (DS4_EG_CHECK: rows compared, rows that differed)
std::vector<std::thread> th_;
std::mutex mu_;
std::condition_variable cv_;
struct Job {
EgBatch* b = nullptr;
int i0 = 0, i1 = 0; // reads [i0, i1)
};
std::deque<Job> q_;
bool quit_ = false;
std::mutex done_mu_;
std::condition_variable done_cv_;
};
} // namespace strata::ds4
+293
View File
@@ -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 <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#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 <mutex>
#include <vector>
#if defined(_MSC_VER)
#include <intrin.h>
#elif defined(__x86_64__)
#include <cpuid.h>
#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<uint8_t> 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<std::vector<uint8_t>> a((size_t) nt, std::vector<uint8_t>(ab));
std::vector<const void*> ap((size_t) nt);
std::vector<std::vector<float>> o0((size_t) nt, std::vector<float>(rows)), o1 = o0;
std::vector<float*> p1((size_t) nt);
for (int t = 0; t < nt; ++t) {
std::vector<float> 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<float> 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<float> 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
File diff suppressed because it is too large. Load diff
+81
View File
@@ -0,0 +1,81 @@
// 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.cuh - a GGUF's weights on the device for maya-ds4 (unsloth's DeepSeek-V4.1-Flash-1017 GGUFs,
// tools/ds4/pack_gguf.py): the dense matrices in BF16 and the routed experts in MXFP4. They stand in for
// strata::dsv41k::exl3's matrices and experts (an x3::Mat with fmt kFmtBF16, an x3::ExpertLayout with fmt kFmtMXFP4)
// with the same arguments and the same results' layout, so the engine's paths (decode, verify windows, chunked prompts,
// tensor parallel) take either format.
//
// MXFP4 is ggml's block_mxfp4: 32 values in 17 bytes, an E8M0 scale e then 16 bytes of E2M1 codes - value j of the
// block in byte j's low nibble (j < 16) or byte j - 16's high nibble, worth kvalues[code] * 2^(e - 128) with kvalues
// {0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12} (the E2M1 values doubled). A matrix is [out][in / 32] blocks
// (row r = output r), as the GGUF stores it, so an expert's blob is its gate, up and down matrices one after another.
// Every product is an F32 sum of exactly dequantised weights times F32 activations, and a window's entry gets the bits
// the token path gives it (the same kernel, the same order).
#pragma once
#include "strata/dsv41/exl3.hpp"
#include <cstddef>
#include <cstdint>
#include <cuda_runtime.h>
namespace strata::ds4::gguf {
namespace x3 = strata::dsv41k::exl3;
constexpr int kFmtBF16 = 1; // x3::Mat::fmt
constexpr int kFmtMXFP4 = 2; // x3::ExpertLayout::fmt (and an expert's matrix as an x3::Mat)
constexpr int kFmtQ8_0 = 3; // x3::Mat::fmt: ggml's Q8_0, an FP16 scale and 32 int8 in 34 bytes (UD-Q4_K_XL's dense)
constexpr int kFmtGG = 4; // x3::Mat::fmt: ggml's low-bit block type m.K (ds4_iq.cuh's: IQ2_XXS .. Q4_K), [n][k / 256]
constexpr int kMxBlock = 32, kMxBytes = 17, kQ8Bytes = 34;
constexpr int kTypeMXFP4 = 39; // ggml's type id
/// Bytes of an MXFP4 row of k values (k % 32 == 0), and of a matrix of n such rows.
__host__ __device__ inline size_t mx_row_bytes(int64_t k) { return (size_t) (k / kMxBlock) * kMxBytes; }
__host__ __device__ inline size_t mx_bytes(int64_t n, int64_t k) { return (size_t) n * mx_row_bytes(k); }
__host__ __device__ inline size_t q8_row_bytes(int64_t k) { return (size_t) (k / 32) * kQ8Bytes; }
/// A GGUF expert layer (x3::ExpertLayout::fmt kFmtMXFP4: block-quantized experts read in place) keeps each role's ggml
/// type in lay.K[r] (r: gate, up, down; 0 = MXFP4): MXFP4 takes these kernels, the low-bit types ds4_iq.cuh's (gate
/// and up of one type). Roles of one layer may differ (down of another type); MXFP4 and a low-bit type do not mix.
inline int expert_type(const x3::ExpertLayout& l, int r) { return l.K[r] == 0 ? kTypeMXFP4 : l.K[r]; }
inline bool mx_experts(const x3::ExpertLayout& l) {
return expert_type(l, 0) == kTypeMXFP4 && expert_type(l, 1) == kTypeMXFP4 && expert_type(l, 2) == kTypeMXFP4;
}
/// Bytes of a row of k values of an expert type (0: not one the device kernels take, or k not whole blocks).
size_t type_row_bytes(int type, int64_t k);
/// Values a block of an expert type (32: MXFP4, 256: the low-bit ones; 0: neither).
int type_block(int type);
/// The type's name (ggml's), "?" when unknown.
const char* type_name(int type);
/// Whether the device kernels take this type (MXFP4 is its own path; the i-quants and K-quants ds4_iq.cu instantiates).
/// A false here with a layout known to type_row_bytes() means the CPU lane reads it and it must not enter the VRAM tier.
bool type_on_device(int type);
/// The per-stream scratch of the MXFP4 experts on the current device (once per stream, as x3::prepare).
bool prepare(cudaStream_t s);
/// x3::mv's contract for GGUF matrices (F32 activations): each job's m->fmt kFmtBF16 (raw = BF16 [n][ld], ld values a
/// row), kFmtMXFP4 (raw = MXFP4 [n][k / 32] blocks, ld bytes a row; 0: mx_row_bytes(k)) - an expert's matrix in VRAM -
/// or kFmtQ8_0 (raw = Q8_0 [n][k / 32] blocks, ld bytes a row; 0: q8_row_bytes(k)).
bool mv(const x3::MvJob* jobs, int n, cudaStream_t s);
/// The columns [c0, c0 + nc) of such a matrix: its rows c0 .. c0 + nc - 1, a contiguous range.
x3::Mat view(const x3::Mat& m, int c0, int nc);
/// x3::reconstruct_rows' layout from a BF16 or Q8_0 matrix: dst[r][c] = W[c][r] (n rows of k values), F16 or BF16
/// bits (a Q8_0 weight rounded to them).
void rows(const x3::Mat& m, uint16_t* dst, bool bf16, cudaStream_t s);
/// x3::moe_gate_up / moe_down / win_experts / set_gate_up / set_down for a GGUF's experts (lay.fmt == kFmtMXFP4; the
/// roles' types in lay.K, see expert_type).
void moe_gate_up(const x3::MoeArgs& a, const float* x, float* h, cudaStream_t s);
void moe_down(const x3::MoeArgs& a, const float* h, const float* sh_out, float* out, cudaStream_t s);
bool win_experts(const x3::WinArgs& a, cudaStream_t s);
void set_gate_up(const x3::SetArgs& a, const float* x, int ldx, const int* row_idx, uint16_t* h16, int ldh,
cudaStream_t s);
void set_down(const x3::SetArgs& a, const uint16_t* h16, int ldh, float* y, int ldy, cudaStream_t s);
/// Launch failures of these kernels since the process started (each is also printed).
int launch_errors();
} // namespace strata::ds4::gguf
+418
View File
@@ -0,0 +1,418 @@
// 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_cpu.cpp - a GGUF's MXFP4 experts on the CPU lane (see ds4_gguf_cpu.hpp).
#include "ds4_gguf_cpu.hpp"
#include "strata/dsv41/exl3_cpu.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#if defined(__x86_64__) || defined(_M_X64)
#define MX_X86 1
#include <immintrin.h>
#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <cpuid.h>
#endif
#endif
// a function's instruction set (GCC / Clang, clang-cl too; MSVC compiles any intrinsic as it is): the file is built for
// the baseline x86-64, and each tier's code runs only where detect() says the CPU and the OS take it
#if defined(MX_X86) && (defined(__GNUC__) || defined(__clang__))
#define MX_TARGET(s) __attribute__((target(s)))
#else
#define MX_TARGET(s)
#endif
#define MX_AVX2 MX_TARGET("avx2,fma")
// AVX-VNNI's intrinsics: GCC 11, Clang 12, MSVC 2022
#if defined(MX_X86) && (defined(_MSC_VER) || (defined(__clang__) && __clang_major__ >= 12) || \
(!defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 11))
#define MX_AVXVNNI 1
#endif
namespace strata::ds4::gguf {
namespace {
constexpr int kBlock = 32, kBytes = 17;
constexpr float kValues[16] = {0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 6.0f, 8.0f, 12.0f,
0.0f, -1.0f, -2.0f, -3.0f, -4.0f, -6.0f, -8.0f, -12.0f};
constexpr int kCodes[16] = {0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12};
float e8m0_half(uint32_t e) { // 2^(e - 128), as the device's
const uint32_t bits = e < 2 ? 0x00200000u << e : (e - 1) << 23;
float f;
std::memcpy(&f, &bits, 4);
return f;
}
struct E8m0Table {
float v[256];
E8m0Table() {
for (int e = 0; e < 256; ++e) v[e] = e8m0_half((uint32_t) e);
}
};
const E8m0Table& e8() {
static const E8m0Table t;
return t;
}
void rows_scalar(const uint8_t* w, size_t rb, int k, int r0, int r1, const float* const* x, int n, float* const* y) {
for (int r = r0; r < r1; ++r) {
const uint8_t* p = w + (size_t) r * rb;
float acc[kMxCpuMaxN] = {};
for (int b = 0; b < k / kBlock; ++b, p += kBytes) {
const float d = e8m0_half(p[0]);
float wv[kBlock];
for (int j = 0; j < 16; ++j) {
wv[j] = kValues[p[1 + j] & 15] * d;
wv[j + 16] = kValues[p[1 + j] >> 4] * d;
}
for (int i = 0; i < n; ++i) {
const float* xb = x[i] + b * kBlock;
float s = 0.0f;
for (int j = 0; j < kBlock; ++j) s += wv[j] * xb[j];
acc[i] += s;
}
}
for (int i = 0; i < n; ++i) y[i][r - r0] = acc[i];
}
}
#if defined(MX_X86)
MX_AVX2 float hsum(__m256 v) {
const __m128 a = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
const __m128 b = _mm_add_ps(a, _mm_movehl_ps(a, a));
return _mm_cvtss_f32(_mm_add_ss(b, _mm_shuffle_ps(b, b, 1)));
}
// a block: the 16 code bytes -> 32 int8 values through a shuffle table (low nibbles: values 0..15, high: 16..31),
// widened to F32 in 4 x 8, times the block's scale (exact), FMAs against each activation
MX_AVX2 void rows_avx2(const uint8_t* w, size_t rb, int k, int r0, int r1, const float* const* x, int n,
float* const* y) {
const __m128i lut = _mm_setr_epi8(0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12);
const __m128i m4 = _mm_set1_epi8(0x0f);
for (int r = r0; r < r1; ++r) {
const uint8_t* p = w + (size_t) r * rb;
__m256 acc[kMxCpuMaxN];
for (int i = 0; i < n; ++i) acc[i] = _mm256_setzero_ps();
for (int b = 0; b < k / kBlock; ++b, p += kBytes) {
const __m256 d = _mm256_set1_ps(e8m0_half(p[0]));
const __m128i q = _mm_loadu_si128((const __m128i*) (p + 1));
const __m128i lo = _mm_shuffle_epi8(lut, _mm_and_si128(q, m4));
const __m128i hi = _mm_shuffle_epi8(lut, _mm_and_si128(_mm_srli_epi16(q, 4), m4));
const __m256 w0 = _mm256_mul_ps(d, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(lo)));
const __m256 w1 = _mm256_mul_ps(d, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(lo, 8))));
const __m256 w2 = _mm256_mul_ps(d, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(hi)));
const __m256 w3 = _mm256_mul_ps(d, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(hi, 8))));
for (int i = 0; i < n; ++i) {
const float* xb = x[i] + b * kBlock;
__m256 a = acc[i];
a = _mm256_fmadd_ps(w0, _mm256_loadu_ps(xb), a);
a = _mm256_fmadd_ps(w1, _mm256_loadu_ps(xb + 8), a);
a = _mm256_fmadd_ps(w2, _mm256_loadu_ps(xb + 16), a);
a = _mm256_fmadd_ps(w3, _mm256_loadu_ps(xb + 24), a);
acc[i] = a;
}
}
for (int i = 0; i < n; ++i) y[i][r - r0] = hsum(acc[i]);
}
}
// ---- the int8 path's vector tiers (ds4_mx_kern.inc)
#define MXK_NS mx_avx2
#define MXK_ATTR MX_TARGET("avx2,fma")
#define MXK_256 1
#include "ds4_mx_kern.inc"
#if defined(MX_AVXVNNI)
#define MXK_NS mx_avxvnni
#define MXK_ATTR MX_TARGET("avx2,fma,avxvnni")
#define MXK_256 1
#define MXK_VNNI 1
#include "ds4_mx_kern.inc"
#endif
#define MXK_NS mx_avx512
#define MXK_ATTR MX_TARGET("avx512f,avx512bw,fma")
#define MXK_512 1
#include "ds4_mx_kern.inc"
#define MXK_NS mx_avx512vnni
#define MXK_ATTR MX_TARGET("avx512f,avx512bw,avx512vnni,fma")
#define MXK_512 1
#define MXK_VNNI 1
#include "ds4_mx_kern.inc"
#endif
// ---- the int8 path's scalar tier: ds4_mx_kern.inc's order (8 accumulators, block j of a group of 8 into L(j)), so it
// gives the vector tiers' bits - also the tests' check on them. The activation's layout (ds4_mx_kern.inc), for any k
// % 32 == 0: the int8 values in quads (a partial last quad padded), then per group of 8 blocks the scales and the
// offset corrections in lane order (a partial last group padded)
inline int act_lane(int b) { return 8 * (b >> 3) + ((b & 7) & 1) * 4 + ((b & 7) >> 1); }
inline size_t act_qbytes(int k) { return (size_t) 128 * (size_t) ((k / kBlock + 3) / 4); }
inline size_t act_groups(int k) { return (size_t) ((k / kBlock + 7) / 8); }
inline int act_q(const uint8_t* act, int b, int j) { // block b's value j (0..31)
return ((const int8_t*) act)[(b >> 2) * 128 + (j >= 16 ? 64 : 0) + 16 * (b & 3) + (j & 15)];
}
inline float act_d(const uint8_t* act, int k, int b) { return ((const float*) (act + act_qbytes(k)))[act_lane(b)]; }
void quant_scalar(const float* x, int b0, int b1, uint8_t* act, int k) {
int8_t* q = (int8_t*) act;
float* dx = (float*) (act + act_qbytes(k));
int32_t* corr = (int32_t*) (act + act_qbytes(k) + 32 * act_groups(k));
for (int b = b0; b < b1; ++b, x += kBlock) {
float am = 0.0f;
for (int j = 0; j < kBlock; ++j) am = std::max(am, std::fabs(x[j]));
const float sc = am / 127.0f;
int8_t v[kBlock];
int s = 0;
for (int j = 0; j < kBlock; ++j) {
v[j] = am > 0.0f ? (int8_t) (int) std::nearbyint(x[j] / sc) : (int8_t) 0;
s += v[j];
}
int8_t* lo = q + (b >> 2) * 128 + 16 * (b & 3);
for (int j = 0; j < 16; ++j) {
lo[j] = v[j];
lo[64 + j] = v[16 + j];
}
dx[act_lane(b)] = sc;
corr[act_lane(b)] = -12 * s;
}
}
void rows_q_scalar(const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, int n, float* const* y) {
const float* t = e8().v;
for (int r = r0; r < r1; ++r) {
const uint8_t* p = w + (size_t) r * rb;
float acc[kMxCpuMaxN][8] = {};
for (int b = 0; b < k / kBlock; ++b, p += kBytes) {
int wv[kBlock];
for (int j = 0; j < 16; ++j) {
wv[j] = kCodes[p[1 + j] & 15];
wv[j + 16] = kCodes[p[1 + j] >> 4];
}
const int l = act_lane(b) & 7;
for (int i = 0; i < n; ++i) {
const uint8_t* a = (const uint8_t*) act[i];
int s = 0;
for (int j = 0; j < kBlock; ++j) s += wv[j] * act_q(a, b, j);
acc[i][l] = std::fma((float) s, t[p[0]] * act_d(a, k, b), acc[i][l]);
}
}
for (int i = 0; i < n; ++i) {
const float* A = acc[i];
y[i][r - r0] = ((A[0] + A[4]) + (A[2] + A[6])) + ((A[1] + A[5]) + (A[3] + A[7]));
}
}
}
// ---- which tiers this CPU runs
struct Cpu {
bool avx2 = false, vnni256 = false, avx512 = false, vnni512 = false, vbmi = false, bmi2 = false;
};
Cpu detect() {
Cpu c;
#if defined(MX_X86)
unsigned r[4] = {0, 0, 0, 0};
auto cpuid = [&](unsigned leaf, unsigned sub) {
#if defined(_MSC_VER)
int x[4];
__cpuidex(x, (int) leaf, (int) sub);
for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i];
#else
__cpuid_count(leaf, sub, r[0], r[1], r[2], r[3]);
#endif
};
cpuid(0, 0);
const unsigned max_leaf = r[0];
if (max_leaf < 7) return c;
cpuid(1, 0);
const bool fma = (r[2] >> 12) & 1u, osxsave = (r[2] >> 27) & 1u, avx = (r[2] >> 28) & 1u;
if (!fma || !osxsave || !avx) return c;
#if defined(_MSC_VER)
const unsigned long long xcr0 = _xgetbv(0);
#else
unsigned lo = 0, hi = 0;
__asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo;
#endif
if ((xcr0 & 0x6) != 0x6) return c; // the OS saves the YMM state
cpuid(7, 0);
const unsigned b7 = r[1], c7 = r[2];
c.avx2 = (b7 >> 5) & 1u;
const bool zmm_os = (xcr0 & 0xE6) == 0xE6;
c.avx512 = c.avx2 && zmm_os && ((b7 >> 16) & 1u) && ((b7 >> 30) & 1u); // F, BW
c.vnni512 = c.avx512 && ((c7 >> 11) & 1u);
c.vbmi = c.avx512 && ((c7 >> 1) & 1u); // AVX-512 VBMI
c.bmi2 = (b7 >> 8) & 1u;
cpuid(7, 1);
c.vnni256 = c.avx2 && ((r[0] >> 4) & 1u); // AVX-VNNI
#endif
return c;
}
const Cpu& cpu() {
static const Cpu c = detect();
return c;
}
// The tier for this CPU, measured: every vector tier it runs times the same small warm job (64 rows of a 5120-wide
// matrix, in L2, against 1, 2 and 4 activations - the compute a row takes, which is where the tiers differ; streaming
// from RAM they all reach the memory's speed) in interleaved rounds, the best round of each counting. The choice never
// changes an answer (the tiers give the same bits), only the speed. DS4_MX_TIER=<name> picks one by hand.
std::string g_tier_report;
int measure_tier(const std::vector<int>& cand);
int pick_tier() {
if (const char* f = std::getenv("DS4_MX_TIER"))
for (int t = 0; t < kMxTiers; ++t)
if (std::string(f) == mx_tier_name(t) && mx_tier_ok(t)) {
g_tier_report = std::string("DS4_MX_TIER=") + f;
return t;
}
std::vector<int> cand;
for (int t = 1; t < kMxTiers; ++t)
if (mx_tier_ok(t)) cand.push_back(t);
if (cand.empty()) return kMxScalar;
if (cand.size() == 1) return cand[0];
return measure_tier(cand);
}
int measure_tier(const std::vector<int>& cand) {
constexpr int K = 5120, R = 64, NT = 4;
const size_t rb = (size_t) K / kBlock * kBytes;
std::vector<uint8_t> w(rb * R), act(mx_act_bytes(K) * NT);
uint32_t s = 0x9E3779B9u;
for (size_t i = 0; i < w.size(); ++i) {
s = s * 1664525u + 1013904223u;
w[i] = (uint8_t) (s >> 24);
}
for (size_t b = 0; b < w.size() / kBytes; ++b) w[b * kBytes] = (uint8_t) (118 + b % 6);
std::vector<float> x(K);
for (int i = 0; i < NT; ++i) {
for (int j = 0; j < K; ++j) {
s = s * 1664525u + 1013904223u;
x[(size_t) j] = (float) ((int) (s >> 16) - 32768) / 32768.0f;
}
quant_scalar(x.data(), 0, K / kBlock, act.data() + (size_t) i * mx_act_bytes(K), K);
}
const void* ap[NT];
for (int i = 0; i < NT; ++i) ap[i] = act.data() + (size_t) i * mx_act_bytes(K);
float y[NT][R];
float* yp[NT] = {y[0], y[1], y[2], y[3]};
std::vector<double> best(cand.size(), 1e30);
for (int round = 0; round < 6; ++round)
for (size_t c = 0; c < cand.size(); ++c) {
const auto t0 = std::chrono::steady_clock::now();
for (int rep = 0; rep < 8; ++rep)
for (int n : {1, 2, 4}) mx_rows_tier(cand[c], w.data(), rb, K, 0, R, ap, n, yp, 0);
const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
if (round > 0) best[c] = std::min(best[c], us); // (round 0: the clock and the caches warm)
}
size_t bi = 0;
for (size_t c = 1; c < cand.size(); ++c)
if (best[c] < best[bi]) bi = c;
char buf[64];
for (size_t c = 0; c < cand.size(); ++c) {
std::snprintf(buf, sizeof buf, "%s%s %.0f us", c ? ", " : "", mx_tier_name(cand[c]), best[c]);
g_tier_report += buf;
}
return cand[bi];
}
int prefetch_bytes() {
const char* f = std::getenv("DS4_MX_PF");
return f != nullptr ? std::max(0, std::atoi(f)) : 0;
}
} // namespace
void q8_round(const float* x, int k, float* out) {
for (int b = 0; b < k / kBlock; ++b) {
const float* xb = x + b * kBlock;
float am = 0.0f;
for (int j = 0; j < kBlock; ++j) am = std::max(am, std::fabs(xb[j]));
const float sc = am / 127.0f;
for (int j = 0; j < kBlock; ++j)
out[b * kBlock + j] = am > 0.0f ? std::nearbyint(xb[j] / sc) * sc : 0.0f;
}
}
void mx_cpu_rows(const uint8_t* w, size_t rb, int k, int r0, int r1, const float* const* x, int n, float* const* y) {
#if defined(MX_X86)
static const bool avx2 = strata::dsv41k::cpu::exl3_cpu_tier() >= 1;
if (avx2) return rows_avx2(w, rb, k, r0, r1, x, n, y);
#endif
rows_scalar(w, rb, k, r0, r1, x, n, y);
}
// ---- the int8 path
bool mx_tier_ok(int t) {
switch (t) {
case kMxScalar: return true;
case kMxAvx2: return cpu().avx2;
#if defined(MX_AVXVNNI)
case kMxAvxVnni: return cpu().vnni256;
#endif
case kMxAvx512: return cpu().avx512;
case kMxAvx512Vnni: return cpu().vnni512;
default: return false;
}
}
const char* mx_tier_name(int t) {
switch (t) {
case kMxScalar: return "scalar";
case kMxAvx2: return "avx2";
case kMxAvxVnni: return "avxvnni";
case kMxAvx512: return "avx512";
case kMxAvx512Vnni: return "avx512vnni";
default: return "?";
}
}
int mx_tier() {
static const int t = pick_tier();
return t;
}
const char* mx_tier_report() {
(void) mx_tier();
return g_tier_report.c_str();
}
void mx_quant_blocks(const float* x, int b0, int b1, void* act, int k) {
#if defined(MX_X86)
if (cpu().avx2 && k % 256 == 0) return mx_avx2::quant(x, b0, b1, (uint8_t*) act, k);
#endif
quant_scalar(x, b0, b1, (uint8_t*) act, k);
}
void mx_quant_blocks_scalar(const float* x, int b0, int b1, void* act, int k) {
quant_scalar(x, b0, b1, (uint8_t*) act, k);
}
int mx_act_value(const void* act, int b, int j) { return act_q((const uint8_t*) act, b, j); }
float mx_act_scale(const void* act, int k, int b) { return act_d((const uint8_t*) act, k, b); }
void mx_rows_tier(int t, const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, int n,
float* const* y, int pf) {
if (k % 256 != 0 || !mx_tier_ok(t)) t = kMxScalar; // (the vector tiers take a group of 8 blocks a step)
const float* tb = e8().v;
#if defined(MX_X86)
switch (t) {
case kMxAvx2: return mx_avx2::rows(w, rb, k, r0, r1, act, n, y, tb, pf);
#if defined(MX_AVXVNNI)
case kMxAvxVnni: return mx_avxvnni::rows(w, rb, k, r0, r1, act, n, y, tb, pf);
#endif
case kMxAvx512: return mx_avx512::rows(w, rb, k, r0, r1, act, n, y, tb, pf);
case kMxAvx512Vnni: return mx_avx512vnni::rows(w, rb, k, r0, r1, act, n, y, tb, pf);
default: break;
}
#endif
(void) tb, (void) pf;
for (int i0 = 0; i0 < n; i0 += kMxCpuMaxN)
rows_q_scalar(w, rb, k, r0, r1, act + i0, std::min(kMxCpuMaxN, n - i0), y + i0);
}
void mx_rows(const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, int n, float* const* y) {
static const int pf = prefetch_bytes();
mx_rows_tier(mx_tier(), w, rb, k, r0, r1, act, n, y, pf);
}
} // namespace strata::ds4::gguf
+101
View File
@@ -0,0 +1,101 @@
// 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_cpu.hpp - a GGUF's MXFP4 experts on the CPU lane of maya-ds4 (the format: ds4_gguf.cuh). The
// weights are read where they lie (the GGUF file's mapping), each block decoded once for all the activations of a
// call (mx_rows: int8 dots, the CPU's best vector tier at run time; a scalar loop otherwise).
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
namespace strata::ds4::gguf {
constexpr int kMxCpuMaxN = 8; // activations a call
/// y[i][r - r0] = (row r of W) . x[i] for r0 <= r < r1 and i < n (n <= kMxCpuMaxN): W's rows hold k values
/// (k % 32 == 0) as MXFP4 blocks, rb bytes apart. (F32 activations: the tests' and the benchmark's old path.)
void mx_cpu_rows(const uint8_t* w, size_t rb, int k, int r0, int r1, const float* const* x, int n, float* const* y);
/// A GGUF's low-bit experts (ds4_iq.cuh's types) on the CPU lane - ggml-cpu's arithmetic through the GLM CPU lane's
/// native experts (strata::dsv41k::cpu::native_*: its AVX-512 / AVX2 multi-token rows where they are ggml's bit for bit,
/// ggml's dots otherwise; ds4_iq_cpu.cpp): an activation quantized once to the weight type's vec_dot_type (Q8_K: an F32
/// scale per 256 values - the device takes one per 32, so the two sides agree to that rounding), each row one dot.
struct IqCpu {
int tg = 0, td = 0, n_embd = 0, n_ff = 0;
int gu_act = 0, d_act = 0; // the activations' ggml types
size_t gu_row = 0, d_row = 0; // bytes a weight row
size_t act_bytes = 0, h_bytes = 0; // bytes of x (n_embd) and of h (n_ff) as those
};
/// The layer's geometry; false (err) when this build or ggml-cpu cannot take it.
bool iq_cpu_fmt(int tg, int td, int n_embd, int n_ff, IqCpu& f, std::string& err);
/// x (k values) as the activation type `act` (f.gu_act / f.d_act) into dst.
void iq_cpu_quant(int act, const float* x, int k, void* dst);
/// ff[t][r] = clamped swiglu(gate_r . a[t], up_r . a[t]) for rows [r0, r1) (limit 0: no clamp), nt tokens.
void iq_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);
/// out[t][r] = down_r . hq[t] for rows [r0, r1).
void iq_cpu_down(const IqCpu& f, const uint8_t* down, const void* const* hq, int nt, float* const* out, int r0, int r1);
/// The trellis types (ds4_iq.cuh's is_tq; ds4_tq_cpu.cpp, Strata's tq_cpu kernels): the same four calls, reached from the
/// iq_cpu_* ones above for those types (their activations: F32 scale a 32 values, then the int8 values).
bool tq_cpu_type(int type);
int tq_cpu_act();
bool tq_cpu_fmt(int tg, int td, int n_embd, int n_ff, IqCpu& f, std::string& err);
void tq_cpu_quant(const float* x, int k, void* dst);
void tq_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);
void tq_cpu_down(const IqCpu& f, const uint8_t* down, const void* const* hq, int nt, float* const* out, int r0, int r1);
/// ggml block types on the CPU lane through ggml-cpu's row dots (ds4_gg_cpu.cpp), for the IQ / K-quant experts.
bool gg_cpu_type(int type);
/// One row of a GGUF block type (Q4_K / Q5_K / Q6_K / Q8_0 / any type ggml has a to_float for) -> k values as BF16
/// (round to nearest even), the host embedding's format. False: ggml has no decode for this type.
bool gg_row_to_bf16(int type, const uint8_t* row, int k, uint16_t* out);
bool gg_cpu_fmt(int tg, int td, int n_embd, int n_ff, IqCpu& f, std::string& err);
void gg_cpu_quant(int act, const float* x, int k, void* dst);
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);
/// -1: from the environment (default: Strata's AVX2 i-quant rows, bit-identical to ggml-cpu's dot, from 2 tokens - 1 on IQ3_S, 3 on IQ1_M;
/// DS4_GG_IQ256=0 never, =1 always), 0 ggml-cpu, 1 always (benches), 2 the default rule.
void gg_cpu_set_iq256(int mode);
void gg_cpu_down(const IqCpu& f, const uint8_t* down, const void* const* hq, int nt, float* const* out, int r0, int r1);
/// The CPU lane's MXFP4 rows in the device's arithmetic (ds4_gguf.cu's mx_dot): the activations rounded to int8 per 32
/// values as the device rounds them (q8_round's q and scale), each block's products summed exactly in integers, then
/// times (weight scale x activation scale) into F32 sums - the same numbers as the device up to the order of the
/// blocks' sums. The vector tiers (ds4_mx_kern.inc): AVX2 vpmaddubsw, AVX-VNNI and AVX-512 (VNNI) vpdpbusd; the CPU's
/// fastest is taken at run time (DS4_MX_TIER=<name> picks another one it runs). Every tier, the scalar one included,
/// sums in the same order: they give the same bits, so the choice never changes an answer.
enum MxTier { kMxScalar = 0, kMxAvx2, kMxAvxVnni, kMxAvx512, kMxAvx512Vnni, kMxTiers };
/// Bytes of an activation of k values (k % 32 == 0) for mx_rows: the int8 values in quads of blocks, then a scale and
/// an offset correction a block in groups of 8 (ds4_mx_kern.inc) - 1.25 k for k % 256 == 0.
inline size_t mx_act_bytes(int k) {
const size_t nb = (size_t) k / 32;
return 128 * ((nb + 3) / 4) + 64 * ((nb + 7) / 8);
}
/// (tests) value j (0..31) of block b of an activation, and the block's scale
int mx_act_value(const void* act, int b, int j);
float mx_act_scale(const void* act, int k, int b);
/// Blocks [b0, b1) of a k-value activation (x at block b0's first value: x[32 (b - b0) + j]) into act.
void mx_quant_blocks(const float* x, int b0, int b1, void* act, int k);
void mx_quant_blocks_scalar(const float* x, int b0, int b1, void* act, int k); // (the same bytes, no vectors)
inline void mx_quant(const float* x, int k, void* act) { mx_quant_blocks(x, 0, k / 32, act, k); }
/// y[i][r - r0] = (row r of W) . act[i] for r0 <= r < r1, i < n (any n; act[i] mx_quant's of k values).
void mx_rows(const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, int n, float* const* y);
/// The same with tier t (the scalar one when the CPU does not run t, or k % 256 != 0); pf: bytes prefetched ahead.
void mx_rows_tier(int t, const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, int n,
float* const* y, int pf = 0);
int mx_tier(); // the tier mx_rows takes (measured on first use: the fastest a core, ds4_gguf_cpu.cpp)
const char* mx_tier_report(); // the measurement behind it (each candidate's time), or how it was picked
bool mx_tier_ok(int t); // this CPU runs tier t
const char* mx_tier_name(int t);
/// Whether the rows of `type` are ds4's own here (IQ3_XXS / IQ3_S on AVX2 / AVX-512 VBMI: ggml-cpu's numbers bit for
/// bit, checked against its dot on first use; DS4_IQ_OWN=0 turns them off) rather than ggml's / the GLM lane's.
bool iq_cpu_own_rows(int type);
/// x rounded as the device's MXFP4 kernels round their activations (q8_quant: per 32 values sc = max|x| / 127, q =
/// round-half-even(x / sc), the same F32 operations, so the same q), into out as q sc - an expert gives the same sums
/// on the CPU lane as in VRAM (up to their order), whichever side the expert cache puts it on.
void q8_round(const float* x, int k, float* out);
} // namespace strata::ds4::gguf
+1497
View File
File diff suppressed because it is too large. Load diff
+133
View File
@@ -0,0 +1,133 @@
// 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_iq.cuh - a GGUF's routed experts in ggml's low-bit block types on the device for maya-ds4: the i-quants
// IQ2_XXS, IQ2_S, IQ3_XXS, IQ3_S, IQ4_XS and the K-quants Q2_K, Q3_K, Q4_K (256 values a block, ggml's layouts:
// ggml-common.h, llama.cpp MIT). ds4_gguf.cu sends an expert layer here when its experts are not MXFP4
// (x3::ExpertLayout::fmt kFmtMXFP4 with K[r] = role r's ggml type; K[r] == kTypeMXFP4: ds4_gguf.cu's own kernels).
//
// Every weight is decoded exactly (ggml's dequantize_row_*: a block scale times an integer scale times a grid or code
// value) and every product takes the activations rounded to int8 per 32 values with an F32 scale (ds4_gguf.cu's
// q8_quant): a 32-value sub-block's sum is an exact integer dot (dp4a) times its scales in F32 - no integer division as
// llama.cpp's vecdotq takes (its sums truncate), so these are the double reference's sums to F32 rounding. A window's
// entry gets the token path's bits (the same kernel, the same order).
#pragma once
#include <cstddef>
#include <cstdint>
#include <cuda_runtime.h>
namespace strata::ds4::gguf::iq {
// ggml type ids
constexpr int kQ5_K = 13, kQ6_K = 14; // (the dense matrices' K-quants, GEMV only)
constexpr int kQ2_K = 10, kQ3_K = 11, kQ4_K = 12, kIQ2_XXS = 16, kIQ2_XS = 17, kIQ3_XXS = 18, kIQ1_S = 19,
kIQ4_NL = 20, kIQ3_S = 21, kIQ2_S = 22, kIQ4_XS = 23, kIQ1_M = 29;
/// The trellis types (Strata's, ds4_tq.cu): ggml's TQK6 / TQK7 (145 / 146, the table codebook) and the experimental
/// TQK5X / TQK4X (224 / 225, computed codebook) and TQK5T / TQK4T (226 / 227, table): a block of 128 values is
/// {fp16 d; 32 steps of K bits}, 2 + 4 K bytes (tools/trellis/tqenc.hpp). They go through the same entry points below.
constexpr int kTQK6 = 145, kTQK7 = 146, kTQK5X = 224, kTQK4X = 225, kTQK5T = 226, kTQK4T = 227;
constexpr int tq_kbits(int type) {
return type == kTQK6 ? 6 : type == kTQK7 ? 7 : (type == kTQK5X || type == kTQK5T) ? 5 : (type == kTQK4X || type == kTQK4T) ? 4 : 0;
}
constexpr bool is_tq(int type) { return tq_kbits(type) > 0; }
/// Whether the device kernels take this ggml type.
bool supported(int type);
/// Whether the type's block layout is known (its row bytes can be computed). It covered more than supported() while
/// IQ1_S, IQ1_M and IQ4_NL had no device kernel; they have one now, so both take the same types.
bool known(int type);
/// Values a block of the type holds (256; the trellis types 128; 0: not one of these).
int block_values(int type);
/// Bytes of a block of the type (0: not one of these).
int block_bytes(int type);
/// Bytes of a row of k values (k % block_values == 0).
inline size_t row_bytes(int type, int64_t k) { return (size_t) (k / block_values(type)) * (size_t) block_bytes(type); }
/// The type's name ("?" when unknown).
const char* name(int type);
/// The token / window experts (ds4_gguf.cu's MxArgs, with the roles' types): group g = an expert (grp_ptr null: expert g
/// of the plan, plan_ptr[g] its blob or 0, its entry g, input row 0; else blob grp_ptr[g], entries grp_ent[grp_start[g]
/// ..], entry e's input row e >> 3). x / h as int8 rows with an F32 scale per 32 (xq, xd: rows of n_embd; hq, hd: row e
/// = entry e, rows of n_ff).
struct Args {
const unsigned long long* plan_ptr = nullptr;
const unsigned long long* grp_ptr = nullptr;
const int *grp_start = nullptr, *grp_ent = nullptr, *n_groups = nullptr;
size_t tr[3] = {0, 0, 0}; // the roles' offsets in a blob
int n_embd = 0, n_ff = 0;
float limit = 0.0f;
const int8_t* xq = nullptr;
const float* xd = nullptr;
const int8_t* hq = nullptr;
const float* hd = nullptr;
float* h = nullptr; // [entries][n_ff]: the clamped swiglu
float* part = nullptr; // [entries][n_embd]: each entry's down output
int tg = 0, td = 0; // gate / up's type, down's
};
/// grid (n_ff / 8, groups): h of every entry (ne_max: a group's most entries). false: a type not covered.
bool gate_up(const Args& a, int groups, int ne_max, cudaStream_t s);
/// grid (n_embd / 8, groups): part of every entry.
bool down(const Args& a, int groups, int ne_max, cudaStream_t s);
/// The prompt path's expert sets (ds4_gguf.cu's SetK): expert i's blob at wbase + i stride owns the sorted rows
/// [bounds[i], bounds[i + 1]) (local row = sorted row - row0); gate / up: h16[local] = F16 swiglu over x[idx[local]]
/// (F32 rows, ldx); down: y[local] = down(h16[local]) (F16 rows in, ldx; F32 out, ldo). A set's experts of at most 16
/// rows take the token kernels' form (each weight read once, the rows' inputs rounded to int8 per 32 as the token path
/// rounds them; STRATA_DS4_NO_LIGHT=1: never), the others GEMM tiles (tensor cores on CUDA, F16 operands).
struct SetArgs {
const uint8_t* wbase = nullptr;
size_t stride = 0;
size_t tr[3] = {0, 0, 0};
const int* bounds = nullptr;
int row0 = 0, max_rows = 0, n_exp = 0;
int n_embd = 0, n_ff = 0;
float limit = 0.0f;
const float* xf = nullptr;
const int* idx = nullptr;
const uint16_t* xh = nullptr;
int ldx = 0;
uint16_t* h = nullptr;
float* y = nullptr;
int ldo = 0;
int tg = 0, td = 0;
int skip_le = 0; // (the tiles) the experts of at most this many rows are left out: the light kernels took them
};
bool set_gate_up(const SetArgs& a, cudaStream_t s);
bool set_down(const SetArgs& a, cudaStream_t s);
/// The light form alone (the set's experts of at most 16 rows; the others untouched), for any of these types and MXFP4
/// (tg / td 39: ds4_gguf.cu's experts): false (nothing launched) when it is switched off - the caller's tiles take every
/// expert then; true: they take those of more rows (skip_le 16).
bool light_gate_up(const SetArgs& a, cudaStream_t s);
bool light_down(const SetArgs& a, cudaStream_t s);
/// GEMV jobs on such matrices (an expert's views on the host-routed path): y[c][r] = alpha (row r . x_c) + bias[r] for
/// ncol activations, x as int8 rows (xq + c k, scales xd + c k / 32).
struct MvJob {
const uint8_t* w = nullptr;
size_t ld = 0; // bytes a row
int type = 0, k = 0, n = 0, ncol = 1;
const int8_t* xq = nullptr;
const float* xd = nullptr;
float* y = nullptr;
size_t ycs = 0;
const float* bias = nullptr;
float alpha = 1.0f;
};
bool mv(const MvJob* jobs, int n, cudaStream_t s);
/// n rows of k values of a matrix of the type (ld bytes a row) as BF16 (bf16) or F16 bits, dst[n][k]: the chunked prompt path's
/// dense GEMM operand. false: a type not covered.
bool dequant_rows(int type, const void* raw, size_t ld, int k, int n, uint16_t* dst, bool bf16, cudaStream_t s);
/// The trellis types' kernels (ds4_tq.cu), reached from the entry points above for those types: arithmetic as the CPU lane's
/// (ds4_tq_cpu.cpp: int8 activations with an F32 scale a 32, exact weights), on the tensor cores of gfx12 (WMMA) or in FMAs.
namespace tq {
bool gate_up(const Args& a, int groups, int ne_max, cudaStream_t s);
bool down(const Args& a, int groups, int ne_max, cudaStream_t s);
bool set_gate_up(const SetArgs& a, cudaStream_t s);
bool set_down(const SetArgs& a, cudaStream_t s);
bool mv(const MvJob* jobs, int n, cudaStream_t s);
} // namespace tq
} // namespace strata::ds4::gguf::iq
+515
View File
@@ -0,0 +1,515 @@
// Generated from ggml-common.h iq1s_grid_gpu (third_party/ggml): entry (neg << 11 | grid index) -> the 8 int8 codes of an
// IQ1_M / IQ1_S group (iq1_codes of its low and its high nibbles), the delta sign folded in. Checked against the device
// computation by ds4_iq_test (bit-compare) and against ggml by its parity checks.
{0xf9f9f9f9,0xf9f9f9f9},{0xf9f9f909,0xf9f9f9f9},{0xf9f90101,0xf9f9f9f9},{0xf9f909f9,0xf9f9f9f9},{0xf9f90909,0xf9f9f9f9},{0xf901f901,0xf9f9f9f9},{0xf9010101,0xf9f9f9f9},{0xf909f9f9,0xf9f9f9f9},
{0xf909f909,0xf9f9f9f9},{0xf90909f9,0xf9f9f9f9},{0xf9090909,0xf9f9f9f9},{0x01f90101,0xf9f9f9f9},{0x0101f901,0xf9f9f9f9},{0x010101f9,0xf9f9f9f9},{0x01010109,0xf9f9f9f9},{0x01090101,0xf9f9f9f9},
{0x09f9f9f9,0xf9f9f9f9},{0x09f9f909,0xf9f9f9f9},{0x09f909f9,0xf9f9f9f9},{0x09f90909,0xf9f9f9f9},{0x09010101,0xf9f9f9f9},{0x0909f9f9,0xf9f9f9f9},{0x0909f909,0xf9f9f9f9},{0x090909f9,0xf9f9f9f9},
{0x09090909,0xf9f9f9f9},{0xf9f901f9,0xf9f9f901},{0xf9f90101,0xf9f9f901},{0xf901f901,0xf9f9f901},{0xf90101f9,0xf9f9f901},{0xf9010109,0xf9f9f901},{0xf9010901,0xf9f9f901},{0xf9010909,0xf9f9f901},
{0xf9090101,0xf9f9f901},{0x01f9f901,0xf9f9f901},{0x01f90109,0xf9f9f901},{0x01f90901,0xf9f9f901},{0x0101f909,0xf9f9f901},{0x01010101,0xf9f9f901},{0x01010909,0xf9f9f901},{0x0109f901,0xf9f9f901},
{0x010901f9,0xf9f9f901},{0x01090109,0xf9f9f901},{0x010909f9,0xf9f9f901},{0x09f90101,0xf9f9f901},{0x0901f901,0xf9f9f901},{0x090101f9,0xf9f9f901},{0x09010109,0xf9f9f901},{0x09090101,0xf9f9f901},
{0xf9f9f9f9,0xf9f9f909},{0xf9f9f909,0xf9f9f909},{0xf9f909f9,0xf9f9f909},{0xf9f90909,0xf9f9f909},{0xf9010101,0xf9f9f909},{0xf909f9f9,0xf9f9f909},{0xf909f909,0xf9f9f909},{0xf90909f9,0xf9f9f909},
{0xf9090909,0xf9f9f909},{0x01f90101,0xf9f9f909},{0x0101f901,0xf9f9f909},{0x01010901,0xf9f9f909},{0x010901f9,0xf9f9f909},{0x01090901,0xf9f9f909},{0x09f9f9f9,0xf9f9f909},{0x09f9f909,0xf9f9f909},
{0x09f909f9,0xf9f9f909},{0x09f90909,0xf9f9f909},{0x0901f901,0xf9f9f909},{0x09010101,0xf9f9f909},{0x09010901,0xf9f9f909},{0x0909f9f9,0xf9f9f909},{0x0909f909,0xf9f9f909},{0x090909f9,0xf9f9f909},
{0x09090909,0xf9f9f909},{0xf901f901,0xf9f901f9},{0xf90101f9,0xf9f901f9},{0xf9010109,0xf9f901f9},{0xf9090101,0xf9f901f9},{0x01f9f901,0xf9f901f9},{0x01f90901,0xf9f901f9},{0x01010101,0xf9f901f9},
{0x01010909,0xf9f901f9},{0x010901f9,0xf9f901f9},{0x01090101,0xf9f901f9},{0x0901f901,0xf9f901f9},{0x09010901,0xf9f901f9},{0x09090101,0xf9f901f9},{0xf9f9f901,0xf9f90101},{0xf9f901f9,0xf9f90101},
{0xf9f90101,0xf9f90101},{0xf9f90109,0xf9f90101},{0xf9010101,0xf9f90101},{0xf90109f9,0xf9f90101},{0xf9010909,0xf9f90101},{0xf9090901,0xf9f90101},{0x01f9f9f9,0xf9f90101},{0x01f90101,0xf9f90101},
{0x01f90909,0xf9f90101},{0x0101f9f9,0xf9f90101},{0x0101f901,0xf9f90101},{0x010101f9,0xf9f90101},{0x01010101,0xf9f90101},{0x01010109,0xf9f90101},{0x01010901,0xf9f90101},{0x0109f9f9,0xf9f90101},
{0x0109f909,0xf9f90101},{0x01090101,0xf9f90101},{0x010909f9,0xf9f90101},{0x01090909,0xf9f90101},{0x09f9f901,0xf9f90101},{0x0901f901,0xf9f90101},{0x09010101,0xf9f90101},{0x090109f9,0xf9f90101},
{0x09010909,0xf9f90101},{0x0909f901,0xf9f90101},{0x090901f9,0xf9f90101},{0x09090101,0xf9f90101},{0x09090109,0xf9f90101},{0x09090901,0xf9f90101},{0xf90101f9,0xf9f90109},{0xf9010901,0xf9f90109},
{0x01f9f901,0xf9f90109},{0x01f901f9,0xf9f90109},{0x0101f9f9,0xf9f90109},{0x0101f909,0xf9f90109},{0x01010101,0xf9f90109},{0x010109f9,0xf9f90109},{0x0109f9f9,0xf9f90109},{0x0109f901,0xf9f90109},
{0x01090109,0xf9f90109},{0x01090901,0xf9f90109},{0x09f90101,0xf9f90109},{0x0901f901,0xf9f90109},{0x090101f9,0xf9f90109},{0x09010901,0xf9f90109},{0xf9f9f9f9,0xf9f909f9},{0xf9f9f909,0xf9f909f9},
{0xf9f909f9,0xf9f909f9},{0xf9f90909,0xf9f909f9},{0xf9010101,0xf9f909f9},{0xf909f9f9,0xf9f909f9},{0xf909f909,0xf9f909f9},{0xf90909f9,0xf9f909f9},{0xf9090909,0xf9f909f9},{0x01f90101,0xf9f909f9},
{0x0101f901,0xf9f909f9},{0x01010109,0xf9f909f9},{0x01090101,0xf9f909f9},{0x09f9f9f9,0xf9f909f9},{0x09f9f909,0xf9f909f9},{0x09f909f9,0xf9f909f9},{0x09f90909,0xf9f909f9},{0x09010101,0xf9f909f9},
{0x0909f9f9,0xf9f909f9},{0x0909f909,0xf9f909f9},{0x090909f9,0xf9f909f9},{0x09090909,0xf9f909f9},{0xf9f90101,0xf9f90901},{0xf901f901,0xf9f90901},{0xf90101f9,0xf9f90901},{0xf9010901,0xf9f90901},
{0xf90901f9,0xf9f90901},{0xf9090101,0xf9f90901},{0x01f9f901,0xf9f90901},{0x0101f9f9,0xf9f90901},{0x0101f901,0xf9f90901},{0x01010101,0xf9f90901},{0x0109f901,0xf9f90901},{0x010901f9,0xf9f90901},
{0x01090901,0xf9f90901},{0x0901f901,0xf9f90901},{0x090101f9,0xf9f90901},{0x09010109,0xf9f90901},{0x09010901,0xf9f90901},{0x09090101,0xf9f90901},{0xf9f9f9f9,0xf9f90909},{0xf9f9f909,0xf9f90909},
{0xf9f909f9,0xf9f90909},{0xf9f90909,0xf9f90909},{0xf9010101,0xf9f90909},{0xf909f9f9,0xf9f90909},{0xf909f909,0xf9f90909},{0xf90909f9,0xf9f90909},{0xf9090909,0xf9f90909},{0x01f90101,0xf9f90909},
{0x0101f901,0xf9f90909},{0x01010901,0xf9f90909},{0x0109f901,0xf9f90909},{0x01090101,0xf9f90909},{0x09f9f9f9,0xf9f90909},{0x09f9f909,0xf9f90909},{0x09f90101,0xf9f90909},{0x09f909f9,0xf9f90909},
{0x09f90909,0xf9f90909},{0x09010101,0xf9f90909},{0x0909f9f9,0xf9f90909},{0x0909f909,0xf9f90909},{0x090909f9,0xf9f90909},{0x09090909,0xf9f90909},{0xf901f9f9,0xf901f9f9},{0xf901f901,0xf901f9f9},
{0xf90101f9,0xf901f9f9},{0xf9010901,0xf901f9f9},{0xf90901f9,0xf901f9f9},{0xf9090101,0xf901f9f9},{0x01f9f901,0xf901f9f9},{0x01f901f9,0xf901f9f9},{0x0101f9f9,0xf901f9f9},{0x01010101,0xf901f9f9},
{0x010109f9,0xf901f9f9},{0x0109f901,0xf901f9f9},{0x010901f9,0xf901f9f9},{0x01090101,0xf901f9f9},{0x01090901,0xf901f9f9},{0x0901f901,0xf901f9f9},{0x090101f9,0xf901f9f9},{0x09010109,0xf901f9f9},
{0x0909f901,0xf901f9f9},{0x09090101,0xf901f9f9},{0xf9f9f901,0xf901f901},{0xf9f901f9,0xf901f901},{0xf9f90109,0xf901f901},{0xf9f90901,0xf901f901},{0xf901f9f9,0xf901f901},{0xf901f909,0xf901f901},
{0xf9010101,0xf901f901},{0xf90109f9,0xf901f901},{0xf909f901,0xf901f901},{0xf90901f9,0xf901f901},{0xf9090901,0xf901f901},{0x01f90101,0xf901f901},{0x01f90909,0xf901f901},{0x0101f9f9,0xf901f901},
{0x0101f901,0xf901f901},{0x0101f909,0xf901f901},{0x010101f9,0xf901f901},{0x01010101,0xf901f901},{0x01010109,0xf901f901},{0x01010901,0xf901f901},{0x0109f9f9,0xf901f901},{0x01090101,0xf901f901},
{0x09f901f9,0xf901f901},{0x0901f909,0xf901f901},{0x09010101,0xf901f901},{0x0909f901,0xf901f901},{0x090901f9,0xf901f901},{0xf901f901,0xf901f909},{0xf90101f9,0xf901f909},{0xf9010109,0xf901f909},
{0xf9090101,0xf901f909},{0x01f9f9f9,0xf901f909},{0x01f90109,0xf901f909},{0x01f90901,0xf901f909},{0x0101f909,0xf901f909},{0x01010101,0xf901f909},{0x010109f9,0xf901f909},{0x01010909,0xf901f909},
{0x010901f9,0xf901f909},{0x01090109,0xf901f909},{0x09f90101,0xf901f909},{0x0901f901,0xf901f909},{0x090101f9,0xf901f909},{0x09010109,0xf901f909},{0x09090101,0xf901f909},{0xf9f9f901,0xf90101f9},
{0xf9f90109,0xf90101f9},{0xf9f90901,0xf90101f9},{0xf90101f9,0xf90101f9},{0xf9010101,0xf90101f9},{0xf90109f9,0xf90101f9},{0xf9010901,0xf90101f9},{0xf909f901,0xf90101f9},{0xf9090109,0xf90101f9},
{0x01f9f901,0xf90101f9},{0x01f90101,0xf90101f9},{0x01f90109,0xf90101f9},{0x01f909f9,0xf90101f9},{0x01f90909,0xf90101f9},{0x0101f901,0xf90101f9},{0x010101f9,0xf90101f9},{0x01010101,0xf90101f9},
{0x01010109,0xf90101f9},{0x01010901,0xf90101f9},{0x0109f909,0xf90101f9},{0x01090101,0xf90101f9},{0x010909f9,0xf90101f9},{0x09f901f9,0xf90101f9},{0x09f90901,0xf90101f9},{0x0901f9f9,0xf90101f9},
{0x090101f9,0xf90101f9},{0x09010101,0xf90101f9},{0x090109f9,0xf90101f9},{0x09010901,0xf90101f9},{0x09010909,0xf90101f9},{0x0909f901,0xf90101f9},{0x090901f9,0xf90101f9},{0x09090101,0xf90101f9},
{0x09090901,0xf90101f9},{0xf9f9f909,0xf9010101},{0xf9f90101,0xf9010101},{0xf9f90909,0xf9010101},{0xf901f901,0xf9010101},{0xf90101f9,0xf9010101},{0xf9010101,0xf9010101},{0xf9010109,0xf9010101},
{0xf9010901,0xf9010101},{0xf909f9f9,0xf9010101},{0xf909f909,0xf9010101},{0xf9090101,0xf9010101},{0xf90909f9,0xf9010101},{0xf9090909,0xf9010101},{0x01f9f901,0xf9010101},{0x01f901f9,0xf9010101},
{0x01f90101,0xf9010101},{0x01f90109,0xf9010101},{0x0101f901,0xf9010101},{0x0101f909,0xf9010101},{0x010101f9,0xf9010101},{0x01010101,0xf9010101},{0x01010109,0xf9010101},{0x01010901,0xf9010101},
{0x01010909,0xf9010101},{0x0109f901,0xf9010101},{0x010901f9,0xf9010101},{0x01090101,0xf9010101},{0x01090109,0xf9010101},{0x01090901,0xf9010101},{0x09f9f9f9,0xf9010101},{0x09f9f909,0xf9010101},
{0x09f901f9,0xf9010101},{0x09f90101,0xf9010101},{0x09f909f9,0xf9010101},{0x09f90909,0xf9010101},{0x0901f9f9,0xf9010101},{0x0901f901,0xf9010101},{0x090101f9,0xf9010101},{0x09010101,0xf9010101},
{0x09010109,0xf9010101},{0x09010901,0xf9010101},{0x09010909,0xf9010101},{0x0909f9f9,0xf9010101},{0x0909f909,0xf9010101},{0x09090101,0xf9010101},{0xf9f9f901,0xf9010109},{0xf9f901f9,0xf9010109},
{0xf9f90101,0xf9010109},{0xf9f90109,0xf9010109},{0xf9010101,0xf9010109},{0xf9010109,0xf9010109},{0xf90109f9,0xf9010109},{0xf9010909,0xf9010109},{0xf909f901,0xf9010109},{0xf9090109,0xf9010109},
{0x01f9f9f9,0xf9010109},{0x01f9f909,0xf9010109},{0x01f901f9,0xf9010109},{0x01f90101,0xf9010109},{0x01f909f9,0xf9010109},{0x01f90909,0xf9010109},{0x0101f901,0xf9010109},{0x01010101,0xf9010109},
{0x01010109,0xf9010109},{0x010109f9,0xf9010109},{0x01010901,0xf9010109},{0x0109f901,0xf9010109},{0x010901f9,0xf9010109},{0x01090101,0xf9010109},{0x010909f9,0xf9010109},{0x01090901,0xf9010109},
{0x01090909,0xf9010109},{0x09f90109,0xf9010109},{0x09f90909,0xf9010109},{0x0901f909,0xf9010109},{0x09010101,0xf9010109},{0x090901f9,0xf9010109},{0x09090901,0xf9010109},{0xf901f901,0xf90109f9},
{0xf9010109,0xf90109f9},{0xf9090101,0xf90109f9},{0x01f9f901,0xf90109f9},{0x01f901f9,0xf90109f9},{0x01f90109,0xf90109f9},{0x01f90901,0xf90109f9},{0x0101f9f9,0xf90109f9},{0x01010101,0xf90109f9},
{0x010109f9,0xf90109f9},{0x01010909,0xf90109f9},{0x0109f9f9,0xf90109f9},{0x0109f901,0xf90109f9},{0x010901f9,0xf90109f9},{0x01090109,0xf90109f9},{0x01090901,0xf90109f9},{0x09f90101,0xf90109f9},
{0x0901f901,0xf90109f9},{0x090101f9,0xf90109f9},{0x09090101,0xf90109f9},{0xf901f9f9,0xf9010901},{0xf901f909,0xf9010901},{0xf9010101,0xf9010901},{0xf9010909,0xf9010901},{0xf909f901,0xf9010901},
{0xf9090101,0xf9010901},{0x01f9f909,0xf9010901},{0x01f901f9,0xf9010901},{0x01f90101,0xf9010901},{0x01f909f9,0xf9010901},{0x0101f901,0xf9010901},{0x010101f9,0xf9010901},{0x01010101,0xf9010901},
{0x01010109,0xf9010901},{0x01010901,0xf9010901},{0x01010909,0xf9010901},{0x0109f9f9,0xf9010901},{0x01090101,0xf9010901},{0x01090909,0xf9010901},{0x09f90901,0xf9010901},{0x0901f901,0xf9010901},
{0x0901f909,0xf9010901},{0x09010101,0xf9010901},{0x090109f9,0xf9010901},{0x0909f901,0xf9010901},{0x09090109,0xf9010901},{0x09090901,0xf9010901},{0xf9f90901,0xf9010909},{0xf9010109,0xf9010909},
{0xf90901f9,0xf9010909},{0xf9090109,0xf9010909},{0x01f901f9,0xf9010909},{0x01f90109,0xf9010909},{0x01f90901,0xf9010909},{0x0101f9f9,0xf9010909},{0x0101f909,0xf9010909},{0x01010101,0xf9010909},
{0x010109f9,0xf9010909},{0x0109f901,0xf9010909},{0x01090109,0xf9010909},{0x01090901,0xf9010909},{0x09f90101,0xf9010909},{0x0901f901,0xf9010909},{0x09010109,0xf9010909},{0x09010909,0xf9010909},
{0xf9f9f9f9,0xf909f9f9},{0xf9f9f909,0xf909f9f9},{0xf9f909f9,0xf909f9f9},{0xf9f90909,0xf909f9f9},{0xf9010101,0xf909f9f9},{0xf909f9f9,0xf909f9f9},{0xf909f909,0xf909f9f9},{0xf9090101,0xf909f9f9},
{0xf90909f9,0xf909f9f9},{0xf9090909,0xf909f9f9},{0x01f90101,0xf909f9f9},{0x0101f901,0xf909f9f9},{0x01010901,0xf909f9f9},{0x0109f901,0xf909f9f9},{0x01090101,0xf909f9f9},{0x09f9f9f9,0xf909f9f9},
{0x09f9f909,0xf909f9f9},{0x09f909f9,0xf909f9f9},{0x09f90909,0xf909f9f9},{0x09010101,0xf909f9f9},{0x0909f9f9,0xf909f9f9},{0x0909f909,0xf909f9f9},{0x09090101,0xf909f9f9},{0x090909f9,0xf909f9f9},
{0x09090909,0xf909f9f9},{0xf9f90101,0xf909f901},{0xf901f901,0xf909f901},{0xf90101f9,0xf909f901},{0xf9010901,0xf909f901},{0xf9090101,0xf909f901},{0x01f9f909,0xf909f901},{0x01f901f9,0xf909f901},
{0x01f90901,0xf909f901},{0x01010101,0xf909f901},{0x010109f9,0xf909f901},{0x01010909,0xf909f901},{0x0109f901,0xf909f901},{0x010901f9,0xf909f901},{0x01090101,0xf909f901},{0x01090109,0xf909f901},
{0x09f90101,0xf909f901},{0x0901f9f9,0xf909f901},{0x09010109,0xf909f901},{0x09010901,0xf909f901},{0x09090101,0xf909f901},{0xf9f9f901,0xf909f909},{0xf9f909f9,0xf909f909},{0xf9f90909,0xf909f909},
{0xf901f901,0xf909f909},{0xf9010101,0xf909f909},{0xf909f9f9,0xf909f909},{0xf909f909,0xf909f909},{0xf90909f9,0xf909f909},{0xf9090909,0xf909f909},{0x01f90101,0xf909f909},{0x0101f901,0xf909f909},
{0x01010109,0xf909f909},{0x01010901,0xf909f909},{0x01090101,0xf909f909},{0x09f9f901,0xf909f909},{0x09f909f9,0xf909f909},{0x09f90909,0xf909f909},{0x0901f901,0xf909f909},{0x09010101,0xf909f909},
{0x0909f9f9,0xf909f909},{0x0909f909,0xf909f909},{0x090909f9,0xf909f909},{0x09090909,0xf909f909},{0xf9f90101,0xf90901f9},{0xf90101f9,0xf90901f9},{0xf9010109,0xf90901f9},{0xf9010901,0xf90901f9},
{0xf9090101,0xf90901f9},{0x01f901f9,0xf90901f9},{0x01f90101,0xf90901f9},{0x01f90109,0xf90901f9},{0x01f90901,0xf90901f9},{0x0101f909,0xf90901f9},{0x01010101,0xf90901f9},{0x010109f9,0xf90901f9},
{0x01010909,0xf90901f9},{0x01090109,0xf90901f9},{0x09f90101,0xf90901f9},{0x0901f901,0xf90901f9},{0x090101f9,0xf90901f9},{0x09010901,0xf90901f9},{0x0909f901,0xf90901f9},{0x09090101,0xf90901f9},
{0xf9f90901,0xf9090101},{0xf9010101,0xf9090101},{0xf909f901,0xf9090101},{0xf9090901,0xf9090101},{0x01f9f9f9,0xf9090101},{0x01f90101,0xf9090101},{0x01f909f9,0xf9090101},{0x0101f901,0xf9090101},
{0x010101f9,0xf9090101},{0x01010101,0xf9090101},{0x01010901,0xf9090101},{0x0109f909,0xf9090101},{0x01090101,0xf9090101},{0x010909f9,0xf9090101},{0x09f90901,0xf9090101},{0x0901f9f9,0xf9090101},
{0x090101f9,0xf9090101},{0x09010101,0xf9090101},{0x090109f9,0xf9090101},{0x09010909,0xf9090101},{0x0909f901,0xf9090101},{0x090901f9,0xf9090101},{0x09090109,0xf9090101},{0x09090901,0xf9090101},
{0xf9f90101,0xf9090109},{0xf901f9f9,0xf9090109},{0xf901f909,0xf9090109},{0xf9010901,0xf9090109},{0xf9090101,0xf9090109},{0x01f9f901,0xf9090109},{0x01f90901,0xf9090109},{0x01010101,0xf9090109},
{0x0109f9f9,0xf9090109},{0x0109f901,0xf9090109},{0x01090901,0xf9090109},{0x09f901f9,0xf9090109},{0x09f90109,0xf9090109},{0x0901f9f9,0xf9090109},{0x09010909,0xf9090109},{0xf9f9f9f9,0xf90909f9},
{0xf9f9f909,0xf90909f9},{0xf9f909f9,0xf90909f9},{0xf9f90909,0xf90909f9},{0xf9010101,0xf90909f9},{0xf909f9f9,0xf90909f9},{0xf909f909,0xf90909f9},{0xf90909f9,0xf90909f9},{0xf9090909,0xf90909f9},
{0x01f90101,0xf90909f9},{0x0101f901,0xf90909f9},{0x010101f9,0xf90909f9},{0x01090101,0xf90909f9},{0x09f9f9f9,0xf90909f9},{0x09f9f909,0xf90909f9},{0x09f909f9,0xf90909f9},{0x09f90909,0xf90909f9},
{0x0909f9f9,0xf90909f9},{0x0909f909,0xf90909f9},{0x090909f9,0xf90909f9},{0x09090909,0xf90909f9},{0xf9f90901,0xf9090901},{0xf901f901,0xf9090901},{0xf90101f9,0xf9090901},{0xf9010901,0xf9090901},
{0xf9090101,0xf9090901},{0x01f90109,0xf9090901},{0x01f90901,0xf9090901},{0x0101f909,0xf9090901},{0x01010101,0xf9090901},{0x0109f901,0xf9090901},{0x010901f9,0xf9090901},{0x01090109,0xf9090901},
{0x01090901,0xf9090901},{0x09f90101,0xf9090901},{0x0901f9f9,0xf9090901},{0x09010109,0xf9090901},{0x09010901,0xf9090901},{0x090901f9,0xf9090901},{0x09090101,0xf9090901},{0xf9f9f9f9,0xf9090909},
{0xf9f9f909,0xf9090909},{0xf9f909f9,0xf9090909},{0xf9f90909,0xf9090909},{0xf909f9f9,0xf9090909},{0xf909f909,0xf9090909},{0xf90909f9,0xf9090909},{0xf9090909,0xf9090909},{0x01f90101,0xf9090909},
{0x0101f901,0xf9090909},{0x01010109,0xf9090909},{0x01010901,0xf9090909},{0x01090101,0xf9090909},{0x09f9f9f9,0xf9090909},{0x09f9f909,0xf9090909},{0x09f909f9,0xf9090909},{0x09f90909,0xf9090909},
{0x09010101,0xf9090909},{0x0909f9f9,0xf9090909},{0x0909f909,0xf9090909},{0x090909f9,0xf9090909},{0x09090909,0xf9090909},{0xf9f90101,0x01f9f9f9},{0xf901f901,0x01f9f9f9},{0xf9010109,0x01f9f9f9},
{0xf9090101,0x01f9f9f9},{0x01f90901,0x01f9f9f9},{0x0101f909,0x01f9f9f9},{0x01010101,0x01f9f9f9},{0x010109f9,0x01f9f9f9},{0x01010909,0x01f9f9f9},{0x0109f901,0x01f9f9f9},{0x010901f9,0x01f9f9f9},
{0x01090109,0x01f9f9f9},{0x090101f9,0x01f9f9f9},{0x09010901,0x01f9f9f9},{0x0909f901,0x01f9f9f9},{0x09090109,0x01f9f9f9},{0xf9f9f9f9,0x01f9f901},{0xf9f9f901,0x01f9f901},{0xf9f901f9,0x01f9f901},
{0xf9f90109,0x01f9f901},{0xf9f90901,0x01f9f901},{0xf901f909,0x01f9f901},{0xf9010101,0x01f9f901},{0xf9010109,0x01f9f901},{0xf90109f9,0x01f9f901},{0xf9010909,0x01f9f901},{0xf909f901,0x01f9f901},
{0xf9090109,0x01f9f901},{0xf9090901,0x01f9f901},{0x01f90101,0x01f9f901},{0x01f909f9,0x01f9f901},{0x01f90909,0x01f9f901},{0x0101f901,0x01f9f901},{0x010101f9,0x01f9f901},{0x01010101,0x01f9f901},
{0x01010109,0x01f9f901},{0x01010901,0x01f9f901},{0x01010909,0x01f9f901},{0x01090101,0x01f9f901},{0x010909f9,0x01f9f901},{0x01090909,0x01f9f901},{0x09f9f901,0x01f9f901},{0x09f901f9,0x01f9f901},
{0x09f90109,0x01f9f901},{0x0901f9f9,0x01f9f901},{0x0901f909,0x01f9f901},{0x09010101,0x01f9f901},{0x0909f9f9,0x01f9f901},{0x0909f901,0x01f9f901},{0x0909f909,0x01f9f901},{0xf9f90101,0x01f9f909},
{0xf901f901,0x01f9f909},{0xf90101f9,0x01f9f909},{0xf9010109,0x01f9f909},{0xf9090101,0x01f9f909},{0x01f9f901,0x01f9f909},{0x0101f909,0x01f9f909},{0x01010101,0x01f9f909},{0x01010909,0x01f9f909},
{0x010901f9,0x01f9f909},{0x01090901,0x01f9f909},{0x09f90901,0x01f9f909},{0x090101f9,0x01f9f909},{0x09090101,0x01f9f909},{0xf9f9f901,0x01f901f9},{0xf9010101,0x01f901f9},{0xf9010901,0x01f901f9},
{0xf9090901,0x01f901f9},{0x01f90101,0x01f901f9},{0x01f909f9,0x01f901f9},{0x01f90909,0x01f901f9},{0x0101f901,0x01f901f9},{0x010101f9,0x01f901f9},{0x01010101,0x01f901f9},{0x01010109,0x01f901f9},
{0x0109f901,0x01f901f9},{0x0109f909,0x01f901f9},{0x01090101,0x01f901f9},{0x010909f9,0x01f901f9},{0x01090909,0x01f901f9},{0x09f9f901,0x01f901f9},{0x09f90109,0x01f901f9},{0x09f90901,0x01f901f9},
{0x0901f9f9,0x01f901f9},{0x0901f909,0x01f901f9},{0x09010101,0x01f901f9},{0x0909f9f9,0x01f901f9},{0x0909f901,0x01f901f9},{0x09090901,0x01f901f9},{0xf9f9f901,0x01f90101},{0xf9f9f909,0x01f90101},
{0xf9f90101,0x01f90101},{0xf9f90909,0x01f90101},{0xf901f901,0x01f90101},{0xf90101f9,0x01f90101},{0xf9010101,0x01f90101},{0xf9010109,0x01f90101},{0xf9010901,0x01f90101},{0xf909f9f9,0x01f90101},
{0xf9090101,0x01f90101},{0xf9090909,0x01f90101},{0x01f9f901,0x01f90101},{0x01f901f9,0x01f90101},{0x01f90101,0x01f90101},{0x01f90109,0x01f90101},{0x01f90901,0x01f90101},{0x0101f9f9,0x01f90101},
{0x0101f901,0x01f90101},{0x010101f9,0x01f90101},{0x01010101,0x01f90101},{0x01010109,0x01f90101},{0x010109f9,0x01f90101},{0x01010901,0x01f90101},{0x0109f901,0x01f90101},{0x010901f9,0x01f90101},
{0x01090101,0x01f90101},{0x01090109,0x01f90101},{0x01090901,0x01f90101},{0x09f9f909,0x01f90101},{0x09f901f9,0x01f90101},{0x09f90101,0x01f90101},{0x09f909f9,0x01f90101},{0x0901f901,0x01f90101},
{0x090101f9,0x01f90101},{0x09010101,0x01f90101},{0x09010109,0x01f90101},{0x09010901,0x01f90101},{0x09010909,0x01f90101},{0x09090101,0x01f90101},{0x090909f9,0x01f90101},{0x09090909,0x01f90101},
{0xf9f9f901,0x01f90109},{0xf9f90101,0x01f90109},{0xf9f90901,0x01f90109},{0xf90101f9,0x01f90109},{0xf9010101,0x01f90109},{0xf90109f9,0x01f90109},{0xf9010909,0x01f90109},{0xf909f901,0x01f90109},
{0xf90901f9,0x01f90109},{0xf9090901,0x01f90109},{0x01f9f9f9,0x01f90109},{0x01f9f909,0x01f90109},{0x01f90101,0x01f90109},{0x01f909f9,0x01f90109},{0x0101f9f9,0x01f90109},{0x0101f901,0x01f90109},
{0x0101f909,0x01f90109},{0x01010101,0x01f90109},{0x01010109,0x01f90109},{0x01010901,0x01f90109},{0x0109f909,0x01f90109},{0x01090101,0x01f90109},{0x010909f9,0x01f90109},{0x09f9f901,0x01f90109},
{0x09f90101,0x01f90109},{0x09f90909,0x01f90109},{0x090101f9,0x01f90109},{0x09010101,0x01f90109},{0x0909f901,0x01f90109},{0x090901f9,0x01f90109},{0x09090109,0x01f90109},{0xf9f90101,0x01f909f9},
{0xf901f901,0x01f909f9},{0xf9010101,0x01f909f9},{0xf9010909,0x01f909f9},{0xf9090101,0x01f909f9},{0x01f9f909,0x01f909f9},{0x01f90901,0x01f909f9},{0x0101f9f9,0x01f909f9},{0x01010101,0x01f909f9},
{0x010109f9,0x01f909f9},{0x0109f901,0x01f909f9},{0x010901f9,0x01f909f9},{0x01090109,0x01f909f9},{0x01090901,0x01f909f9},{0x09f90101,0x01f909f9},{0x0901f901,0x01f909f9},{0x090101f9,0x01f909f9},
{0x09010109,0x01f909f9},{0x09010901,0x01f909f9},{0x09090101,0x01f909f9},{0xf9f9f901,0x01f90901},{0xf9f90101,0x01f90901},{0xf9f90109,0x01f90901},{0xf9f90909,0x01f90901},{0xf901f9f9,0x01f90901},
{0xf90101f9,0x01f90901},{0xf9010101,0x01f90901},{0xf90109f9,0x01f90901},{0xf909f901,0x01f90901},{0xf90901f9,0x01f90901},{0xf9090109,0x01f90901},{0x01f9f9f9,0x01f90901},{0x01f90101,0x01f90901},
{0x01f90909,0x01f90901},{0x0101f901,0x01f90901},{0x0101f909,0x01f90901},{0x010101f9,0x01f90901},{0x01010101,0x01f90901},{0x01010109,0x01f90901},{0x01010901,0x01f90901},{0x0109f9f9,0x01f90901},
{0x0109f909,0x01f90901},{0x01090101,0x01f90901},{0x01090109,0x01f90901},{0x01090909,0x01f90901},{0x09f90109,0x01f90901},{0x09f90901,0x01f90901},{0x0901f909,0x01f90901},{0x09010101,0x01f90901},
{0x09010109,0x01f90901},{0x090109f9,0x01f90901},{0x0909f901,0x01f90901},{0x090901f9,0x01f90901},{0x09090109,0x01f90901},{0x09090901,0x01f90901},{0xf9010109,0x01f90909},{0x01f901f9,0x01f90909},
{0x01f90109,0x01f90909},{0x01f90901,0x01f90909},{0x01010101,0x01f90909},{0x010109f9,0x01f90909},{0x01010909,0x01f90909},{0x010901f9,0x01f90909},{0x01090901,0x01f90909},{0x090101f9,0x01f90909},
{0x09090101,0x01f90909},{0xf9f9f901,0x0101f9f9},{0xf9f901f9,0x0101f9f9},{0xf9f90101,0x0101f9f9},{0xf9f90109,0x0101f9f9},{0xf9f90901,0x0101f9f9},{0xf901f909,0x0101f9f9},{0xf9010101,0x0101f9f9},
{0xf9010909,0x0101f9f9},{0xf909f901,0x0101f9f9},{0xf90901f9,0x0101f9f9},{0xf9090901,0x0101f9f9},{0x01f9f9f9,0x0101f9f9},{0x01f90101,0x0101f9f9},{0x01f909f9,0x0101f9f9},{0x0101f901,0x0101f9f9},
{0x010101f9,0x0101f9f9},{0x01010101,0x0101f9f9},{0x01010109,0x0101f9f9},{0x01010901,0x0101f9f9},{0x01090101,0x0101f9f9},{0x010909f9,0x0101f9f9},{0x09f90109,0x0101f9f9},{0x09f90901,0x0101f9f9},
{0x09010101,0x0101f9f9},{0x090109f9,0x0101f9f9},{0x0909f9f9,0x0101f9f9},{0x0909f901,0x0101f9f9},{0x09090109,0x0101f9f9},{0x09090901,0x0101f9f9},{0xf9f90101,0x0101f901},{0xf9f909f9,0x0101f901},
{0xf9f90901,0x0101f901},{0xf9f90909,0x0101f901},{0xf901f901,0x0101f901},{0xf90101f9,0x0101f901},{0xf9010101,0x0101f901},{0xf9010109,0x0101f901},{0xf90109f9,0x0101f901},{0xf9010901,0x0101f901},
{0xf909f9f9,0x0101f901},{0xf9090101,0x0101f901},{0xf9090109,0x0101f901},{0xf90909f9,0x0101f901},{0xf9090909,0x0101f901},{0x01f9f901,0x0101f901},{0x01f901f9,0x0101f901},{0x01f90101,0x0101f901},
{0x01f90109,0x0101f901},{0x01f90901,0x0101f901},{0x0101f9f9,0x0101f901},{0x0101f901,0x0101f901},{0x0101f909,0x0101f901},{0x010101f9,0x0101f901},{0x01010101,0x0101f901},{0x01010109,0x0101f901},
{0x010109f9,0x0101f901},{0x01010901,0x0101f901},{0x01010909,0x0101f901},{0x0109f901,0x0101f901},{0x010901f9,0x0101f901},{0x01090101,0x0101f901},{0x01090109,0x0101f901},{0x01090901,0x0101f901},
{0x09f9f909,0x0101f901},{0x09f90101,0x0101f901},{0x0901f901,0x0101f901},{0x090101f9,0x0101f901},{0x09010101,0x0101f901},{0x09010109,0x0101f901},{0x09010901,0x0101f901},{0x0909f9f9,0x0101f901},
{0x09090101,0x0101f901},{0x09090909,0x0101f901},{0xf9f9f901,0x0101f909},{0xf9f90109,0x0101f909},{0xf901f909,0x0101f909},{0xf9010101,0x0101f909},{0xf9010909,0x0101f909},{0xf909f901,0x0101f909},
{0xf90901f9,0x0101f909},{0x01f9f909,0x0101f909},{0x01f90101,0x0101f909},{0x01f90909,0x0101f909},{0x0101f901,0x0101f909},{0x010101f9,0x0101f909},{0x01010101,0x0101f909},{0x01010109,0x0101f909},
{0x01010901,0x0101f909},{0x0109f909,0x0101f909},{0x01090101,0x0101f909},{0x09f90101,0x0101f909},{0x0901f9f9,0x0101f909},{0x0901f909,0x0101f909},{0x09010101,0x0101f909},{0x09010901,0x0101f909},
{0x09010909,0x0101f909},{0x090901f9,0x0101f909},{0xf9f901f9,0x010101f9},{0xf9f90101,0x010101f9},{0xf901f901,0x010101f9},{0xf90101f9,0x010101f9},{0xf9010101,0x010101f9},{0xf9010109,0x010101f9},
{0xf90109f9,0x010101f9},{0xf9010901,0x010101f9},{0xf909f901,0x010101f9},{0xf9090101,0x010101f9},{0xf90909f9,0x010101f9},{0xf9090909,0x010101f9},{0x01f9f901,0x010101f9},{0x01f901f9,0x010101f9},
{0x01f90101,0x010101f9},{0x01f90109,0x010101f9},{0x01f90901,0x010101f9},{0x01f90909,0x010101f9},{0x0101f9f9,0x010101f9},{0x0101f901,0x010101f9},{0x010101f9,0x010101f9},{0x01010101,0x010101f9},
{0x01010109,0x010101f9},{0x010109f9,0x010101f9},{0x01010901,0x010101f9},{0x01010909,0x010101f9},{0x0109f901,0x010101f9},{0x0109f909,0x010101f9},{0x010901f9,0x010101f9},{0x01090101,0x010101f9},
{0x01090109,0x010101f9},{0x01090901,0x010101f9},{0x09f9f9f9,0x010101f9},{0x09f909f9,0x010101f9},{0x09f90909,0x010101f9},{0x0901f901,0x010101f9},{0x090101f9,0x010101f9},{0x09010101,0x010101f9},
{0x09010109,0x010101f9},{0x09010901,0x010101f9},{0x0909f901,0x010101f9},{0x090901f9,0x010101f9},{0x09090101,0x010101f9},{0x09090909,0x010101f9},{0xf9f9f901,0x01010101},{0xf9f9f909,0x01010101},
{0xf9f901f9,0x01010101},{0xf9f90101,0x01010101},{0xf9f90109,0x01010101},{0xf9f90901,0x01010101},{0xf901f9f9,0x01010101},{0xf901f901,0x01010101},{0xf901f909,0x01010101},{0xf90101f9,0x01010101},
{0xf9010101,0x01010101},{0xf9010109,0x01010101},{0xf9010901,0x01010101},{0xf9010909,0x01010101},{0xf909f901,0x01010101},{0xf90901f9,0x01010101},{0xf9090101,0x01010101},{0xf9090109,0x01010101},
{0xf9090901,0x01010101},{0x01f9f9f9,0x01010101},{0x01f9f901,0x01010101},{0x01f9f909,0x01010101},{0x01f901f9,0x01010101},{0x01f90101,0x01010101},{0x01f90109,0x01010101},{0x01f909f9,0x01010101},
{0x01f90901,0x01010101},{0x0101f9f9,0x01010101},{0x0101f901,0x01010101},{0x0101f909,0x01010101},{0x010101f9,0x01010101},{0x01010101,0x01010101},{0x01010109,0x01010101},{0x010109f9,0x01010101},
{0x01010901,0x01010101},{0x01010909,0x01010101},{0x0109f9f9,0x01010101},{0x0109f901,0x01010101},{0x010901f9,0x01010101},{0x01090101,0x01010101},{0x01090109,0x01010101},{0x010909f9,0x01010101},
{0x01090901,0x01010101},{0x01090909,0x01010101},{0x09f9f901,0x01010101},{0x09f901f9,0x01010101},{0x09f90101,0x01010101},{0x09f90901,0x01010101},{0x09f90909,0x01010101},{0x0901f9f9,0x01010101},
{0x0901f901,0x01010101},{0x090101f9,0x01010101},{0x09010101,0x01010101},{0x09010109,0x01010101},{0x090109f9,0x01010101},{0x09010901,0x01010101},{0x0909f901,0x01010101},{0x090901f9,0x01010101},
{0x09090101,0x01010101},{0x09090109,0x01010101},{0x09090901,0x01010101},{0xf9f9f9f9,0x01010109},{0xf9f9f901,0x01010109},{0xf9f9f909,0x01010109},{0xf9f901f9,0x01010109},{0xf9f90109,0x01010109},
{0xf9f909f9,0x01010109},{0xf9f90901,0x01010109},{0xf901f901,0x01010109},{0xf90101f9,0x01010109},{0xf9010101,0x01010109},{0xf90109f9,0x01010109},{0xf9010901,0x01010109},{0xf909f9f9,0x01010109},
{0xf909f901,0x01010109},{0xf909f909,0x01010109},{0xf90901f9,0x01010109},{0xf9090101,0x01010109},{0xf9090109,0x01010109},{0xf90909f9,0x01010109},{0xf9090901,0x01010109},{0x01f9f901,0x01010109},
{0x01f90101,0x01010109},{0x01f90109,0x01010109},{0x01f909f9,0x01010109},{0x01f90901,0x01010109},{0x01f90909,0x01010109},{0x0101f9f9,0x01010109},{0x0101f901,0x01010109},{0x0101f909,0x01010109},
{0x010101f9,0x01010109},{0x01010101,0x01010109},{0x01010109,0x01010109},{0x010109f9,0x01010109},{0x01010901,0x01010109},{0x01010909,0x01010109},{0x0109f901,0x01010109},{0x010901f9,0x01010109},
{0x01090101,0x01010109},{0x01090901,0x01010109},{0x09f9f909,0x01010109},{0x09f90101,0x01010109},{0x09f90109,0x01010109},{0x09f909f9,0x01010109},{0x09f90901,0x01010109},{0x09f90909,0x01010109},
{0x0901f901,0x01010109},{0x09010101,0x01010109},{0x09010909,0x01010109},{0x0909f909,0x01010109},{0x09090101,0x01010109},{0x09090109,0x01010109},{0x090909f9,0x01010109},{0x09090901,0x01010109},
{0xf9f901f9,0x010109f9},{0xf9f90101,0x010109f9},{0xf9f90109,0x010109f9},{0xf9f90901,0x010109f9},{0xf901f9f9,0x010109f9},{0xf9010101,0x010109f9},{0xf90109f9,0x010109f9},{0xf909f901,0x010109f9},
{0xf9090909,0x010109f9},{0x01f90101,0x010109f9},{0x01f909f9,0x010109f9},{0x01f90909,0x010109f9},{0x0101f901,0x010109f9},{0x010101f9,0x010109f9},{0x01010101,0x010109f9},{0x01010109,0x010109f9},
{0x010109f9,0x010109f9},{0x01010901,0x010109f9},{0x0109f9f9,0x010109f9},{0x0109f909,0x010109f9},{0x010901f9,0x010109f9},{0x01090101,0x010109f9},{0x09f9f909,0x010109f9},{0x09f90901,0x010109f9},
{0x0901f9f9,0x010109f9},{0x0901f909,0x010109f9},{0x09010101,0x010109f9},{0x090109f9,0x010109f9},{0x0909f901,0x010109f9},{0x09090901,0x010109f9},{0xf9f9f901,0x01010901},{0xf9f9f909,0x01010901},
{0xf9f90101,0x01010901},{0xf9f90909,0x01010901},{0xf901f901,0x01010901},{0xf90101f9,0x01010901},{0xf9010101,0x01010901},{0xf9010109,0x01010901},{0xf9010901,0x01010901},{0xf9090101,0x01010901},
{0x01f9f901,0x01010901},{0x01f901f9,0x01010901},{0x01f90101,0x01010901},{0x01f90109,0x01010901},{0x01f90901,0x01010901},{0x0101f9f9,0x01010901},{0x0101f901,0x01010901},{0x0101f909,0x01010901},
{0x010101f9,0x01010901},{0x01010101,0x01010901},{0x01010109,0x01010901},{0x010109f9,0x01010901},{0x01010901,0x01010901},{0x01010909,0x01010901},{0x0109f901,0x01010901},{0x010901f9,0x01010901},
{0x01090101,0x01010901},{0x01090109,0x01010901},{0x01090901,0x01010901},{0x09f9f901,0x01010901},{0x09f90101,0x01010901},{0x09f90901,0x01010901},{0x0901f901,0x01010901},{0x090101f9,0x01010901},
{0x09010101,0x01010901},{0x09010109,0x01010901},{0x090109f9,0x01010901},{0x09010901,0x01010901},{0x09090101,0x01010901},{0xf9f901f9,0x01010909},{0xf9f909f9,0x01010909},{0xf9010101,0x01010909},
{0xf9010909,0x01010909},{0xf909f9f9,0x01010909},{0xf9090101,0x01010909},{0xf9090109,0x01010909},{0xf9090901,0x01010909},{0x01f90101,0x01010909},{0x01f909f9,0x01010909},{0x01f90901,0x01010909},
{0x0101f901,0x01010909},{0x01010101,0x01010909},{0x01010109,0x01010909},{0x010109f9,0x01010909},{0x01010901,0x01010909},{0x0109f909,0x01010909},{0x01090101,0x01010909},{0x010909f9,0x01010909},
{0x01090909,0x01010909},{0x09f9f901,0x01010909},{0x09f90909,0x01010909},{0x0901f909,0x01010909},{0x09010101,0x01010909},{0x09010109,0x01010909},{0x090109f9,0x01010909},{0x09010909,0x01010909},
{0x0909f901,0x01010909},{0xf9f90101,0x0109f9f9},{0xf90101f9,0x0109f9f9},{0xf9010109,0x0109f9f9},{0xf9010901,0x0109f9f9},{0xf9090101,0x0109f9f9},{0x01f901f9,0x0109f9f9},{0x0101f9f9,0x0109f9f9},
{0x01010101,0x0109f9f9},{0x01010109,0x0109f9f9},{0x010109f9,0x0109f9f9},{0x01010909,0x0109f9f9},{0x0109f901,0x0109f9f9},{0x010901f9,0x0109f9f9},{0x01090109,0x0109f9f9},{0x01090901,0x0109f9f9},
{0x09f9f901,0x0109f9f9},{0x09010109,0x0109f9f9},{0x09090101,0x0109f9f9},{0xf9f9f901,0x0109f901},{0xf9f901f9,0x0109f901},{0xf9f90109,0x0109f901},{0xf9f90901,0x0109f901},{0xf901f909,0x0109f901},
{0xf9010101,0x0109f901},{0xf909f901,0x0109f901},{0xf909f909,0x0109f901},{0xf9090109,0x0109f901},{0xf9090901,0x0109f901},{0x01f90101,0x0109f901},{0x01f90901,0x0109f901},{0x0101f901,0x0109f901},
{0x01010101,0x0109f901},{0x01010109,0x0109f901},{0x01010901,0x0109f901},{0x01090101,0x0109f901},{0x01090109,0x0109f901},{0x01090909,0x0109f901},{0x09f901f9,0x0109f901},{0x09f90909,0x0109f901},
{0x0901f909,0x0109f901},{0x09010101,0x0109f901},{0x0909f901,0x0109f901},{0x09090109,0x0109f901},{0x09090901,0x0109f901},{0xf901f901,0x0109f909},{0xf9010109,0x0109f909},{0xf9010901,0x0109f909},
{0x01f9f9f9,0x0109f909},{0x01f9f901,0x0109f909},{0x01f90109,0x0109f909},{0x01010101,0x0109f909},{0x01010109,0x0109f909},{0x010109f9,0x0109f909},{0x0109f9f9,0x0109f909},{0x09f90101,0x0109f909},
{0x0901f901,0x0109f909},{0x09010109,0x0109f909},{0x09090101,0x0109f909},{0xf901f901,0x010901f9},{0xf901f909,0x010901f9},{0xf9010101,0x010901f9},{0xf9010109,0x010901f9},{0xf9010909,0x010901f9},
{0xf909f901,0x010901f9},{0xf9090109,0x010901f9},{0xf9090901,0x010901f9},{0x01f9f9f9,0x010901f9},{0x01f9f909,0x010901f9},{0x01f90101,0x010901f9},{0x01f909f9,0x010901f9},{0x01f90909,0x010901f9},
{0x0101f901,0x010901f9},{0x010101f9,0x010901f9},{0x01010101,0x010901f9},{0x01010109,0x010901f9},{0x01010901,0x010901f9},{0x01010909,0x010901f9},{0x0109f9f9,0x010901f9},{0x0109f909,0x010901f9},
{0x01090101,0x010901f9},{0x09f901f9,0x010901f9},{0x09f90101,0x010901f9},{0x09f90901,0x010901f9},{0x0901f9f9,0x010901f9},{0x0901f909,0x010901f9},{0x090101f9,0x010901f9},{0x09010101,0x010901f9},
{0x09010109,0x010901f9},{0x090109f9,0x010901f9},{0x09010909,0x010901f9},{0x0909f901,0x010901f9},{0x090901f9,0x010901f9},{0x09090901,0x010901f9},{0xf9f90101,0x01090101},{0xf9f909f9,0x01090101},
{0xf9f90909,0x01090101},{0xf901f901,0x01090101},{0xf9010101,0x01090101},{0xf9010109,0x01090101},{0xf9010901,0x01090101},{0x01f901f9,0x01090101},{0x01f90101,0x01090101},{0x01f90109,0x01090101},
{0x01f90901,0x01090101},{0x0101f9f9,0x01090101},{0x0101f901,0x01090101},{0x010101f9,0x01090101},{0x01010101,0x01090101},{0x01010109,0x01090101},{0x01010901,0x01090101},{0x0109f901,0x01090101},
{0x010901f9,0x01090101},{0x01090101,0x01090101},{0x01090109,0x01090101},{0x01090901,0x01090101},{0x09f90109,0x01090101},{0x09f90901,0x01090101},{0x09f90909,0x01090101},{0x0901f901,0x01090101},
{0x09010101,0x01090101},{0x09010109,0x01090101},{0x09010901,0x01090101},{0x09010909,0x01090101},{0x0909f909,0x01090101},{0x09090101,0x01090101},{0x09090109,0x01090101},{0x090909f9,0x01090101},
{0xf9f9f909,0x01090109},{0xf9f90901,0x01090109},{0xf9010101,0x01090109},{0xf909f9f9,0x01090109},{0xf9090109,0x01090109},{0xf90909f9,0x01090109},{0xf9090901,0x01090109},{0x01f9f9f9,0x01090109},
{0x01f90101,0x01090109},{0x01f909f9,0x01090109},{0x01f90909,0x01090109},{0x0101f901,0x01090109},{0x010101f9,0x01090109},{0x01010101,0x01090109},{0x01010109,0x01090109},{0x010109f9,0x01090109},
{0x01010909,0x01090109},{0x0109f9f9,0x01090109},{0x01090101,0x01090109},{0x010909f9,0x01090109},{0x09f9f9f9,0x01090109},{0x09f9f909,0x01090109},{0x09f90101,0x01090109},{0x09f90909,0x01090109},
{0x090101f9,0x01090109},{0x09010109,0x01090109},{0x090109f9,0x01090109},{0x09010901,0x01090109},{0x0909f9f9,0x01090109},{0x090901f9,0x01090109},{0x09090109,0x01090109},{0x09090909,0x01090109},
{0xf9010109,0x010909f9},{0xf9010901,0x010909f9},{0xf9090101,0x010909f9},{0x01f9f901,0x010909f9},{0x0101f909,0x010909f9},{0x01010101,0x010909f9},{0x01010909,0x010909f9},{0x0109f901,0x010909f9},
{0x01090901,0x010909f9},{0x09f90101,0x010909f9},{0x0901f901,0x010909f9},{0x090109f9,0x010909f9},{0x09090109,0x010909f9},{0xf9f9f901,0x01090901},{0xf9f901f9,0x01090901},{0xf901f9f9,0x01090901},
{0xf9010101,0x01090901},{0xf909f901,0x01090901},{0xf90901f9,0x01090901},{0xf9090109,0x01090901},{0xf9090901,0x01090901},{0x01f9f9f9,0x01090901},{0x01f9f901,0x01090901},{0x01f90101,0x01090901},
{0x01f90109,0x01090901},{0x01f909f9,0x01090901},{0x0101f901,0x01090901},{0x010101f9,0x01090901},{0x01010101,0x01090901},{0x01010109,0x01090901},{0x01010901,0x01090901},{0x0109f9f9,0x01090901},
{0x01090101,0x01090901},{0x01090909,0x01090901},{0x09f9f909,0x01090901},{0x09f901f9,0x01090901},{0x09f90909,0x01090901},{0x09010101,0x01090901},{0x0909f901,0x01090901},{0x090901f9,0x01090901},
{0x09090101,0x01090901},{0x09090901,0x01090901},{0xf901f901,0x01090909},{0xf9010109,0x01090909},{0xf90109f9,0x01090909},{0x01f9f901,0x01090909},{0x01f901f9,0x01090909},{0x01f90901,0x01090909},
{0x0101f9f9,0x01090909},{0x01010101,0x01090909},{0x010109f9,0x01090909},{0x01010909,0x01090909},{0x010901f9,0x01090909},{0x01090101,0x01090909},{0x01090901,0x01090909},{0x09f90109,0x01090909},
{0x090101f9,0x01090909},{0x090109f9,0x01090909},{0x09010909,0x01090909},{0x09090109,0x01090909},{0xf9f9f9f9,0x09f9f9f9},{0xf9f9f909,0x09f9f9f9},{0xf9f909f9,0x09f9f9f9},{0xf9f90909,0x09f9f9f9},
{0xf909f9f9,0x09f9f9f9},{0xf909f909,0x09f9f9f9},{0xf90909f9,0x09f9f9f9},{0xf9090909,0x09f9f9f9},{0x01f90101,0x09f9f9f9},{0x0101f9f9,0x09f9f9f9},{0x0101f901,0x09f9f9f9},{0x010101f9,0x09f9f9f9},
{0x01010109,0x09f9f9f9},{0x01010901,0x09f9f9f9},{0x01090101,0x09f9f9f9},{0x09f9f9f9,0x09f9f9f9},{0x09f9f909,0x09f9f9f9},{0x09f909f9,0x09f9f9f9},{0x09f90909,0x09f9f9f9},{0x09010101,0x09f9f9f9},
{0x0909f9f9,0x09f9f9f9},{0x0909f909,0x09f9f9f9},{0x090909f9,0x09f9f9f9},{0x09090909,0x09f9f9f9},{0xf9f90101,0x09f9f901},{0xf901f901,0x09f9f901},{0xf90101f9,0x09f9f901},{0xf9010109,0x09f9f901},
{0xf9010901,0x09f9f901},{0xf9090101,0x09f9f901},{0x01f9f901,0x09f9f901},{0x01f901f9,0x09f9f901},{0x01f90901,0x09f9f901},{0x0101f9f9,0x09f9f901},{0x0101f909,0x09f9f901},{0x01010101,0x09f9f901},
{0x01010109,0x09f9f901},{0x010109f9,0x09f9f901},{0x01010901,0x09f9f901},{0x010901f9,0x09f9f901},{0x01090109,0x09f9f901},{0x01090901,0x09f9f901},{0x09f90101,0x09f9f901},{0x09f90901,0x09f9f901},
{0x090101f9,0x09f9f901},{0x09010109,0x09f9f901},{0x09010901,0x09f9f901},{0x09090101,0x09f9f901},{0xf9f9f9f9,0x09f9f909},{0xf9f9f909,0x09f9f909},{0xf9f909f9,0x09f9f909},{0xf9f90909,0x09f9f909},
{0xf9010101,0x09f9f909},{0xf909f9f9,0x09f9f909},{0xf909f909,0x09f9f909},{0xf90909f9,0x09f9f909},{0xf9090909,0x09f9f909},{0x0101f901,0x09f9f909},{0x010101f9,0x09f9f909},{0x01010901,0x09f9f909},
{0x01090101,0x09f9f909},{0x09f9f9f9,0x09f9f909},{0x09f9f909,0x09f9f909},{0x09f909f9,0x09f9f909},{0x09f90909,0x09f9f909},{0x09010101,0x09f9f909},{0x0909f9f9,0x09f9f909},{0x0909f909,0x09f9f909},
{0x090909f9,0x09f9f909},{0x09090909,0x09f9f909},{0xf90101f9,0x09f901f9},{0xf9010901,0x09f901f9},{0x01f9f901,0x09f901f9},{0x01f901f9,0x09f901f9},{0x0101f901,0x09f901f9},{0x01010101,0x09f901f9},
{0x01010909,0x09f901f9},{0x0109f901,0x09f901f9},{0x010901f9,0x09f901f9},{0x01090901,0x09f901f9},{0x090101f9,0x09f901f9},{0x09010901,0x09f901f9},{0xf9f9f901,0x09f90101},{0xf9f90901,0x09f90101},
{0xf901f909,0x09f90101},{0xf9010101,0x09f90101},{0xf9010909,0x09f90101},{0xf9090109,0x09f90101},{0xf9090901,0x09f90101},{0x01f9f9f9,0x09f90101},{0x01f9f901,0x09f90101},{0x01f90101,0x09f90101},
{0x01f909f9,0x09f90101},{0x0101f901,0x09f90101},{0x010101f9,0x09f90101},{0x01010101,0x09f90101},{0x01010109,0x09f90101},{0x01010901,0x09f90101},{0x01010909,0x09f90101},{0x01090101,0x09f90101},
{0x01090109,0x09f90101},{0x010909f9,0x09f90101},{0x01090909,0x09f90101},{0x09f9f901,0x09f90101},{0x09f901f9,0x09f90101},{0x09f90109,0x09f90101},{0x09f90901,0x09f90101},{0x0901f9f9,0x09f90101},
{0x0901f909,0x09f90101},{0x09010101,0x09f90101},{0x090109f9,0x09f90101},{0x09090109,0x09f90101},{0xf901f901,0x09f90109},{0xf9010109,0x09f90109},{0xf9010901,0x09f90109},{0xf9090101,0x09f90109},
{0x01f9f901,0x09f90109},{0x01f901f9,0x09f90109},{0x01f90901,0x09f90109},{0x01f90909,0x09f90109},{0x0101f9f9,0x09f90109},{0x01010101,0x09f90109},{0x01010901,0x09f90109},{0x01010909,0x09f90109},
{0x0109f901,0x09f90109},{0x01090109,0x09f90109},{0x01090909,0x09f90109},{0x09f90101,0x09f90109},{0x0901f901,0x09f90109},{0x09010909,0x09f90109},{0x090901f9,0x09f90109},{0xf9f9f9f9,0x09f909f9},
{0xf9f9f909,0x09f909f9},{0xf9f909f9,0x09f909f9},{0xf9f90909,0x09f909f9},{0xf9010101,0x09f909f9},{0xf909f9f9,0x09f909f9},{0xf909f909,0x09f909f9},{0xf90909f9,0x09f909f9},{0xf9090909,0x09f909f9},
{0x01f9f901,0x09f909f9},{0x01f90101,0x09f909f9},{0x0101f901,0x09f909f9},{0x010101f9,0x09f909f9},{0x01010901,0x09f909f9},{0x01090101,0x09f909f9},{0x01090901,0x09f909f9},{0x09f9f9f9,0x09f909f9},
{0x09f9f909,0x09f909f9},{0x09f909f9,0x09f909f9},{0x09f90909,0x09f909f9},{0x09010101,0x09f909f9},{0x0909f9f9,0x09f909f9},{0x0909f909,0x09f909f9},{0x090909f9,0x09f909f9},{0x09090909,0x09f909f9},
{0xf9f90101,0x09f90901},{0xf9f90109,0x09f90901},{0xf901f901,0x09f90901},{0xf90101f9,0x09f90901},{0xf9010109,0x09f90901},{0xf9090101,0x09f90901},{0x01f9f901,0x09f90901},{0x01f901f9,0x09f90901},
{0x01f90109,0x09f90901},{0x01f90901,0x09f90901},{0x0101f9f9,0x09f90901},{0x0101f909,0x09f90901},{0x01010101,0x09f90901},{0x01010909,0x09f90901},{0x0109f901,0x09f90901},{0x010901f9,0x09f90901},
{0x09f90101,0x09f90901},{0x09010109,0x09f90901},{0x09010901,0x09f90901},{0x09090101,0x09f90901},{0xf9f9f9f9,0x09f90909},{0xf9f9f909,0x09f90909},{0xf9f909f9,0x09f90909},{0xf9f90909,0x09f90909},
{0xf9010101,0x09f90909},{0xf909f9f9,0x09f90909},{0xf909f909,0x09f90909},{0xf90909f9,0x09f90909},{0xf9090909,0x09f90909},{0x01f90101,0x09f90909},{0x0101f901,0x09f90909},{0x010101f9,0x09f90909},
{0x01010109,0x09f90909},{0x09f9f9f9,0x09f90909},{0x09f9f909,0x09f90909},{0x09f909f9,0x09f90909},{0x09f90909,0x09f90909},{0x09010101,0x09f90909},{0x0909f9f9,0x09f90909},{0x0909f909,0x09f90909},
{0x090909f9,0x09f90909},{0x09090909,0x09f90909},{0xf9f90101,0x0901f9f9},{0xf901f901,0x0901f9f9},{0xf9010109,0x0901f9f9},{0xf90109f9,0x0901f9f9},{0xf9010901,0x0901f9f9},{0xf9090101,0x0901f9f9},
{0x01f9f901,0x0901f9f9},{0x01f90109,0x0901f9f9},{0x01f90901,0x0901f9f9},{0x01010101,0x0901f9f9},{0x010109f9,0x0901f9f9},{0x01010909,0x0901f9f9},{0x01090901,0x0901f9f9},{0x01090909,0x0901f9f9},
{0x09f90101,0x0901f9f9},{0x0901f901,0x0901f9f9},{0x090101f9,0x0901f9f9},{0x09010109,0x0901f9f9},{0x09010901,0x0901f9f9},{0x09090101,0x0901f9f9},{0xf9f9f901,0x0901f901},{0xf9f901f9,0x0901f901},
{0xf9f90109,0x0901f901},{0xf9f90901,0x0901f901},{0xf901f9f9,0x0901f901},{0xf9010101,0x0901f901},{0xf90109f9,0x0901f901},{0xf9010909,0x0901f901},{0xf909f901,0x0901f901},{0xf90901f9,0x0901f901},
{0xf9090109,0x0901f901},{0xf9090901,0x0901f901},{0x01f9f9f9,0x0901f901},{0x01f90101,0x0901f901},{0x0101f9f9,0x0901f901},{0x0101f901,0x0901f901},{0x010101f9,0x0901f901},{0x01010101,0x0901f901},
{0x01010109,0x0901f901},{0x01010901,0x0901f901},{0x0109f909,0x0901f901},{0x01090101,0x0901f901},{0x09f901f9,0x0901f901},{0x09f90109,0x0901f901},{0x0901f909,0x0901f901},{0x09010101,0x0901f901},
{0x090109f9,0x0901f901},{0x0909f901,0x0901f901},{0x090901f9,0x0901f901},{0x09090109,0x0901f901},{0x09090901,0x0901f901},{0xf9f90101,0x0901f909},{0xf901f901,0x0901f909},{0xf90101f9,0x0901f909},
{0xf9010901,0x0901f909},{0xf9090101,0x0901f909},{0x01f901f9,0x0901f909},{0x01f90109,0x0901f909},{0x01f90901,0x0901f909},{0x0101f9f9,0x0901f909},{0x0101f909,0x0901f909},{0x01010101,0x0901f909},
{0x010109f9,0x0901f909},{0x01090109,0x0901f909},{0x01090901,0x0901f909},{0x09f90101,0x0901f909},{0x090101f9,0x0901f909},{0x09010109,0x0901f909},{0x09090901,0x0901f909},{0xf9f9f901,0x090101f9},
{0xf9f901f9,0x090101f9},{0xf9f90109,0x090101f9},{0xf901f9f9,0x090101f9},{0xf9010101,0x090101f9},{0xf90109f9,0x090101f9},{0xf9090109,0x090101f9},{0x01f9f9f9,0x090101f9},{0x01f90909,0x090101f9},
{0x0101f901,0x090101f9},{0x010101f9,0x090101f9},{0x01010101,0x090101f9},{0x01010109,0x090101f9},{0x010109f9,0x090101f9},{0x01010901,0x090101f9},{0x0109f9f9,0x090101f9},{0x0109f901,0x090101f9},
{0x0109f909,0x090101f9},{0x01090101,0x090101f9},{0x09f901f9,0x090101f9},{0x09f90109,0x090101f9},{0x0901f909,0x090101f9},{0x090101f9,0x090101f9},{0x09010101,0x090101f9},{0x090109f9,0x090101f9},
{0x0909f901,0x090101f9},{0x09090901,0x090101f9},{0xf9f9f9f9,0x09010101},{0xf9f90101,0x09010101},{0xf9f909f9,0x09010101},{0xf9f90909,0x09010101},{0xf901f9f9,0x09010101},{0xf901f901,0x09010101},
{0xf90101f9,0x09010101},{0xf9010101,0x09010101},{0xf9010109,0x09010101},{0xf9010901,0x09010101},{0xf909f901,0x09010101},{0xf9090101,0x09010101},{0xf9090901,0x09010101},{0xf9090909,0x09010101},
{0x01f9f901,0x09010101},{0x01f901f9,0x09010101},{0x01f90101,0x09010101},{0x01f90109,0x09010101},{0x01f90901,0x09010101},{0x0101f9f9,0x09010101},{0x0101f901,0x09010101},{0x0101f909,0x09010101},
{0x010101f9,0x09010101},{0x01010101,0x09010101},{0x01010109,0x09010101},{0x010109f9,0x09010101},{0x01010901,0x09010101},{0x01010909,0x09010101},{0x0109f901,0x09010101},{0x010901f9,0x09010101},
{0x01090101,0x09010101},{0x01090109,0x09010101},{0x01090901,0x09010101},{0x09f9f901,0x09010101},{0x09f90101,0x09010101},{0x09f909f9,0x09010101},{0x0901f901,0x09010101},{0x0901f909,0x09010101},
{0x090101f9,0x09010101},{0x09010101,0x09010101},{0x09010109,0x09010101},{0x09010901,0x09010101},{0x09010909,0x09010101},{0x0909f9f9,0x09010101},{0x0909f909,0x09010101},{0x09090101,0x09010101},
{0x090909f9,0x09010101},{0x09090909,0x09010101},{0xf9f9f901,0x09010109},{0xf9f901f9,0x09010109},{0xf901f9f9,0x09010109},{0xf9010101,0x09010109},{0xf9010901,0x09010109},{0xf909f9f9,0x09010109},
{0xf9090109,0x09010109},{0xf9090901,0x09010109},{0x01f90101,0x09010109},{0x01f909f9,0x09010109},{0x01f90901,0x09010109},{0x0101f901,0x09010109},{0x0101f909,0x09010109},{0x01010101,0x09010109},
{0x01010109,0x09010109},{0x01010901,0x09010109},{0x01090101,0x09010109},{0x010909f9,0x09010109},{0x09f9f909,0x09010109},{0x09f901f9,0x09010109},{0x09f90901,0x09010109},{0x09f90909,0x09010109},
{0x0901f909,0x09010109},{0x090101f9,0x09010109},{0x09010101,0x09010109},{0x090901f9,0x09010109},{0x09090109,0x09010109},{0x09090901,0x09010109},{0xf9f90101,0x090109f9},{0xf9010109,0x090109f9},
{0xf9010901,0x090109f9},{0xf9090101,0x090109f9},{0x01f9f901,0x090109f9},{0x01f90109,0x090109f9},{0x0101f9f9,0x090109f9},{0x0101f909,0x090109f9},{0x01010101,0x090109f9},{0x01010109,0x090109f9},
{0x01010909,0x090109f9},{0x010901f9,0x090109f9},{0x01090101,0x090109f9},{0x09f90101,0x090109f9},{0x0901f901,0x090109f9},{0x09010109,0x090109f9},{0x09010901,0x090109f9},{0x09090101,0x090109f9},
{0xf9f901f9,0x09010901},{0xf9f90109,0x09010901},{0xf9f90901,0x09010901},{0xf901f9f9,0x09010901},{0xf901f909,0x09010901},{0xf9010101,0x09010901},{0xf90109f9,0x09010901},{0xf9010909,0x09010901},
{0xf909f9f9,0x09010901},{0xf909f901,0x09010901},{0xf90901f9,0x09010901},{0xf9090109,0x09010901},{0x01f9f9f9,0x09010901},{0x01f9f909,0x09010901},{0x01f90101,0x09010901},{0x01f909f9,0x09010901},
{0x01f90909,0x09010901},{0x0101f901,0x09010901},{0x010101f9,0x09010901},{0x01010101,0x09010901},{0x01010109,0x09010901},{0x01010901,0x09010901},{0x0109f909,0x09010901},{0x01090101,0x09010901},
{0x01090109,0x09010901},{0x01090909,0x09010901},{0x09f9f901,0x09010901},{0x09f901f9,0x09010901},{0x0901f9f9,0x09010901},{0x0901f909,0x09010901},{0x09010101,0x09010901},{0x09010909,0x09010901},
{0x0909f901,0x09010901},{0x09090109,0x09010901},{0xf9f90101,0x09010909},{0xf9010101,0x09010909},{0xf9090101,0x09010909},{0x01f901f9,0x09010909},{0x01f90109,0x09010909},{0x01f90901,0x09010909},
{0x0101f9f9,0x09010909},{0x01010101,0x09010909},{0x010109f9,0x09010909},{0x0109f901,0x09010909},{0x09f90101,0x09010909},{0x0901f901,0x09010909},{0x090101f9,0x09010909},{0x09010101,0x09010909},
{0x09010109,0x09010909},{0xf9f9f9f9,0x0909f9f9},{0xf9f9f909,0x0909f9f9},{0xf9f909f9,0x0909f9f9},{0xf9f90909,0x0909f9f9},{0xf9010101,0x0909f9f9},{0xf909f9f9,0x0909f9f9},{0xf909f909,0x0909f9f9},
{0xf90909f9,0x0909f9f9},{0xf9090909,0x0909f9f9},{0x01f90101,0x0909f9f9},{0x0101f901,0x0909f9f9},{0x010101f9,0x0909f9f9},{0x01010109,0x0909f9f9},{0x01010901,0x0909f9f9},{0x09f9f9f9,0x0909f9f9},
{0x09f9f909,0x0909f9f9},{0x09f909f9,0x0909f9f9},{0x09f90909,0x0909f9f9},{0x09010101,0x0909f9f9},{0x0909f9f9,0x0909f9f9},{0x0909f909,0x0909f9f9},{0x090909f9,0x0909f9f9},{0x09090909,0x0909f9f9},
{0xf9f90101,0x0909f901},{0xf9f90901,0x0909f901},{0xf901f901,0x0909f901},{0xf90101f9,0x0909f901},{0xf9010109,0x0909f901},{0xf9010901,0x0909f901},{0xf9010909,0x0909f901},{0x01f90109,0x0909f901},
{0x01f90901,0x0909f901},{0x0101f901,0x0909f901},{0x01010101,0x0909f901},{0x010109f9,0x0909f901},{0x01010909,0x0909f901},{0x0109f901,0x0909f901},{0x010901f9,0x0909f901},{0x09f90101,0x0909f901},
{0x0901f9f9,0x0909f901},{0x0901f909,0x0909f901},{0x09010109,0x0909f901},{0x09010901,0x0909f901},{0xf9f9f909,0x0909f909},{0xf9f909f9,0x0909f909},{0xf9f90909,0x0909f909},{0xf901f9f9,0x0909f909},
{0xf9010901,0x0909f909},{0xf909f909,0x0909f909},{0xf90909f9,0x0909f909},{0xf9090909,0x0909f909},{0x01f90101,0x0909f909},{0x0101f901,0x0909f909},{0x01010109,0x0909f909},{0x01010901,0x0909f909},
{0x01090101,0x0909f909},{0x09f9f9f9,0x0909f909},{0x09f9f909,0x0909f909},{0x09f909f9,0x0909f909},{0x09f90909,0x0909f909},{0x09010101,0x0909f909},{0x0909f9f9,0x0909f909},{0x0909f909,0x0909f909},
{0x090909f9,0x0909f909},{0x09090909,0x0909f909},{0xf9010901,0x090901f9},{0xf9090101,0x090901f9},{0x01f9f901,0x090901f9},{0x01f901f9,0x090901f9},{0x0101f9f9,0x090901f9},{0x010101f9,0x090901f9},
{0x01010101,0x090901f9},{0x010109f9,0x090901f9},{0x01010909,0x090901f9},{0x0109f901,0x090901f9},{0x01090101,0x090901f9},{0x01090109,0x090901f9},{0x010909f9,0x090901f9},{0x01090901,0x090901f9},
{0x09f90101,0x090901f9},{0xf9f90109,0x09090101},{0xf9f90901,0x09090101},{0xf901f9f9,0x09090101},{0xf901f909,0x09090101},{0xf9010101,0x09090101},{0xf90109f9,0x09090101},{0xf9090109,0x09090101},
{0xf9090901,0x09090101},{0x01f9f909,0x09090101},{0x01f90101,0x09090101},{0x0101f901,0x09090101},{0x010101f9,0x09090101},{0x01010101,0x09090101},{0x01010109,0x09090101},{0x01010901,0x09090101},
{0x01090101,0x09090101},{0x01090909,0x09090101},{0x09f9f901,0x09090101},{0x09f901f9,0x09090101},{0x09f90101,0x09090101},{0x09f90109,0x09090101},{0x09f90901,0x09090101},{0x0901f909,0x09090101},
{0x09010101,0x09090101},{0x090109f9,0x09090101},{0xf9f90101,0x09090109},{0xf901f901,0x09090109},{0xf9010109,0x09090109},{0xf9010909,0x09090109},{0xf909f901,0x09090109},{0xf9090101,0x09090109},
{0x01f901f9,0x09090109},{0x01f90109,0x09090109},{0x01f90909,0x09090109},{0x0101f909,0x09090109},{0x01010101,0x09090109},{0x01010109,0x09090109},{0x010109f9,0x09090109},{0x0109f9f9,0x09090109},
{0x0109f909,0x09090109},{0x09f90109,0x09090109},{0x0901f9f9,0x09090109},{0x09010101,0x09090109},{0x09010109,0x09090109},{0x09010901,0x09090109},{0x0909f901,0x09090109},{0x090901f9,0x09090109},
{0x09090109,0x09090109},{0xf9f9f9f9,0x090909f9},{0xf9f9f909,0x090909f9},{0xf9f909f9,0x090909f9},{0xf9f90909,0x090909f9},{0xf909f9f9,0x090909f9},{0xf909f909,0x090909f9},{0xf90909f9,0x090909f9},
{0xf9090909,0x090909f9},{0x0101f901,0x090909f9},{0x010101f9,0x090909f9},{0x01010109,0x090909f9},{0x01010901,0x090909f9},{0x09f9f9f9,0x090909f9},{0x09f9f909,0x090909f9},{0x09f909f9,0x090909f9},
{0x09f90909,0x090909f9},{0x09010101,0x090909f9},{0x0909f9f9,0x090909f9},{0x0909f909,0x090909f9},{0x090909f9,0x090909f9},{0x09090909,0x090909f9},{0xf9f90101,0x09090901},{0xf90101f9,0x09090901},
{0xf9010901,0x09090901},{0xf909f901,0x09090901},{0xf9090101,0x09090901},{0x01f9f901,0x09090901},{0x0101f9f9,0x09090901},{0x01010101,0x09090901},{0x01010909,0x09090901},{0x0109f901,0x09090901},
{0x01090109,0x09090901},{0x01090901,0x09090901},{0x0901f9f9,0x09090901},{0x09010109,0x09090901},{0xf9f9f9f9,0x09090909},{0xf9f9f909,0x09090909},{0xf9f909f9,0x09090909},{0xf9f90909,0x09090909},
{0xf909f9f9,0x09090909},{0xf909f909,0x09090909},{0xf90909f9,0x09090909},{0xf9090909,0x09090909},{0x0101f901,0x09090909},{0x010101f9,0x09090909},{0x01010109,0x09090909},{0x09f9f9f9,0x09090909},
{0x09f9f909,0x09090909},{0x09f909f9,0x09090909},{0x09f90909,0x09090909},{0x09010101,0x09090909},{0x0909f9f9,0x09090909},{0x0909f909,0x09090909},{0x090909f9,0x09090909},{0x09090909,0x09090909},
{0xf7f7f7f7,0xf7f7f7f7},{0xf7f7f707,0xf7f7f7f7},{0xf7f7ffff,0xf7f7f7f7},{0xf7f707f7,0xf7f7f7f7},{0xf7f70707,0xf7f7f7f7},{0xf7fff7ff,0xf7f7f7f7},{0xf7ffffff,0xf7f7f7f7},{0xf707f7f7,0xf7f7f7f7},
{0xf707f707,0xf7f7f7f7},{0xf70707f7,0xf7f7f7f7},{0xf7070707,0xf7f7f7f7},{0xfff7ffff,0xf7f7f7f7},{0xfffff7ff,0xf7f7f7f7},{0xfffffff7,0xf7f7f7f7},{0xffffff07,0xf7f7f7f7},{0xff07ffff,0xf7f7f7f7},
{0x07f7f7f7,0xf7f7f7f7},{0x07f7f707,0xf7f7f7f7},{0x07f707f7,0xf7f7f7f7},{0x07f70707,0xf7f7f7f7},{0x07ffffff,0xf7f7f7f7},{0x0707f7f7,0xf7f7f7f7},{0x0707f707,0xf7f7f7f7},{0x070707f7,0xf7f7f7f7},
{0x07070707,0xf7f7f7f7},{0xf7f7fff7,0xf7f7f7ff},{0xf7f7ffff,0xf7f7f7ff},{0xf7fff7ff,0xf7f7f7ff},{0xf7fffff7,0xf7f7f7ff},{0xf7ffff07,0xf7f7f7ff},{0xf7ff07ff,0xf7f7f7ff},{0xf7ff0707,0xf7f7f7ff},
{0xf707ffff,0xf7f7f7ff},{0xfff7f7ff,0xf7f7f7ff},{0xfff7ff07,0xf7f7f7ff},{0xfff707ff,0xf7f7f7ff},{0xfffff707,0xf7f7f7ff},{0xffffffff,0xf7f7f7ff},{0xffff0707,0xf7f7f7ff},{0xff07f7ff,0xf7f7f7ff},
{0xff07fff7,0xf7f7f7ff},{0xff07ff07,0xf7f7f7ff},{0xff0707f7,0xf7f7f7ff},{0x07f7ffff,0xf7f7f7ff},{0x07fff7ff,0xf7f7f7ff},{0x07fffff7,0xf7f7f7ff},{0x07ffff07,0xf7f7f7ff},{0x0707ffff,0xf7f7f7ff},
{0xf7f7f7f7,0xf7f7f707},{0xf7f7f707,0xf7f7f707},{0xf7f707f7,0xf7f7f707},{0xf7f70707,0xf7f7f707},{0xf7ffffff,0xf7f7f707},{0xf707f7f7,0xf7f7f707},{0xf707f707,0xf7f7f707},{0xf70707f7,0xf7f7f707},
{0xf7070707,0xf7f7f707},{0xfff7ffff,0xf7f7f707},{0xfffff7ff,0xf7f7f707},{0xffff07ff,0xf7f7f707},{0xff07fff7,0xf7f7f707},{0xff0707ff,0xf7f7f707},{0x07f7f7f7,0xf7f7f707},{0x07f7f707,0xf7f7f707},
{0x07f707f7,0xf7f7f707},{0x07f70707,0xf7f7f707},{0x07fff7ff,0xf7f7f707},{0x07ffffff,0xf7f7f707},{0x07ff07ff,0xf7f7f707},{0x0707f7f7,0xf7f7f707},{0x0707f707,0xf7f7f707},{0x070707f7,0xf7f7f707},
{0x07070707,0xf7f7f707},{0xf7fff7ff,0xf7f7fff7},{0xf7fffff7,0xf7f7fff7},{0xf7ffff07,0xf7f7fff7},{0xf707ffff,0xf7f7fff7},{0xfff7f7ff,0xf7f7fff7},{0xfff707ff,0xf7f7fff7},{0xffffffff,0xf7f7fff7},
{0xffff0707,0xf7f7fff7},{0xff07fff7,0xf7f7fff7},{0xff07ffff,0xf7f7fff7},{0x07fff7ff,0xf7f7fff7},{0x07ff07ff,0xf7f7fff7},{0x0707ffff,0xf7f7fff7},{0xf7f7f7ff,0xf7f7ffff},{0xf7f7fff7,0xf7f7ffff},
{0xf7f7ffff,0xf7f7ffff},{0xf7f7ff07,0xf7f7ffff},{0xf7ffffff,0xf7f7ffff},{0xf7ff07f7,0xf7f7ffff},{0xf7ff0707,0xf7f7ffff},{0xf70707ff,0xf7f7ffff},{0xfff7f7f7,0xf7f7ffff},{0xfff7ffff,0xf7f7ffff},
{0xfff70707,0xf7f7ffff},{0xfffff7f7,0xf7f7ffff},{0xfffff7ff,0xf7f7ffff},{0xfffffff7,0xf7f7ffff},{0xffffffff,0xf7f7ffff},{0xffffff07,0xf7f7ffff},{0xffff07ff,0xf7f7ffff},{0xff07f7f7,0xf7f7ffff},
{0xff07f707,0xf7f7ffff},{0xff07ffff,0xf7f7ffff},{0xff0707f7,0xf7f7ffff},{0xff070707,0xf7f7ffff},{0x07f7f7ff,0xf7f7ffff},{0x07fff7ff,0xf7f7ffff},{0x07ffffff,0xf7f7ffff},{0x07ff07f7,0xf7f7ffff},
{0x07ff0707,0xf7f7ffff},{0x0707f7ff,0xf7f7ffff},{0x0707fff7,0xf7f7ffff},{0x0707ffff,0xf7f7ffff},{0x0707ff07,0xf7f7ffff},{0x070707ff,0xf7f7ffff},{0xf7fffff7,0xf7f7ff07},{0xf7ff07ff,0xf7f7ff07},
{0xfff7f7ff,0xf7f7ff07},{0xfff7fff7,0xf7f7ff07},{0xfffff7f7,0xf7f7ff07},{0xfffff707,0xf7f7ff07},{0xffffffff,0xf7f7ff07},{0xffff07f7,0xf7f7ff07},{0xff07f7f7,0xf7f7ff07},{0xff07f7ff,0xf7f7ff07},
{0xff07ff07,0xf7f7ff07},{0xff0707ff,0xf7f7ff07},{0x07f7ffff,0xf7f7ff07},{0x07fff7ff,0xf7f7ff07},{0x07fffff7,0xf7f7ff07},{0x07ff07ff,0xf7f7ff07},{0xf7f7f7f7,0xf7f707f7},{0xf7f7f707,0xf7f707f7},
{0xf7f707f7,0xf7f707f7},{0xf7f70707,0xf7f707f7},{0xf7ffffff,0xf7f707f7},{0xf707f7f7,0xf7f707f7},{0xf707f707,0xf7f707f7},{0xf70707f7,0xf7f707f7},{0xf7070707,0xf7f707f7},{0xfff7ffff,0xf7f707f7},
{0xfffff7ff,0xf7f707f7},{0xffffff07,0xf7f707f7},{0xff07ffff,0xf7f707f7},{0x07f7f7f7,0xf7f707f7},{0x07f7f707,0xf7f707f7},{0x07f707f7,0xf7f707f7},{0x07f70707,0xf7f707f7},{0x07ffffff,0xf7f707f7},
{0x0707f7f7,0xf7f707f7},{0x0707f707,0xf7f707f7},{0x070707f7,0xf7f707f7},{0x07070707,0xf7f707f7},{0xf7f7ffff,0xf7f707ff},{0xf7fff7ff,0xf7f707ff},{0xf7fffff7,0xf7f707ff},{0xf7ff07ff,0xf7f707ff},
{0xf707fff7,0xf7f707ff},{0xf707ffff,0xf7f707ff},{0xfff7f7ff,0xf7f707ff},{0xfffff7f7,0xf7f707ff},{0xfffff7ff,0xf7f707ff},{0xffffffff,0xf7f707ff},{0xff07f7ff,0xf7f707ff},{0xff07fff7,0xf7f707ff},
{0xff0707ff,0xf7f707ff},{0x07fff7ff,0xf7f707ff},{0x07fffff7,0xf7f707ff},{0x07ffff07,0xf7f707ff},{0x07ff07ff,0xf7f707ff},{0x0707ffff,0xf7f707ff},{0xf7f7f7f7,0xf7f70707},{0xf7f7f707,0xf7f70707},
{0xf7f707f7,0xf7f70707},{0xf7f70707,0xf7f70707},{0xf7ffffff,0xf7f70707},{0xf707f7f7,0xf7f70707},{0xf707f707,0xf7f70707},{0xf70707f7,0xf7f70707},{0xf7070707,0xf7f70707},{0xfff7ffff,0xf7f70707},
{0xfffff7ff,0xf7f70707},{0xffff07ff,0xf7f70707},{0xff07f7ff,0xf7f70707},{0xff07ffff,0xf7f70707},{0x07f7f7f7,0xf7f70707},{0x07f7f707,0xf7f70707},{0x07f7ffff,0xf7f70707},{0x07f707f7,0xf7f70707},
{0x07f70707,0xf7f70707},{0x07ffffff,0xf7f70707},{0x0707f7f7,0xf7f70707},{0x0707f707,0xf7f70707},{0x070707f7,0xf7f70707},{0x07070707,0xf7f70707},{0xf7fff7f7,0xf7fff7f7},{0xf7fff7ff,0xf7fff7f7},
{0xf7fffff7,0xf7fff7f7},{0xf7ff07ff,0xf7fff7f7},{0xf707fff7,0xf7fff7f7},{0xf707ffff,0xf7fff7f7},{0xfff7f7ff,0xf7fff7f7},{0xfff7fff7,0xf7fff7f7},{0xfffff7f7,0xf7fff7f7},{0xffffffff,0xf7fff7f7},
{0xffff07f7,0xf7fff7f7},{0xff07f7ff,0xf7fff7f7},{0xff07fff7,0xf7fff7f7},{0xff07ffff,0xf7fff7f7},{0xff0707ff,0xf7fff7f7},{0x07fff7ff,0xf7fff7f7},{0x07fffff7,0xf7fff7f7},{0x07ffff07,0xf7fff7f7},
{0x0707f7ff,0xf7fff7f7},{0x0707ffff,0xf7fff7f7},{0xf7f7f7ff,0xf7fff7ff},{0xf7f7fff7,0xf7fff7ff},{0xf7f7ff07,0xf7fff7ff},{0xf7f707ff,0xf7fff7ff},{0xf7fff7f7,0xf7fff7ff},{0xf7fff707,0xf7fff7ff},
{0xf7ffffff,0xf7fff7ff},{0xf7ff07f7,0xf7fff7ff},{0xf707f7ff,0xf7fff7ff},{0xf707fff7,0xf7fff7ff},{0xf70707ff,0xf7fff7ff},{0xfff7ffff,0xf7fff7ff},{0xfff70707,0xf7fff7ff},{0xfffff7f7,0xf7fff7ff},
{0xfffff7ff,0xf7fff7ff},{0xfffff707,0xf7fff7ff},{0xfffffff7,0xf7fff7ff},{0xffffffff,0xf7fff7ff},{0xffffff07,0xf7fff7ff},{0xffff07ff,0xf7fff7ff},{0xff07f7f7,0xf7fff7ff},{0xff07ffff,0xf7fff7ff},
{0x07f7fff7,0xf7fff7ff},{0x07fff707,0xf7fff7ff},{0x07ffffff,0xf7fff7ff},{0x0707f7ff,0xf7fff7ff},{0x0707fff7,0xf7fff7ff},{0xf7fff7ff,0xf7fff707},{0xf7fffff7,0xf7fff707},{0xf7ffff07,0xf7fff707},
{0xf707ffff,0xf7fff707},{0xfff7f7f7,0xf7fff707},{0xfff7ff07,0xf7fff707},{0xfff707ff,0xf7fff707},{0xfffff707,0xf7fff707},{0xffffffff,0xf7fff707},{0xffff07f7,0xf7fff707},{0xffff0707,0xf7fff707},
{0xff07fff7,0xf7fff707},{0xff07ff07,0xf7fff707},{0x07f7ffff,0xf7fff707},{0x07fff7ff,0xf7fff707},{0x07fffff7,0xf7fff707},{0x07ffff07,0xf7fff707},{0x0707ffff,0xf7fff707},{0xf7f7f7ff,0xf7fffff7},
{0xf7f7ff07,0xf7fffff7},{0xf7f707ff,0xf7fffff7},{0xf7fffff7,0xf7fffff7},{0xf7ffffff,0xf7fffff7},{0xf7ff07f7,0xf7fffff7},{0xf7ff07ff,0xf7fffff7},{0xf707f7ff,0xf7fffff7},{0xf707ff07,0xf7fffff7},
{0xfff7f7ff,0xf7fffff7},{0xfff7ffff,0xf7fffff7},{0xfff7ff07,0xf7fffff7},{0xfff707f7,0xf7fffff7},{0xfff70707,0xf7fffff7},{0xfffff7ff,0xf7fffff7},{0xfffffff7,0xf7fffff7},{0xffffffff,0xf7fffff7},
{0xffffff07,0xf7fffff7},{0xffff07ff,0xf7fffff7},{0xff07f707,0xf7fffff7},{0xff07ffff,0xf7fffff7},{0xff0707f7,0xf7fffff7},{0x07f7fff7,0xf7fffff7},{0x07f707ff,0xf7fffff7},{0x07fff7f7,0xf7fffff7},
{0x07fffff7,0xf7fffff7},{0x07ffffff,0xf7fffff7},{0x07ff07f7,0xf7fffff7},{0x07ff07ff,0xf7fffff7},{0x07ff0707,0xf7fffff7},{0x0707f7ff,0xf7fffff7},{0x0707fff7,0xf7fffff7},{0x0707ffff,0xf7fffff7},
{0x070707ff,0xf7fffff7},{0xf7f7f707,0xf7ffffff},{0xf7f7ffff,0xf7ffffff},{0xf7f70707,0xf7ffffff},{0xf7fff7ff,0xf7ffffff},{0xf7fffff7,0xf7ffffff},{0xf7ffffff,0xf7ffffff},{0xf7ffff07,0xf7ffffff},
{0xf7ff07ff,0xf7ffffff},{0xf707f7f7,0xf7ffffff},{0xf707f707,0xf7ffffff},{0xf707ffff,0xf7ffffff},{0xf70707f7,0xf7ffffff},{0xf7070707,0xf7ffffff},{0xfff7f7ff,0xf7ffffff},{0xfff7fff7,0xf7ffffff},
{0xfff7ffff,0xf7ffffff},{0xfff7ff07,0xf7ffffff},{0xfffff7ff,0xf7ffffff},{0xfffff707,0xf7ffffff},{0xfffffff7,0xf7ffffff},{0xffffffff,0xf7ffffff},{0xffffff07,0xf7ffffff},{0xffff07ff,0xf7ffffff},
{0xffff0707,0xf7ffffff},{0xff07f7ff,0xf7ffffff},{0xff07fff7,0xf7ffffff},{0xff07ffff,0xf7ffffff},{0xff07ff07,0xf7ffffff},{0xff0707ff,0xf7ffffff},{0x07f7f7f7,0xf7ffffff},{0x07f7f707,0xf7ffffff},
{0x07f7fff7,0xf7ffffff},{0x07f7ffff,0xf7ffffff},{0x07f707f7,0xf7ffffff},{0x07f70707,0xf7ffffff},{0x07fff7f7,0xf7ffffff},{0x07fff7ff,0xf7ffffff},{0x07fffff7,0xf7ffffff},{0x07ffffff,0xf7ffffff},
{0x07ffff07,0xf7ffffff},{0x07ff07ff,0xf7ffffff},{0x07ff0707,0xf7ffffff},{0x0707f7f7,0xf7ffffff},{0x0707f707,0xf7ffffff},{0x0707ffff,0xf7ffffff},{0xf7f7f7ff,0xf7ffff07},{0xf7f7fff7,0xf7ffff07},
{0xf7f7ffff,0xf7ffff07},{0xf7f7ff07,0xf7ffff07},{0xf7ffffff,0xf7ffff07},{0xf7ffff07,0xf7ffff07},{0xf7ff07f7,0xf7ffff07},{0xf7ff0707,0xf7ffff07},{0xf707f7ff,0xf7ffff07},{0xf707ff07,0xf7ffff07},
{0xfff7f7f7,0xf7ffff07},{0xfff7f707,0xf7ffff07},{0xfff7fff7,0xf7ffff07},{0xfff7ffff,0xf7ffff07},{0xfff707f7,0xf7ffff07},{0xfff70707,0xf7ffff07},{0xfffff7ff,0xf7ffff07},{0xffffffff,0xf7ffff07},
{0xffffff07,0xf7ffff07},{0xffff07f7,0xf7ffff07},{0xffff07ff,0xf7ffff07},{0xff07f7ff,0xf7ffff07},{0xff07fff7,0xf7ffff07},{0xff07ffff,0xf7ffff07},{0xff0707f7,0xf7ffff07},{0xff0707ff,0xf7ffff07},
{0xff070707,0xf7ffff07},{0x07f7ff07,0xf7ffff07},{0x07f70707,0xf7ffff07},{0x07fff707,0xf7ffff07},{0x07ffffff,0xf7ffff07},{0x0707fff7,0xf7ffff07},{0x070707ff,0xf7ffff07},{0xf7fff7ff,0xf7ff07f7},
{0xf7ffff07,0xf7ff07f7},{0xf707ffff,0xf7ff07f7},{0xfff7f7ff,0xf7ff07f7},{0xfff7fff7,0xf7ff07f7},{0xfff7ff07,0xf7ff07f7},{0xfff707ff,0xf7ff07f7},{0xfffff7f7,0xf7ff07f7},{0xffffffff,0xf7ff07f7},
{0xffff07f7,0xf7ff07f7},{0xffff0707,0xf7ff07f7},{0xff07f7f7,0xf7ff07f7},{0xff07f7ff,0xf7ff07f7},{0xff07fff7,0xf7ff07f7},{0xff07ff07,0xf7ff07f7},{0xff0707ff,0xf7ff07f7},{0x07f7ffff,0xf7ff07f7},
{0x07fff7ff,0xf7ff07f7},{0x07fffff7,0xf7ff07f7},{0x0707ffff,0xf7ff07f7},{0xf7fff7f7,0xf7ff07ff},{0xf7fff707,0xf7ff07ff},{0xf7ffffff,0xf7ff07ff},{0xf7ff0707,0xf7ff07ff},{0xf707f7ff,0xf7ff07ff},
{0xf707ffff,0xf7ff07ff},{0xfff7f707,0xf7ff07ff},{0xfff7fff7,0xf7ff07ff},{0xfff7ffff,0xf7ff07ff},{0xfff707f7,0xf7ff07ff},{0xfffff7ff,0xf7ff07ff},{0xfffffff7,0xf7ff07ff},{0xffffffff,0xf7ff07ff},
{0xffffff07,0xf7ff07ff},{0xffff07ff,0xf7ff07ff},{0xffff0707,0xf7ff07ff},{0xff07f7f7,0xf7ff07ff},{0xff07ffff,0xf7ff07ff},{0xff070707,0xf7ff07ff},{0x07f707ff,0xf7ff07ff},{0x07fff7ff,0xf7ff07ff},
{0x07fff707,0xf7ff07ff},{0x07ffffff,0xf7ff07ff},{0x07ff07f7,0xf7ff07ff},{0x0707f7ff,0xf7ff07ff},{0x0707ff07,0xf7ff07ff},{0x070707ff,0xf7ff07ff},{0xf7f707ff,0xf7ff0707},{0xf7ffff07,0xf7ff0707},
{0xf707fff7,0xf7ff0707},{0xf707ff07,0xf7ff0707},{0xfff7fff7,0xf7ff0707},{0xfff7ff07,0xf7ff0707},{0xfff707ff,0xf7ff0707},{0xfffff7f7,0xf7ff0707},{0xfffff707,0xf7ff0707},{0xffffffff,0xf7ff0707},
{0xffff07f7,0xf7ff0707},{0xff07f7ff,0xf7ff0707},{0xff07ff07,0xf7ff0707},{0xff0707ff,0xf7ff0707},{0x07f7ffff,0xf7ff0707},{0x07fff7ff,0xf7ff0707},{0x07ffff07,0xf7ff0707},{0x07ff0707,0xf7ff0707},
{0xf7f7f7f7,0xf707f7f7},{0xf7f7f707,0xf707f7f7},{0xf7f707f7,0xf707f7f7},{0xf7f70707,0xf707f7f7},{0xf7ffffff,0xf707f7f7},{0xf707f7f7,0xf707f7f7},{0xf707f707,0xf707f7f7},{0xf707ffff,0xf707f7f7},
{0xf70707f7,0xf707f7f7},{0xf7070707,0xf707f7f7},{0xfff7ffff,0xf707f7f7},{0xfffff7ff,0xf707f7f7},{0xffff07ff,0xf707f7f7},{0xff07f7ff,0xf707f7f7},{0xff07ffff,0xf707f7f7},{0x07f7f7f7,0xf707f7f7},
{0x07f7f707,0xf707f7f7},{0x07f707f7,0xf707f7f7},{0x07f70707,0xf707f7f7},{0x07ffffff,0xf707f7f7},{0x0707f7f7,0xf707f7f7},{0x0707f707,0xf707f7f7},{0x0707ffff,0xf707f7f7},{0x070707f7,0xf707f7f7},
{0x07070707,0xf707f7f7},{0xf7f7ffff,0xf707f7ff},{0xf7fff7ff,0xf707f7ff},{0xf7fffff7,0xf707f7ff},{0xf7ff07ff,0xf707f7ff},{0xf707ffff,0xf707f7ff},{0xfff7f707,0xf707f7ff},{0xfff7fff7,0xf707f7ff},
{0xfff707ff,0xf707f7ff},{0xffffffff,0xf707f7ff},{0xffff07f7,0xf707f7ff},{0xffff0707,0xf707f7ff},{0xff07f7ff,0xf707f7ff},{0xff07fff7,0xf707f7ff},{0xff07ffff,0xf707f7ff},{0xff07ff07,0xf707f7ff},
{0x07f7ffff,0xf707f7ff},{0x07fff7f7,0xf707f7ff},{0x07ffff07,0xf707f7ff},{0x07ff07ff,0xf707f7ff},{0x0707ffff,0xf707f7ff},{0xf7f7f7ff,0xf707f707},{0xf7f707f7,0xf707f707},{0xf7f70707,0xf707f707},
{0xf7fff7ff,0xf707f707},{0xf7ffffff,0xf707f707},{0xf707f7f7,0xf707f707},{0xf707f707,0xf707f707},{0xf70707f7,0xf707f707},{0xf7070707,0xf707f707},{0xfff7ffff,0xf707f707},{0xfffff7ff,0xf707f707},
{0xffffff07,0xf707f707},{0xffff07ff,0xf707f707},{0xff07ffff,0xf707f707},{0x07f7f7ff,0xf707f707},{0x07f707f7,0xf707f707},{0x07f70707,0xf707f707},{0x07fff7ff,0xf707f707},{0x07ffffff,0xf707f707},
{0x0707f7f7,0xf707f707},{0x0707f707,0xf707f707},{0x070707f7,0xf707f707},{0x07070707,0xf707f707},{0xf7f7ffff,0xf707fff7},{0xf7fffff7,0xf707fff7},{0xf7ffff07,0xf707fff7},{0xf7ff07ff,0xf707fff7},
{0xf707ffff,0xf707fff7},{0xfff7fff7,0xf707fff7},{0xfff7ffff,0xf707fff7},{0xfff7ff07,0xf707fff7},{0xfff707ff,0xf707fff7},{0xfffff707,0xf707fff7},{0xffffffff,0xf707fff7},{0xffff07f7,0xf707fff7},
{0xffff0707,0xf707fff7},{0xff07ff07,0xf707fff7},{0x07f7ffff,0xf707fff7},{0x07fff7ff,0xf707fff7},{0x07fffff7,0xf707fff7},{0x07ff07ff,0xf707fff7},{0x0707f7ff,0xf707fff7},{0x0707ffff,0xf707fff7},
{0xf7f707ff,0xf707ffff},{0xf7ffffff,0xf707ffff},{0xf707f7ff,0xf707ffff},{0xf70707ff,0xf707ffff},{0xfff7f7f7,0xf707ffff},{0xfff7ffff,0xf707ffff},{0xfff707f7,0xf707ffff},{0xfffff7ff,0xf707ffff},
{0xfffffff7,0xf707ffff},{0xffffffff,0xf707ffff},{0xffff07ff,0xf707ffff},{0xff07f707,0xf707ffff},{0xff07ffff,0xf707ffff},{0xff0707f7,0xf707ffff},{0x07f707ff,0xf707ffff},{0x07fff7f7,0xf707ffff},
{0x07fffff7,0xf707ffff},{0x07ffffff,0xf707ffff},{0x07ff07f7,0xf707ffff},{0x07ff0707,0xf707ffff},{0x0707f7ff,0xf707ffff},{0x0707fff7,0xf707ffff},{0x0707ff07,0xf707ffff},{0x070707ff,0xf707ffff},
{0xf7f7ffff,0xf707ff07},{0xf7fff7f7,0xf707ff07},{0xf7fff707,0xf707ff07},{0xf7ff07ff,0xf707ff07},{0xf707ffff,0xf707ff07},{0xfff7f7ff,0xf707ff07},{0xfff707ff,0xf707ff07},{0xffffffff,0xf707ff07},
{0xff07f7f7,0xf707ff07},{0xff07f7ff,0xf707ff07},{0xff0707ff,0xf707ff07},{0x07f7fff7,0xf707ff07},{0x07f7ff07,0xf707ff07},{0x07fff7f7,0xf707ff07},{0x07ff0707,0xf707ff07},{0xf7f7f7f7,0xf70707f7},
{0xf7f7f707,0xf70707f7},{0xf7f707f7,0xf70707f7},{0xf7f70707,0xf70707f7},{0xf7ffffff,0xf70707f7},{0xf707f7f7,0xf70707f7},{0xf707f707,0xf70707f7},{0xf70707f7,0xf70707f7},{0xf7070707,0xf70707f7},
{0xfff7ffff,0xf70707f7},{0xfffff7ff,0xf70707f7},{0xfffffff7,0xf70707f7},{0xff07ffff,0xf70707f7},{0x07f7f7f7,0xf70707f7},{0x07f7f707,0xf70707f7},{0x07f707f7,0xf70707f7},{0x07f70707,0xf70707f7},
{0x0707f7f7,0xf70707f7},{0x0707f707,0xf70707f7},{0x070707f7,0xf70707f7},{0x07070707,0xf70707f7},{0xf7f707ff,0xf70707ff},{0xf7fff7ff,0xf70707ff},{0xf7fffff7,0xf70707ff},{0xf7ff07ff,0xf70707ff},
{0xf707ffff,0xf70707ff},{0xfff7ff07,0xf70707ff},{0xfff707ff,0xf70707ff},{0xfffff707,0xf70707ff},{0xffffffff,0xf70707ff},{0xff07f7ff,0xf70707ff},{0xff07fff7,0xf70707ff},{0xff07ff07,0xf70707ff},
{0xff0707ff,0xf70707ff},{0x07f7ffff,0xf70707ff},{0x07fff7f7,0xf70707ff},{0x07ffff07,0xf70707ff},{0x07ff07ff,0xf70707ff},{0x0707fff7,0xf70707ff},{0x0707ffff,0xf70707ff},{0xf7f7f7f7,0xf7070707},
{0xf7f7f707,0xf7070707},{0xf7f707f7,0xf7070707},{0xf7f70707,0xf7070707},{0xf707f7f7,0xf7070707},{0xf707f707,0xf7070707},{0xf70707f7,0xf7070707},{0xf7070707,0xf7070707},{0xfff7ffff,0xf7070707},
{0xfffff7ff,0xf7070707},{0xffffff07,0xf7070707},{0xffff07ff,0xf7070707},{0xff07ffff,0xf7070707},{0x07f7f7f7,0xf7070707},{0x07f7f707,0xf7070707},{0x07f707f7,0xf7070707},{0x07f70707,0xf7070707},
{0x07ffffff,0xf7070707},{0x0707f7f7,0xf7070707},{0x0707f707,0xf7070707},{0x070707f7,0xf7070707},{0x07070707,0xf7070707},{0xf7f7ffff,0xfff7f7f7},{0xf7fff7ff,0xfff7f7f7},{0xf7ffff07,0xfff7f7f7},
{0xf707ffff,0xfff7f7f7},{0xfff707ff,0xfff7f7f7},{0xfffff707,0xfff7f7f7},{0xffffffff,0xfff7f7f7},{0xffff07f7,0xfff7f7f7},{0xffff0707,0xfff7f7f7},{0xff07f7ff,0xfff7f7f7},{0xff07fff7,0xfff7f7f7},
{0xff07ff07,0xfff7f7f7},{0x07fffff7,0xfff7f7f7},{0x07ff07ff,0xfff7f7f7},{0x0707f7ff,0xfff7f7f7},{0x0707ff07,0xfff7f7f7},{0xf7f7f7f7,0xfff7f7ff},{0xf7f7f7ff,0xfff7f7ff},{0xf7f7fff7,0xfff7f7ff},
{0xf7f7ff07,0xfff7f7ff},{0xf7f707ff,0xfff7f7ff},{0xf7fff707,0xfff7f7ff},{0xf7ffffff,0xfff7f7ff},{0xf7ffff07,0xfff7f7ff},{0xf7ff07f7,0xfff7f7ff},{0xf7ff0707,0xfff7f7ff},{0xf707f7ff,0xfff7f7ff},
{0xf707ff07,0xfff7f7ff},{0xf70707ff,0xfff7f7ff},{0xfff7ffff,0xfff7f7ff},{0xfff707f7,0xfff7f7ff},{0xfff70707,0xfff7f7ff},{0xfffff7ff,0xfff7f7ff},{0xfffffff7,0xfff7f7ff},{0xffffffff,0xfff7f7ff},
{0xffffff07,0xfff7f7ff},{0xffff07ff,0xfff7f7ff},{0xffff0707,0xfff7f7ff},{0xff07ffff,0xfff7f7ff},{0xff0707f7,0xfff7f7ff},{0xff070707,0xfff7f7ff},{0x07f7f7ff,0xfff7f7ff},{0x07f7fff7,0xfff7f7ff},
{0x07f7ff07,0xfff7f7ff},{0x07fff7f7,0xfff7f7ff},{0x07fff707,0xfff7f7ff},{0x07ffffff,0xfff7f7ff},{0x0707f7f7,0xfff7f7ff},{0x0707f7ff,0xfff7f7ff},{0x0707f707,0xfff7f7ff},{0xf7f7ffff,0xfff7f707},
{0xf7fff7ff,0xfff7f707},{0xf7fffff7,0xfff7f707},{0xf7ffff07,0xfff7f707},{0xf707ffff,0xfff7f707},{0xfff7f7ff,0xfff7f707},{0xfffff707,0xfff7f707},{0xffffffff,0xfff7f707},{0xffff0707,0xfff7f707},
{0xff07fff7,0xfff7f707},{0xff0707ff,0xfff7f707},{0x07f707ff,0xfff7f707},{0x07fffff7,0xfff7f707},{0x0707ffff,0xfff7f707},{0xf7f7f7ff,0xfff7fff7},{0xf7ffffff,0xfff7fff7},{0xf7ff07ff,0xfff7fff7},
{0xf70707ff,0xfff7fff7},{0xfff7ffff,0xfff7fff7},{0xfff707f7,0xfff7fff7},{0xfff70707,0xfff7fff7},{0xfffff7ff,0xfff7fff7},{0xfffffff7,0xfff7fff7},{0xffffffff,0xfff7fff7},{0xffffff07,0xfff7fff7},
{0xff07f7ff,0xfff7fff7},{0xff07f707,0xfff7fff7},{0xff07ffff,0xfff7fff7},{0xff0707f7,0xfff7fff7},{0xff070707,0xfff7fff7},{0x07f7f7ff,0xfff7fff7},{0x07f7ff07,0xfff7fff7},{0x07f707ff,0xfff7fff7},
{0x07fff7f7,0xfff7fff7},{0x07fff707,0xfff7fff7},{0x07ffffff,0xfff7fff7},{0x0707f7f7,0xfff7fff7},{0x0707f7ff,0xfff7fff7},{0x070707ff,0xfff7fff7},{0xf7f7f7ff,0xfff7ffff},{0xf7f7f707,0xfff7ffff},
{0xf7f7ffff,0xfff7ffff},{0xf7f70707,0xfff7ffff},{0xf7fff7ff,0xfff7ffff},{0xf7fffff7,0xfff7ffff},{0xf7ffffff,0xfff7ffff},{0xf7ffff07,0xfff7ffff},{0xf7ff07ff,0xfff7ffff},{0xf707f7f7,0xfff7ffff},
{0xf707ffff,0xfff7ffff},{0xf7070707,0xfff7ffff},{0xfff7f7ff,0xfff7ffff},{0xfff7fff7,0xfff7ffff},{0xfff7ffff,0xfff7ffff},{0xfff7ff07,0xfff7ffff},{0xfff707ff,0xfff7ffff},{0xfffff7f7,0xfff7ffff},
{0xfffff7ff,0xfff7ffff},{0xfffffff7,0xfff7ffff},{0xffffffff,0xfff7ffff},{0xffffff07,0xfff7ffff},{0xffff07f7,0xfff7ffff},{0xffff07ff,0xfff7ffff},{0xff07f7ff,0xfff7ffff},{0xff07fff7,0xfff7ffff},
{0xff07ffff,0xfff7ffff},{0xff07ff07,0xfff7ffff},{0xff0707ff,0xfff7ffff},{0x07f7f707,0xfff7ffff},{0x07f7fff7,0xfff7ffff},{0x07f7ffff,0xfff7ffff},{0x07f707f7,0xfff7ffff},{0x07fff7ff,0xfff7ffff},
{0x07fffff7,0xfff7ffff},{0x07ffffff,0xfff7ffff},{0x07ffff07,0xfff7ffff},{0x07ff07ff,0xfff7ffff},{0x07ff0707,0xfff7ffff},{0x0707ffff,0xfff7ffff},{0x070707f7,0xfff7ffff},{0x07070707,0xfff7ffff},
{0xf7f7f7ff,0xfff7ff07},{0xf7f7ffff,0xfff7ff07},{0xf7f707ff,0xfff7ff07},{0xf7fffff7,0xfff7ff07},{0xf7ffffff,0xfff7ff07},{0xf7ff07f7,0xfff7ff07},{0xf7ff0707,0xfff7ff07},{0xf707f7ff,0xfff7ff07},
{0xf707fff7,0xfff7ff07},{0xf70707ff,0xfff7ff07},{0xfff7f7f7,0xfff7ff07},{0xfff7f707,0xfff7ff07},{0xfff7ffff,0xfff7ff07},{0xfff707f7,0xfff7ff07},{0xfffff7f7,0xfff7ff07},{0xfffff7ff,0xfff7ff07},
{0xfffff707,0xfff7ff07},{0xffffffff,0xfff7ff07},{0xffffff07,0xfff7ff07},{0xffff07ff,0xfff7ff07},{0xff07f707,0xfff7ff07},{0xff07ffff,0xfff7ff07},{0xff0707f7,0xfff7ff07},{0x07f7f7ff,0xfff7ff07},
{0x07f7ffff,0xfff7ff07},{0x07f70707,0xfff7ff07},{0x07fffff7,0xfff7ff07},{0x07ffffff,0xfff7ff07},{0x0707f7ff,0xfff7ff07},{0x0707fff7,0xfff7ff07},{0x0707ff07,0xfff7ff07},{0xf7f7ffff,0xfff707f7},
{0xf7fff7ff,0xfff707f7},{0xf7ffffff,0xfff707f7},{0xf7ff0707,0xfff707f7},{0xf707ffff,0xfff707f7},{0xfff7f707,0xfff707f7},{0xfff707ff,0xfff707f7},{0xfffff7f7,0xfff707f7},{0xffffffff,0xfff707f7},
{0xffff07f7,0xfff707f7},{0xff07f7ff,0xfff707f7},{0xff07fff7,0xfff707f7},{0xff07ff07,0xfff707f7},{0xff0707ff,0xfff707f7},{0x07f7ffff,0xfff707f7},{0x07fff7ff,0xfff707f7},{0x07fffff7,0xfff707f7},
{0x07ffff07,0xfff707f7},{0x07ff07ff,0xfff707f7},{0x0707ffff,0xfff707f7},{0xf7f7f7ff,0xfff707ff},{0xf7f7ffff,0xfff707ff},{0xf7f7ff07,0xfff707ff},{0xf7f70707,0xfff707ff},{0xf7fff7f7,0xfff707ff},
{0xf7fffff7,0xfff707ff},{0xf7ffffff,0xfff707ff},{0xf7ff07f7,0xfff707ff},{0xf707f7ff,0xfff707ff},{0xf707fff7,0xfff707ff},{0xf707ff07,0xfff707ff},{0xfff7f7f7,0xfff707ff},{0xfff7ffff,0xfff707ff},
{0xfff70707,0xfff707ff},{0xfffff7ff,0xfff707ff},{0xfffff707,0xfff707ff},{0xfffffff7,0xfff707ff},{0xffffffff,0xfff707ff},{0xffffff07,0xfff707ff},{0xffff07ff,0xfff707ff},{0xff07f7f7,0xfff707ff},
{0xff07f707,0xfff707ff},{0xff07ffff,0xfff707ff},{0xff07ff07,0xfff707ff},{0xff070707,0xfff707ff},{0x07f7ff07,0xfff707ff},{0x07f707ff,0xfff707ff},{0x07fff707,0xfff707ff},{0x07ffffff,0xfff707ff},
{0x07ffff07,0xfff707ff},{0x07ff07f7,0xfff707ff},{0x0707f7ff,0xfff707ff},{0x0707fff7,0xfff707ff},{0x0707ff07,0xfff707ff},{0x070707ff,0xfff707ff},{0xf7ffff07,0xfff70707},{0xfff7fff7,0xfff70707},
{0xfff7ff07,0xfff70707},{0xfff707ff,0xfff70707},{0xffffffff,0xfff70707},{0xffff07f7,0xfff70707},{0xffff0707,0xfff70707},{0xff07fff7,0xfff70707},{0xff0707ff,0xfff70707},{0x07fffff7,0xfff70707},
{0x0707ffff,0xfff70707},{0xf7f7f7ff,0xfffff7f7},{0xf7f7fff7,0xfffff7f7},{0xf7f7ffff,0xfffff7f7},{0xf7f7ff07,0xfffff7f7},{0xf7f707ff,0xfffff7f7},{0xf7fff707,0xfffff7f7},{0xf7ffffff,0xfffff7f7},
{0xf7ff0707,0xfffff7f7},{0xf707f7ff,0xfffff7f7},{0xf707fff7,0xfffff7f7},{0xf70707ff,0xfffff7f7},{0xfff7f7f7,0xfffff7f7},{0xfff7ffff,0xfffff7f7},{0xfff707f7,0xfffff7f7},{0xfffff7ff,0xfffff7f7},
{0xfffffff7,0xfffff7f7},{0xffffffff,0xfffff7f7},{0xffffff07,0xfffff7f7},{0xffff07ff,0xfffff7f7},{0xff07ffff,0xfffff7f7},{0xff0707f7,0xfffff7f7},{0x07f7ff07,0xfffff7f7},{0x07f707ff,0xfffff7f7},
{0x07ffffff,0xfffff7f7},{0x07ff07f7,0xfffff7f7},{0x0707f7f7,0xfffff7f7},{0x0707f7ff,0xfffff7f7},{0x0707ff07,0xfffff7f7},{0x070707ff,0xfffff7f7},{0xf7f7ffff,0xfffff7ff},{0xf7f707f7,0xfffff7ff},
{0xf7f707ff,0xfffff7ff},{0xf7f70707,0xfffff7ff},{0xf7fff7ff,0xfffff7ff},{0xf7fffff7,0xfffff7ff},{0xf7ffffff,0xfffff7ff},{0xf7ffff07,0xfffff7ff},{0xf7ff07f7,0xfffff7ff},{0xf7ff07ff,0xfffff7ff},
{0xf707f7f7,0xfffff7ff},{0xf707ffff,0xfffff7ff},{0xf707ff07,0xfffff7ff},{0xf70707f7,0xfffff7ff},{0xf7070707,0xfffff7ff},{0xfff7f7ff,0xfffff7ff},{0xfff7fff7,0xfffff7ff},{0xfff7ffff,0xfffff7ff},
{0xfff7ff07,0xfffff7ff},{0xfff707ff,0xfffff7ff},{0xfffff7f7,0xfffff7ff},{0xfffff7ff,0xfffff7ff},{0xfffff707,0xfffff7ff},{0xfffffff7,0xfffff7ff},{0xffffffff,0xfffff7ff},{0xffffff07,0xfffff7ff},
{0xffff07f7,0xfffff7ff},{0xffff07ff,0xfffff7ff},{0xffff0707,0xfffff7ff},{0xff07f7ff,0xfffff7ff},{0xff07fff7,0xfffff7ff},{0xff07ffff,0xfffff7ff},{0xff07ff07,0xfffff7ff},{0xff0707ff,0xfffff7ff},
{0x07f7f707,0xfffff7ff},{0x07f7ffff,0xfffff7ff},{0x07fff7ff,0xfffff7ff},{0x07fffff7,0xfffff7ff},{0x07ffffff,0xfffff7ff},{0x07ffff07,0xfffff7ff},{0x07ff07ff,0xfffff7ff},{0x0707f7f7,0xfffff7ff},
{0x0707ffff,0xfffff7ff},{0x07070707,0xfffff7ff},{0xf7f7f7ff,0xfffff707},{0xf7f7ff07,0xfffff707},{0xf7fff707,0xfffff707},{0xf7ffffff,0xfffff707},{0xf7ff0707,0xfffff707},{0xf707f7ff,0xfffff707},
{0xf707fff7,0xfffff707},{0xfff7f707,0xfffff707},{0xfff7ffff,0xfffff707},{0xfff70707,0xfffff707},{0xfffff7ff,0xfffff707},{0xfffffff7,0xfffff707},{0xffffffff,0xfffff707},{0xffffff07,0xfffff707},
{0xffff07ff,0xfffff707},{0xff07f707,0xfffff707},{0xff07ffff,0xfffff707},{0x07f7ffff,0xfffff707},{0x07fff7f7,0xfffff707},{0x07fff707,0xfffff707},{0x07ffffff,0xfffff707},{0x07ff07ff,0xfffff707},
{0x07ff0707,0xfffff707},{0x0707fff7,0xfffff707},{0xf7f7fff7,0xfffffff7},{0xf7f7ffff,0xfffffff7},{0xf7fff7ff,0xfffffff7},{0xf7fffff7,0xfffffff7},{0xf7ffffff,0xfffffff7},{0xf7ffff07,0xfffffff7},
{0xf7ff07f7,0xfffffff7},{0xf7ff07ff,0xfffffff7},{0xf707f7ff,0xfffffff7},{0xf707ffff,0xfffffff7},{0xf70707f7,0xfffffff7},{0xf7070707,0xfffffff7},{0xfff7f7ff,0xfffffff7},{0xfff7fff7,0xfffffff7},
{0xfff7ffff,0xfffffff7},{0xfff7ff07,0xfffffff7},{0xfff707ff,0xfffffff7},{0xfff70707,0xfffffff7},{0xfffff7f7,0xfffffff7},{0xfffff7ff,0xfffffff7},{0xfffffff7,0xfffffff7},{0xffffffff,0xfffffff7},
{0xffffff07,0xfffffff7},{0xffff07f7,0xfffffff7},{0xffff07ff,0xfffffff7},{0xffff0707,0xfffffff7},{0xff07f7ff,0xfffffff7},{0xff07f707,0xfffffff7},{0xff07fff7,0xfffffff7},{0xff07ffff,0xfffffff7},
{0xff07ff07,0xfffffff7},{0xff0707ff,0xfffffff7},{0x07f7f7f7,0xfffffff7},{0x07f707f7,0xfffffff7},{0x07f70707,0xfffffff7},{0x07fff7ff,0xfffffff7},{0x07fffff7,0xfffffff7},{0x07ffffff,0xfffffff7},
{0x07ffff07,0xfffffff7},{0x07ff07ff,0xfffffff7},{0x0707f7ff,0xfffffff7},{0x0707fff7,0xfffffff7},{0x0707ffff,0xfffffff7},{0x07070707,0xfffffff7},{0xf7f7f7ff,0xffffffff},{0xf7f7f707,0xffffffff},
{0xf7f7fff7,0xffffffff},{0xf7f7ffff,0xffffffff},{0xf7f7ff07,0xffffffff},{0xf7f707ff,0xffffffff},{0xf7fff7f7,0xffffffff},{0xf7fff7ff,0xffffffff},{0xf7fff707,0xffffffff},{0xf7fffff7,0xffffffff},
{0xf7ffffff,0xffffffff},{0xf7ffff07,0xffffffff},{0xf7ff07ff,0xffffffff},{0xf7ff0707,0xffffffff},{0xf707f7ff,0xffffffff},{0xf707fff7,0xffffffff},{0xf707ffff,0xffffffff},{0xf707ff07,0xffffffff},
{0xf70707ff,0xffffffff},{0xfff7f7f7,0xffffffff},{0xfff7f7ff,0xffffffff},{0xfff7f707,0xffffffff},{0xfff7fff7,0xffffffff},{0xfff7ffff,0xffffffff},{0xfff7ff07,0xffffffff},{0xfff707f7,0xffffffff},
{0xfff707ff,0xffffffff},{0xfffff7f7,0xffffffff},{0xfffff7ff,0xffffffff},{0xfffff707,0xffffffff},{0xfffffff7,0xffffffff},{0xffffffff,0xffffffff},{0xffffff07,0xffffffff},{0xffff07f7,0xffffffff},
{0xffff07ff,0xffffffff},{0xffff0707,0xffffffff},{0xff07f7f7,0xffffffff},{0xff07f7ff,0xffffffff},{0xff07fff7,0xffffffff},{0xff07ffff,0xffffffff},{0xff07ff07,0xffffffff},{0xff0707f7,0xffffffff},
{0xff0707ff,0xffffffff},{0xff070707,0xffffffff},{0x07f7f7ff,0xffffffff},{0x07f7fff7,0xffffffff},{0x07f7ffff,0xffffffff},{0x07f707ff,0xffffffff},{0x07f70707,0xffffffff},{0x07fff7f7,0xffffffff},
{0x07fff7ff,0xffffffff},{0x07fffff7,0xffffffff},{0x07ffffff,0xffffffff},{0x07ffff07,0xffffffff},{0x07ff07f7,0xffffffff},{0x07ff07ff,0xffffffff},{0x0707f7ff,0xffffffff},{0x0707fff7,0xffffffff},
{0x0707ffff,0xffffffff},{0x0707ff07,0xffffffff},{0x070707ff,0xffffffff},{0xf7f7f7f7,0xffffff07},{0xf7f7f7ff,0xffffff07},{0xf7f7f707,0xffffff07},{0xf7f7fff7,0xffffff07},{0xf7f7ff07,0xffffff07},
{0xf7f707f7,0xffffff07},{0xf7f707ff,0xffffff07},{0xf7fff7ff,0xffffff07},{0xf7fffff7,0xffffff07},{0xf7ffffff,0xffffff07},{0xf7ff07f7,0xffffff07},{0xf7ff07ff,0xffffff07},{0xf707f7f7,0xffffff07},
{0xf707f7ff,0xffffff07},{0xf707f707,0xffffff07},{0xf707fff7,0xffffff07},{0xf707ffff,0xffffff07},{0xf707ff07,0xffffff07},{0xf70707f7,0xffffff07},{0xf70707ff,0xffffff07},{0xfff7f7ff,0xffffff07},
{0xfff7ffff,0xffffff07},{0xfff7ff07,0xffffff07},{0xfff707f7,0xffffff07},{0xfff707ff,0xffffff07},{0xfff70707,0xffffff07},{0xfffff7f7,0xffffff07},{0xfffff7ff,0xffffff07},{0xfffff707,0xffffff07},
{0xfffffff7,0xffffff07},{0xffffffff,0xffffff07},{0xffffff07,0xffffff07},{0xffff07f7,0xffffff07},{0xffff07ff,0xffffff07},{0xffff0707,0xffffff07},{0xff07f7ff,0xffffff07},{0xff07fff7,0xffffff07},
{0xff07ffff,0xffffff07},{0xff0707ff,0xffffff07},{0x07f7f707,0xffffff07},{0x07f7ffff,0xffffff07},{0x07f7ff07,0xffffff07},{0x07f707f7,0xffffff07},{0x07f707ff,0xffffff07},{0x07f70707,0xffffff07},
{0x07fff7ff,0xffffff07},{0x07ffffff,0xffffff07},{0x07ff0707,0xffffff07},{0x0707f707,0xffffff07},{0x0707ffff,0xffffff07},{0x0707ff07,0xffffff07},{0x070707f7,0xffffff07},{0x070707ff,0xffffff07},
{0xf7f7fff7,0xffff07f7},{0xf7f7ffff,0xffff07f7},{0xf7f7ff07,0xffff07f7},{0xf7f707ff,0xffff07f7},{0xf7fff7f7,0xffff07f7},{0xf7ffffff,0xffff07f7},{0xf7ff07f7,0xffff07f7},{0xf707f7ff,0xffff07f7},
{0xf7070707,0xffff07f7},{0xfff7ffff,0xffff07f7},{0xfff707f7,0xffff07f7},{0xfff70707,0xffff07f7},{0xfffff7ff,0xffff07f7},{0xfffffff7,0xffff07f7},{0xffffffff,0xffff07f7},{0xffffff07,0xffff07f7},
{0xffff07f7,0xffff07f7},{0xffff07ff,0xffff07f7},{0xff07f7f7,0xffff07f7},{0xff07f707,0xffff07f7},{0xff07fff7,0xffff07f7},{0xff07ffff,0xffff07f7},{0x07f7f707,0xffff07f7},{0x07f707ff,0xffff07f7},
{0x07fff7f7,0xffff07f7},{0x07fff707,0xffff07f7},{0x07ffffff,0xffff07f7},{0x07ff07f7,0xffff07f7},{0x0707f7ff,0xffff07f7},{0x070707ff,0xffff07f7},{0xf7f7f7ff,0xffff07ff},{0xf7f7f707,0xffff07ff},
{0xf7f7ffff,0xffff07ff},{0xf7f70707,0xffff07ff},{0xf7fff7ff,0xffff07ff},{0xf7fffff7,0xffff07ff},{0xf7ffffff,0xffff07ff},{0xf7ffff07,0xffff07ff},{0xf7ff07ff,0xffff07ff},{0xf707ffff,0xffff07ff},
{0xfff7f7ff,0xffff07ff},{0xfff7fff7,0xffff07ff},{0xfff7ffff,0xffff07ff},{0xfff7ff07,0xffff07ff},{0xfff707ff,0xffff07ff},{0xfffff7f7,0xffff07ff},{0xfffff7ff,0xffff07ff},{0xfffff707,0xffff07ff},
{0xfffffff7,0xffff07ff},{0xffffffff,0xffff07ff},{0xffffff07,0xffff07ff},{0xffff07f7,0xffff07ff},{0xffff07ff,0xffff07ff},{0xffff0707,0xffff07ff},{0xff07f7ff,0xffff07ff},{0xff07fff7,0xffff07ff},
{0xff07ffff,0xffff07ff},{0xff07ff07,0xffff07ff},{0xff0707ff,0xffff07ff},{0x07f7f7ff,0xffff07ff},{0x07f7ffff,0xffff07ff},{0x07f707ff,0xffff07ff},{0x07fff7ff,0xffff07ff},{0x07fffff7,0xffff07ff},
{0x07ffffff,0xffff07ff},{0x07ffff07,0xffff07ff},{0x07ff07f7,0xffff07ff},{0x07ff07ff,0xffff07ff},{0x0707ffff,0xffff07ff},{0xf7f7fff7,0xffff0707},{0xf7f707f7,0xffff0707},{0xf7ffffff,0xffff0707},
{0xf7ff0707,0xffff0707},{0xf707f7f7,0xffff0707},{0xf707ffff,0xffff0707},{0xf707ff07,0xffff0707},{0xf70707ff,0xffff0707},{0xfff7ffff,0xffff0707},{0xfff707f7,0xffff0707},{0xfff707ff,0xffff0707},
{0xfffff7ff,0xffff0707},{0xffffffff,0xffff0707},{0xffffff07,0xffff0707},{0xffff07f7,0xffff0707},{0xffff07ff,0xffff0707},{0xff07f707,0xffff0707},{0xff07ffff,0xffff0707},{0xff0707f7,0xffff0707},
{0xff070707,0xffff0707},{0x07f7f7ff,0xffff0707},{0x07f70707,0xffff0707},{0x07fff707,0xffff0707},{0x07ffffff,0xffff0707},{0x07ffff07,0xffff0707},{0x07ff07f7,0xffff0707},{0x07ff0707,0xffff0707},
{0x0707f7ff,0xffff0707},{0xf7f7ffff,0xff07f7f7},{0xf7fffff7,0xff07f7f7},{0xf7ffff07,0xff07f7f7},{0xf7ff07ff,0xff07f7f7},{0xf707ffff,0xff07f7f7},{0xfff7fff7,0xff07f7f7},{0xfffff7f7,0xff07f7f7},
{0xffffffff,0xff07f7f7},{0xffffff07,0xff07f7f7},{0xffff07f7,0xff07f7f7},{0xffff0707,0xff07f7f7},{0xff07f7ff,0xff07f7f7},{0xff07fff7,0xff07f7f7},{0xff07ff07,0xff07f7f7},{0xff0707ff,0xff07f7f7},
{0x07f7f7ff,0xff07f7f7},{0x07ffff07,0xff07f7f7},{0x0707ffff,0xff07f7f7},{0xf7f7f7ff,0xff07f7ff},{0xf7f7fff7,0xff07f7ff},{0xf7f7ff07,0xff07f7ff},{0xf7f707ff,0xff07f7ff},{0xf7fff707,0xff07f7ff},
{0xf7ffffff,0xff07f7ff},{0xf707f7ff,0xff07f7ff},{0xf707f707,0xff07f7ff},{0xf707ff07,0xff07f7ff},{0xf70707ff,0xff07f7ff},{0xfff7ffff,0xff07f7ff},{0xfff707ff,0xff07f7ff},{0xfffff7ff,0xff07f7ff},
{0xffffffff,0xff07f7ff},{0xffffff07,0xff07f7ff},{0xffff07ff,0xff07f7ff},{0xff07ffff,0xff07f7ff},{0xff07ff07,0xff07f7ff},{0xff070707,0xff07f7ff},{0x07f7fff7,0xff07f7ff},{0x07f70707,0xff07f7ff},
{0x07fff707,0xff07f7ff},{0x07ffffff,0xff07f7ff},{0x0707f7ff,0xff07f7ff},{0x0707ff07,0xff07f7ff},{0x070707ff,0xff07f7ff},{0xf7fff7ff,0xff07f707},{0xf7ffff07,0xff07f707},{0xf7ff07ff,0xff07f707},
{0xfff7f7f7,0xff07f707},{0xfff7f7ff,0xff07f707},{0xfff7ff07,0xff07f707},{0xffffffff,0xff07f707},{0xffffff07,0xff07f707},{0xffff07f7,0xff07f707},{0xff07f7f7,0xff07f707},{0x07f7ffff,0xff07f707},
{0x07fff7ff,0xff07f707},{0x07ffff07,0xff07f707},{0x0707ffff,0xff07f707},{0xf7fff7ff,0xff07fff7},{0xf7fff707,0xff07fff7},{0xf7ffffff,0xff07fff7},{0xf7ffff07,0xff07fff7},{0xf7ff0707,0xff07fff7},
{0xf707f7ff,0xff07fff7},{0xf707ff07,0xff07fff7},{0xf70707ff,0xff07fff7},{0xfff7f7f7,0xff07fff7},{0xfff7f707,0xff07fff7},{0xfff7ffff,0xff07fff7},{0xfff707f7,0xff07fff7},{0xfff70707,0xff07fff7},
{0xfffff7ff,0xff07fff7},{0xfffffff7,0xff07fff7},{0xffffffff,0xff07fff7},{0xffffff07,0xff07fff7},{0xffff07ff,0xff07fff7},{0xffff0707,0xff07fff7},{0xff07f7f7,0xff07fff7},{0xff07f707,0xff07fff7},
{0xff07ffff,0xff07fff7},{0x07f7fff7,0xff07fff7},{0x07f7ffff,0xff07fff7},{0x07f707ff,0xff07fff7},{0x07fff7f7,0xff07fff7},{0x07fff707,0xff07fff7},{0x07fffff7,0xff07fff7},{0x07ffffff,0xff07fff7},
{0x07ffff07,0xff07fff7},{0x07ff07f7,0xff07fff7},{0x07ff0707,0xff07fff7},{0x0707f7ff,0xff07fff7},{0x0707fff7,0xff07fff7},{0x070707ff,0xff07fff7},{0xf7f7ffff,0xff07ffff},{0xf7f707f7,0xff07ffff},
{0xf7f70707,0xff07ffff},{0xf7fff7ff,0xff07ffff},{0xf7ffffff,0xff07ffff},{0xf7ffff07,0xff07ffff},{0xf7ff07ff,0xff07ffff},{0xfff7fff7,0xff07ffff},{0xfff7ffff,0xff07ffff},{0xfff7ff07,0xff07ffff},
{0xfff707ff,0xff07ffff},{0xfffff7f7,0xff07ffff},{0xfffff7ff,0xff07ffff},{0xfffffff7,0xff07ffff},{0xffffffff,0xff07ffff},{0xffffff07,0xff07ffff},{0xffff07ff,0xff07ffff},{0xff07f7ff,0xff07ffff},
{0xff07fff7,0xff07ffff},{0xff07ffff,0xff07ffff},{0xff07ff07,0xff07ffff},{0xff0707ff,0xff07ffff},{0x07f7ff07,0xff07ffff},{0x07f707ff,0xff07ffff},{0x07f70707,0xff07ffff},{0x07fff7ff,0xff07ffff},
{0x07ffffff,0xff07ffff},{0x07ffff07,0xff07ffff},{0x07ff07ff,0xff07ffff},{0x07ff0707,0xff07ffff},{0x0707f707,0xff07ffff},{0x0707ffff,0xff07ffff},{0x0707ff07,0xff07ffff},{0x070707f7,0xff07ffff},
{0xf7f7f707,0xff07ff07},{0xf7f707ff,0xff07ff07},{0xf7ffffff,0xff07ff07},{0xf707f7f7,0xff07ff07},{0xf707ff07,0xff07ff07},{0xf70707f7,0xff07ff07},{0xf70707ff,0xff07ff07},{0xfff7f7f7,0xff07ff07},
{0xfff7ffff,0xff07ff07},{0xfff707f7,0xff07ff07},{0xfff70707,0xff07ff07},{0xfffff7ff,0xff07ff07},{0xfffffff7,0xff07ff07},{0xffffffff,0xff07ff07},{0xffffff07,0xff07ff07},{0xffff07f7,0xff07ff07},
{0xffff0707,0xff07ff07},{0xff07f7f7,0xff07ff07},{0xff07ffff,0xff07ff07},{0xff0707f7,0xff07ff07},{0x07f7f7f7,0xff07ff07},{0x07f7f707,0xff07ff07},{0x07f7ffff,0xff07ff07},{0x07f70707,0xff07ff07},
{0x07fffff7,0xff07ff07},{0x07ffff07,0xff07ff07},{0x07ff07f7,0xff07ff07},{0x07ff07ff,0xff07ff07},{0x0707f7f7,0xff07ff07},{0x0707fff7,0xff07ff07},{0x0707ff07,0xff07ff07},{0x07070707,0xff07ff07},
{0xf7ffff07,0xff0707f7},{0xf7ff07ff,0xff0707f7},{0xf707ffff,0xff0707f7},{0xfff7f7ff,0xff0707f7},{0xfffff707,0xff0707f7},{0xffffffff,0xff0707f7},{0xffff0707,0xff0707f7},{0xff07f7ff,0xff0707f7},
{0xff0707ff,0xff0707f7},{0x07f7ffff,0xff0707f7},{0x07fff7ff,0xff0707f7},{0x07ff07f7,0xff0707f7},{0x0707ff07,0xff0707f7},{0xf7f7f7ff,0xff0707ff},{0xf7f7fff7,0xff0707ff},{0xf7fff7f7,0xff0707ff},
{0xf7ffffff,0xff0707ff},{0xf707f7ff,0xff0707ff},{0xf707fff7,0xff0707ff},{0xf707ff07,0xff0707ff},{0xf70707ff,0xff0707ff},{0xfff7f7f7,0xff0707ff},{0xfff7f7ff,0xff0707ff},{0xfff7ffff,0xff0707ff},
{0xfff7ff07,0xff0707ff},{0xfff707f7,0xff0707ff},{0xfffff7ff,0xff0707ff},{0xfffffff7,0xff0707ff},{0xffffffff,0xff0707ff},{0xffffff07,0xff0707ff},{0xffff07ff,0xff0707ff},{0xff07f7f7,0xff0707ff},
{0xff07ffff,0xff0707ff},{0xff070707,0xff0707ff},{0x07f7f707,0xff0707ff},{0x07f7fff7,0xff0707ff},{0x07f70707,0xff0707ff},{0x07ffffff,0xff0707ff},{0x0707f7ff,0xff0707ff},{0x0707fff7,0xff0707ff},
{0x0707ffff,0xff0707ff},{0x070707ff,0xff0707ff},{0xf7fff7ff,0xff070707},{0xf7ffff07,0xff070707},{0xf7ff07f7,0xff070707},{0xfff7f7ff,0xff070707},{0xfff7fff7,0xff070707},{0xfff707ff,0xff070707},
{0xfffff7f7,0xff070707},{0xffffffff,0xff070707},{0xffff07f7,0xff070707},{0xffff0707,0xff070707},{0xff07fff7,0xff070707},{0xff07ffff,0xff070707},{0xff0707ff,0xff070707},{0x07f7ff07,0xff070707},
{0x07fffff7,0xff070707},{0x07ff07f7,0xff070707},{0x07ff0707,0xff070707},{0x0707ff07,0xff070707},{0xf7f7f7f7,0x07f7f7f7},{0xf7f7f707,0x07f7f7f7},{0xf7f707f7,0x07f7f7f7},{0xf7f70707,0x07f7f7f7},
{0xf707f7f7,0x07f7f7f7},{0xf707f707,0x07f7f7f7},{0xf70707f7,0x07f7f7f7},{0xf7070707,0x07f7f7f7},{0xfff7ffff,0x07f7f7f7},{0xfffff7f7,0x07f7f7f7},{0xfffff7ff,0x07f7f7f7},{0xfffffff7,0x07f7f7f7},
{0xffffff07,0x07f7f7f7},{0xffff07ff,0x07f7f7f7},{0xff07ffff,0x07f7f7f7},{0x07f7f7f7,0x07f7f7f7},{0x07f7f707,0x07f7f7f7},{0x07f707f7,0x07f7f7f7},{0x07f70707,0x07f7f7f7},{0x07ffffff,0x07f7f7f7},
{0x0707f7f7,0x07f7f7f7},{0x0707f707,0x07f7f7f7},{0x070707f7,0x07f7f7f7},{0x07070707,0x07f7f7f7},{0xf7f7ffff,0x07f7f7ff},{0xf7fff7ff,0x07f7f7ff},{0xf7fffff7,0x07f7f7ff},{0xf7ffff07,0x07f7f7ff},
{0xf7ff07ff,0x07f7f7ff},{0xf707ffff,0x07f7f7ff},{0xfff7f7ff,0x07f7f7ff},{0xfff7fff7,0x07f7f7ff},{0xfff707ff,0x07f7f7ff},{0xfffff7f7,0x07f7f7ff},{0xfffff707,0x07f7f7ff},{0xffffffff,0x07f7f7ff},
{0xffffff07,0x07f7f7ff},{0xffff07f7,0x07f7f7ff},{0xffff07ff,0x07f7f7ff},{0xff07fff7,0x07f7f7ff},{0xff07ff07,0x07f7f7ff},{0xff0707ff,0x07f7f7ff},{0x07f7ffff,0x07f7f7ff},{0x07f707ff,0x07f7f7ff},
{0x07fffff7,0x07f7f7ff},{0x07ffff07,0x07f7f7ff},{0x07ff07ff,0x07f7f7ff},{0x0707ffff,0x07f7f7ff},{0xf7f7f7f7,0x07f7f707},{0xf7f7f707,0x07f7f707},{0xf7f707f7,0x07f7f707},{0xf7f70707,0x07f7f707},
{0xf7ffffff,0x07f7f707},{0xf707f7f7,0x07f7f707},{0xf707f707,0x07f7f707},{0xf70707f7,0x07f7f707},{0xf7070707,0x07f7f707},{0xfffff7ff,0x07f7f707},{0xfffffff7,0x07f7f707},{0xffff07ff,0x07f7f707},
{0xff07ffff,0x07f7f707},{0x07f7f7f7,0x07f7f707},{0x07f7f707,0x07f7f707},{0x07f707f7,0x07f7f707},{0x07f70707,0x07f7f707},{0x07ffffff,0x07f7f707},{0x0707f7f7,0x07f7f707},{0x0707f707,0x07f7f707},
{0x070707f7,0x07f7f707},{0x07070707,0x07f7f707},{0xf7fffff7,0x07f7fff7},{0xf7ff07ff,0x07f7fff7},{0xfff7f7ff,0x07f7fff7},{0xfff7fff7,0x07f7fff7},{0xfffff7ff,0x07f7fff7},{0xffffffff,0x07f7fff7},
{0xffff0707,0x07f7fff7},{0xff07f7ff,0x07f7fff7},{0xff07fff7,0x07f7fff7},{0xff0707ff,0x07f7fff7},{0x07fffff7,0x07f7fff7},{0x07ff07ff,0x07f7fff7},{0xf7f7f7ff,0x07f7ffff},{0xf7f707ff,0x07f7ffff},
{0xf7fff707,0x07f7ffff},{0xf7ffffff,0x07f7ffff},{0xf7ff0707,0x07f7ffff},{0xf707ff07,0x07f7ffff},{0xf70707ff,0x07f7ffff},{0xfff7f7f7,0x07f7ffff},{0xfff7f7ff,0x07f7ffff},{0xfff7ffff,0x07f7ffff},
{0xfff707f7,0x07f7ffff},{0xfffff7ff,0x07f7ffff},{0xfffffff7,0x07f7ffff},{0xffffffff,0x07f7ffff},{0xffffff07,0x07f7ffff},{0xffff07ff,0x07f7ffff},{0xffff0707,0x07f7ffff},{0xff07ffff,0x07f7ffff},
{0xff07ff07,0x07f7ffff},{0xff0707f7,0x07f7ffff},{0xff070707,0x07f7ffff},{0x07f7f7ff,0x07f7ffff},{0x07f7fff7,0x07f7ffff},{0x07f7ff07,0x07f7ffff},{0x07f707ff,0x07f7ffff},{0x07fff7f7,0x07f7ffff},
{0x07fff707,0x07f7ffff},{0x07ffffff,0x07f7ffff},{0x07ff07f7,0x07f7ffff},{0x0707ff07,0x07f7ffff},{0xf7fff7ff,0x07f7ff07},{0xf7ffff07,0x07f7ff07},{0xf7ff07ff,0x07f7ff07},{0xf707ffff,0x07f7ff07},
{0xfff7f7ff,0x07f7ff07},{0xfff7fff7,0x07f7ff07},{0xfff707ff,0x07f7ff07},{0xfff70707,0x07f7ff07},{0xfffff7f7,0x07f7ff07},{0xffffffff,0x07f7ff07},{0xffff07ff,0x07f7ff07},{0xffff0707,0x07f7ff07},
{0xff07f7ff,0x07f7ff07},{0xff07ff07,0x07f7ff07},{0xff070707,0x07f7ff07},{0x07f7ffff,0x07f7ff07},{0x07fff7ff,0x07f7ff07},{0x07ff0707,0x07f7ff07},{0x0707fff7,0x07f7ff07},{0xf7f7f7f7,0x07f707f7},
{0xf7f7f707,0x07f707f7},{0xf7f707f7,0x07f707f7},{0xf7f70707,0x07f707f7},{0xf7ffffff,0x07f707f7},{0xf707f7f7,0x07f707f7},{0xf707f707,0x07f707f7},{0xf70707f7,0x07f707f7},{0xf7070707,0x07f707f7},
{0xfff7f7ff,0x07f707f7},{0xfff7ffff,0x07f707f7},{0xfffff7ff,0x07f707f7},{0xfffffff7,0x07f707f7},{0xffff07ff,0x07f707f7},{0xff07ffff,0x07f707f7},{0xff0707ff,0x07f707f7},{0x07f7f7f7,0x07f707f7},
{0x07f7f707,0x07f707f7},{0x07f707f7,0x07f707f7},{0x07f70707,0x07f707f7},{0x07ffffff,0x07f707f7},{0x0707f7f7,0x07f707f7},{0x0707f707,0x07f707f7},{0x070707f7,0x07f707f7},{0x07070707,0x07f707f7},
{0xf7f7ffff,0x07f707ff},{0xf7f7ff07,0x07f707ff},{0xf7fff7ff,0x07f707ff},{0xf7fffff7,0x07f707ff},{0xf7ffff07,0x07f707ff},{0xf707ffff,0x07f707ff},{0xfff7f7ff,0x07f707ff},{0xfff7fff7,0x07f707ff},
{0xfff7ff07,0x07f707ff},{0xfff707ff,0x07f707ff},{0xfffff7f7,0x07f707ff},{0xfffff707,0x07f707ff},{0xffffffff,0x07f707ff},{0xffff0707,0x07f707ff},{0xff07f7ff,0x07f707ff},{0xff07fff7,0x07f707ff},
{0x07f7ffff,0x07f707ff},{0x07ffff07,0x07f707ff},{0x07ff07ff,0x07f707ff},{0x0707ffff,0x07f707ff},{0xf7f7f7f7,0x07f70707},{0xf7f7f707,0x07f70707},{0xf7f707f7,0x07f70707},{0xf7f70707,0x07f70707},
{0xf7ffffff,0x07f70707},{0xf707f7f7,0x07f70707},{0xf707f707,0x07f70707},{0xf70707f7,0x07f70707},{0xf7070707,0x07f70707},{0xfff7ffff,0x07f70707},{0xfffff7ff,0x07f70707},{0xfffffff7,0x07f70707},
{0xffffff07,0x07f70707},{0x07f7f7f7,0x07f70707},{0x07f7f707,0x07f70707},{0x07f707f7,0x07f70707},{0x07f70707,0x07f70707},{0x07ffffff,0x07f70707},{0x0707f7f7,0x07f70707},{0x0707f707,0x07f70707},
{0x070707f7,0x07f70707},{0x07070707,0x07f70707},{0xf7f7ffff,0x07fff7f7},{0xf7fff7ff,0x07fff7f7},{0xf7ffff07,0x07fff7f7},{0xf7ff07f7,0x07fff7f7},{0xf7ff07ff,0x07fff7f7},{0xf707ffff,0x07fff7f7},
{0xfff7f7ff,0x07fff7f7},{0xfff7ff07,0x07fff7f7},{0xfff707ff,0x07fff7f7},{0xffffffff,0x07fff7f7},{0xffff07f7,0x07fff7f7},{0xffff0707,0x07fff7f7},{0xff0707ff,0x07fff7f7},{0xff070707,0x07fff7f7},
{0x07f7ffff,0x07fff7f7},{0x07fff7ff,0x07fff7f7},{0x07fffff7,0x07fff7f7},{0x07ffff07,0x07fff7f7},{0x07ff07ff,0x07fff7f7},{0x0707ffff,0x07fff7f7},{0xf7f7f7ff,0x07fff7ff},{0xf7f7fff7,0x07fff7ff},
{0xf7f7ff07,0x07fff7ff},{0xf7f707ff,0x07fff7ff},{0xf7fff7f7,0x07fff7ff},{0xf7ffffff,0x07fff7ff},{0xf7ff07f7,0x07fff7ff},{0xf7ff0707,0x07fff7ff},{0xf707f7ff,0x07fff7ff},{0xf707fff7,0x07fff7ff},
{0xf707ff07,0x07fff7ff},{0xf70707ff,0x07fff7ff},{0xfff7f7f7,0x07fff7ff},{0xfff7ffff,0x07fff7ff},{0xfffff7f7,0x07fff7ff},{0xfffff7ff,0x07fff7ff},{0xfffffff7,0x07fff7ff},{0xffffffff,0x07fff7ff},
{0xffffff07,0x07fff7ff},{0xffff07ff,0x07fff7ff},{0xff07f707,0x07fff7ff},{0xff07ffff,0x07fff7ff},{0x07f7fff7,0x07fff7ff},{0x07f7ff07,0x07fff7ff},{0x07fff707,0x07fff7ff},{0x07ffffff,0x07fff7ff},
{0x07ff07f7,0x07fff7ff},{0x0707f7ff,0x07fff7ff},{0x0707fff7,0x07fff7ff},{0x0707ff07,0x07fff7ff},{0x070707ff,0x07fff7ff},{0xf7f7ffff,0x07fff707},{0xf7fff7ff,0x07fff707},{0xf7fffff7,0x07fff707},
{0xf7ff07ff,0x07fff707},{0xf707ffff,0x07fff707},{0xfff7fff7,0x07fff707},{0xfff7ff07,0x07fff707},{0xfff707ff,0x07fff707},{0xfffff7f7,0x07fff707},{0xfffff707,0x07fff707},{0xffffffff,0x07fff707},
{0xffff07f7,0x07fff707},{0xff07ff07,0x07fff707},{0xff0707ff,0x07fff707},{0x07f7ffff,0x07fff707},{0x07fffff7,0x07fff707},{0x07ffff07,0x07fff707},{0x070707ff,0x07fff707},{0xf7f7f7ff,0x07fffff7},
{0xf7f7fff7,0x07fffff7},{0xf7f7ff07,0x07fffff7},{0xf7fff7f7,0x07fffff7},{0xf7ffffff,0x07fffff7},{0xf7ff07f7,0x07fffff7},{0xf707ff07,0x07fffff7},{0xfff7f7f7,0x07fffff7},{0xfff70707,0x07fffff7},
{0xfffff7ff,0x07fffff7},{0xfffffff7,0x07fffff7},{0xffffffff,0x07fffff7},{0xffffff07,0x07fffff7},{0xffff07f7,0x07fffff7},{0xffff07ff,0x07fffff7},{0xff07f7f7,0x07fffff7},{0xff07f7ff,0x07fffff7},
{0xff07f707,0x07fffff7},{0xff07ffff,0x07fffff7},{0x07f7fff7,0x07fffff7},{0x07f7ff07,0x07fffff7},{0x07fff707,0x07fffff7},{0x07fffff7,0x07fffff7},{0x07ffffff,0x07fffff7},{0x07ff07f7,0x07fffff7},
{0x0707f7ff,0x07fffff7},{0x070707ff,0x07fffff7},{0xf7f7f7f7,0x07ffffff},{0xf7f7ffff,0x07ffffff},{0xf7f707f7,0x07ffffff},{0xf7f70707,0x07ffffff},{0xf7fff7f7,0x07ffffff},{0xf7fff7ff,0x07ffffff},
{0xf7fffff7,0x07ffffff},{0xf7ffffff,0x07ffffff},{0xf7ffff07,0x07ffffff},{0xf7ff07ff,0x07ffffff},{0xf707f7ff,0x07ffffff},{0xf707ffff,0x07ffffff},{0xf70707ff,0x07ffffff},{0xf7070707,0x07ffffff},
{0xfff7f7ff,0x07ffffff},{0xfff7fff7,0x07ffffff},{0xfff7ffff,0x07ffffff},{0xfff7ff07,0x07ffffff},{0xfff707ff,0x07ffffff},{0xfffff7f7,0x07ffffff},{0xfffff7ff,0x07ffffff},{0xfffff707,0x07ffffff},
{0xfffffff7,0x07ffffff},{0xffffffff,0x07ffffff},{0xffffff07,0x07ffffff},{0xffff07f7,0x07ffffff},{0xffff07ff,0x07ffffff},{0xffff0707,0x07ffffff},{0xff07f7ff,0x07ffffff},{0xff07fff7,0x07ffffff},
{0xff07ffff,0x07ffffff},{0xff07ff07,0x07ffffff},{0xff0707ff,0x07ffffff},{0x07f7f7ff,0x07ffffff},{0x07f7ffff,0x07ffffff},{0x07f707f7,0x07ffffff},{0x07fff7ff,0x07ffffff},{0x07fff707,0x07ffffff},
{0x07fffff7,0x07ffffff},{0x07ffffff,0x07ffffff},{0x07ffff07,0x07ffffff},{0x07ff07ff,0x07ffffff},{0x07ff0707,0x07ffffff},{0x0707f7f7,0x07ffffff},{0x0707f707,0x07ffffff},{0x0707ffff,0x07ffffff},
{0x070707f7,0x07ffffff},{0x07070707,0x07ffffff},{0xf7f7f7ff,0x07ffff07},{0xf7f7fff7,0x07ffff07},{0xf7fff7f7,0x07ffff07},{0xf7ffffff,0x07ffff07},{0xf7ff07ff,0x07ffff07},{0xf707f7f7,0x07ffff07},
{0xf707ff07,0x07ffff07},{0xf70707ff,0x07ffff07},{0xfff7ffff,0x07ffff07},{0xfff707f7,0x07ffff07},{0xfff707ff,0x07ffff07},{0xfffff7ff,0x07ffff07},{0xfffff707,0x07ffff07},{0xffffffff,0x07ffff07},
{0xffffff07,0x07ffff07},{0xffff07ff,0x07ffff07},{0xff07ffff,0x07ffff07},{0xff0707f7,0x07ffff07},{0x07f7f707,0x07ffff07},{0x07f7fff7,0x07ffff07},{0x07f707ff,0x07ffff07},{0x07f70707,0x07ffff07},
{0x07fff707,0x07ffff07},{0x07fffff7,0x07ffff07},{0x07ffffff,0x07ffff07},{0x0707fff7,0x07ffff07},{0x0707ff07,0x07ffff07},{0x070707ff,0x07ffff07},{0xf7f7ffff,0x07ff07f7},{0xf7ffff07,0x07ff07f7},
{0xf7ff07ff,0x07ff07f7},{0xf707ffff,0x07ff07f7},{0xfff7f7ff,0x07ff07f7},{0xfff7ff07,0x07ff07f7},{0xfffff7f7,0x07ff07f7},{0xfffff707,0x07ff07f7},{0xffffffff,0x07ff07f7},{0xffffff07,0x07ff07f7},
{0xffff0707,0x07ff07f7},{0xff07fff7,0x07ff07f7},{0xff07ffff,0x07ff07f7},{0x07f7ffff,0x07ff07f7},{0x07fff7ff,0x07ff07f7},{0x07ffff07,0x07ff07f7},{0x07ff07ff,0x07ff07f7},{0x0707ffff,0x07ff07f7},
{0xf7f7fff7,0x07ff07ff},{0xf7f7ff07,0x07ff07ff},{0xf7f707ff,0x07ff07ff},{0xf7fff7f7,0x07ff07ff},{0xf7fff707,0x07ff07ff},{0xf7ffffff,0x07ff07ff},{0xf7ff07f7,0x07ff07ff},{0xf7ff0707,0x07ff07ff},
{0xf707f7f7,0x07ff07ff},{0xf707f7ff,0x07ff07ff},{0xf707fff7,0x07ff07ff},{0xf707ff07,0x07ff07ff},{0xfff7f7f7,0x07ff07ff},{0xfff7f707,0x07ff07ff},{0xfff7ffff,0x07ff07ff},{0xfff707f7,0x07ff07ff},
{0xfff70707,0x07ff07ff},{0xfffff7ff,0x07ff07ff},{0xfffffff7,0x07ff07ff},{0xffffffff,0x07ff07ff},{0xffffff07,0x07ff07ff},{0xffff07ff,0x07ff07ff},{0xff07f707,0x07ff07ff},{0xff07ffff,0x07ff07ff},
{0xff07ff07,0x07ff07ff},{0xff070707,0x07ff07ff},{0x07f7f7ff,0x07ff07ff},{0x07f7fff7,0x07ff07ff},{0x07fff7f7,0x07ff07ff},{0x07fff707,0x07ff07ff},{0x07ffffff,0x07ff07ff},{0x07ff0707,0x07ff07ff},
{0x0707f7ff,0x07ff07ff},{0x0707ff07,0x07ff07ff},{0xf7f7ffff,0x07ff0707},{0xf7ffffff,0x07ff0707},{0xf707ffff,0x07ff0707},{0xfff7fff7,0x07ff0707},{0xfff7ff07,0x07ff0707},{0xfff707ff,0x07ff0707},
{0xfffff7f7,0x07ff0707},{0xffffffff,0x07ff0707},{0xffff07f7,0x07ff0707},{0xff07f7ff,0x07ff0707},{0x07f7ffff,0x07ff0707},{0x07fff7ff,0x07ff0707},{0x07fffff7,0x07ff0707},{0x07ffffff,0x07ff0707},
{0x07ffff07,0x07ff0707},{0xf7f7f7f7,0x0707f7f7},{0xf7f7f707,0x0707f7f7},{0xf7f707f7,0x0707f7f7},{0xf7f70707,0x0707f7f7},{0xf7ffffff,0x0707f7f7},{0xf707f7f7,0x0707f7f7},{0xf707f707,0x0707f7f7},
{0xf70707f7,0x0707f7f7},{0xf7070707,0x0707f7f7},{0xfff7ffff,0x0707f7f7},{0xfffff7ff,0x0707f7f7},{0xfffffff7,0x0707f7f7},{0xffffff07,0x0707f7f7},{0xffff07ff,0x0707f7f7},{0x07f7f7f7,0x0707f7f7},
{0x07f7f707,0x0707f7f7},{0x07f707f7,0x0707f7f7},{0x07f70707,0x0707f7f7},{0x07ffffff,0x0707f7f7},{0x0707f7f7,0x0707f7f7},{0x0707f707,0x0707f7f7},{0x070707f7,0x0707f7f7},{0x07070707,0x0707f7f7},
{0xf7f7ffff,0x0707f7ff},{0xf7f707ff,0x0707f7ff},{0xf7fff7ff,0x0707f7ff},{0xf7fffff7,0x0707f7ff},{0xf7ffff07,0x0707f7ff},{0xf7ff07ff,0x0707f7ff},{0xf7ff0707,0x0707f7ff},{0xfff7ff07,0x0707f7ff},
{0xfff707ff,0x0707f7ff},{0xfffff7ff,0x0707f7ff},{0xffffffff,0x0707f7ff},{0xffff07f7,0x0707f7ff},{0xffff0707,0x0707f7ff},{0xff07f7ff,0x0707f7ff},{0xff07fff7,0x0707f7ff},{0x07f7ffff,0x0707f7ff},
{0x07fff7f7,0x0707f7ff},{0x07fff707,0x0707f7ff},{0x07ffff07,0x0707f7ff},{0x07ff07ff,0x0707f7ff},{0xf7f7f707,0x0707f707},{0xf7f707f7,0x0707f707},{0xf7f70707,0x0707f707},{0xf7fff7f7,0x0707f707},
{0xf7ff07ff,0x0707f707},{0xf707f707,0x0707f707},{0xf70707f7,0x0707f707},{0xf7070707,0x0707f707},{0xfff7ffff,0x0707f707},{0xfffff7ff,0x0707f707},{0xffffff07,0x0707f707},{0xffff07ff,0x0707f707},
{0xff07ffff,0x0707f707},{0x07f7f7f7,0x0707f707},{0x07f7f707,0x0707f707},{0x07f707f7,0x0707f707},{0x07f70707,0x0707f707},{0x07ffffff,0x0707f707},{0x0707f7f7,0x0707f707},{0x0707f707,0x0707f707},
{0x070707f7,0x0707f707},{0x07070707,0x0707f707},{0xf7ff07ff,0x0707fff7},{0xf707ffff,0x0707fff7},{0xfff7f7ff,0x0707fff7},{0xfff7fff7,0x0707fff7},{0xfffff7f7,0x0707fff7},{0xfffffff7,0x0707fff7},
{0xffffffff,0x0707fff7},{0xffff07f7,0x0707fff7},{0xffff0707,0x0707fff7},{0xff07f7ff,0x0707fff7},{0xff07ffff,0x0707fff7},{0xff07ff07,0x0707fff7},{0xff0707f7,0x0707fff7},{0xff0707ff,0x0707fff7},
{0x07f7ffff,0x0707fff7},{0xf7f7ff07,0x0707ffff},{0xf7f707ff,0x0707ffff},{0xf7fff7f7,0x0707ffff},{0xf7fff707,0x0707ffff},{0xf7ffffff,0x0707ffff},{0xf7ff07f7,0x0707ffff},{0xf707ff07,0x0707ffff},
{0xf70707ff,0x0707ffff},{0xfff7f707,0x0707ffff},{0xfff7ffff,0x0707ffff},{0xfffff7ff,0x0707ffff},{0xfffffff7,0x0707ffff},{0xffffffff,0x0707ffff},{0xffffff07,0x0707ffff},{0xffff07ff,0x0707ffff},
{0xff07ffff,0x0707ffff},{0xff070707,0x0707ffff},{0x07f7f7ff,0x0707ffff},{0x07f7fff7,0x0707ffff},{0x07f7ffff,0x0707ffff},{0x07f7ff07,0x0707ffff},{0x07f707ff,0x0707ffff},{0x07fff707,0x0707ffff},
{0x07ffffff,0x0707ffff},{0x07ff07f7,0x0707ffff},{0xf7f7ffff,0x0707ff07},{0xf7fff7ff,0x0707ff07},{0xf7ffff07,0x0707ff07},{0xf7ff0707,0x0707ff07},{0xf707f7ff,0x0707ff07},{0xf707ffff,0x0707ff07},
{0xfff7fff7,0x0707ff07},{0xfff7ff07,0x0707ff07},{0xfff70707,0x0707ff07},{0xfffff707,0x0707ff07},{0xffffffff,0x0707ff07},{0xffffff07,0x0707ff07},{0xffff07f7,0x0707ff07},{0xff07f7f7,0x0707ff07},
{0xff07f707,0x0707ff07},{0x07f7ff07,0x0707ff07},{0x07fff7f7,0x0707ff07},{0x07ffffff,0x0707ff07},{0x07ffff07,0x0707ff07},{0x07ff07ff,0x0707ff07},{0x0707f7ff,0x0707ff07},{0x0707fff7,0x0707ff07},
{0x0707ff07,0x0707ff07},{0xf7f7f7f7,0x070707f7},{0xf7f7f707,0x070707f7},{0xf7f707f7,0x070707f7},{0xf7f70707,0x070707f7},{0xf707f7f7,0x070707f7},{0xf707f707,0x070707f7},{0xf70707f7,0x070707f7},
{0xf7070707,0x070707f7},{0xfffff7ff,0x070707f7},{0xfffffff7,0x070707f7},{0xffffff07,0x070707f7},{0xffff07ff,0x070707f7},{0x07f7f7f7,0x070707f7},{0x07f7f707,0x070707f7},{0x07f707f7,0x070707f7},
{0x07f70707,0x070707f7},{0x07ffffff,0x070707f7},{0x0707f7f7,0x070707f7},{0x0707f707,0x070707f7},{0x070707f7,0x070707f7},{0x07070707,0x070707f7},{0xf7f7ffff,0x070707ff},{0xf7fffff7,0x070707ff},
{0xf7ff07ff,0x070707ff},{0xf707f7ff,0x070707ff},{0xf707ffff,0x070707ff},{0xfff7f7ff,0x070707ff},{0xfffff7f7,0x070707ff},{0xffffffff,0x070707ff},{0xffff0707,0x070707ff},{0xff07f7ff,0x070707ff},
{0xff07ff07,0x070707ff},{0xff0707ff,0x070707ff},{0x07fff7f7,0x070707ff},{0x07ffff07,0x070707ff},{0xf7f7f7f7,0x07070707},{0xf7f7f707,0x07070707},{0xf7f707f7,0x07070707},{0xf7f70707,0x07070707},
{0xf707f7f7,0x07070707},{0xf707f707,0x07070707},{0xf70707f7,0x07070707},{0xf7070707,0x07070707},{0xfffff7ff,0x07070707},{0xfffffff7,0x07070707},{0xffffff07,0x07070707},{0x07f7f7f7,0x07070707},
{0x07f7f707,0x07070707},{0x07f707f7,0x07070707},{0x07f70707,0x07070707},{0x07ffffff,0x07070707},{0x0707f7f7,0x07070707},{0x0707f707,0x07070707},{0x070707f7,0x07070707},{0x07070707,0x07070707},
+782
View File
@@ -0,0 +1,782 @@
// 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_iq_cpu.cpp - a GGUF's low-bit experts on the CPU lane (see ds4_gguf_cpu.hpp): the GLM CPU lane's native
// experts (src/kernels/cpu/native_expert.cpp), whose arithmetic is ggml-cpu's - and for IQ3_XXS / IQ3_S (Maya-S's
// down, Maya-M's gate / up / down) rows of our own, the same numbers bit for bit, faster.
#include "ds4_gguf_cpu.hpp"
// Strata port: the low-bit (IQ) experts have no CPU lane here (they need Maya's native_expert split-base rows); the stub
// branch below answers for them. MXFP4, the source format, has its own CPU rows (ds4_gguf_cpu.cpp).
#undef STRATA_NATIVE_EXPERTS
#if defined(STRATA_NATIVE_EXPERTS)
#include "strata/kernels/cpu/native_expert.hpp" // (only with STRATA_NATIVE_EXPERTS)
#define GGML_COMMON_DECL_CPP
#define GGML_COMMON_IMPL_CPP
#include "ggml-common.h"
#include "ggml-cpu.h"
#include "ggml.h"
#endif
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <mutex>
#include <string>
#include <vector>
#if defined(__x86_64__) || defined(_M_X64)
#define IQ_X86 1
#include <immintrin.h>
#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <cpuid.h>
#endif
#endif
#if defined(IQ_X86) && (defined(__GNUC__) || defined(__clang__))
#define IQ_AVX2 __attribute__((target("avx2,fma")))
#else
#define IQ_AVX2
#endif
namespace strata::ds4::gguf {
#if defined(STRATA_NATIVE_EXPERTS)
namespace kc = strata::dsv41k::cpu;
namespace {
kc::NativeFmt native(const IqCpu& f) { // (the fields the rows read; no lookups)
kc::NativeFmt n;
n.gu_type = f.tg;
n.d_type = f.td;
n.gu_act = f.gu_act;
n.d_act = f.d_act;
n.n_embd = f.n_embd;
n.n_ff = f.n_ff;
n.gu_row = f.gu_row;
n.d_row = f.d_row;
n.up_off = f.gu_row * (size_t) f.n_ff;
n.down_off = 2 * n.up_off;
n.bytes = n.down_off + f.d_row * (size_t) f.n_embd;
n.act_bytes = f.act_bytes;
n.h_bytes = f.h_bytes;
return n;
}
// ---- what this CPU runs: AVX2 + FMA (the OS saving the YMM state), and AVX-512 F / BW + VBMI with BMI2 (the ZMM state)
struct IqCpuIsa {
bool avx2 = false, w512 = false;
};
IqCpuIsa iq_isa() {
IqCpuIsa c;
#if defined(IQ_X86)
unsigned r[4] = {0, 0, 0, 0};
auto cpuid = [&](unsigned leaf, unsigned sub) {
#if defined(_MSC_VER)
int x[4];
__cpuidex(x, (int) leaf, (int) sub);
for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i];
#else
__cpuid_count(leaf, sub, r[0], r[1], r[2], r[3]);
#endif
};
cpuid(0, 0);
if (r[0] < 7) return c;
cpuid(1, 0);
if (!((r[2] >> 12) & 1u) || !((r[2] >> 27) & 1u) || !((r[2] >> 28) & 1u)) return c; // FMA, OSXSAVE, AVX
#if defined(_MSC_VER)
const unsigned long long xcr0 = _xgetbv(0);
#else
unsigned lo = 0, hi = 0;
__asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo;
#endif
if ((xcr0 & 0x6) != 0x6) return c;
cpuid(7, 0);
c.avx2 = (r[1] >> 5) & 1u;
c.w512 = c.avx2 && (xcr0 & 0xE6) == 0xE6 && ((r[1] >> 16) & 1u) && ((r[1] >> 30) & 1u) && ((r[2] >> 1) & 1u) &&
((r[1] >> 8) & 1u); // AVX-512 F, BW, VBMI; BMI2
#endif
return c;
}
const IqCpuIsa& isa() {
static const IqCpuIsa c = iq_isa();
return c;
}
// ---- IQ3_XXS / IQ3_S rows of our own. ggml-cpu's AVX2 dots build each 32-value chunk's grid magnitudes from eight
// scalar table loads and inserts, and redo it for every token; here the grid comes in with one vpgatherdd from the
// same table, the signs are built in registers (the GLM rows' sgn7_vec / sgn_vec), and every token of a call applies
// the decoded chunk. The arithmetic is ggml's to the bit: the same exact int32 lanes per block (lane l: the chunks'
// grid entries l, each times its 2 s + 1), then for each block fma(d_x d_y, lanes, acc) and hsum_float_8 (IQ3_XXS:
// times 0.25) - checked against ggml-cpu's own dot once per type (iq3_check), else ggml's rows are used.
inline float h2f(uint16_t h) { // F16 -> F32, exactly
const uint32_t s = (uint32_t) (h & 0x8000u) << 16, e = (h >> 10) & 0x1fu, m = h & 0x3ffu;
uint32_t b;
if (e == 0) {
const float f = (float) m * 5.9604644775390625e-8f; // m 2^-24 (exact)
std::memcpy(&b, &f, 4);
b |= s;
} else if (e == 31) {
b = s | 0x7f800000u | (m << 13);
} else {
b = s | ((e + 112u) << 23) | (m << 13);
}
float f;
std::memcpy(&f, &b, 4);
return f;
}
inline uint32_t u32(const uint8_t* p) {
uint32_t v;
std::memcpy(&v, p, 4);
return v;
}
#if defined(IQ_X86)
IQ_AVX2 inline float hsum_ggml(__m256 x) { // ggml's hsum_float_8, the same additions in the same order
__m128 r = _mm256_extractf128_ps(x, 1);
r = _mm_add_ps(r, _mm256_castps256_ps128(x));
r = _mm_add_ps(r, _mm_movehl_ps(r, r));
r = _mm_add_ss(r, _mm_movehdup_ps(r));
return _mm_cvtss_f32(r);
}
// IQ2_S / IQ3_S: 32 explicit sign bits -> 32 bytes of -1 / +1 (ggml's bit selector)
IQ_AVX2 inline __m256i sgn32(uint32_t m) {
const __m256i sh = _mm256_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, //
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3);
const __m256i sel = _mm256_set1_epi64x((long long) 0x8040201008040201ull);
const __m256i b = _mm256_and_si256(_mm256_shuffle_epi8(_mm256_set1_epi32((int) m), sh), sel);
return _mm256_or_si256(_mm256_cmpeq_epi8(b, sel), _mm256_set1_epi8(1));
}
// table entries into a vector without the shuffle port (ggml's _mm256_set_epi64x / _epi32 of table loads ends up in
// inserts, one shuffle each; here each entry is a broadcast load and the lanes are put together by dword blends)
IQ_AVX2 inline __m256i bq(const void* p) { return _mm256_castpd_si256(_mm256_broadcast_sd((const double*) p)); }
IQ_AVX2 inline __m256i bd(const void* p) { return _mm256_castps_si256(_mm256_broadcast_ss((const float*) p)); }
IQ_AVX2 inline __m256i tab4(const uint64_t* t, unsigned a, unsigned b, unsigned c, unsigned d) { // qwords t[a] t[b] t[c] t[d]
return _mm256_blend_epi32(_mm256_blend_epi32(bq(t + a), bq(t + b), 0x0C), _mm256_blend_epi32(bq(t + c), bq(t + d), 0xC0),
0xF0);
}
IQ_AVX2 inline __m256i tab8(const uint32_t* t, const unsigned* i) { // dwords t[i[0]] .. t[i[7]]
const __m256i a = _mm256_blend_epi32(bd(t + i[0]), bd(t + i[1]), 0x02), b = _mm256_blend_epi32(bd(t + i[2]), bd(t + i[3]), 0x08);
const __m256i c = _mm256_blend_epi32(bd(t + i[4]), bd(t + i[5]), 0x20), e = _mm256_blend_epi32(bd(t + i[6]), bd(t + i[7]), 0x80);
return _mm256_blend_epi32(_mm256_blend_epi32(a, b, 0x0C), _mm256_blend_epi32(c, e, 0xC0), 0xF0);
}
// the 8 sign bytes (-1 / +1) of each 7-bit sign index with its parity bit: ggml's keven_signs_q2xs, as +-1 bytes
alignas(64) uint64_t g_ks64[128];
void build_ks64() {
for (int i = 0; i < 128; ++i) {
int par = 0;
for (int b = 0; b < 7; ++b) par ^= (i >> b) & 1;
const int s = i | (par << 7);
uint64_t v = 0;
for (int j = 0; j < 8; ++j) v |= (uint64_t) (((s >> j) & 1) ? 0xFFu : 0x01u) << (8 * j);
g_ks64[i] = v;
}
}
IQ_AVX2 inline __m256i sgn7t(uint32_t w) { // a chunk's four 7-bit sign indices (bits 0..27 of w)
return tab4(g_ks64, w & 127u, (w >> 7) & 127u, (w >> 14) & 127u, (w >> 21) & 127u);
}
IQ_AVX2 inline __m256i sc16(int a, int b) { // int16 lanes 0-7 a (values 0-15), 8-15 b (values 16-31)
return _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_set1_epi16((short) a)), _mm_set1_epi16((short) b), 1);
}
bool g_gather18 = false, g_gather21 = false; // the IQ3_XXS / IQ3_S grids by vpgatherdd (own(): if faster here)
// IQ2_XXS's grid entry with its signs applied, for every grid index g and sign index i, at g << 7 | i (256 KB, built on
// first use): one lookup instead of two; the products are then (q8 + 128) x signed grid less 128 x the grid's pair sums
// (vpmaddubsw takes u8 x s8), the same integers as ggml's |grid| x signed q8
alignas(64) uint64_t g_ct2x[256 * 128];
bool g_ct16 = false; // (own(): if faster here)
void build_ct2x() {
for (int g = 0; g < 256; ++g)
for (int i = 0; i < 128; ++i) {
const uint64_t sg = g_ks64[i]; // (+-1 bytes)
uint64_t v = 0;
for (int j = 0; j < 8; ++j) {
const int gb = (int) ((iq2xxs_grid[g] >> (8 * j)) & 255u);
const int sb = ((sg >> (8 * j)) & 255u) == 0xFFu ? -gb : gb;
v |= (uint64_t) (uint8_t) (int8_t) sb << (8 * j);
}
g_ct2x[(size_t) g << 7 | (size_t) i] = v;
}
}
// rows [r0, r1) (out[t][r - r0]) of NT tokens; TY 16 = IQ2_XXS, 22 = IQ2_S, 18 = IQ3_XXS, 21 = IQ3_S. A pair of
// 32-value chunks a step: grid magnitudes g1 / g2, sign vectors s1 / s2 (-1 / +1), scales c1 / c2 - decoded once - then
// every token: q8 times the signs, vpmaddubsw against the grid, vpmaddwd by the scales, into ggml's 8 int32 lanes
template <int TY, int NT>
IQ_AVX2 void iq_rows_avx2(const uint8_t* w, size_t rb, int nb, const block_q8_K* const* y, float* const* out, int r0,
int r1) {
const __m256i sub = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
const bool gat = TY == 18 ? g_gather18 : TY == 21 ? g_gather21 : false;
const bool ct = TY == 16 && g_ct16;
const __m256i k80 = _mm256_set1_epi8((char) 0x80);
constexpr float K = TY == 18 ? 0.25f : TY == 21 ? 1.0f : 0.125f;
constexpr size_t BB = TY == 16 ? sizeof(block_iq2_xxs) : TY == 22 ? sizeof(block_iq2_s) :
TY == 18 ? sizeof(block_iq3_xxs) : sizeof(block_iq3_s);
for (int r = r0; r < r1; ++r) {
const uint8_t* row = w + (size_t) r * rb;
__m256 accf[NT];
for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps();
for (int i = 0; i < nb; ++i) {
const uint8_t* blk = row + (size_t) i * BB;
__m256i sumi[NT];
for (int t = 0; t < NT; ++t) sumi[t] = _mm256_setzero_si256();
uint16_t dh;
std::memcpy(&dh, blk, 2);
for (int ib = 0; ib < QK_K / 32; ib += 2) {
__m256i g1, g2, s1, s2, c1, c2;
if (TY == 16) { // IQ2_XXS: per chunk a word of 4 grid indices, a word of 4 sign indices + the scale
const uint8_t* q = blk + 2 + 8 * ib;
const uint32_t a0 = u32(q), a1 = u32(q + 4), b0 = u32(q + 8), b1 = u32(q + 12);
if (ct) { // (g1 / g2 the signed grids; s1 / s2 their 128 x pair sums)
g1 = tab4(g_ct2x, (a0 & 255u) << 7 | (a1 & 127u), ((a0 >> 8) & 255u) << 7 | ((a1 >> 7) & 127u),
((a0 >> 16) & 255u) << 7 | ((a1 >> 14) & 127u), (a0 >> 24) << 7 | ((a1 >> 21) & 127u));
g2 = tab4(g_ct2x, (b0 & 255u) << 7 | (b1 & 127u), ((b0 >> 8) & 255u) << 7 | ((b1 >> 7) & 127u),
((b0 >> 16) & 255u) << 7 | ((b1 >> 14) & 127u), (b0 >> 24) << 7 | ((b1 >> 21) & 127u));
s1 = _mm256_maddubs_epi16(k80, g1);
s2 = _mm256_maddubs_epi16(k80, g2);
} else {
g1 = tab4(iq2xxs_grid, a0 & 255u, (a0 >> 8) & 255u, (a0 >> 16) & 255u, a0 >> 24);
g2 = tab4(iq2xxs_grid, b0 & 255u, (b0 >> 8) & 255u, (b0 >> 16) & 255u, b0 >> 24);
s1 = sgn7t(a1);
s2 = sgn7t(b1);
}
c1 = _mm256_set1_epi16((short) (2 * (a1 >> 28) + 1));
c2 = _mm256_set1_epi16((short) (2 * (b1 >> 28) + 1));
} else if (TY == 22) { // IQ2_S: 10-bit grid indices (qs | 2 bits of qh), explicit signs, 2 scales a chunk
const uint8_t* qs = blk + 2 + 4 * ib;
const uint8_t* qh = blk + 2 + QK_K / 4;
const uint8_t* sg = blk + 2 + QK_K / 8 + 4 * ib;
const uint8_t* scl = blk + 2 + QK_K / 4 + QK_K / 32;
const unsigned h0 = qh[ib], h1 = qh[ib + 1];
g1 = tab4(iq2s_grid, qs[0] | ((h0 << 8) & 0x300u), qs[1] | ((h0 << 6) & 0x300u), qs[2] | ((h0 << 4) & 0x300u),
qs[3] | ((h0 << 2) & 0x300u));
g2 = tab4(iq2s_grid, qs[4] | ((h1 << 8) & 0x300u), qs[5] | ((h1 << 6) & 0x300u), qs[6] | ((h1 << 4) & 0x300u),
qs[7] | ((h1 << 2) & 0x300u));
s1 = sgn32(u32(sg));
s2 = sgn32(u32(sg + 4));
c1 = sc16(2 * (scl[ib] & 0xf) + 1, 2 * (scl[ib] >> 4) + 1);
c2 = sc16(2 * (scl[ib + 1] & 0xf) + 1, 2 * (scl[ib + 1] >> 4) + 1);
} else if (TY == 18) { // IQ3_XXS: 8 grid indices a chunk, then the chunks' sign / scale words
const uint8_t* q3 = blk + 2 + 8 * ib;
const uint8_t* gas = blk + 2 + QK_K / 4 + 4 * ib;
if (gat) {
g1 = _mm256_i32gather_epi32((const int*) iq3xxs_grid, _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) q3)), 4);
g2 = _mm256_i32gather_epi32((const int*) iq3xxs_grid,
_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) (q3 + 8))), 4);
} else {
unsigned i1[8], i2[8];
for (int k = 0; k < 8; ++k) {
i1[k] = q3[k];
i2[k] = q3[8 + k];
}
g1 = tab8(iq3xxs_grid, i1);
g2 = tab8(iq3xxs_grid, i2);
}
const uint32_t a0 = u32(gas), a1 = u32(gas + 4);
s1 = sgn7t(a0);
s2 = sgn7t(a1);
c1 = _mm256_set1_epi16((short) (2 * (a0 >> 28) + 1));
c2 = _mm256_set1_epi16((short) (2 * (a1 >> 28) + 1));
} else { // IQ3_S: 9-bit grid indices (qs | a bit of qh), explicit signs
const uint8_t* qs = blk + 2 + 8 * ib;
const uint8_t* qh = blk + 2 + QK_K / 4;
const uint8_t* sg = blk + 2 + QK_K / 4 + QK_K / 32 + 4 * ib;
const int sc = blk[2 + QK_K / 4 + QK_K / 32 + QK_K / 8 + ib / 2];
const unsigned h0 = qh[ib], h1 = qh[ib + 1];
if (gat) {
const __m256i hb1 = _mm256_slli_epi32(_mm256_and_si256(_mm256_srlv_epi32(_mm256_set1_epi32((int) h0), sub), _mm256_set1_epi32(1)), 8);
const __m256i hb2 = _mm256_slli_epi32(_mm256_and_si256(_mm256_srlv_epi32(_mm256_set1_epi32((int) h1), sub), _mm256_set1_epi32(1)), 8);
g1 = _mm256_i32gather_epi32((const int*) iq3s_grid,
_mm256_or_si256(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) qs)), hb1), 4);
g2 = _mm256_i32gather_epi32((const int*) iq3s_grid,
_mm256_or_si256(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) (qs + 8))), hb2), 4);
} else {
unsigned i1[8], i2[8];
for (int k = 0; k < 8; ++k) {
i1[k] = qs[k] | (((h0 >> k) & 1u) << 8);
i2[k] = qs[8 + k] | (((h1 >> k) & 1u) << 8);
}
g1 = tab8(iq3s_grid, i1);
g2 = tab8(iq3s_grid, i2);
}
s1 = sgn32(u32(sg));
s2 = sgn32(u32(sg + 4));
c1 = _mm256_set1_epi16((short) (2 * (sc & 0xf) + 1));
c2 = _mm256_set1_epi16((short) (2 * (sc >> 4) + 1));
}
if (ct) {
for (int t = 0; t < NT; ++t) {
const int8_t* q8 = y[t][i].qs + 32 * ib;
const __m256i u1 = _mm256_xor_si256(_mm256_loadu_si256((const __m256i*) q8), k80); // (q8 + 128)
const __m256i u2 = _mm256_xor_si256(_mm256_loadu_si256((const __m256i*) (q8 + 32)), k80);
const __m256i d1 = _mm256_sub_epi16(_mm256_maddubs_epi16(u1, g1), s1);
const __m256i d2 = _mm256_sub_epi16(_mm256_maddubs_epi16(u2, g2), s2);
sumi[t] = _mm256_add_epi32(sumi[t], _mm256_add_epi32(_mm256_madd_epi16(d1, c1), _mm256_madd_epi16(d2, c2)));
}
continue;
}
for (int t = 0; t < NT; ++t) {
const int8_t* q8 = y[t][i].qs + 32 * ib;
const __m256i d1 = _mm256_maddubs_epi16(g1, _mm256_sign_epi8(_mm256_loadu_si256((const __m256i*) q8), s1));
const __m256i d2 = _mm256_maddubs_epi16(g2, _mm256_sign_epi8(_mm256_loadu_si256((const __m256i*) (q8 + 32)), s2));
sumi[t] = _mm256_add_epi32(sumi[t], _mm256_add_epi32(_mm256_madd_epi16(d1, c1), _mm256_madd_epi16(d2, c2)));
}
}
const float dx = h2f(dh);
for (int t = 0; t < NT; ++t)
accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(sumi[t]), accf[t]);
}
for (int t = 0; t < NT; ++t) out[t][r - r0] = K * hsum_ggml(accf[t]);
}
}
// ---- the same rows in 512-bit lanes (AVX-512 BW + VBMI, BMI2: Ice Lake and later Intel, Zen 4 / Zen 5), the GLM
// lane's one-token IQ2_XXS scheme (src/kernels/cpu/iq_avx512_one.cpp) for 3-bit grids: every grid byte is one of 8
// levels, so an entry is four 3-bit codes (a u16) and the grid's codes fit in registers - IQ3_XXS's 256 in 8 zmm,
// IQ3_S's 512 in 16; a block's 64 indices are looked up 32 at a time with two-register word permutes and blends, each
// 64 values' 16 codes spread to their bytes by a word permute, a multishift, an and and a byte shuffle; IQ3_XXS's signs
// come from pdep and a parity fold, IQ3_S's are a mask register's bits. Two chunks a register, folded to ggml's 8
// lanes, then ggml's float steps: the same numbers to the bit (own_check).
#if defined(__GNUC__) || defined(__clang__)
#define IQ_512 __attribute__((target("avx512f,avx512bw,avx512vbmi,bmi2,avx2,fma")))
#else
#define IQ_512
#endif
alignas(64) uint16_t g_code3x[256], g_code3s[512];
bool g_codes_ok = false;
IQ_512 inline uint32_t signs4(uint32_t w) { // ksigns_iq2xs for the four 7-bit fields of w: i | parity(i) << 7
const uint64_t s = _pdep_u64(w & 0x0FFFFFFFu, 0x7F7F7F7Full);
uint64_t p = s ^ ((s >> 4) & 0x0F0F0F0Full);
p ^= (p >> 2) & 0x03030303ull;
p ^= (p >> 1) & 0x01010101ull;
return (uint32_t) (s | ((p & 0x01010101ull) << 7));
}
// each grid entry as four 3-bit level codes; false if a byte is not one of the 8 levels (a grid this file does not know)
bool build_codes3() {
static const int lx[8] = {4, 12, 20, 28, 36, 44, 52, 62}, ls[8] = {1, 3, 5, 7, 9, 11, 13, 15};
auto code = [](uint32_t e, const int* lv) -> int {
int c = 0;
for (int k = 0; k < 4; ++k) {
const int b = (int) ((e >> (8 * k)) & 255u);
int l = -1;
for (int j = 0; j < 8; ++j)
if (lv[j] == b) l = j;
if (l < 0) return -1;
c |= l << (3 * k);
}
return c;
};
for (int i = 0; i < 256; ++i) {
const int c = code(iq3xxs_grid[i], lx);
if (c < 0) return false;
g_code3x[i] = (uint16_t) c;
}
for (int i = 0; i < 512; ++i) {
const int c = code(iq3s_grid[i], ls);
if (c < 0) return false;
g_code3s[i] = (uint16_t) c;
}
return true;
}
IQ_512 inline __m256i fold(__m512i a) { // a block's 16 int32 lanes -> ggml's 8 (lane k + lane k + 8), exact
return _mm256_add_epi32(_mm512_castsi512_si256(a), _mm512_extracti64x4_epi64(a, 1));
}
IQ_512 inline __m512i scales4(int s0, int s1, int s2, int s3) { // int16 lanes 0-7 s0, 8-15 s1, 16-23 s2, 24-31 s3
const __m512i idx = _mm512_set_epi16(3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, //
0, 0, 0, 0, 0, 0, 0, 0);
const uint64_t packed = (uint64_t) (uint16_t) s0 | ((uint64_t) (uint16_t) s1 << 16) |
((uint64_t) (uint16_t) s2 << 32) | ((uint64_t) (uint16_t) s3 << 48);
return _mm512_permutexvar_epi16(idx, _mm512_set1_epi64((long long) packed));
}
// the codes of 32 word indices: 64 entries a register pair, NP pairs, blended by the index's bits 6, 7 (and 8)
template <int NP>
IQ_512 inline __m512i lookup(const __m512i* T, __m512i idx) {
__m512i r[NP];
for (int j = 0; j < NP; ++j) r[j] = _mm512_permutex2var_epi16(T[2 * j], idx, T[2 * j + 1]);
const __mmask32 m6 = _mm512_test_epi16_mask(idx, _mm512_set1_epi16(64));
const __mmask32 m7 = _mm512_test_epi16_mask(idx, _mm512_set1_epi16(128));
__m512i a = _mm512_mask_blend_epi16(m7, _mm512_mask_blend_epi16(m6, r[0], r[1]), _mm512_mask_blend_epi16(m6, r[2], r[3]));
if (NP == 8) {
const __mmask32 m8 = _mm512_test_epi16_mask(idx, _mm512_set1_epi16(256));
const __m512i b = _mm512_mask_blend_epi16(m7, _mm512_mask_blend_epi16(m6, r[NP > 4 ? 4 : 0], r[NP > 5 ? 5 : 0]),
_mm512_mask_blend_epi16(m6, r[NP > 6 ? 6 : 0], r[NP > 7 ? 7 : 0]));
a = _mm512_mask_blend_epi16(m8, a, b);
}
return a;
}
template <int TY, int NT>
IQ_512 void iq3_rows_512(const uint8_t* w, size_t rb, int nb, const block_q8_K* const* y, float* const* out, int r0,
int r1) {
constexpr int NTAB = TY == 18 ? 8 : 16;
constexpr size_t BB = TY == 18 ? sizeof(block_iq3_xxs) : sizeof(block_iq3_s);
__m512i T[NTAB];
for (int k = 0; k < NTAB; ++k)
T[k] = _mm512_load_si512((const void*) ((TY == 18 ? g_code3x : g_code3s) + 32 * k));
// code -> grid byte (IQ3_XXS 4 .. 62, IQ3_S 1 .. 15) in every 128-bit lane; byte b of an output qword <- 3 bits at
// [0, 3, 6, 9] (its first entry's code, word 0) or [32, 35, 38, 41] (the second's, word 2)
const __m512i lut = TY == 18 ? _mm512_set4_epi32(0, 0, 0x3E342C24, 0x1C140C04) : _mm512_set4_epi32(0, 0, 0x0F0D0B09, 0x07050301);
const __m512i ctl = _mm512_set1_epi64(0x2926232009060300LL);
const __m512i seven = _mm512_set1_epi8(7), zero = _mm512_setzero_si512();
__m512i pidx[2]; // a 64-value group h of 32 codes: output qword m <- entries 16 h + 2 m (word 0), + 1 (word 2)
for (int h = 0; h < 2; ++h) {
alignas(64) uint16_t p[32];
for (int m = 0; m < 8; ++m) {
p[4 * m] = p[4 * m + 1] = (uint16_t) (16 * h + 2 * m);
p[4 * m + 2] = p[4 * m + 3] = (uint16_t) (16 * h + 2 * m + 1);
}
pidx[h] = _mm512_load_si512((const void*) p);
}
for (int r = r0; r < r1; ++r) {
const uint8_t* row = w + (size_t) r * rb;
__m256 accf[NT];
for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps();
for (int i = 0; i < nb; ++i) {
const uint8_t* blk = row + (size_t) i * BB;
__m512i codes[2];
if (TY == 18) {
const __m512i q = _mm512_loadu_si512((const void*) (blk + 2));
codes[0] = lookup<4>(T, _mm512_cvtepu8_epi16(_mm512_castsi512_si256(q)));
codes[1] = lookup<4>(T, _mm512_cvtepu8_epi16(_mm512_extracti64x4_epi64(q, 1)));
} else {
const uint8_t* qh = blk + 2 + QK_K / 4;
const __m512i hi = _mm512_set1_epi16(256);
const __m512i ia = _mm512_cvtepu8_epi16(_mm256_loadu_si256((const __m256i*) (blk + 2)));
const __m512i ib = _mm512_cvtepu8_epi16(_mm256_loadu_si256((const __m256i*) (blk + 34)));
// (index k of chunk c: qs[8 c + k] | bit k of qh[c] << 8 - the 32 bits of qh[0..3] are chunks 0..3's)
codes[0] = lookup<8>(T, _mm512_or_si512(ia, _mm512_maskz_mov_epi16((__mmask32) u32(qh), hi)));
codes[1] = lookup<8>(T, _mm512_or_si512(ib, _mm512_maskz_mov_epi16((__mmask32) u32(qh + 4), hi)));
}
__m512i acc[NT];
for (int t = 0; t < NT; ++t) acc[t] = _mm512_setzero_si512();
for (int p = 0; p < 4; ++p) {
const __m512i rep = _mm512_permutexvar_epi16(pidx[p & 1], codes[p >> 1]);
const __m512i g = _mm512_shuffle_epi8(lut, _mm512_and_si512(_mm512_multishift_epi64_epi8(ctl, rep), seven));
uint64_t sm;
int sa, sb;
if (TY == 18) {
const uint8_t* sw = blk + 2 + QK_K / 4 + 8 * p;
const uint32_t wa = u32(sw), wb = u32(sw + 4);
sm = (uint64_t) signs4(wa) | ((uint64_t) signs4(wb) << 32);
sa = 2 * (int) (wa >> 28) + 1;
sb = 2 * (int) (wb >> 28) + 1;
} else {
std::memcpy(&sm, blk + 2 + QK_K / 4 + QK_K / 32 + 8 * p, 8);
const int sc = blk[2 + QK_K / 4 + QK_K / 32 + QK_K / 8 + p];
sa = 2 * (sc & 0xf) + 1;
sb = 2 * (sc >> 4) + 1;
}
const __mmask64 m = _cvtu64_mask64(sm);
const __m512i S = scales4(sa, sa, sb, sb);
for (int t = 0; t < NT; ++t) {
const __m512i yv = _mm512_loadu_si512((const void*) (y[t][i].qs + 64 * p));
const __m512i ys = _mm512_mask_sub_epi8(yv, m, zero, yv);
acc[t] = _mm512_add_epi32(acc[t], _mm512_madd_epi16(_mm512_maddubs_epi16(g, ys), S));
}
}
uint16_t dh;
std::memcpy(&dh, blk, 2);
const float dx = h2f(dh);
for (int t = 0; t < NT; ++t)
accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(fold(acc[t])), accf[t]);
}
for (int t = 0; t < NT; ++t) out[t][r - r0] = (TY == 18 ? 0.25f : 1.0f) * hsum_ggml(accf[t]);
}
}
template <int TY>
void iq_rows_n(const uint8_t* w, size_t rb, int n, const void* const* act, int nt, float* const* out, int r0, int r1) {
static const bool w512 = [] {
const char* v = std::getenv("DS4_IQ_AVX2"); // (=1: the AVX2 rows on an AVX-512 CPU, to compare)
return (TY == 18 || TY == 21) && g_codes_ok && isa().w512 && !(v != nullptr && std::atoi(v) != 0);
}();
const int nb = n / QK_K;
for (int t0 = 0; t0 < nt; t0 += 4) {
const block_q8_K* y[4];
float* o[4];
const int c = nt - t0 < 4 ? nt - t0 : 4;
for (int t = 0; t < c; ++t) {
y[t] = (const block_q8_K*) act[t0 + t];
o[t] = out[t0 + t];
}
if constexpr (TY == 18 || TY == 21) {
if (w512) {
switch (c) {
case 1: iq3_rows_512<TY, 1>(w, rb, nb, y, o, r0, r1); break;
case 2: iq3_rows_512<TY, 2>(w, rb, nb, y, o, r0, r1); break;
case 3: iq3_rows_512<TY, 3>(w, rb, nb, y, o, r0, r1); break;
default: iq3_rows_512<TY, 4>(w, rb, nb, y, o, r0, r1); break;
}
continue;
}
}
switch (c) {
case 1: iq_rows_avx2<TY, 1>(w, rb, nb, y, o, r0, r1); break;
case 2: iq_rows_avx2<TY, 2>(w, rb, nb, y, o, r0, r1); break;
case 3: iq_rows_avx2<TY, 3>(w, rb, nb, y, o, r0, r1); break;
default: iq_rows_avx2<TY, 4>(w, rb, nb, y, o, r0, r1); break;
}
}
}
#endif // IQ_X86
// out[t][r - r0] for the rows of `type` (an own type only)
void own_rows(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 defined(IQ_X86)
if (type == GGML_TYPE_IQ2_XXS) return iq_rows_n<16>(w, rb, n, act, nt, out, r0, r1);
if (type == GGML_TYPE_IQ2_S) return iq_rows_n<22>(w, rb, n, act, nt, out, r0, r1);
if (type == GGML_TYPE_IQ3_XXS) return iq_rows_n<18>(w, rb, n, act, nt, out, r0, r1);
if (type == GGML_TYPE_IQ3_S) return iq_rows_n<21>(w, rb, n, act, nt, out, r0, r1);
#endif
(void) type, (void) w, (void) rb, (void) n, (void) act, (void) nt, (void) out, (void) r0, (void) r1;
}
// our rows against ggml-cpu's dot, bit for bit: random blocks of the type (its F16 scale a small normal value), Q8_K
// activations from ggml's quantizer, 1, 2, 3, 5 and 9 tokens, 13 rows of 8 blocks
bool own_check(int type) {
ggml_cpu_init();
const ggml_type t = (ggml_type) type;
const int n = 2048, rows = 13;
const size_t rb = ggml_row_size(t, n), bb = ggml_type_size(t), ab = ggml_row_size(GGML_TYPE_Q8_K, n);
uint64_t st = 0x9E3779B97F4A7C15ull;
auto next = [&st] {
st ^= st << 13;
st ^= st >> 7;
st ^= st << 17;
return st;
};
std::vector<uint8_t> 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));
std::memcpy(&w[o], &d, sizeof d);
}
const auto* q8 = ggml_get_type_traits_cpu(GGML_TYPE_Q8_K);
const auto dot = ggml_get_type_traits_cpu(t)->vec_dot;
for (int nt : {1, 2, 3, 5, 9}) {
std::vector<uint8_t> a(ab * (size_t) nt);
std::vector<float> x((size_t) n), got((size_t) nt * rows), ref((size_t) nt * rows);
std::vector<const void*> ap((size_t) nt);
std::vector<float*> op((size_t) nt);
for (int k = 0; k < nt; ++k) {
for (auto& v : x) v = ((float) (next() % 2001) - 1000.0f) * 1e-3f;
q8->from_float(x.data(), a.data() + ab * (size_t) k, n);
ap[(size_t) k] = a.data() + ab * (size_t) k;
op[(size_t) k] = got.data() + (size_t) k * rows;
}
own_rows(type, w.data(), rb, n, ap.data(), nt, op.data(), 0, rows);
for (int k = 0; k < nt; ++k)
for (int r = 0; r < rows; ++r) dot(n, &ref[(size_t) k * rows + r], 0, w.data() + (size_t) r * rb, 0, ap[(size_t) k], 0, 1);
if (std::memcmp(got.data(), ref.data(), got.size() * sizeof(float)) != 0) return false;
}
return true;
}
// the time (us, best of 5 rounds) of 32 rows of 16 blocks of the type against one token: ours with the IQ3 grids as
// broadcasts + blends (variant 1) or by vpgatherdd (2), or the native lane's rows (0: the GLM lane's / ggml-cpu's)
double time_variant(int type, int variant) {
const ggml_type t = (ggml_type) type;
const int n = 4096, rows = 32;
const size_t rb = ggml_row_size(t, n), bb = ggml_type_size(t), ab = ggml_row_size(GGML_TYPE_Q8_K, n);
std::vector<uint8_t> w(rb * rows), a(ab);
uint32_t s = 12345u;
for (auto& b : w) b = (uint8_t) ((s = s * 1664525u + 1013904223u) >> 24);
for (size_t o = 0; o < w.size(); o += bb) {
const ggml_fp16_t d = ggml_fp32_to_fp16(0.003f);
std::memcpy(&w[o], &d, sizeof d);
}
std::vector<float> x((size_t) n), y((size_t) rows);
for (auto& v : x) v = (float) ((int) ((s = s * 1664525u + 1013904223u) >> 16) - 32768) / 32768.0f;
ggml_get_type_traits_cpu(GGML_TYPE_Q8_K)->from_float(x.data(), a.data(), n);
const void* ap[1] = {a.data()};
float* yp[1] = {y.data()};
kc::NativeFmt nf; // (the native rows timed as a gate / up pair of the same rows: 2 x rows dots, as ours below)
std::string err;
if (variant == 0 && !kc::native_fmt(type, type, n, QK_K, nf, err)) return 1e30;
bool* gflag = type == GGML_TYPE_IQ3_XXS ? &g_gather18 : type == GGML_TYPE_IQ3_S ? &g_gather21 :
type == GGML_TYPE_IQ2_XXS ? &g_ct16 : nullptr;
const bool keep = gflag != nullptr && *gflag;
if (gflag != nullptr) *gflag = variant >= 2;
double best = 1e30;
for (int round = 0; round < 6; ++round) {
const auto t0 = std::chrono::steady_clock::now();
for (int rep = 0; rep < 4; ++rep) {
if (variant == 0) {
kc::native_gu_rows_split(nf, w.data(), w.data(), ap, 1, yp, 0, rows, std::numeric_limits<float>::infinity());
} else {
own_rows(type, w.data(), rb, n, ap, 1, yp, 0, rows);
own_rows(type, w.data(), rb, n, ap, 1, yp, 0, rows);
}
}
const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
if (round > 0) best = std::min(best, us);
}
if (gflag != nullptr) *gflag = keep;
return best;
}
// our rows for this type, here: IQ3_XXS / IQ3_S on AVX2 or AVX-512 VBMI, IQ2_XXS / IQ2_S on AVX2 - checked once
// against ggml-cpu's dot (each variant), then the fastest of ours and the native lane's measured on this CPU (they
// give the same bits, so the choice changes no answer). DS4_IQ_OWN=0: the native lane's rows; =1: ours without
// measuring (DS4_IQ_GATHER=1: the IQ3 grids by vpgatherdd); DS4_IQ_AVX2=1: our AVX2 rows on an AVX-512 CPU too.
bool own(int type) {
#if defined(IQ_X86)
int k;
switch (type) {
case GGML_TYPE_IQ3_XXS: k = 0; break;
case GGML_TYPE_IQ3_S: k = 1; break;
case GGML_TYPE_IQ2_XXS: k = 2; break;
case GGML_TYPE_IQ2_S: k = 3; break;
default: return false;
}
static int mode = -1; // DS4_IQ_OWN: -1 measured, 0 never, 1 always
static bool force_avx2 = false, force_gather = false;
static const bool allowed = [] {
const char* v = std::getenv("DS4_IQ_OWN");
mode = v == nullptr ? -1 : std::atoi(v) != 0 ? 1 : 0;
const char* a2 = std::getenv("DS4_IQ_AVX2");
force_avx2 = a2 != nullptr && std::atoi(a2) != 0;
const char* gt = std::getenv("DS4_IQ_GATHER");
force_gather = gt != nullptr && std::atoi(gt) != 0;
g_codes_ok = build_codes3(); // (the 512-bit rows' tables; without them those rows are not used)
build_ks64();
build_ct2x();
return mode != 0 && isa().avx2;
}();
// (IQ2 on an AVX-512 CPU: the GLM lane's AVX-512 rows serve them, unless DS4_IQ_AVX2)
if (!allowed || (k >= 2 && isa().w512 && !force_avx2)) return false;
static std::once_flag once[4];
static bool ok[4];
std::call_once(once[k], [&] {
bool* gflag = k == 0 ? &g_gather18 : k == 1 ? &g_gather21 : k == 2 ? &g_ct16 : nullptr; // (the second form)
bool good = own_check(type); // (the blend form; the 512-bit rows where they serve)
bool good_g = false;
if (gflag != nullptr) {
*gflag = true;
good_g = own_check(type);
*gflag = false;
}
if (mode == 1) {
if (gflag != nullptr) *gflag = force_gather && good_g;
ok[k] = good || (force_gather && good_g);
return;
}
// the variants timed in turns, the best of each kept (other work on the machine - the load's read-ahead, the
// prompt - then hits them alike), and ours taken only when clearly faster (10 %): the choice changes no answer,
// a wrong one costs time (Uranus' Golden Cove: one-shot timings 30-80 % apart run to run, the choice flipping)
double tn = 1e30, tb = 1e30, tg = 1e30;
for (int it = 0; it < 5; ++it) {
tn = std::min(tn, time_variant(type, 0));
if (good) tb = std::min(tb, time_variant(type, 1));
if (good_g) tg = std::min(tg, time_variant(type, 2));
}
if (gflag != nullptr) *gflag = tg < tb;
ok[k] = std::min(tb, tg) < 0.9 * tn;
if (std::getenv("DS4_IQ_VERBOSE") != nullptr)
std::fprintf(stderr, "ds4: CPU lane %s rows: native %.0f us, ours %.0f us%s -> %s\n", ggml_type_name((ggml_type) type),
tn, tb, gflag != nullptr ? (std::string(" (second form: gather / one table ") + std::to_string((int) tg) + " us)").c_str() : "",
ok[k] ? (gflag != nullptr && *gflag ? "ours (second form)" : "ours") : "native");
});
return ok[k];
#else
(void) type;
return false;
#endif
}
} // namespace
bool iq_cpu_fmt(int tg, int td, int n_embd, int n_ff, IqCpu& f, std::string& err) {
kc::NativeFmt n;
if (!kc::native_fmt(tg, td, n_embd, n_ff, n, err)) return false;
f.tg = tg;
f.td = td;
f.n_embd = n_embd;
f.n_ff = n_ff;
f.gu_act = n.gu_act;
f.d_act = n.d_act;
f.gu_row = n.gu_row;
f.d_row = n.d_row;
f.act_bytes = n.act_bytes;
f.h_bytes = n.h_bytes;
return true;
}
void iq_cpu_quant(int act, const float* x, int k, void* dst) {
kc::NativeFmt n;
n.gu_act = act;
n.n_embd = k;
kc::native_quant_act(n, x, dst);
}
void iq_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) {
if (r1 > r0 && own(f.tg)) { // (native_gu_rows_split's epilogue, on the same values)
const int nr = r1 - r0;
thread_local std::vector<float> buf;
thread_local std::vector<float*> go, uo;
buf.resize((size_t) 2 * nt * nr);
go.resize((size_t) nt);
uo.resize((size_t) nt);
for (int t = 0; t < nt; ++t) {
go[(size_t) t] = buf.data() + (size_t) t * nr;
uo[(size_t) t] = buf.data() + (size_t) (nt + t) * nr;
}
own_rows(f.tg, gate, f.gu_row, f.n_embd, act, nt, go.data(), r0, r1);
own_rows(f.tg, up, f.gu_row, f.n_embd, act, nt, uo.data(), r0, r1);
for (int t = 0; t < nt; ++t)
for (int r = 0; r < nr; ++r) {
float g = go[(size_t) t][r], u = uo[(size_t) t][r];
if (limit > 0.0f) {
g = std::fmin(g, limit);
u = std::fmin(std::fmax(u, -limit), limit);
}
ff[t][r0 + r] = (g / (1.f + std::exp(-g))) * u;
}
return;
}
kc::native_gu_rows_split(native(f), gate, up, act, nt, ff, r0, r1,
limit > 0.0f ? limit : std::numeric_limits<float>::infinity());
}
void iq_cpu_down(const IqCpu& f, const uint8_t* down, const void* const* hq, int nt, float* const* out, int r0, int r1) {
if (r1 > r0 && own(f.td)) {
thread_local std::vector<float*> o;
o.resize((size_t) nt);
for (int t = 0; t < nt; ++t) o[(size_t) t] = out[t] + r0;
own_rows(f.td, down, f.d_row, f.n_ff, hq, nt, o.data(), r0, r1);
return;
}
kc::native_down_rows_split(native(f), down, hq, nt, out, r0, r1);
}
bool iq_cpu_own_rows(int type) { return own(type); }
#else
// (no ggml-cpu lane for the low-bit types here; the trellis types have their own: ds4_tq_cpu.cpp)
bool iq_cpu_fmt(int tg, int td, int n_embd, int n_ff, IqCpu& f, std::string& err) {
if (tq_cpu_type(tg) && tq_cpu_type(td)) return tq_cpu_fmt(tg, td, n_embd, n_ff, f, err);
if (gg_cpu_type(tg) && gg_cpu_type(td)) return gg_cpu_fmt(tg, td, n_embd, n_ff, f, err);
err = "this build has no ggml-cpu (STRATA_NATIVE_EXPERTS=OFF): the low-bit experts CPU lane is not in it";
return false;
}
void iq_cpu_quant(int act, const float* x, int k, void* dst) {
if (act == tq_cpu_act()) tq_cpu_quant(x, k, dst);
else gg_cpu_quant(act, x, k, dst);
}
void iq_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) {
if (tq_cpu_type(f.tg)) tq_cpu_gate_up(f, gate, up, act, nt, ff, r0, r1, limit);
else gg_cpu_gate_up(f, gate, up, act, nt, ff, r0, r1, limit);
}
void iq_cpu_down(const IqCpu& f, const uint8_t* down, const void* const* hq, int nt, float* const* out, int r0, int r1) {
if (tq_cpu_type(f.td)) tq_cpu_down(f, down, hq, nt, out, r0, r1);
else gg_cpu_down(f, down, hq, nt, out, r0, r1);
}
bool iq_cpu_own_rows(int) { return false; }
#endif
} // namespace strata::ds4::gguf
+274
View File
@@ -0,0 +1,274 @@
// Strata. The prompt sets of ds4_iq.cu on the gfx12 (RDNA4, R9700 = gfx1201) matrix cores: v_wmma_f32_16x16x16_f16, F16 operands,
// F32 accumulation. Included by ds4_iq.cu inside its anonymous namespace (it uses its Ty, decode<>, load_tab<>, swiglu, SetArgs).
//
// The idea is the CUDA prompt tiles' (set_h16ws_kernel on f-dsv41-cuk-int2): a block-tile of the expert's rows x weight rows, K in
// steps of 64; each i-quant block is decoded ONCE into shared memory as F16 (code * the sub-block's scale: the product is exact up
// to the F16 rounding of the scale and the product) and then shared by every row of the tile; x as F16 rows next to it, both
// double-buffered, one barrier a step. The F32 FMA tile of today (set_kernel) decodes the weights once per 64 rows and does
// scalar FMAs. Default ON for gfx12, STRATA_DS4_HIPK=0 switches it off (gfx12 only, the types below, experts of more than 16 rows).
#pragma once
#if defined(STRATA_USE_HIP)
namespace hipk {
constexpr int kStH = 72; // halves a shared row: 64 + 8 (the pad spreads the banks; rows stay 16-byte aligned)
using hv2 = _Float16 __attribute__((ext_vector_type(2)));
using hv8 = _Float16 __attribute__((ext_vector_type(8)));
using fv8 = float __attribute__((ext_vector_type(8)));
template <int T>
constexpr bool kTypes = T == kIQ2_XXS || T == kIQ2_XS || T == kIQ2_S || T == kIQ3_XXS || T == kIQ3_S || T == kIQ4_XS ||
T == kIQ1_S || T == kIQ1_M || T == kIQ4_NL;
__device__ __forceinline__ fv8 wmma16(hv8 a, hv8 b, fv8 c) {
#if defined(__gfx1200__) || defined(__gfx1201__)
return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);
#else
return c;
#endif
}
__device__ __forceinline__ uint32_t as_u32(hv2 v) { return __builtin_bit_cast(uint32_t, v); }
__device__ __forceinline__ hv2 as_hv2(uint32_t v) { return __builtin_bit_cast(hv2, v); }
// 4 int8 codes (a word) -> 4 halves times the scale: 1024 + (code + 128) is exact in a half's mantissa, less 1152
__device__ __forceinline__ uint2 codes4(int w, hv2 sc) {
const uint32_t u = (uint32_t) w ^ 0x80808080u;
const uint32_t lo = __byte_perm(u, 0x64646464u, 0x5140), hi = __byte_perm(u, 0x64646464u, 0x5342);
const hv2 m = {(_Float16) 1152.0f, (_Float16) 1152.0f};
const hv2 a = (as_hv2(lo) - m) * sc, b = (as_hv2(hi) - m) * sc;
return make_uint2(as_u32(a), as_u32(b));
}
// BM rows x BN weight rows (a matrix: gate and up: two) per block, 8 waves WM x WN, each wave (BM/WM) x (BN/WN)
template <int T, bool GU, int BM, int BN, int WM, int WN>
__global__ void __launch_bounds__(256) set_kernel(const SetArgs a, int dbg) {
static_assert(WM * WN == 8, "8 waves");
constexpr int NM = GU ? 2 : 1, MT = BM / WM / 16, NT = BN / WN / 16;
static_assert(MT >= 1 && NT >= 1 && MT * WM * 16 == BM && NT * WN * 16 == BN, "wave tiling");
__shared__ uint32_t tab[Ty<T>::TAB > 0 ? Ty<T>::TAB : 1];
__shared__ int srow[BM];
__shared__ __align__(16) _Float16 xs[2][BM][kStH];
__shared__ __align__(16) _Float16 ws[2][NM][BN][kStH];
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)
load_tab<T>(tab);
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 = GU ? a.n_embd : a.n_ff;
const size_t rb = row_bytes_t<T>(K);
const int tid = (int) threadIdx.x, warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4;
if (tid < BM) srow[tid] = GU ? a.idx[r0 + min(tid, nr - 1)] : r0 + min(tid, nr - 1);
__syncthreads();
const int nst = K / 64;
// a step's operands are fetched and decoded into registers (the global loads and the codebook's lookups) while the matrix
// cores work on the step before, and written to shared memory after them
constexpr int NI = (NM * BN * 2 + 255) / 256; // weight items a thread
constexpr int NX = GU ? (BM * 16 + 255) / 256 : (BM * 8 + 255) / 256; // row chunks a thread
struct Regs {
int q[NI][8];
_Float16 sc0[NI], sc1[NI];
float4 xv[GU ? NX : 1];
uint4 xu[GU ? 1 : NX];
};
auto fetch = [&](int s, Regs& R) {
#pragma unroll
for (int ii = 0; ii < NI; ++ii) {
const int it = tid + ii * 256;
if (it < NM * BN * 2) {
const int kbl = it & 1, col = (it >> 1) % BN, mat = it / (2 * BN);
Sub sb;
if (dbg & 2) { for (int w = 0; w < 8; ++w) sb.q[w] = tid + w; sb.d = 1.0f; sb.s0 = sb.s1 = 1; } else
decode<T>(blob + a.tr[GU ? mat : 2] + (size_t) (c0 + col) * rb, s * 2 + kbl, tab, sb);
#pragma unroll
for (int w = 0; w < 8; ++w) R.q[ii][w] = sb.q[w];
R.sc0[ii] = (_Float16) (sb.d * (float) sb.s0);
R.sc1[ii] = (_Float16) (sb.d * (float) sb.s1);
}
}
#pragma unroll
for (int xi = 0; xi < NX; ++xi) {
const int c = tid + xi * 256;
if constexpr (GU) {
if (c < BM * 16) {
const int row = c >> 4, ch = c & 15;
R.xv[xi] = *(const float4*) (a.xf + (size_t) srow[row] * a.ldx + (size_t) s * 64 + ch * 4);
}
} else {
if (c < BM * 8) {
const int row = c >> 3, ch = c & 7;
R.xu[xi] = *(const uint4*) (a.xh + (size_t) srow[row] * a.ldx + (size_t) s * 64 + ch * 8);
}
}
}
};
auto store = [&](const Regs& R, int b) {
#pragma unroll
for (int ii = 0; ii < NI; ++ii) {
const int it = tid + ii * 256;
if (it < NM * BN * 2) {
const int kbl = it & 1, col = (it >> 1) % BN, mat = it / (2 * BN);
const hv2 h0 = {R.sc0[ii], R.sc0[ii]}, h1 = {R.sc1[ii], R.sc1[ii]};
uint2* dst = (uint2*) &ws[b][mat][col][kbl * 32]; // (values 4 w .. 4 w + 3 of the half at dst[w], 16 + 4 w .. at dst[4 + w])
#pragma unroll
for (int w = 0; w < 4; ++w) {
dst[w] = codes4(R.q[ii][w], h0);
dst[4 + w] = codes4(R.q[ii][4 + w], h1);
}
}
}
#pragma unroll
for (int xi = 0; xi < NX; ++xi) {
const int c = tid + xi * 256;
if constexpr (GU) {
if (c < BM * 16) {
const int row = c >> 4, ch = c & 15;
const float4 v = R.xv[xi];
const hv2 p = {(_Float16) v.x, (_Float16) v.y}, q = {(_Float16) v.z, (_Float16) v.w};
*(uint2*) &xs[b][row][ch * 4] = make_uint2(as_u32(p), as_u32(q));
}
} else {
if (c < BM * 8) {
const int row = c >> 3, ch = c & 7;
*(uint4*) &xs[b][row][ch * 8] = R.xu[xi];
}
}
}
};
const int wm = warp / WN, wn = warp % WN;
fv8 acc[NM][MT][NT];
#pragma unroll
for (int m = 0; m < NM; ++m)
#pragma unroll
for (int i = 0; i < MT; ++i)
#pragma unroll
for (int j = 0; j < NT; ++j) acc[m][i][j] = fv8{0, 0, 0, 0, 0, 0, 0, 0};
// read-ahead: the first and last byte of the weights' block and a word of the rows' line of a step PF steps on, summed into a
// value that is never used (the loads only warm the caches; their latency is not waited for until the end)
int touched = 0;
auto touch = [&](int s) {
if (dbg & 4) return;
#pragma unroll
for (int ii = 0; ii < NI; ++ii) {
const int it = tid + ii * 256;
if (it < NM * BN * 2) {
const int col = (it >> 1) % BN, mat = it / (2 * BN);
const uint8_t* p = blob + a.tr[GU ? mat : 2] + (size_t) (c0 + col) * rb + (size_t) ((s * 2) >> 3) * Ty<T>::B;
touched += p[0] + p[Ty<T>::B - 1];
}
}
if constexpr (GU) {
for (int c = tid; c < BM * 2; c += 256) touched += (int) a.xf[(size_t) srow[c >> 1] * a.ldx + (size_t) s * 64 + (c & 1) * 32];
} else {
for (int c = tid; c < BM * 2; c += 256) touched += (int) a.xh[(size_t) srow[c >> 1] * a.ldx + (size_t) s * 64 + (c & 1) * 32];
}
};
constexpr int PF = 4;
for (int s = 1; s <= PF && s < nst; ++s) touch(s + 1 < nst ? s + 1 : s);
{
Regs R0;
fetch(0, R0);
store(R0, 0);
}
__syncthreads();
for (int s = 0; s < nst; ++s) {
const int b = s & 1;
Regs R;
if (s + 1 < nst) fetch(s + 1, R);
if (s + 1 + PF < nst) touch(s + 1 + PF);
#pragma unroll
for (int kk = 0; kk < 4; ++kk) {
hv8 af[MT];
#pragma unroll
for (int i = 0; i < MT; ++i) af[i] = *(const hv8*) &xs[b][wm * (16 * MT) + i * 16 + l16][kk * 16 + hi * 8];
#pragma unroll
for (int m = 0; m < NM; ++m)
#pragma unroll
for (int j = 0; j < NT; ++j) {
const hv8 bf = *(const hv8*) &ws[b][m][wn * (16 * NT) + j * 16 + l16][kk * 16 + hi * 8];
#pragma unroll
for (int i = 0; i < MT; ++i)
if (!(dbg & 1) && wm * (16 * MT) + i * 16 < nr) acc[m][i][j] = wmma16(af[i], bf, acc[m][i][j]); // (a tile past the rows: skipped, uniform)
}
}
if (s + 1 < nst) store(R, b ^ 1);
__syncthreads();
}
if (touched == 0x7fffffff && tid == 12345) a.y[0] = 0.0f;
// D[row = 8 hi + i][col = l16] of every tile
#pragma unroll
for (int i = 0; i < MT; ++i)
#pragma unroll
for (int q = 0; q < 8; ++q) {
const int row = wm * (16 * MT) + i * 16 + 8 * hi + q;
if (row >= nr) continue;
const size_t lr = (size_t) (r0 + row);
#pragma unroll
for (int j = 0; j < NT; ++j) {
const int col = c0 + wn * (16 * NT) + j * 16 + l16;
if (GU) a.h[lr * a.ldo + col] = __half_as_ushort(__float2half_rn(swiglu(acc[0][i][j][q], acc[1][i][j][q], a.limit)));
else a.y[lr * a.ldo + col] = acc[0][i][j][q];
}
}
}
#include "ds4_iq_hip_r.inc"
inline bool ok_device() { // gfx12 unless STRATA_DS4_HIPK=0
static std::atomic<int> state[16];
int dev = 0;
cudaGetDevice(&dev);
if (dev < 0 || dev >= 16) return false;
int v = state[dev].load(std::memory_order_relaxed);
if (v == 0) {
cudaDeviceProp prop{};
const bool gfx12 = cudaGetDeviceProperties(&prop, dev) == cudaSuccess && std::strncmp(prop.gcnArchName, "gfx12", 5) == 0;
const char* e = std::getenv("STRATA_DS4_HIPK");
v = gfx12 && !(e != nullptr && e[0] == '0') ? 1 : 2; // (on by default on gfx12; STRATA_DS4_HIPK=0 off)
state[dev].store(v, std::memory_order_relaxed);
}
return v == 1;
}
template <int T, bool GU, int BM, int BN, int WM, int WN>
inline bool run(const SetArgs& a, cudaStream_t s) {
const int N = GU ? a.n_ff : a.n_embd;
const dim3 grid((unsigned) ((a.max_rows + BM - 1) / BM), (unsigned) (N / BN), (unsigned) a.n_exp);
static const int dbg = std::getenv("HIPK_DBG") ? std::atoi(std::getenv("HIPK_DBG")) : 0;
set_kernel<T, GU, BM, BN, WM, WN><<<grid, 256, 0, s>>>(a, dbg);
return cudaPeekAtLastError() == cudaSuccess;
}
// false: not taken (the caller's tiles do it)
template <int T, bool GU>
inline bool launch(const SetArgs& a, cudaStream_t s) {
if constexpr (!kTypes<T>) {
return false;
} else {
if (!ok_device() || a.max_rows <= 16) return false;
const int K = GU ? a.n_embd : a.n_ff, N = GU ? a.n_ff : a.n_embd;
if (K % 256 != 0 || N % 64 != 0 || a.ldx % 8 != 0 || a.ldo % 2 != 0) return false;
if (((uintptr_t) (GU ? (const void*) a.xf : (const void*) a.xh) & 15) != 0) return false;
static const int var = std::getenv("STRATA_DS4_HIPK") ? std::atoi(std::getenv("STRATA_DS4_HIPK")) : 0;
if (var != 2) { // 2: the shared-memory weights kernel
static const int cfg = std::getenv("HIPK_CFG") ? std::atoi(std::getenv("HIPK_CFG")) : 0;
if (cfg == 1 && a.max_rows <= 32) return runr<T, GU, 32, 4, 1>(a, s);
if (cfg == 2 && a.max_rows <= 32) return runr<T, GU, 32, 8, 1>(a, s);
if (cfg == 3 && a.max_rows <= 32) return runr<T, GU, 32, 2, 2>(a, s);
if (cfg == 4 && a.max_rows <= 32) return runr<T, GU, 32, 8, 2>(a, s);
if (cfg == 5 && a.max_rows <= 32) return runr<T, GU, 32, 2, 1>(a, s);
if (a.max_rows <= 32) return runr<T, GU, 32, 4, 2>(a, s);
if (a.max_rows <= 64) return runr<T, GU, 64, 4, 2>(a, s);
return runr<T, GU, 128, 8, 1>(a, s);
}
if (a.max_rows <= 32) return run<T, GU, 32, 64, 2, 4>(a, s);
if (a.max_rows <= 64) return run<T, GU, 64, 64, 2, 4>(a, s);
if constexpr (GU) return run<T, GU, 128, 32, 4, 2>(a, s);
else return run<T, GU, 128, 64, 4, 2>(a, s);
}
}
} // namespace hipk
#endif
+177
View File
@@ -0,0 +1,177 @@
// Strata. Part of ds4_iq_hip.inc (included from it): the weights straight into the matrix cores' registers.
// One lane of the B operand of a 16x16x16 step holds 8 consecutive k of one weight row: exactly one 8-value group of a 32-value
// sub-block of an i-quant block (the grid entry, its signs). grp_dec decodes that group alone: 8 int8 codes (two words) and the
// scale (weight = scale * code), so a wave needs no shared memory for the weights and no barrier: every wave decodes its own
// columns once and uses them for every row of the tile. kb: the 32-value sub-block of the row, p: its group (0..3).
// The decode is in two halves so that the loads of a k-step can be issued one k-step ahead of its use: grp_load fetches the
// group raw bytes into registers (Raw), grp_dec turns them into codes and scale (the codebook lookups, the signs).
__device__ __forceinline__ float hf(uint32_t h) { return __half2float(__ushort_as_half((uint16_t) h)); }
#include "ds4_iq_hip_s.inc"
constexpr int kKC = 64; // K a step: two sub-blocks
// BM rows (MT tiles of 16) x BN = NW 16 NTW weight rows per block; NW waves, each NTW column tiles of 16 and every row tile
template <int T, bool GU, int BM, int NW, int NTW>
__global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg) {
constexpr int NM = GU ? 2 : 1, MT = BM / 16, BN = NW * 16 * NTW, NTH = NW * 32;
static_assert(BM % 16 == 0, "row tiles");
__shared__ uint32_t tab[Ty<T>::TAB > 0 ? Ty<T>::TAB : 1];
__shared__ int srow[BM];
__shared__ __align__(16) _Float16 xs[2][BM][kStH];
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)
load_tab<T>(tab);
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 = GU ? a.n_embd : a.n_ff;
const size_t rb = row_bytes_t<T>(K);
const int tid = (int) threadIdx.x, warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4;
for (int i = tid; i < BM; i += NTH) srow[i] = GU ? a.idx[r0 + min(i, nr - 1)] : r0 + min(i, nr - 1);
__syncthreads();
const int nst = K / kKC;
// the weight rows of this lane column tiles
const uint8_t* wrow[NM][NTW];
#pragma unroll
for (int m = 0; m < NM; ++m)
#pragma unroll
for (int j = 0; j < NTW; ++j)
wrow[m][j] = blob + a.tr[GU ? m : 2] + (size_t) ((c0 + warp * (16 * NTW) + j * 16 + l16)) * rb;
constexpr int NX = GU ? (BM * 16 + NTH - 1) / NTH : (BM * 8 + NTH - 1) / NTH;
struct XR {
float4 f[GU ? NX : 1];
uint4 u[GU ? 1 : NX];
};
auto fetchx = [&](int s, XR& R) {
#pragma unroll
for (int xi = 0; xi < NX; ++xi) {
const int c = tid + xi * NTH;
if constexpr (GU) {
if (c < BM * 16) {
const int row = c >> 4, ch = c & 15;
R.f[xi] = *(const float4*) (a.xf + (size_t) srow[row] * a.ldx + (size_t) s * kKC + ch * 4);
}
} else {
if (c < BM * 8) {
const int row = c >> 3, ch = c & 7;
R.u[xi] = *(const uint4*) (a.xh + (size_t) srow[row] * a.ldx + (size_t) s * kKC + ch * 8);
}
}
}
};
auto storex = [&](const XR& R, int b) {
#pragma unroll
for (int xi = 0; xi < NX; ++xi) {
const int c = tid + xi * NTH;
if constexpr (GU) {
if (c < BM * 16) {
const int row = c >> 4, ch = c & 15;
const float4 v = R.f[xi];
const hv2 p = {(_Float16) v.x, (_Float16) v.y}, q = {(_Float16) v.z, (_Float16) v.w};
*(uint2*) &xs[b][row][ch * 4] = make_uint2(as_u32(p), as_u32(q));
}
} else {
if (c < BM * 8) {
const int row = c >> 3, ch = c & 7;
*(uint4*) &xs[b][row][ch * 8] = R.u[xi];
}
}
}
};
fv8 acc[NM][MT][NTW];
#pragma unroll
for (int m = 0; m < NM; ++m)
#pragma unroll
for (int i = 0; i < MT; ++i)
#pragma unroll
for (int j = 0; j < NTW; ++j) acc[m][i][j] = fv8{0, 0, 0, 0, 0, 0, 0, 0};
{
XR R0;
fetchx(0, R0);
storex(R0, 0);
}
// the weights of a step (64 values) are loaded one step ahead: two sets of registers, the step loop unrolled by two
SRaw sr0[NM][NTW], sr1[NM][NTW];
auto load_stage = [&](SRaw (&dst)[NM][NTW], int s) {
#pragma unroll
for (int m = 0; m < NM; ++m)
#pragma unroll
for (int j = 0; j < NTW; ++j) stage_load<T>(wrow[m][j], s, hi, dst[m][j]);
};
auto do_stage = [&](int s, SRaw (&cur)[NM][NTW], SRaw (&nxt)[NM][NTW]) {
const int b = s & 1;
XR R;
if (s + 1 < nst) {
fetchx(s + 1, R);
load_stage(nxt, s + 1);
}
hv8 bf[NM][NTW];
auto step = [&](auto tt) {
constexpr int t = decltype(tt)::value;
constexpr int sub = t >> 1, ks = t & 1;
#pragma unroll
for (int m = 0; m < NM; ++m)
#pragma unroll
for (int j = 0; j < NTW; ++j) {
int c0_, c1_;
float sc;
step_dec<T, t>(cur[m][j], s, hi, tab, c0_, c1_, sc);
const hv2 h = {(_Float16) sc, (_Float16) sc};
const uint2 u0 = codes4(c0_, h), u1 = codes4(c1_, h);
bf[m][j] = __builtin_bit_cast(hv8, make_uint4(u0.x, u0.y, u1.x, u1.y));
}
const int kcol = sub * 32 + ks * 16 + hi * 8;
#pragma unroll
for (int i = 0; i < MT; ++i) {
if (i * 16 < nr) { // (a tile past the rows: skipped, uniform)
const hv8 af = *(const hv8*) &xs[b][i * 16 + l16][kcol];
#pragma unroll
for (int m = 0; m < NM; ++m)
#pragma unroll
for (int j = 0; j < NTW; ++j) acc[m][i][j] = wmma16(af, bf[m][j], acc[m][i][j]);
}
}
};
step(std::integral_constant<int, 0>{});
step(std::integral_constant<int, 1>{});
step(std::integral_constant<int, 2>{});
step(std::integral_constant<int, 3>{});
if (s + 1 < nst) storex(R, b ^ 1);
__syncthreads();
};
load_stage(sr0, 0);
__syncthreads();
for (int s = 0; s < nst; s += 2) { // (nst is a multiple of 4)
do_stage(s, sr0, sr1);
do_stage(s + 1, sr1, sr0);
}
#pragma unroll
for (int i = 0; i < MT; ++i)
#pragma unroll
for (int q = 0; q < 8; ++q) {
const int row = i * 16 + 8 * hi + q;
if (row >= nr) continue;
const size_t lr = (size_t) (r0 + row);
#pragma unroll
for (int j = 0; j < NTW; ++j) {
const int col = c0 + warp * (16 * NTW) + j * 16 + l16;
if (GU) a.h[lr * a.ldo + col] = __half_as_ushort(__float2half_rn(swiglu(acc[0][i][j][q], acc[1][i][j][q], a.limit)));
else a.y[lr * a.ldo + col] = acc[0][i][j][q];
}
}
}
template <int T, bool GU, int BM, int NW, int NTW>
inline bool runr(const SetArgs& a, cudaStream_t s) {
const int N = GU ? a.n_ff : a.n_embd;
constexpr int BN = NW * 16 * NTW;
if (N % BN != 0) return false;
const dim3 grid((unsigned) ((a.max_rows + BM - 1) / BM), (unsigned) (N / BN), (unsigned) a.n_exp);
static const int dbg = std::getenv("HIPK_DBG") ? std::atoi(std::getenv("HIPK_DBG")) : 0;
set_kernel_r<T, GU, BM, NW, NTW><<<grid, NW * 32, 0, s>>>(a, dbg);
return cudaPeekAtLastError() == cudaSuccess;
}
+162
View File
@@ -0,0 +1,162 @@
// Strata. Part of ds4_iq_hip_r.inc: the weights of a whole 64-value step (two 32-value sub-blocks) of one weight row in a few wide
// loads, and the decode of its four 8-value groups (k-steps) from registers. The loads are unaligned (the blocks of the i-quants are
// 2-byte aligned; the AMD hardware takes unaligned vector loads). A lane holds the group p = 2 ks + hi of every sub-block, so
// the two lanes of a column (hi 0 / 1) share most of their bytes. s: the step (64 values), b: the block (256 values: 4 steps),
// jb = 2 (s & 3): the first sub-block of the step in its block.
struct SRaw {
uint32_t w[10];
};
__device__ __forceinline__ uint4 ldu128(const void* p) {
uint4 v;
__builtin_memcpy(&v, p, 16);
return v;
}
__device__ __forceinline__ uint2 ldu64(const void* p) {
uint2 v;
__builtin_memcpy(&v, p, 8);
return v;
}
__device__ __forceinline__ uint32_t ldu32(const void* p) {
uint32_t v;
__builtin_memcpy(&v, p, 4);
return v;
}
__device__ __forceinline__ uint32_t ldu16(const void* p) {
uint16_t v;
__builtin_memcpy(&v, p, 2);
return v;
}
template <int T>
__device__ __forceinline__ void stage_load(const uint8_t* __restrict__ row, int s, int hi, SRaw& r) {
if constexpr (T == kIQ4_NL) { // 32-value blocks of 18 bytes: the step is blocks 2 s and 2 s + 1
const uint8_t* b0 = row + (size_t) (2 * s) * 18;
const uint2 qa = ldu64(b0 + 2 + 8 * hi), qb = ldu64(b0 + 18 + 2 + 8 * hi);
r.w[0] = qa.x, r.w[1] = qa.y, r.w[2] = qb.x, r.w[3] = qb.y;
r.w[4] = ldu16(b0);
r.w[5] = ldu16(b0 + 18);
} else {
const uint8_t* b = row + (size_t) (s >> 2) * Ty<T>::B;
const int jb = 2 * (s & 3);
if constexpr (T == kIQ2_XXS) {
const uint4 q = ldu128(b + 2 + 8 * jb);
r.w[0] = q.x, r.w[1] = q.y, r.w[2] = q.z, r.w[3] = q.w;
r.w[4] = ldu16(b);
} else if constexpr (T == kIQ2_XS) {
const uint4 q = ldu128(b + 2 + 8 * jb);
r.w[0] = q.x, r.w[1] = q.y, r.w[2] = q.z, r.w[3] = q.w;
r.w[4] = ldu16(b + 66 + jb);
r.w[5] = ldu16(b);
} else if constexpr (T == kIQ2_S) {
const uint2 q = ldu64(b + 2 + 4 * jb), sg = ldu64(b + 34 + 4 * jb);
r.w[0] = q.x, r.w[1] = q.y, r.w[2] = sg.x, r.w[3] = sg.y;
r.w[4] = ldu16(b + 66 + jb);
r.w[5] = ldu16(b + 74 + jb);
r.w[6] = ldu16(b);
} else if constexpr (T == kIQ3_XXS) {
const uint4 q = ldu128(b + 2 + 8 * jb);
const uint2 ax = ldu64(b + 66 + 4 * jb);
r.w[0] = q.x, r.w[1] = q.y, r.w[2] = q.z, r.w[3] = q.w;
r.w[4] = ax.x, r.w[5] = ax.y;
r.w[6] = ldu16(b);
} else if constexpr (T == kIQ3_S) {
const uint4 q = ldu128(b + 2 + 8 * jb);
const uint2 sg = ldu64(b + 74 + 4 * jb);
r.w[0] = q.x, r.w[1] = q.y, r.w[2] = q.z, r.w[3] = q.w;
r.w[4] = ldu16(b + 66 + jb);
r.w[5] = sg.x, r.w[6] = sg.y;
r.w[7] = b[106 + (jb >> 1)];
r.w[8] = ldu16(b);
} else if constexpr (T == kIQ4_XS) {
const uint2 qa = ldu64(b + 8 + 16 * jb + 8 * hi), qb = ldu64(b + 8 + 16 * (jb + 1) + 8 * hi);
r.w[0] = qa.x, r.w[1] = qa.y, r.w[2] = qb.x, r.w[3] = qb.y;
r.w[4] = ldu16(b + 2);
r.w[5] = b[4 + (jb >> 1)];
r.w[6] = ldu16(b);
} else if constexpr (T == kIQ1_S) {
const uint2 q = ldu64(b + 2 + 4 * jb);
r.w[0] = q.x, r.w[1] = q.y;
r.w[2] = ldu32(b + 34 + 2 * jb);
r.w[3] = ldu16(b);
} else { // IQ1_M
const uint2 q = ldu64(b + 4 * jb);
const uint2 d4 = ldu64(b + 48);
r.w[0] = q.x, r.w[1] = q.y;
r.w[2] = ldu32(b + 32 + 2 * jb);
r.w[3] = ldu16(b + 48 + (jb >> 1) * 2);
r.w[4] = d4.x, r.w[5] = d4.y;
}
}
}
// the k-step t (0..3, compile time) of a loaded step: sub-block sub = t >> 1, group p = 2 (t & 1) + hi
template <int T, int TT>
__device__ __forceinline__ void step_dec(const SRaw& r, int s, int hi, const uint32_t* tab, int& c0, int& c1, float& sc) {
constexpr int sub = TT >> 1, ks = TT & 1;
const int p = 2 * ks + hi;
if constexpr (T == kIQ2_XXS) {
const uint2 g = ((const uint2*) tab)[(r.w[2 * sub] >> (8 * p)) & 255u];
const uint32_t a1 = r.w[2 * sub + 1];
const uint32_t sg = ksigns8(a1 >> (7 * p));
c0 = sgn4(g.x, sg);
c1 = sgn4(g.y, sg >> 4);
sc = hf(r.w[4]) * (float) (2 * (int) (a1 >> 28) + 1) * 0.125f;
} else if constexpr (T == kIQ2_XS) {
const uint32_t v = (r.w[2 * sub + (ks)] >> (16 * hi)) & 0xffffu;
const uint2 g = ((const uint2*) tab)[v & 511u];
const uint32_t sg = ksigns8(v >> 9);
const uint32_t scb = (r.w[4] >> (8 * sub)) & 255u;
c0 = sgn4(g.x, sg);
c1 = sgn4(g.y, sg >> 4);
sc = hf(r.w[5]) * (float) (2 * (int) (ks == 0 ? scb & 15 : scb >> 4) + 1) * 0.125f;
} else if constexpr (T == kIQ2_S) {
const uint32_t qh = (r.w[4] >> (8 * sub)) & 255u;
const uint32_t idx = ((r.w[sub] >> (8 * p)) & 255u) | ((qh << (8 - 2 * p)) & 0x300u);
const uint32_t sg = (r.w[2 + sub] >> (8 * p)) & 255u;
const uint32_t scb = (r.w[5] >> (8 * sub)) & 255u;
const uint2 g = ((const uint2*) tab)[idx];
c0 = sgn4(g.x, sg);
c1 = sgn4(g.y, sg >> 4);
sc = hf(r.w[6]) * (float) (2 * (int) (ks == 0 ? scb & 15 : scb >> 4) + 1) * 0.125f;
} else if constexpr (T == kIQ3_XXS) {
const uint32_t word = r.w[2 * sub + ks];
const uint32_t aux = r.w[4 + sub];
const uint32_t sg = ksigns8(aux >> (7 * p));
c0 = sgn4(tab[(word >> (16 * hi)) & 255u], sg);
c1 = sgn4(tab[(word >> (16 * hi + 8)) & 255u], sg >> 4);
sc = hf(r.w[6]) * (float) (2 * (int) (aux >> 28) + 1) * 0.25f;
} else if constexpr (T == kIQ3_S) {
const uint32_t word = r.w[2 * sub + ks];
const uint32_t h = (r.w[4] >> (8 * sub)) & 255u;
const uint32_t sg = (r.w[5 + sub] >> (8 * p)) & 255u;
c0 = sgn4(tab[((word >> (16 * hi)) & 255u) | ((h << (8 - 2 * p)) & 256u)], sg);
c1 = sgn4(tab[((word >> (16 * hi + 8)) & 255u) | ((h << (7 - 2 * p)) & 256u)], sg >> 4);
sc = hf(r.w[8]) * (float) (1 + 2 * (int) ((r.w[7] >> (4 * sub)) & 15));
} else if constexpr (T == kIQ4_XS) {
const int jb = 2 * (s & 3);
const int ls = ((r.w[5] >> (4 * sub)) & 15) | (((r.w[4] >> (2 * (jb + sub))) & 3) << 4);
const int2 v0 = tab16(r.w[2 * sub], tab), v1 = tab16(r.w[2 * sub + 1], tab);
c0 = ks == 0 ? v0.x : v0.y;
c1 = ks == 0 ? v1.x : v1.y;
sc = hf(r.w[6]) * (float) (ls - 32);
} else if constexpr (T == kIQ1_S) {
const uint32_t qh = (r.w[2] >> (16 * sub)) & 0xffffu;
const uint32_t g = tab[((r.w[sub] >> (8 * p)) & 255u) | (((qh >> (3 * p)) & 7u) << 8)];
const bool neg = (qh & 0x8000u) != 0;
c0 = (int) iq1_codes(g & 0x0F0F0F0Fu, neg);
c1 = (int) iq1_codes((g >> 4) & 0x0F0F0F0Fu, neg);
sc = hf(r.w[3]) * (float) (2 * (int) ((qh >> 12) & 7u) + 1) * 0.125f;
} else if constexpr (T == kIQ1_M) {
const uint32_t qh = (r.w[2] >> (8 * (2 * sub + ks))) & 255u; // (p < 2: the first byte of the sub-block, else the second)
const uint32_t g = tab[((r.w[sub] >> (8 * p)) & 255u) | ((qh << (hi ? 4 : 8)) & 0x700u)];
const bool neg = (hi ? qh & 0x80u : qh & 0x08u) != 0;
c0 = (int) iq1_codes(g & 0x0F0F0F0Fu, neg);
c1 = (int) iq1_codes((g >> 4) & 0x0F0F0F0Fu, neg);
const int sh = (int) ((r.w[3] >> (6 * sub + (ks == 0 ? 0 : 3))) & 7u);
const uint32_t d16 = (r.w[4] >> 12 & 0xfu) | ((r.w[4] >> 24) & 0xf0u) | ((r.w[5] >> 4) & 0xf00u) | ((r.w[5] >> 16) & 0xf000u);
sc = hf(d16) * (float) (2 * sh + 1) * 0.125f;
} else { // IQ4_NL
const int2 v0 = tab16(r.w[2 * sub], tab), v1 = tab16(r.w[2 * sub + 1], tab);
c0 = ks == 0 ? v0.x : v0.y;
c1 = ks == 0 ? v1.x : v1.y;
sc = hf(r.w[4 + sub]);
}
}
File diff suppressed because it is too large. Load diff
+306
View File
@@ -0,0 +1,306 @@
// 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_kernels.cuh - DeepSeek-V4.1's own device kernels for a window of T tokens (1 <= T <= kWin) at positions
// p0 .. p0 + T - 1 (the EXL3 matrices go through strata::dsv41k::exl3). The math is DeepSeek's inference/model.py
// (MIT); tools/ds4/ref.py is the oracle the engine is checked against. Every pointer is device memory, every activation
// F32, rows of a window back to back; the KV caches keep the reference's FP8 / FP4 roundings packed as DeepSeek stores
// them (codes and scales, kv_row_bytes), the window attention's working rows BF16 (those values are exact in BF16).
// What differs from query to query (its window, how much of the compressed KV it sees, how many rows it selects) is
// known on the host and passed by value.
#pragma once
#include <cstddef>
#include <cstdint>
#include <cuda_runtime.h>
namespace strata::ds4 {
constexpr int kWin = 16; // tokens a window takes at most (the EXL3 GEMV's activations per job)
constexpr int kPicks = 8; // routed experts a token can take at most
/// The caches' rows: DeepSeek's own roundings kept as codes and scales - lossless, the values are on those grids already
/// (the numbers are Finish::quant's; a finish with that quant and a pdst writes the format), a row of d values in
/// kv_row_bytes(fmt, d) bytes, padded to 16 (the hand-offs copy 16-byte units):
/// kKvFp8 the window ring: d E4M3 codes, then d / 32 power-of-two scales (UE8M0: the F32 exponent byte)
/// kKvFp4 the compressed KV: d / 2 bytes of E2M1 codes (value 2i in the low nibble), then d / 16 E4M3 scales
/// kKvFp4p the index keys: d / 2 bytes of E2M1 codes, then d / 32 UE8M0 scales
/// kKvBf16: plain BF16 rows (a DSpark block's own rows, and the reference the tests check the packed rows against).
constexpr int kKvBf16 = 0, kKvFp8 = 1, kKvFp4 = 2, kKvFp4p = 3;
__host__ __device__ constexpr size_t kv_row_bytes(int fmt, int d) {
return fmt == kKvBf16 ? (size_t) d * 2
: fmt == kKvFp8 ? ((size_t) d + (size_t) d / 32 + 15) / 16 * 16
: fmt == kKvFp4 ? ((size_t) d / 2 + (size_t) d / 16 + 15) / 16 * 16
: ((size_t) d / 2 + (size_t) d / 32 + 15) / 16 * 16;
}
/// h[t][s][e] = BF16 rows[t][e] for each of the hc streams.
void embed(const uint16_t* rows_bf16, int T, float* h, int dim, int hc, cudaStream_t s);
/// The per-vector finish: n_vec vectors of len values at x + v * stride, each in order
/// norm (w != null): x = x * rsqrt(mean(x^2) + eps) * w
/// rope (rd > 0): the last rd values as adjacent complex pairs rotated by pos_v * freqs[i] (inverse: the conjugate),
/// pos_v = pos + (v / vpp) * pos_step
/// quant 0 none, 1 FP8 E4M3 with a power-of-two scale per 32, 2 FP4 E2M1 with an E4M3 scale per 16, 3 FP4 with a
/// power-of-two scale per 32 (the reference kernels' act_quant / fp4_act_quant, inplace)
/// and written back to x, or as BF16 to dst + v * dst_stride when dst is given, or packed (quant > 0: the cache format of
/// that number, kv_row_bytes) to pdst + v * pdst_stride bytes when pdst is given (x then left as it was).
struct Finish {
const float* w = nullptr;
float eps = 1e-20f;
int rd = 0, pos = 0, inverse = 0, vpp = 1, pos_step = 1;
const float* freqs = nullptr; // rd / 2 values
int quant = 0;
uint16_t* dst = nullptr;
long long dst_stride = 0;
uint8_t* pdst = nullptr;
long long pdst_stride = 0;
};
void finish(float* x, int n_vec, int len, long long stride, const Finish& f, cudaStream_t s);
/// Hyper-Connections, row t of each [T][..] array: mixes[t][m] = (h_flat . fn[m]) * rsqrt(mean(h_flat^2) + eps), then
/// pre / post / comb as hc_split_sinkhorn (comb[t][j * hc + k], j the source stream, k the destination). Strides: mixes
/// 32, pre / post 8, comb 64 floats a row.
void hc_mix(const float* h, const float* fn, int hcdim, int n_mix, int T, float eps, float* mixes, cudaStream_t s);
void hc_split(const float* mixes, const float* scale, const float* base, int hc, int iters, float hc_eps, int T,
float* pre, float* post, float* comb, cudaStream_t s);
/// x[t][e] = sum_s mix[t][s] h[t][s][e], then x = rmsnorm(x) * w (w null: no norm).
void hc_pre_norm(const float* h, const float* mix, const float* w, int dim, int hc, int T, float eps, float* x,
cudaStream_t s);
/// out[t][k][e] = post[t][k] y[t][e] + sum_j comb[t][j][k] res[t][j][e] (out must not alias res).
void hc_post(const float* y, const float* res, const float* post, const float* comb, int dim, int hc, int T,
float* out, cudaStream_t s);
/// hc_post with out = res (h), the same arithmetic: a chunk keeps one copy of its streams.
void hc_post_inplace(const float* y, float* h, const float* post, const float* comb, int dim, int hc, int T,
cudaStream_t s);
/// A chunk's hc_mix: the dots of each row with the n_mix weights already in mixes (a GEMM's, rows 32 apart), times
/// rsqrt(mean(h_row^2) + eps) - hc_mix's value up to the dots' summation order.
void hc_mix_scale(const float* h, int hcdim, int n_mix, int T, float eps, float* mixes, cudaStream_t s);
/// y[t][r] = alpha * sum_k W[r][k] x[t][k], W F16 bits [n][k] (the indexer's weights_proj).
void gemv_f16(const uint16_t* W, const float* x, int n, int k, int T, float alpha, float* y, cudaStream_t s);
/// The same for T activations x[t] = x + t ldx into y + t ldy, each weight read once for all of them; each output is
/// gemv_f16's bit for bit.
void gemv_f16_rows(const uint16_t* W, const float* x, size_t ldx, int n, int k, int T, float alpha, float* y, size_t ldy,
cudaStream_t s);
/// y[t ldy + r] = sum_k W[r][k] x[t][k] in F32 (W [n][k], k % 128 == 0): the router's logits, as DeepSeek's
/// inference computes them (linear(x.float(), weight.float())) - a warp a row, the same summing order for any T, so
/// the token, window and chunk paths get the same bits.
void gemv_f32(const float* W, const float* x, int n, int k, int T, float* y, int ldy, cudaStream_t s);
/// The router, row t: scores = sqrt(softplus(logits[t])) (n experts, rows 1024 apart), the top `k` of scores + bias;
/// weights from the unbiased scores, normalized to sum 1 (+1e-20) and times route_scale -> idx[t][i], w[t][i] (rows
/// kPicks apart). Rows of image tokens (bit t of vl) take bias_vl instead (training's noaux_tc_for_vl).
constexpr int kVlRows = 8192;
struct VlBits {
uint32_t w[kVlRows / 32];
};
void route(const float* logits, const float* bias, int n, int k, int T, float route_scale, int* idx, float* w,
cudaStream_t s, const float* bias_vl = nullptr, const VlBits* vl = nullptr);
/// h = silu(min(g, lim)) * clamp(u, -lim, lim) (lim <= 0: no clamp); n values.
void swiglu(const float* g, const float* u, int n, float lim, float* h, cudaStream_t s);
/// The ratio-r compressor over a window: token t (position p0 + t) takes slot (p0 + t) % r of the state; each token that
/// completes a group writes the group's pooled latent (softmax over the slots, per value, then rmsnorm(w)) to the next
/// row of latent.
void compress_win(const float* kv, const float* score, float* kv_state, float* score_state, int ratio, int p0, int T,
int d, const float* w, float eps, float* latent, cudaStream_t s);
/// Per-query sizes, by value - or (gen > 0, a chunk of any length) made on the device from the query's position: query
/// t at position p0 + t has nn = (p0 + t + 1) / R compressed positions and cb = min(ccap, ceil(nn / blk)) candidate
/// blocks; gen 1: n = nn, k = min(kcap, nn) (the indexer's scores and their top-k)
/// gen 2: n = nn, k = cb (index_score over the candidates)
/// gen 3: n = cb * blk, k = min(kcap, nn) (the top-k of the candidates' scores)
/// gen 4: n = ceil(nn / blk), k = kcap (the candidate blocks' top-k)
struct Rows {
int n[kWin];
int k[kWin];
int gen = 0, R = 1, kcap = 0, ccap = 0, blk = 1;
long long p0 = 0;
};
/// The indexer's scores, row t: out[t][i] = sum_h relu(q[t][h] . k[p]) w[t][h] for i < n (the widest query's), p = i, or
/// with candidates p = cand[t][i / blk] * blk + i % blk for i < lim.k[t] * blk; positions >= lim.n[t] (or past the
/// query's candidates) -> -inf. q rows heads * hd apart, w rows 64, cand rows cand_stride, out rows out_stride; the keys
/// k rows of format kfmt (the cache's kKvFp4p, or kKvBf16).
void index_score(const float* q, const float* w, const void* k, int heads, int hd, int T, int n, const int* cand,
int cand_stride, int blk, const Rows& lim, float* out, long long out_stride, cudaStream_t s,
int kfmt = kKvFp4p);
/// The top r.k[t] of vals[t][0, r.n[t]) (row t at vals + t * stride): their positions (unordered; with candidates
/// cand[t][i / blk] * blk + i % blk) into out[t][0, k). r.k[t] >= r.n[t] takes them all.
void topk(const float* vals, long long stride, int T, const Rows& r, const int* cand, int cand_stride, int blk,
int* out, int out_stride, cudaStream_t s);
/// Level one of the candidate pre-filter, row t: block b's score = the max over its blk positions of the r.n[t] the
/// query sees; the block of its newest position is pinned; the top r.k[t] blocks -> out[t] (bm: scratch rows bm_stride).
void cand_blocks(const float* score, long long stride, int T, const Rows& r, int blk, float* bm, long long bm_stride,
int* out, int out_stride, cudaStream_t s);
/// Sparse attention, query t: heads x d values of q[t] against win rows win0[t] .. win0[t] + nwin[t] - 1 of the window
/// buffer (d BF16 each) and the nsel[t] compressed rows ckv[sel[t][i]] (format ckv_fmt: the cache's kKvFp4, or kKvBf16);
/// K = V, a learned sink logit per head. The packed rows, the same bits either way: up to kAttnScratchT queries (with
/// a scratch, heads_per_block 0; or -1, any T) decoded once a query into scr's BF16 rows for the BF16 rows' kernel;
/// else a kernel that decodes each staged row once for heads_per_block heads of a query (1, 2, 4, 8; 0: as many as
/// keep two blocks a multiprocessor).
struct AttnScratch {
uint16_t* rows = nullptr; // [max_t * cap][512] BF16
int max_t = 0, cap = 0; // queries, rows a query (at least the sel_stride)
};
constexpr int kAttnScratchT = 7; // (the staged kernel wins from 8 queries: V100, Sun)
struct AttnRows {
int win0[kWin], nwin[kWin], nsel[kWin];
// gen: query t is a chunk's row t0 + t at position p0 + t0 + t (the window buffer: the ring's win rows before p0,
// then the chunk's), selecting min(kcap, (its position + 1) / R) compressed rows when R > 0
int gen = 0, t0 = 0, win = 0, R = 0, kcap = 0;
long long p0 = 0;
};
void sparse_attn(const float* q, const uint16_t* win, const void* ckv, const int* sel, int sel_stride,
const AttnRows& a, const float* sink, int heads, int d, int T, float scale, float* out, cudaStream_t s,
int ckv_fmt = kKvFp4, int heads_per_block = 0, const AttnScratch* scr = nullptr);
/// The window buffer: ext[r] = ring[(p0 - n + r) % n] for the n rows before p0 (zeros before position 0); afterwards
/// ring[(p0 + t) % n] = ext[n + t] for t < T. The ring's rows kKvFp8 (each group of 32 at the smallest power-of-two
/// scale its BF16 values fit under: exact for values on the FP8 grid, the window's), the window buffer's BF16 (p0 = n:
/// the ring's rows as they lie).
void ring_to_ext(const uint8_t* ring, uint16_t* ext, int64_t p0, int n, int d, cudaStream_t s);
void ext_to_ring(const uint16_t* ext, uint8_t* ring, int64_t p0, int n, int T, int d, cudaStream_t s,
uint8_t* backup = nullptr);
/// A speculative window's rollback: ring[(p0 + t) % n] = backup[t] for keep <= t < T (the rows ext_to_ring replaced).
void ring_restore(uint8_t* ring, const uint8_t* backup, int64_t p0, int n, int keep, int T, int d, cudaStream_t s);
/// The same for up to kMaxRingBatch layers' rings at once (one launch).
constexpr int kMaxRingBatch = 64;
struct RingBatch {
uint8_t* ring[kMaxRingBatch] = {};
const uint8_t* bak[kMaxRingBatch] = {};
int n = 0;
};
void ring_restore_batch(const RingBatch& b, int64_t p0, int n, int keep, int T, int d, cudaStream_t s);
/// Engram. rows: n rows of hd values -> out F32 [n * hd]. fmt, the pack's row layout: 0 FP8 E4M3 values with E8M0
/// scales (scales: n x (hd / 32)); 1 ggml Q6_K superblocks (hd / 256 of 210 bytes at the start of each row's hd bytes;
/// no scales), decoded as ggml's dequantize_row_q6_K; 2 ggml IQ4_NL blocks (hd / 32 of 18 bytes, an fp16 d and 16
/// nibble bytes at the start of each row's hd bytes; no scales), decoded as ggml's dequantize_row_iq4_nl.
void engram_dequant(const uint8_t* rows, const uint8_t* scales, int n, int hd, float* out, cudaStream_t s, int fmt = 0);
/// The same over the host's per-token layout (a chunk): token t's cols rows, then their scales, `per` bytes a token;
/// T tokens -> out F32 [T * cols][hd].
void engram_dequant_tok(const uint8_t* src, size_t per, int cols, int T, int hd, float* out, cudaStream_t s,
int fmt = 0);
/// h[t][k] += gate[t][k] * value[t] with the gate from the normalized dot of h[t][k] * w[k] * key[t][k]
/// (kv[t] = [key hc x dim | value dim]).
void engram_gate(float* h, const float* kv, const float* w, int hc, int dim, int T, float eps, cudaStream_t s);
/// out[r] = x[src[r]] for r < n (rows of cols floats).
struct Gather {
int src[kWin * kPicks];
};
void gather_rows(const float* x, const Gather& g, int n, int cols, float* out, cudaStream_t s);
/// The MoE's sum, token t: out[t] = sum_j w[t][j] ed[row[t][j]] (its VRAM experts, in pick order) + cpu[t] (when its
/// cpu flag is set) + sh[t].
struct Combine {
int n[kWin];
int row[kWin][kPicks];
float w[kWin][kPicks];
int cpu[kWin];
};
void combine(const float* ed, const float* cpu, const float* sh, const Combine& c, int T, int dim, float* out,
cudaStream_t s);
/// The mailboxes of a small window (decode, a draft's verification, the drafter's block): host-mapped memory, a ring of
/// kRing. The device publishes a layer's routing and its FFN inputs for the window's T tokens (seq written last, after
/// a system fence); the host answers with the CPU lane's weighted part of each token that took a CPU-lane expert.
constexpr int kRing = 64;
constexpr int kMaxDim = 8192;
constexpr int kAhead1 = 16, kAhead = kAhead1 + kPicks; // a token's guesses for the next layer, then the one after
struct Req {
unsigned seq;
int T;
int na[2]; // lookahead: ahead[t][0 .. na[0]) the next layer's likely picks, ahead[t][kAhead1 ..) +na[1] the one after's
int ids[kWin][kPicks];
float w[kWin][kPicks];
int ahead[kWin][kAhead];
float x[kWin][kMaxDim];
};
struct Resp {
unsigned seq;
int pad[3];
int cpu[kWin]; // 1: part[t] is the CPU lane's weighted sum for token t
float part[kWin][kMaxDim];
};
/// route() for the T tokens of a window, plus: plan_ptr[t][i] = vram[idx[t][i]] (0: not on the device), each token's x
/// (dim floats) and picks into the request slot, then T and seq (req null: no request, the plan alone).
void route_publish(const float* logits, const float* bias, int n, int k, int T, float route_scale,
const unsigned long long* vram, const float* x, int dim, int* idx, float* w,
unsigned long long* plan_ptr, Req* req, unsigned seq, cudaStream_t s, const float* bias_vl = nullptr,
unsigned vl = 0, int na0 = 0, int na1 = 0);
/// Lookahead: the m picks a later layer will likely make (its gate's logits on this layer's FFN input, the routing's
/// score + bias, the m best of n) into req->ahead[t][off ..) for the T tokens - before route_publish, which publishes them.
void route_ahead(const float* logits, const float* bias, int n, int m, int T, Req* req, int off, cudaStream_t s);
/// The RAM store's picks for the device (a decode token's k plan pointers): those the VRAM table left at 0 whose expert zc_tab has (the
/// slot's device address) are copied into stage slot i (stride apart, `bytes` each) and the plan then points there.
void zc_stage(unsigned long long* plan, const int* idx, const unsigned long long* zc_tab, int k, uint8_t* stage, size_t stride, size_t bytes,
cudaStream_t s);
/// Waits (one thread, on the device) until *seq_ptr == seq.
void wait_seq(const unsigned* seq_ptr, unsigned seq, cudaStream_t s);
/// A chunk's routed experts as sorted rows: the picks (t, i < k) of T tokens (idx rows kPicks apart) by the virtual
/// slot vs[expert] (n_vs of them: the VRAM slots, then the experts streamed in), each slot's rows in token order:
/// bounds[n_vs + 1], row_tok[r], pos[t][i] (the pick's sorted row, rows kPicks apart).
void moe_sort(const int* idx, int T, int k, const int* vs, int n_vs, int* bounds, int* row_tok, int* pos,
cudaStream_t s);
/// acc[t] += w[t][i] * y[pos[t][i] - r0] for each pick of t (in pick order) whose sorted row is in [r0, r1).
void moe_combine(float* acc, const float* y, const int* pos, const float* w, int T, int k, int r0, int r1, int dim,
cudaStream_t s);
/// rows[t][0] = 1, the rest 0 (the first layer's pre-mix: stream 0).
void init_pre(float* pre, int T, cudaStream_t s);
/// out[t][e] = mean over the hc streams of h[t][s][e] (the DSpark drafter's taps), rows out_stride floats apart.
void hc_mean(const float* h, int T, int hc, int dim, float* out, long long out_stride, cudaStream_t s);
/// out[t][i] = i for i < n, rows `stride` apart (the drafter's block rows as every query's selection).
void iota_rows(int* out, int T, int n, int stride, cudaStream_t s);
/// The DSpark markov head: logits[v] += E[*tok] . H[v] for v < V (E BF16 [V][R], H F16 [V][R]).
void markov_add(float* logits, const uint16_t* E, const uint16_t* H, const int* tok, int V, int R, cudaStream_t s);
/// The markov bias over a head group: a member's rows [v0, v0 + vn) of it added to its share of a logits row (erow:
/// the previous token's E row, BF16, on the device) - markov_add's sums; the share's argmax (the greedy sampler's rule)
/// into a host-mapped slot {value, index, seq}; every member's slot of the step -> the global argmax into *tok and its
/// E row (E host-mapped) into erow.
void markov_share(float* logits, const uint16_t* H, const uint16_t* erow, int vn, int R, cudaStream_t s);
void argmax_share(const float* row, int vn, int v0, unsigned* slot, unsigned seq, cudaStream_t s);
void markov_pick(const unsigned* slots, int nm, unsigned seq, int* tok, const uint16_t* E, uint16_t* erow, int R,
cudaStream_t s);
/// The DSpark confidence: out[t] = sigmoid(w . [x[t] | E[tok[t]]]) (x rows dim floats, w F32 [dim + R]).
void confidence(const float* x, const uint16_t* E, const int* tok, const float* w, int T, int dim, int R, float* out,
cudaStream_t s);
/// The pipeline's hand-offs and tensor parallelism, through host-mapped memory (these cards copy peer to peer only
/// through the driver's staging). xfer_put copies up to 4 segments (16-byte multiples, 16-byte aligned) device ->
/// host-mapped, then (flag given) sets *flag = seq after a system fence (cnt: a device counter of the stream, 0
/// between uses); xfer_get waits on the device until *flag >= seq, then copies host-mapped -> device.
struct Xfer {
const void* src[4] = {nullptr, nullptr, nullptr, nullptr};
void* dst[4] = {nullptr, nullptr, nullptr, nullptr};
size_t bytes[4] = {0, 0, 0, 0};
int n = 0;
};
void xfer_put(const Xfer& x, unsigned* flag, unsigned seq, unsigned* cnt, cudaStream_t s);
// Windows (WDDM, CUDA and HIP alike) holds launches back until the host waits or queries the stream: the work queued on
// `s` submitted now (cudaStreamQuery, which does not wait). Elsewhere nothing. DS4_WIN_SUBMIT=0: off (A/B tests)
void win_submit(cudaStream_t s);
void xfer_get(const Xfer& x, const unsigned* flag, unsigned seq, cudaStream_t s);
/// Waits (one thread) until flags[i * stride] >= seq for i < n (a pipelined chunk's readers have taken a buffer);
/// set_flag: *flag = v after a system fence (a reader's acknowledgement).
void wait_flags(const unsigned* flags, int n, int stride, unsigned seq, cudaStream_t s);
void set_flag(unsigned* flag, unsigned v, cudaStream_t s);
/// A tensor-parallel group's all-reduce: host-mapped rows data[member][slot] (stride floats), flags[member][slot]
/// (32 apart). x (n floats, n % 4 == 0: this member's partial) -> the sum of the nm members' partials in member order,
/// the same bits on every member; seq counts the group's all-reduces (the same on each member), slot = seq % slots.
struct ArGroup {
float* data = nullptr;
unsigned* flags = nullptr;
size_t stride = 0;
int nm = 1, slots = 4;
// three members or more: a reduce-scatter + all-gather (each member sums its chunk of every block's range, in
// member order, then reads the others' sums) - [slots][stride] sums, [2][nm][slots][kArBlocks][8] flags
float* sums = nullptr;
unsigned* bflags = nullptr;
};
constexpr int kArBlocks = 64;
void allreduce(float* x, int n, const ArGroup& a, int mi, unsigned seq, unsigned* cnt, cudaStream_t s);
} // namespace strata::ds4
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+196
View File
@@ -0,0 +1,196 @@
// 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_model.hpp - DeepSeek-V4.1-Flash on Maya: an EXL3 model (tools/ds4/pack.py's pack beside its files) over
// the machine's GPUs, layer-split, with the routed experts that do not fit in VRAM on the CPU lane.
//
// Windows of up to 16 tokens through every layer (a prompt in windows, a decode step a window of one): each query of a
// window sees exactly what the reference's decode path gives it (DeepSeek's inference/model.py at start_pos > 0) -
// its own 128-token window, the compressed groups completed by its position. The state a token leaves is the
// 128-token window ring of every layer, the compressors' partial groups, the compressed KV and index keys of the KV
// source layers (append-only), and the Engram n-gram history; checkpoint() / restore() keep the first two (the rest is
// truncated by position) so a conversation can go back to the end of its last prompt. A conversation that leaves the
// model altogether (another chat answered in between) is a slot: slot_save / slot_load take the same state - the
// compressed KV and index keys included, which a checkpoint leaves in place - through a file or a host buffer.
#pragma once
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace strata::ds4 {
struct Options {
std::string pack; // <model>/maya-ds4
int64_t max_context = 32768;
std::vector<int> gpus; // empty: every visible GPU
int64_t reserve_mib = 600; // VRAM left free on each GPU
double vram_experts = 1.0; // the share of the expert budget to use (tests: less, so the CPU lane works)
int cpu_threads = 0; // 0: the physical cores
std::string profile; // expert hit counts (read to place the hottest experts in VRAM, written back)
bool expert_cache = true; // experts move between VRAM and the CPU lane as they are used
// the CPU lane's experts read in place from the model's files, the page cache keeping what fits, instead of
// copied into RAM: 1 on, 0 off, -1 (auto) where the RAM this process can get does not hold them
int mmap_experts = -1;
// the experts the VRAM leaves over are cached in RAM by a store of their own (ds4_store.hpp): whole experts read unbuffered into
// slots, a replacement policy (0 lru, 1 lfu, 2 lfu then lru), filled on demand and by the lookahead's guesses. GB of RAM at
// most (never past the RAM the process can still get less 8 GB); 0: off, the OS page cache as before
double ssd_cache_gb = -1.0; // < 0: auto (the RAM the process can get less a floor, at most 48 GB; off below 4 GB), 0: off
int ssd_policy = 0;
// dspark_auto: the drafter is loaded only where the routed experts fit the GPUs (more than 1.5x what they have, the verify rounds
// read 3.3x the bytes of a token and measured no faster than plain decoding, and the drafter's 7 GB of experts take the VRAM the
// trunk's hottest would have had); --dspark on / off / none says it outright
bool dspark_auto = true;
bool dspark = true; // load the DSpark drafter (the checkpoint's mtp.* blocks) for speculative decoding
int dspark_block = 0; // at most this many drafts a round (--dspark-block N; 0: the pack's block size)
float dspark_conf = 0.5f; // a draft is verified while its confidence (sigmoid) is at least this
// tensor parallelism: runs of tp GPUs of one kind (the same memory) take the same layers, each a share of the
// heads, of the output projection and of every expert's FFN, summed through host-mapped memory (a GPU unlike the
// next stays alone); tp > 1 runs with threads (--tp 1 --threads off: one host thread, layer split only)
int tp = 2;
bool threads = false; // a host thread per GPU enqueues its layers (the hand-offs host-mapped)
// prompts in chunks of this many tokens through each layer at once (threads): the GEMMs on the tensor cores, the
// CPU lane's experts streamed to the GPUs a chunk at a time instead of computed on the host; 0: windows of 16;
// -1: 2048, or 8192 with the experts read in place (every chunk streams them all from the files)
int prefill_chunk = -1;
bool vision = true; // the vision tower (the checkpoint's vision.* / aligner.*), when it has one
bool vision_only = false; // (tests) load the vision tower alone: encode_image() and nothing else
bool verbose = false;
};
/// A picture in the prompt: its span's rows (every position of the span carries the image token), BF16 [span][dim]
struct Image {
int64_t start = 0;
std::shared_ptr<const std::vector<uint16_t>> rows;
};
struct Stats {
int64_t tokens = 0;
int64_t experts = 0, cpu_experts = 0; // routed experts run, and how many of them on the CPU lane
double cpu_ms = 0.0, gpu_wait_ms = 0.0; // the CPU lane's time; the host's waits for the routing
double layer_ms = 0.0, head_ms = 0.0, engram_ms = 0.0; // the layers' host time in all; the head's wait; Engram reads
int64_t eg_rows = 0, eg_hits = 0, eg_reads = 0; // Engram rows asked for, served without a read, read from the files
double eg_io_ms = 0.0; // the windows' Engram reads, issue to last done (mostly hidden)
int64_t eg_cached = 0, eg_cache_cap = 0; // the row cache's rows held, its capacity
int64_t swaps = 0; // experts the cache moved into VRAM
int64_t skipped = 0; // routed experts STRATA_DS4_DISK_SKIP_W left out (light, not in RAM)
int64_t ram_experts = 0, ram_moves = 0; // CPU-lane experts read from the RAM tier; experts moved into it
double prof_ms[6] = {}; // DS4_PROF: the GPU's time in decode by stage (between layers, attention, routing +
int64_t prof_tokens = 0; // shared expert, experts' gate / up, the wait for the CPU lane, down + post)
// lookahead (decode windows of one): the picks of layers guessed a layer before (the next layer's gate on this
// layer's FFN input), of them in the guess's top k / in all its guesses / in the guess two layers before; the picks
// read from the files, of them prefetched early; experts prefetched early
int64_t ahead_picks = 0, ahead_hit_k = 0, ahead_hit = 0, ahead_hit2 = 0;
int64_t ahead_cold = 0, ahead_cold_hit = 0, ahead_pf = 0;
int64_t ahead_rank_n[16] = {}, ahead_rank_hit[16] = {}; // the next-layer guesses by rank, and how many were picked
// the RAM store (--ssd-cache), totals since the load: reads asked for and found there (hits), missed (misses), started ahead
// of use (prefetched) of which used / given up unused, slots given up, bytes read, ms the CPU lane waited for the reads
int64_t store_hits = 0, store_misses = 0, store_prefetched = 0, store_pf_used = 0, store_pf_wasted = 0, store_evictions = 0;
int64_t store_bytes = 0, store_fails = 0;
int64_t store_zc = 0, store_zc_visible = 0; // experts the GPU computed from the store (zero-copy over PCIe); slots it may read
double store_wait_ms = 0.0, store_busy_ms = 0.0;
int64_t store_slots = 0, store_slots_max = 0;
int64_t drafts_offered = 0, drafts_accepted = 0, drafts_rounds = 0;
// per draft position (the 1st .. 8th of a round): verified with all the drafts before it accepted, and accepted
int64_t draft_reached[8] = {}, draft_kept[8] = {};
double draft_ms = 0.0, verify_ms = 0.0; // the drafter's time, the verification windows' time
};
class Model {
public:
Model();
~Model();
bool load(const Options& o, std::string& err);
/// Feeds `token` at position pos(); with logits, the next token's logits are left on the head's device.
bool step(int token, bool logits, std::string& err);
/// Feeds n tokens (windows of up to 16, or a long run in chunks of prefill_chunk); the last `logits_rows` of them get
/// logits (logits_rows > 16: only a run of one chunk or window).
bool feed(const int* tokens, int n, int logits_rows, std::string& err);
/// feed() of a prompt's end that also keeps the state before its last token in checkpoint `slot` (a prompt's
/// last token then rides along in the run of chunks instead of a window of its own); the same as
/// feed(n - 1), checkpoint(slot), feed(1)
bool feed_mark(const int* tokens, int n, int logits_rows, int slot, std::string& err);
/// The next token from the last feed's last logit row (greedy when temperature <= 0).
int sample(float temperature, float top_p, int top_k, float min_p, uint64_t seed, uint64_t counter);
/// The last feed's logit rows on the host (rows x vocab floats).
bool logits(std::vector<float>& out);
/// The DSpark drafter (speculative decoding): its block size (0: not loaded), drafts for the positions after `y`
/// (y: the token at pos(), not fed yet) with their confidences, and the verification of [y, drafts]: how many of the
/// drafts stand and the token after them (the state then holds y and the accepted drafts). The drafts are the
/// drafter's argmax; a sampled request passes its chain (the same temperature / top_p / top_k / min_p / seed /
/// counter as its verify()) so that with DS4_DSPARK_SAMPLE=1 they are drawn from the drafter's distribution, as
/// DeepSeek's reference does. verify() keeps a draft d with probability min(1, p(d) / q(d)) over the request's
/// chain - the speculative-sampling rule, so every token is still distributed as the model's own draw.
int draft_block() const;
bool draft(int y, std::vector<int>& drafts, std::vector<float>& conf, std::string& err, float temperature = 0.0f,
float top_p = 1.0f, int top_k = 0, float min_p = 0.0f, uint64_t seed = 0, uint64_t counter = 0);
bool verify(int y, const std::vector<int>& drafts, float temperature, float top_p, int top_k, float min_p,
uint64_t seed, uint64_t counter, int& accepted, int& next, std::string& err);
/// Tokens a feed call takes at a time to use the chunked prompt path (all of a prompt: its chunks run as a
/// pipeline; 16 without it).
int feed_unit() const;
/// Called from feed() while a run of chunks goes through the layers, with the tokens done so far.
void set_progress(std::function<void(int64_t)> f);
/// Asked while a run of chunks goes through the layers: true (a Stop) ends it early - one GPU after the layer it is
/// on, several at a chunk all of them reach - and feed() returns false with cancelled() true. The state past the
/// prompt's start is then not usable: restore() a checkpoint kept before the feed, or reset().
void set_cancel(std::function<bool()> f);
bool cancelled() const; // the last feed() / feed_mark() ended early on a Stop
int64_t pos() const;
int64_t max_context() const;
int vocab() const;
int dim() const;
const std::vector<int32_t>& tokens() const; // what the state has consumed, in order
void reset();
/// Keep the state at the current position in checkpoint slot 0 or 1 (the end of a prompt, the position before it);
/// restore(limit) goes back to the latest one at or before limit (-1: none).
void checkpoint(int slot = 0);
bool restore(int64_t limit);
int64_t restorable(int64_t limit) const;
/// Checkpoint 1 also becomes the anchor (kept until a restore goes before it): the position before the end of the
/// first prompt of a run that continued in place, where a re-rendered history (earlier reasoning dropped) splits.
void pin();
/// The positions restore() can go back to, latest first (a slot keeps them: it can be taken back at any of them).
std::vector<int64_t> check_positions() const;
/// The conversation in the model into `out` (slot_save): its position, its tokens, every window ring (the DSpark
/// blocks' included), the compressors' partial groups and each KV source's compressed KV and index keys up to it,
/// the pieces the state a prompt continues is made of. 0 and err: nothing was set aside (it holds pictures, there
/// is no conversation, or the conversation is already set aside - unchanged since).
uint64_t slot_save(std::vector<uint8_t>& out, std::string& err);
/// `data` (a slot's bytes) back into the model: the state at the slot's position n_pos, as slot_save took it -
/// what a prompt that continues the slot's tokens reads on from (the caller checked the tokens are a prefix).
bool slot_load(const uint8_t* data, size_t bytes, int64_t n_pos, std::string& err);
/// What a saved conversation must match: this engine's version, this model's geometry and files and the drafter's
/// blocks - a slot naming anything else is not this model's state (a file's .meta says so; slot_load refuses).
std::string slot_identity() const;
/// The vision tower: the token every position of an image's span carries (-1: no tower).
int image_token() const;
/// An image's pixels (RGB rows, width x height, both multiples of the patch size: the server's resize) -> the
/// rows of its span, BF16 [n_h * (n_w + 1) + 2][dim]: image_start, n_h rows of (n_w aligner rows, image_newline),
/// image_end.
bool encode_image(const uint8_t* rgb, int width, int height, std::vector<uint16_t>& span, std::string& err);
/// The pictures of the prompt about to be fed ({}: none): positions inside a span read its rows (and route with
/// the image bias, and take no part in the Engram n-grams); the rest the embedding table's.
void set_images(std::vector<Image> images);
void save_profile() const;
const Stats& stats() const;
std::string describe() const;
/// INFO / VRAM lines for the server's Monitor.
std::vector<std::string> info_lines() const;
struct Impl;
private:
std::unique_ptr<Impl> p_;
};
} // namespace strata::ds4
+251
View File
@@ -0,0 +1,251 @@
// 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_mx_kern.inc - the CPU lane's int8 MXFP4 rows (ds4_gguf_cpu.hpp: mx_rows), one body for the x86 tiers.
// ds4_gguf_cpu.cpp includes it once a tier, inside its unnamed namespace, after <immintrin.h>, with
// MXK_NS the tier's namespace
// MXK_ATTR the tier's instruction set as a function attribute (GCC / Clang: target(...); MSVC: nothing - it takes
// any intrinsic) on every function here, so the file is built for the baseline and each tier's code runs
// only where ds4_gguf_cpu.cpp's CPU check says it can
// MXK_256 or MXK_512, and MXK_VNNI (vpdpbusd; else vpmaddubsw + vpmaddwd)
// and gets MXK_NS::rows(...) (and with MXK_256 and no MXK_VNNI, MXK_NS::quant(...)); the macros are undefined at the end.
//
// The arithmetic is the device's (ds4_gguf.cu, mx_dot) - a block's 32 codes times the int8 activations summed exactly
// in integers, times (weight scale x activation scale) into F32 sums - in ONE order for every tier, the scalar one
// included (ds4_gguf_cpu.cpp's rows_q_scalar), so every tier gives the same bits and the choice of tier never changes
// an answer:
// * the blocks go in groups of 8; block j of a group adds into accumulator L(j), L = {0, 4, 1, 5, 2, 6, 3, 7} (the
// order a 256-bit hadd tree leaves the 8 blocks' totals in: lanes = blocks 0, 2, 4, 6, 1, 3, 5, 7):
// acc[L(j)] = fma(float(total_j), dw_j * dx_j, acc[L(j)]), the groups in turn;
// * the row is ((acc0 + acc4) + (acc2 + acc6)) + ((acc1 + acc5) + (acc3 + acc7)) (hsum256's tree).
// The codes come out of a shuffle table as w + 12 (0..24, unsigned bytes), so the products go through vpmaddubsw /
// vpdpbusd as u8 x s8; each block's total then gets the activation's -12 x (sum of its 32 values) back, exactly.
//
// The activation of a call (mx_act_bytes(k): k % 256 == 0 here; quant() / ds4_gguf_cpu.cpp's quant_scalar):
// [0, k) int8 values in quads of 4 blocks, quad g at 128 g: the 4 blocks' values 0..15 (block j at
// +16 j), then their 16..31 - one 256-bit step takes a pair of blocks, one 512-bit step a quad
// [k, k + k/8) F32 scale of each block, group G (8 blocks) at 8 G in lane order (blocks 0, 2, 4, 6, 1, 3, 5, 7)
// [k + k/8, + k/8) int32 -12 x (sum of the block's 32 values), the same order
namespace MXK_NS {
constexpr int kBlockBytes = 17; // E8M0 scale + 16 code bytes
MXK_ATTR inline float hsum256(__m256 v) {
const __m128 a = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
const __m128 b = _mm_add_ps(a, _mm_movehl_ps(a, a));
return _mm_cvtss_f32(_mm_add_ss(b, _mm_shuffle_ps(b, b, 1)));
}
// the 8 weight scales of a group (its first block at p), in lane order
MXK_ATTR inline __m256 group_dw(const uint8_t* p, const float* e8) {
return _mm256_setr_ps(e8[p[0]], e8[p[2 * kBlockBytes]], e8[p[4 * kBlockBytes]], e8[p[6 * kBlockBytes]],
e8[p[kBlockBytes]], e8[p[3 * kBlockBytes]], e8[p[5 * kBlockBytes]], e8[p[7 * kBlockBytes]]);
}
#if defined(MXK_256)
// ---------------------------------------------------------------- 256-bit: a pair of blocks a step
// a pair's codes (a1: values 0..15 of both blocks, a2: 16..31) times x1 / x2: 8 int32 lanes, block A's 4 then B's 4
MXK_ATTR inline __m256i pair_dot(__m256i a1, __m256i a2, __m256i x1, __m256i x2) {
#if defined(MXK_VNNI)
return _mm256_dpbusd_avx_epi32(_mm256_dpbusd_avx_epi32(_mm256_setzero_si256(), a1, x1), a2, x2);
#else
const __m256i p = _mm256_add_epi16(_mm256_maddubs_epi16(a1, x1), _mm256_maddubs_epi16(a2, x2));
return _mm256_madd_epi16(p, _mm256_set1_epi16(1));
#endif
}
template <int N>
MXK_ATTR inline void rows_n(const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, float* const* y,
const float* e8, int pf) {
const __m256i lut = _mm256_setr_epi8(12, 13, 14, 15, 16, 18, 20, 24, 12, 11, 10, 9, 8, 6, 4, 0, //
12, 13, 14, 15, 16, 18, 20, 24, 12, 11, 10, 9, 8, 6, 4, 0);
const __m256i m4 = _mm256_set1_epi8(0x0f);
const int ng = k / 256;
const int8_t* xq[N];
const float* xd[N];
const int32_t* xc[N];
for (int i = 0; i < N; ++i) {
const uint8_t* a = (const uint8_t*) act[i];
xq[i] = (const int8_t*) a;
xd[i] = (const float*) (a + k);
xc[i] = (const int32_t*) (a + k + k / 8);
}
for (int r = r0; r < r1; ++r) {
const uint8_t* p = w + (size_t) r * rb;
__m256 acc[N];
for (int i = 0; i < N; ++i) acc[i] = _mm256_setzero_ps();
for (int G = 0; G < ng; ++G, p += 8 * kBlockBytes) {
if (pf > 0) _mm_prefetch((const char*) p + pf, _MM_HINT_T0);
const __m256 dw = group_dw(p, e8);
// the group's 4 pairs of blocks (2 q, 2 q + 1) decoded once; then each activation in turn: its 4 pair dots,
// the hadd tree to the 8 blocks' totals (lanes: blocks 0 2 4 6 | 1 3 5 7), the FMA - only the accumulators
// stay live from one activation to the next (16 YMM registers on AVX2)
__m256i a1[4], a2[4];
for (int q = 0; q < 4; ++q) {
const uint8_t* pb = p + 2 * q * kBlockBytes;
const __m256i c = _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_loadu_si128((const __m128i*) (pb + 1))),
_mm_loadu_si128((const __m128i*) (pb + 18)), 1);
a1[q] = _mm256_shuffle_epi8(lut, _mm256_and_si256(c, m4));
a2[q] = _mm256_shuffle_epi8(lut, _mm256_and_si256(_mm256_srli_epi16(c, 4), m4));
}
const int o = G * 256; // (quads 2 G and 2 G + 1: pair q at (q / 2) * 128 + (q % 2) * 32)
for (int i = 0; i < N; ++i) {
const int8_t* x = xq[i] + o;
const __m256i s0 = pair_dot(a1[0], a2[0], _mm256_loadu_si256((const __m256i*) x),
_mm256_loadu_si256((const __m256i*) (x + 64)));
const __m256i s1 = pair_dot(a1[1], a2[1], _mm256_loadu_si256((const __m256i*) (x + 32)),
_mm256_loadu_si256((const __m256i*) (x + 96)));
const __m256i s2 = pair_dot(a1[2], a2[2], _mm256_loadu_si256((const __m256i*) (x + 128)),
_mm256_loadu_si256((const __m256i*) (x + 192)));
const __m256i s3 = pair_dot(a1[3], a2[3], _mm256_loadu_si256((const __m256i*) (x + 160)),
_mm256_loadu_si256((const __m256i*) (x + 224)));
const __m256i u = _mm256_hadd_epi32(_mm256_hadd_epi32(s0, s1), _mm256_hadd_epi32(s2, s3));
const __m256i tot = _mm256_add_epi32(u, _mm256_loadu_si256((const __m256i*) (xc[i] + 8 * G)));
acc[i] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(tot), _mm256_mul_ps(dw, _mm256_loadu_ps(xd[i] + 8 * G)), acc[i]);
}
}
for (int i = 0; i < N; ++i) y[i][r - r0] = hsum256(acc[i]);
}
}
#if !defined(MXK_VNNI)
// blocks [b0, b1) of x (x at block b0's first value) into act, the bytes of quant_scalar (ds4_gguf_cpu.cpp): the same
// IEEE division and round-half-even conversion, the same max
MXK_ATTR inline void quant(const float* x, int b0, int b1, uint8_t* act, int k) {
int8_t* q = (int8_t*) act;
float* dx = (float*) (act + k);
int32_t* corr = (int32_t*) (act + k + k / 8);
const __m256 sign = _mm256_set1_ps(-0.0f);
const __m256i order = _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7);
for (int b = b0; b < b1; ++b, x += 32) {
const __m256 v0 = _mm256_loadu_ps(x), v1 = _mm256_loadu_ps(x + 8);
const __m256 v2 = _mm256_loadu_ps(x + 16), v3 = _mm256_loadu_ps(x + 24);
const __m256 m = _mm256_max_ps(_mm256_max_ps(_mm256_andnot_ps(sign, v0), _mm256_andnot_ps(sign, v1)),
_mm256_max_ps(_mm256_andnot_ps(sign, v2), _mm256_andnot_ps(sign, v3)));
__m128 m2 = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps(m, 1));
m2 = _mm_max_ps(m2, _mm_movehl_ps(m2, m2));
m2 = _mm_max_ss(m2, _mm_shuffle_ps(m2, m2, 1));
const float am = _mm_cvtss_f32(m2);
const float sc = am / 127.0f;
int8_t* lo = q + (b >> 2) * 128 + 16 * (b & 3);
int8_t* hi = lo + 64;
int s = 0;
if (am > 0.0f) {
const __m256 vs = _mm256_set1_ps(sc);
const __m256i q0 = _mm256_cvtps_epi32(_mm256_div_ps(v0, vs)), q1 = _mm256_cvtps_epi32(_mm256_div_ps(v1, vs));
const __m256i q2 = _mm256_cvtps_epi32(_mm256_div_ps(v2, vs)), q3 = _mm256_cvtps_epi32(_mm256_div_ps(v3, vs));
const __m256i pk = _mm256_permutevar8x32_epi32(
_mm256_packs_epi16(_mm256_packs_epi32(q0, q1), _mm256_packs_epi32(q2, q3)), order);
_mm_storeu_si128((__m128i*) lo, _mm256_castsi256_si128(pk));
_mm_storeu_si128((__m128i*) hi, _mm256_extracti128_si256(pk, 1));
__m256i t = _mm256_add_epi32(_mm256_add_epi32(q0, q1), _mm256_add_epi32(q2, q3));
__m128i t2 = _mm_add_epi32(_mm256_castsi256_si128(t), _mm256_extracti128_si256(t, 1));
t2 = _mm_add_epi32(t2, _mm_shuffle_epi32(t2, 0x4E));
t2 = _mm_add_epi32(t2, _mm_shuffle_epi32(t2, 0xB1));
s = _mm_cvtsi128_si32(t2);
} else {
_mm_storeu_si128((__m128i*) lo, _mm_setzero_si128());
_mm_storeu_si128((__m128i*) hi, _mm_setzero_si128());
}
const int j = b & 7, lane = 8 * (b >> 3) + (j & 1) * 4 + (j >> 1);
dx[lane] = sc;
corr[lane] = -12 * s;
}
}
#endif
#endif // MXK_256
#if defined(MXK_512)
// ---------------------------------------------------------------- 512-bit: a quad of blocks a step
MXK_ATTR inline __m512i quad_dot(__m512i a1, __m512i a2, __m512i x1, __m512i x2) {
#if defined(MXK_VNNI)
return _mm512_dpbusd_epi32(_mm512_dpbusd_epi32(_mm512_setzero_si512(), a1, x1), a2, x2);
#else
const __m512i p = _mm512_add_epi16(_mm512_maddubs_epi16(a1, x1), _mm512_maddubs_epi16(a2, x2));
return _mm512_madd_epi16(p, _mm512_set1_epi16(1));
#endif
}
template <int N>
MXK_ATTR inline void rows_n(const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, float* const* y,
const float* e8, int pf) {
const __m512i lut = _mm512_broadcast_i32x4(_mm_setr_epi8(12, 13, 14, 15, 16, 18, 20, 24, 12, 11, 10, 9, 8, 6, 4, 0));
const __m512i m4 = _mm512_set1_epi8(0x0f);
// a quad's 16 lanes after adjacent-pair sums: block j's halves in lanes 4 j and 4 j + 2; the group's two quads ->
// the 8 blocks in lane order (0 2 4 6 1 3 5 7), first halves (pa) and second halves (pb)
const __m512i pa = _mm512_setr_epi32(0, 8, 16, 24, 4, 12, 20, 28, 0, 0, 0, 0, 0, 0, 0, 0);
const __m512i pb = _mm512_setr_epi32(2, 10, 18, 26, 6, 14, 22, 30, 0, 0, 0, 0, 0, 0, 0, 0);
const int ng = k / 256;
const int8_t* xq[N];
const float* xd[N];
const int32_t* xc[N];
for (int i = 0; i < N; ++i) {
const uint8_t* a = (const uint8_t*) act[i];
xq[i] = (const int8_t*) a;
xd[i] = (const float*) (a + k);
xc[i] = (const int32_t*) (a + k + k / 8);
}
for (int r = r0; r < r1; ++r) {
const uint8_t* p = w + (size_t) r * rb;
__m256 acc[N];
for (int i = 0; i < N; ++i) acc[i] = _mm256_setzero_ps();
for (int G = 0; G < ng; ++G, p += 8 * kBlockBytes) {
if (pf > 0) _mm_prefetch((const char*) p + pf, _MM_HINT_T0);
const __m256 dw = group_dw(p, e8);
__m512i h0[N];
for (int qd = 0; qd < 2; ++qd) { // the group's quads: blocks 4 qd .. 4 qd + 3
const uint8_t* pq = p + 4 * qd * kBlockBytes;
__m512i c = _mm512_castsi128_si512(_mm_loadu_si128((const __m128i*) (pq + 1)));
c = _mm512_inserti32x4(c, _mm_loadu_si128((const __m128i*) (pq + 18)), 1);
c = _mm512_inserti32x4(c, _mm_loadu_si128((const __m128i*) (pq + 35)), 2);
c = _mm512_inserti32x4(c, _mm_loadu_si128((const __m128i*) (pq + 52)), 3);
const __m512i a1 = _mm512_shuffle_epi8(lut, _mm512_and_si512(c, m4));
const __m512i a2 = _mm512_shuffle_epi8(lut, _mm512_and_si512(_mm512_srli_epi16(c, 4), m4));
const int o = (2 * G + qd) * 128;
for (int i = 0; i < N; ++i) {
const __m512i s = quad_dot(a1, a2, _mm512_loadu_si512((const void*) (xq[i] + o)),
_mm512_loadu_si512((const void*) (xq[i] + o + 64)));
const __m512i h = _mm512_add_epi32(s, _mm512_shuffle_epi32(s, (_MM_PERM_ENUM) 0xB1));
if (qd == 0) {
h0[i] = h;
continue;
}
const __m512i ta = _mm512_permutex2var_epi32(h0[i], pa, h), tb = _mm512_permutex2var_epi32(h0[i], pb, h);
const __m256i tot = _mm256_add_epi32(
_mm256_add_epi32(_mm512_castsi512_si256(ta), _mm512_castsi512_si256(tb)),
_mm256_loadu_si256((const __m256i*) (xc[i] + 8 * G)));
acc[i] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(tot), _mm256_mul_ps(dw, _mm256_loadu_ps(xd[i] + 8 * G)), acc[i]);
}
}
}
for (int i = 0; i < N; ++i) y[i][r - r0] = hsum256(acc[i]);
}
}
#endif // MXK_512
// y[i][r - r0] for every i < n, in calls of up to 8 activations; e8 the 256 E8M0 scales as F32 (2^(e - 128)), pf the
// bytes to prefetch ahead in a row (0: none)
MXK_ATTR inline void rows(const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, int n,
float* const* y, const float* e8, int pf) {
for (int i0 = 0; i0 < n; i0 += 8) {
float* yy[8];
const int c = n - i0 < 8 ? n - i0 : 8;
for (int i = 0; i < c; ++i) yy[i] = y[i0 + i];
switch (c) {
case 1: rows_n<1>(w, rb, k, r0, r1, act + i0, yy, e8, pf); break;
case 2: rows_n<2>(w, rb, k, r0, r1, act + i0, yy, e8, pf); break;
case 3: rows_n<3>(w, rb, k, r0, r1, act + i0, yy, e8, pf); break;
case 4: rows_n<4>(w, rb, k, r0, r1, act + i0, yy, e8, pf); break;
case 5: rows_n<5>(w, rb, k, r0, r1, act + i0, yy, e8, pf); break;
case 6: rows_n<6>(w, rb, k, r0, r1, act + i0, yy, e8, pf); break;
case 7: rows_n<7>(w, rb, k, r0, r1, act + i0, yy, e8, pf); break;
default: rows_n<8>(w, rb, k, r0, r1, act + i0, yy, e8, pf); break;
}
}
}
} // namespace MXK_NS
#undef MXK_NS
#undef MXK_ATTR
#undef MXK_256
#undef MXK_512
#undef MXK_VNNI
+65
View File
@@ -0,0 +1,65 @@
// 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_numerics.cuh - the BF16 and FP8 (E4M3) conversions of maya-ds4's kernels, on CUDA through its
// intrinsics (cuda_bf16.h / cuda_fp8.h) and on HIP in plain arithmetic that gives the same bits: BF16 round to
// nearest even; E4M3 (OCP "fn": no infinities, max 448) decoded exactly, rounded to nearest even and saturated.
#pragma once
#include <cstdint>
#include <cuda_runtime.h>
#if !defined(STRATA_USE_HIP)
#include <cuda_bf16.h>
#include <cuda_fp16.h>
#include <cuda_fp8.h>
#endif
namespace strata::ds4 {
/// F32 -> BF16 bits, round to nearest even (a NaN stays a NaN).
__device__ __forceinline__ uint16_t bf16_rn(float f) {
#if !defined(STRATA_USE_HIP)
return __bfloat16_as_ushort(__float2bfloat16_rn(f));
#else
const uint32_t u = __float_as_uint(f);
if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 0x40u);
return (uint16_t) ((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
#endif
}
/// An E4M3 code's value (exact in F32).
__device__ __forceinline__ float e4m3_value(uint8_t q) {
#if !defined(STRATA_USE_HIP)
const __half_raw h = __nv_cvt_fp8_to_halfraw((__nv_fp8_storage_t) q, __NV_E4M3);
return __half2float(__half(h));
#else
const uint32_t e = (q >> 3) & 15u, m = q & 7u;
float v;
if (e == 15u && m == 7u) v = __uint_as_float(0x7fc00000u); // NaN
else if (e == 0u) v = (float) m * 0.001953125f; // m 2^-9
else v = __uint_as_float(((e + 120u) << 23) | (m << 20)); // (1 + m / 8) 2^(e - 7)
return (q & 0x80u) ? -v : v;
#endif
}
/// v rounded to the nearest E4M3 value (ties to even), saturated at +-448.
__device__ __forceinline__ float e4m3_round(float v) {
#if !defined(STRATA_USE_HIP)
const __nv_fp8_storage_t q = __nv_cvt_float_to_fp8(v, __NV_SATFINITE, __NV_E4M3);
const __half_raw h = __nv_cvt_fp8_to_halfraw(q, __NV_E4M3);
return __half2float(__half(h));
#else
const float a = fabsf(v);
if (!(a == a)) return v;
float r;
if (a >= 448.0f) r = 448.0f;
else {
const int e = (int) ((__float_as_uint(a) >> 23) & 0xffu) - 127; // a's binade (a > 0)
const float step = e < -6 ? 0.001953125f : __uint_as_float((uint32_t) (e - 3 + 127) << 23);
r = a == 0.0f ? 0.0f : rintf(a / step) * step; // (a power of two: exact)
r = fminf(r, 448.0f);
}
return v < 0.0f ? -r : r;
#endif
}
} // namespace strata::ds4
+561
View File
@@ -0,0 +1,561 @@
// 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_os.hpp - the few OS services maya-ds4 needs, on Linux and on Windows: files read at an offset and
// mapped read-only (the experts read in place), page-cache hints, anonymous host memory on a NUMA node, thread pinning,
// each NUMA node's physical cores, the RAM this process can still get. (On Windows as src/core/expert_source.cpp
// does it for GLM: no FILE_FLAG_RANDOM_ACCESS - the page cache must keep what it read.)
#pragma once
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <psapi.h> // (K32QueryWorkingSetEx: kernel32's, no psapi.lib)
#include <timeapi.h>
#ifdef _MSC_VER
#pragma comment(lib, "winmm.lib")
#endif
#else
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#endif
namespace strata::ds4::os {
/// Windows sleeps in 15.6 ms ticks unless a process asks for finer ones: the CPU lane's service thread naps (sleep_for 20 us)
/// between tokens, and the device's first wait of the next token then waits out the tick. 1 ms for the process's life
/// (Project Maya #358). Off by default (owner PC, shipped profile, 3 pairs: not faster in every pair); DS4_TIMER_MS=1 turns it on.
/// Elsewhere nothing.
inline void fine_timer() {
#if defined(_WIN32)
const char* v = std::getenv("DS4_TIMER_MS");
const int ms = v != nullptr ? std::atoi(v) : 0;
if (ms > 0) timeBeginPeriod((UINT) ms);
#endif
}
using fd_t = intptr_t;
constexpr fd_t kBadFd = -1;
#if defined(_WIN32)
inline std::wstring wide(const std::string& s) { // UTF-8 -> UTF-16 (a path with non-ASCII characters)
const int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
std::wstring w((size_t) (n > 0 ? n : 1), L'\0');
if (n > 0) MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, &w[0], n);
return w;
}
#endif
/// A file opened for reading (kBadFd: it could not be).
inline fd_t open_ro(const std::string& path) {
#if defined(_WIN32)
HANDLE h = CreateFileW(wide(path).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
return h == INVALID_HANDLE_VALUE ? kBadFd : (fd_t) h;
#else
const int fd = ::open(path.c_str(), O_RDONLY);
return fd < 0 ? kBadFd : (fd_t) fd;
#endif
}
/// The same file opened for unbuffered reads (Linux: O_DIRECT - no page cache, the disk straight into the buffer;
/// kBadFd where the filesystem refuses it, or on Windows, whose unbuffered reads of a mapped file take a slow path)
inline fd_t open_direct(const std::string& path) {
#if defined(_WIN32)
// FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED: the disk straight into an aligned buffer, any number of reads in flight on
// one handle (DS4_WIN_DIRECT=0: none, the page cache's buffered reads as before)
static const bool off = [] {
const char* v = std::getenv("DS4_WIN_DIRECT");
return v != nullptr && std::atoi(v) == 0;
}();
if (off) return kBadFd;
HANDLE h = CreateFileW(wide(path).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, nullptr);
return h == INVALID_HANDLE_VALUE ? kBadFd : (fd_t) h;
#else
const int fd = ::open(path.c_str(), O_RDONLY | O_DIRECT);
return fd < 0 ? kBadFd : (fd_t) fd;
#endif
}
/// [off, off + n) through an unbuffered descriptor into dst, a kDirectAlign-aligned buffer of at least
/// direct_span(off, n) bytes: the file read from off rounded down, so the bytes land at dst + (off % kDirectAlign).
/// False if a read fails (the caller reads buffered instead).
constexpr uint64_t kDirectAlign = 4096;
inline uint64_t direct_span(uint64_t off, uint64_t n) {
const uint64_t a0 = off & ~(kDirectAlign - 1), a1 = (off + n + kDirectAlign - 1) & ~(kDirectAlign - 1);
return a1 - a0;
}
inline bool pread_direct(fd_t f, void* dst, uint64_t n, uint64_t off) {
#if defined(_WIN32)
struct Ev { // (each thread its own, closed when it ends)
HANDLE h = CreateEventW(nullptr, TRUE, FALSE, nullptr);
~Ev() {
if (h != nullptr) CloseHandle(h);
}
};
static thread_local Ev ev;
if (ev.h == nullptr) return false;
const uint64_t a0 = off & ~(kDirectAlign - 1), need = direct_span(off, n), want = (off - a0) + n;
uint8_t* p = (uint8_t*) dst;
uint64_t got = 0;
while (got < need) {
const DWORD ask = (DWORD) std::min<uint64_t>(need - got, 1ull << 30); // (a multiple of 4096)
OVERLAPPED ov{};
const uint64_t at = a0 + got;
ov.Offset = (DWORD) (at & 0xffffffffu);
ov.OffsetHigh = (DWORD) (at >> 32);
ov.hEvent = ev.h;
ResetEvent(ev.h);
DWORD r = 0;
if (!ReadFile((HANDLE) f, p + got, ask, nullptr, &ov)) {
const DWORD e = GetLastError();
if (e == ERROR_HANDLE_EOF) break;
if (e != ERROR_IO_PENDING) return false;
}
if (!GetOverlappedResult((HANDLE) f, &ov, &r, TRUE)) {
if (GetLastError() == ERROR_HANDLE_EOF) break;
return false;
}
if (r == 0) break; // (the file's end: the last aligned read is short)
got += r;
if (r % kDirectAlign != 0) break;
}
return got >= want;
#else
const uint64_t a0 = off & ~(kDirectAlign - 1), need = direct_span(off, n), want = (off - a0) + n;
uint8_t* p = (uint8_t*) dst;
uint64_t got = 0;
while (got < need) {
const ssize_t r = ::pread((int) f, p + got, (size_t) std::min<uint64_t>(need - got, 1ull << 30), (off_t) (a0 + got));
if (r < 0) return false;
if (r == 0) break; // (the file's end: the last aligned read is short)
got += (uint64_t) r;
if ((uint64_t) r % kDirectAlign != 0) break;
}
return got >= want;
#endif
}
/// Windows: the file opened for unbuffered reads (FILE_FLAG_NO_BUFFERING), for a file no view of this process maps -
/// unbuffered reads of a mapped file take a slow path there (open_direct); kBadFd elsewhere
inline fd_t open_unbuffered(const std::string& path) {
#if defined(_WIN32)
HANDLE h = CreateFileW(wide(path).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, nullptr);
return h == INVALID_HANDLE_VALUE ? kBadFd : (fd_t) h;
#else
(void) path;
return kBadFd;
#endif
}
/// [off, off + n) through open_unbuffered's handle (one thread's) into buf, kDirectAlign-aligned and at least
/// direct_span(off, n) bytes: the bytes land at buf + off % kDirectAlign
inline bool pread_unbuffered(fd_t f, void* buf, uint64_t n, uint64_t off) {
#if defined(_WIN32)
const uint64_t a0 = off & ~(kDirectAlign - 1), span = direct_span(off, n);
OVERLAPPED ov{};
ov.Offset = (DWORD) a0;
ov.OffsetHigh = (DWORD) (a0 >> 32);
DWORD got = 0;
return ReadFile((HANDLE) f, buf, (DWORD) span, &got, &ov) && got >= (off - a0) + n;
#else
(void) f, (void) buf, (void) n, (void) off;
return false;
#endif
}
/// The same file opened for reads from many threads at once (Windows runs the reads of a synchronous handle one at a
/// time, so an overlapped one; Linux: a plain descriptor, pread is concurrent anyway)
inline fd_t open_par(const std::string& path) {
#if defined(_WIN32)
HANDLE h = CreateFileW(wide(path).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, nullptr);
return h == INVALID_HANDLE_VALUE ? kBadFd : (fd_t) h;
#else
const int fd = ::open(path.c_str(), O_RDONLY);
return fd < 0 ? kBadFd : (fd_t) fd;
#endif
}
/// n bytes at off through open_par's handle (any thread, concurrently)
inline bool pread_par(fd_t f, void* dst, uint64_t n, uint64_t off) {
#if defined(_WIN32)
struct Ev { // (each thread its own, closed when it ends)
HANDLE h = CreateEventW(nullptr, TRUE, FALSE, nullptr);
~Ev() {
if (h != nullptr) CloseHandle(h);
}
};
static thread_local Ev ev;
if (ev.h == nullptr) return false;
uint8_t* p = (uint8_t*) dst;
while (n > 0) {
const DWORD want = (DWORD) std::min<uint64_t>(n, 1ull << 30);
OVERLAPPED ov{};
ov.Offset = (DWORD) (off & 0xffffffffu);
ov.OffsetHigh = (DWORD) (off >> 32);
ov.hEvent = ev.h;
ResetEvent(ev.h);
DWORD got = 0;
if (!ReadFile((HANDLE) f, p, want, nullptr, &ov) && GetLastError() != ERROR_IO_PENDING) return false;
if (!GetOverlappedResult((HANDLE) f, &ov, &got, TRUE) || got == 0) return false;
p += got, off += got, n -= got;
}
return true;
#else
uint8_t* p = (uint8_t*) dst;
while (n > 0) {
const ssize_t r = ::pread((int) f, p, (size_t) std::min<uint64_t>(n, 1ull << 30), (off_t) off);
if (r <= 0) return false;
p += r, off += (uint64_t) r, n -= (uint64_t) r;
}
return true;
#endif
}
/// `from` renamed to `to`, replacing `to` if it exists (rename(2) does; Windows' rename fails on an existing file, so
/// MoveFileExW with MOVEFILE_REPLACE_EXISTING)
inline bool replace_file(const std::string& from, const std::string& to) {
#if defined(_WIN32)
return MoveFileExW(wide(from).c_str(), wide(to).c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
#else
return std::rename(from.c_str(), to.c_str()) == 0;
#endif
}
inline void close_fd(fd_t f) {
if (f == kBadFd) return;
#if defined(_WIN32)
CloseHandle((HANDLE) f);
#else
::close((int) f);
#endif
}
inline uint64_t file_size(fd_t f) {
#if defined(_WIN32)
LARGE_INTEGER sz{};
return GetFileSizeEx((HANDLE) f, &sz) ? (uint64_t) sz.QuadPart : 0;
#else
struct stat sb;
return ::fstat((int) f, &sb) == 0 && sb.st_size > 0 ? (uint64_t) sb.st_size : 0;
#endif
}
/// n bytes at offset off into dst (any thread, concurrently); false if the file ends first or a read fails.
inline bool pread_full(fd_t f, void* dst, uint64_t n, uint64_t off) {
uint8_t* p = (uint8_t*) dst;
while (n > 0) {
const uint64_t want = std::min<uint64_t>(n, 1ull << 30);
#if defined(_WIN32)
OVERLAPPED ov{};
ov.Offset = (DWORD) (off & 0xffffffffu);
ov.OffsetHigh = (DWORD) (off >> 32);
DWORD got = 0;
if (!ReadFile((HANDLE) f, p, (DWORD) want, &got, &ov) || got == 0) return false;
const uint64_t r = got;
#else
const ssize_t rr = ::pread((int) f, p, (size_t) want, (off_t) off);
if (rr <= 0) return false;
const uint64_t r = (uint64_t) rr;
#endif
p += r, off += r, n -= r;
}
return true;
}
/// The whole file mapped read-only (nullptr: it could not be).
inline void* map_ro(fd_t f, uint64_t bytes) {
if (bytes == 0) return nullptr;
#if defined(_WIN32)
HANDLE m = CreateFileMappingW((HANDLE) f, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (m == nullptr) return nullptr;
void* v = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0);
CloseHandle(m); // (the view keeps the mapping)
return v;
#else
void* p = ::mmap(nullptr, (size_t) bytes, PROT_READ, MAP_SHARED, (int) f, 0);
return p == MAP_FAILED ? nullptr : p;
#endif
}
inline void unmap(void* p, uint64_t bytes) {
if (p == nullptr) return;
#if defined(_WIN32)
(void) bytes;
UnmapViewOfFile(p);
#else
::munmap(p, (size_t) bytes);
#endif
}
/// A hint that [off, off + n) of the file is needed soon (need) or not again soon (!need); nothing where the OS has
/// no such hint for a file (Windows' page cache reads ahead on its own).
inline void advise(fd_t f, uint64_t off, uint64_t n, bool need) {
#if defined(_WIN32)
(void) f, (void) off, (void) n, (void) need;
#else
posix_fadvise((int) f, (off_t) off, (off_t) n, need ? POSIX_FADV_WILLNEED : POSIX_FADV_DONTNEED);
#endif
}
/// Ranges of a file's mapping about to be read: the OS reads them in now, with large requests side by side, instead of
/// a page fault at a time later (Windows: PrefetchVirtualMemory - cold expert-sized pieces came in 5x faster on an NVMe;
/// Linux: madvise WILLNEED, the kernel's read-ahead of the whole range). Best effort: a failure changes nothing.
inline void prefetch(const std::vector<std::pair<const void*, size_t>>& ranges) {
if (ranges.empty()) return;
#if defined(_WIN32)
std::vector<WIN32_MEMORY_RANGE_ENTRY> r(ranges.size());
for (size_t i = 0; i < ranges.size(); ++i) {
r[i].VirtualAddress = const_cast<void*>(ranges[i].first);
r[i].NumberOfBytes = ranges[i].second;
}
PrefetchVirtualMemory(GetCurrentProcess(), (ULONG_PTR) r.size(), r.data(), 0);
#else
const uintptr_t pg = 4096;
for (const auto& x : ranges) {
const uintptr_t a = (uintptr_t) x.first, b = a & ~(pg - 1);
madvise((void*) b, x.second + (a - b), MADV_WILLNEED);
}
#endif
}
/// Whether every page of [p, p + n) of a file's mapping is in the page cache (Linux mincore; elsewhere false: the
/// caller reads buffered anyway, which the cache serves)
inline bool resident(const void* p, size_t n) {
#if defined(_WIN32)
(void) p, (void) n;
return false;
#else
const uintptr_t pg = 4096, a = (uintptr_t) p, b = a & ~(pg - 1);
const size_t len = n + (a - b), np = (len + pg - 1) / pg;
thread_local std::vector<unsigned char> v;
if (v.size() < np) v.resize(np);
if (mincore((void*) b, len, v.data()) != 0) return false;
for (size_t i = 0; i < np; ++i)
if ((v[i] & 1) == 0) return false;
return true;
#endif
}
/// Whether a range of a file's mapping looks resident, so that prefetch() would only cost CPU time (it walks every page:
/// ~50 ns a 4 KiB page on Windows - 0.34 ms for a 6.3 MB expert matrix on a Strix Halo): `samples` pages spread over
/// it all resident (Linux: mincore, the page cache; Windows: QueryWorkingSetEx, the process's working set - a page on
/// the standby list counts as not resident, and prefetch() is what brings those back cheaply). An expert's pages are
/// read together, so they come and go together: a wrong "yes" costs page faults, a wrong "no" a prefetch.
inline bool resident_sampled(const void* p, size_t bytes, int samples = 8) {
if (bytes == 0) return true;
const uintptr_t pg = 4096, a = (uintptr_t) p, span = bytes - 1;
samples = std::max(1, std::min(samples, 16));
#if defined(_WIN32)
PSAPI_WORKING_SET_EX_INFORMATION w[16] = {};
for (int i = 0; i < samples; ++i)
w[i].VirtualAddress = (PVOID) ((a + (samples > 1 ? span / (samples - 1) * i : 0)) & ~(pg - 1));
if (!K32QueryWorkingSetEx(GetCurrentProcess(), w, (DWORD) (samples * sizeof w[0]))) return false;
for (int i = 0; i < samples; ++i)
if (!w[i].VirtualAttributes.Valid) return false;
return true;
#else
for (int i = 0; i < samples; ++i) {
unsigned char v = 0;
const uintptr_t at = (a + (samples > 1 ? span / (samples - 1) * i : 0)) & ~(pg - 1);
if (mincore((void*) at, pg, &v) != 0 || !(v & 1)) return false;
}
return true;
#endif
}
/// prefetch() of the ranges that do not look resident (resident_sampled) - on Windows, where PrefetchVirtualMemory walks
/// every page of a resident range (0.34 ms a 6.3 MB expert matrix on a Strix Halo); Linux's madvise(WILLNEED) on cached
/// pages costs ~1 us a matrix (a Core i5-12600T), less than the residency check (2.5 us): every range there
inline void prefetch_cold(const std::vector<std::pair<const void*, size_t>>& ranges) {
#if defined(_WIN32)
static const bool all = [] { // (DS4_PF_ALL=1: every range, as before)
const char* v = std::getenv("DS4_PF_ALL");
return v != nullptr && std::atoi(v) != 0;
}();
if (all) return prefetch(ranges);
std::vector<std::pair<const void*, size_t>> cold;
for (const auto& x : ranges)
if (!resident_sampled(x.first, x.second)) cold.push_back(x);
prefetch(cold);
#else
prefetch(ranges);
#endif
}
/// Whether [p, p + n) of a file's mapping is in RAM now: every page (Linux, one mincore), sampled pages of the working
/// set (Windows; a page on the standby list counts as not in RAM)
inline bool in_ram(const void* p, size_t n) {
#if defined(_WIN32)
return resident_sampled(p, n, 8);
#else
return resident(p, n);
#endif
}
/// Anonymous memory on NUMA node `node` of `nodes` (node < 0 or nodes < 2: wherever the first touch puts it), on huge
/// pages where the OS gives them; nullptr if it cannot be had.
inline void* anon_alloc(size_t bytes, int node, int nodes) {
#if defined(_WIN32)
if (node >= 0 && nodes > 1)
return VirtualAllocExNuma(GetCurrentProcess(), nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE,
(DWORD) node);
return VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
#else
void* m = ::mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (m == MAP_FAILED) return nullptr;
madvise(m, bytes, MADV_HUGEPAGE);
if (node >= 0 && nodes > 1) {
unsigned long mask[4] = {0, 0, 0, 0};
mask[node / 64] = 1ul << (node % 64);
syscall(SYS_mbind, m, bytes, 2 /* MPOL_BIND */, mask, 256, 0);
}
return m;
#endif
}
/// An address range of `bytes` reserved (no memory behind it yet), and pieces of it made real: the store's arena is one range so a
/// kernel can tell its pointers by [lo, hi). nullptr: it could not be had.
inline void* range_reserve(size_t bytes) {
#if defined(_WIN32)
return VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_READWRITE);
#else
void* m = ::mmap(nullptr, bytes, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
return m == MAP_FAILED ? nullptr : m;
#endif
}
inline bool range_commit(void* p, size_t bytes) {
#if defined(_WIN32)
return VirtualAlloc(p, bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr;
#else
return ::mprotect(p, bytes, PROT_READ | PROT_WRITE) == 0;
#endif
}
/// A committed piece of a reserved range given back to the system (its address range stays reserved)
inline void range_decommit(void* p, size_t bytes) {
#if defined(_WIN32)
VirtualFree(p, bytes, MEM_DECOMMIT);
#else
::madvise(p, bytes, MADV_DONTNEED);
::mprotect(p, bytes, PROT_NONE);
#endif
}
inline void range_release(void* p, size_t bytes) {
if (p == nullptr) return;
#if defined(_WIN32)
(void) bytes;
VirtualFree(p, 0, MEM_RELEASE);
#else
::munmap(p, bytes);
#endif
}
inline void anon_free(void* p, size_t bytes) {
if (p == nullptr) return;
#if defined(_WIN32)
(void) bytes;
VirtualFree(p, 0, MEM_RELEASE);
#else
::munmap(p, bytes);
#endif
}
/// The calling thread, or `t`, on logical CPU `cpu` (Windows: the first 64 CPUs, processor group 0).
inline void pin_self(int cpu) {
#if defined(_WIN32)
if (cpu >= 0 && cpu < 64) SetThreadAffinityMask(GetCurrentThread(), (DWORD_PTR) 1 << cpu);
#else
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
sched_setaffinity(0, sizeof set, &set);
#endif
}
inline void pin_thread(std::thread& t, int cpu) {
#if defined(_WIN32)
if (cpu >= 0 && cpu < 64) SetThreadAffinityMask((HANDLE) t.native_handle(), (DWORD_PTR) 1 << cpu);
#else
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
pthread_setaffinity_np(t.native_handle(), sizeof(set), &set);
#endif
}
#if defined(_WIN32)
/// Each NUMA node's physical cores (the first logical CPU of each), processor group 0 - Windows' answer to
/// /sys/devices/system/node; empty if the OS does not say.
inline std::vector<std::vector<int>> node_cores(bool smt = false) { // (smt: every logical CPU of a core, not its first)
std::vector<std::vector<int>> nodes;
auto query = [](LOGICAL_PROCESSOR_RELATIONSHIP rel, std::vector<uint8_t>& buf) {
DWORD len = 0;
GetLogicalProcessorInformationEx(rel, nullptr, &len);
buf.resize(len);
return len > 0 && GetLogicalProcessorInformationEx(rel, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len);
};
std::vector<uint8_t> nb, cb;
if (!query(RelationNumaNode, nb) || !query(RelationProcessorCore, cb)) return nodes;
std::vector<KAFFINITY> masks;
for (size_t o = 0; o < nb.size();) {
auto* e = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) (nb.data() + o);
if (e->NumaNode.GroupMask.Group == 0) masks.push_back(e->NumaNode.GroupMask.Mask);
o += e->Size;
}
nodes.resize(masks.size());
for (size_t o = 0; o < cb.size();) {
auto* e = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) (cb.data() + o);
if (e->Processor.GroupCount > 0 && e->Processor.GroupMask[0].Group == 0) {
const KAFFINITY m = e->Processor.GroupMask[0].Mask;
int first = -1;
for (int b = 0; b < 64; ++b)
if ((m >> b) & 1) {
first = b;
break;
}
for (size_t n = 0; n < masks.size() && first >= 0; ++n)
if ((masks[n] >> first) & 1) {
nodes[n].push_back(first);
if (smt)
for (int b = first + 1; b < 64; ++b)
if ((m >> b) & 1) nodes[n].push_back(b);
}
}
o += e->Size;
}
nodes.erase(std::remove_if(nodes.begin(), nodes.end(), [](const std::vector<int>& v) { return v.empty(); }),
nodes.end());
for (auto& v : nodes) std::sort(v.begin(), v.end());
return nodes;
}
/// The RAM this process can still get (~0: not known).
inline uint64_t ram_avail() {
MEMORYSTATUSEX s{};
s.dwLength = sizeof(s);
return GlobalMemoryStatusEx(&s) ? (uint64_t) s.ullAvailPhys : ~uint64_t{0};
}
#endif
/// Windows' commit (RAM + page file, what every private allocation is charged to - on an integrated GPU the GPU's
/// own allocations too): the limit, what this process can still commit, the RAM; all ~0 where there is no such limit
/// (Linux overcommits; its RAM is ram_avail's business).
struct Commit {
uint64_t limit = ~uint64_t{0}, avail = ~uint64_t{0}, ram = ~uint64_t{0};
};
inline Commit commit() {
Commit c;
#if defined(_WIN32)
MEMORYSTATUSEX s{};
s.dwLength = sizeof(s);
if (GlobalMemoryStatusEx(&s)) {
c.limit = (uint64_t) s.ullTotalPageFile;
c.avail = (uint64_t) s.ullAvailPageFile;
c.ram = (uint64_t) s.ullTotalPhys;
}
#endif
return c;
}
} // namespace strata::ds4::os
+273
View File
@@ -0,0 +1,273 @@
// Strata. `strata-dsv41 --pack-info`: the pack as a description, before anything is loaded onto a GPU - the type map
// (layer x role), the bytes an expert and a token, the tier sizes, and the tensors whose type has no device kernel (they
// would go to the CPU lane, or stop the load). Host only, no device, no weights read: tensors.txt and ds4.txt are the
// pack's whole description (tools/dsv41/pack_gguf.py). The same report is the first line of every benchmark log.
#include "ds4_packinfo.hpp"
#include "ds4_iq.cuh" // iq::supported / iq::name: the device-type list below is derived from the kernels, not copied
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>
#include <set>
#include <string>
#include <vector>
#if defined(_MSC_VER)
#include <cstring>
#define strtok_r strtok_s
#endif
namespace strata::ds4 {
namespace {
// The ggml block types the device kernels take (ds4_iq.cu's Ty<> / DS4_IQ_SWITCH + ds4_gguf.cu's MXFP4). A name here
// and not in the pack's tensor list is fine; a tensor whose type is not here is the CPU lane's (ggml-cpu's row dots).
// It was a copy of the supported() switch and fell behind when IQ1_S, IQ1_M and IQ4_NL got kernels (2026-10-23), so it is
// now the switch itself, by type name.
bool device_type(const std::string& t) {
static const std::set<std::string> ok = [] {
std::set<std::string> s = {"MXFP4", "TQK6", "TQK7", "TQK5X", "TQK4X", "TQK5T", "TQK4T"}; // ds4_gguf.cu / trellis
for (int ty = 0; ty < 64; ++ty) {
const char* n = gguf::iq::name(ty);
if (n && std::strcmp(n, "?") != 0 && gguf::iq::supported(ty)) s.insert(n);
}
return s;
}();
return ok.count(t) != 0;
}
// The types the dense path reads as they are (ds4_gguf.cu: BF16 / F32 / MXFP8 rows, Q8_0 rows; ds4_iq's GEMV for the
// K-quants is the same device support as the experts').
bool dense_type(const std::string& t) {
return t == "BF16" || t == "F32" || t == "F16" || t == "MXFP8" || t == "Q8_0" || device_type(t);
}
struct Tensor {
std::string dtype;
double bytes = 0;
std::vector<long long> shape;
};
double gb(double b) { return b / 1e9; }
} // namespace
int pack_info(const std::string& dir, std::FILE* out) {
std::map<std::string, std::string> kv;
{
std::ifstream f(dir + "/ds4.txt");
if (!f) {
std::fprintf(out, "pack-info: %s/ds4.txt: not found\n", dir.c_str());
return 1;
}
std::string line;
while (std::getline(f, line)) {
const size_t sp = line.find(' ');
if (sp != std::string::npos) kv[line.substr(0, sp)] = line.substr(sp + 1);
}
}
auto num = [&](const char* k, long long d) {
auto it = kv.find(k);
return it == kv.end() ? d : std::atoll(it->second.c_str());
};
const long long nl = num("num_hidden_layers", 0), ne = num("n_routed_experts", 0), topk = num("num_experts_per_tok", 0);
const long long dim = num("hidden_size", 0), ff = num("moe_intermediate_size", 0), vocab = num("vocab_size", 0);
std::map<std::string, Tensor> t;
std::vector<std::string> files;
std::map<int, double> need; // bytes the pack needs from each file (its largest tensor end)
{
std::FILE* f = std::fopen((dir + "/tensors.txt").c_str(), "r");
if (f == nullptr) {
std::fprintf(out, "pack-info: %s/tensors.txt: not found\n", dir.c_str());
return 1;
}
std::vector<char> buf(1 << 16);
while (std::fgets(buf.data(), (int) buf.size(), f) != nullptr) {
char* s = buf.data();
if (s[0] == 'f') { // file <i> <name>
char name[4096];
int i = 0;
if (std::sscanf(s, "file %d %4095s", &i, name) == 2) {
if ((int) files.size() <= i) files.resize((size_t) i + 1);
files[(size_t) i] = name;
}
continue;
}
if (s[0] != 't') continue;
char* save = nullptr;
::strtok_r(s, " \n", &save);
const char* name = ::strtok_r(nullptr, " \n", &save);
const char* dt = ::strtok_r(nullptr, " \n", &save);
const char* fi = ::strtok_r(nullptr, " \n", &save);
const char* off = ::strtok_r(nullptr, " \n", &save);
const char* nb = ::strtok_r(nullptr, " \n", &save);
if (name == nullptr || dt == nullptr || fi == nullptr || off == nullptr || nb == nullptr) continue;
Tensor x;
x.dtype = dt;
x.bytes = (double) std::strtoull(nb, nullptr, 10);
const int idx = std::atoi(fi);
need[idx] = std::max(need[idx], (double) std::strtoull(off, nullptr, 10) + x.bytes);
while (const char* d = ::strtok_r(nullptr, " \n", &save)) x.shape.push_back(std::atoll(d));
t[name] = std::move(x);
}
std::fclose(f);
}
if (t.empty()) {
std::fprintf(out, "pack-info: %s/tensors.txt: no tensors\n", dir.c_str());
return 1;
}
// the files the pack points at: they must be there, and at least as long as the largest tensor end says (the weights
// live elsewhere; a pack whose model_dir was cleaned up still describes itself perfectly - this is the check)
const std::string md = kv.count("model_dir") ? kv["model_dir"] : "";
int missing = 0;
for (const auto& [i, n] : need) {
const std::string name = (size_t) i < files.size() ? files[(size_t) i] : "";
if (name.empty()) {
std::fprintf(out, " file %d: no name in tensors.txt\n", i);
++missing;
continue;
}
const std::string path = md + "/" + name;
std::FILE* f = std::fopen(path.c_str(), "rb");
if (f == nullptr) {
std::fprintf(out, " MISSING %s (%.2f GB wanted)\n", path.c_str(), n / 1e9);
++missing;
continue;
}
#if defined(_WIN32)
_fseeki64(f, 0, SEEK_END); // (long is 32 bits there: the weights are far past 2 GB)
const long long sz = _ftelli64(f);
#else
std::fseek(f, 0, SEEK_END);
const long long sz = std::ftell(f);
#endif
std::fclose(f);
if ((double) sz + 0.5 < n) {
std::fprintf(out, " SHORT %s: %.2f GB there, %.2f GB wanted\n", path.c_str(), (double) sz / 1e9, n / 1e9);
++missing;
}
}
// ---- the expert map: layer -> role types and bytes an expert
struct Role {
std::string type[3];
double bytes[3] = {0, 0, 0};
bool mixed = false;
int n = 0;
};
std::vector<Role> lay((size_t) nl);
std::map<std::string, long long> type_count; // tensor count a type (the experts' 3 roles)
double experts_bytes = 0;
std::set<std::string> no_kernel;
for (long long il = 0; il < nl; ++il) {
Role& r = lay[(size_t) il];
const std::string pre = "layers." + std::to_string(il) + ".ffn.experts.";
for (long long e = 0; e < ne; ++e) {
const char* role[3] = {"w1", "w3", "w2"};
for (int k = 0; k < 3; ++k) {
auto it = t.find(pre + std::to_string(e) + "." + role[k] + ".weight");
if (it == t.end()) {
std::fprintf(out, "pack-info: %s%s%lld.%s.weight: missing\n", pre.c_str(), "", e, role[k]);
return 1;
}
if (e == 0) {
r.type[k] = it->second.dtype;
r.bytes[k] = it->second.bytes;
} else if (it->second.dtype != r.type[k] || it->second.bytes != r.bytes[k]) {
r.mixed = true;
}
if (e == 0) {
++type_count[it->second.dtype];
if (!device_type(it->second.dtype)) no_kernel.insert("layer " + std::to_string(il) + " " + role[k] + " " + it->second.dtype);
}
}
}
r.n = (int) ne;
experts_bytes += (double) ne * (r.bytes[0] + r.bytes[1] + r.bytes[2]);
}
const double per_expert = nl > 0 ? experts_bytes / ((double) nl * (double) ne) : 0;
// (a token picks `topk` experts a layer: sum over the layers of topk x one expert of that layer)
double token_bytes = 0;
for (long long il = 0; il < nl; ++il) token_bytes += (double) topk * (lay[(size_t) il].bytes[0] + lay[(size_t) il].bytes[1] + lay[(size_t) il].bytes[2]);
const double expert_params = (double) nl * (double) ne * 3.0 * (double) ff * (double) dim;
// ---- the dense side: everything that is not an expert tensor
double dense = 0, dense_embed = 0, dense_head = 0, dense_mtp = 0, dense_vision = 0, dense_engram = 0;
std::set<std::string> dense_types;
for (const auto& [name, x] : t) {
if (name.find(".ffn.experts.") != std::string::npos && name.rfind("layers.", 0) == 0) continue;
dense += x.bytes;
dense_types.insert(x.dtype);
if (name == "embed.weight") dense_embed += x.bytes;
else if (name == "head.weight") dense_head += x.bytes;
else if (name.rfind("mtp.", 0) == 0) dense_mtp += x.bytes;
else if (name.find(".engram.") != std::string::npos) dense_engram += x.bytes;
else if (name.rfind("vision.", 0) == 0 || name.rfind("aligner.", 0) == 0) dense_vision += x.bytes;
if (!dense_type(x.dtype)) no_kernel.insert("dense " + name + " " + x.dtype);
}
// ---- report
std::fprintf(out, "pack-info %s\n", dir.c_str());
std::fprintf(out, " model_dir %s format %s %lld layers x %lld experts, %lld used; dim %lld, ff %lld, vocab %lld\n",
kv.count("model_dir") ? kv["model_dir"].c_str() : "?", kv.count("format") ? kv["format"].c_str() : "?", nl, ne, topk,
dim, ff, vocab);
std::fprintf(out, " layer gate+up down bytes/expert MB/token\n");
for (long long il = 0; il < nl; ++il) {
const Role& r = lay[(size_t) il];
const double eb = r.bytes[0] + r.bytes[1] + r.bytes[2];
std::fprintf(out, " %5lld %-9s %-9s %13.0f %10.2f%s\n", il, r.type[0].c_str(), r.type[2].c_str(), eb,
(double) topk * eb / 1e6, r.mixed ? " (mixed)" : "");
}
std::fprintf(out, " expert tensors by type:");
for (const auto& [ty, n] : type_count) std::fprintf(out, " %s %lld", ty.c_str(), n);
std::fprintf(out, "\n");
std::fprintf(out, " an expert %.2f MB, %lld picks a token: %.3f GB a token\n", per_expert / 1e6, topk, token_bytes / 1e9);
std::fprintf(out, " all experts %.1f GB at %.2f bpw (%.0f G parameters), dense %.2f GB (embed %.2f, head %.2f, mtp %.2f, vision %.2f, engram %.2f)\n",
gb(experts_bytes), expert_params > 0 ? experts_bytes * 8.0 / expert_params : 0.0, expert_params / 1e9, gb(dense),
gb(dense_embed), gb(dense_head), gb(dense_mtp), gb(dense_vision), gb(dense_engram));
std::fprintf(out, " dense types:");
for (const auto& d : dense_types) std::fprintf(out, " %s", d.c_str());
std::fprintf(out, "\n");
// the geometry the engine needs at run time but that is easy to lose in a pack built by another tool: DSpark's block
// size / noise token / markov rank (0 there means it drafts one token a run, i.e. it is off) and the Engram's layers
{
auto kvn = [&](const char* k) {
auto it = kv.find(k);
return it == kv.end() ? 0 : std::atoll(it->second.c_str());
};
const int n_mtp = (int) std::count_if(t.begin(), t.end(), [](const auto& p) { return p.first.rfind("mtp.", 0) == 0; });
const long long nl_eg = num("engram_layer_ids", -1);
std::fprintf(out, " dspark: block_size %lld, noise_token_id %lld, markov_rank %lld, routed experts %lld of %lld%s\n",
num("dspark_block_size", 0), num("dspark_noise_token_id", 0), num("dspark_markov_rank", 0),
num("dspark_n_routed_experts", 0), num("dspark_num_experts_per_tok", 0),
num("dspark_block_size", 0) == 0 ? " <- DSpark cannot draft (block size 0)" : "");
std::fprintf(out, " mtp tensors: %d%s\n", n_mtp, n_mtp == 0 ? " <- no DSpark drafter in the pack" : "");
auto it = kv.find("engram_layer_ids");
std::fprintf(out, " engram layers: %s%s\n", it == kv.end() ? "(none)" : it->second.c_str(),
it == kv.end() ? " <- the Engram tables are not used" : "");
}
if (no_kernel.empty()) {
std::fprintf(out, " no GPU kernel: none (every tensor is a device type)\n");
} else {
std::fprintf(out, " no GPU kernel (%zu): the CPU lane takes them, they cannot go in the VRAM tier\n", no_kernel.size());
int shown = 0;
for (const std::string& s : no_kernel) {
std::fprintf(out, " %s\n", s.c_str());
if (++shown >= 40) {
std::fprintf(out, " ... %zu more\n", no_kernel.size() - (size_t) shown);
break;
}
}
}
if (missing > 0) {
std::fprintf(out, " %d of %zu files missing or short: this pack cannot load (build it again, or point model_dir at "
"the weights)\n", missing, need.size());
return 2;
}
std::fprintf(out, " files: %zu, all present and long enough\n", need.size());
return 0;
}
} // namespace strata::ds4
+13
View File
@@ -0,0 +1,13 @@
// Strata. The pack report (ds4_packinfo.cpp): `strata-dsv41 --pack-info --pack <dir>`. Host only: no device, no weights.
#pragma once
#include <cstdio>
#include <string>
namespace strata::ds4 {
/// Prints the pack's type map, its bytes an expert / a token, its tier sizes and the tensors whose type has no device
/// kernel. 0 when the pack's description was read, non-zero (and a line saying what is missing) otherwise.
int pack_info(const std::string& dir, std::FILE* out);
} // namespace strata::ds4
+237
View File
@@ -0,0 +1,237 @@
// 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_pool.hpp - the DeepSeek engine's CPU workers: run(n, fn) runs fn(0..n-1) on the workers and the caller and
// returns when every job is done. The design is glmfast::Workers' (src/core/glm_fast_state.hpp): one 64-bit ticket
// (generation << 32 | next index) claimed by CAS, so a worker that wakes late for an older batch can never take a job
// of the current one; idle workers spin for a while, then sleep on a condition variable.
#pragma once
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <cstring>
#include <deque>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>
#include "ds4_os.hpp"
#if defined(_MSC_VER)
#include <intrin.h>
#endif
namespace strata::ds4 {
inline void cpu_relax() {
#if defined(_MSC_VER)
_mm_pause();
#elif defined(__x86_64__) || defined(_M_X64)
__builtin_ia32_pause();
#endif
}
class Pool {
public:
explicit Pool(int n, const std::vector<int>& cpus = {}, int spin_us = 200) : spin_us_(spin_us) {
for (int i = 0; i < n; ++i) {
th_.emplace_back([this] { loop(); });
if (!cpus.empty()) os::pin_thread(th_.back(), cpus[(size_t) i % cpus.size()]);
}
}
~Pool() {
quit_.store(true);
{
std::lock_guard<std::mutex> lk(mu_);
}
cv_.notify_all();
for (auto& t : th_) t.join();
}
int size() const { return (int) th_.size() + 1; }
void run(int n, const std::function<void(int)>& fn) {
start(n, fn);
help();
wait();
}
/// The batch goes to the workers; the caller may help() and must wait() before fn goes out of scope. (Two pools
/// - one a NUMA node - run at once this way: start both, help one, wait for both.)
void start(int n, const std::function<void(int)>& fn) {
n_ = n;
if (n <= 0) return;
const uint64_t g = (gen_.load(std::memory_order_relaxed) + 1) & 0xffffffffu;
ticket_.store((g << 32) | 0x7fffffffu, std::memory_order_seq_cst);
fn_ = &fn;
total_.store(n, std::memory_order_release);
done_.store(0, std::memory_order_relaxed);
ticket_.store(g << 32, std::memory_order_release);
gen_.store(g, std::memory_order_release);
if (sleeping_.load(std::memory_order_acquire) > 0) {
std::lock_guard<std::mutex> lk(mu_);
cv_.notify_all();
}
}
void help() {
if (n_ > 0) work(gen_.load(std::memory_order_acquire));
}
void wait() {
if (n_ <= 0) return;
while (done_.load(std::memory_order_acquire) < n_) cpu_relax();
n_ = 0;
}
private:
void work(uint64_t g) {
for (;;) {
uint64_t t = ticket_.load(std::memory_order_acquire);
if ((t >> 32) != g) return;
const int n = total_.load(std::memory_order_acquire);
if ((int) (t & 0xffffffffu) >= n) return;
if (!ticket_.compare_exchange_weak(t, t + 1, std::memory_order_acq_rel)) continue;
(*fn_)((int) (t & 0xffffffffu));
done_.fetch_add(1, std::memory_order_acq_rel);
}
}
void loop() {
uint64_t seen = gen_.load();
for (;;) {
const auto t0 = std::chrono::steady_clock::now();
uint64_t g;
for (;;) {
g = gen_.load(std::memory_order_acquire);
if (g != seen || quit_.load(std::memory_order_relaxed)) break;
cpu_relax();
if (std::chrono::steady_clock::now() - t0 > std::chrono::microseconds(spin_us_)) {
std::unique_lock<std::mutex> lk(mu_);
sleeping_.fetch_add(1);
cv_.wait(lk, [&] { return gen_.load() != seen || quit_.load(); });
sleeping_.fetch_sub(1);
}
}
if (quit_.load()) return;
seen = g;
work(g);
}
}
std::vector<std::thread> th_;
int spin_us_;
int n_ = 0; // the current batch's size (the caller's side)
const std::function<void(int)>* fn_ = nullptr;
alignas(64) std::atomic<uint64_t> ticket_{0};
alignas(64) std::atomic<uint64_t> gen_{0};
alignas(64) std::atomic<int> total_{0};
alignas(64) std::atomic<int> done_{0};
std::atomic<int> sleeping_{0};
std::atomic<bool> quit_{false};
std::mutex mu_;
std::condition_variable cv_;
};
/// File reads on threads of their own, in the order they were pushed, the pusher never waiting: the prompt path's
/// streamed experts (each part of an expert a job), unbuffered where the job has a direct descriptor and its range is
/// not all in the page cache already (the disk straight into dst, the cache neither used nor disturbed), buffered
/// otherwise or when the unbuffered read fails - the bytes land at dst + off % os::kDirectAlign either way. A job's `left` is
/// counted down when it is done (`bad` set if it failed); wait_any() sleeps until some job finished or the timeout.
class IoQueue {
public:
struct Job {
os::fd_t fd = os::kBadFd, dfd = os::kBadFd;
uint64_t off = 0, len = 0;
uint8_t* dst = nullptr;
std::atomic<int>* left = nullptr;
std::atomic<bool>* bad = nullptr;
const uint8_t* mem = nullptr; // non-null: a copy of len bytes from memory to dst instead of a read
const void* map = nullptr; // the range in the file's mapping: all in the page cache, it is read buffered
uint8_t* keep = nullptr; // non-null (a read): the len bytes read copied here as well
std::atomic<bool>* cancel = nullptr; // set before the job starts: it is dropped unread (bad is set, left counted down)
};
explicit IoQueue(int n) {
for (int i = 0; i < n; ++i) th_.emplace_back([this] { loop(); });
}
~IoQueue() {
{
std::lock_guard<std::mutex> lk(mu_);
quit_ = true;
}
cv_.notify_all();
for (auto& t : th_) t.join();
}
/// low: a read that can wait (a guess) - the jobs of the first queue are all taken before any of this one's
void push(const Job* jobs, int n, bool low = false) {
{
std::lock_guard<std::mutex> lk(mu_);
for (int i = 0; i < n; ++i) (low ? ql_ : q_).push_back(jobs[i]);
}
if (n == 1) cv_.notify_one();
else cv_.notify_all();
}
void wait_any(int us) {
std::unique_lock<std::mutex> lk(done_mu_);
const uint64_t seen = done_;
done_cv_.wait_for(lk, std::chrono::microseconds(us), [&] { return done_ != seen; });
}
double busy_ms() const { return busy_us_.load(std::memory_order_relaxed) / 1000.0; }
uint64_t direct_bytes() const { return direct_.load(std::memory_order_relaxed); }
uint64_t buffered_bytes() const { return buffered_.load(std::memory_order_relaxed); }
private:
void loop() {
for (;;) {
Job j;
{
std::unique_lock<std::mutex> lk(mu_);
cv_.wait(lk, [&] { return quit_ || !q_.empty() || !ql_.empty(); });
if (quit_ && q_.empty() && ql_.empty()) return;
std::deque<Job>& qq = q_.empty() ? ql_ : q_;
j = qq.front();
qq.pop_front();
}
if (j.cancel != nullptr && j.cancel->load(std::memory_order_acquire)) { // (dropped unread)
if (j.bad != nullptr) j.bad->store(true, std::memory_order_release);
if (j.left != nullptr) j.left->fetch_sub(1, std::memory_order_acq_rel);
{
std::lock_guard<std::mutex> lk(done_mu_);
++done_;
}
done_cv_.notify_all();
continue;
}
const auto t0 = std::chrono::steady_clock::now();
const uint64_t lead = j.off % os::kDirectAlign;
bool ok = false;
if (j.mem != nullptr) {
std::memcpy(j.dst, j.mem, (size_t) j.len);
ok = true;
} else if (j.dfd != os::kBadFd && !(j.map != nullptr && os::resident(j.map, (size_t) j.len)) &&
os::pread_direct(j.dfd, j.dst, j.len, j.off)) { // (the page cache's ones: buffered, below)
ok = true;
direct_.fetch_add(j.len, std::memory_order_relaxed);
} else if (os::pread_par(j.fd, j.dst + lead, j.len, j.off)) {
ok = true;
buffered_.fetch_add(j.len, std::memory_order_relaxed);
}
if (ok && j.keep != nullptr && j.mem == nullptr) std::memmove(j.keep, j.dst + lead, (size_t) j.len); // (keep may overlap dst: the store reads in place and moves up)
busy_us_.fetch_add((uint64_t) std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - t0).count(),
std::memory_order_relaxed);
if (!ok && j.bad != nullptr) j.bad->store(true, std::memory_order_release);
if (j.left != nullptr) j.left->fetch_sub(1, std::memory_order_acq_rel);
{
std::lock_guard<std::mutex> lk(done_mu_);
++done_;
}
done_cv_.notify_all();
}
}
std::vector<std::thread> th_;
std::mutex mu_, done_mu_;
std::condition_variable cv_, done_cv_;
std::deque<Job> q_, ql_;
uint64_t done_ = 0;
bool quit_ = false;
std::atomic<uint64_t> busy_us_{0}, direct_{0}, buffered_{0};
};
} // namespace strata::ds4
+30
View File
@@ -0,0 +1,30 @@
// 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_q6k.cuh - one value of a ggml Q6_K superblock (256 values, 210 bytes: ql[128] the low 4 bits, qh[64] the
// high 2, scales[16] int8 a 16 values, d F16), as ggml's dequantize_row_q6_K computes it: d * scale * (q - 32), the two
// products in that order in F32 - the same bits (the Engram tables a GGUF may hold in Q6_K).
#pragma once
#include <cuda_fp16.h>
#include <cstdint>
namespace strata::ds4 {
constexpr int kQ6kBytes = 210;
__device__ __forceinline__ float q6k_value(const uint8_t* __restrict__ b, int i) {
const uint8_t* ql = b;
const uint8_t* qh = b + 128;
const int8_t* sc = (const int8_t*) (b + 192);
// (the F16 scale's bits as a half: HIP's headers take no brace-initialized __half_raw from them)
const float d = __half2float(__ushort_as_half((unsigned short) (b[208] | (b[209] << 8))));
const int h = i >> 7, w = i & 127, quarter = w >> 5, l = w & 31; // (ggml's loop: half h, 32-value quarters)
ql += h * 64;
qh += h * 32;
sc += h * 8;
const int lo = quarter & 1 ? ql[l + 32] : ql[l];
const int q = ((quarter & 2 ? lo >> 4 : lo & 0xF) | (((qh[l] >> (2 * quarter)) & 3) << 4)) - 32;
return __fmul_rn(__fmul_rn(d, (float) sc[(l >> 4) + 2 * quarter]), (float) q);
}
} // namespace strata::ds4
+98
View File
@@ -0,0 +1,98 @@
// The kept-conversation (slot) bookkeeping that needs no GPU: a slot's .meta file (identity, size, tokens, checkpoint
// positions) and the choice of which kept conversation a prompt continues, and from where. The engine's serve loop
// (ds4_main.cpp) uses these; tests/dsv41/slot_test.cpp checks them alone.
//
// Slot .meta layout (little endian), "DS4META2":
// u64 magic, u64 identity length, identity bytes, u64 .bin bytes, u64 token count, i32 tokens[],
// u64 checkpoint count (0..4), i64 checkpoints[], u64 magic
// The magic at both ends and the .bin size make a half-written or foreign file refused, never read.
#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <string>
#include <vector>
namespace strata::ds4::slotmeta {
constexpr uint64_t kMagic = 0x324154454d345344ull; // "DS4META2"
// Written under a temporary name and renamed over `path` (an interrupted write leaves no half file).
inline bool write(const std::string& path, const std::string& identity, const std::vector<int32_t>& toks,
uint64_t bytes, const std::vector<int64_t>& cks) {
const std::string tmp = path + ".tmp";
{
std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
const uint64_t il = identity.size(), nt = toks.size(), nc = cks.size();
f.write((const char*) &kMagic, 8);
f.write((const char*) &il, 8);
f.write(identity.data(), (std::streamsize) il);
f.write((const char*) &bytes, 8);
f.write((const char*) &nt, 8);
f.write((const char*) toks.data(), (std::streamsize) (nt * sizeof(int32_t)));
f.write((const char*) &nc, 8);
f.write((const char*) cks.data(), (std::streamsize) (nc * sizeof(int64_t)));
f.write((const char*) &kMagic, 8);
f.flush();
if (!f) return false;
}
std::error_code ec;
std::filesystem::rename(tmp, path, ec);
return !ec;
}
// false: foreign (another identity), damaged, cut short, or not plausible (no tokens, more than max_ctx, a checkpoint
// outside the tokens).
inline bool read(const std::string& path, const std::string& identity, int64_t max_ctx, std::vector<int32_t>& toks,
uint64_t& bytes, std::vector<int64_t>& cks) {
std::ifstream f(path, std::ios::binary);
uint64_t m0 = 0, il = 0, nt = 0, nc = 0, m1 = 0;
if (!f.read((char*) &m0, 8) || m0 != kMagic || !f.read((char*) &il, 8) || il != identity.size()) return false;
std::string id(il, '\0');
if (!f.read(id.data(), (std::streamsize) il) || id != identity) return false;
if (!f.read((char*) &bytes, 8) || !f.read((char*) &nt, 8) || nt == 0 || nt > (uint64_t) max_ctx) return false;
toks.resize(nt);
if (!f.read((char*) toks.data(), (std::streamsize) (nt * sizeof(int32_t))) || !f.read((char*) &nc, 8) || nc > 4)
return false;
cks.resize(nc);
if (!f.read((char*) cks.data(), (std::streamsize) (nc * sizeof(int64_t))) || !f.read((char*) &m1, 8) || m1 != kMagic)
return false;
for (int64_t c : cks)
if (c <= 0 || (uint64_t) c > nt) return false;
return true;
}
// The kept conversation `prompt` continues the furthest, and where: *len is the number of the slot's tokens that are
// the prompt's (0: none). A conversation the prompt continues whole comes back whole (len == its size); one the prompt
// leaves part way - a retried prompt, a history re-rendered without the earlier reasoning - comes back at its latest
// checkpoint the prompt still agrees with. Only a match longer than `floor` (what the model itself can go back to)
// counts. The last prompt token is never covered (a prompt always reads its last token). Ties keep the earlier slot.
struct Cand {
const std::vector<int32_t>* tokens;
const std::vector<int64_t>* cks;
};
inline size_t pick(const std::vector<Cand>& slots, const std::vector<int>& prompt, size_t floor, size_t* len) {
*len = 0;
if (prompt.size() < 2) return SIZE_MAX;
size_t best = SIZE_MAX;
for (size_t i = 0; i < slots.size(); ++i) {
const std::vector<int32_t>& t = *slots[i].tokens;
const size_t lim = std::min(t.size(), prompt.size() - 1);
size_t c = 0;
while (c < lim && t[c] == prompt[c]) ++c;
size_t u = c == t.size() ? c : 0;
if (u == 0)
for (int64_t k : *slots[i].cks)
if ((size_t) k <= c && (size_t) k > u) u = (size_t) k;
if (u > *len && u > floor) {
best = i;
*len = u;
}
}
return best;
}
} // namespace strata::ds4::slotmeta
+530
View File
@@ -0,0 +1,530 @@
// Strata. src/dsv41/ds4_store.hpp - the RAM tier of the DeepSeek-V4.1 routed experts as a cache of its own: whole experts read
// from the model's files by unbuffered requests (the OS page cache neither used nor disturbed), kept in a fixed arena of slots
// that a replacement policy owns, filled on demand (the CPU lane's picks) and ahead of time (the lookahead's guesses).
//
// A slot holds an expert in the engine's blob layout (gate | up | down at the layer's offsets tr[r], the same as a VRAM slot), so
// the CPU lane's rows read it in place and - when the arena is registered with the GPU - the device kernels read it over PCIe
// (zero-copy, 24 GB/s on a 5070) through the same plan pointers as a VRAM expert. An expert is three matrices at three file
// offsets (the GGUF's one tensor a role and layer): each is read aligned (4096) into the slot and moved into place (the read's
// lead of up to 4095 bytes), the blob layout leaving 8192 bytes between matrices (and around the blob) for the aligned spans.
//
// Memory: slots are allocated in chunks as they are first needed (private memory), never past the budget nor past the RAM this
// process can still get less `floor_bytes` (the owner's session and the system keep theirs).
//
// Policy (the slot to give up, among the unpinned, not GPU-visible ones): lru (oldest touch), lfu (lowest decayed hit count).
// A slot whose expert a window is computing is pinned from ensure() to release(); a slot the GPU may read is `visible` until
// sync() takes it back at a window boundary (the GPU idle), which also publishes the newly ready ones.
#pragma once
#include "ds4_os.hpp"
#include "ds4_pool.hpp"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace strata::ds4 {
class ExpertStore {
public:
struct LayerGeo {
int n_exp = 0;
int file[3] = {-1, -1, -1};
uint64_t off[3] = {0, 0, 0}, stride[3] = {0, 0, 0}; // matrix r of expert e: file[r], off[r] + e stride[r]
uint64_t bytes[3] = {0, 0, 0};
uint64_t tr[3] = {0, 0, 0}; // matrix r's place in the blob
uint64_t blob = 0; // the blob's bytes (gaps of 8192 between matrices)
};
enum Policy { kLru = 0, kLfu = 1 };
struct Stats {
std::atomic<int64_t> hits{0}, misses{0}, prefetched{0}, prefetch_used{0}, prefetch_wasted{0}, evictions{0}, fails{0};
std::atomic<int64_t> bytes_read{0}, wait_ns{0}, no_slot{0}, cancelled{0};
};
struct Vis { // a slot the GPU may read from now on (dev != 0), or no longer (dev == 0)
int layer = 0, e = 0;
unsigned long long dev = 0;
};
struct Cfg {
int threads = 8;
size_t budget_bytes = 0; // the arena at most (grown in chunks as slots are first needed)
size_t floor_bytes = 8ull << 30; // RAM left alone
Policy policy = kLru;
float decay = 0.97f; // lfu: heat x decay every `decay_every` accesses of its layer
int decay_every = 240;
std::function<uint64_t()> ram_avail; // the RAM this process can still get (~0: unknown)
// a new chunk of the arena for the GPU to read in place: returns the device address of `host` (null: not visible)
std::function<void*(void* host, size_t bytes)> map_chunk;
std::function<void(void* host)> unmap_chunk;
size_t reserve = 192; // slots kept evictable (not visible) for the window's demand and guesses
int vis_percent = 100; // the share of experts the GPU may take (by a fixed hash): the rest stay the CPU lane's, so both lanes work
};
bool init(const Cfg& c, const std::vector<LayerGeo>& layers, const std::vector<os::fd_t>& dfds, const std::vector<os::fd_t>& pfds) {
cfg_ = c;
geo_ = layers;
dfds_ = dfds;
pfds_ = pfds;
size_t blob = 0;
for (const LayerGeo& g : geo_) blob = std::max<size_t>(blob, g.blob);
slot_bytes_ = (blob + 2 * kSlack + os::kDirectAlign - 1) & ~(size_t) (os::kDirectAlign - 1);
if (blob == 0 || c.budget_bytes < slot_bytes_) return false;
nmax_ = c.budget_bytes / slot_bytes_;
// one reserved range for the whole arena (chunks committed as they are needed), 64 KB aligned chunks
arena_bytes_ = ((nmax_ + kChunk - 1) / kChunk) * kChunk * slot_bytes_;
arena_ = (uint8_t*) os::range_reserve(arena_bytes_);
if (arena_ == nullptr) return false;
slots_.reset(new Slot[nmax_]);
where_.resize(geo_.size());
heat_.resize(geo_.size());
hits_in_layer_.assign(geo_.size(), 0);
for (size_t l = 0; l < geo_.size(); ++l) {
where_[l].assign((size_t) geo_[l].n_exp, -1);
heat_[l].assign((size_t) geo_[l].n_exp, 0.0f);
}
io_.reset(new IoQueue(std::max(1, c.threads)));
grow(); // (the first chunk now: whether the GPU can map it is known from the start)
// DS4_STORE_PREGROW=1 (default on Linux with the GPU mapping, =0 off): the whole arena now. cuMemHostRegister (the GPU mapping of a chunk) taken while a kernel of
// the decode is running waited on it for good on Linux (H100, driver 580): registering all chunks before the first
// kernel avoids it
#if defined(__linux__)
const bool pregrow = cfg_.map_chunk && !(std::getenv("DS4_STORE_PREGROW") != nullptr && std::atoi(std::getenv("DS4_STORE_PREGROW")) == 0); // (Linux: on with the GPU mapping)
#else
const bool pregrow = std::getenv("DS4_STORE_PREGROW") != nullptr && std::atoi(std::getenv("DS4_STORE_PREGROW")) != 0;
#endif
if (pregrow)
while (grow()) {
}
return true;
}
~ExpertStore() {
io_.reset();
for (size_t i = 0; i < chunks_.size(); ++i)
if (cfg_.unmap_chunk && chunk_dev_[i] != nullptr) cfg_.unmap_chunk(chunks_[i].first);
os::range_release(arena_, arena_bytes_);
}
size_t slot_bytes() const { return slot_bytes_; }
size_t slots_allocated() const { return nalloc_; }
size_t slots_max() const { return nmax_; }
const Stats& stats() const { return st_; }
double busy_ms() const { return io_ ? io_->busy_ms() : 0.0; }
static constexpr size_t kSlack = 8192;
/// The slot holding (layer, e) ready to read, or -1. (Any thread; a slot found stays valid while it is pinned or visible.)
int find(int layer, int e) const {
if (layer < 0 || layer >= (int) where_.size()) return -1; // (a layer the store does not cover: the DSpark drafter's)
const int s = where_[(size_t) layer][(size_t) e];
if (s < 0) return -1;
Slot& sp = slots_[(size_t) s];
try_ready(sp);
return sp.state.load(std::memory_order_acquire) == kReady && sp.layer == layer && sp.expert == e ? s : -1;
}
const uint8_t* mat(int slot, int r) const { return slots_[(size_t) slot].base + geo_[(size_t) slots_[(size_t) slot].layer].tr[r]; }
const uint8_t* blob(int slot) const { return slots_[(size_t) slot].base; }
/// The device address of the slot's blob (0: the arena is not mapped for the GPU)
unsigned long long dev_blob(int slot) const {
const size_t c = (size_t) slot / kChunk;
if (c >= chunk_dev_.size() || chunk_dev_[c] == nullptr) return 0;
return (unsigned long long) ((uint8_t*) chunk_dev_[c] + (slots_[(size_t) slot].base - (uint8_t*) chunks_[c].first));
}
/// Makes the experts es[0..n) of `layer` ready and pinned (reading what is not here), waiting for the reads; the
/// caller releases them. False if a read failed or no slot could be had for one (ok[i] says which are fine; the caller
/// reads the others another way).
bool ensure(int layer, const int* es, int n, std::vector<char>& ok) {
ok.assign((size_t) n, 0);
if (layer < 0 || layer >= (int) geo_.size()) return false;
std::vector<int> sl((size_t) n, -1);
{
std::lock_guard<std::mutex> lk(mu_);
for (int i = 0; i < n; ++i) {
const int e = es[i];
touch_heat(layer, e);
int s = where_[(size_t) layer][(size_t) e];
if (s >= 0) {
Slot& sp = slots_[(size_t) s];
try_ready(sp);
if (sp.state.load() == kReady && !sp.prefetch) st_.hits.fetch_add(1, std::memory_order_relaxed);
if (sp.prefetch) st_.prefetch_used.fetch_add(1, std::memory_order_relaxed);
sp.prefetch = false;
sp.pin++;
sp.tick = ++clock_;
sl[(size_t) i] = s;
continue;
}
st_.misses.fetch_add(1, std::memory_order_relaxed);
s = start_fill(layer, e, true);
sl[(size_t) i] = s;
}
}
const auto t0 = std::chrono::steady_clock::now();
bool all = true;
for (int i = 0; i < n; ++i) {
const int s = sl[(size_t) i];
if (s < 0) {
all = false;
continue;
}
Slot& sp = slots_[(size_t) s];
while (sp.left.load(std::memory_order_acquire) > 0) io_->wait_any(2000);
std::lock_guard<std::mutex> lk(mu_);
finish(sp);
if (sp.state.load() == kReady) ok[(size_t) i] = 1;
else {
sp.pin--;
sl[(size_t) i] = -1;
all = false;
}
}
st_.wait_ns.fetch_add(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - t0).count(),
std::memory_order_relaxed);
return all;
}
void release(int layer, const int* es, int n, const std::vector<char>& ok) {
if (layer < 0 || layer >= (int) geo_.size()) return;
std::lock_guard<std::mutex> lk(mu_);
for (int i = 0; i < n; ++i)
if (ok[(size_t) i]) {
const int s = where_[(size_t) layer][(size_t) es[i]];
if (s >= 0 && slots_[(size_t) s].pin > 0) slots_[(size_t) s].pin--;
}
}
/// Starts reading (layer, e) if it is neither here nor on its way (a guess: unpinned, may be given up before it is used).
void prefetch(int layer, int e) {
if (layer < 0 || layer >= (int) geo_.size() || e < 0 || e >= geo_[(size_t) layer].n_exp) return;
if (where_[(size_t) layer][(size_t) e] >= 0) return;
std::lock_guard<std::mutex> lk(mu_);
if (where_[(size_t) layer][(size_t) e] >= 0) return;
if (start_fill(layer, e, false) >= 0) st_.prefetched.fetch_add(1, std::memory_order_relaxed);
}
/// Reads the experts of `list` (layer, expert; hottest first) into free slots and returns when they are in (a start that
/// is already warm: the profile's hottest, so the first tokens find them). The first `list.size()` fit the arena less
/// `leave` slots; returns how many were read.
size_t preload(const std::vector<std::pair<int, int>>& list, size_t leave) {
size_t n = 0;
{
std::lock_guard<std::mutex> lk(mu_);
const size_t room = nmax_ > leave ? nmax_ - leave : 0;
const size_t take = std::min(list.size(), room);
for (size_t k = take; k-- > 0;) { // (coldest first: the hottest get the newest ticks)
const int layer = list[k].first, e = list[k].second;
if (layer < 0 || layer >= (int) geo_.size() || e < 0 || e >= geo_[(size_t) layer].n_exp) continue;
if (where_[(size_t) layer][(size_t) e] >= 0) continue;
const int s = start_fill(layer, e, false);
if (s < 0) break;
slots_[(size_t) s].prefetch = false; // (warm, not a guess)
++n;
}
}
for (size_t i = 0;; ++i) { // until every read is done
bool busy = false;
{
std::lock_guard<std::mutex> lk(mu_);
for (size_t j = 0; j < nalloc_; ++j) {
Slot& sp = slots_[j];
if (sp.state.load(std::memory_order_acquire) != kLoading) continue;
if (sp.left.load(std::memory_order_acquire) > 0) busy = true;
else {
try_ready(sp);
if (sp.state.load(std::memory_order_acquire) == kLoading) finish(sp);
}
}
}
if (!busy) break;
io_->wait_any(5000);
}
return n;
}
/// Guesses still waiting in the queue for a layer the token is past: dropped unread (their slots free once the queue has gone by)
void cancel_stale(int layer_now) {
std::lock_guard<std::mutex> lk(mu_);
for (size_t i = 0; i < nalloc_; ++i) {
Slot& sp = slots_[i];
if (sp.prefetch && sp.pin == 0 && sp.layer >= 0 && sp.layer <= layer_now && sp.state.load(std::memory_order_acquire) == kLoading)
sp.cancel.store(true, std::memory_order_release);
}
}
/// An access the host saw for an expert the GPU computed (keeps it warm in the policy's eyes).
void touch(int layer, int e) {
if (layer < 0 || layer >= (int) where_.size()) return;
std::lock_guard<std::mutex> lk(mu_);
touch_heat(layer, e);
const int s = where_[(size_t) layer][(size_t) e];
if (s >= 0) slots_[(size_t) s].tick = ++clock_;
}
bool gpu_mapped() const { return !chunk_dev_.empty() && chunk_dev_[0] != nullptr; }
/// The arena's address range (the device sees its host pointers as they are when the mapping is the identity)
unsigned long long arena_lo() const { return (unsigned long long) (uintptr_t) arena_; }
unsigned long long arena_hi() const { return (unsigned long long) (uintptr_t) (arena_ + arena_bytes_); }
bool identity_mapped() const {
for (size_t i = 0; i < chunks_.size(); ++i)
if (chunk_dev_[i] != nullptr && chunk_dev_[i] != chunks_[i].first) return false;
return true;
}
size_t max_blob() const { return slot_bytes_ - 2 * kSlack; }
/// At a window boundary (nothing reading the slots; the caller applies `ev` to the device's table before the next window):
/// every ready slot not visible yet becomes visible (`gpu_ok(layer, e)`: false for an expert VRAM holds), and visible
/// slots of the lowest score are taken back until `cfg.reserve` slots can be given up. Returns the number of events.
size_t sync(std::vector<Vis>& ev, const std::function<bool(int, int)>& gpu_ok) {
std::lock_guard<std::mutex> lk(mu_);
size_t nvis = 0, nfree = 0;
for (size_t i = 0; i < nalloc_; ++i) {
Slot& sp = slots_[i];
if (sp.state.load(std::memory_order_acquire) == kLoading && sp.left.load(std::memory_order_acquire) == 0) {
try_ready(sp);
if (sp.state.load(std::memory_order_acquire) == kLoading) finish(sp);
}
const int st = sp.state.load(std::memory_order_acquire);
if (st == kFree) {
++nfree;
continue;
}
if (st != kReady) continue;
if (sp.visible) {
++nvis;
continue;
}
if (sp.pin == 0) ++nfree;
if (sp.pin == 0 && dev_blob((int) i) != 0 && gpu_ok(sp.layer, sp.expert) && !sp.prefetch && vis_hash(sp.layer, sp.expert) < cfg_.vis_percent) {
sp.visible = true;
++nvis;
if (sp.pin == 0) --nfree;
ev.push_back({sp.layer, sp.expert, dev_blob((int) i)});
}
}
// give slots back until the reserve is there: the visible ones with the lowest score
if (nfree < cfg_.reserve && nvis > 0) {
std::vector<std::pair<double, size_t>> cand;
cand.reserve(nvis);
for (size_t i = 0; i < nalloc_; ++i)
if (slots_[i].visible && slots_[i].state.load(std::memory_order_acquire) == kReady) cand.push_back({score(slots_[i]), i});
const size_t want = std::min(cand.size(), cfg_.reserve - nfree);
std::partial_sort(cand.begin(), cand.begin() + (long) want, cand.end());
for (size_t k = 0; k < want; ++k) {
Slot& sp = slots_[cand[k].second];
sp.visible = false;
ev.push_back({sp.layer, sp.expert, 0ull});
}
}
return ev.size();
}
/// RAM is short: gives back whole chunks from the end of the arena (their experts forgotten) - up to `want`, stopping at one
/// with a slot in use (pinned, loading, or GPU-visible). Returns the chunks given back.
size_t shrink_chunks(size_t want) {
std::lock_guard<std::mutex> lk(mu_);
size_t done = 0;
while (done < want && !chunks_.empty()) {
const size_t c = chunks_.size() - 1, first = c * kChunk;
bool busy = false;
for (size_t i = first; i < nalloc_ && !busy; ++i) {
Slot& sp = slots_[i];
if (sp.state.load(std::memory_order_acquire) == kLoading && sp.left.load(std::memory_order_acquire) == 0) { // (read by now)
try_ready(sp);
if (sp.state.load(std::memory_order_acquire) == kLoading) finish(sp);
}
busy = sp.pin > 0 || sp.visible || sp.state.load(std::memory_order_acquire) == kLoading;
}
if (busy) break;
for (size_t i = first; i < nalloc_; ++i) {
Slot& sp = slots_[i];
if (sp.layer >= 0 && sp.expert >= 0) {
where_[(size_t) sp.layer][(size_t) sp.expert] = -1;
st_.evictions.fetch_add(1, std::memory_order_relaxed);
}
sp.layer = sp.expert = -1;
sp.prefetch = false;
sp.state.store(kFree, std::memory_order_release);
sp.base = nullptr;
}
if (cfg_.unmap_chunk && chunk_dev_[c] != nullptr) cfg_.unmap_chunk(chunks_[c].first);
os::range_decommit(chunks_[c].first, chunks_[c].second);
chunks_.pop_back();
chunk_dev_.pop_back();
nalloc_ = first;
free_hint_ = std::min(free_hint_, first);
++done;
++shrunk_;
}
return done;
}
size_t shrunk() const { return shrunk_; }
/// An expert VRAM took over: no longer a visible slot
void unmark(int layer, int e) {
if (layer < 0 || layer >= (int) where_.size()) return;
std::lock_guard<std::mutex> lk(mu_);
const int s = where_[(size_t) layer][(size_t) e];
if (s >= 0) slots_[(size_t) s].visible = false;
}
size_t visible_count() const {
size_t n = 0;
for (size_t i = 0; i < nalloc_; ++i) n += slots_[i].visible ? 1 : 0;
return n;
}
private:
static constexpr int kFree = 0, kLoading = 1, kReady = 2, kFailed = 3;
static constexpr size_t kChunk = 64; // slots a chunk of the arena
struct Slot {
uint8_t* base = nullptr; // the blob's first byte
int layer = -1, expert = -1, pin = 0;
bool prefetch = false, visible = false;
std::atomic<int> state{kFree}, left{0};
std::atomic<bool> bad{false}, cancel{false};
uint64_t tick = 0;
};
static int vis_hash(int layer, int e) { return (int) (((unsigned) layer * 2654435761u + (unsigned) e * 40503u) >> 7) % 100; }
double score(const Slot& sp) const {
if (cfg_.policy == kLru) return (double) sp.tick;
return (double) heat_[(size_t) sp.layer][(size_t) sp.expert] + 1e-9 * (double) sp.tick;
}
void touch_heat(int layer, int e) {
heat_[(size_t) layer][(size_t) e] += 1.0f;
if (cfg_.policy != kLru && ++hits_in_layer_[(size_t) layer] % (uint64_t) cfg_.decay_every == 0)
for (float& h : heat_[(size_t) layer]) h *= cfg_.decay; // (a linear pass over 384 floats every 240 accesses of that layer)
}
// a slot for (layer, e) and its reads started; -1 if there is none to be had. mu_ held.
int start_fill(int layer, int e, bool demand) {
int s = take_slot(demand);
if (s < 0) {
st_.no_slot.fetch_add(1, std::memory_order_relaxed);
return -1;
}
Slot& sp = slots_[(size_t) s];
if (sp.layer >= 0 && sp.expert >= 0) {
where_[(size_t) sp.layer][(size_t) sp.expert] = -1;
if (sp.prefetch) st_.prefetch_wasted.fetch_add(1, std::memory_order_relaxed);
st_.evictions.fetch_add(1, std::memory_order_relaxed);
}
sp.layer = layer;
sp.expert = e;
sp.pin = demand ? 1 : 0;
sp.prefetch = !demand;
sp.visible = false;
sp.tick = ++clock_;
sp.state.store(kLoading, std::memory_order_release);
sp.bad.store(false);
sp.cancel.store(false);
sp.left.store(3, std::memory_order_release);
where_[(size_t) layer][(size_t) e] = s;
const LayerGeo& g = geo_[(size_t) layer];
IoQueue::Job jobs[3];
for (int r = 0; r < 3; ++r) {
const uint64_t off = g.off[r] + (uint64_t) e * g.stride[r];
const uint64_t lead = off % os::kDirectAlign;
uint8_t* fin = sp.base + g.tr[r]; // where the matrix belongs
// the aligned read lands the file's byte `off` at dst + lead: dst is fin - lead rounded down to 4096 (its span spills
// under 4096 bytes either way into the blob's gaps), the matrix is then moved up to fin
uint8_t* dst = (uint8_t*) ((uintptr_t) (fin - lead) & ~(uintptr_t) (os::kDirectAlign - 1));
IoQueue::Job& j = jobs[r];
j.fd = pfds_[(size_t) g.file[r]];
j.dfd = dfds_[(size_t) g.file[r]];
j.off = off;
j.len = g.bytes[r];
j.dst = dst;
j.keep = fin;
j.left = &sp.left;
j.bad = &sp.bad;
j.cancel = demand ? nullptr : &sp.cancel;
}
st_.bytes_read.fetch_add((int64_t) (g.bytes[0] + g.bytes[1] + g.bytes[2]), std::memory_order_relaxed);
io_->push(jobs, 3, !demand); // (a guess waits behind every demand read)
return s;
}
// loading -> ready once its reads are done and whole (lock-free; a failed one is cleaned up by finish / take_slot)
void try_ready(Slot& sp) const {
int want = kLoading;
if (sp.left.load(std::memory_order_acquire) == 0 && !sp.bad.load(std::memory_order_acquire))
sp.state.compare_exchange_strong(want, kReady, std::memory_order_acq_rel);
}
void finish(Slot& sp) { // mu_ held; reads done
if (sp.state.load() != kLoading) return;
if (sp.bad.load()) {
where_[(size_t) sp.layer][(size_t) sp.expert] = -1;
sp.layer = sp.expert = -1;
sp.state.store(kFree, std::memory_order_release);
sp.prefetch = false;
if (sp.cancel.load()) st_.cancelled.fetch_add(1, std::memory_order_relaxed);
else st_.fails.fetch_add(1, std::memory_order_relaxed);
return;
}
sp.state.store(kReady, std::memory_order_release);
}
bool grow() {
if (nalloc_ >= nmax_) return false;
const size_t n = std::min(kChunk, nmax_ - nalloc_);
const size_t bytes = n * slot_bytes_;
const uint64_t avail = cfg_.ram_avail ? cfg_.ram_avail() : ~uint64_t{0};
if (avail != ~uint64_t{0} && avail < bytes + cfg_.floor_bytes) return false;
void* p = arena_ + nalloc_ * slot_bytes_;
if (!os::range_commit(p, bytes)) return false;
chunks_.push_back({p, bytes});
void* dev = cfg_.map_chunk ? cfg_.map_chunk(p, bytes) : nullptr;
chunk_dev_.push_back(dev);
for (size_t i = 0; i < n; ++i) slots_[nalloc_ + i].base = (uint8_t*) p + i * slot_bytes_ + kSlack;
nalloc_ += n;
return true;
}
// the slot to give up (or a free one): the policy's lowest among the unpinned, not visible, ready ones. mu_ held.
int take_slot(bool demand) {
for (size_t i = free_hint_; i < nalloc_; ++i)
if (slots_[i].state.load(std::memory_order_acquire) == kFree) {
free_hint_ = i + 1;
return (int) i;
}
if (grow()) return take_slot(demand);
int best = -1;
double bv = 0;
for (size_t i = 0; i < nalloc_; ++i) {
Slot& sp = slots_[i];
if (sp.state.load(std::memory_order_acquire) == kLoading && sp.left.load(std::memory_order_acquire) == 0) {
try_ready(sp);
if (sp.state.load(std::memory_order_acquire) == kLoading) finish(sp);
if (sp.state.load(std::memory_order_acquire) == kFree) {
free_hint_ = std::min(free_hint_, i);
return (int) i;
}
}
if (sp.pin > 0 || sp.visible || sp.state.load(std::memory_order_acquire) != kReady) continue;
const double v = score(sp);
if (best < 0 || v < bv) {
best = (int) i;
bv = v;
}
}
if (best < 0) return -1;
free_hint_ = std::min<size_t>(free_hint_, (size_t) best);
return best;
}
Cfg cfg_;
std::vector<LayerGeo> geo_;
std::vector<os::fd_t> dfds_, pfds_;
size_t slot_bytes_ = 0, nmax_ = 0, nalloc_ = 0, free_hint_ = 0, arena_bytes_ = 0;
uint8_t* arena_ = nullptr;
size_t shrunk_ = 0;
std::unique_ptr<Slot[]> slots_;
std::vector<std::pair<void*, size_t>> chunks_;
std::vector<void*> chunk_dev_;
std::vector<std::vector<int>> where_;
std::vector<std::vector<float>> heat_;
std::vector<uint64_t> hits_in_layer_;
uint64_t clock_ = 0;
std::mutex mu_;
std::unique_ptr<IoQueue> io_;
Stats st_;
};
} // namespace strata::ds4
+539
View File
@@ -0,0 +1,539 @@
// Strata. The trellis routed experts (TQK6 / TQK7 / TQK5X / TQK4X / TQK5T / TQK4T, ds4_iq.cuh's is_tq) on the device for the
// DeepSeek-V4.1 engine path. The weights stay as the file has them (a row of k values = k / 128 blocks of {fp16 d; 4 K stream
// bytes}); the blob in VRAM is the file's bytes, so the expert cache, the tensor-parallel cuts and the CPU lane read the same
// layout. Arithmetic as the CPU lane's (ds4_tq_cpu.cpp): the activations are int8 with an F32 scale per 32 values (the
// engine's q8_quant), the weights exact (fp16 codebook values times the block's fp16 scale); the sums are F32.
//
// gfx12 (RDNA4, R9700): v_wmma_f32_16x16x16_f16. The weights are the B operand (16 rows of a tile = the 16 columns, a lane
// holds one row's 8 consecutive k), the activations the A operand (16 entries = the 16 rows, split x = hi + lo in two fp16
// so the product keeps ~2^-22), D[entry][weight row] in F32: a lane holds the entries 8 kg .. 8 kg + 7 of its row, so the
// block scale d is the lane's own. Lane l = r + 16 kg owns row r and the 16 steps 16 kg .. 16 kg + 15 of every block, whose
// 15-bit states are one 128-bit window of the stream (the tile code of tools/dsv41_lab/wmma_emu.hpp, checked there against a
// double reference and on the card by tests/dsv41/tqw_hip_test.cpp). Elsewhere the same lane mapping in plain FMAs.
#include "ds4_iq.cuh"
#include <cuda_fp16.h>
#include "ggml-common-tq.h" // tq_lut_f16 (the 2048-point codebook as fp16 bit patterns, __device__)
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#if defined(STRATA_USE_HIP) && !defined(DS4_TQ_PORTABLE) && (defined(__GFX12__) || defined(__gfx1200__) || defined(__gfx1201__))
#define DS4_TQ_WMMA 1
#endif
#if !defined(STRATA_USE_HIP) && defined(__CUDACC__) // (HIP's non-sync shuffle name, for the portable lane on CUDA)
#define __shfl_xor(v, m) __shfl_xor_sync(0xffffffffu, (v), (m))
#endif
namespace strata::ds4::gguf::iq::tq {
namespace {
constexpr int kWaves = 4, kThreads = kWaves * 32; // a block: 4 waves, a wave = one 16-row tile of each matrix
constexpr int kTileRows = 16;
constexpr int kMaxEnt = 16; // entries (columns) a pass
#if defined(DS4_TQ_WMMA)
typedef _Float16 half8_t __attribute__((ext_vector_type(8)));
typedef float float8_t __attribute__((ext_vector_type(8)));
#endif
constexpr bool computed_code(int type) { return type == kTQK5X || type == kTQK4X; }
// ---------------------------------------------------------------- the codebook and the stream
// a step's 15-bit state -> the four weights as two words of two fp16 (lo, hi): w0 w1 | w2 w3
template <bool COMPUTED>
__device__ __forceinline__ void step_words(const uint32_t* lut, uint32_t s, uint32_t& w0, uint32_t& w1) {
if (COMPUTED) {
w0 = ((s * 89226354u + 64248484u) & 0x8FFF8FFFu) ^ 0x3B603B60u;
w1 = ((s * 0x9E3779B1u + 0x7F4A7C15u) & 0x8FFF8FFFu) ^ 0x3B603B60u;
} else {
const uint32_t x = s * 0x9e3779b1u;
w0 = lut[x >> 21];
w1 = lut[(x >> 10) & 2047u];
}
}
__device__ __forceinline__ float half_bits_f(uint32_t b) { return __half2float(__ushort_as_half((unsigned short) b)); }
// the 128-bit window of a lane's 16 steps in one block record: record = {u16 d; stream}, lane half kg takes stream bits
// [(16 - 16 kg) K, (32 - 16 kg) K) plus the 15 - K bits after them (circular), so state(u), u = 0..15, is the 15 bits at
// (15 - u) K of the window.
template <int K>
__device__ __forceinline__ void stream_window(const uint8_t* rec, int kg, uint64_t& lo, uint64_t& hi) {
const uint16_t* st = (const uint16_t*) (rec + 2);
constexpr int NW = (15 * K + 15 + 15) / 16; // u16 words that hold 15 K + 15 bits
uint64_t w[2] = {0ull, 0ull};
if (kg == 1) {
#pragma unroll
for (int i = 0; i < NW; ++i) w[i >> 2] |= (uint64_t) st[i] << (16 * (i & 3));
} else { // the stream's upper half [16 K, 32 K) = K words; the bits past its end wrap to the stream's start
const uint16_t* up = st + K;
#pragma unroll
for (int i = 0; i < K; ++i) w[i >> 2] |= (uint64_t) up[i] << (16 * (i & 3));
const uint64_t wrap = (uint64_t) st[0] & ((1ull << (15 - K)) - 1ull); // 15 - K <= 11 bits: inside word 0
const int p = 16 * K;
w[p >> 6] |= wrap << (p & 63); // (p & 63) + 15 - K <= 56: never past the word
}
lo = w[0];
hi = w[1];
}
__device__ __forceinline__ uint32_t state_at(uint64_t lo, uint64_t hi, int pos) { // 15 bits at bit pos of the 128-bit window
uint64_t v;
if (pos + 15 <= 64) v = lo >> pos;
else if (pos >= 64) v = hi >> (pos - 64);
else v = (lo >> pos) | (hi << (64 - pos));
return (uint32_t) v & 0x7fffu;
}
// ---------------------------------------------------------------- activations: where a lane's 8 values of an entry come from
// Each loader: valid(m) says entry m (this pass's column) exists; load8(m, k0, v) the 8 values k0..k0+7 as F32.
struct ActQ8 { // int8 rows with an F32 scale a 32: entry m = row rows[m] of q (n values a row), scales d (n / 32 a row)
const int8_t* q;
const float* d;
const int* rows;
int n;
__device__ __forceinline__ void load8(int m, int k0, float* v) const {
const size_t r = (size_t) rows[m];
const int2 w = *(const int2*) (q + r * n + k0);
const float sc = d[r * (n / 32) + (k0 >> 5)];
const int8_t* b = (const int8_t*) &w;
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = (float) b[j] * sc;
}
};
struct ActF32 { // F32 rows: entry m = row rows[m] (ld floats a row)
const float* x;
const int* rows;
size_t ld;
__device__ __forceinline__ void load8(int m, int k0, float* v) const {
const float4* p = (const float4*) (x + (size_t) rows[m] * ld + k0);
const float4 a = p[0], b = p[1];
v[0] = a.x; v[1] = a.y; v[2] = a.z; v[3] = a.w; v[4] = b.x; v[5] = b.y; v[6] = b.z; v[7] = b.w;
}
};
struct ActF16 { // F16 rows: entry m = row rows[m] (ld halves a row)
const uint16_t* x;
const int* rows;
size_t ld;
__device__ __forceinline__ void load8(int m, int k0, float* v) const {
const uint4 w = *(const uint4*) (x + (size_t) rows[m] * ld + k0);
const uint32_t u[4] = {w.x, w.y, w.z, w.w};
#pragma unroll
for (int j = 0; j < 4; ++j) {
v[2 * j] = half_bits_f(u[j] & 0xffffu);
v[2 * j + 1] = half_bits_f(u[j] >> 16);
}
}
};
// ---------------------------------------------------------------- the stream window by 32-bit loads
// The same 128-bit window as stream_window, from aligned 32-bit loads (a record is 2 + 4 K bytes: its scale, then the stream, at
// any 2-byte alignment): the array starts at the 4-byte floor of the record, the stream at bit 16 or 32 of it. Loads past the
// end of the record are skipped (the window bits above what a lane needs are junk anyway).
template <int K>
__device__ __forceinline__ void stream_window_u32(const uint8_t* rec, int kg, uint64_t& lo, uint64_t& hi) {
constexpr int bsz = 2 + 4 * K;
const uintptr_t ad = (uintptr_t) rec;
const uint32_t* pa = (const uint32_t*) (ad & ~(uintptr_t) 3);
const int off = 16 + 8 * (int) (ad & 3); // the stream's first bit in the array: 16 or 32
const int start = off + (kg ? 0 : 16 * K);
const int w0 = start >> 5, s = start & 31;
const int nwords = (int) (((ad & 3) + bsz + 3) >> 2); // words that hold the record
uint32_t v[5];
#pragma unroll
for (int i = 0; i < 5; ++i) v[i] = (w0 + i < nwords) ? pa[w0 + i] : 0u;
uint32_t r[4];
#pragma unroll
for (int i = 0; i < 4; ++i) r[i] = (uint32_t) ((((uint64_t) v[i + 1] << 32) | v[i]) >> s);
lo = ((uint64_t) r[1] << 32) | r[0];
hi = ((uint64_t) r[3] << 32) | r[2];
if (!kg) { // the upper half [16 K, 32 K) of the stream (16 K >= 64 bits); the bits past its end wrap to the stream's start
hi &= (1ull << (16 * K - 64)) - 1ull;
const uint32_t first = off == 16 ? (pa[0] >> 16) : pa[1];
const uint64_t wrap = (uint64_t) first & ((1ull << (15 - K)) - 1ull);
const int p = 16 * K - 64;
hi |= wrap << p;
}
}
// ---------------------------------------------------------------- NM 16-row tiles (matrices sharing the activations) over up to 16 entries
// acc_out[mi][i] (i < 8) = D[entry 8 kg + i][row r] of matrix mi's tile: sum over the row's k values of x_entry * w, k % 128 == 0.
// wrows[mi]: the tile's row r (this lane's) of matrix mi in the blob; nblk blocks. The activation fragments are made once for all NM.
template <int K, bool COMPUTED, int NM, bool WORDS, class Act>
__device__ __forceinline__ void tile_dot(const uint8_t* const* wrows, int nblk, const uint32_t* lut, const Act& act, int ne,
float (*acc_out)[8]) {
constexpr int bsz = 2 + 4 * K;
const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4;
float tot[NM][8];
#pragma unroll
for (int mi = 0; mi < NM; ++mi)
#pragma unroll
for (int i = 0; i < 8; ++i) tot[mi][i] = 0.0f;
const bool have = r < ne; // this lane's A rows (the entry m = r)
for (int b = 0; b < nblk; ++b) {
float d[NM];
uint64_t lo[NM], hi[NM];
#pragma unroll
for (int mi = 0; mi < NM; ++mi) {
const uint8_t* rec = wrows[mi] + (size_t) b * bsz;
d[mi] = half_bits_f(*(const uint16_t*) rec);
if (WORDS) stream_window_u32<K>(rec, kg, lo[mi], hi[mi]);
else stream_window<K>(rec, kg, lo[mi], hi[mi]);
}
#if defined(DS4_TQ_WMMA)
float8_t acc[NM];
#pragma unroll
for (int mi = 0; mi < NM; ++mi) acc[mi] = float8_t{0, 0, 0, 0, 0, 0, 0, 0};
#pragma unroll
for (int m = 0; m < 8; ++m) {
half8_t ah, al;
{
float v[8];
if (have) act.load8(r, b * 128 + 64 * kg + 8 * m, v);
else {
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = 0.0f;
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
const _Float16 h = (_Float16) v[j];
ah[j] = h;
al[j] = (_Float16) (v[j] - (float) h);
}
}
#pragma unroll
for (int mi = 0; mi < NM; ++mi) {
half8_t wf;
#pragma unroll
for (int s2 = 0; s2 < 2; ++s2) {
const int u = 2 * m + s2;
uint32_t w0, w1;
step_words<COMPUTED>(lut, state_at(lo[mi], hi[mi], (15 - u) * K), w0, w1);
wf[4 * s2 + 0] = __builtin_bit_cast(_Float16, (uint16_t) (w0 & 0xffffu));
wf[4 * s2 + 1] = __builtin_bit_cast(_Float16, (uint16_t) (w0 >> 16));
wf[4 * s2 + 2] = __builtin_bit_cast(_Float16, (uint16_t) (w1 & 0xffffu));
wf[4 * s2 + 3] = __builtin_bit_cast(_Float16, (uint16_t) (w1 >> 16));
}
acc[mi] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(ah, wf, acc[mi]); // D[m = entry][n = weight row]
acc[mi] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(al, wf, acc[mi]);
}
}
#pragma unroll
for (int mi = 0; mi < NM; ++mi)
#pragma unroll
for (int i = 0; i < 8; ++i) tot[mi][i] += d[mi] * acc[mi][i];
#else
// plain FMAs: this lane's row r, its 64 weights of the block against every entry (lane r + 16 kg' sums the halves)
float part[NM][kMaxEnt];
#pragma unroll
for (int mi = 0; mi < NM; ++mi)
#pragma unroll
for (int e = 0; e < kMaxEnt; ++e) part[mi][e] = 0.0f;
#pragma unroll
for (int m = 0; m < 8; ++m) {
float w[NM][8];
#pragma unroll
for (int mi = 0; mi < NM; ++mi)
#pragma unroll
for (int s2 = 0; s2 < 2; ++s2) {
uint32_t w0, w1;
step_words<COMPUTED>(lut, state_at(lo[mi], hi[mi], (15 - (2 * m + s2)) * K), w0, w1);
w[mi][4 * s2 + 0] = half_bits_f(w0 & 0xffffu);
w[mi][4 * s2 + 1] = half_bits_f(w0 >> 16);
w[mi][4 * s2 + 2] = half_bits_f(w1 & 0xffffu);
w[mi][4 * s2 + 3] = half_bits_f(w1 >> 16);
}
#pragma unroll
for (int e = 0; e < kMaxEnt; ++e)
if (e < ne) {
float v[8];
act.load8(e, b * 128 + 64 * kg + 8 * m, v);
#pragma unroll
for (int mi = 0; mi < NM; ++mi)
#pragma unroll
for (int j = 0; j < 8; ++j) part[mi][e] = fmaf(w[mi][j], v[j], part[mi][e]);
}
}
// entries 0..7 into tot[i] of the kg = 0 lane, 8..15 of the kg = 1 lane, so the output indexing matches the WMMA's
#pragma unroll
for (int mi = 0; mi < NM; ++mi)
#pragma unroll
for (int i = 0; i < 8; ++i) {
const float p0 = part[mi][i], p1 = part[mi][8 + i];
const float q0 = __shfl_xor_sync(0xffffffffu, p0, 16), q1 = __shfl_xor_sync(0xffffffffu, p1, 16);
tot[mi][i] += d[mi] * (kg == 0 ? p0 + q0 : p1 + q1);
}
#endif
}
#pragma unroll
for (int mi = 0; mi < NM; ++mi)
#pragma unroll
for (int i = 0; i < 8; ++i) acc_out[mi][i] = tot[mi][i];
}
__device__ __forceinline__ float swiglu(float gv, float uv, float limit) { // ds4_iq.cu's
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);
}
template <int K, bool COMPUTED>
__device__ __forceinline__ void load_lut(uint32_t* lut) {
if (!COMPUTED) {
// the table as the CPU decoder has it (tq_cpu.cpp's int16 state table): fp16 * 2^13 rounded half away from zero, over
// 2^13 - exact for values >= 2^-3 and within 2^-14 below; the result is still an exact fp16 (fewer significant bits)
for (int i = threadIdx.x; i < 2048; i += blockDim.x) {
uint32_t pair = 0;
#pragma unroll
for (int j = 0; j < 2; ++j) {
const float v = half_bits_f(tq_lut_f16[2 * i + j]) * 8192.0f;
const int n = (int) (v < 0.0f ? v - 0.5f : v + 0.5f);
pair |= (uint32_t) __half_as_ushort(__float2half_rn((float) n / 8192.0f)) << (16 * j);
}
lut[i] = pair;
}
__syncthreads();
}
}
// ---------------------------------------------------------------- token / window experts
__device__ __forceinline__ bool group_of(const Args& 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 / 64, groups): a wave = a 16-row tile of the gate and of the up of the group's expert, 16 entries a pass
template <int K, bool COMPUTED, bool WORDS>
__global__ void __launch_bounds__(kThreads) gate_up_kernel(const Args a) {
__shared__ uint32_t lut[COMPUTED ? 1 : 2048];
__shared__ int ent[kMaxEnt], xr[kMaxEnt];
const uint8_t* blob;
int m0, m1;
if (!group_of(a, blockIdx.y, blob, m0, m1)) return; // (uniform)
load_lut<K, COMPUTED>(lut);
const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4, wave = threadIdx.x >> 5;
const int tile = blockIdx.x * kWaves + wave;
const int row = tile * kTileRows + r;
const size_t rb = (size_t) (a.n_embd / 128) * (2 + 4 * K);
const uint8_t* g = blob + a.tr[0] + (size_t) row * rb;
const uint8_t* u = blob + a.tr[1] + (size_t) row * rb;
for (int mm = m0; mm < m1; mm += kMaxEnt) {
const int ne = min(kMaxEnt, m1 - mm);
__syncthreads();
if ((int) threadIdx.x < ne) {
const int e = a.grp_ptr != nullptr ? a.grp_ent[mm + threadIdx.x] : mm + threadIdx.x;
ent[threadIdx.x] = e;
xr[threadIdx.x] = a.grp_ptr != nullptr ? e >> 3 : 0;
}
__syncthreads();
if (tile * kTileRows >= a.n_ff) continue;
const ActQ8 act{a.xq, a.xd, xr, a.n_embd};
const uint8_t* wr[2] = {g, u};
float gu[2][8];
tile_dot<K, COMPUTED, 2, WORDS>(wr, a.n_embd / 128, lut, act, ne, gu);
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int m = 8 * kg + i;
if (m < ne) a.h[(size_t) ent[m] * a.n_ff + row] = swiglu(gu[0][i], gu[1][i], a.limit);
}
}
}
// grid (n_embd / 64, groups): the down's tile of a wave against the entries' int8 h
template <int K, bool COMPUTED, bool WORDS>
__global__ void __launch_bounds__(kThreads) down_kernel(const Args a) {
__shared__ uint32_t lut[COMPUTED ? 1 : 2048];
__shared__ int ent[kMaxEnt];
const uint8_t* blob;
int m0, m1;
if (!group_of(a, blockIdx.y, blob, m0, m1)) return;
load_lut<K, COMPUTED>(lut);
const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4, wave = threadIdx.x >> 5;
const int tile = blockIdx.x * kWaves + wave;
const int row = tile * kTileRows + r;
const size_t rb = (size_t) (a.n_ff / 128) * (2 + 4 * K);
const uint8_t* d = blob + a.tr[2] + (size_t) row * rb;
for (int mm = m0; mm < m1; mm += kMaxEnt) {
const int ne = min(kMaxEnt, m1 - mm);
__syncthreads();
if ((int) threadIdx.x < ne) ent[threadIdx.x] = a.grp_ptr != nullptr ? a.grp_ent[mm + threadIdx.x] : mm + threadIdx.x;
__syncthreads();
if (tile * kTileRows >= a.n_embd) continue;
const ActQ8 act{a.hq, a.hd, ent, a.n_ff};
const uint8_t* wr[1] = {d};
float dd[1][8];
tile_dot<K, COMPUTED, 1, WORDS>(wr, a.n_ff / 128, lut, act, ne, dd);
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int m = 8 * kg + i;
if (m < ne) a.part[(size_t) ent[m] * a.n_embd + row] = dd[0][i];
}
}
}
// ---------------------------------------------------------------- the prompt path's sets
// grid (n_ff / 64, chunks of 16 rows, n_exp): expert e = blockIdx.z owns the sorted rows [bounds[e], bounds[e + 1]); local
// row = sorted row - row0. gate / up: F32 x[idx[local]] (ldx) -> F16 swiglu h[local * ldo + c]; down: F16 xh[local] (ldx) ->
// F32 y[local * ldo + c].
template <int K, bool COMPUTED, bool GATE_UP, bool WORDS>
__global__ void __launch_bounds__(kThreads) set_kernel(const SetArgs a) {
__shared__ uint32_t lut[COMPUTED ? 1 : 2048];
__shared__ int rowsel[kMaxEnt];
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.y * kMaxEnt;
if (r0 >= hi) return; // (uniform)
load_lut<K, COMPUTED>(lut);
const int ne = min(kMaxEnt, hi - r0);
const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4, wave = threadIdx.x >> 5;
const int N = GATE_UP ? a.n_ff : a.n_embd, Kin = GATE_UP ? a.n_embd : a.n_ff;
const int tile = blockIdx.x * kWaves + wave;
const int row = tile * kTileRows + r;
const size_t rb = (size_t) (Kin / 128) * (2 + 4 * K);
const uint8_t* blob = a.wbase + (size_t) e * a.stride;
if ((int) threadIdx.x < ne) rowsel[threadIdx.x] = GATE_UP ? a.idx[r0 + threadIdx.x] : r0 + (int) threadIdx.x;
__syncthreads();
if (tile * kTileRows >= N) return;
float res[2][8];
if (GATE_UP) {
const ActF32 act{a.xf, rowsel, (size_t) a.ldx};
const uint8_t* wr[2] = {blob + a.tr[0] + (size_t) row * rb, blob + a.tr[1] + (size_t) row * rb};
tile_dot<K, COMPUTED, 2, WORDS>(wr, Kin / 128, lut, act, ne, res);
} else {
const ActF16 act{a.xh, rowsel, (size_t) a.ldx};
const uint8_t* wr[1] = {blob + a.tr[2] + (size_t) row * rb};
tile_dot<K, COMPUTED, 1, WORDS>(wr, Kin / 128, lut, act, ne, res);
}
const int kgl = threadIdx.x >> 4 & 1;
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int m = 8 * kgl + i;
if (m >= ne) continue;
const size_t lr = (size_t) (r0 + m);
if (GATE_UP) a.h[lr * a.ldo + row] = __half_as_ushort(__float2half_rn(swiglu(res[0][i], res[1][i], a.limit)));
else a.y[lr * a.ldo + row] = res[0][i];
}
}
// ---------------------------------------------------------------- GEMV jobs
// grid (n / 64): y[c * ycs + r] = alpha (row r . x_c) + bias[r] for ncol (<= 16) int8 activation columns
template <int K, bool COMPUTED, bool WORDS>
__global__ void __launch_bounds__(kThreads) mv_kernel(const MvJob j) {
__shared__ uint32_t lut[COMPUTED ? 1 : 2048];
__shared__ int cols[kMaxEnt];
load_lut<K, COMPUTED>(lut);
if ((int) threadIdx.x < kMaxEnt) cols[threadIdx.x] = (int) threadIdx.x;
__syncthreads();
const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4, wave = threadIdx.x >> 5;
const int tile = blockIdx.x * kWaves + wave;
if (tile * kTileRows >= j.n) return;
const int row = tile * kTileRows + r;
const ActQ8 act{j.xq, j.xd, cols, j.k};
const uint8_t* wr[1] = {j.w + (size_t) row * j.ld};
float accm[1][8];
tile_dot<K, COMPUTED, 1, WORDS>(wr, j.k / 128, lut, act, j.ncol, accm);
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int m = 8 * kg + i;
if (m < j.ncol && row < j.n) j.y[(size_t) m * j.ycs + row] = j.alpha * accm[0][i] + (j.bias != nullptr ? j.bias[row] : 0.0f);
}
}
// ---------------------------------------------------------------- dispatch
#define DS4_TQ_SWITCH(t, F) \
switch (t) { \
case kTQK6: F(6, false); break; \
case kTQK7: F(7, false); break; \
case kTQK5X: F(5, true); break; \
case kTQK4X: F(4, true); break; \
case kTQK5T: F(5, false); break; \
case kTQK4T: F(4, false); break; \
default: return false; \
}
// 32-bit stream loads (STRATA_DS4_TQ_WORDS=1) or the 16-bit ones (default)
bool use_words() {
static const bool on = [] {
const char* e = std::getenv("STRATA_DS4_TQ_WORDS");
return e != nullptr && std::atoi(e) != 0; // (no gain measured on the R9700: 13.8 vs 14.2 ms a token)
}();
return on;
}
bool bad(const char* what) {
std::fprintf(stderr, "ds4 tq: %s\n", what);
return false;
}
} // namespace
bool gate_up(const Args& a, int groups, int ne_max, cudaStream_t s) {
const bool w = use_words();
(void) ne_max;
if (a.n_embd % 128 != 0 || a.n_ff % (kWaves * kTileRows) != 0) return bad("gate_up: geometry not covered");
const dim3 grid((unsigned) (a.n_ff / (kWaves * kTileRows)), (unsigned) groups);
#define GU_(K, C) { if (w) gate_up_kernel<K, C, true><<<grid, kThreads, 0, s>>>(a); else gate_up_kernel<K, C, false><<<grid, kThreads, 0, s>>>(a); }
DS4_TQ_SWITCH(a.tg, GU_)
#undef GU_
return true;
}
bool down(const Args& a, int groups, int ne_max, cudaStream_t s) {
const bool w = use_words();
(void) ne_max;
if (a.n_ff % 128 != 0 || a.n_embd % (kWaves * kTileRows) != 0) return bad("down: geometry not covered");
const dim3 grid((unsigned) (a.n_embd / (kWaves * kTileRows)), (unsigned) groups);
#define DN_(K, C) { if (w) down_kernel<K, C, true><<<grid, kThreads, 0, s>>>(a); else down_kernel<K, C, false><<<grid, kThreads, 0, s>>>(a); }
DS4_TQ_SWITCH(a.td, DN_)
#undef DN_
return true;
}
bool set_gate_up(const SetArgs& a, cudaStream_t s) {
const bool w = use_words();
if (a.n_embd % 128 != 0 || a.n_ff % (kWaves * kTileRows) != 0) return bad("set_gate_up: geometry not covered");
const dim3 grid((unsigned) (a.n_ff / (kWaves * kTileRows)), (unsigned) ((a.max_rows + kMaxEnt - 1) / kMaxEnt), (unsigned) a.n_exp);
#define SG_(K, C) { if (w) set_kernel<K, C, true, true><<<grid, kThreads, 0, s>>>(a); else set_kernel<K, C, true, false><<<grid, kThreads, 0, s>>>(a); }
DS4_TQ_SWITCH(a.tg, SG_)
#undef SG_
return true;
}
bool set_down(const SetArgs& a, cudaStream_t s) {
const bool w = use_words();
if (a.n_ff % 128 != 0 || a.n_embd % (kWaves * kTileRows) != 0) return bad("set_down: geometry not covered");
const dim3 grid((unsigned) (a.n_embd / (kWaves * kTileRows)), (unsigned) ((a.max_rows + kMaxEnt - 1) / kMaxEnt), (unsigned) a.n_exp);
#define SD_(K, C) { if (w) set_kernel<K, C, false, true><<<grid, kThreads, 0, s>>>(a); else set_kernel<K, C, false, false><<<grid, kThreads, 0, s>>>(a); }
DS4_TQ_SWITCH(a.td, SD_)
#undef SD_
return true;
}
bool mv(const MvJob* jobs, int n, cudaStream_t s) {
for (int i = 0; i < n; ++i) {
const MvJob& j = jobs[i];
const bool w = use_words();
if (j.k % 128 != 0 || j.n % kTileRows != 0 || j.ncol < 1 || j.ncol > kMaxEnt) return bad("mv: geometry not covered");
const dim3 grid((unsigned) ((j.n + kWaves * kTileRows - 1) / (kWaves * kTileRows)));
#define MV_(K, C) { if (w) mv_kernel<K, C, true><<<grid, kThreads, 0, s>>>(j); else mv_kernel<K, C, false><<<grid, kThreads, 0, s>>>(j); }
DS4_TQ_SWITCH(j.type, MV_)
#undef MV_
}
return true;
}
} // namespace strata::ds4::gguf::iq::tq
+136
View File
@@ -0,0 +1,136 @@
// Strata. The trellis routed experts (ds4_iq.cuh's is_tq types) on the CPU lane of the DeepSeek-V4.1 engine path: Strata's
// own decode-and-dot kernels (include/strata/kernels/cpu/tq_cpu.hpp: AVX-512 / AVX2 / scalar, one result whatever the ISA)
// over the file's rows read in place. The activations are the device's (ds4_gguf.cu's q8_quant: int8 with an F32 scale a 32
// values), so an expert gives the same sums on either lane up to the order of the blocks' float sums.
#include "ds4_gguf_cpu.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
#if defined(STRATA_DSV41_TQ_CPU)
#include "strata/kernels/cpu/tq_cpu.hpp"
#endif
namespace strata::ds4::gguf {
#if defined(STRATA_DSV41_TQ_CPU)
namespace kc = strata::kernels::cpu;
namespace {
int kbits_of(int type) {
switch (type) {
case 145: return 6;
case 146: return 7;
case 224: case 226: return 5;
case 225: case 227: return 4;
default: return 0;
}
}
constexpr int kActTq = 100; // IqCpu::gu_act / d_act of these types: the layout below
// an activation of k values: k / 32 F32 scales, then k int8
size_t act_bytes_of(int k) { return (size_t) k / 32 * 4 + (size_t) k; }
void unpack(const void* act, int k, kc::tq_detail::TqAct& a) {
const uint8_t* p = (const uint8_t*) act;
std::memcpy(a.d, p, (size_t) k / 32 * 4);
const int8_t* q = (const int8_t*) (p + (size_t) k / 32 * 4);
for (int i = 0; i < k; ++i) a.q[i] = q[i];
}
// dots of rows [r0, r1) of one matrix against nt activations: out[t][r]
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) {
static thread_local std::vector<kc::tq_detail::TqAct> unp(kc::kTqMaxTokens);
const kc::tq_detail::TqAct* ap[kc::kTqMaxTokens];
for (int t = 0; t < nt; ++t) {
unpack(act[t], n, unp[(size_t) t]);
ap[t] = &unp[(size_t) t];
}
const int kb = kc::tq_kbits(type);
const int16_t* tab = kc::tq_state_table_for(type);
switch (kc::tq_isa()) {
case kc::TqIsa::avx512: kc::tq_detail::tq_rows_avx512(kb, tab, w, rb, n, ap, nt, out, r0, r1); break;
case kc::TqIsa::avx2: kc::tq_detail::tq_rows_avx2(kb, tab, w, rb, n, ap, nt, out, r0, r1); break;
default: kc::tq_detail::tq_rows_scalar(kb, tab, w, rb, n, ap, nt, out, r0, r1); break;
}
}
} // namespace
bool tq_cpu_fmt(int tg, int td, int n_embd, int n_ff, IqCpu& f, std::string& err) {
if (kbits_of(tg) == 0 || kbits_of(td) == 0) {
err = "not trellis types";
return false;
}
if (n_embd % 128 != 0 || n_ff % 128 != 0 || n_embd > kc::kTqMaxN || n_ff > kc::kTqMaxN) {
err = "the trellis CPU kernels take widths of 128 blocks up to " + std::to_string(kc::kTqMaxN);
return false;
}
f.tg = tg;
f.td = td;
f.n_embd = n_embd;
f.n_ff = n_ff;
f.gu_act = f.d_act = kActTq;
f.gu_row = (size_t) (n_embd / 128) * (2 + 4 * kbits_of(tg));
f.d_row = (size_t) (n_ff / 128) * (2 + 4 * kbits_of(td));
f.act_bytes = act_bytes_of(n_embd);
f.h_bytes = act_bytes_of(n_ff);
return true;
}
// x (k values) -> the layout above (the device's q8_quant: sc = max|x| / 127, q = round-half-even(x / sc))
void tq_cpu_quant(const float* x, int k, void* dst) {
float* d = (float*) dst;
int8_t* q = (int8_t*) ((uint8_t*) dst + (size_t) k / 32 * 4);
for (int b = 0; b < k / 32; ++b) {
const float* xb = x + b * 32;
float am = 0.0f;
for (int j = 0; j < 32; ++j) am = std::max(am, std::fabs(xb[j]));
const float sc = am / 127.0f;
d[b] = sc;
for (int j = 0; j < 32; ++j) q[b * 32 + j] = (int8_t) (am > 0.0f ? (int) std::nearbyint(xb[j] / sc) : 0);
}
}
void tq_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) {
static thread_local std::vector<float> tmp[kc::kTqMaxTokens];
float* up_out[kc::kTqMaxTokens];
for (int t = 0; t < nt; ++t) {
tmp[t].resize((size_t) r1);
up_out[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, up_out, r0, r1);
for (int t = 0; t < nt; ++t)
for (int r = r0; r < r1; ++r) {
float g = ff[t][r], u = up_out[t][r];
if (limit > 0.0f) {
g = std::min(g, limit);
u = std::min(std::max(u, -limit), limit);
}
ff[t][r] = g / (1.0f + std::exp(-g)) * u;
}
}
void tq_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);
}
bool tq_cpu_type(int type) { return kbits_of(type) > 0; }
int tq_cpu_act() { return kActTq; }
#else
bool tq_cpu_fmt(int, int, int, int, IqCpu&, std::string& err) {
err = "this build has no CPU trellis kernels (STRATA_NATIVE_EXPERTS=OFF)";
return false;
}
void tq_cpu_quant(const float*, int, void*) {}
void tq_cpu_gate_up(const IqCpu&, const uint8_t*, const uint8_t*, const void* const*, int, float* const*, int, int, float) {}
void tq_cpu_down(const IqCpu&, const uint8_t*, const void* const*, int, float* const*, int, int) {}
bool tq_cpu_type(int) { return false; }
int tq_cpu_act() { return 100; }
#endif
} // namespace strata::ds4::gguf
+138
View File
@@ -0,0 +1,138 @@
// Strata. gfx12 (RDNA4, R9700 = gfx1201) WMMA form of the trellis expert GEMV of the dsv41 CUDA lab (tools/dsv41_lab:
// tqk_gemv3.cuh, wmma_emu.hpp = the specification, hip/tqk_gemv_wmma.hip.cpp = its first HIP form). Layout "TQW" (see
// wmma_emu.hpp::repack_tqw): a wave = T tiles of 16 rows, lane l = r + 16 kg owns row r and 16 consecutive steps of every
// 128-weight block; activations are the B operand (NB <= 16 columns), split x = hi + lo in two fp16 for ~2^-22 accuracy.
// CODE 0: the table codebook (K5/K6/K7 of the shipped files: two lookups into an 8 KB LDS table of half2 per step);
// CODE 1: the computed "3single" code (no table; the new K4/K5 types if they take it).
#pragma once
#include <hip/hip_runtime.h>
#include <cstdint>
namespace strata::ds4::tqw {
typedef _Float16 half8_t __attribute__((ext_vector_type(8)));
typedef float float8_t __attribute__((ext_vector_type(8)));
constexpr uint32_t kMask = 0x7fffu;
struct Job {
const uint32_t* words; // TQW words [tile][P][K][32 lanes]
const uint16_t* scales; // [tile][P][16 rows][2 blocks] fp16
const half8_t* xb; // prepared B fragments (prep_b)
float* y; // [NB][ldy]
int rows, in, ldy;
};
__device__ __forceinline__ void step_words(const uint32_t* lut, uint32_t s, uint32_t& w0, uint32_t& w1, int code) {
if (code == 1) {
w0 = ((s * 89226354u + 64248484u) & 0x8FFF8FFFu) ^ 0x3B603B60u;
w1 = ((s * 0x9E3779B1u + 0x7F4A7C15u) & 0x8FFF8FFFu) ^ 0x3B603B60u;
} else {
const uint32_t x = s * 0x9e3779b1u;
w0 = lut[x >> 21];
w1 = lut[(x >> 10) & 2047u];
}
}
// activations -> B fragments. out[(((blk * 8 + m) * 2 + kg) * nb + n) * 2 + {0 = hi, 1 = lo}] = 8 halves of x[n][blk * 128 + 4 * (16 kg + 2 m) + j]
__global__ void prep_b(const float* x, int ldx, int nb, int in, half8_t* out) {
const int nblk = in / 128;
const size_t gid = (size_t) blockIdx.x * blockDim.x + threadIdx.x, n_all = (size_t) nblk * 8 * 2 * nb;
if (gid >= n_all) return;
const int n = (int) (gid % nb), kg = (int) ((gid / nb) % 2), m = (int) ((gid / (2 * nb)) % 8), blk = (int) (gid / (16 * nb));
const float* p = x + (size_t) n * ldx + blk * 128 + 4 * (16 * kg + 2 * m);
half8_t hi, lo;
#pragma unroll
for (int j = 0; j < 8; ++j) { hi[j] = (_Float16) p[j]; lo[j] = (_Float16) (p[j] - (float) hi[j]); }
out[gid * 2] = hi;
out[gid * 2 + 1] = lo;
}
template <int K, int NB, int T, int EXACT, int CODE>
__global__ void __launch_bounds__(128) gemv(const Job* jobs, const uint32_t* __restrict__ lut_g) {
__shared__ uint32_t lut[CODE == 0 ? 2048 : 1];
if (CODE == 0) {
for (int i = threadIdx.x; i < 2048; i += blockDim.x) lut[i] = lut_g[i];
__syncthreads();
}
const Job job = jobs[blockIdx.y];
const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4;
const int tile0 = (blockIdx.x * (blockDim.x >> 5) + wave) * T;
if (tile0 * 16 >= job.rows) return;
const int nblk = job.in / 128, NP = nblk / 2;
float tot[T][8];
#pragma unroll
for (int t = 0; t < T; ++t)
#pragma unroll
for (int i = 0; i < 8; ++i) tot[t][i] = 0.f;
for (int P = 0; P < NP; ++P) {
uint32_t rec[T][K];
#pragma unroll
for (int t = 0; t < T; ++t)
#pragma unroll
for (int j = 0; j < K; ++j) rec[t][j] = __builtin_nontemporal_load(job.words + (((size_t) (tile0 + t) * NP + P) * K + j) * 32 + lane);
#pragma unroll
for (int bk = 0; bk < 2; ++bk) {
half8_t bh[8], bl[8];
if (r < NB) {
#pragma unroll
for (int m = 0; m < 8; ++m) {
const half8_t* p = job.xb + (((((size_t) (2 * P + bk) * 8 + m) * 2 + kg) * NB + r) * 2);
bh[m] = p[0];
if (EXACT) bl[m] = p[1];
}
} else {
#pragma unroll
for (int m = 0; m < 8; ++m) { bh[m] = half8_t{0, 0, 0, 0, 0, 0, 0, 0}; bl[m] = bh[m]; }
}
#pragma unroll
for (int t = 0; t < T; ++t) {
// chunk bk of the record: bits [16 K bk, 16 K bk + 16 K); window 0 = steps u 0..7 (+ 15-K bits of the partner chunk),
// window 1 = steps u 8..15
constexpr int NW = K; // (words of a record)
auto bits = [&](int pos, int n) -> uint64_t { // n <= 56 bits at record bit pos (pos is a compile-time constant here)
const int a = pos >> 5, sh = pos & 31;
const uint32_t w0 = rec[t][a], w1 = a + 1 < NW ? rec[t][a + 1 < NW ? a + 1 : 0] : 0u, w2 = a + 2 < NW ? rec[t][a + 2 < NW ? a + 2 : 0] : 0u;
// (w2:w1:w0) >> sh, low 64 bits
const uint64_t out = (sh == 0) ? (((uint64_t) w1 << 32) | w0) : ((((uint64_t) w1 << 32) | w0) >> sh) | ((uint64_t) w2 << (64 - sh));
return out & ((1ull << n) - 1ull);
};
const int b0 = 16 * K * bk;
const uint64_t lo8 = bits(b0, 8 * K), hi8 = bits(b0 + 8 * K, 8 * K);
const uint32_t mine = (uint32_t) (lo8 & 0xffffffffu); // the bits the PARTNER needs: this lane's chunk bits [0, 15 - K)
const uint32_t pc = __shfl_xor((int) mine, 16);
const uint64_t win0 = hi8 | ((uint64_t) (pc & ((1u << (15 - K)) - 1u)) << (8 * K));
const uint64_t win1 = lo8 | ((hi8 & ((1ull << (15 - K)) - 1ull)) << (8 * K));
float8_t acc = {0, 0, 0, 0, 0, 0, 0, 0};
#pragma unroll
for (int m = 0; m < 8; ++m) {
half8_t a;
#pragma unroll
for (int s2 = 0; s2 < 2; ++s2) {
const int u = 2 * m + s2;
const uint32_t st = (uint32_t) (u < 8 ? win0 >> ((7 - u) * K) : win1 >> ((15 - u) * K)) & kMask;
uint32_t w0, w1;
step_words(lut, st, w0, w1, CODE);
a[4 * s2 + 0] = __builtin_bit_cast(_Float16, (uint16_t) (w0 & 0xffffu));
a[4 * s2 + 1] = __builtin_bit_cast(_Float16, (uint16_t) (w0 >> 16));
a[4 * s2 + 2] = __builtin_bit_cast(_Float16, (uint16_t) (w1 & 0xffffu));
a[4 * s2 + 3] = __builtin_bit_cast(_Float16, (uint16_t) (w1 >> 16));
}
acc = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, bh[m], acc);
if (EXACT) acc = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, bl[m], acc);
}
// scales of rows 8 kg .. 8 kg + 7 of this block: 8 consecutive (row, bk) pairs of 2 -> stride 2
const uint16_t* sp = job.scales + (((size_t) (tile0 + t) * NP + P) * 16 + 8 * kg) * 2 + bk;
#pragma unroll
for (int i = 0; i < 8; ++i) tot[t][i] += (float) __builtin_bit_cast(_Float16, sp[2 * i]) * acc[i];
}
}
}
#pragma unroll
for (int t = 0; t < T; ++t)
if (r < NB)
#pragma unroll
for (int i = 0; i < 8; ++i) job.y[(size_t) r * job.ldy + (tile0 + t) * 16 + 8 * kg + i] = tot[t][i];
}
} // namespace strata::ds4::tqw
+519
View File
@@ -0,0 +1,519 @@
// 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_vision.cu - DeepSeek-V4.1's vision tower (see ds4_vision.cuh).
//
// One encode, N patches on a gh x gw grid:
// patchify (the reference's (x / 255 - 0.5) / 0.5, BF16) -> x = patch_embed(patches) FP32 [N][1024]
// per block, its weights in slot (b % 2) while block b + 1's copy runs:
// xn = norm1(x); qkv = rope(wqkv(xn) + bias) (rows in pieces of rb_: the FP32 GEMM output)
// per query piece of qb_ rows, per head: S = Q K^T / 8 (FP32), P = softmax(S) (BF16), O[:, head] = P V;
// x[piece] += wo(O) + bias
// xn = norm2(x); per row piece: x += w2(silu(gate) * up), gate | up = w1(xn)
// xn = norm(x); the 3 x 3 unfold; GELU(w1 + b1); w2 + b2 -> BF16 rows (the aligner's weights stream in pieces too)
#include "ds4_vision.cuh"
#include <cublas_v2.h>
#include "ds4_numerics.cuh"
#include <cuda_runtime.h>
#include <algorithm>
#include <cfloat>
#include <cmath>
#include <cstring>
namespace strata::ds4 {
namespace {
#define VK(call) \
do { \
cudaError_t e_ = (call); \
if (e_ != cudaSuccess) { \
err = std::string("vision: ") + #call + ": " + cudaGetErrorString(e_); \
return false; \
} \
} while (0)
#define VB(call) \
do { \
cublasStatus_t e_ = (call); \
if (e_ != CUBLAS_STATUS_SUCCESS) { \
err = std::string("vision: ") + #call + ": cuBLAS status " + std::to_string((int) e_); \
return false; \
} \
} while (0)
constexpr int kT = 256; // threads of the row kernels
constexpr int kSmT = 512, kSmPer = 20; // softmax: a row of up to 10240 keys in registers
constexpr size_t kWs = 16u << 20; // cuBLAS workspace
__device__ __forceinline__ float bf(uint16_t b) { return __uint_as_float((uint32_t) b << 16); }
__device__ __forceinline__ uint16_t bfr(float f) { return bf16_rn(f); }
__device__ float block_reduce(float v, bool is_max) {
__shared__ float red[32];
__shared__ float tot;
for (int o = 16; o > 0; o >>= 1) {
const float u = __shfl_xor_sync(0xffffffffu, v, o);
v = is_max ? fmaxf(v, u) : v + u;
}
const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = (blockDim.x + 31) >> 5;
__syncthreads(); // (an earlier call's readers of red / tot are done)
if (lane == 0) red[w] = v;
__syncthreads();
if (w == 0) {
v = lane < nw ? red[lane] : (is_max ? -FLT_MAX : 0.0f);
for (int o = 16; o > 0; o >>= 1) {
const float u = __shfl_xor_sync(0xffffffffu, v, o);
v = is_max ? fmaxf(v, u) : v + u;
}
if (lane == 0) tot = v;
}
__syncthreads();
return tot;
}
// patch i of the gh x gw grid: its 3 x p x p values, channel-major (the reference's reshape / permute)
__global__ void patchify_kernel(const uint8_t* __restrict__ rgb, int width, int gw, int p, uint16_t* __restrict__ out) {
const int i = blockIdx.x, e = threadIdx.x, pp = p * p;
if (e >= 3 * pp) return;
const int c = e / pp, r = e % pp, y = (i / gw) * p + r / p, x = (i % gw) * p + r % p;
const float u = (float) rgb[((size_t) y * width + x) * 3 + c];
out[(size_t) i * 3 * pp + e] = bfr(__fdiv_rn(__fsub_rn(__fdiv_rn(u, 255.0f), 0.5f), 0.5f));
}
// x[r] += y[r] (y null: nothing) + bias
__global__ void add_rows_kernel(float* __restrict__ x, const float* __restrict__ y, int ldy,
const uint16_t* __restrict__ bias, int dim) {
const int r = blockIdx.x;
for (int e = threadIdx.x; e < dim; e += blockDim.x) {
float v = x[(size_t) r * dim + e];
if (y != nullptr) v += y[(size_t) r * ldy + e];
if (bias != nullptr) v += bf(bias[e]);
x[(size_t) r * dim + e] = v;
}
}
__global__ void rmsnorm_kernel(const float* __restrict__ x, const uint16_t* __restrict__ w, int dim, float eps,
uint16_t* __restrict__ out) {
const int r = blockIdx.x;
const float* xr = x + (size_t) r * dim;
float ss = 0.0f;
for (int e = threadIdx.x; e < dim; e += blockDim.x) ss += xr[e] * xr[e];
ss = block_reduce(ss, false);
const float rs = rsqrtf(ss / (float) dim + eps);
for (int e = threadIdx.x; e < dim; e += blockDim.x) out[(size_t) r * dim + e] = bfr(bf(w[e]) * (xr[e] * rs));
}
// a piece's rows of wqkv's output (+ bias, rounded to BF16 as the reference's linear) into qkv, q and k rotated: the
// head's first half pairs with its second; frequency j < hd / 4 turns with the patch's row, the rest with its column
__global__ void qkv_rope_kernel(const float* __restrict__ y, const uint16_t* __restrict__ bias, int r0, int gw,
const float* __restrict__ inv_freq, int heads, int hd, uint16_t* __restrict__ qkv) {
const int r = blockIdx.x, gr = r0 + r, dim = heads * hd, half = hd / 2, nf = hd / 4;
const int row = gr / gw, col = gr % gw;
const float* yr = y + (size_t) r * 3 * dim;
uint16_t* o = qkv + (size_t) gr * 3 * dim;
for (int i = threadIdx.x; i < 2 * heads * half; i += blockDim.x) {
const int base = (i / half) * hd, d = i % half;
const float x1 = bf(bfr(yr[base + d] + bf(bias[base + d])));
const float x2 = bf(bfr(yr[base + d + half] + bf(bias[base + d + half])));
float sn, cs;
sincosf((float) (d < nf ? row : col) * inv_freq[d % nf], &sn, &cs);
o[base + d] = bfr(x1 * cs - x2 * sn);
o[base + d + half] = bfr(x2 * cs + x1 * sn);
}
for (int e = 2 * dim + threadIdx.x; e < 3 * dim; e += blockDim.x) o[e] = bfr(yr[e] + bf(bias[e]));
}
__global__ void __launch_bounds__(kSmT) softmax_kernel(const float* __restrict__ s, int n, uint16_t* __restrict__ p) {
const float* sr = s + (size_t) blockIdx.x * n;
uint16_t* pr = p + (size_t) blockIdx.x * n;
float v[kSmPer];
float m = -FLT_MAX;
#pragma unroll
for (int k = 0; k < kSmPer; ++k) {
const int e = threadIdx.x + k * kSmT;
v[k] = e < n ? sr[e] : -FLT_MAX;
m = fmaxf(m, v[k]);
}
m = block_reduce(m, true);
float sum = 0.0f;
#pragma unroll
for (int k = 0; k < kSmPer; ++k) {
const int e = threadIdx.x + k * kSmT;
v[k] = e < n ? expf(v[k] - m) : 0.0f;
sum += v[k];
}
const float inv = 1.0f / block_reduce(sum, false);
#pragma unroll
for (int k = 0; k < kSmPer; ++k) {
const int e = threadIdx.x + k * kSmT;
if (e < n) pr[e] = bfr(v[k] * inv);
}
}
// mid = silu(gate) * up, gate | up the halves of w1's row (BF16 steps, as the reference's)
__global__ void silu_mul_kernel(const float* __restrict__ y, int inter, uint16_t* __restrict__ mid) {
const int r = blockIdx.y, e = blockIdx.x * blockDim.x + threadIdx.x;
if (e >= inter) return;
const float gt = bf(bfr(y[(size_t) r * 2 * inter + e])), up = bf(bfr(y[(size_t) r * 2 * inter + inter + e]));
mid[(size_t) r * inter + e] = bfr(bf(bfr(gt / (1.0f + expf(-gt)))) * up);
}
// the aligner's input: block (bi, bj) of the m x m patches as one row, value c * m * m + kh * m + kw (F.unfold's
// order), zero past the grid
__global__ void unfold_kernel(const uint16_t* __restrict__ xn, int gh, int gw, int m, int dim, int lw,
uint16_t* __restrict__ un) {
const int l = blockIdx.x, bi = l / lw, bj = l % lw, mm = m * m;
for (int f = threadIdx.x; f < dim * mm; f += blockDim.x) {
const int c = f / mm, k = f % mm, y = bi * m + k / m, x = bj * m + k % m;
un[(size_t) l * dim * mm + f] = y < gh && x < gw ? xn[((size_t) y * gw + x) * dim + c] : (uint16_t) 0;
}
}
// out = act(bf16(y + bias)): GELU (erf) or none
__global__ void bias_act_kernel(const float* __restrict__ y, const uint16_t* __restrict__ bias, int n, int gelu,
uint16_t* __restrict__ out) {
const int r = blockIdx.y, e = blockIdx.x * blockDim.x + threadIdx.x;
if (e >= n) return;
float v = bf(bfr(y[(size_t) r * n + e] + bf(bias[e])));
if (gelu) v = 0.5f * v * (1.0f + erff(v * 0.70710678118654752f));
out[(size_t) r * n + e] = bfr(v);
}
int cdiv(int a, int b) { return (a + b - 1) / b; }
// y[r][o] = alpha * sum_k x[r][k] W[o][k] (row-major W [out][in] with row stride ldw, x [rows][ldx], y [rows][ldy])
bool gemm(cublasHandle_t h, const uint16_t* W, int ldw, const uint16_t* x, int ldx, void* y, cudaDataType yt, int ldy,
int rows, int in, int out, float alpha, std::string& err) {
const float beta = 0.0f;
VB(cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, out, rows, in, &alpha, W, CUDA_R_16BF, ldw, x, CUDA_R_16BF, ldx, &beta,
y, yt, ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
return true;
}
} // namespace
template <class T>
bool VisionTower::dalloc(T*& p, size_t n, std::string& err) {
void* v = nullptr;
const size_t b = (n * sizeof(T) + 255) / 256 * 256;
if (cudaMalloc(&v, b) != cudaSuccess) {
err = "vision: cudaMalloc " + std::to_string(b >> 20) + " MiB on CUDA" + std::to_string(at_) + " failed";
return false;
}
dallocs_.push_back(v);
dev_bytes_ += b;
p = (T*) v;
return true;
}
VisionTower::~VisionTower() { release(); }
void VisionTower::release() {
if (at_ < 0) return;
int cur = 0;
cudaGetDevice(&cur);
cudaSetDevice(at_);
for (int i = 0; i < 2; ++i) {
if (copied_[i]) cudaEventDestroy((cudaEvent_t) copied_[i]);
if (used_[i]) cudaEventDestroy((cudaEvent_t) used_[i]);
copied_[i] = used_[i] = nullptr;
}
if (blas_) cublasDestroy((cublasHandle_t) blas_);
if (st_) cudaStreamDestroy((cudaStream_t) st_);
if (cs_) cudaStreamDestroy((cudaStream_t) cs_);
for (void* p : dallocs_) cudaFree(p);
if (host_) cudaFreeHost(host_);
cudaSetDevice(cur);
blas_ = st_ = cs_ = nullptr;
dallocs_.clear();
host_ = nullptr;
dev_ = at_ = -1;
dev_bytes_ = 0;
}
bool VisionTower::load(const VisionGeo& g, int device, const Reader& read, std::string& err) {
g_ = g;
const int D = g.dim, I = g.inter, P = g.patch, M = g.merge, hd = g.heads > 0 ? g.dim / g.heads : 0;
if (g.layers <= 0 || hd * g.heads != D || hd % 4 != 0 || P <= 0 || M <= 0 || g.max_tokens < 5) {
err = "vision: geometry not covered";
return false;
}
// the largest aligner grid within max_tokens (n_h * (n_w + 1) + 2): the work buffers' size
int cells = 0;
for (int h = 1; h <= g.max_tokens - 2; ++h) {
const int w = (g.max_tokens - 2) / h - 1;
if (w >= 1) cells = std::max(cells, h * w);
}
max_n_ = cells * M * M;
if (max_n_ > kSmT * kSmPer) {
err = "vision: " + std::to_string(max_n_) + " patches are more than the attention covers";
return false;
}
cudaSetDevice(device);
at_ = device;
dev_bytes_ = 0;
// the checkpoint's tensors, checked before anything is read
struct Want {
std::string name;
std::vector<int64_t> shape;
};
std::vector<Want> want = {{"vision.patch_embed.proj.weight", {D, 3 * P * P}},
{"vision.patch_embed.proj.bias", {D}},
{"vision.norm.weight", {D}},
{"aligner.w1.weight", {g.out, (int64_t) D * M * M}},
{"aligner.w1.bias", {g.out}},
{"aligner.w2.weight", {g.out, g.out}},
{"aligner.w2.bias", {g.out}}};
for (int l = 0; l < g.layers; ++l) {
const std::string B = "vision.blocks." + std::to_string(l) + ".";
want.push_back({B + "norm1.weight", {D}});
want.push_back({B + "norm2.weight", {D}});
want.push_back({B + "attn.wqkv.weight", {3 * D, D}});
want.push_back({B + "attn.wqkv.bias", {3 * D}});
want.push_back({B + "attn.wo.weight", {D, D}});
want.push_back({B + "attn.wo.bias", {D}});
want.push_back({B + "mlp.w1.weight", {2 * I, D}});
want.push_back({B + "mlp.w2.weight", {D, I}});
}
for (const Want& w : want) {
std::vector<int64_t> s;
if (!read(w.name, s, nullptr)) {
err = "vision: " + w.name + " is not in the checkpoint";
return false;
}
if (s != w.shape) {
err = "vision: " + w.name + " has another shape than the config's";
return false;
}
}
// the streamed weights, pinned
block_n_ = (size_t) 3 * D * D + (size_t) D * D + (size_t) 2 * I * D + (size_t) D * I;
al1_off_ = block_n_ * g.layers;
al2_off_ = al1_off_ + (size_t) g.out * D * M * M;
const size_t host_n = al2_off_ + (size_t) g.out * g.out;
if (cudaHostAlloc((void**) &host_, host_n * 2, cudaHostAllocDefault) != cudaSuccess) {
host_ = nullptr;
err = "vision: pinning " + std::to_string((host_n * 2) >> 20) + " MiB of host memory failed";
return false;
}
std::vector<int64_t> s;
for (int l = 0; l < g.layers; ++l) {
const std::string B = "vision.blocks." + std::to_string(l) + ".";
uint16_t* b = host_ + (size_t) l * block_n_;
if (!read(B + "attn.wqkv.weight", s, b) || !read(B + "attn.wo.weight", s, b + (size_t) 3 * D * D) ||
!read(B + "mlp.w1.weight", s, b + (size_t) 4 * D * D) ||
!read(B + "mlp.w2.weight", s, b + (size_t) 4 * D * D + (size_t) 2 * I * D)) {
err = "vision: block " + std::to_string(l) + ": read failed";
return false;
}
}
if (!read("aligner.w1.weight", s, host_ + al1_off_) || !read("aligner.w2.weight", s, host_ + al2_off_)) {
err = "vision: the aligner: read failed";
return false;
}
// the small ones on the device
auto up = [&](const std::string& name, size_t n, uint16_t*& d) -> bool {
std::vector<uint16_t> h(n);
std::vector<int64_t> sh;
if (!read(name, sh, h.data())) {
err = "vision: " + name + ": read failed";
return false;
}
if (!dalloc(d, n, err)) return false;
VK(cudaMemcpy(d, h.data(), n * 2, cudaMemcpyHostToDevice));
return true;
};
bool ok = up("vision.patch_embed.proj.weight", (size_t) D * 3 * P * P, pe_w_) &&
up("vision.patch_embed.proj.bias", D, pe_b_) && up("vision.norm.weight", D, norm_) &&
up("aligner.w1.bias", g.out, al1_b_) && up("aligner.w2.bias", g.out, al2_b_);
n1_.assign(g.layers, nullptr);
n2_.assign(g.layers, nullptr);
bqkv_.assign(g.layers, nullptr);
bo_.assign(g.layers, nullptr);
for (int l = 0; l < g.layers && ok; ++l) {
const std::string B = "vision.blocks." + std::to_string(l) + ".";
ok = up(B + "norm1.weight", D, n1_[l]) && up(B + "norm2.weight", D, n2_[l]) &&
up(B + "attn.wqkv.bias", 3 * D, bqkv_[l]) && up(B + "attn.wo.bias", D, bo_[l]);
}
if (!ok) return false;
{ // the rotary's frequencies: theta ^ -(2i / (hd / 2)), hd / 4 of them
const int nf = hd / 4;
std::vector<float> f(nf);
for (int i = 0; i < nf; ++i) f[i] = 1.0f / std::pow(g.theta, (float) (2 * i) / (float) (hd / 2));
if (!dalloc(inv_freq_, nf, err)) return false;
VK(cudaMemcpy(inv_freq_, f.data(), nf * 4, cudaMemcpyHostToDevice));
}
// the work buffers: the patch grid's rows whole (the residual, its norm, q / k / v), the GEMM outputs a piece of
// rows at a time, the attention's scores a piece of queries at a time (~48 MB)
const int L = cells;
rb_ = 2048;
qb_ = std::max(16, (int) ((48u << 20) / ((size_t) max_n_ * 4)) / 16 * 16);
slot_n_ = std::max(block_n_, (size_t) 1 << 22);
const size_t y_n = (size_t) rb_ * std::max({3 * D, 2 * I, D});
const size_t qkv_n = std::max({(size_t) max_n_ * 3 * D,
(size_t) max_n_ * 3 * P * P + ((size_t) max_n_ * 3 * P * P + 1) / 2, // patches, pixels
(size_t) L * D * M * M + (size_t) 2 * L * g.out}); // the aligner's
if ((size_t) L * g.out > y_n || (size_t) max_n_ * D > y_n) {
err = "vision: work buffer sizes";
return false;
}
ok = dalloc(x_, (size_t) max_n_ * D, err) && dalloc(xn_, (size_t) max_n_ * D, err) && dalloc(qkv_, qkv_n, err) &&
dalloc(y_, y_n, err) && dalloc(o_, (size_t) max_n_ * D, err) && dalloc(mid_, (size_t) rb_ * I, err) &&
dalloc(s_, (size_t) qb_ * max_n_, err) && dalloc(p_, (size_t) qb_ * max_n_, err) &&
dalloc(slot_[0], slot_n_, err) && dalloc(slot_[1], slot_n_, err) && dalloc(ws_, kWs, err);
if (!ok) return false;
patch_ = qkv_; // (before block 0's qkv)
rgb_ = (uint8_t*) (qkv_ + (size_t) max_n_ * 3 * P * P);
un_ = qkv_; // (after the last block's attention)
a16_ = un_ + (size_t) L * D * M * M;
outb_ = a16_ + (size_t) L * g.out;
cublasHandle_t h = nullptr;
VB(cublasCreate(&h));
blas_ = h;
cudaStream_t st = nullptr, cs = nullptr;
VK(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking));
VK(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking));
st_ = st;
cs_ = cs;
VB(cublasSetStream(h, st));
VB(cublasSetWorkspace(h, ws_, kWs));
for (int i = 0; i < 2; ++i) {
cudaEvent_t a = nullptr, b = nullptr;
VK(cudaEventCreateWithFlags(&a, cudaEventDisableTiming));
VK(cudaEventCreateWithFlags(&b, cudaEventDisableTiming));
copied_[i] = a;
used_[i] = b;
}
dev_ = device;
return true;
}
bool VisionTower::encode(const uint8_t* rgb, int width, int height, std::vector<uint16_t>& rows, int& n_h, int& n_w,
std::string& err) {
if (dev_ < 0) {
err = "vision: not loaded";
return false;
}
const VisionGeo& g = g_;
const int D = g.dim, I = g.inter, P = g.patch, M = g.merge, hd = D / g.heads, H3 = 3 * D;
if (width <= 0 || height <= 0 || width % P != 0 || height % P != 0) {
err = "vision: an image of " + std::to_string(width) + " x " + std::to_string(height) +
" pixels (both sides must be multiples of " + std::to_string(P) + ")";
return false;
}
const int gh = height / P, gw = width / P, N = gh * gw;
n_h = cdiv(gh, M);
n_w = cdiv(gw, M);
const int L = n_h * n_w;
if (N > max_n_ || n_h * (n_w + 1) + 2 > g.max_tokens) {
err = "vision: an image of " + std::to_string(width) + " x " + std::to_string(height) + " pixels is more than " +
std::to_string(g.max_tokens) + " image tokens";
return false;
}
cudaSetDevice(dev_);
cublasHandle_t h = (cublasHandle_t) blas_;
cudaStream_t s = (cudaStream_t) st_, cs = (cudaStream_t) cs_;
// the weights in the order the encode takes them: the blocks, then the aligner's in pieces of a slot
std::vector<Piece> pcs;
for (int l = 0; l < g.layers; ++l) pcs.push_back({host_ + (size_t) l * block_n_, block_n_});
const int in1 = D * M * M, r1 = (int) std::min<size_t>(g.out, slot_n_ / in1), r2 = (int) std::min<size_t>(g.out, slot_n_ / g.out);
for (int o0 = 0; o0 < g.out; o0 += r1)
pcs.push_back({host_ + al1_off_ + (size_t) o0 * in1, (size_t) std::min(r1, g.out - o0) * in1});
for (int o0 = 0; o0 < g.out; o0 += r2)
pcs.push_back({host_ + al2_off_ + (size_t) o0 * g.out, (size_t) std::min(r2, g.out - o0) * g.out});
auto fetch = [&](size_t i) -> bool {
const int k = (int) (i % 2);
VK(cudaStreamWaitEvent(cs, (cudaEvent_t) used_[k], 0));
VK(cudaMemcpyAsync(slot_[k], pcs[i].host, pcs[i].n * 2, cudaMemcpyHostToDevice, cs));
VK(cudaEventRecord((cudaEvent_t) copied_[k], cs));
return true;
};
size_t pi = 0; // the piece being used
auto take = [&]() -> const uint16_t* { // the next piece's slot, once its copy is in (the one after it started)
const int k = (int) (pi % 2);
if (pi + 1 < pcs.size() && !fetch(pi + 1)) return nullptr;
if (cudaStreamWaitEvent(s, (cudaEvent_t) copied_[k], 0) != cudaSuccess) {
err = "vision: waiting for a weight copy failed";
return nullptr;
}
return slot_[k];
};
auto done = [&]() { // the piece's work is queued: its slot is free once that ran
cudaEventRecord((cudaEvent_t) used_[pi % 2], s);
++pi;
};
if (!fetch(0)) return false;
// the patches
VK(cudaMemcpyAsync(rgb_, rgb, (size_t) N * 3 * P * P, cudaMemcpyHostToDevice, s));
patchify_kernel<<<N, 3 * P * P, 0, s>>>(rgb_, width, gw, P, patch_);
if (!gemm(h, pe_w_, 3 * P * P, patch_, 3 * P * P, x_, CUDA_R_32F, D, N, 3 * P * P, D, 1.0f, err)) return false;
add_rows_kernel<<<N, kT, 0, s>>>(x_, nullptr, 0, pe_b_, D);
const float scale = 1.0f / std::sqrt((float) hd);
const int qb = (int) std::max<size_t>(1, std::min<size_t>((size_t) N, (size_t) qb_ * max_n_ / (size_t) N));
for (int l = 0; l < g.layers; ++l) {
const uint16_t* wqkv = take();
if (wqkv == nullptr) return false;
const uint16_t *wo = wqkv + (size_t) H3 * D, *w1 = wo + (size_t) D * D, *w2 = w1 + (size_t) 2 * I * D;
rmsnorm_kernel<<<N, kT, 0, s>>>(x_, n1_[l], D, g.eps, xn_);
for (int r0 = 0; r0 < N; r0 += rb_) {
const int nr = std::min(rb_, N - r0);
if (!gemm(h, wqkv, D, xn_ + (size_t) r0 * D, D, y_, CUDA_R_32F, H3, nr, D, H3, 1.0f, err)) return false;
qkv_rope_kernel<<<nr, kT, 0, s>>>(y_, bqkv_[l], r0, gw, inv_freq_, g.heads, hd, qkv_);
}
for (int q0 = 0; q0 < N; q0 += qb) {
const int nq = std::min(qb, N - q0);
const float one = 1.0f, zero = 0.0f;
for (int hh = 0; hh < g.heads; ++hh) {
// S^T (keys x queries, column-major) = K Q^T: row-major S [query][key]
VB(cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, N, nq, hd, &scale, qkv_ + D + hh * hd, CUDA_R_16BF, H3,
qkv_ + (size_t) q0 * H3 + hh * hd, CUDA_R_16BF, H3, &zero, s_, CUDA_R_32F, N,
CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
softmax_kernel<<<nq, kSmT, 0, s>>>(s_, N, p_);
// O^T (hd x queries) = V^T P^T: row-major O [query][head's hd] at column hh * hd
VB(cublasGemmEx(h, CUBLAS_OP_N, CUBLAS_OP_N, hd, nq, N, &one, qkv_ + 2 * D + hh * hd, CUDA_R_16BF, H3,
p_, CUDA_R_16BF, N, &zero, o_ + hh * hd, CUDA_R_16BF, D, CUBLAS_COMPUTE_32F,
CUBLAS_GEMM_DEFAULT));
}
if (!gemm(h, wo, D, o_, D, y_, CUDA_R_32F, D, nq, D, D, 1.0f, err)) return false;
add_rows_kernel<<<nq, kT, 0, s>>>(x_ + (size_t) q0 * D, y_, D, bo_[l], D);
}
rmsnorm_kernel<<<N, kT, 0, s>>>(x_, n2_[l], D, g.eps, xn_);
for (int r0 = 0; r0 < N; r0 += rb_) {
const int nr = std::min(rb_, N - r0);
if (!gemm(h, w1, D, xn_ + (size_t) r0 * D, D, y_, CUDA_R_32F, 2 * I, nr, D, 2 * I, 1.0f, err)) return false;
silu_mul_kernel<<<dim3(cdiv(I, kT), nr), kT, 0, s>>>(y_, I, mid_);
if (!gemm(h, w2, I, mid_, I, y_, CUDA_R_32F, D, nr, I, D, 1.0f, err)) return false;
add_rows_kernel<<<nr, kT, 0, s>>>(x_ + (size_t) r0 * D, y_, D, nullptr, D);
}
done();
}
rmsnorm_kernel<<<N, kT, 0, s>>>(x_, norm_, D, g.eps, xn_);
// the aligner
unfold_kernel<<<L, kT, 0, s>>>(xn_, gh, gw, M, D, n_w, un_);
for (int o0 = 0; o0 < g.out; o0 += r1) {
const uint16_t* w = take();
if (w == nullptr) return false;
if (!gemm(h, w, in1, un_, in1, y_ + o0, CUDA_R_32F, g.out, L, in1, std::min(r1, g.out - o0), 1.0f, err))
return false;
done();
}
bias_act_kernel<<<dim3(cdiv(g.out, kT), L), kT, 0, s>>>(y_, al1_b_, g.out, 1, a16_);
for (int o0 = 0; o0 < g.out; o0 += r2) {
const uint16_t* w = take();
if (w == nullptr) return false;
if (!gemm(h, w, g.out, a16_, g.out, y_ + o0, CUDA_R_32F, g.out, L, g.out, std::min(r2, g.out - o0), 1.0f, err))
return false;
done();
}
bias_act_kernel<<<dim3(cdiv(g.out, kT), L), kT, 0, s>>>(y_, al2_b_, g.out, 0, outb_);
rows.resize((size_t) L * g.out);
VK(cudaMemcpyAsync(rows.data(), outb_, rows.size() * 2, cudaMemcpyDeviceToHost, s));
VK(cudaStreamSynchronize(s));
VK(cudaGetLastError());
return true;
}
} // namespace strata::ds4
+79
View File
@@ -0,0 +1,79 @@
// 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_vision.cuh - DeepSeek-V4.1's vision tower on one GPU (DeepSeek's inference/vision.py):
// patches (14 x 14 RGB, scaled to [-1, 1]) -> Linear(588 -> 1024)
// 32 blocks: x += attn(rmsnorm(x)) (16 heads of 64, full bidirectional attention over the image, a 2D rotary on q
// and k: the first half of each head's frequencies the patch row, the second its column);
// x += w2(silu(gate) * up) with gate, up = w1(rmsnorm(x))
// rmsnorm, then the aligner: each 3 x 3 block of patches (zero-padded at the right and bottom) as one 9216 row,
// Linear(9216 -> 5120), GELU, Linear(5120 -> 5120): one LLM embedding row per block, in reading order.
// The BF16 weights live in pinned host memory and stream to the GPU a block at a time (two slots, the next block's
// copy under this one's work), so the tower costs the model ~350 MB of the GPU's memory, not ~1 GB; the GEMMs are
// cuBLAS (BF16 in, FP32 accumulation), the residual stream FP32.
#pragma once
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
namespace strata::ds4 {
struct VisionGeo {
int layers = 0, dim = 1024, heads = 16, inter = 2816, patch = 14, merge = 3, out = 5120;
float theta = 10000.0f, eps = 1e-6f;
int max_tokens = 1024; // an image's span in the prompt at most: n_h * (n_w + 1) + 2 tokens
};
class VisionTower {
public:
/// read(name, shape, dst): the tensor's shape, and (dst not null) its BF16 data into dst; false: not there
using Reader = std::function<bool(const std::string& name, std::vector<int64_t>& shape, void* dst)>;
VisionTower() = default;
VisionTower(const VisionTower&) = delete;
VisionTower& operator=(const VisionTower&) = delete;
~VisionTower();
bool load(const VisionGeo& g, int device, const Reader& read, std::string& err);
/// Frees everything load took (a load that failed half way too); loaded() is false after it.
void release();
bool loaded() const { return dev_ >= 0; }
int device() const { return dev_; }
size_t device_bytes() const { return dev_bytes_; }
/// The patches an image may have (its aligner grid within max_tokens).
int max_patches() const { return max_n_; }
/// rgb: height x width x 3 bytes, both sides multiples of the patch size -> the aligner's rows, BF16
/// [n_h * n_w][out] in reading order (n_h x n_w: the patch grid over 3, rounded up).
bool encode(const uint8_t* rgb, int width, int height, std::vector<uint16_t>& rows, int& n_h, int& n_w,
std::string& err);
private:
struct Piece { // a weight the encode streams in: host bits, its size
const uint16_t* host = nullptr;
size_t n = 0;
};
VisionGeo g_;
int dev_ = -1, at_ = -1, max_n_ = 0, qb_ = 0, rb_ = 0; // (at_: the device its memory is on)
size_t dev_bytes_ = 0, slot_n_ = 0;
std::vector<void*> dallocs_;
uint16_t* host_ = nullptr; // pinned: every block's [wqkv, wo, w1, w2], then aligner w1, w2
size_t block_n_ = 0; // a block's weights (BF16 values)
size_t al1_off_ = 0, al2_off_ = 0; // the aligner's weights in host_
// resident (small): the patch embedding, the norms and biases
uint16_t *pe_w_ = nullptr, *pe_b_ = nullptr, *norm_ = nullptr, *al1_b_ = nullptr, *al2_b_ = nullptr;
std::vector<uint16_t*> n1_, n2_, bqkv_, bo_;
// work buffers (max_n_ patches)
uint8_t* rgb_ = nullptr;
uint16_t *patch_ = nullptr, *xn_ = nullptr, *qkv_ = nullptr, *o_ = nullptr, *mid_ = nullptr, *p_ = nullptr,
*un_ = nullptr, *a16_ = nullptr, *outb_ = nullptr;
float *x_ = nullptr, *y_ = nullptr, *s_ = nullptr, *inv_freq_ = nullptr;
uint16_t* slot_[2] = {nullptr, nullptr};
void* blas_ = nullptr; // cublasHandle_t
uint8_t* ws_ = nullptr;
void *st_ = nullptr, *cs_ = nullptr; // cudaStream_t: the work, the weight copies
void *copied_[2] = {nullptr, nullptr}, *used_[2] = {nullptr, nullptr}; // cudaEvent_t per slot
template <class T>
bool dalloc(T*& p, size_t n, std::string& err);
};
} // namespace strata::ds4
+1745
View File
File diff suppressed because it is too large. Load diff
+1281
View File
File diff suppressed because it is too large. Load diff
+967
View File
@@ -0,0 +1,967 @@
// 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/kernels/cuda/exl3_legacy.cu - v1.1.8's EXL3 decode kernels, kept for NVIDIA GPUs before sm_80 (V100, T4,
// RTX 20): #180's decode kernels run the tiles on the tensor cores from sm_80 on, and their CUDA-core fallback was
// slower here than these (a V100 with EXL3-3.05bpw: decode 4.9 -> 4.4 tok/s). exl3.cu's mv / moe_gate_up / moe_down
// / win_experts / prepare / several_ok call these on such a GPU (STRATA_GLM_EXL3_DECODE=legacy|new picks one on any
// GPU); the prompt path is exl3.cu's on every GPU. The code below is v1.1.8's as it was, the prompt path's kernels
// left out.
//
// The codebooks and the trellis window arithmetic follow exllamav3 (MIT, turboderp - exllamav3_ext/quant/
// codebook.cuh, exl3_dq.cuh, hadamard_inner.cuh); the kernels around them are shaped for this engine's decode:
//
// * a block owns 128 outputs (8 tiles - exactly one output rotation block) over a slice of at most 4096 inputs;
// its 8 warps take the slice's 16-row tile rows in turn, each staging the row's 8 tiles in shared memory with
// coalesced loads and decoding 8 weights per lane (one fragment: 2 columns x 4 rows), F32 accumulation;
// * the input rotation runs per block on the slice it reads (F32 or q8_1 in, FP16 in shared memory), so the
// engine's activation buffers are used as they are;
// * a matrix with more than 4096 inputs, or too few output blocks to fill the device, splits its inputs over
// blocks: the partial sums go to a per-stream scratch and the LAST block of an output block adds them up in
// split order (deterministic) and runs the output rotation.
#if !defined(STRATA_USE_HIP) // (AMD runs exl3.cu's kernels; EXL3 does not run there anyway)
#include "strata/dsv41/exl3.hpp"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <atomic>
#include <cstdio>
#include <map>
#include <mutex>
#include <utility>
namespace strata::dsv41k::exl3::legacy {
namespace {
constexpr int kThreads = 256, kWarps = 8;
constexpr int kCols = 128; // outputs per block: 8 tiles, one rotation block
constexpr int kMaxKR = 4096; // inputs per block (the rotated slice lives in shared memory)
constexpr float kHad = 0.088388347648f; // 1 / sqrt(128)
struct Q81 { // the engine's q8_1 block (ggml block_q8_1): d, sum, 32 int8
__half2 ds;
int8_t qs[32];
};
std::atomic<int> g_launch_errors{0};
void launch_check(const char* what) {
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "exl3 %s: %s\n", what, cudaGetErrorString(e));
g_launch_errors.fetch_add(1, std::memory_order_relaxed);
}
}
// ---------------------------------------------------------------- the codebooks
__device__ __forceinline__ uint32_t bytesum_plus(uint32_t x, uint32_t acc) {
#if defined(STRATA_USE_HIP)
return acc + (x & 0xffu) + ((x >> 8) & 0xffu) + ((x >> 16) & 0xffu) + (x >> 24);
#else
return __dp4a(x, 0x01010101u, acc);
#endif
}
// two states -> two values, FP16 arithmetic as exllamav3's decode_3inst_2 (the tensor-core kernels take the half2)
template <int cb>
__device__ __forceinline__ __half2 decode2h(uint32_t s0, uint32_t s1) {
if constexpr (cb == 2) {
const uint32_t a = bytesum_plus(s0 * 0x83DCD12Du, 0x6400u);
const uint32_t b = bytesum_plus(s1 * 0x83DCD12Du, 0x6400u);
const __half2 h = __halves2half2(__ushort_as_half((unsigned short) a), __ushort_as_half((unsigned short) b));
return __hfma2(h, __half2half2(__ushort_as_half(0x1eee)), __half2half2(__ushort_as_half(0xc931)));
} else {
uint32_t x0 = cb == 1 ? s0 * 0xCBAC1FEDu : s0 * 89226354u + 64248484u;
uint32_t x1 = cb == 1 ? s1 * 0xCBAC1FEDu : s1 * 89226354u + 64248484u;
x0 = (x0 & 0x8fff8fffu) ^ 0x3b603b60u;
x1 = (x1 & 0x8fff8fffu) ^ 0x3b603b60u;
const __half2 lo = __halves2half2(__ushort_as_half((unsigned short) (x0 & 0xffffu)),
__ushort_as_half((unsigned short) (x1 & 0xffffu)));
const __half2 hi = __halves2half2(__ushort_as_half((unsigned short) (x0 >> 16)),
__ushort_as_half((unsigned short) (x1 >> 16)));
return __hadd2(lo, hi);
}
}
template <int cb>
__device__ __forceinline__ float2 decode2(uint32_t s0, uint32_t s1) {
return __half22float2(decode2h<cb>(s0, s1));
}
// step p's state: the 16-bit window ending at bit (p + 1) K of the tile's MSB-first bit stream (w: its 8 K words),
// wrapping around the tile (the + 256 K keeps the start non-negative)
template <int K>
__device__ __forceinline__ uint32_t state_at(const uint32_t* w, int p) {
constexpr int W = 8 * K;
const int b1 = (p + 1 + 256) * K;
const int i1 = (b1 - 1) >> 5, i0 = (b1 - 16) >> 5;
const int sh = ((i1 + 1) << 5) - b1;
const uint64_t m = ((uint64_t) w[i0 % W] << 32) | (uint64_t) w[i1 % W];
return (uint32_t) (m >> sh) & 0xffffu;
}
// lane's 8 steps (lane * 8 + j): v[j] sits at tile row (lane & 3) * 2 + (j & 1) + 8 (j >> 1 & 1), column
// (lane >> 2) + 8 (j >> 2)
template <int K, int cb>
__device__ __forceinline__ void decode8(const uint32_t* w, int lane, float* v) {
const int p0 = lane * 8;
#pragma unroll
for (int j = 0; j < 8; j += 2) {
const float2 d = decode2<cb>(state_at<K>(w, p0 + j), state_at<K>(w, p0 + j + 1));
v[j] = d.x;
v[j + 1] = d.y;
}
}
// ---------------------------------------------------------------- the rotation
// the 128-point transform of the 128 values a warp holds 4 per lane (value lane * 4 + i), over sqrt(128)
__device__ __forceinline__ void had128(float* v, int lane) {
const float s0 = v[0] + v[1], d0 = v[0] - v[1], s1 = v[2] + v[3], d1 = v[2] - v[3];
v[0] = s0 + s1;
v[1] = d0 + d1;
v[2] = s0 - s1;
v[3] = d0 - d1;
#pragma unroll
for (int m = 1; m < 32; m <<= 1) {
#pragma unroll
for (int i = 0; i < 4; ++i) {
const float o = __shfl_xor_sync(0xffffffffu, v[i], m);
v[i] = (lane & m) ? o - v[i] : v[i] + o;
}
}
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] *= kHad;
}
__device__ __forceinline__ float h2f(uint16_t b) { return __half2float(__ushort_as_half(b)); }
// xs[i] = H(x * suh)[k0 + i] for i < kr (kr % 128 == 0); x from xf (F32) or xq (q8_1); every warp of the block
__device__ void rotate_in(const float* __restrict__ xf, const Q81* __restrict__ xq, const uint16_t* __restrict__ suh,
int k0, int kr, __half* xs) {
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
for (int c = warp; c < kr / 128; c += kWarps) {
const int base = k0 + c * 128 + lane * 4;
float v[4];
if (xf != nullptr) {
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] = xf[base + i];
} else {
const Q81* b = xq + base / 32;
const float d = __low2float(b->ds);
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] = d * (float) b->qs[base % 32 + i];
}
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] *= h2f(suh[base + i]);
had128(v, lane);
#pragma unroll
for (int i = 0; i < 4; ++i) xs[c * 128 + lane * 4 + i] = __float2half_rn(v[i]);
}
}
// ---------------------------------------------------------------- the block GEMV
// a lane's 4 weights of one column times the activation's 4 inputs, added to a: the rounding spelled out, so the
// one-activation and the several-activation GEMVs (block_gemv, block_gemv_n) give each activation the same bits
__device__ __forceinline__ float dot4_acc(float a, const float* v, float x0, float x1, float x2, float x3) {
return __fadd_rn(a, __fmaf_rn(v[3], x3, __fmaf_rn(v[2], x2, __fmaf_rn(v[1], x1, __fmul_rn(v[0], x0)))));
}
// red[c] (c < 128) = sum over the 16-row slices [ks0, ks1) of x' . W'[:, tc0 * 16 + c], x' = xs from slice ks0 on.
// tr: the matrix's first tile, ld tiles per slice row. stage: kWarps * 64 K words, red: kWarps * 128 floats.
// Ends with a __syncthreads (red[0..127] complete).
template <int K, int cb>
__device__ void block_gemv(const uint32_t* __restrict__ tr, int ld, int tc0, int ks0, int ks1, const __half* xs,
uint32_t* stage, float* red) {
constexpr int W = 8 * K, TW = 8 * W;
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
uint32_t* st = stage + warp * TW;
float acc[8][2];
#pragma unroll
for (int t = 0; t < 8; ++t) acc[t][0] = acc[t][1] = 0.0f;
const int kk = (lane & 3) * 2;
for (int ks = ks0 + warp; ks < ks1; ks += kWarps) {
const uint32_t* src = tr + ((size_t) ks * ld + tc0) * W;
__syncwarp();
#pragma unroll
for (int i = lane; i < TW; i += 32) st[i] = src[i];
__syncwarp();
const __half* xk = xs + (ks - ks0) * 16;
const float x0 = __half2float(xk[kk]), x1 = __half2float(xk[kk + 1]);
const float x2 = __half2float(xk[kk + 8]), x3 = __half2float(xk[kk + 9]);
#pragma unroll
for (int t = 0; t < 8; ++t) {
float v[8];
decode8<K, cb>(st + t * W, lane, v);
acc[t][0] = dot4_acc(acc[t][0], v, x0, x1, x2, x3);
acc[t][1] = dot4_acc(acc[t][1], v + 4, x0, x1, x2, x3);
}
}
// the 4 lanes of one lane / 4 hold the same two columns of every tile
#pragma unroll
for (int t = 0; t < 8; ++t)
#pragma unroll
for (int c = 0; c < 2; ++c) {
acc[t][c] += __shfl_xor_sync(0xffffffffu, acc[t][c], 1);
acc[t][c] += __shfl_xor_sync(0xffffffffu, acc[t][c], 2);
}
if ((lane & 3) == 0)
#pragma unroll
for (int t = 0; t < 8; ++t) {
red[warp * kCols + t * 16 + (lane >> 2)] = acc[t][0];
red[warp * kCols + t * 16 + 8 + (lane >> 2)] = acc[t][1];
}
__syncthreads();
if (threadIdx.x < kCols) {
float s = 0.0f;
#pragma unroll
for (int w = 0; w < kWarps; ++w) s += red[w * kCols + threadIdx.x];
red[threadIdx.x] = s;
}
__syncthreads();
}
// block_gemv for nc activations at once (nc <= kNC; activation c's rotated slice at xs + c * kMaxKR): each lane decodes
// its 8 weights of a tile once and adds them into every activation's sums - as exllamav3's small-m GEMV and fused MoE
// kernels share a tile's decode among the rows of an MMA, but with block_gemv's own F32 arithmetic, so outc[c * 128 +
// i] (i < 128) is bit for bit block_gemv's red[i] for activation c alone. Ends with a __syncthreads.
constexpr int kNC = 4;
template <int K, int cb>
__device__ void block_gemv_n(const uint32_t* __restrict__ tr, int ld, int tc0, int ks0, int ks1, const __half* xs,
int nc, uint32_t* stage, float* red, float* outc) {
constexpr int W = 8 * K, TW = 8 * W;
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
uint32_t* st = stage + warp * TW;
float acc[kNC][8][2];
#pragma unroll
for (int c = 0; c < kNC; ++c)
#pragma unroll
for (int t = 0; t < 8; ++t) acc[c][t][0] = acc[c][t][1] = 0.0f;
const int kk = (lane & 3) * 2;
for (int ks = ks0 + warp; ks < ks1; ks += kWarps) {
const uint32_t* src = tr + ((size_t) ks * ld + tc0) * W;
__syncwarp();
#pragma unroll
for (int i = lane; i < TW; i += 32) st[i] = src[i];
__syncwarp();
float x[kNC][4];
#pragma unroll
for (int c = 0; c < kNC; ++c) {
const __half* xk = xs + c * kMaxKR + (ks - ks0) * 16;
if (c < nc) {
x[c][0] = __half2float(xk[kk]);
x[c][1] = __half2float(xk[kk + 1]);
x[c][2] = __half2float(xk[kk + 8]);
x[c][3] = __half2float(xk[kk + 9]);
}
}
#pragma unroll
for (int t = 0; t < 8; ++t) {
float v[8];
decode8<K, cb>(st + t * W, lane, v);
#pragma unroll
for (int c = 0; c < kNC; ++c)
if (c < nc) {
acc[c][t][0] = dot4_acc(acc[c][t][0], v, x[c][0], x[c][1], x[c][2], x[c][3]);
acc[c][t][1] = dot4_acc(acc[c][t][1], v + 4, x[c][0], x[c][1], x[c][2], x[c][3]);
}
}
}
// per activation, block_gemv's reduction
#pragma unroll
for (int c = 0; c < kNC; ++c) {
if (c >= nc) break;
#pragma unroll
for (int t = 0; t < 8; ++t)
#pragma unroll
for (int h = 0; h < 2; ++h) {
acc[c][t][h] += __shfl_xor_sync(0xffffffffu, acc[c][t][h], 1);
acc[c][t][h] += __shfl_xor_sync(0xffffffffu, acc[c][t][h], 2);
}
if ((lane & 3) == 0)
#pragma unroll
for (int t = 0; t < 8; ++t) {
red[warp * kCols + t * 16 + (lane >> 2)] = acc[c][t][0];
red[warp * kCols + t * 16 + 8 + (lane >> 2)] = acc[c][t][1];
}
__syncthreads();
if (threadIdx.x < kCols) {
float s = 0.0f;
#pragma unroll
for (int w = 0; w < kWarps; ++w) s += red[w * kCols + threadIdx.x];
outc[c * kCols + threadIdx.x] = s;
}
__syncthreads();
}
}
// one warp: y[c] = alpha * (H(red) * svh)[c] + bias[c] for the block's 128 outputs
__device__ __forceinline__ void epilogue(const float* red, const uint16_t* svh, float alpha, const float* bias,
float* y) {
const int lane = threadIdx.x & 31;
float v[4];
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] = red[lane * 4 + i];
had128(v, lane);
#pragma unroll
for (int i = 0; i < 4; ++i) {
const int c = lane * 4 + i;
y[c] = __fmaf_rn(__fmul_rn(alpha, v[i]), h2f(svh[c]), bias != nullptr ? bias[c] : 0.0f);
}
}
// ---------------------------------------------------------------- mv
struct KJob {
const uint32_t* tr;
const uint16_t* suh;
const uint16_t* svh;
const float* xf;
const Q81* xq;
float* y;
const float* bias;
float* part; // S x n partial sums (S > 1); mv_n_kernel: nc x S x n
unsigned* cnt; // n / 128 counters, zero between launches
float alpha;
int k, n, ld, S, kr;
int nc; // mv_n_kernel: the activations (1..kNC), xf / xq / y advanced by these per activation
size_t xf_cs, xq_cs, y_cs; // (floats, bytes, floats)
};
struct KBatch {
KJob j[kMaxMvJobs];
int blk_end[kMaxMvJobs];
int n;
};
// the dynamic shared memory of the several-activation kernels (mv_n_kernel, win_gu_kernel, win_down_kernel):
// red[kWarps][128] outc[kNC][128] gu[2][kNC][128] (F32), stage[kWarps * 64 K] (words), xs[kNC][kMaxKR] (FP16) - up to
// 58 KB, past the 48 KB a launch gets without asking (set_smem)
constexpr size_t smem_n_bytes(int K) {
return (size_t) (kWarps * kCols + kNC * kCols + 2 * kNC * kCols) * 4 + (size_t) kWarps * 64 * K * 4 +
(size_t) kNC * kMaxKR * 2;
}
struct SmemN {
float *red, *outc, *gu;
uint32_t* stage;
__half* xs;
};
template <int K>
__device__ __forceinline__ SmemN smem_n(unsigned char* p) {
SmemN s;
s.red = (float*) p;
s.outc = s.red + kWarps * kCols;
s.gu = s.outc + kNC * kCols;
s.stage = (uint32_t*) (s.gu + 2 * kNC * kCols);
s.xs = (__half*) (s.stage + kWarps * 64 * K);
return s;
}
template <int K, int cb>
__global__ void __launch_bounds__(kThreads) mv_kernel(const KBatch b) {
__shared__ __half xs[kMaxKR];
__shared__ uint32_t stage[kWarps * 64 * K];
__shared__ float red[kWarps * kCols];
__shared__ int last;
int ji = 0;
while ((int) blockIdx.x >= b.blk_end[ji]) ++ji;
const KJob& J = b.j[ji];
const int local = (int) blockIdx.x - (ji > 0 ? b.blk_end[ji - 1] : 0);
const int g = local / J.S, sp = local % J.S;
const int k0 = sp * J.kr, k1 = min(J.k, k0 + J.kr);
rotate_in(J.xf, J.xq, J.suh, k0, k1 - k0, xs);
__syncthreads();
block_gemv<K, cb>(J.tr, J.ld, g * 8, k0 / 16, k1 / 16, xs, stage, red);
const int warp = threadIdx.x >> 5;
if (J.S == 1) {
if (warp == 0)
epilogue(red, J.svh + g * kCols, J.alpha, J.bias != nullptr ? J.bias + g * kCols : nullptr,
J.y + g * kCols);
return;
}
if (threadIdx.x < kCols) J.part[(size_t) sp * J.n + g * kCols + threadIdx.x] = red[threadIdx.x];
__threadfence();
__syncthreads();
if (threadIdx.x == 0) last = atomicAdd(&J.cnt[g], 1u) == (unsigned) (J.S - 1);
__syncthreads();
if (!last) return;
__threadfence();
if (threadIdx.x < kCols) {
float s = 0.0f;
for (int i = 0; i < J.S; ++i) s += *(volatile const float*) &J.part[(size_t) i * J.n + g * kCols + threadIdx.x];
red[threadIdx.x] = s;
}
__syncthreads();
if (warp == 0)
epilogue(red, J.svh + g * kCols, J.alpha, J.bias != nullptr ? J.bias + g * kCols : nullptr, J.y + g * kCols);
if (threadIdx.x == 0) J.cnt[g] = 0u;
}
// mv_kernel for a job's nc activations at once (a verify window's tokens): the same input split, the weights read and
// decoded once for all of them (block_gemv_n), each activation's partials and sums in mv_kernel's order - every
// activation's y is mv_kernel's for it alone, bit for bit
template <int K, int cb>
__global__ void __launch_bounds__(kThreads) mv_n_kernel(const KBatch b) {
extern __shared__ __align__(16) unsigned char smem_raw[];
const SmemN sm = smem_n<K>(smem_raw);
__shared__ int last;
int ji = 0;
while ((int) blockIdx.x >= b.blk_end[ji]) ++ji;
const KJob& J = b.j[ji];
const int local = (int) blockIdx.x - (ji > 0 ? b.blk_end[ji - 1] : 0);
const int g = local / J.S, sp = local % J.S;
const int k0 = sp * J.kr, k1 = min(J.k, k0 + J.kr);
for (int c = 0; c < J.nc; ++c)
rotate_in(J.xf != nullptr ? J.xf + c * J.xf_cs : nullptr,
J.xq != nullptr ? (const Q81*) ((const uint8_t*) J.xq + c * J.xq_cs) : nullptr, J.suh, k0, k1 - k0,
sm.xs + c * kMaxKR);
__syncthreads();
block_gemv_n<K, cb>(J.tr, J.ld, g * 8, k0 / 16, k1 / 16, sm.xs, J.nc, sm.stage, sm.red, sm.outc);
const int warp = threadIdx.x >> 5;
const float* bias = J.bias != nullptr ? J.bias + g * kCols : nullptr;
if (J.S == 1) {
if (warp < J.nc)
epilogue(sm.outc + warp * kCols, J.svh + g * kCols, J.alpha, bias, J.y + warp * J.y_cs + g * kCols);
return;
}
if (threadIdx.x < kCols)
for (int c = 0; c < J.nc; ++c)
J.part[((size_t) c * J.S + sp) * J.n + g * kCols + threadIdx.x] = sm.outc[c * kCols + threadIdx.x];
__threadfence();
__syncthreads();
if (threadIdx.x == 0) last = atomicAdd(&J.cnt[g], 1u) == (unsigned) (J.S - 1);
__syncthreads();
if (!last) return;
__threadfence();
if (threadIdx.x < kCols)
for (int c = 0; c < J.nc; ++c) {
float s = 0.0f;
for (int i = 0; i < J.S; ++i)
s += *(volatile const float*) &J.part[((size_t) c * J.S + i) * J.n + g * kCols + threadIdx.x];
sm.outc[c * kCols + threadIdx.x] = s;
}
__syncthreads();
if (warp < J.nc) epilogue(sm.outc + warp * kCols, J.svh + g * kCols, J.alpha, bias, J.y + warp * J.y_cs + g * kCols);
if (threadIdx.x == 0) J.cnt[g] = 0u;
}
// ---------------------------------------------------------------- the routed experts
struct KMoe {
const unsigned long long* plan_ptr;
const float* plan_w;
const float* cpu_part;
const int* cpu_flag;
const float* x;
float* h; // [k][n_ff]
const float* sh_out;
float* out;
float* part; // [k][n_embd]
unsigned* cnt; // n_embd / 128
size_t suh[3], svh[3], tr[3];
int k, n_embd, n_ff;
float limit;
};
// the pieces the token's experts (moe_*_kernel) and a window's grouped experts (win_*_kernel) share, so each window
// token gets the token path's bits: one warp's output block of 128 (H, then svh) ...
__device__ __forceinline__ void block_out(const float* red, const uint16_t* svh, float* dst) {
const int lane = threadIdx.x & 31;
float v[4];
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] = red[lane * 4 + i];
had128(v, lane);
#pragma unroll
for (int i = 0; i < 4; ++i) dst[lane * 4 + i] = __fmul_rn(v[i], h2f(svh[lane * 4 + i]));
}
// ... the clamped swiglu ...
__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);
}
// ... and one output's sum: the experts' rows in plan order (p[i]: expert i's, 0 for one not on the device), the CPU
// lane's part when flagged (cpu_part: null when not), the shared expert's row (sh: 0 without one)
__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);
}
// grid (n_ff / 128, k): expert blockIdx.y's gate and up for 128 h values, then the clamped swiglu
template <int K, int cb>
__global__ void __launch_bounds__(kThreads) moe_gate_up_kernel(const KMoe a) {
__shared__ __half xs[2][kMaxKR];
__shared__ uint32_t stage[kWarps * 64 * K];
__shared__ float red[kWarps * kCols];
__shared__ float gu[2][kCols];
const int ei = blockIdx.y, g = blockIdx.x;
const unsigned long long ptr = a.plan_ptr[ei];
if (ptr == 0ull) return;
const uint8_t* blob = (const uint8_t*) ptr;
const int warp = threadIdx.x >> 5;
for (int r = 0; r < 2; ++r) rotate_in(a.x, nullptr, (const uint16_t*) (blob + a.suh[r]), 0, a.n_embd, xs[r]);
__syncthreads();
for (int r = 0; r < 2; ++r) {
block_gemv<K, cb>((const uint32_t*) (blob + a.tr[r]), a.n_ff / 16, g * 8, 0, a.n_embd / 16, xs[r], stage, red);
if (warp == 0) block_out(red, (const uint16_t*) (blob + a.svh[r]) + g * kCols, gu[r]);
__syncthreads();
}
if (threadIdx.x < kCols)
a.h[(size_t) ei * a.n_ff + g * kCols + threadIdx.x] = swiglu(gu[0][threadIdx.x], gu[1][threadIdx.x], a.limit);
}
// grid (n_embd / 128, k): expert blockIdx.y's down rows for 128 outputs; the last block of each output block adds
// the experts up in plan order (as the engine's moe_down), then the CPU lane's part and the shared expert
template <int K, int cb>
__global__ void __launch_bounds__(kThreads) moe_down_kernel(const KMoe a) {
__shared__ __half xs[kMaxKR];
__shared__ uint32_t stage[kWarps * 64 * K];
__shared__ float red[kWarps * kCols];
__shared__ int last;
const int ei = blockIdx.y, g = blockIdx.x;
const unsigned long long ptr = a.plan_ptr[ei];
const int warp = threadIdx.x >> 5;
float* part = a.part + (size_t) ei * a.n_embd + g * kCols;
if (ptr != 0ull) {
const uint8_t* blob = (const uint8_t*) ptr;
rotate_in(a.h + (size_t) ei * a.n_ff, nullptr, (const uint16_t*) (blob + a.suh[2]), 0, a.n_ff, xs);
__syncthreads();
block_gemv<K, cb>((const uint32_t*) (blob + a.tr[2]), a.n_embd / 16, g * 8, 0, a.n_ff / 16, xs, stage, red);
if (warp == 0) block_out(red, (const uint16_t*) (blob + a.svh[2]) + g * kCols, part);
} else if (threadIdx.x < kCols) {
part[threadIdx.x] = 0.0f;
}
__threadfence();
__syncthreads();
if (threadIdx.x == 0) last = atomicAdd(&a.cnt[g], 1u) == (unsigned) (a.k - 1);
__syncthreads();
if (!last) return;
__threadfence();
if (threadIdx.x < kCols) {
const int r = g * kCols + threadIdx.x;
float p[8];
for (int i = 0; i < a.k; ++i) p[i] = *(volatile const float*) &a.part[(size_t) i * a.n_embd + r];
a.out[r] = combine(a.plan_w, p, a.k, a.cpu_flag != nullptr && *a.cpu_flag ? a.cpu_part + r : nullptr,
a.sh_out != nullptr ? a.sh_out[r] : 0.0f);
}
if (threadIdx.x == 0) a.cnt[g] = 0u;
}
// ---------------------------------------------------------------- a verify window's routed experts
// gf::moe_win_experts' grouping (group g: one expert, its blob at grp_ptr[g]; its entries e = t * 8 + i at
// grp_ent[grp_start[g] ..)), each group's weights read and decoded once for up to kNC of its tokens at a time (as
// exllamav3's fused MoE runs a run of slots that picked one expert as the rows of one MMA tile), with the token
// path's arithmetic per entry: every token's output is moe_gate_up + moe_down's for it alone, bit for bit
struct KWin {
const unsigned long long* grp_ptr;
const int *grp_start, *grp_ent, *n_groups;
const unsigned long long* plan_ptr;
const float* plan_w;
const float* cpu_part;
const int* cpu_flag;
const float* x;
size_t x_stride;
float* h; // [T * 8][n_ff]
float* part; // [T * 8][n_embd]
const float* sh_out; // [T][n_embd]
float* out;
size_t out_stride;
size_t suh[3], svh[3], tr[3];
int k, n_embd, n_ff;
float limit;
};
// grid (n_ff / 128, groups at most): group blockIdx.y's gate and up for 128 h values of each entry, the clamped swiglu
template <int K, int cb>
__global__ void __launch_bounds__(kThreads) win_gu_kernel(const KWin a) {
extern __shared__ __align__(16) unsigned char smem_raw[];
const SmemN sm = smem_n<K>(smem_raw);
const int grp = blockIdx.y, g = blockIdx.x;
if (grp >= *a.n_groups) return;
const uint8_t* blob = (const uint8_t*) a.grp_ptr[grp];
const int warp = threadIdx.x >> 5;
const int m1 = a.grp_start[grp + 1];
for (int m0 = a.grp_start[grp]; m0 < m1; m0 += kNC) {
const int nc = min(kNC, m1 - m0);
for (int r = 0; r < 2; ++r) {
for (int c = 0; c < nc; ++c)
rotate_in(a.x + (size_t) (a.grp_ent[m0 + c] >> 3) * a.x_stride, nullptr,
(const uint16_t*) (blob + a.suh[r]), 0, a.n_embd, sm.xs + c * kMaxKR);
__syncthreads();
block_gemv_n<K, cb>((const uint32_t*) (blob + a.tr[r]), a.n_ff / 16, g * 8, 0, a.n_embd / 16, sm.xs, nc,
sm.stage, sm.red, sm.outc);
if (warp < nc)
block_out(sm.outc + warp * kCols, (const uint16_t*) (blob + a.svh[r]) + g * kCols,
sm.gu + (r * kNC + warp) * kCols);
__syncthreads();
}
if (threadIdx.x < kCols)
for (int c = 0; c < nc; ++c)
a.h[(size_t) a.grp_ent[m0 + c] * a.n_ff + g * kCols + threadIdx.x] =
swiglu(sm.gu[c * kCols + threadIdx.x], sm.gu[(kNC + c) * kCols + threadIdx.x], a.limit);
__syncthreads();
}
}
// grid (n_embd / 128, groups at most): group blockIdx.y's down rows for 128 outputs of each entry into its part rows
template <int K, int cb>
__global__ void __launch_bounds__(kThreads) win_down_kernel(const KWin a) {
extern __shared__ __align__(16) unsigned char smem_raw[];
const SmemN sm = smem_n<K>(smem_raw);
const int grp = blockIdx.y, g = blockIdx.x;
if (grp >= *a.n_groups) return;
const uint8_t* blob = (const uint8_t*) a.grp_ptr[grp];
const int warp = threadIdx.x >> 5;
const int m1 = a.grp_start[grp + 1];
for (int m0 = a.grp_start[grp]; m0 < m1; m0 += kNC) {
const int nc = min(kNC, m1 - m0);
for (int c = 0; c < nc; ++c)
rotate_in(a.h + (size_t) a.grp_ent[m0 + c] * a.n_ff, nullptr, (const uint16_t*) (blob + a.suh[2]), 0,
a.n_ff, sm.xs + c * kMaxKR);
__syncthreads();
block_gemv_n<K, cb>((const uint32_t*) (blob + a.tr[2]), a.n_embd / 16, g * 8, 0, a.n_ff / 16, sm.xs, nc,
sm.stage, sm.red, sm.outc);
if (warp < nc)
block_out(sm.outc + warp * kCols, (const uint16_t*) (blob + a.svh[2]) + g * kCols,
a.part + (size_t) a.grp_ent[m0 + warp] * a.n_embd + g * kCols);
__syncthreads();
}
}
// grid (n_embd / 128, T): each token's outputs, moe_down_kernel's combine (an entry off the device adds 0)
__global__ void __launch_bounds__(kCols) win_combine_kernel(const KWin a) {
const int t = blockIdx.y, r = blockIdx.x * kCols + threadIdx.x;
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[t] ? a.cpu_part + (size_t) t * a.n_embd + r : nullptr,
a.sh_out != nullptr ? a.sh_out[(size_t) t * a.n_embd + r] : 0.0f);
}
// ---------------------------------------------------------------- dispatch
// F(K, cb) for K 1..8 and the three codebooks
template <template <int, int> class F, typename... A>
bool dispatch(int K, int cb, A&&... args) {
#define EXL3_CASE(KK) \
case KK: \
if (cb == 2) F<KK, 2>::run(std::forward<A>(args)...); \
else if (cb == 1) F<KK, 1>::run(std::forward<A>(args)...); \
else F<KK, 0>::run(std::forward<A>(args)...); \
return true;
switch (K) {
EXL3_CASE(1) EXL3_CASE(2) EXL3_CASE(3) EXL3_CASE(4) EXL3_CASE(5) EXL3_CASE(6) EXL3_CASE(7) EXL3_CASE(8)
default: return false;
}
#undef EXL3_CASE
}
template <int K, int cb> struct RunMv {
static void run(const KBatch& b, int blocks, cudaStream_t s) { mv_kernel<K, cb><<<blocks, kThreads, 0, s>>>(b); }
};
template <int K, int cb> struct RunMvN {
static void run(const KBatch& b, int blocks, cudaStream_t s) {
mv_n_kernel<K, cb><<<blocks, kThreads, smem_n_bytes(K), s>>>(b);
}
};
template <int K, int cb> struct RunWin {
static void run(const KWin& a, int groups, cudaStream_t s) {
win_gu_kernel<K, cb><<<dim3((unsigned) (a.n_ff / kCols), (unsigned) groups), kThreads, smem_n_bytes(K), s>>>(a);
}
};
template <int K, int cb> struct RunWinDown {
static void run(const KWin& a, int groups, cudaStream_t s) {
win_down_kernel<K, cb><<<dim3((unsigned) (a.n_embd / kCols), (unsigned) groups), kThreads, smem_n_bytes(K),
s>>>(a);
}
};
template <int K, int cb> struct AllowSmemN {
static void run() {
const int b = (int) smem_n_bytes(K);
cudaFuncSetAttribute(mv_n_kernel<K, cb>, cudaFuncAttributeMaxDynamicSharedMemorySize, b);
cudaFuncSetAttribute(win_gu_kernel<K, cb>, cudaFuncAttributeMaxDynamicSharedMemorySize, b);
cudaFuncSetAttribute(win_down_kernel<K, cb>, cudaFuncAttributeMaxDynamicSharedMemorySize, b);
}
};
template <int K, int cb> struct RunGU {
static void run(const KMoe& a, cudaStream_t s) {
moe_gate_up_kernel<K, cb><<<dim3((unsigned) (a.n_ff / kCols), (unsigned) a.k), kThreads, 0, s>>>(a);
}
};
template <int K, int cb> struct RunDown {
static void run(const KMoe& a, cudaStream_t s) {
moe_down_kernel<K, cb><<<dim3((unsigned) (a.n_embd / kCols), (unsigned) a.k), kThreads, 0, s>>>(a);
}
};
// ---------------------------------------------------------------- per-stream scratch
constexpr size_t kPartFloats = (size_t) 2 << 20; // split partials: 8 MB
constexpr size_t kCounters = 16384;
constexpr size_t kHFloats = (size_t) 8 * 8192; // the experts' h
struct Scratch {
float* part = nullptr;
unsigned* cnt = nullptr;
float* h = nullptr;
};
std::mutex g_mu;
std::map<std::pair<int, cudaStream_t>, Scratch> g_scratch;
Scratch* scratch(cudaStream_t s) {
int dev = 0;
cudaGetDevice(&dev);
std::lock_guard<std::mutex> lk(g_mu);
auto it = g_scratch.find({dev, s});
if (it != g_scratch.end()) return &it->second;
cudaStreamCaptureStatus cs = cudaStreamCaptureStatusNone;
if (cudaStreamIsCapturing(s, &cs) == cudaSuccess && cs != cudaStreamCaptureStatusNone) {
std::fprintf(stderr, "exl3: scratch for a stream first seen inside a graph capture (call exl3::prepare)\n");
return nullptr;
}
Scratch sc;
if (cudaMalloc(&sc.part, kPartFloats * sizeof(float)) != cudaSuccess ||
cudaMalloc(&sc.cnt, kCounters * sizeof(unsigned)) != cudaSuccess ||
cudaMalloc(&sc.h, kHFloats * sizeof(float)) != cudaSuccess ||
cudaMemsetAsync(sc.cnt, 0, kCounters * sizeof(unsigned), s) != cudaSuccess) {
std::fprintf(stderr, "exl3: scratch did not allocate\n");
return nullptr;
}
cudaStreamSynchronize(s);
return &(g_scratch[{dev, s}] = sc);
}
int sm_count() {
int dev = 0, sms = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev);
return std::max(1, sms);
}
// the several-activation kernels may use smem_n_bytes of shared memory: asked once per device (prepare, before a graph
// capture; else at the first such launch). A device that cannot give a block that much (48 KB GPUs) runs one
// activation at a time instead
constexpr int kMaxDev = 64;
std::atomic<int> g_smem_n[kMaxDev]; // 0 not asked, 1 allowed, 2 refused
bool allow_smem_n() {
int dev = 0;
cudaGetDevice(&dev);
if (dev < 0 || dev >= kMaxDev) return false;
const int st = g_smem_n[dev].load(std::memory_order_acquire);
if (st != 0) return st == 1;
std::lock_guard<std::mutex> lk(g_mu);
if (g_smem_n[dev].load(std::memory_order_relaxed) != 0) return g_smem_n[dev].load() == 1;
int optin = 0;
cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev);
bool ok = (size_t) optin >= smem_n_bytes(8);
if (ok) {
for (int K = 1; K <= 8; ++K)
for (int cb = 0; cb <= 2; ++cb) dispatch<AllowSmemN>(K, cb);
ok = cudaGetLastError() == cudaSuccess;
}
if (!ok)
std::fprintf(stderr, "exl3: CUDA%d gives a block %d bytes of shared memory, the several-activation kernels "
"need %zu - a verify window's tokens run one at a time there\n", dev, optin,
smem_n_bytes(8));
g_smem_n[dev].store(ok ? 1 : 2, std::memory_order_release);
return ok;
}
// mv's input split for m: S blocks of kr inputs per output block, at most kMaxKR inputs a block and about two blocks
// per SM (the same for every activation count: mv_kernel and mv_n_kernel sum each activation alike)
void mv_split(const Mat& m, int sms, int& S, int& kr) {
const int groups = m.n / kCols;
S = (m.k + kMaxKR - 1) / kMaxKR;
while (groups * S < 2 * sms && m.k / (S * 2) >= 256) S *= 2;
kr = ((m.k + S - 1) / S + 127) / 128 * 128;
S = (m.k + kr - 1) / kr;
}
} // namespace
int launch_errors() { return g_launch_errors.load(std::memory_order_relaxed); }
bool prepare(cudaStream_t s) {
if (scratch(s) == nullptr) return false;
(void) allow_smem_n();
return true;
}
bool several_ok() { return allow_smem_n(); }
bool mv(const MvJob* jobs, int n, cudaStream_t s) {
if (n <= 0 || n > kMaxMvJobs) return false;
Scratch* sc = scratch(s);
if (sc == nullptr) return false;
const int sms = sm_count();
// the launch units: a job of one activation is mv_kernel's, a job of several mv_n_kernel's in runs of up to kNC
// (one mv_kernel unit an activation where the device lacks the shared memory)
struct Unit {
int j, c0, nc;
};
Unit units[kMaxMvJobs * kMaxMvCols];
int nu = 0;
bool several = false;
for (int j = 0; j < n; ++j) several = several || jobs[j].ncol > 1;
const int run = several && allow_smem_n() ? kNC : 1;
for (int j = 0; j < n; ++j) {
const Mat& m = *jobs[j].m;
if (!supported(m) || jobs[j].y == nullptr || (jobs[j].xf == nullptr && jobs[j].xq == nullptr) ||
jobs[j].ncol < 1 || jobs[j].ncol > kMaxMvCols) {
std::fprintf(stderr, "exl3 mv: job %d unsupported (k %d n %d K %d cb %d, %d activations)\n", j, m.k, m.n,
m.K, m.cb, jobs[j].ncol);
return false;
}
for (int c0 = 0; c0 < jobs[j].ncol; c0 += run) units[nu++] = {j, c0, std::min(run, jobs[j].ncol - c0)};
}
bool done[sizeof(units) / sizeof(units[0])] = {};
for (int i = 0; i < nu; ++i) {
if (done[i]) continue;
const Mat& m0 = *jobs[units[i].j].m;
const bool multi = units[i].nc > 1;
// a launch: the units of one (K, codebook, kernel), as many as KBatch and the split scratch take (the next
// launch on the stream may use the scratch again: this one's last blocks are done with it by then)
KBatch b{};
int blocks = 0, nb = 0;
size_t part_at = 0, cnt_at = 0;
for (int u = i; u < nu && nb < kMaxMvJobs; ++u) {
const MvJob& job = jobs[units[u].j];
const Mat& m = *job.m;
if (done[u] || m.K != m0.K || m.cb != m0.cb || (units[u].nc > 1) != multi) continue;
const int c0 = units[u].c0, nc = units[u].nc, groups = m.n / kCols;
int S = 1, kr = 0;
mv_split(m, sms, S, kr);
const size_t need = S > 1 ? (size_t) S * m.n * nc : 0;
if (S > 1 && (part_at + need > kPartFloats || cnt_at + (size_t) groups > kCounters)) {
if (nb > 0) continue; // the next launch
std::fprintf(stderr, "exl3 mv: scratch too small for k %d n %d (%d activations)\n", m.k, m.n, nc);
return false;
}
done[u] = true;
KJob& J = b.j[nb];
J.tr = m.trellis;
J.suh = m.suh;
J.svh = m.svh;
J.xf = job.xf != nullptr ? job.xf + c0 * job.xf_cs : nullptr;
J.xq = job.xq != nullptr ? (const Q81*) ((const uint8_t*) job.xq + c0 * job.xq_cs) : nullptr;
J.y = job.y + c0 * job.y_cs;
J.bias = job.bias;
J.alpha = job.alpha;
J.k = m.k;
J.n = m.n;
J.ld = m.ld > 0 ? m.ld : m.n / 16;
J.S = S;
J.kr = kr;
J.part = sc->part + part_at;
J.cnt = sc->cnt + cnt_at;
J.nc = nc;
J.xf_cs = job.xf_cs;
J.xq_cs = job.xq_cs;
J.y_cs = job.y_cs;
part_at += need;
if (S > 1) cnt_at += (size_t) groups;
blocks += groups * S;
b.blk_end[nb++] = blocks;
}
b.n = nb;
if (!(multi ? dispatch<RunMvN>(m0.K, m0.cb, b, blocks, s) : dispatch<RunMv>(m0.K, m0.cb, b, blocks, s)))
return false;
}
launch_check("mv");
return true;
}
static bool moe_args(const MoeArgs& a, KMoe& m, cudaStream_t s) {
Scratch* sc = scratch(s);
if (sc == nullptr) return false;
if (a.k < 1 || a.k > 8 || a.n_embd % kCols != 0 || a.n_ff % kCols != 0 || a.n_embd > kMaxKR ||
a.n_ff > kMaxKR || (size_t) a.k * a.n_ff > kHFloats || (size_t) a.k * a.n_embd > kPartFloats ||
(size_t) (a.n_embd / kCols) > kCounters) {
std::fprintf(stderr, "exl3 moe: geometry not covered (k %d n_embd %d n_ff %d)\n", a.k, a.n_embd, a.n_ff);
return false;
}
m = KMoe{};
m.plan_ptr = a.plan_ptr;
m.plan_w = a.plan_w;
m.cpu_part = a.cpu_part;
m.cpu_flag = a.cpu_flag;
m.h = sc->h;
m.part = sc->part;
m.cnt = sc->cnt;
for (int r = 0; r < 3; ++r) {
m.suh[r] = a.lay.suh[r];
m.svh[r] = a.lay.svh[r];
m.tr[r] = a.lay.trellis[r];
}
m.k = a.k;
m.n_embd = a.n_embd;
m.n_ff = a.n_ff;
m.limit = a.limit;
return true;
}
void moe_gate_up(const MoeArgs& a, const float* x, float* h, cudaStream_t s) {
KMoe m;
if (!moe_args(a, m, s)) return;
if (a.lay.K[0] != a.lay.K[1]) {
std::fprintf(stderr, "exl3 moe_gate_up: gate K %d != up K %d\n", a.lay.K[0], a.lay.K[1]);
return;
}
m.x = x;
if (h != nullptr) m.h = h;
if (!dispatch<RunGU>(a.lay.K[0], a.lay.cb, m, s)) std::fprintf(stderr, "exl3 moe_gate_up: K %d\n", a.lay.K[0]);
launch_check("moe_gate_up");
}
void moe_down(const MoeArgs& a, const float* h, const float* sh_out, float* out, cudaStream_t s) {
KMoe m;
if (!moe_args(a, m, s)) return;
if (h != nullptr) m.h = const_cast<float*>(h);
m.sh_out = sh_out;
m.out = out;
if (!dispatch<RunDown>(a.lay.K[2], a.lay.cb, m, s)) std::fprintf(stderr, "exl3 moe_down: K %d\n", a.lay.K[2]);
launch_check("moe_down");
}
bool win_experts(const WinArgs& a, cudaStream_t s) {
if (a.T < 1 || a.k < 1 || a.k > 8 || a.n_embd % kCols != 0 || a.n_ff % kCols != 0 || a.n_embd > kMaxKR ||
a.n_ff > kMaxKR || a.lay.K[0] != a.lay.K[1] || a.h == nullptr || a.part == nullptr || a.out == nullptr) {
std::fprintf(stderr, "exl3 win_experts: not covered (T %d k %d n_embd %d n_ff %d, gate K %d up K %d)\n", a.T,
a.k, a.n_embd, a.n_ff, a.lay.K[0], a.lay.K[1]);
return false;
}
if (!allow_smem_n()) return false;
KWin w{};
w.grp_ptr = a.grp_ptr;
w.grp_start = a.grp_start;
w.grp_ent = a.grp_ent;
w.n_groups = a.n_groups;
w.plan_ptr = a.plan_ptr;
w.plan_w = a.plan_w;
w.cpu_part = a.cpu_part;
w.cpu_flag = a.cpu_flag;
w.x = a.x;
w.x_stride = a.x_stride;
w.h = a.h;
w.part = a.part;
w.sh_out = a.sh_out;
w.out = a.out;
w.out_stride = a.out_stride;
for (int r = 0; r < 3; ++r) {
w.suh[r] = a.lay.suh[r];
w.svh[r] = a.lay.svh[r];
w.tr[r] = a.lay.trellis[r];
}
w.k = a.k;
w.n_embd = a.n_embd;
w.n_ff = a.n_ff;
w.limit = a.limit;
const int groups = a.T * a.k; // at most (the blocks past the real count return at once)
if (!dispatch<RunWin>(a.lay.K[0], a.lay.cb, w, groups, s) ||
!dispatch<RunWinDown>(a.lay.K[2], a.lay.cb, w, groups, s))
return false;
win_combine_kernel<<<dim3((unsigned) (a.n_embd / kCols), (unsigned) a.T), kCols, 0, s>>>(w);
launch_check("win_experts");
return true;
}
} // namespace strata::dsv41k::exl3::legacy
#endif
+57
View File
@@ -0,0 +1,57 @@
// 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/dsv41/vendor/moe_win.cu - the window's expert grouping kernel.
// Extracted from Project Maya's src/kernels/cuda/glm_fast.cu (MIT, see third_party/project-maya/NOTICE.md).
#include "strata/dsv41/moe_win.hpp"
#include <cstdio>
#include <cstdlib>
namespace strata::dsv41k::glmf {
namespace {
constexpr int kWinEnt = kMaxWinTokens * 8;
// the entries grouped by expert slot (in order of first appearance), each group's members in entry order (t * 8 + i)
// (the tables in shared memory: as locals they were a 2.6 KB stack a thread, which the driver reserves for every thread
// the device can hold - ~420 MB on a V100 - and a launch failed "out of memory" once the expert pool had the rest)
__global__ void moe_win_group_kernel(const __grid_constant__ MoeWin w) {
__shared__ unsigned long long gp[kWinEnt];
__shared__ int cnt[kWinEnt], gof[kWinEnt], fill[kWinEnt + 1];
if (threadIdx.x != 0) return;
int ng = 0;
for (int t = 0; t < w.T; ++t)
for (int i = 0; i < 8; ++i) {
const int e = t * 8 + i;
gof[e] = -1;
const unsigned long long p = i < w.k ? w.plan_ptr[e] : 0ull;
if (p == 0ull) continue;
int g = 0;
while (g < ng && gp[g] != p) ++g;
if (g == ng) {
gp[ng] = p;
cnt[ng++] = 0;
}
++cnt[g];
gof[e] = g;
}
fill[0] = 0;
for (int g = 0; g < ng; ++g) {
w.grp_ptr[g] = gp[g];
w.grp_start[g] = fill[g];
fill[g + 1] = fill[g] + cnt[g];
}
w.grp_start[ng] = fill[ng];
for (int e = 0; e < w.T * 8; ++e)
if (gof[e] >= 0) w.grp_ent[fill[gof[e]]++] = e;
*w.n_groups = ng;
}
} // namespace
void moe_win_group(const MoeWin& w, cudaStream_t s) {
moe_win_group_kernel<<<1, 32, 0, s>>>(w);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "dsv41: moe_win_group: %s\n", cudaGetErrorString(e));
std::abort();
}
}
} // namespace strata::dsv41k::glmf
+581
View File
@@ -0,0 +1,581 @@
// 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/kernels/cuda/sampler.cu - P2.S2: the sampler chain, in llama.cpp's order.
//
// penalties -> top_k -> top_p -> min_p -> temperature -> pick
//
// THE ORDER IS THE WHOLE CONTENT OF THIS FILE. llama.cpp builds its chain by walking `params.samplers`, whose
// default is { PENALTIES, DRY, TOP_N_SIGMA, TOP_K, TYPICAL_P, TOP_P, MIN_P, XTC, TEMPERATURE } (`common/common.h`
// at 3cf03257) - ONE penalties stage, first, and TEMPERATURE AFTER THE TRUNCATION FILTERS. (Issue #53: this file
// used to apply the penalties a second time after the temperature, and min_p before top_p - both taken from the
// order of the `case` labels in `common/sampling.cpp`, which is not the order the chain runs.) Every order
// produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test
// does that against an independently computed distribution.
//
// Both kernels put ONE BLOCK per token over the vocabulary: `sampler_greedy_kernel` is the plain argmax,
// `sampler_kernel` runs the sampled chain as `top_k` block-argmax rounds followed by the top_p / temperature /
// draw chain (its header says why the selection must be parallel and why the tie rule keeps the semantics).
#include "strata/dsv41/sampler.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
namespace strata::dsv41k {
namespace {
// Philox 4x32-10, the counter-based generator the phase asks for. Counter-based matters because it makes the
// stream a function of (seed, position) rather than of how many draws came before - so a batch can be sampled
// in any order and a run is reproducible.
__device__ __forceinline__ uint32_t philox4x32_round(uint32_t& c0, uint32_t& c1, uint32_t& c2, uint32_t& c3,
uint32_t k0, uint32_t k1) {
const uint32_t hi0 = __umulhi(0x9E3779B9u, c0);
const uint32_t hi1 = __umulhi(0xBB67AE85u, c2);
const uint32_t lo0 = 0x9E3779B9u * c0;
const uint32_t lo1 = 0xBB67AE85u * c2;
const uint32_t n0 = hi1 ^ c1 ^ k0;
const uint32_t n1 = lo1;
const uint32_t n2 = hi0 ^ c3 ^ k1;
const uint32_t n3 = lo0;
c0 = n0; c1 = n1; c2 = n2; c3 = n3;
return 0;
}
__device__ __forceinline__ float philox_uniform(uint64_t seed, uint64_t counter) {
uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32);
uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32);
for (int i = 0; i < 10; ++i) {
philox4x32_round(c0, c1, c2, c3, (uint32_t) i, 0u);
}
// 24 bits of mantissa, so the value is uniform in [0,1) with no rounding to 1.0
return (float) (c0 >> 8) * (1.0f / 16777216.0f);
}
// `count_in_history` and the penalty application, transcribed from `llama_sampler_penalties_apply`.
// The repeat penalty MULTIPLIES for non-positive logits and DIVIDES for positive ones - dividing
// unconditionally is the natural reading of the source paper and it INVERTS the penalty on half the
// vocabulary. The presence penalty is `float(count > 0)`, a boolean, not the count.
__device__ __forceinline__ int history_count(const int* __restrict__ h, int n, int v) {
int c = 0;
for (int i = 0; i < n; ++i) if (h[i] == v) ++c;
return c;
}
__device__ __forceinline__ float apply_penalties(float logit, int count, const SamplerParams& p) {
if (count <= 0) return logit;
if (logit <= 0.0f) logit *= p.penalty_repeat;
else logit /= p.penalty_repeat;
logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
return logit;
}
/// **THE GREEDY ARGMAX, ONE BLOCK PER TOKEN, COVERING THE VOCABULARY.**
///
/// **WHY THIS IS A SEPARATE KERNEL AND NOT A BRANCH.** `sampler_kernel` is launched as a grid over TOKENS
/// with 64 threads and a `if (t >= n_tokens) return;` at the top. The decode path has `n_tokens == 1`, so
/// that launch was `<<<1, 64>>>`, 63 threads exited on the first line, and ONE THREAD walked all 248,320
/// logits in a dependent loop on one SM of 48. Measured in isolation (`bench/micro/sampler_cost.cu`):
/// **3.11 ms per token**, 5.7% of an ~54 ms token, and the whole of round 309's `sample` phase - the two
/// synchronisations around it are 0.03 ms each.
///
/// The obvious repair is to parallelise the scan inside `sampler_kernel`, and it is WRONG: with one thread
/// per token, a block reduction over the vocabulary has nothing to reduce, and the threads that returned
/// early are not there for `__syncthreads` or `__shfl_down_sync`. The first attempt did exactly that and
/// produced the token `5120` thirty-two times. The grid has to be over tokens with the BLOCK over the
/// vocabulary, which is a different launch configuration and therefore a different kernel.
///
/// **THE TIE RULE IS UNCHANGED AND THAT IS THE WHOLE CORRECTNESS ARGUMENT.** The serial scan walked `v`
/// ascending with `if (s > bv)`, so the LOWEST index wins a tie. Each thread keeps that rule over its own
/// strided subset and the reduction resolves two candidates by taking the larger value and, on equality, the
/// SMALLER index - the same total order, so `sampler_parity` and C1 see no change.
__global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vocab,
const int* __restrict__ history, int history_len, const SamplerParams p,
int pmin, int plen, int* __restrict__ out) {
const int t = blockIdx.x;
const float* l = logits + (size_t) t * n_vocab;
(void) pmin;
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
int hlen = 0;
if (hrow) {
hlen = plen < history_len ? plen : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the window is the TAIL
}
// PENALTY MEMBERSHIP AS A BITMAP. The history touches at most `hlen` tokens of a quarter-million
// vocabulary, but the naive `history_count` per candidate per argmax round costs O(k x n_vocab x hlen)
// integer compares (~318 M per token at k=20, hlen=64 - measured 45 -> 31 tok/s on a real workload).
// A shared bitmap gives an O(1) membership test, and only the (at most hlen) hits pay the count scan;
// the counts - and therefore every sampled value - are exactly what the per-candidate scan produced.
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
// The gate needs a NON-EMPTY WINDOW (`hlen > 0`): the launch sizes the shared bitmap only when penalties
// are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it.
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
__syncthreads();
}
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
// `n_vocab` is the "no candidate" index: it loses every comparison to a real one, so a thread with no
// elements contributes nothing rather than contributing a bogus zero.
float bv = __int_as_float(0xff800000); // -inf
int best = n_vocab;
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
const float s = apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p);
if (s > bv) { bv = s; best = v; }
}
for (int off = 16; off > 0; off >>= 1) {
const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off);
const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off);
if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
}
__shared__ float sv[32];
__shared__ int si[32];
const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
if (lane == 0) { sv[warp] = bv; si[warp] = best; }
__syncthreads();
if (warp == 0) {
const int nw = (int) ((blockDim.x + 31) >> 5);
float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000);
int wi = lane < nw ? si[lane] : n_vocab;
for (int off = 16; off > 0; off >>= 1) {
const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off);
const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off);
if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
}
// A tie between two `-inf` candidates leaves `wi == n_vocab`, and the serial version answered 0.
if (lane == 0) out[t] = (wi < n_vocab) ? wi : 0;
}
}
/// **THE SAMPLED PATH, ONE BLOCK PER TOKEN.** The kernel below replaced a version that ran the whole chain
/// in ONE THREAD per token (`<<<ceil(T/64), 64>>>`, so a 4-token window fielded four threads): `top_k` alone
/// was `k` sequential scans of the vocabulary with an inner sweep over the already-taken list - 20 x 248,320
/// iterations of dependent work on one SM - and a verify window measured **1.6 s in the sampler**, which made
/// every temperature-bearing request ~30x slower than a greedy one. The selection is `k` argmax rounds, and
/// an argmax over the vocabulary parallelises exactly like `sampler_greedy_kernel` (block over the vocab), so
/// the rounds run back to back inside a block-per-token launch: the per-token cost falls to
/// `k x n_vocab / 1024` plus `k` block reductions.
///
/// THE SEMANTICS ARE THE SERIAL ONES, EXACTLY. Each round's argmax resolves ties to the LOWEST index (the
/// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its
/// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the
/// Philox draw apply after the cut. `sampler_parity` pins all of it against the host reference.
// MODE 0 = the draw (sample_tokens, unchanged); 1 = speculative sampling's draft (sample_draft: the draw from the
// draft block's logits, on a Philox stream of its own, and its kept list in ql[t]); 2 = its verify (sample_verify:
// the draft draft[t] with probability min(1, p/q), else a draw from max(0, p - q)). The selection is shared.
constexpr uint64_t kSpecDraftKey = 0x5bd1e9955bd1e995ull, kSpecAcceptKey = 0x9e3779b97f4a7c15ull,
kSpecResidKey = 0xc2b2ae3d27d4eb4full;
// one block of 1024 threads per row (the launches below): the bound keeps every mode at 64 registers a thread, so a
// block fits the 64K-register file - unbounded, sm_75 (Turing) compiled the draft mode to 68 and its launch failed
// ("too many resources requested for launch") wherever the NextN block sat on a Turing card
template <int MODE>
__global__ void __launch_bounds__(1024) sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens,
const int* __restrict__ history, int history_len, const SamplerParams p,
int* __restrict__ out, SpecList* __restrict__ ql, const int* __restrict__ draft) {
const int t = blockIdx.x;
if (t >= n_tokens) return;
const float* l = logits + (size_t) t * n_vocab;
// Temperature is needed by BOTH stages below, so it is computed here; the chain still APPLIES it after
// the truncation filters - the survivors are chosen on the raw logits and only then scaled.
const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
// The penalty window is the last `penalty_last_n` entries of this row's history (disabled at this
// launch: `sample_tokens` refuses a non-zero `penalty_last_n` without a history buffer).
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
int hlen = 0;
if (hrow) {
hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the window is the TAIL
}
// the membership bitmap, as in `sampler_greedy_kernel` - see the cost note there. The gate needs an
// NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties are on, so a caller that hands over
// a stale history buffer with `penalty_last_n == 0` must not touch it.
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
__syncthreads();
}
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
// top_k in 1..64 is taken as given; 0 ("off") and anything wider mean the widest shortlist the kernel
// keeps, 64. Every row writes out[t]: a verify window reads all of them.
const int KMAX = 64;
int k = (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX;
if (k > n_vocab) k = n_vocab;
// ---- top_k: an exact RADIX SELECT, then a rank sort of the k survivors. The order is the serial one:
// descending by (penalised) logit, ties to the lower index - i.e. descending by the composite key
// (ordered(score) << 32) | ~index, which is distinct for every token. So: find the k-th largest ordered score
// T byte by byte (4 histogram passes over the vocabulary), keep every token above T and the lowest-indexed
// ones equal to T, then rank the k of them by the composite key. The k block-argmax rounds this replaces
// re-scanned the taken list for every token in every round: 1.5 ms a sample at top_k 20 and 11 ms at 64 on an
// RTX 4090 (the tail card's critical path in every sampled decode step).
// THE COMMON CASE takes two passes: a coarse histogram of the top 11 bits finds the bin that holds the k-th
// largest; every token in that bin or above (at most kCap) is copied to shared memory and ranked there by the
// composite key. A flat distribution with more than kCap tokens there takes the full radix select below.
__shared__ int sel_ids[KMAX];
__shared__ float sel_logit[KMAX];
__shared__ unsigned int sh_prefix, sh_remaining, sh_ncand, sh_tie_base;
// ONE shared pool, its parts reused phase by phase: the penalty bitmap (dynamic shared memory, 31 KB at a Qwen
// vocabulary) must still fit beside it under the 48 KB a launch gets without opting in.
// [0, 2048) the coarse histogram, then (once its bin is known) the candidates' scores and ids;
// in the fallback, the byte histogram and the k candidates
// [2048, 3072) the block scan
constexpr int kBins = 2048, kCap = 1024; // the coarse histogram: the ordered score's top 11 bits
__shared__ unsigned int pool[kBins + 1024];
unsigned int* coarse = pool;
unsigned int* ccand_u = pool;
int* ccand_i = (int*) pool + kCap;
unsigned int* hist = pool;
unsigned int* cand_u = pool + 256;
int* cand_i = (int*) pool + 256 + KMAX;
unsigned int* scan = pool + kBins;
__shared__ int sh_bin;
__shared__ unsigned int sh_ncoarse;
// a score's ordered bits: larger float -> larger unsigned; NaN below everything (never kept before a number)
auto ordered = [](float x) -> unsigned int {
unsigned int b = __float_as_uint(x);
if ((b & 0x7fffffffu) > 0x7f800000u) return 0u;
if (b == 0x80000000u) b = 0u; // -0 ties with +0, as the float comparison it replaces
return (b & 0x80000000u) ? ~b : (b | 0x80000000u);
};
auto score = [&](int v) -> float {
return apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p);
};
for (int b = threadIdx.x; b < kBins; b += blockDim.x) coarse[b] = 0u;
if (threadIdx.x == 0) sh_ncoarse = 0u;
__syncthreads();
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) atomicAdd(&coarse[ordered(score(v)) >> 21], 1u);
__syncthreads();
{ // the bin holding the k-th largest: suffix counts over the bins (2 bins a thread, a block scan)
const int nt = (int) blockDim.x, per = (kBins + nt - 1) / nt;
const int b_hi = kBins - 1 - (int) threadIdx.x * per; // this thread's bins, from the top down
unsigned int mine = 0u;
for (int j = 0; j < per && b_hi - j >= 0; ++j) mine += coarse[b_hi - j];
scan[threadIdx.x] = mine;
__syncthreads();
for (int off = 1; off < nt; off <<= 1) {
const unsigned int add = (int) threadIdx.x >= off ? scan[threadIdx.x - off] : 0u;
__syncthreads();
scan[threadIdx.x] += add;
__syncthreads();
}
unsigned int above = scan[threadIdx.x] - mine; // tokens in the bins above this thread's
if (above < (unsigned int) k && above + mine >= (unsigned int) k) {
for (int j = 0; j < per && b_hi - j >= 0; ++j) {
above += coarse[b_hi - j];
if (above >= (unsigned int) k) { sh_bin = b_hi - j; sh_tie_base = above; break; }
}
}
__syncthreads();
}
const int bin = sh_bin;
const bool coarse_ok = sh_tie_base <= (unsigned int) kCap; // the tokens in that bin and above fit
if (coarse_ok) {
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
const unsigned int u = ordered(score(v));
if ((int) (u >> 21) >= bin) {
const unsigned int at = atomicAdd(&sh_ncoarse, 1u);
if (at < (unsigned int) kCap) { ccand_u[at] = u; ccand_i[at] = v; }
}
}
__syncthreads();
const int nc = (int) min(sh_ncoarse, (unsigned int) kCap);
for (int i = threadIdx.x; i < nc; i += blockDim.x) {
const unsigned int ui = ccand_u[i];
const int ii = ccand_i[i];
int r = 0;
for (int j = 0; j < nc && r < k; ++j) {
const unsigned int uj = ccand_u[j];
r += uj > ui || (uj == ui && ccand_i[j] < ii);
}
if (r < k) {
sel_ids[r] = ii;
sel_logit[r] = score(ii);
}
}
__syncthreads();
} else {
if (threadIdx.x == 0) {
sh_prefix = 0u;
sh_remaining = (unsigned int) k;
sh_ncand = 0u;
}
unsigned int mask = 0u;
for (int pass = 0; pass < 4; ++pass) {
const int shift = 24 - 8 * pass;
for (int b = threadIdx.x; b < 256; b += blockDim.x) hist[b] = 0u;
__syncthreads();
const unsigned int prefix = sh_prefix;
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
const unsigned int u = ordered(score(v));
if ((u & mask) == prefix) atomicAdd(&hist[(u >> shift) & 255u], 1u);
}
__syncthreads();
if (threadIdx.x == 0) { // the digit that holds the remaining-th largest, from the top
unsigned int cum = 0u, rem = sh_remaining;
int d = 255;
for (; d > 0; --d) {
if (cum + hist[d] >= rem) break;
cum += hist[d];
}
sh_remaining = rem - cum;
sh_prefix = prefix | ((unsigned int) d << shift);
}
mask |= 255u << shift;
__syncthreads();
}
const unsigned int T = sh_prefix; // the k-th largest ordered score
const unsigned int need = sh_remaining; // how many tokens equal to T are kept (the lowest-indexed ones)
// every token above T (fewer than k of them)
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
const unsigned int u = ordered(score(v));
if (u > T) {
const unsigned int at = atomicAdd(&sh_ncand, 1u);
if (at < (unsigned int) KMAX) { cand_u[at] = u; cand_i[at] = v; }
}
}
__syncthreads();
if (threadIdx.x == 0) sh_tie_base = sh_ncand;
// the ties in index order: each thread counts its own contiguous range, an exclusive scan orders the ranges
{
const int nt = (int) blockDim.x;
const int chunk = (n_vocab + nt - 1) / nt;
const int lo = (int) threadIdx.x * chunk, hi = min(n_vocab, lo + chunk);
unsigned int mine = 0u;
for (int v = lo; v < hi; ++v) mine += ordered(score(v)) == T;
scan[threadIdx.x] = mine;
__syncthreads();
for (int off = 1; off < nt; off <<= 1) { // Hillis-Steele inclusive scan
const unsigned int add = (int) threadIdx.x >= off ? scan[threadIdx.x - off] : 0u;
__syncthreads();
scan[threadIdx.x] += add;
__syncthreads();
}
unsigned int rank = scan[threadIdx.x] - mine; // ties before this range
for (int v = lo; v < hi && rank < need; ++v)
if (ordered(score(v)) == T) {
const unsigned int at = sh_tie_base + rank;
if (at < (unsigned int) KMAX) { cand_u[at] = T; cand_i[at] = v; }
++rank;
}
}
__syncthreads();
// rank sort: candidate i's place is the number of candidates with a larger composite key
if ((int) threadIdx.x < k) {
const unsigned int ui = cand_u[threadIdx.x];
const int ii = cand_i[threadIdx.x];
int r = 0;
for (int j = 0; j < k; ++j) {
const unsigned int uj = cand_u[j];
r += uj > ui || (uj == ui && cand_i[j] < ii);
}
sel_ids[r] = ii;
sel_logit[r] = score(ii);
}
__syncthreads();
}
// ---- top_p over the top_k list (penalised logits, descending as the selection produced them), then min_p,
// then temperature and one Philox draw - llama.cpp's order (issue #53). Every thread computes the same chain
// redundantly over `sel_*` - the arithmetic is the serial kernel's, instruction for instruction - so they
// agree on `pick` and thread 0 writes it.
// (one thread: the chain is serial and in double precision, which consumer cards run at 1/64 rate - 1024
// threads computing it redundantly cost more than the whole selection above)
if (threadIdx.x != 0) return;
int n_keep = k;
float mx = sel_logit[0];
for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]);
if (p.top_p < 1.0f) {
double sum = 0.0;
for (int i = 0; i < k; ++i) sum += exp((double) sel_logit[i] - (double) mx);
double cum = 0.0;
int cut = k;
for (int i = 0; i < k; ++i) {
cum += exp((double) sel_logit[i] - (double) mx) / sum;
if (cum >= (double) p.top_p) { cut = i + 1; break; }
}
if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
n_keep = cut;
}
// ---- min_p on top_p's survivors: the descending prefix whose probability is at least `min_p` of the top
// token's. In logit space the threshold is `sel_logit[0] + logf(min_p)` - equivalent to `p >= min_p * p_max`
// without the overflow an exp of raw logits risks. 0 disables, and the head itself always survives
// (`expf(0) == 1 >= min_p` for min_p in 0..1), so the count never reaches zero.
if (p.min_p > 0.0f) {
const float thresh = sel_logit[0] + logf(p.min_p);
for (int i = 0; i < n_keep; ++i)
if (sel_logit[i] < thresh) { n_keep = i; break; }
}
// temperature only: the penalties were applied once, before the selection (issue #53: they were applied a
// second time here, after the temperature scaling - llama.cpp's chain has one penalties stage)
auto scaled = [&](int i) { return sel_logit[i] * inv_t; };
float smx = scaled(0);
for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, scaled(i));
double sum = 0.0;
for (int i = 0; i < n_keep; ++i) sum += exp((double) scaled(i) - (double) smx);
if constexpr (MODE == 0) {
const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
double cum = 0.0;
int pick = sel_ids[n_keep - 1];
for (int i = 0; i < n_keep; ++i) {
cum += exp((double) scaled(i) - (double) smx) / sum;
if ((double) u < cum) { pick = sel_ids[i]; break; }
}
if (threadIdx.x == 0) out[t] = pick;
} else {
double w[KMAX]; // the kept list's probabilities, as the plain draw computes them
for (int i = 0; i < n_keep; ++i) w[i] = exp((double) scaled(i) - (double) smx) / sum;
// the plain draw over w with a given uniform (MODE 0's loop)
auto draw = [&](float u) -> int {
double cum = 0.0;
int pick = sel_ids[n_keep - 1];
for (int i = 0; i < n_keep; ++i) {
cum += w[i];
if ((double) u < cum) { pick = sel_ids[i]; break; }
}
return pick;
};
if constexpr (MODE == 1) {
SpecList* q = ql + t;
q->n = n_keep;
for (int i = 0; i < n_keep; ++i) { q->ids[i] = sel_ids[i]; q->p[i] = w[i]; }
out[t] = draw(philox_uniform(p.seed ^ kSpecDraftKey, p.counter + (uint64_t) t));
} else {
const SpecList* q = ql + t;
const int d = draft[t];
const int qn = q->n < KMAX ? q->n : KMAX;
auto qof = [&](int id) -> double {
for (int j = 0; j < qn; ++j)
if (q->ids[j] == id) return q->p[j];
return 0.0;
};
double pd = 0.0;
for (int i = 0; i < n_keep; ++i)
if (sel_ids[i] == d) { pd = w[i]; break; }
const double qd = qof(d);
int pick = -1;
if (qd <= 0.0) {
pick = draw(philox_uniform(p.seed, p.counter + (uint64_t) t)); // not a draft from q: the plain draw
} else if ((double) philox_uniform(p.seed ^ kSpecAcceptKey, p.counter + (uint64_t) t) * qd < pd) {
pick = d; // kept: probability min(1, p(d)/q(d))
} else {
// rejected: a draw from max(0, p - q), renormalised - over p's kept list (p is 0 outside it)
double r[KMAX], z = 0.0;
for (int i = 0; i < n_keep; ++i) {
const double x = w[i] - qof(sel_ids[i]);
r[i] = x > 0.0 ? x : 0.0;
z += r[i];
}
const float u = philox_uniform(p.seed ^ kSpecResidKey, p.counter + (uint64_t) t);
if (z > 0.0) {
double cum = 0.0;
for (int i = 0; i < n_keep; ++i) {
if (r[i] <= 0.0) continue;
pick = sel_ids[i]; // the last one with residual mass, if rounding leaves cum below u
cum += r[i] / z;
if ((double) u < cum) break;
}
} else {
pick = draw(u); // p == q to the last bit: a rejection had probability 0 - never in practice
}
}
out[t] = pick;
}
}
}
} // namespace
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
const SamplerParams& p, int* out, void* stream) {
if (n_tokens <= 0 || n_vocab <= 0) return;
if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) {
std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n",
p.penalty_last_n, (const void*) history, history_len);
std::exit(1);
}
const unsigned shmem = (history != nullptr && history_len > 0 && p.penalty_last_n > 0)
? (unsigned) ((n_vocab + 31) / 32) * sizeof(unsigned) // the penalty bitmap
: 0;
if (p.greedy || p.temperature <= 0.0f) {
// One block per token, 1,024 threads over the vocabulary. See `sampler_greedy_kernel`.
const int gthreads = 1024;
sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out);
} else {
// The same block-per-token shape: the selection's k argmax rounds reduce inside the block. See
// `sampler_kernel`'s header for what the old one-thread-per-token launch cost.
sampler_kernel<0><<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, n_tokens, history, history_len, p, out, nullptr, nullptr);
}
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "sample_tokens launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
namespace {
void spec_check(const char* who, int n_tokens, int n_vocab, const SamplerParams& p) {
if (p.greedy || p.temperature <= 0.0f || p.penalty_last_n > 0 || n_vocab <= 0) {
std::fprintf(stderr, "%s: a sampled request without penalties only (greedy %d, temperature %g, penalty_last_n "
"%d, n_vocab %d)\n", who, (int) p.greedy, p.temperature, p.penalty_last_n, n_vocab);
std::exit(1);
}
(void) n_tokens;
}
void spec_launched(const char* who, void* stream) {
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "%s launch: %s\n", who, cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
} // namespace
void sample_draft(const float* logits, int n_tokens, int n_vocab, const SamplerParams& p, SpecList* q, int* out,
void* stream) {
if (n_tokens <= 0) return;
spec_check("sample_draft", n_tokens, n_vocab, p);
sampler_kernel<1><<<(unsigned) n_tokens, 1024, 0, (cudaStream_t) stream>>>(logits, n_vocab, n_tokens, nullptr, 0,
p, out, q, nullptr);
spec_launched("sample_draft", stream);
}
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) {
if (n_tokens <= 0) return;
spec_check("sample_verify", n_tokens, n_vocab, p);
sampler_kernel<2><<<(unsigned) n_tokens, 1024, 0, (cudaStream_t) stream>>>(logits, n_vocab, n_tokens, nullptr, 0,
p, out, const_cast<SpecList*>(q), draft);
spec_launched("sample_verify", stream);
}
} // namespace strata::dsv41k
+18
View File
@@ -32,6 +32,7 @@
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
// STRATA_AVXVNNI (CMake: the compiler has the AVX-VNNI intrinsics): GCC and Clang compile them only inside functions
// with target("avxvnni") - the VNNI copy of iq_avx2_rows.inl.
@@ -534,6 +535,23 @@ void iq256_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void*
iq256_rows_v(iq256_variant(), type, w, row_bytes, n, act, nt, out, r0, r1);
}
bool iq256x_supported(int type) noexcept { return type == 16 || type == 17 || type == 18 || type == 21 || type == 22 || type == 29; }
void iq256x_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
int r0, int r1) {
const int variant = iq256_variant();
const bool g = (variant & kIq256Gather) != 0;
#if STRATA_AVXVNNI
if (variant & kIq256Vnni) {
if (g) vnni::dot_type<true, true>(type, nt, w, row_bytes, n, act, out, r0, r1);
else vnni::dot_type<false, true>(type, nt, w, row_bytes, n, act, out, r0, r1);
return;
}
#endif
if (g) plain::dot_type<true, true>(type, nt, w, row_bytes, n, act, out, r0, r1);
else plain::dot_type<false, true>(type, nt, w, row_bytes, n, act, out, r0, r1);
}
void iq4nl256_down_rows_v(int variant, const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt,
float* const* out, int r0, int r1) {
const block_q8_0* y[8];
+369 -52
View File
@@ -78,7 +78,7 @@ void gu_ggml_one(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const
}
}
template <int TY, int NT> STRATA_ROWS_FN
template <int TY, int NT, bool EX = false> STRATA_ROWS_FN
inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) {
const int pf = prefetch_distance();
__m256 accf[NT];
@@ -86,8 +86,12 @@ inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y,
for (int i = 0; i < nblocks; ++i) {
const uint8_t* blk = row + (size_t) i * Fmt32<TY>::bytes;
rows_ahead(blk, pf);
__m256i acci[NT];
for (int t = 0; t < NT; ++t) acci[t] = _mm256_setzero_si256();
// EX: independent integer accumulators a token (A of them) cut the dependent madd+add chain from eight steps to 8/A -
// few tokens have too little else in flight to hide it (integer sums, the same bits)
constexpr int A = EX ? (NT == 1 ? 4 : NT == 2 ? 2 : 1) : 1;
__m256i acci[NT][A];
for (int t = 0; t < NT; ++t)
for (int a = 0; a < A; ++a) acci[t][a] = _mm256_setzero_si256();
for (int j = 0; j < 4; ++j) {
for (int half = 0; half < 2; ++half) {
__m256i g, sgn, sc;
@@ -96,15 +100,20 @@ inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y,
for (int t = 0; t < NT; ++t) {
const __m256i yv = _mm256_loadu_si256((const __m256i*) (y[t][i].qs + off));
const __m256i ys = _mm256_sign_epi8(yv, sgn);
acci[t] = madd_add(acci[t], _mm256_maddubs_epi16(g, ys), sc);
acci[t][(2 * j + half) % A] = madd_add(acci[t][(2 * j + half) % A], _mm256_maddubs_epi16(g, ys), sc);
}
}
}
const float dx = h2f(u16(blk)) * Fmt32<TY>::K;
for (int t = 0; t < NT; ++t)
accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(acci[t]), accf[t]);
for (int a = 1; a < A; ++a) acci[t][0] = _mm256_add_epi32(acci[t][0], acci[t][a]);
// EX (the DeepSeek CPU lane's rows): ggml's float order, so a token's dot is the same bits as ggml-cpu's whatever
// number of tokens share the pass - block scale f16(d) * y.d, the format's constant K after the sum, ggml's hsum.
// Without EX the order of the main engine's rows (unchanged).
const float dx = EX ? h2f(u16(blk)) : h2f(u16(blk)) * Fmt32<TY>::K;
for (int t = 0; t < NT; ++t)
accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(acci[t][0]), accf[t]);
}
for (int t = 0; t < NT; ++t) res[t] = hsum8(accf[t]);
for (int t = 0; t < NT; ++t) res[t] = EX ? Fmt32<TY>::K * ggml_hsum8(accf[t]) : hsum8(accf[t]);
}
// ---- IQ2_XS (17) with ggml's vectorized sign decode (arch/x86/quants.c, ggml_vec_dot_iq2_xs_q8_K):
@@ -156,8 +165,10 @@ inline void row_dot_iq2xs(const uint8_t* row, int nblocks, const block_q8_K* con
__m128i st = _mm_set1_epi64x((long long) u64(blk + 66));
st = _mm_unpacklo_epi8(_mm_and_si128(st, m4), _mm_and_si128(_mm_srli_epi16(st, 4), m4));
const __m128i scales = _mm_add_epi8(_mm_slli_epi16(st, 1), m1);
__m256i acc[NT][2];
for (int t = 0; t < NT; ++t) acc[t][0] = acc[t][1] = _mm256_setzero_si256();
constexpr int CH = GGML ? 4 : 2; // (EX: four independent integer chains a token)
__m256i acc[NT][CH];
for (int t = 0; t < NT; ++t)
for (int c = 0; c < CH; ++c) acc[t][c] = _mm256_setzero_si256();
for (int jj = 0; jj < 2; ++jj) { // 128 values (16 u16) per step
const __m256i q2 = _mm256_loadu_si256((const __m256i*) (blk + 2 + 32 * jj));
const __m256i p7 = _mm256_srli_epi16(q2, 9); // 7 sign bits per u16, even bytes
@@ -183,7 +194,7 @@ inline void row_dot_iq2xs(const uint8_t* row, int nblocks, const block_q8_K* con
for (int t = 0; t < NT; ++t) {
const __m256i yv = _mm256_loadu_si256((const __m256i*) (y[t][i].qs + off));
const __m256i ys = _mm256_sign_epi8(yv, sgn);
acc[t][h & 1] = madd_add(acc[t][h & 1], _mm256_maddubs_epi16(g, ys), sc);
acc[t][h % CH] = madd_add(acc[t][h % CH], _mm256_maddubs_epi16(g, ys), sc);
}
}
}
@@ -191,98 +202,404 @@ inline void row_dot_iq2xs(const uint8_t* row, int nblocks, const block_q8_K* con
const float d = h2f(u16(blk)) * (GGML ? y[t][i].d : 0.125f);
const float scale = GGML ? d : d * y[t][i].d;
accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(scale),
_mm256_cvtepi32_ps(_mm256_add_epi32(acc[t][0], acc[t][1])), accf[t]);
_mm256_cvtepi32_ps(CH == 4 ? _mm256_add_epi32(_mm256_add_epi32(acc[t][0], acc[t][1]), _mm256_add_epi32(acc[t][2], acc[t][3]))
: _mm256_add_epi32(acc[t][0], acc[t][1])), accf[t]);
}
}
for (int t = 0; t < NT; ++t) res[t] = GGML ? 0.125f * ggml_hsum8(accf[t]) : hsum8(accf[t]);
}
template <int TY, int NT> STRATA_ROWS_FN
inline void row_dot_any(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) {
if constexpr (TY == 17) row_dot_iq2xs<NT>(row, nblocks, y, res);
else row_dot<TY, NT>(row, nblocks, y, res);
// ---- IQ1_M (29): 56-byte blocks (qs[32], qh[16], scales[8] holding the 3-bit sub-scales and, in their top nibbles, the
// block's f16 d), ggml's ggml_vec_dot_iq1_m_q8_K (AVX2): s = hsum(sum d*sumi1) + 0.125 * hsum(sum d*sumi2), sumi1 the
// grid dot, sumi2 the +-1 delta dot. Both are kept lane for lane as ggml has them, so the bits are ggml's.
// - the grid values are -1/0/1 bytes: |g| and g's sign (the two halves of ggml's mul_add_epi8) are taken once per weight chunk;
// - the delta dot needs no weight bytes beyond one sign a group of 8: sign(q8, delta) summed in pairs and times the scale is
// (pair sums of q8) times (+-scale), so the pair sums of every activation chunk are made once per call (iq1m_pre_build) and
// a token's delta dot is one madd per 32 values;
// - the indices' high bits and the delta signs of eight groups come out of one 32-bit load by variable shifts (ggml's
// non-BMI2 path branches on every bit).
// the pair sums maddubs(1, q8) of every 32-value chunk of an activation: 16 int16 a chunk, 8 chunks a block
STRATA_ROWS_FN inline void iq1m_pre_build(const block_q8_K* y, int nblocks, int16_t* p) {
const __m256i one8 = _mm256_set1_epi8(1);
for (int i = 0; i < nblocks; ++i)
for (int c = 0; c < 8; ++c)
_mm256_storeu_si256((__m256i*) (p + ((size_t) i * 8 + c) * 16),
_mm256_maddubs_epi16(one8, _mm256_loadu_si256((const __m256i*) (y[i].qs + 32 * c))));
}
template <int TY, int NT> STRATA_ROWS_FN
template <int NT> STRATA_ROWS_FN
inline void row_dot_iq1m(const uint8_t* row, int nblocks, const block_q8_K* const* y, const int16_t* const* P, float* res) {
const __m256i mask = _mm256_set1_epi16(0x7);
const __m256i mone = _mm256_set1_epi16(1);
const __m256i mtwo8 = _mm256_set1_epi8(2);
const __m256i scales_shift = _mm256_set_epi64x(9, 3, 6, 0);
const __m256i nib_shift = _mm256_setr_epi32(0, 4, 8, 12, 16, 20, 24, 28);
const __m256i m7 = _mm256_set1_epi32(7), m8 = _mm256_set1_epi32(8);
const int pf = prefetch_distance();
__m256 acc1[NT], acc2[NT];
for (int t = 0; t < NT; ++t) acc1[t] = acc2[t] = _mm256_setzero_ps();
for (int i = 0; i < nblocks; ++i) {
const uint8_t* blk = row + (size_t) i * 56;
rows_ahead(blk, pf);
const uint8_t* qs = blk;
const uint8_t* qh = blk + 32;
const uint8_t* scb = blk + 48;
const uint16_t sc0 = u16(scb), sc1 = u16(scb + 2), sc2 = u16(scb + 4), sc3 = u16(scb + 6);
const uint16_t d16 = (uint16_t) ((sc0 >> 12) | ((sc1 >> 8) & 0x00f0) | ((sc2 >> 4) & 0x0f00) | (sc3 & 0xf000));
__m256i scales = _mm256_set1_epi64x((long long) u64(scb));
scales = _mm256_srlv_epi64(scales, scales_shift);
scales = _mm256_add_epi16(_mm256_slli_epi16(_mm256_and_si256(scales, mask), 1), mone);
__m256i sidx1 = _mm256_set1_epi16(0x0100);
__m256i sidx2 = _mm256_add_epi8(sidx1, _mm256_set1_epi8(8));
// the block's four 64-value steps decoded once into a small stack frame, then each token runs over them with two
// accumulators in registers (NT tokens' worth of accumulators and decode together do not fit 16 registers)
struct Dec { __m256i a1, g1, a2, g2, sa, sb, ssa, ssb; };
Dec dec[4];
for (int it = 0; it < 4; ++it) {
const __m256i v8 = _mm256_srlv_epi32(_mm256_set1_epi32((int) u32(qh + 4 * it)), nib_shift); // group k's qh nibble
const __m256i idx = _mm256_or_si256(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) (qs + 8 * it))),
_mm256_slli_epi32(_mm256_and_si256(v8, m7), 8));
alignas(32) int32_t ix[8];
_mm256_store_si256((__m256i*) ix, idx);
const __m256i g1 = _mm256_set_epi64x((long long) iq1s_grid[ix[3]], (long long) iq1s_grid[ix[2]],
(long long) iq1s_grid[ix[1]], (long long) iq1s_grid[ix[0]]);
const __m256i g2 = _mm256_set_epi64x((long long) iq1s_grid[ix[7]], (long long) iq1s_grid[ix[6]],
(long long) iq1s_grid[ix[5]], (long long) iq1s_grid[ix[4]]);
const __m256i neg = _mm256_cmpeq_epi32(_mm256_and_si256(v8, m8), m8); // delta -1: all ones a group
const __m256i n1 = _mm256_cvtepi32_epi64(_mm256_castsi256_si128(neg)); // 4 int16 lanes a group of 8 values
const __m256i n2 = _mm256_cvtepi32_epi64(_mm256_extracti128_si256(neg, 1));
const __m256i sc_a = _mm256_shuffle_epi8(scales, sidx1);
const __m256i sc_b = _mm256_shuffle_epi8(scales, sidx2);
dec[it] = Dec{_mm256_sign_epi8(g1, g1), g1, _mm256_sign_epi8(g2, g2), g2, sc_a, sc_b,
_mm256_sign_epi16(sc_a, _mm256_or_si256(n1, mone)), _mm256_sign_epi16(sc_b, _mm256_or_si256(n2, mone))};
sidx1 = _mm256_add_epi8(sidx1, mtwo8);
sidx2 = _mm256_add_epi8(sidx2, mtwo8);
}
const float dx = h2f(d16);
for (int t = 0; t < NT; ++t) {
__m256i s1 = _mm256_setzero_si256(), s2 = _mm256_setzero_si256();
for (int it = 0; it < 4; ++it) {
const Dec& dc = dec[it];
const __m256i q8a = _mm256_loadu_si256((const __m256i*) (y[t][i].qs + 64 * it));
const __m256i q8b = _mm256_loadu_si256((const __m256i*) (y[t][i].qs + 64 * it + 32));
const __m256i dot1 = _mm256_maddubs_epi16(dc.a1, _mm256_sign_epi8(q8a, dc.g1));
const __m256i dot2 = _mm256_maddubs_epi16(dc.a2, _mm256_sign_epi8(q8b, dc.g2));
s1 = _mm256_add_epi32(s1, _mm256_add_epi32(_mm256_madd_epi16(dot1, dc.sa), _mm256_madd_epi16(dot2, dc.sb)));
const int16_t* pp = P[t] + ((size_t) i * 8 + 2 * it) * 16;
s2 = _mm256_add_epi32(s2, _mm256_add_epi32(_mm256_madd_epi16(_mm256_loadu_si256((const __m256i*) pp), dc.ssa),
_mm256_madd_epi16(_mm256_loadu_si256((const __m256i*) (pp + 16)), dc.ssb)));
}
const __m256 d = _mm256_set1_ps(y[t][i].d * dx);
acc1[t] = _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(s1), acc1[t]);
acc2[t] = _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(s2), acc2[t]);
}
}
for (int t = 0; t < NT; ++t) res[t] = ggml_hsum8(acc1[t]) + 0.125f * ggml_hsum8(acc2[t]);
}
template <int TY, int NT, bool EX = false> STRATA_ROWS_FN
inline void row_dot_any(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res,
const int16_t* const* aux = nullptr) {
if constexpr (TY == 29) row_dot_iq1m<NT>(row, nblocks, y, aux, res);
else if constexpr (TY == 17) row_dot_iq2xs<NT, EX>(row, nblocks, y, res);
else row_dot<TY, NT, EX>(row, nblocks, y, res);
}
template <int TY, int NT, bool EX> STRATA_ROWS_FN
void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, float* const* ff,
int r0, int r1) {
const block_q8_K* y[NT];
for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
const int nb = n / QK_K;
const int16_t* aux[NT] = {};
if constexpr (TY == 29) { // (IQ1_M's activation pair sums, once for the rows of this call)
static thread_local std::vector<int16_t> pre;
pre.resize((size_t) NT * nb * 128);
for (int t = 0; t < NT; ++t) {
iq1m_pre_build(y[t], nb, pre.data() + (size_t) t * nb * 128);
aux[t] = pre.data() + (size_t) t * nb * 128;
}
}
float g[NT], u[NT];
for (int r = r0; r < r1; ++r) {
row_dot_any<TY, NT>(blob + (size_t) r * gu_row, nb, y, g);
row_dot_any<TY, NT>(blob + up_off + (size_t) r * gu_row, nb, y, u);
row_dot_any<TY, NT, EX>(blob + (size_t) r * gu_row, nb, y, g, aux);
row_dot_any<TY, NT, EX>(blob + up_off + (size_t) r * gu_row, nb, y, u, aux);
for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t];
}
}
template <int TY, int NT> STRATA_ROWS_FN
template <int TY, int NT, bool EX> STRATA_ROWS_FN
void dot_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) {
const block_q8_K* y[NT];
for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
const int nb = n / QK_K;
const int16_t* aux[NT] = {};
if constexpr (TY == 29) { // (IQ1_M's activation pair sums, once for the rows of this call)
static thread_local std::vector<int16_t> pre;
pre.resize((size_t) NT * nb * 128);
for (int t = 0; t < NT; ++t) {
iq1m_pre_build(y[t], nb, pre.data() + (size_t) t * nb * 128);
aux[t] = pre.data() + (size_t) t * nb * 128;
}
}
float res[NT];
for (int r = r0; r < r1; ++r) {
row_dot_any<TY, NT>(w + (size_t) r * row_bytes, n / QK_K, y, res);
row_dot_any<TY, NT, EX>(w + (size_t) r * row_bytes, nb, y, res, aux);
for (int t = 0; t < NT; ++t) out[t][r] = res[t];
}
}
template <int TY> STRATA_ROWS_FN
void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
float* const* ff, int r0, int r1) {
switch (nt) {
case 1: gu_rows<TY, 1>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 2: gu_rows<TY, 2>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 3: gu_rows<TY, 3>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 4: gu_rows<TY, 4>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 5: gu_rows<TY, 5>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 6: gu_rows<TY, 6>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 7: gu_rows<TY, 7>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
default: gu_rows<TY, 8>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
}
// ---- many tokens an expert (the prompt: a chunk's tokens routed to one expert), EX rows only.
// The weights of a 256-value block are decoded once into signed int8 (the grid magnitude times the sign) and every token of the
// call applies them. The activations come as u8 (q8 + 128, made once per call for all the rows): maddubs(act_u8, w_s8) needs no
// per-token sign, and sum(w * q) = sum(w * (q + 128)) - 128 * sum(w) with the second sum made once per weight block (corr), so the
// integer sums are exactly ggml's, lane for lane (no int16 overflow: |w| <= 62 for these grids, 255 * 62 * 2 < 32767).
// A token costs, per 32 values, one maddubs, one madd and one add (the single-token form has a sign on top).
constexpr int kWideTokens = 64;
STRATA_ROWS_FN inline void wide_prep(const block_q8_K* y, int nb, uint8_t* u) {
const __m256i flip = _mm256_set1_epi8((char) 0x80);
for (int i = 0; i < nb; ++i)
for (int c = 0; c < 8; ++c)
_mm256_storeu_si256((__m256i*) (u + (size_t) i * 256 + 32 * c),
_mm256_xor_si256(_mm256_loadu_si256((const __m256i*) (y[i].qs + 32 * c)), flip));
}
template <int TY> STRATA_ROWS_FN
void dot_rows_wide(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int T, float* const* out, int r0, int r1) {
// tokens in tiles of kTile and rows in groups of kRows: a tile's activation slice of one block (kTile * 256 B) and the group's
// accumulators (kRows * kTile * 32 B) stay in L1 while the group's rows go past, the tile's whole activation in L2
#ifndef STRATA_WIDE_TILE
#define STRATA_WIDE_TILE 16
#endif
#ifndef STRATA_WIDE_ROWS
#define STRATA_WIDE_ROWS 8
#endif
constexpr int kTile = STRATA_WIDE_TILE, kRows = STRATA_WIDE_ROWS;
const int nb = n / QK_K;
static thread_local std::vector<uint8_t> ubuf;
static thread_local std::vector<float> accb;
ubuf.resize((size_t) (T < kTile ? T : kTile) * n);
accb.resize((size_t) kRows * kTile * 8);
const __m256i one8 = _mm256_set1_epi8(1);
const int pf = prefetch_distance();
for (int t0 = 0; t0 < T; t0 += kTile) {
const int tt = T - t0 < kTile ? T - t0 : kTile;
const block_q8_K* y[kTile];
for (int t = 0; t < tt; ++t) {
y[t] = (const block_q8_K*) act[t0 + t];
wide_prep(y[t], nb, ubuf.data() + (size_t) t * n);
}
for (int rg = r0; rg < r1; rg += kRows) {
const int rr = r1 - rg < kRows ? r1 - rg : kRows;
for (int k = 0; k < rr * tt; ++k) _mm256_storeu_ps(&accb[(size_t) k * 8], _mm256_setzero_ps());
for (int i = 0; i < nb; ++i) {
for (int q = 0; q < rr; ++q) {
const uint8_t* blk = w + (size_t) (rg + q) * row_bytes + (size_t) i * Fmt32<TY>::bytes;
rows_ahead(blk, pf);
__m256i w8[8], sc[8];
__m256i corr = _mm256_setzero_si256();
for (int j = 0; j < 4; ++j)
for (int half = 0; half < 2; ++half) {
__m256i g, sgn, s;
Fmt32<TY>::decode(blk, j, half, g, sgn, s);
const int k = 2 * j + half;
w8[k] = _mm256_sign_epi8(g, sgn);
sc[k] = s;
corr = madd_add(corr, _mm256_maddubs_epi16(one8, w8[k]), s);
}
const __m256i corr128 = _mm256_slli_epi32(corr, 7);
const float dx = h2f(u16(blk));
float* accq = &accb[(size_t) q * tt * 8];
for (int t = 0; t < tt; ++t) {
const uint8_t* u = ubuf.data() + (size_t) t * n + (size_t) i * 256;
__m256i a0 = _mm256_setzero_si256(), a1 = _mm256_setzero_si256();
for (int k = 0; k < 8; k += 2) {
a0 = madd_add(a0, _mm256_maddubs_epi16(_mm256_loadu_si256((const __m256i*) (u + 32 * k)), w8[k]), sc[k]);
a1 = madd_add(a1, _mm256_maddubs_epi16(_mm256_loadu_si256((const __m256i*) (u + 32 * k + 32)), w8[k + 1]), sc[k + 1]);
}
const __m256i s = _mm256_sub_epi32(_mm256_add_epi32(a0, a1), corr128);
float* ap = accq + (size_t) t * 8;
_mm256_storeu_ps(ap, _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(s), _mm256_loadu_ps(ap)));
}
}
}
for (int q = 0; q < rr; ++q)
for (int t = 0; t < tt; ++t)
out[t0 + t][rg + q] = Fmt32<TY>::K * ggml_hsum8(_mm256_loadu_ps(&accb[((size_t) q * tt + t) * 8]));
}
}
}
// IQ1_M the same way: its grid bytes are already signed (-1, 0, 1), and the delta dot keeps the pair sums of the activation
// (maddubs(1, q8), made once per tile). Two float accumulators a (row, token), ggml's sum d*sumi1 and sum d*sumi2.
STRATA_ROWS_FN
void dot_rows_wide_iq1m(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int T, float* const* out, int r0, int r1) {
constexpr int kTile = STRATA_WIDE_TILE, kRows = STRATA_WIDE_ROWS;
const int nb = n / QK_K;
static thread_local std::vector<uint8_t> ubuf;
static thread_local std::vector<int16_t> pbuf;
static thread_local std::vector<float> accb;
ubuf.resize((size_t) (T < kTile ? T : kTile) * n);
pbuf.resize((size_t) (T < kTile ? T : kTile) * n);
accb.resize((size_t) kRows * kTile * 16);
const __m256i one8 = _mm256_set1_epi8(1);
const __m256i mask = _mm256_set1_epi16(0x7);
const __m256i mone = _mm256_set1_epi16(1);
const __m256i mtwo8 = _mm256_set1_epi8(2);
const __m256i scales_shift = _mm256_set_epi64x(9, 3, 6, 0);
const __m256i nib_shift = _mm256_setr_epi32(0, 4, 8, 12, 16, 20, 24, 28);
const __m256i m7 = _mm256_set1_epi32(7), m8 = _mm256_set1_epi32(8);
const int pf = prefetch_distance();
for (int t0 = 0; t0 < T; t0 += kTile) {
const int tt = T - t0 < kTile ? T - t0 : kTile;
const block_q8_K* y[kTile];
for (int t = 0; t < tt; ++t) {
y[t] = (const block_q8_K*) act[t0 + t];
wide_prep(y[t], nb, ubuf.data() + (size_t) t * n);
iq1m_pre_build(y[t], nb, pbuf.data() + (size_t) t * n);
}
for (int rg = r0; rg < r1; rg += kRows) {
const int rr = r1 - rg < kRows ? r1 - rg : kRows;
for (int k = 0; k < rr * tt * 2; ++k) _mm256_storeu_ps(&accb[(size_t) k * 8], _mm256_setzero_ps());
for (int i = 0; i < nb; ++i) {
for (int q = 0; q < rr; ++q) {
const uint8_t* blk = w + (size_t) (rg + q) * row_bytes + (size_t) i * 56;
rows_ahead(blk, pf);
const uint8_t* qs = blk;
const uint8_t* qh = blk + 32;
const uint8_t* scb = blk + 48;
const uint16_t sc0 = u16(scb), sc1 = u16(scb + 2), sc2 = u16(scb + 4), sc3 = u16(scb + 6);
const uint16_t d16 = (uint16_t) ((sc0 >> 12) | ((sc1 >> 8) & 0x00f0) | ((sc2 >> 4) & 0x0f00) | (sc3 & 0xf000));
__m256i scales = _mm256_set1_epi64x((long long) u64(scb));
scales = _mm256_srlv_epi64(scales, scales_shift);
scales = _mm256_add_epi16(_mm256_slli_epi16(_mm256_and_si256(scales, mask), 1), mone);
__m256i sidx1 = _mm256_set1_epi16(0x0100);
__m256i sidx2 = _mm256_add_epi8(sidx1, _mm256_set1_epi8(8));
__m256i g1[4], g2[4], sa[4], sb[4], ssa[4], ssb[4];
__m256i corr = _mm256_setzero_si256();
for (int it = 0; it < 4; ++it) {
const __m256i v8 = _mm256_srlv_epi32(_mm256_set1_epi32((int) u32(qh + 4 * it)), nib_shift);
const __m256i idx = _mm256_or_si256(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) (qs + 8 * it))),
_mm256_slli_epi32(_mm256_and_si256(v8, m7), 8));
alignas(32) int32_t ix[8];
_mm256_store_si256((__m256i*) ix, idx);
g1[it] = _mm256_set_epi64x((long long) iq1s_grid[ix[3]], (long long) iq1s_grid[ix[2]],
(long long) iq1s_grid[ix[1]], (long long) iq1s_grid[ix[0]]);
g2[it] = _mm256_set_epi64x((long long) iq1s_grid[ix[7]], (long long) iq1s_grid[ix[6]],
(long long) iq1s_grid[ix[5]], (long long) iq1s_grid[ix[4]]);
const __m256i neg = _mm256_cmpeq_epi32(_mm256_and_si256(v8, m8), m8);
const __m256i n1 = _mm256_cvtepi32_epi64(_mm256_castsi256_si128(neg));
const __m256i n2 = _mm256_cvtepi32_epi64(_mm256_extracti128_si256(neg, 1));
sa[it] = _mm256_shuffle_epi8(scales, sidx1);
sb[it] = _mm256_shuffle_epi8(scales, sidx2);
ssa[it] = _mm256_sign_epi16(sa[it], _mm256_or_si256(n1, mone));
ssb[it] = _mm256_sign_epi16(sb[it], _mm256_or_si256(n2, mone));
sidx1 = _mm256_add_epi8(sidx1, mtwo8);
sidx2 = _mm256_add_epi8(sidx2, mtwo8);
corr = madd_add(madd_add(corr, _mm256_maddubs_epi16(one8, g1[it]), sa[it]), _mm256_maddubs_epi16(one8, g2[it]), sb[it]);
}
const __m256i corr128 = _mm256_slli_epi32(corr, 7);
const float dx = h2f(d16);
float* accq = &accb[(size_t) q * tt * 16];
for (int t = 0; t < tt; ++t) {
const uint8_t* u = ubuf.data() + (size_t) t * n + (size_t) i * 256;
const int16_t* pp = pbuf.data() + (size_t) t * n + (size_t) i * 128;
__m256i a0 = _mm256_setzero_si256(), a1 = _mm256_setzero_si256();
__m256i b0 = _mm256_setzero_si256(), b1 = _mm256_setzero_si256();
for (int it = 0; it < 4; ++it) {
a0 = madd_add(a0, _mm256_maddubs_epi16(_mm256_loadu_si256((const __m256i*) (u + 64 * it)), g1[it]), sa[it]);
a1 = madd_add(a1, _mm256_maddubs_epi16(_mm256_loadu_si256((const __m256i*) (u + 64 * it + 32)), g2[it]), sb[it]);
b0 = madd_add(b0, _mm256_loadu_si256((const __m256i*) (pp + 32 * it)), ssa[it]);
b1 = madd_add(b1, _mm256_loadu_si256((const __m256i*) (pp + 32 * it + 16)), ssb[it]);
}
const __m256i s1 = _mm256_sub_epi32(_mm256_add_epi32(a0, a1), corr128);
const __m256i s2 = _mm256_add_epi32(b0, b1);
const __m256 d = _mm256_set1_ps(y[t][i].d * dx);
float* ap = accq + (size_t) t * 16;
_mm256_storeu_ps(ap, _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(s1), _mm256_loadu_ps(ap)));
_mm256_storeu_ps(ap + 8, _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(s2), _mm256_loadu_ps(ap + 8)));
}
}
}
for (int q = 0; q < rr; ++q)
for (int t = 0; t < tt; ++t) {
const float* ap = &accb[((size_t) q * tt + t) * 16];
out[t0 + t][rg + q] = ggml_hsum8(_mm256_loadu_ps(ap)) + 0.125f * ggml_hsum8(_mm256_loadu_ps(ap + 8));
}
}
}
}
template <int TY, bool EX> STRATA_ROWS_FN
void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
float* const* ff, int r0, int r1) {
switch (nt) {
case 1: gu_rows<TY, 1, EX>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 2: gu_rows<TY, 2, EX>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 3: gu_rows<TY, 3, EX>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 4: gu_rows<TY, 4, EX>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 5: gu_rows<TY, 5, EX>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 6: gu_rows<TY, 6, EX>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 7: gu_rows<TY, 7, EX>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
default: gu_rows<TY, 8, EX>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
}
}
template <int TY, bool EX> STRATA_ROWS_FN
void dot_rows_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0,
int r1) {
if constexpr (EX) {
if (nt >= 7) { // (a prompt chunk's tokens: one decode of a block for all of them)
if constexpr (TY == 29) dot_rows_wide_iq1m(w, row_bytes, n, act, nt, out, r0, r1);
else dot_rows_wide<TY>(w, row_bytes, n, act, nt, out, r0, r1);
return;
}
}
switch (nt) {
case 1: dot_rows<TY, 1>(w, row_bytes, n, act, out, r0, r1); break;
case 2: dot_rows<TY, 2>(w, row_bytes, n, act, out, r0, r1); break;
case 3: dot_rows<TY, 3>(w, row_bytes, n, act, out, r0, r1); break;
case 4: dot_rows<TY, 4>(w, row_bytes, n, act, out, r0, r1); break;
case 1: dot_rows<TY, 1, EX>(w, row_bytes, n, act, out, r0, r1); break;
case 2: dot_rows<TY, 2, EX>(w, row_bytes, n, act, out, r0, r1); break;
case 3: dot_rows<TY, 3, EX>(w, row_bytes, n, act, out, r0, r1); break;
case 4: dot_rows<TY, 4, EX>(w, row_bytes, n, act, out, r0, r1); break;
case 5: if constexpr (EX) { dot_rows<TY, 5, EX>(w, row_bytes, n, act, out, r0, r1); break; } // (the DeepSeek lane's verify
[[fallthrough]]; // rounds: one decode of 5 or 6)
case 6: if constexpr (EX) { dot_rows<TY, 6, EX>(w, row_bytes, n, act, out, r0, r1); break; }
[[fallthrough]];
default: for (int t0 = 0; t0 < nt; t0 += 4) {
const int k = nt - t0 < 4 ? nt - t0 : 4;
dot_rows_nt<TY>(k, w, row_bytes, n, act + t0, out + t0, r0, r1);
dot_rows_nt<TY, EX>(k, w, row_bytes, n, act + t0, out + t0, r0, r1);
}
}
}
// The decode of each format for a variant: the gathered one (kIq256Gather) for IQ3_XXS, IQ3_S and IQ2_S.
template <bool G> STRATA_ROWS_FN
template <bool G, bool EX = false> STRATA_ROWS_FN
void gu_type(int type, int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
float* const* ff, int r0, int r1) {
switch (type) {
case 16: gu_rows_nt<16>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 17: gu_rows_nt<17>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 18: gu_rows_nt<G ? 118 : 18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 21: gu_rows_nt<G ? 121 : 21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 22: gu_rows_nt<G ? 122 : 22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 23: gu_rows_nt<23>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 16: gu_rows_nt<16, EX>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 17: gu_rows_nt<17, EX>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 18: gu_rows_nt<G ? 118 : 18, EX>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 21: gu_rows_nt<G ? 121 : 21, EX>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 22: gu_rows_nt<G ? 122 : 22, EX>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 23: gu_rows_nt<23, EX>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
case 29: gu_rows_nt<29, EX>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
default: break;
}
}
template <bool G> STRATA_ROWS_FN
template <bool G, bool EX = false> STRATA_ROWS_FN
void dot_type(int type, int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out,
int r0, int r1) {
switch (type) {
case 16: dot_rows_nt<16>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 17: dot_rows_nt<17>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 18: dot_rows_nt<G ? 118 : 18>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 21: dot_rows_nt<G ? 121 : 21>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 22: dot_rows_nt<G ? 122 : 22>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 23: dot_rows_nt<23>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 16: dot_rows_nt<16, EX>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 17: dot_rows_nt<17, EX>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 18: dot_rows_nt<G ? 118 : 18, EX>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 21: dot_rows_nt<G ? 121 : 21, EX>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 22: dot_rows_nt<G ? 122 : 22, EX>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 23: dot_rows_nt<23, EX>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 29: dot_rows_nt<29, EX>(nt, w, row_bytes, n, act, out, r0, r1); break;
default: break;
}
}
+329
View File
@@ -15,10 +15,16 @@
#include "ggml-common.h"
#include <immintrin.h>
#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <cpuid.h>
#endif
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
namespace strata::kernels::cpu {
namespace {
@@ -240,6 +246,297 @@ void dot_rows_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void*
}
}
// The sign masks of IQ2_XXS / IQ2_XS / IQ3_XXS come from a 7-bit index whose 8th bit is the parity of the other seven (ksigns_iq2xs[i] =
// i | parity(i) << 7). The table needs a load and a few shifts and ors a group of eight values; popcount does it for all eight groups
// of 64 values in one vector: measured on Zen 5, one-token IQ2_XXS rows 33 -> 45-50 GB/s (16 threads, DRAM-sized), cache-resident 16.8 -> 13.4 ns a block.
// (AVX512_VPOPCNTDQ + VL: Zen 4, Zen 5, Ice Lake and later; iq512x_supported() asks for it.)
inline __mmask64 sign_mask_from_idx(__m256i si) {
const __m256i par = _mm256_slli_epi32(_mm256_and_si256(_mm256_popcnt_epi32(si), _mm256_set1_epi32(1)), 7);
return _cvtu64_mask64((uint64_t) _mm_cvtsi128_si64(_mm256_cvtepi32_epi8(_mm256_or_si256(si, par))));
}
inline __m256i sign_idx_xxs(uint32_t lo4, uint32_t hi4) { // four 7-bit fields of each of two words -> eight dwords
const __m256i w = _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_set1_epi32((int) lo4)), _mm_set1_epi32((int) hi4), 1);
return _mm256_and_si256(_mm256_srlv_epi32(w, _mm256_setr_epi32(0, 7, 14, 21, 0, 7, 14, 21)), _mm256_set1_epi32(127));
}
template <int TY> struct FmtX : Fmt<TY> {};
template <> struct FmtX<16> : Fmt<16> {
static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
const uint8_t* q = b + 2 + 16 * j;
const uint32_t a0 = u32(q), a1 = u32(q + 4), b0 = u32(q + 8), b1 = u32(q + 12);
g = _mm512_set_epi64((long long) iq2xxs_grid[b0 >> 24], (long long) iq2xxs_grid[(b0 >> 16) & 255],
(long long) iq2xxs_grid[(b0 >> 8) & 255], (long long) iq2xxs_grid[b0 & 255],
(long long) iq2xxs_grid[a0 >> 24], (long long) iq2xxs_grid[(a0 >> 16) & 255],
(long long) iq2xxs_grid[(a0 >> 8) & 255], (long long) iq2xxs_grid[a0 & 255]);
m = sign_mask_from_idx(sign_idx_xxs(a1, b1));
const int sa = 2 * (int) (a1 >> 28) + 1, sb = 2 * (int) (b1 >> 28) + 1;
sc = scales4(sa, sa, sb, sb);
}
};
template <> struct FmtX<17> : Fmt<17> {
static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
const uint8_t* q = b + 2 + 16 * j;
uint16_t v[8];
std::memcpy(v, q, 16);
g = _mm512_set_epi64((long long) iq2xs_grid[v[7] & 511], (long long) iq2xs_grid[v[6] & 511],
(long long) iq2xs_grid[v[5] & 511], (long long) iq2xs_grid[v[4] & 511],
(long long) iq2xs_grid[v[3] & 511], (long long) iq2xs_grid[v[2] & 511],
(long long) iq2xs_grid[v[1] & 511], (long long) iq2xs_grid[v[0] & 511]);
m = sign_mask_from_idx(_mm256_srli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) q)), 9));
const uint8_t s0 = b[66 + 2 * j], s1 = b[66 + 2 * j + 1];
sc = scales4(2 * (s0 & 15) + 1, 2 * (s0 >> 4) + 1, 2 * (s1 & 15) + 1, 2 * (s1 >> 4) + 1);
}
};
template <> struct FmtX<18> : Fmt<18> {
static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
const uint8_t* q = b + 2 + 16 * j;
g = _mm512_set_epi32((int) iq3xxs_grid[q[15]], (int) iq3xxs_grid[q[14]], (int) iq3xxs_grid[q[13]], (int) iq3xxs_grid[q[12]],
(int) iq3xxs_grid[q[11]], (int) iq3xxs_grid[q[10]], (int) iq3xxs_grid[q[9]], (int) iq3xxs_grid[q[8]],
(int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]],
(int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]);
const uint32_t a = u32(b + 2 + 64 + 8 * j), c = u32(b + 2 + 64 + 8 * j + 4);
m = sign_mask_from_idx(sign_idx_xxs(a, c));
const int sa = 2 * (int) (a >> 28) + 1, sb = 2 * (int) (c >> 28) + 1;
sc = scales4(sa, sa, sb, sb);
}
};
// ---- the DeepSeek CPU lane's exact rows (iq512x_rows): the same 64-value decode, but summed as ggml's AVX2 dots sum, so a
// token's row is ggml-cpu's vec_dot bit for bit at any number of tokens: the integer sums of a block fold to ggml's eight lanes
// (low half = the even 32-value chunk, high half = the odd one), the block scale is f16(d) * y.d, eight float lanes accumulate
// across blocks, and K * ggml's hsum comes last. vpdpwssd is the madd and the add in one.
inline __m256i fold256(__m512i a) { return _mm256_add_epi32(_mm512_castsi512_si256(a), _mm512_extracti64x4_epi64(a, 1)); }
inline float hsum8_ggml(__m256 x) {
__m128 s = _mm_add_ps(_mm256_extractf128_ps(x, 1), _mm256_castps256_ps128(x));
s = _mm_add_ps(s, _mm_movehl_ps(s, s));
s = _mm_add_ss(s, _mm_movehdup_ps(s));
return _mm_cvtss_f32(s);
}
template <int TY, int NT>
inline void row_dot_x(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) {
__m256 accf[NT];
for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps();
const __m512i zero = _mm512_setzero_si512();
for (int i = 0; i < nblocks; ++i) {
const uint8_t* blk = row + (size_t) i * FmtX<TY>::bytes;
if (prefetch_ahead > 0) {
const uint8_t* ahead = blk + (size_t) prefetch_ahead;
_mm_prefetch((const char*) ahead, _MM_HINT_T0);
_mm_prefetch((const char*) ahead + 64, _MM_HINT_T0);
}
__m512i acci[NT];
for (int t = 0; t < NT; ++t) acci[t] = _mm512_setzero_si512();
for (int j = 0; j < 4; ++j) {
__m512i g, sc;
__mmask64 m;
FmtX<TY>::decode(blk, j, g, m, sc);
for (int t = 0; t < NT; ++t) {
const __m512i yv = _mm512_loadu_si512((const void*) (y[t][i].qs + 64 * j));
const __m512i ys = _mm512_mask_sub_epi8(yv, m, zero, yv);
acci[t] = _mm512_dpwssd_epi32(acci[t], _mm512_maddubs_epi16(g, ys), sc);
}
}
const float dx = h2f(u16(blk));
for (int t = 0; t < NT; ++t)
accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(fold256(acci[t])), accf[t]);
}
for (int t = 0; t < NT; ++t) res[t] = FmtX<TY>::K * hsum8_ggml(accf[t]);
}
template <int TY, int NT>
void dot_rows_x(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) {
const block_q8_K* y[NT];
for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
float res[NT];
for (int r = r0; r < r1; ++r) {
row_dot_x<TY, NT>(w + (size_t) r * row_bytes, n / QK_K, y, res);
for (int t = 0; t < NT; ++t) out[t][r] = res[t];
}
}
// many tokens an expert (the prompt): signed int8 weights decoded once per block, activations as u8 (q8 + 128, once a call),
// sum(w * q) = sum(w * (q + 128)) - 128 * sum(w) with the second sum once a weight block; tokens in tiles of 16 and rows in
// groups of 8 so the tile's slice of a block and the group's accumulators stay in L1 (the AVX2 form's layout)
template <int TY>
void dot_rows_wide(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int T, float* const* out, int r0, int r1) {
constexpr int kTile = 16, kRows = 8;
const int nb = n / QK_K;
static thread_local std::vector<uint8_t> ubuf;
static thread_local std::vector<float> accb;
ubuf.resize((size_t) (T < kTile ? T : kTile) * n);
accb.resize((size_t) kRows * kTile * 8);
const __m512i zero = _mm512_setzero_si512(), one8 = _mm512_set1_epi8(1), flip = _mm512_set1_epi8((char) 0x80);
for (int t0 = 0; t0 < T; t0 += kTile) {
const int tt = T - t0 < kTile ? T - t0 : kTile;
const block_q8_K* y[kTile];
for (int t = 0; t < tt; ++t) {
y[t] = (const block_q8_K*) act[t0 + t];
uint8_t* u = ubuf.data() + (size_t) t * n;
for (int i = 0; i < nb; ++i)
for (int j = 0; j < 4; ++j)
_mm512_storeu_si512((void*) (u + (size_t) i * 256 + 64 * j),
_mm512_xor_si512(_mm512_loadu_si512((const void*) (y[t][i].qs + 64 * j)), flip));
}
for (int rg = r0; rg < r1; rg += kRows) {
const int rr = r1 - rg < kRows ? r1 - rg : kRows;
for (int k = 0; k < rr * tt; ++k) _mm256_storeu_ps(&accb[(size_t) k * 8], _mm256_setzero_ps());
for (int i = 0; i < nb; ++i)
for (int q = 0; q < rr; ++q) {
const uint8_t* blk = w + (size_t) (rg + q) * row_bytes + (size_t) i * FmtX<TY>::bytes;
if (prefetch_ahead > 0) {
_mm_prefetch((const char*) blk + prefetch_ahead, _MM_HINT_T0);
_mm_prefetch((const char*) blk + prefetch_ahead + 64, _MM_HINT_T0);
}
__m512i w8[4], sc[4];
__m512i corr = zero;
for (int j = 0; j < 4; ++j) {
__m512i g, s;
__mmask64 m;
FmtX<TY>::decode(blk, j, g, m, s);
w8[j] = _mm512_mask_sub_epi8(g, m, zero, g);
sc[j] = s;
corr = _mm512_dpwssd_epi32(corr, _mm512_maddubs_epi16(one8, w8[j]), s);
}
const __m256i corr128 = _mm256_slli_epi32(fold256(corr), 7);
const float dx = h2f(u16(blk));
float* accq = &accb[(size_t) q * tt * 8];
for (int t = 0; t < tt; ++t) {
const uint8_t* u = ubuf.data() + (size_t) t * n + (size_t) i * 256;
__m512i a = zero;
for (int j = 0; j < 4; ++j)
a = _mm512_dpwssd_epi32(a, _mm512_maddubs_epi16(_mm512_loadu_si512((const void*) (u + 64 * j)), w8[j]), sc[j]);
const __m256i s = _mm256_sub_epi32(fold256(a), corr128);
float* ap = accq + (size_t) t * 8;
_mm256_storeu_ps(ap, _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(s), _mm256_loadu_ps(ap)));
}
}
for (int q = 0; q < rr; ++q)
for (int t = 0; t < tt; ++t)
out[t0 + t][rg + q] = FmtX<TY>::K * hsum8_ggml(_mm256_loadu_ps(&accb[((size_t) q * tt + t) * 8]));
}
}
}
template <int TY>
void dot_rows_x_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) {
switch (nt) {
case 1: dot_rows_x<TY, 1>(w, row_bytes, n, act, out, r0, r1); break;
case 2: dot_rows_x<TY, 2>(w, row_bytes, n, act, out, r0, r1); break;
case 3: dot_rows_x<TY, 3>(w, row_bytes, n, act, out, r0, r1); break;
case 4: dot_rows_x<TY, 4>(w, row_bytes, n, act, out, r0, r1); break;
case 5: dot_rows_x<TY, 5>(w, row_bytes, n, act, out, r0, r1); break;
case 6: dot_rows_x<TY, 6>(w, row_bytes, n, act, out, r0, r1); break;
default: dot_rows_wide<TY>(w, row_bytes, n, act, nt, out, r0, r1); break;
}
}
// ---- IQ1_M (29), AVX-512, 1..6 tokens: ggml's dot lane for lane. The grid indices come out of two pdep (as ggml's BMI2 path), the
// +-1 delta signs out of one pext into an 8-bit mask a 64-value step; the signed grid bytes are split into |g| and a negative mask;
// the delta dot is the pair sums of the activation (made once a call) times +-scale. d is f16 in the top nibbles of the scales.
inline void iq1m_pre(const block_q8_K* y, int nb, int16_t* p) {
const __m256i one8 = _mm256_set1_epi8(1);
for (int i = 0; i < nb; ++i)
for (int c = 0; c < 8; ++c)
_mm256_storeu_si256((__m256i*) (p + ((size_t) i * 8 + c) * 16),
_mm256_maddubs_epi16(one8, _mm256_loadu_si256((const __m256i*) (y[i].qs + 32 * c))));
}
template <int NT>
void rows_m(const uint8_t* w, size_t rb, int n, const block_q8_K* const* y, const int16_t* const* P, float* const* out, int r0, int r1) {
const int nb = n / QK_K;
const __m256i mask = _mm256_set1_epi16(0x7), mone = _mm256_set1_epi16(1), mtwo8 = _mm256_set1_epi8(2);
const __m256i scales_shift = _mm256_set_epi64x(9, 3, 6, 0);
const __m512i zero = _mm512_setzero_si512();
for (int r = r0; r < r1; ++r) {
__m256 a1[NT], a2[NT];
for (int t = 0; t < NT; ++t) a1[t] = a2[t] = _mm256_setzero_ps();
const uint8_t* row = w + (size_t) r * rb;
for (int i = 0; i < nb; ++i) {
const uint8_t* blk = row + (size_t) i * 56;
const uint8_t* qs = blk;
const uint8_t* qh = blk + 32;
const uint8_t* scb = blk + 48;
if (prefetch_ahead > 0) {
_mm_prefetch((const char*) blk + prefetch_ahead, _MM_HINT_T0);
_mm_prefetch((const char*) blk + prefetch_ahead + 64, _MM_HINT_T0);
}
const uint16_t sc0 = u16(scb), sc1 = u16(scb + 2), sc2 = u16(scb + 4), sc3 = u16(scb + 6);
const uint16_t d16 = (uint16_t) ((sc0 >> 12) | ((sc1 >> 8) & 0x00f0) | ((sc2 >> 4) & 0x0f00) | (sc3 & 0xf000));
__m256i scales = _mm256_set1_epi64x((long long) u64(scb));
scales = _mm256_srlv_epi64(scales, scales_shift);
scales = _mm256_add_epi16(_mm256_slli_epi16(_mm256_and_si256(scales, mask), 1), mone);
__m256i sidx1 = _mm256_set1_epi16(0x0100);
__m256i sidx2 = _mm256_add_epi8(sidx1, _mm256_set1_epi8(8));
__m512i s1[NT], s2[NT];
for (int t = 0; t < NT; ++t) s1[t] = s2[t] = zero;
for (int it = 0; it < 4; ++it) {
const uint32_t qh32 = u32(qh + 4 * it);
const uint64_t p1 = _pdep_u64(u32(qs + 8 * it), 0x00ff00ff00ff00ffULL) | _pdep_u64(qh32 & 0x7777, 0x0f000f000f000f00ULL);
const uint64_t p2 = _pdep_u64(u32(qs + 8 * it + 4), 0x00ff00ff00ff00ffULL) | _pdep_u64((qh32 >> 16) & 0x7777, 0x0f000f000f000f00ULL);
uint16_t ix[8];
std::memcpy(ix, &p1, 8);
std::memcpy(ix + 4, &p2, 8);
const __m512i g = _mm512_set_epi64((long long) iq1s_grid[ix[7]], (long long) iq1s_grid[ix[6]], (long long) iq1s_grid[ix[5]],
(long long) iq1s_grid[ix[4]], (long long) iq1s_grid[ix[3]], (long long) iq1s_grid[ix[2]],
(long long) iq1s_grid[ix[1]], (long long) iq1s_grid[ix[0]]);
const __m512i negv = _mm512_maskz_set1_epi64((__mmask8) _pext_u32(qh32, 0x88888888u), -1);
const __m256i sca = _mm256_shuffle_epi8(scales, sidx1);
const __m256i scb2 = _mm256_shuffle_epi8(scales, sidx2);
sidx1 = _mm256_add_epi8(sidx1, mtwo8);
sidx2 = _mm256_add_epi8(sidx2, mtwo8);
const __m512i sc = _mm512_inserti64x4(_mm512_castsi256_si512(sca), scb2, 1);
const __m512i ssc = _mm512_sub_epi16(_mm512_xor_si512(sc, negv), negv);
const __m512i ag = _mm512_abs_epi8(g);
const __mmask64 gneg = _mm512_movepi8_mask(g);
for (int t = 0; t < NT; ++t) {
const __m512i q8 = _mm512_loadu_si512((const void*) (y[t][i].qs + 64 * it));
const __m512i pp = _mm512_loadu_si512((const void*) (P[t] + ((size_t) i * 8 + 2 * it) * 16));
const __m512i ys = _mm512_mask_sub_epi8(q8, gneg, zero, q8);
s1[t] = _mm512_dpwssd_epi32(s1[t], _mm512_maddubs_epi16(ag, ys), sc);
s2[t] = _mm512_dpwssd_epi32(s2[t], pp, ssc);
}
}
const float dx = h2f(d16);
for (int t = 0; t < NT; ++t) {
const __m256 d = _mm256_set1_ps(y[t][i].d * dx);
a1[t] = _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(fold256(s1[t])), a1[t]);
a2[t] = _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(fold256(s2[t])), a2[t]);
}
}
for (int t = 0; t < NT; ++t) out[t][r] = hsum8_ggml(a1[t]) + 0.125f * hsum8_ggml(a2[t]);
}
}
void rows_m_nt(int nt, const uint8_t* w, size_t rb, int n, const void* const* act, float* const* out, int r0, int r1) {
const int nb = n / QK_K;
static thread_local std::vector<int16_t> pre;
for (int t0 = 0; t0 < nt; t0 += 6) {
const int k = nt - t0 < 6 ? nt - t0 : 6;
const block_q8_K* y[6];
const int16_t* P[6];
float* o[6];
pre.resize((size_t) k * n);
for (int t = 0; t < k; ++t) {
y[t] = (const block_q8_K*) act[t0 + t];
iq1m_pre(y[t], nb, pre.data() + (size_t) t * n);
P[t] = pre.data() + (size_t) t * n;
o[t] = out[t0 + t];
}
switch (k) {
case 1: rows_m<1>(w, rb, n, y, P, o, r0, r1); break;
case 2: rows_m<2>(w, rb, n, y, P, o, r0, r1); break;
case 3: rows_m<3>(w, rb, n, y, P, o, r0, r1); break;
case 4: rows_m<4>(w, rb, n, y, P, o, r0, r1); break;
case 5: rows_m<5>(w, rb, n, y, P, o, r0, r1); break;
default: rows_m<6>(w, rb, n, y, P, o, r0, r1); break;
}
}
}
} // namespace
void iq512_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
@@ -266,4 +563,36 @@ void iq512_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void*
}
}
static bool has_vpopcnt() {
static const bool ok = [] {
#if defined(_MSC_VER)
int r[4];
__cpuidex(r, 7, 0);
return ((r[2] >> 14) & 1) != 0; // AVX512_VPOPCNTDQ
#else
unsigned a, b, c, d;
__cpuid_count(7, 0, a, b, c, d);
return ((c >> 14) & 1u) != 0;
#endif
}();
return ok;
}
bool iq512x_supported(int type) noexcept {
return has_vpopcnt() && (type == 16 || type == 17 || type == 18 || type == 21 || type == 22 || type == 29);
}
void iq512x_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
int r0, int r1) {
switch (type) {
case 16: dot_rows_x_nt<16>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 17: dot_rows_x_nt<17>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 18: dot_rows_x_nt<18>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 21: dot_rows_x_nt<21>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 22: dot_rows_x_nt<22>(nt, w, row_bytes, n, act, out, r0, r1); break;
case 29: rows_m_nt(nt, w, row_bytes, n, act, out, r0, r1); break;
default: break;
}
}
} // namespace strata::kernels::cpu
+89
View File
@@ -0,0 +1,89 @@
// src/kernels/cpu/tq_avx2.cpp - the trellis expert rows (TQ2_T / TQK6 / TQK7) on AVX2 + FMA (tq_cpu.hpp).
// Compiled for AVX2 only and reached behind cpu_avx2_ok(), so nothing here can fault on an older CPU.
//
// Per 128-weight block: the 32 states in scalar code (tq_states.hpp: one 32-bit read, a shift and a mask each, used
// as table indices straight away), four 8-byte state-table rows per YMM register as scalar loads, then per token
// VPMADDWD against the unpacked int16 activations and a VPHADDD tree that leaves the four exact sub-block sums
// S[k] in one XMM, so the float part is the scalar kernel's, lane for lane. The weights are decoded once per block
// for all the tokens of the group.
//
// Measured on Zen 5 (cycles per block, one token, AVX2): ~48 with this scheme; computing the states with byte
// shuffles instead (VPSHUFB / VPSRLVD per 8 states) and moving them to GPRs or through memory was slower (60-80),
// and ggml-cpu's AVX2 vec_dot for these types (agentionai llama.cpp, the same state table) takes about 2.3x as long.
#include "strata/kernels/cpu/tq_cpu.hpp"
#include "tq_states.hpp"
#include <immintrin.h>
namespace strata::kernels::cpu::tq_detail {
namespace {
// four state-table rows (8 bytes each) into one YMM: a load and three broadcast loads blended in. Broadcast loads
// and VPBLENDD avoid the shuffle port that VPINSRQ / VINSERTI128 need (the two measure the same on Zen 5).
inline __m256i rows4(const long long* tab, uint32_t s0, uint32_t s1, uint32_t s2, uint32_t s3) {
__m256i v = _mm256_castsi128_si256(_mm_loadl_epi64((const __m128i*) (tab + s0)));
v = _mm256_blend_epi32(v, _mm256_set1_epi64x(tab[s1]), 0x0C);
v = _mm256_blend_epi32(v, _mm256_set1_epi64x(tab[s2]), 0x30);
return _mm256_blend_epi32(v, _mm256_set1_epi64x(tab[s3]), 0xC0);
}
template <int KB>
void rows_t(const int16_t* table, const uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt, float* const* out, int r0,
int r1) {
const int nb = n / 128;
constexpr size_t bsz = 2 + 4 * KB;
const long long* tab = (const long long*) table;
for (int r = r0; r < r1; ++r) {
const uint8_t* x = w + (size_t) r * row_bytes;
__m128 acc[kTqMaxTokens];
for (int t = 0; t < nt; ++t) acc[t] = _mm_setzero_ps();
for (int i = 0; i < nb; ++i) {
const uint8_t* blk = x + (size_t) i * bsz;
const uint8_t* qs = blk + 2;
const uint64_t wr = tq_wrap<KB>(qs);
__m256i wv[8]; // wv[m] = weights 16m .. 16m+15 (states 4m .. 4m+3)
#if defined(__GNUC__)
#pragma GCC unroll 8
#endif
for (int m = 0; m < 8; ++m)
wv[m] = rows4(tab, tq_state<KB>(qs, wr, 4 * m), tq_state<KB>(qs, wr, 4 * m + 1),
tq_state<KB>(qs, wr, 4 * m + 2), tq_state<KB>(qs, wr, 4 * m + 3));
const __m128 dx = _mm_set1_ps(tq_half_to_float(tq_ld16(blk)));
for (int t = 0; t < nt; ++t) {
const __m256i* q = (const __m256i*) (a[t]->q + 128 * i);
const __m256i p0 = _mm256_add_epi32(_mm256_madd_epi16(wv[0], _mm256_load_si256(q + 0)),
_mm256_madd_epi16(wv[1], _mm256_load_si256(q + 1)));
const __m256i p1 = _mm256_add_epi32(_mm256_madd_epi16(wv[2], _mm256_load_si256(q + 2)),
_mm256_madd_epi16(wv[3], _mm256_load_si256(q + 3)));
const __m256i p2 = _mm256_add_epi32(_mm256_madd_epi16(wv[4], _mm256_load_si256(q + 4)),
_mm256_madd_epi16(wv[5], _mm256_load_si256(q + 5)));
const __m256i p3 = _mm256_add_epi32(_mm256_madd_epi16(wv[6], _mm256_load_si256(q + 6)),
_mm256_madd_epi16(wv[7], _mm256_load_si256(q + 7)));
// per 128-bit lane [p0, p1, p2, p3] partial sums, then the two lanes added: S[0..3], exact
const __m256i h = _mm256_hadd_epi32(_mm256_hadd_epi32(p0, p1), _mm256_hadd_epi32(p2, p3));
const __m128i s = _mm_add_epi32(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1));
const __m128 sc = _mm_mul_ps(dx, _mm_loadu_ps(a[t]->d + 4 * i));
acc[t] = _mm_fmadd_ps(_mm_cvtepi32_ps(s), sc, acc[t]);
}
}
for (int t = 0; t < nt; ++t) {
alignas(16) float v[4];
_mm_store_ps(v, acc[t]);
out[t][r] = ((v[0] + v[1]) + (v[2] + v[3])) * (1.0f / 8192.0f);
}
}
}
} // namespace
void tq_rows_avx2(int kb, const int16_t* table, const uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt,
float* const* out, int r0, int r1) {
if (kb == 8) rows_t<8>(table, w, row_bytes, n, a, nt, out, r0, r1);
else if (kb == 6) rows_t<6>(table, w, row_bytes, n, a, nt, out, r0, r1);
else if (kb == 5) rows_t<5>(table, w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK5X
else if (kb == 4) rows_t<4>(table, w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK4X
else rows_t<7>(table, w, row_bytes, n, a, nt, out, r0, r1);
}
} // namespace strata::kernels::cpu::tq_detail
+97
View File
@@ -0,0 +1,97 @@
// src/kernels/cpu/tq_avx512.cpp - the trellis expert rows (TQ2_T / TQK6 / TQK7) on AVX-512 F/BW/VL/VNNI
// (tq_cpu.hpp). Reached behind cpu_avx512_ok() only.
//
// Per 128-weight block: the AVX2 kernel's decode (scalar states, scalar 8-byte state-table loads, one ZMM of 32
// int16 weights per Q8_0 sub-block); per token four VPDPWSSD against the unpacked int16 activations, an unpack/add
// tree to the four exact sub-block sums S[k] in one XMM, and the scalar kernel's float steps lane for lane. The
// weights are decoded once per block for all the tokens of the group.
//
// Measured on Zen 5 (cycles per block): the decode bounds it, so one token is no faster than AVX2 (~48); each extra
// token of a group costs ~10% less than on AVX2. ggml-cpu's AVX-512 decode for these types - all states from two
// VPERMB and the table rows by VPGATHERQQ - was 20-30% slower here: Zen gathers are slow, and so are Intel ones
// under the Gather Data Sampling microcode mitigation.
#include "strata/kernels/cpu/tq_cpu.hpp"
#include "tq_states.hpp"
#include <immintrin.h>
namespace strata::kernels::cpu::tq_detail {
namespace {
// four ZMM of 16 int32 partial sums -> [S0, S1, S2, S3] (exact integer adds)
inline __m128i reduce4(__m512i p0, __m512i p1, __m512i p2, __m512i p3) {
const __m512i a = _mm512_add_epi32(_mm512_unpacklo_epi32(p0, p1), _mm512_unpackhi_epi32(p0, p1));
const __m512i b = _mm512_add_epi32(_mm512_unpacklo_epi32(p2, p3), _mm512_unpackhi_epi32(p2, p3));
const __m512i c = _mm512_add_epi32(_mm512_unpacklo_epi64(a, b), _mm512_unpackhi_epi64(a, b));
// c: per 128-bit lane [p0, p1, p2, p3] partial sums; add the four lanes
const __m256i d = _mm256_add_epi32(_mm512_castsi512_si256(c), _mm512_extracti64x4_epi64(c, 1));
return _mm_add_epi32(_mm256_castsi256_si128(d), _mm256_extracti128_si256(d, 1));
}
// four state-table rows (8 bytes each) into one YMM: scalar loads, broadcast and blended in; two make a ZMM
inline __m256i rows4(const long long* tab, uint32_t s0, uint32_t s1, uint32_t s2, uint32_t s3) {
__m256i v = _mm256_castsi128_si256(_mm_loadl_epi64((const __m128i*) (tab + s0)));
v = _mm256_blend_epi32(v, _mm256_set1_epi64x(tab[s1]), 0x0C);
v = _mm256_blend_epi32(v, _mm256_set1_epi64x(tab[s2]), 0x30);
return _mm256_blend_epi32(v, _mm256_set1_epi64x(tab[s3]), 0xC0);
}
template <int KB>
inline __m512i rows8(const long long* tab, const uint8_t* qs, uint64_t wr, int t0) {
const __m256i lo = rows4(tab, tq_state<KB>(qs, wr, t0), tq_state<KB>(qs, wr, t0 + 1), tq_state<KB>(qs, wr, t0 + 2),
tq_state<KB>(qs, wr, t0 + 3));
const __m256i hi = rows4(tab, tq_state<KB>(qs, wr, t0 + 4), tq_state<KB>(qs, wr, t0 + 5),
tq_state<KB>(qs, wr, t0 + 6), tq_state<KB>(qs, wr, t0 + 7));
return _mm512_inserti64x4(_mm512_castsi256_si512(lo), hi, 1);
}
template <int KB>
void rows_t(const int16_t* table, const uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt, float* const* out, int r0,
int r1) {
const int nb = n / 128;
constexpr size_t bsz = 2 + 4 * KB;
const long long* tab = (const long long*) table;
for (int r = r0; r < r1; ++r) {
const uint8_t* x = w + (size_t) r * row_bytes;
__m128 acc[kTqMaxTokens];
for (int t = 0; t < nt; ++t) acc[t] = _mm_setzero_ps();
for (int i = 0; i < nb; ++i) {
const uint8_t* blk = x + (size_t) i * bsz;
const uint8_t* qs = blk + 2;
const uint64_t wr = tq_wrap<KB>(qs);
// states 8k .. 8k+7 -> weights 32k .. 32k+31 = Q8_0 sub-block k
const __m512i w0 = rows8<KB>(tab, qs, wr, 0), w1 = rows8<KB>(tab, qs, wr, 8);
const __m512i w2 = rows8<KB>(tab, qs, wr, 16), w3 = rows8<KB>(tab, qs, wr, 24);
const __m128 dx = _mm_set1_ps(tq_half_to_float(tq_ld16(blk)));
for (int t = 0; t < nt; ++t) {
const __m512i* q = (const __m512i*) (a[t]->q + 128 * i);
const __m512i z = _mm512_setzero_si512();
const __m128i s = reduce4(_mm512_dpwssd_epi32(z, w0, _mm512_load_si512(q + 0)),
_mm512_dpwssd_epi32(z, w1, _mm512_load_si512(q + 1)),
_mm512_dpwssd_epi32(z, w2, _mm512_load_si512(q + 2)),
_mm512_dpwssd_epi32(z, w3, _mm512_load_si512(q + 3)));
const __m128 sc = _mm_mul_ps(dx, _mm_loadu_ps(a[t]->d + 4 * i));
acc[t] = _mm_fmadd_ps(_mm_cvtepi32_ps(s), sc, acc[t]);
}
}
for (int t = 0; t < nt; ++t) {
alignas(16) float v[4];
_mm_store_ps(v, acc[t]);
out[t][r] = ((v[0] + v[1]) + (v[2] + v[3])) * (1.0f / 8192.0f);
}
}
}
} // namespace
void tq_rows_avx512(int kb, const int16_t* table, const uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt,
float* const* out, int r0, int r1) {
if (kb == 8) rows_t<8>(table, w, row_bytes, n, a, nt, out, r0, r1);
else if (kb == 6) rows_t<6>(table, w, row_bytes, n, a, nt, out, r0, r1);
else if (kb == 5) rows_t<5>(table, w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK5X
else if (kb == 4) rows_t<4>(table, w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK4X
else rows_t<7>(table, w, row_bytes, n, a, nt, out, r0, r1);
}
} // namespace strata::kernels::cpu::tq_detail
+33
View File
@@ -0,0 +1,33 @@
// src/kernels/cpu/tq_computed.hpp - the LUT-free ("computed") codebook of the experimental trellis types TQK5X / TQK4X
// (version 2): a state's four weights come from two 32-bit LCG words instead of the hashed 2048-point table.
//
// r_i = ((s * A_i + B_i) & 0x8FFF8FFF) ^ 0x3B603B60 i = 0, 1 (s = the 15-bit state)
// weights 0, 1 = the low and high fp16 of r_0, weights 2, 3 = those of r_1
//
// (QTIP's 3INST word, Tseng et al., Cornell-RelaxML/qtip lib/codebook/bitshift.py; the variant "3single" of the
// f-dsv41-cudalab study, which measured it at the SQNR of the table on real DeepSeek experts and a GEMV without
// shared-memory lookups.) The mask fixes the top exponent bits, so |w| lies in [0.125, 2) and the int16 table value
// round(w * 2^13) used by the CPU kernels is an exact integer (1024..16383): decoder and encoder agree to the bit.
// The existing types (TQ2_T, TQK6, TQK7) and the table-based K5 / K4 (ids 226 / 227, "version 1") do not use it.
#pragma once
#include <cstdint>
#include "tq_states.hpp"
namespace strata::kernels::cpu::tq_detail {
inline constexpr uint32_t kCompA[2] = {89226354u, 0x9E3779B1u};
inline constexpr uint32_t kCompB[2] = {64248484u, 0x7F4A7C15u};
inline constexpr uint32_t kCompMask = 0x8FFF8FFFu, kCompXor = 0x3B603B60u;
inline uint32_t comp_word(uint32_t s, int i) { return ((s * kCompA[i] + kCompB[i]) & kCompMask) ^ kCompXor; }
/// The four weights of state s at scale 2^13 (int16, exact).
inline void comp_state4(uint32_t s, int16_t out[4]) {
const uint32_t r0 = comp_word(s & 0x7fffu, 0), r1 = comp_word(s & 0x7fffu, 1);
const uint16_t h[4] = {(uint16_t) (r0 & 0xffffu), (uint16_t) (r0 >> 16), (uint16_t) (r1 & 0xffffu), (uint16_t) (r1 >> 16)};
for (int j = 0; j < 4; ++j) out[j] = (int16_t) (tq_half_to_float(h[j]) * 8192.0f);
}
} // namespace strata::kernels::cpu::tq_detail
+234
View File
@@ -0,0 +1,234 @@
// src/kernels/cpu/tq_cpu.cpp - see include/strata/kernels/cpu/tq_cpu.hpp: the state table, the scalar reference
// kernel, the activation unpacking and the run-time ISA choice. Compiled for the baseline x86-64 (no AVX), so
// everything here runs on any CPU; the AVX2 / AVX-512 kernels are in their own translation units.
#include "strata/kernels/cpu/tq_cpu.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "tq_states.hpp"
#include "tq_computed.hpp"
#include "ggml-common-tq.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
// The AVX2 / AVX-512 units (tq_avx2.cpp, tq_avx512.cpp) exist on x86-64 builds only; anything else (arm64: the Metal build)
// runs the scalar kernel.
#if defined(__x86_64__) || defined(_M_X64)
#define STRATA_TQ_X86 1
#endif
namespace strata::kernels::cpu {
namespace {
alignas(64) int16_t g_table[(tq_detail::kTqStateMask + 1) * 4];
alignas(64) int16_t g_table_c[(tq_detail::kTqStateMask + 1) * 4];
void fill_table() {
for (uint32_t s = 0; s <= tq_detail::kTqStateMask; ++s) {
const uint32_t x = s * 0x9e3779b1u;
const uint32_t pts[2] = {x >> 21, (x >> 10) & 2047u}; // the hash's two codebook points
for (int h = 0; h < 2; ++h)
for (int j = 0; j < 2; ++j) {
// fp16 * 2^13 is exact in float; round half away from zero, as the fork's ggml-cpu table does
const float v = tq_detail::tq_half_to_float(tq_lut_f16[2 * pts[h] + j]) * 8192.0f;
g_table[4 * s + 2 * h + j] = (int16_t) (v < 0.0f ? v - 0.5f : v + 0.5f);
}
}
}
void fill_table_computed() {
for (uint32_t s = 0; s <= tq_detail::kTqStateMask; ++s) tq_detail::comp_state4(s, g_table_c + 4 * s);
}
int env_isa_cap() {
const char* e = std::getenv("STRATA_TQ_ISA");
if (e == nullptr || *e == 0) return 2;
const std::string v(e);
if (v == "scalar") return 0;
if (v == "avx2") return 1;
return 2;
}
template <int KB>
void rows_scalar_t(const int16_t* tab, const uint8_t* w, size_t row_bytes, int n, const tq_detail::TqAct* const* a, int nt,
float* const* out, int r0, int r1) {
const int nb = n / 128;
constexpr size_t bsz = 2 + 4 * KB;
for (int r = r0; r < r1; ++r) {
const uint8_t* x = w + (size_t) r * row_bytes;
float acc[kTqMaxTokens][4] = {};
for (int i = 0; i < nb; ++i) {
const uint8_t* blk = x + (size_t) i * bsz;
const float dx = tq_detail::tq_half_to_float(tq_detail::tq_ld16(blk));
uint32_t st[32];
tq_detail::tq_states<KB>(blk + 2, st);
for (int t = 0; t < nt; ++t) {
const int16_t* q = a[t]->q + 128 * i;
for (int k = 0; k < 4; ++k) {
int32_t s = 0;
for (int j = 0; j < 8; ++j) {
const int16_t* wv = tab + 4 * st[8 * k + j];
const int16_t* qv = q + 32 * k + 4 * j;
s += wv[0] * qv[0] + wv[1] * qv[1] + wv[2] * qv[2] + wv[3] * qv[3];
}
const float sc = dx * a[t]->d[4 * i + k];
acc[t][k] = std::fma((float) s, sc, acc[t][k]);
}
}
}
for (int t = 0; t < nt; ++t)
out[t][r] = ((acc[t][0] + acc[t][1]) + (acc[t][2] + acc[t][3])) * (1.0f / 8192.0f);
}
}
} // namespace
const int16_t* tq_state_table() {
static std::once_flag once;
std::call_once(once, fill_table);
return g_table;
}
const int16_t* tq_state_table_computed() {
static std::once_flag once;
std::call_once(once, fill_table_computed);
return g_table_c;
}
const int16_t* tq_state_table_for(int t) { return (t == kTqTypeK5X || t == kTqTypeK4X) ? tq_state_table_computed() : tq_state_table(); }
bool tq_supported(int t) noexcept {
return t == 144 || t == 145 || t == 146 || t == kTqTypeK5X || t == kTqTypeK4X || t == kTqTypeK5T || t == kTqTypeK4T;
}
int tq_kbits(int t) noexcept {
return t == 144 ? 8 : t == 145 ? 6 : t == 146 ? 7 : (t == kTqTypeK5X || t == kTqTypeK5T) ? 5 : (t == kTqTypeK4X || t == kTqTypeK4T) ? 4 : 0;
}
bool tq_isa_ok(TqIsa isa) {
#if defined(STRATA_TQ_X86)
switch (isa) {
case TqIsa::avx512: return cpu_avx512_ok();
case TqIsa::avx2: return cpu_avx2_ok();
default: return true;
}
#else
return isa == TqIsa::scalar; // arm64 (the Metal build): the AVX units are not compiled, the scalar kernel runs
#endif
}
TqIsa tq_isa() {
static const TqIsa isa = [] {
const int cap = env_isa_cap();
if (cap >= 2 && tq_isa_ok(TqIsa::avx512)) return TqIsa::avx512;
if (cap >= 1 && tq_isa_ok(TqIsa::avx2)) return TqIsa::avx2;
return TqIsa::scalar;
}();
return isa;
}
bool tq_kernels_enabled() {
static const bool on = [] {
if (const char* e = std::getenv("STRATA_NO_TQ_KERNELS"); e != nullptr && std::atoi(e) != 0) return false;
// Every CPU runs them: the scalar kernel (baseline x86-64) where there is no AVX2. A ggml built from upstream
// has no vec_dot for the trellis types to fall back to, so a CPU without AVX2 must not be sent there.
return true;
}();
return on;
}
const char* tq_isa_name(TqIsa isa) {
return isa == TqIsa::avx512 ? "avx512" : isa == TqIsa::avx2 ? "avx2" : "scalar";
}
namespace tq_detail {
void unpack_act(const void* q8_0, int n, TqAct& a) {
const uint8_t* p = (const uint8_t*) q8_0;
for (int b = 0; b < n / 32; ++b, p += 34) { // block_q8_0: fp16 d, 32 x int8
a.d[b] = tq_half_to_float(tq_ld16(p));
const int8_t* q = (const int8_t*) (p + 2);
for (int j = 0; j < 32; ++j) a.q[32 * b + j] = q[j];
}
}
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) {
if (kb == 8) rows_scalar_t<8>(tab, w, row_bytes, n, a, nt, out, r0, r1);
else if (kb == 6) rows_scalar_t<6>(tab, w, row_bytes, n, a, nt, out, r0, r1);
else if (kb == 5) rows_scalar_t<5>(tab, w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK5X / TQK5T
else if (kb == 4) rows_scalar_t<4>(tab, w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK4X / TQK4T
else rows_scalar_t<7>(tab, w, row_bytes, n, a, nt, out, r0, r1);
}
} // namespace tq_detail
namespace {
// the activations of one call, unpacked once for all its rows
struct ActSet {
tq_detail::TqAct act[kTqMaxTokens];
const tq_detail::TqAct* ptr[kTqMaxTokens];
};
ActSet& unpack_all(const void* const* act, int n, int nt) {
thread_local std::unique_ptr<ActSet> set;
if (!set) set.reset(new ActSet);
for (int t = 0; t < nt; ++t) {
tq_detail::unpack_act(act[t], n, set->act[t]);
set->ptr[t] = &set->act[t];
}
return *set;
}
void rows_on(TqIsa isa, int kb, const int16_t* tab, const uint8_t* w, size_t row_bytes, int n,
const tq_detail::TqAct* const* a, int nt, float* const* out, int r0, int r1) {
switch (isa) {
#if defined(STRATA_TQ_X86)
case TqIsa::avx512: tq_detail::tq_rows_avx512(kb, tab, w, row_bytes, n, a, nt, out, r0, r1); break;
case TqIsa::avx2: tq_detail::tq_rows_avx2(kb, tab, w, row_bytes, n, a, nt, out, r0, r1); break;
#endif
default: tq_detail::tq_rows_scalar(kb, tab, w, row_bytes, n, a, nt, out, r0, r1); break;
}
}
} // namespace
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) {
if (!tq_isa_ok(isa)) std::abort(); // a caller bug: asked for an ISA this CPU does not have
const int16_t* tab = tq_state_table_for(ggml_type);
const ActSet& s = unpack_all(act, n, nt);
rows_on(isa, tq_kbits(ggml_type), tab, w, row_bytes, n, s.ptr, nt, out, r0, r1);
}
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) {
if (!tq_isa_ok(isa)) std::abort();
const int16_t* tab = tq_state_table_for(ggml_type);
const ActSet& s = unpack_all(act, n, nt);
thread_local std::vector<float> gbuf, ubuf;
const size_t nr = (size_t) r1; // row r of token t at [t * r1 + r]
if (gbuf.size() < nr * kTqMaxTokens) { gbuf.resize(nr * kTqMaxTokens); ubuf.resize(nr * kTqMaxTokens); }
float* gp[kTqMaxTokens];
float* up[kTqMaxTokens];
for (int t = 0; t < nt; ++t) {
gp[t] = gbuf.data() + (size_t) t * nr;
up[t] = ubuf.data() + (size_t) t * nr;
}
const int kb = tq_kbits(ggml_type);
rows_on(isa, kb, tab, blob, gu_row, n, s.ptr, nt, gp, r0, r1);
rows_on(isa, kb, tab, blob + up_off, gu_row, n, s.ptr, nt, up, r0, r1);
for (int t = 0; t < nt; ++t)
for (int r = r0; r < r1; ++r) {
const float g = gp[t][r], u = up[t][r];
ff[t][r] = (g / (1.f + std::exp(-g))) * u; // native_gu_rows' SwiGLU expression
}
}
} // namespace strata::kernels::cpu
+88
View File
@@ -0,0 +1,88 @@
// src/kernels/cpu/tq_states.hpp - the 32 trellis states of one TQ2_T / TQK6 / TQK7 block in plain C++ (all three
// kernels: scalar code beat byte-shuffle versions on AVX2 and AVX-512). Internal to src/kernels/cpu/tq_*.cpp.
//
// TQ2_T (K = 8): state t = qs[(t + 31) % 32] << 8 | qs[t], masked to 15 bits.
// TQK (K = 6, 7): the 16 stream bits from bit (31 - t)*K, LSB first, circular modulo 32*K bits, masked to 15 bits.
// Every window is one unaligned 32-bit little-endian read inside the block's 4*K bytes, except the windows that run
// past the end (t = 0 and 1), which read a 64-bit view of the last four bytes followed by the first four.
#pragma once
#include <cstdint>
#include <cstring>
namespace strata::kernels::cpu::tq_detail {
inline constexpr uint32_t kTqStateMask = 0x7fffu;
inline uint32_t tq_ld32(const uint8_t* p) {
uint32_t v;
std::memcpy(&v, p, 4);
return v; // x86 (and every target Strata builds for) is little-endian
}
/// State t alone (t a constant after unrolling); `wrap` = tq_wrap<KB>(qs) for the TQK windows past the end.
template <int KB>
inline uint64_t tq_wrap(const uint8_t* qs) {
if constexpr (KB == 8) return 0;
else return (uint64_t) tq_ld32(qs + 4 * KB - 4) | ((uint64_t) tq_ld32(qs) << 32);
}
template <int KB>
inline uint32_t tq_state(const uint8_t* qs, uint64_t wrap, int t) {
if constexpr (KB == 8) {
return (((uint32_t) qs[(t + 31) & 31] << 8) | qs[t]) & kTqStateMask;
} else {
constexpr int NB = 4 * KB;
const int off = (31 - t) * KB, b = off >> 3;
const uint32_t v = b + 4 <= NB ? tq_ld32(qs + b) >> (off & 7) : (uint32_t) (wrap >> (off - 8 * (NB - 4)));
return v & kTqStateMask;
}
}
template <int KB>
inline void tq_states(const uint8_t* qs, uint32_t* st) {
if constexpr (KB == 8) {
st[0] = (((uint32_t) qs[31] << 8) | qs[0]) & kTqStateMask;
#if defined(__GNUC__)
#pragma GCC unroll 31
#endif
for (int t = 1; t < 32; ++t) st[t] = (((uint32_t) qs[t - 1] << 8) | qs[t]) & kTqStateMask;
} else {
constexpr int NB = 4 * KB;
const uint64_t wrap = (uint64_t) tq_ld32(qs + NB - 4) | ((uint64_t) tq_ld32(qs) << 32);
#if defined(__GNUC__)
#pragma GCC unroll 32
#endif
for (int t = 0; t < 32; ++t) {
const int off = (31 - t) * KB, b = off >> 3;
const uint32_t v = b + 4 <= NB ? tq_ld32(qs + b) >> (off & 7) : (uint32_t) (wrap >> (off - 8 * (NB - 4)));
st[t] = v & kTqStateMask;
}
}
}
/// fp16 bits -> float, exact (the block scales and the Q8_0 activation scales).
inline float tq_half_to_float(uint16_t h) {
const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
uint32_t exp = (h >> 10) & 0x1fu, man = h & 0x3ffu, bits;
if (exp == 0x1fu) {
bits = sign | 0x7f800000u | (man << 13);
} else if (exp != 0) {
bits = sign | ((exp + 112u) << 23) | (man << 13);
} else if (man == 0) {
bits = sign;
} else { // subnormal: man * 2^-24, exact in float
const float m = (float) man * (1.0f / 16777216.0f);
return sign ? -m : m;
}
float f;
std::memcpy(&f, &bits, 4);
return f;
}
inline uint16_t tq_ld16(const uint8_t* p) {
uint16_t v;
std::memcpy(&v, p, 2);
return v;
}
} // namespace strata::kernels::cpu::tq_detail
+107
View File
@@ -0,0 +1,107 @@
// 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.
// tests/ds4_cpu_bench.cpp - how fast does this CPU run DeepSeek-V4.1-Flash's EXL3 experts (5120 -> 2304 -> 5120, K 3)?
//
// ds4_cpu_bench [--threads N] [--node 0|1|-1] [--mode band|rows] [--experts N] [--per-call N] [--iters N]
//
// Random trellis words in memory bound to --node (-1: wherever the first touch puts them), --threads workers pinned to
// that node's physical cores (CPU i is on node i % 2 here, CPUs 0..43 the physical cores), each call computing
// --per-call experts' gate and up (all columns) from one activation: the time of a matrix pass and its GB/s.
#include "strata/dsv41/exl3_cpu.hpp"
#include "../../src/dsv41/ds4_pool.hpp"
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
namespace kc = strata::dsv41k::cpu;
static void* node_alloc(size_t bytes, int node) {
void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED) return nullptr;
madvise(p, bytes, MADV_HUGEPAGE);
if (node >= 0) {
unsigned long mask = 1ul << node;
if (syscall(SYS_mbind, p, bytes, 2 /*MPOL_BIND*/, &mask, 64, 0) != 0) std::perror("mbind");
}
return p;
}
int main(int argc, char** argv) {
int threads = 22, node = 0, n_exp = 64, per_call = 2, iters = 40;
std::string mode = "rows";
for (int i = 1; i + 1 < argc; i += 2) {
const std::string a = argv[i];
if (a == "--threads") threads = std::atoi(argv[i + 1]);
else if (a == "--node") node = std::atoi(argv[i + 1]);
else if (a == "--mode") mode = argv[i + 1];
else if (a == "--experts") n_exp = std::atoi(argv[i + 1]);
else if (a == "--per-call") per_call = std::atoi(argv[i + 1]);
else if (a == "--iters") iters = std::atoi(argv[i + 1]);
}
const int E = 5120, FF = 2304, K = 3;
const size_t tb = (size_t) E / 16 * FF / 16 * 32 * K; // one matrix's trellis
std::vector<int> cpus;
for (int c = 0; c < 44; ++c)
if (node < 0 || c % 2 == node) cpus.push_back(c);
strata::ds4::Pool pool(threads - 1, std::vector<int>(cpus.begin() + 1, cpus.end()));
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpus[0], &set);
sched_setaffinity(0, sizeof set, &set);
}
uint8_t* mem = (uint8_t*) node_alloc(tb * n_exp, node);
std::vector<uint16_t> suh(E), svh(FF);
for (auto& v : suh) v = 0x3c00; // 1.0
for (auto& v : svh) v = 0x3c00;
pool.run(n_exp, [&](int e) {
std::mt19937 r(e);
uint32_t* w = (uint32_t*) (mem + tb * e);
for (size_t i = 0; i < tb / 4; ++i) w[i] = r();
});
std::vector<float> x(E, 0.5f), xh(E), acc((size_t) 64 * FF), y((size_t) per_call * FF);
const float xs = 0.0f;
kc::Exl3Part p0;
p0.suh = suh.data();
p0.svh = svh.data();
p0.k = E;
p0.n = FF;
p0.K = K;
kc::exl3_cpu_prepare(p0, x.data(), xh.data());
const int GQ = E / 256; // rows mode: pieces of 256 inputs over every column
std::vector<float> accp((size_t) per_call * GQ * FF);
auto t0 = std::chrono::steady_clock::now();
long long bytes = 0;
for (int it = 0; it < iters; ++it) {
const int base = (it * per_call) % (n_exp - per_call + 1);
if (mode == "band") {
pool.run(per_call * (FF / 128), [&](int j) {
kc::Exl3Part p = p0;
p.trellis = (const uint32_t*) (mem + tb * (base + j / (FF / 128)));
kc::exl3_cpu_band(p, xh.data(), xs, (j % (FF / 128)) * 128,
y.data() + (size_t) (j / (FF / 128)) * FF + (j % (FF / 128)) * 128);
});
} else {
pool.run(per_call * GQ, [&](int j) {
kc::Exl3Part p = p0;
p.trellis = (const uint32_t*) (mem + tb * (base + j / GQ));
const int q = j % GQ;
kc::exl3_cpu_rows_acc(p, xh.data(), q * 16, (q + 1) * 16, accp.data() + (size_t) j * FF);
});
}
bytes += (long long) tb * per_call;
}
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
std::printf("%s node %d threads %d per-call %d: %.3f ms per matrix, %.1f GB/s\n", mode.c_str(), node, threads,
per_call, ms / (iters * per_call), bytes / 1e6 / ms);
return 0;
}
File diff suppressed because it is too large. Load diff
+383
View File
@@ -0,0 +1,383 @@
// 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.
// tests/ds4_mx_bench.cpp - how fast does this CPU run DeepSeek-V4.1-Flash's MXFP4 experts on the CPU lane?
//
// ds4_mx_bench [--threads 1,6,12] [--T 1,2,4,8,16] [--experts 16] [--per-layer 3] [--secs 0.4] [--pf 0]
// [--kernels float,avx2,avxvnni,avx512,avx512vnni,ggml,scalar] [--file PATH] [--make-file PATH]
//
// Experts of the real shape (gate / up 2304 rows x 5120, down 5120 x 2304, MXFP4: 18.8 MB each) with random codes in
// anonymous memory (huge pages where the OS gives them), or in a file's mapping (--file: 4 KiB page-cache pages, as the
// engine reads the GGUF; --make-file writes one). A "layer" is --per-layer experts, as the lane runs them: the gate /
// up rows of every expert in 64-row jobs on the pool, then (a barrier) their down rows; the layers walk through the
// experts, so the weights come from RAM, not the cache. Prints the weights' GB/s for each kernel x tokens x threads
// (T tokens a call: each row read once for up to 8 of them), the int8 tiers' agreement with the scalar tier, and the
// cost of the activation quant and of madvise(WILLNEED) on cached pages.
#include "../../src/dsv41/ds4_gguf_cpu.hpp"
#include "../../src/dsv41/ds4_pool.hpp"
#if defined(STRATA_NATIVE_EXPERTS)
#include "ggml-cpu.h"
#include "ggml.h"
#endif
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
namespace gg = strata::ds4::gguf;
namespace os = strata::ds4::os;
using strata::ds4::Pool;
namespace {
constexpr int E = 5120, FF = 2304, RB = 64;
const size_t kGr = (size_t) E / 32 * 17, kDr = (size_t) FF / 32 * 17; // row bytes
const size_t kMat = kGr * FF; // gate (= up = down) bytes
const size_t kExpert = 3 * kMat;
double now_s() {
return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
}
std::vector<int> ints(const std::string& s) {
std::vector<int> v;
size_t a = 0;
while (a < s.size()) {
size_t b = s.find(',', a);
if (b == std::string::npos) b = s.size();
v.push_back(std::atoi(s.substr(a, b - a).c_str()));
a = b + 1;
}
return v;
}
std::vector<std::string> words(const std::string& s) {
std::vector<std::string> v;
size_t a = 0;
while (a < s.size()) {
size_t b = s.find(',', a);
if (b == std::string::npos) b = s.size();
v.push_back(s.substr(a, b - a));
a = b + 1;
}
return v;
}
// the logical CPUs, one of each core first, then their second threads (pinning order)
std::vector<int> cpu_order() {
std::vector<int> first, rest;
#if defined(_WIN32)
DWORD len = 0;
GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len);
std::vector<uint8_t> buf(len);
if (len > 0 && GetLogicalProcessorInformationEx(RelationProcessorCore,
(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) {
for (size_t o = 0; o < buf.size();) {
auto* e = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) (buf.data() + o);
if (e->Processor.GroupCount > 0 && e->Processor.GroupMask[0].Group == 0) {
const KAFFINITY m = e->Processor.GroupMask[0].Mask;
bool f = true;
for (int b = 0; b < 64; ++b)
if ((m >> b) & 1) {
(f ? first : rest).push_back(b);
f = false;
}
}
o += e->Size;
}
}
#else
for (int c = 0; c < 1024; ++c) {
std::FILE* f = std::fopen(("/sys/devices/system/cpu/cpu" + std::to_string(c) + "/topology/thread_siblings_list").c_str(), "r");
if (f == nullptr) break;
int s0 = -1;
if (std::fscanf(f, "%d", &s0) != 1) s0 = c;
std::fclose(f);
(s0 == c ? first : rest).push_back(c);
}
#endif
if (first.empty())
for (unsigned c = 0; c < std::max(1u, std::thread::hardware_concurrency()); ++c) first.push_back((int) c);
std::sort(first.begin(), first.end());
std::sort(rest.begin(), rest.end());
first.insert(first.end(), rest.begin(), rest.end());
return first;
}
void fill_mx(uint8_t* p, size_t bytes, uint64_t seed) { // random MXFP4 blocks, scales 2^-14 .. 2^-6 as weights'
std::mt19937_64 rng(seed);
for (size_t b = 0; b + 17 <= bytes; b += 17) {
const uint64_t r = rng(), s = rng();
p[b] = (uint8_t) (114 + r % 9);
std::memcpy(p + b + 1, &r, 8);
std::memcpy(p + b + 9, &s, 8);
}
}
enum Kern { kFloat = 100, kGgml = 101 };
int kern_id(const std::string& s) {
if (s == "float") return kFloat;
if (s == "ggml") return kGgml;
for (int t = 0; t < gg::kMxTiers; ++t)
if (s == gg::mx_tier_name(t)) return t;
return -1;
}
struct Acts { // T tokens' activations of E and FF values in every form a kernel takes
int T = 0;
std::vector<float> xf, hf; // F32 (rounded as q8_round) [T][E], [T][FF]
std::vector<uint8_t> xq, hq; // mx_quant's [T][2E], [T][2FF]
std::vector<uint8_t> x8, h8; // ggml's block_q8_0 [T][E / 32 * 34]
void make(int t, uint64_t seed) {
T = t;
std::mt19937 rng((unsigned) seed);
std::normal_distribution<float> nd(0.0f, 1.0f);
xf.resize((size_t) T * E);
hf.resize((size_t) T * FF);
for (auto& v : xf) v = nd(rng);
for (auto& v : hf) v = 0.05f * nd(rng);
xq.resize((size_t) T * gg::mx_act_bytes(E));
hq.resize((size_t) T * gg::mx_act_bytes(FF));
x8.resize((size_t) T * E / 32 * 34);
h8.resize((size_t) T * FF / 32 * 34);
for (int i = 0; i < T; ++i) {
gg::mx_quant(&xf[(size_t) i * E], E, &xq[(size_t) i * gg::mx_act_bytes(E)]);
gg::mx_quant(&hf[(size_t) i * FF], FF, &hq[(size_t) i * gg::mx_act_bytes(FF)]);
#if defined(STRATA_NATIVE_EXPERTS)
const auto* q8 = ggml_get_type_traits_cpu(GGML_TYPE_Q8_0);
q8->from_float(&xf[(size_t) i * E], &x8[(size_t) i * E / 32 * 34], E);
q8->from_float(&hf[(size_t) i * FF], &h8[(size_t) i * FF / 32 * 34], FF);
#endif
gg::q8_round(&xf[(size_t) i * E], E, &xf[(size_t) i * E]);
gg::q8_round(&hf[(size_t) i * FF], FF, &hf[(size_t) i * FF]);
}
}
};
// rows [r0, r1) of one matrix (k values a row) against the T activations, kernel `kern`
void rows(int kern, const uint8_t* w, size_t rb, int k, int r0, int r1, const Acts& a, float* const* y, int pf) {
const bool down = k == FF;
if (kern == kFloat) {
for (int i0 = 0; i0 < a.T; i0 += 8) {
const float* xp[8];
const int n = std::min(8, a.T - i0);
for (int i = 0; i < n; ++i) xp[i] = (down ? a.hf.data() : a.xf.data()) + (size_t) (i0 + i) * k;
gg::mx_cpu_rows(w, rb, k, r0, r1, xp, n, y + i0);
}
return;
}
if (kern == kGgml) {
#if defined(STRATA_NATIVE_EXPERTS)
static const ggml_vec_dot_t dot = ggml_get_type_traits_cpu(GGML_TYPE_MXFP4)->vec_dot;
const uint8_t* x8 = down ? a.h8.data() : a.x8.data();
for (int r = r0; r < r1; ++r)
for (int i = 0; i < a.T; ++i) dot(k, &y[i][r - r0], 0, w + (size_t) r * rb, 0, x8 + (size_t) i * k / 32 * 34, 0, 1);
#endif
return;
}
const void* ap[16];
for (int i = 0; i < a.T; ++i) ap[i] = (down ? a.hq.data() : a.xq.data()) + (size_t) i * gg::mx_act_bytes(k);
gg::mx_rows_tier(kern, w, rb, k, r0, r1, ap, a.T, y, pf);
}
struct Bench {
const uint8_t* mem = nullptr;
int n_exp = 16, per_layer = 3;
double secs = 0.4;
// GB/s of weights with `pool` (its size the threads), kernel kern, the T tokens of a
double run(Pool& pool, int kern, const Acts& a, int pf) {
const int GB = FF / RB, DB = E / RB;
std::vector<std::vector<float>> ys((size_t) pool.size() * 64);
int layer = 0;
size_t bytes = 0;
auto one_layer = [&] {
const int e0 = (layer * per_layer) % n_exp;
std::function<void(int)> fgu = [&](int j) {
const int e = (e0 + j / (2 * GB)) % n_exp, m = (j / GB) % 2, b = j % GB;
float yb[16][RB];
float* yp[16];
for (int i = 0; i < a.T; ++i) yp[i] = yb[i];
rows(kern, mem + (size_t) e * kExpert + (size_t) m * kMat, kGr, E, b * RB, b * RB + RB, a, yp, pf);
};
pool.run(per_layer * 2 * GB, fgu);
std::function<void(int)> fd = [&](int j) {
const int e = (e0 + j / DB) % n_exp, b = j % DB;
float yb[16][RB];
float* yp[16];
for (int i = 0; i < a.T; ++i) yp[i] = yb[i];
rows(kern, mem + (size_t) e * kExpert + 2 * kMat, kDr, FF, b * RB, b * RB + RB, a, yp, pf);
};
pool.run(per_layer * DB, fd);
bytes += (size_t) per_layer * kExpert;
++layer;
};
for (int w = 0; w < 2; ++w) one_layer(); // (warm: the threads, the code)
bytes = 0;
const double t0 = now_s();
double t = t0;
while (t - t0 < secs) {
one_layer();
t = now_s();
}
return bytes / (t - t0) / 1e9;
}
};
} // namespace
int main(int argc, char** argv) {
std::vector<int> threads = {1}, Ts = {1, 2, 4, 8, 16}, pfs = {0};
std::vector<std::string> kerns = {"float", "avx2", "avxvnni", "avx512", "avx512vnni", "ggml"};
std::string file, make_file;
Bench B;
for (int i = 1; i + 1 < argc; i += 2) {
const std::string a = argv[i], v = argv[i + 1];
if (a == "--threads") threads = ints(v);
else if (a == "--T") Ts = ints(v);
else if (a == "--pf") pfs = ints(v);
else if (a == "--experts") B.n_exp = std::atoi(v.c_str());
else if (a == "--per-layer") B.per_layer = std::atoi(v.c_str());
else if (a == "--secs") B.secs = std::atof(v.c_str());
else if (a == "--kernels") kerns = words(v);
else if (a == "--file") file = v;
else if (a == "--make-file") make_file = v;
}
#if defined(STRATA_NATIVE_EXPERTS)
ggml_cpu_init();
#endif
const size_t total = (size_t) B.n_exp * kExpert;
if (!make_file.empty()) {
std::FILE* f = std::fopen(make_file.c_str(), "wb");
if (f == nullptr) return 1;
std::vector<uint8_t> buf(kExpert);
for (int e = 0; e < B.n_exp; ++e) {
fill_mx(buf.data(), buf.size(), 1000 + (uint64_t) e);
std::fwrite(buf.data(), 1, buf.size(), f);
}
std::fclose(f);
std::printf("wrote %s: %d experts, %.0f MB\n", make_file.c_str(), B.n_exp, total / 1e6);
return 0;
}
os::fd_t fd = os::kBadFd;
if (!file.empty()) {
fd = os::open_ro(file);
if (fd == os::kBadFd || os::file_size(fd) < total) {
std::fprintf(stderr, "%s: cannot open, or smaller than %d experts\n", file.c_str(), B.n_exp);
return 1;
}
B.mem = (const uint8_t*) os::map_ro(fd, total);
volatile uint64_t s = 0; // (into the page cache and the mapping)
for (size_t o = 0; o < total; o += 4096) s += B.mem[o];
} else {
uint8_t* m = (uint8_t*) os::anon_alloc(total, -1, 1);
if (m == nullptr) return 1;
for (int e = 0; e < B.n_exp; ++e) fill_mx(m + (size_t) e * kExpert, kExpert, 1000 + (uint64_t) e);
B.mem = m;
}
std::printf("CPU tiers:");
for (int t = 0; t < gg::kMxTiers; ++t)
if (gg::mx_tier_ok(t)) std::printf(" %s", gg::mx_tier_name(t));
std::printf(" (mx_rows takes %s: %s); weights %s, %d experts (%.0f MB), %d a layer\n", gg::mx_tier_name(gg::mx_tier()),
gg::mx_tier_report(), file.empty() ? "anonymous memory" : file.c_str(), B.n_exp, total / 1e6, B.per_layer);
// ---- the int8 tiers against the scalar tier, and the old F32 path against both (T = 3, 64 rows of each kind)
{
Acts a;
a.make(3, 7);
for (int down = 0; down < 2; ++down) {
const int k = down ? FF : E;
const size_t rb = down ? kDr : kGr;
const uint8_t* w = B.mem + (down ? 2 * kMat : 0);
float ref[3][RB], got[3][RB];
float* rp[3] = {ref[0], ref[1], ref[2]};
float* gp[3] = {got[0], got[1], got[2]};
rows(gg::kMxScalar, w, rb, k, 0, RB, a, rp, 0);
for (int t = 0; t < gg::kMxTiers + 1; ++t) {
const int kern = t < gg::kMxTiers ? t : kFloat;
if (kern != kFloat && (kern == gg::kMxScalar || !gg::mx_tier_ok(kern))) continue;
rows(kern, w, rb, k, 0, RB, a, gp, 0);
double md = 0, mx = 0;
for (int i = 0; i < 3; ++i)
for (int r = 0; r < RB; ++r) {
md = std::max(md, (double) std::fabs(got[i][r] - ref[i][r]));
mx = std::max(mx, (double) std::fabs(ref[i][r]));
}
std::printf(" %-6s %-10s vs scalar: max |diff| %.3g (max |y| %.3g, rel %.2g)%s\n", down ? "down" : "gate",
kern == kFloat ? "float" : gg::mx_tier_name(kern), md, mx, md / std::max(mx, 1e-30),
kern != kFloat && std::memcmp(got, ref, sizeof got) == 0 ? " bit-identical" : "");
}
}
// the quant's two forms: the same bytes
std::vector<uint8_t> q1(gg::mx_act_bytes(E)), q2(gg::mx_act_bytes(E));
gg::mx_quant_blocks(a.xf.data(), 0, E / 32, q1.data(), E);
gg::mx_quant_blocks_scalar(a.xf.data(), 0, E / 32, q2.data(), E);
std::printf(" quant: vector vs scalar bytes %s\n", q1 == q2 ? "identical" : "DIFFER");
}
// ---- the quant and madvise costs
{
std::vector<float> x(E), r(E);
std::mt19937 rng(3);
std::normal_distribution<float> nd;
for (auto& v : x) v = nd(rng);
std::vector<uint8_t> q(gg::mx_act_bytes(E));
const int N = 20000;
double t0 = now_s();
for (int i = 0; i < N; ++i) gg::mx_quant(x.data(), E, q.data());
const double tq = (now_s() - t0) / N;
t0 = now_s();
for (int i = 0; i < N / 10; ++i) gg::q8_round(x.data(), E, r.data());
const double tr = (now_s() - t0) / (N / 10);
std::printf("activation of %d: mx_quant %.2f us, q8_round (old, scalar) %.2f us\n", E, tq * 1e6, tr * 1e6);
if (!file.empty()) {
t0 = now_s();
int n = 0;
for (int e = 0; e < B.n_exp; ++e)
for (int m = 0; m < 3; ++m, ++n)
os::prefetch({{B.mem + (size_t) e * kExpert + (size_t) m * kMat, kMat}});
std::printf("madvise(WILLNEED) of a cached expert matrix (%.1f MB): %.1f us\n", kMat / 1e6,
(now_s() - t0) / n * 1e6);
t0 = now_s();
int nres = 0;
for (int rep = 0; rep < 10; ++rep)
for (int e = 0; e < B.n_exp; ++e)
for (int m = 0; m < 3; ++m)
nres += os::resident_sampled(B.mem + (size_t) e * kExpert + (size_t) m * kMat, kMat);
std::printf("os::resident_sampled (8 pages) of an expert matrix: %.2f us (%d of %d resident)\n",
(now_s() - t0) / (10 * n) * 1e6, nres / 10, n);
}
}
// ---- the table
const std::vector<int> order = cpu_order();
std::printf("\n%-11s %3s %4s %5s %9s %10s\n", "kernel", "T", "thr", "pf", "GB/s", "GB/s/thr");
for (int nt : threads) {
nt = std::max(1, std::min(nt, (int) order.size()));
Pool pool(nt - 1, std::vector<int>(order.begin() + 1, order.begin() + nt), 20000);
os::pin_self(order[0]);
for (const std::string& ks : kerns) {
const int kern = kern_id(ks);
if (kern < 0 || (kern < gg::kMxTiers && !gg::mx_tier_ok(kern))) continue;
#if !defined(STRATA_NATIVE_EXPERTS)
if (kern == kGgml) continue;
#endif
for (int T : Ts) {
if (T < 1 || T > 16) continue;
Acts a;
a.make(T, 11 + (uint64_t) T);
for (int pf : pfs) {
if (pf != 0 && (kern == kFloat || kern == kGgml || kern == gg::kMxScalar)) continue;
const double g = B.run(pool, kern, a, pf);
std::printf("%-11s %3d %4d %5d %9.2f %10.2f\n", ks.c_str(), T, nt, pf, g, g / nt);
std::fflush(stdout);
}
}
}
}
return 0;
}
+284
View File
@@ -0,0 +1,284 @@
// Strata. The DeepSeek-V4.1 CPU lane's ggml-type rows (src/dsv41/ds4_gg_cpu.cpp): ggml-cpu's row dot against Strata's AVX2
// multi-token i-quant rows, on random blocks of IQ2_XXS / IQ3_XXS.
// ds4_gg_bench [--type 16|18] [--threads N] [--mb M] [--nt 1..8] [--reps R]
// Checks first (every row, every token): the two paths' results agree to a few float ulps (the integer sums are the same;
// only the order of the float additions differs) and, with --exact, bit for bit. Then the time of a pass over M MB of
// weights (default 3072, far past L3) on N threads, as GB/s of weights read, beside a plain streaming read of the same
// bytes (the memory ceiling the rows are measured against).
#include "ds4_gguf_cpu.hpp"
#include "ggml-cpu.h"
#include "ggml.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <thread>
#include <vector>
using namespace strata::ds4::gguf;
using clk = std::chrono::steady_clock;
static double secs(clk::time_point a) { return std::chrono::duration<double>(clk::now() - a).count(); }
// ---- --expert: the engine's expert pipeline on random experts (gate+up+SwiGLU, quantize h, down) in jobs of 64 rows over N threads, for
// ggml-cpu's dots (mode 0), the default rule (2) and the AVX2 rows always (1); GB/s of all three matrices' bytes, outputs compared bit for bit.
static void fill_blocks(uint8_t* w, size_t bytes, int type, uint64_t seed) {
uint64_t st = 0x9E3779B97F4A7C15ull ^ (seed * 0xD1B54A32D192ED03ull);
auto next = [&st] { st ^= st << 13; st ^= st >> 7; st ^= st << 17; return st; };
for (size_t o = 0; o + 8 <= bytes; o += 8) { const uint64_t v = next(); std::memcpy(w + o, &v, 8); }
const size_t bb = ggml_type_size((ggml_type) type);
for (size_t o = 0; o + bb <= bytes; o += bb) {
const ggml_fp16_t d = ggml_fp32_to_fp16(0.002f + 0.001f * (float) (next() % 16));
if (type == 29) {
uint16_t sc[4];
std::memcpy(sc, w + o + 48, 8);
for (int k = 0; k < 4; ++k) sc[k] = (uint16_t) ((sc[k] & 0x0fff) | ((d >> (4 * k)) & 0xf) << 12);
std::memcpy(w + o + 48, sc, 8);
} else {
std::memcpy(w + o, &d, sizeof d);
}
}
}
static int run_expert(int tg, int td, int threads, long mb, int nt, int reps) {
ggml_cpu_init();
const int E = 5120, FF = 2304;
IqCpu f;
std::string err;
if (!gg_cpu_fmt(tg, td, E, FF, f, err)) { std::fprintf(stderr, "gg_cpu_fmt: %s\n", err.c_str()); return 2; }
const size_t gbytes = f.gu_row * FF, dbytes = f.d_row * E, ebytes = 2 * gbytes + dbytes;
const int ne = (int) std::max(2L, (long) ((size_t) mb * 1000000 / ebytes));
std::vector<uint8_t> gw((size_t) ne * gbytes), uw((size_t) ne * gbytes), dw((size_t) ne * dbytes);
for (int e = 0; e < ne; ++e) {
fill_blocks(&gw[(size_t) e * gbytes], gbytes, tg, 3 * (uint64_t) e + 1);
fill_blocks(&uw[(size_t) e * gbytes], gbytes, tg, 3 * (uint64_t) e + 2);
fill_blocks(&dw[(size_t) e * dbytes], dbytes, td, 3 * (uint64_t) e + 3);
}
uint64_t st = 12345;
auto next = [&st] { st ^= st << 13; st ^= st >> 7; st ^= st << 17; return st; };
std::vector<std::vector<uint8_t>> act((size_t) nt, std::vector<uint8_t>(f.act_bytes));
for (int t = 0; t < nt; ++t) {
std::vector<float> x((size_t) E);
for (auto& v : x) v = ((float) (next() % 2001) - 1000.0f) * 1e-3f;
gg_cpu_quant(f.gu_act, x.data(), E, act[(size_t) t].data());
}
std::vector<float> h((size_t) ne * nt * FF), y((size_t) ne * nt * E);
std::vector<uint8_t> hq((size_t) ne * nt * f.h_bytes);
const int RB = 64;
auto run_jobs = [&](long njobs, const std::function<void(long)>& fn) {
std::atomic<long> cur{0};
std::vector<std::thread> th;
for (int k = 0; k < threads; ++k)
th.emplace_back([&] { for (;;) { const long j = cur.fetch_add(1); if (j >= njobs) break; fn(j); } });
for (auto& t : th) t.join();
};
auto pass = [&](int mode) {
gg_cpu_set_iq256(mode);
double best = 1e30;
for (int r = 0; r < reps + 1; ++r) {
const auto t0 = clk::now();
const long gb = (FF + RB - 1) / RB, db = (E + RB - 1) / RB;
run_jobs((long) ne * gb, [&](long j) {
const int e = (int) (j / gb), r0 = (int) (j % gb) * RB, r1 = std::min(FF, r0 + RB);
const void* ap[64];
float* hp[64];
for (int t = 0; t < nt; ++t) { ap[t] = act[(size_t) t].data(); hp[t] = &h[((size_t) e * nt + t) * FF]; }
gg_cpu_gate_up(f, &gw[(size_t) e * gbytes], &uw[(size_t) e * gbytes], ap, nt, hp, r0, r1, 10.0f);
});
run_jobs((long) ne * nt, [&](long j) { gg_cpu_quant(f.d_act, &h[(size_t) j * FF], FF, &hq[(size_t) j * f.h_bytes]); });
run_jobs((long) ne * db, [&](long j) {
const int e = (int) (j / db), r0 = (int) (j % db) * RB, r1 = std::min(E, r0 + RB);
const void* hp[64];
float* yp[64];
for (int t = 0; t < nt; ++t) { hp[t] = &hq[((size_t) e * nt + t) * f.h_bytes]; yp[t] = &y[((size_t) e * nt + t) * E]; }
gg_cpu_down(f, &dw[(size_t) e * dbytes], hp, nt, yp, r0, r1);
});
if (r > 0) best = std::min(best, secs(t0));
}
return best;
};
const double gb = (double) ne * ebytes / 1e9;
std::vector<float> y0;
double t0s = 0;
int rc = 0;
for (int mode : {0, 2, 1}) {
const double t = pass(mode);
if (mode == 0) { y0 = y; t0s = t; }
const bool same = std::memcmp(y0.data(), y.data(), y.size() * 4) == 0;
std::printf("expert gate/up %d down %d nt %d threads %d: %d experts, %.2f GB | mode %s %.3f s = %.1f GB/s (x%.2f) %s\n", tg, td, nt,
threads, ne, gb, mode == 0 ? "ggml " : mode == 2 ? "auto " : "own ", t, gb / t, t0s / t, same ? "bit-identical" : "DIFFERENT");
if (!same) rc = 1;
}
return rc;
}
int main(int argc, char** argv) {
int type = 18, threads = 32, nt = 1, reps = 3;
long mb = 3072;
bool exact = false, expert = false;
int dtype = -1;
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
auto val = [&] { return i + 1 < argc ? std::atol(argv[++i]) : 0L; };
if (a == "--type") type = (int) val();
else if (a == "--threads") threads = (int) val();
else if (a == "--mb") mb = val();
else if (a == "--nt") nt = (int) val();
else if (a == "--reps") reps = (int) val();
else if (a == "--exact") exact = true;
else if (a == "--expert") expert = true;
else if (a == "--dtype") dtype = (int) val();
}
if (expert) return run_expert(type, dtype < 0 ? type : dtype, threads, mb, nt, reps);
ggml_cpu_init();
const int n = 5120; // a gate / up row
IqCpu f;
std::string err;
if (!gg_cpu_fmt(type, type, n, 2304, f, err)) {
std::fprintf(stderr, "gg_cpu_fmt: %s\n", err.c_str());
return 2;
}
const size_t rb = f.gu_row;
const long rows = (long) ((size_t) mb * 1000000 / rb) / 8 * 8;
std::vector<uint8_t> w((size_t) rows * rb);
uint64_t st = 0x9E3779B97F4A7C15ull;
auto next = [&st] { st ^= st << 13; st ^= st >> 7; st ^= st << 17; return st; };
for (size_t o = 0; o + 8 <= w.size(); o += 8) { const uint64_t v = next(); std::memcpy(&w[o], &v, 8); }
const size_t bb = ggml_type_size((ggml_type) type);
for (size_t o = 0; o + bb <= w.size(); o += bb) { // the blocks' F16 scale: a small normal value
const ggml_fp16_t d = ggml_fp32_to_fp16(0.002f + 0.001f * (float) (next() % 16));
if (type == 29) { // IQ1_M: no d field - its f16 is spread over the top nibbles of the four scale words (bytes 48..55)
uint16_t sc[4];
std::memcpy(sc, &w[o + 48], 8);
for (int k = 0; k < 4; ++k) sc[k] = (uint16_t) ((sc[k] & 0x0fff) | ((d >> (4 * k)) & 0xf) << 12);
std::memcpy(&w[o + 48], sc, 8);
} else {
std::memcpy(&w[o], &d, sizeof d);
}
}
std::vector<std::vector<uint8_t>> a((size_t) nt, std::vector<uint8_t>(f.act_bytes));
std::vector<const void*> ap((size_t) nt);
for (int t = 0; t < nt; ++t) {
std::vector<float> x((size_t) n);
for (auto& v : x) v = ((float) (next() % 2001) - 1000.0f) * 1e-3f;
gg_cpu_quant(f.gu_act, x.data(), n, a[(size_t) t].data());
ap[(size_t) t] = a[(size_t) t].data();
}
std::vector<std::vector<float>> o0((size_t) nt, std::vector<float>((size_t) rows)), o1 = o0;
std::vector<float*> p0, p1;
for (int t = 0; t < nt; ++t) { p0.push_back(o0[(size_t) t].data()); p1.push_back(o1[(size_t) t].data()); }
// a pass over all rows on `threads` threads, mode 0 ggml-cpu, 1 Strata's rows; returns the best time of reps
auto pass = [&](int mode, float* const* out) {
gg_cpu_set_iq256(mode);
double best = 1e30;
for (int r = 0; r < reps + 1; ++r) {
const auto t0 = clk::now();
std::vector<std::thread> th;
std::atomic<long> cursor{0};
const long chunk = 64;
for (int k = 0; k < threads; ++k)
th.emplace_back([&] {
for (;;) {
const long r0 = cursor.fetch_add(chunk);
if (r0 >= rows) break;
// one "expert part" is 2304 rows; the engine hands a thread a few rows of it at a time
gg_cpu_down(f, w.data(), ap.data(), nt, out, (int) r0, (int) std::min(rows, r0 + chunk));
}
});
for (auto& t : th) t.join();
if (r > 0) best = std::min(best, secs(t0));
}
return best;
};
// gg_cpu_down uses f.td / d_row; here td == tg and the activation has n_embd values: f.d_row would be for n_ff.
// Use the gate rows through a second IqCpu whose down geometry is the gate's.
f.td = f.tg; f.d_row = f.gu_row; f.n_ff = n; f.d_act = f.gu_act; f.h_bytes = f.act_bytes;
const double t_gg = pass(0, p0.data());
const double t_own = pass(1, p1.data());
long bad = 0, differ = 0;
double worst = 0, worst_ref = 0, absmax = 0, absdiff = 0;
for (int t = 0; t < nt; ++t)
for (long r = 0; r < rows; ++r) {
const float x = o0[(size_t) t][(size_t) r], y = o1[(size_t) t][(size_t) r];
absmax = std::max(absmax, (double) std::fabs(x));
absdiff = std::max(absdiff, (double) std::fabs((double) x - y));
if (std::memcmp(&x, &y, 4) != 0) {
++differ;
const double rel = std::fabs((double) x - y) / (std::fabs((double) x) + 1e-3);
worst = std::max(worst, rel);
if (rel > 1e-5) ++bad;
}
}
// The pass criterion above divides by one value's magnitude, so a token whose dot cancels to near zero fails it while
// agreeing to a few ulps. The real bound is the L1 norm of the products (|x - ref| <= eps * sum|w x|): decode a
// sample of rows with ggml's own to_float and the activation as its Q8_K blocks hold it, and compare in double.
int sampled = 0;
{
const ggml_type_traits* tt = ggml_get_type_traits((ggml_type) type);
std::vector<float> wrow((size_t) n);
// the activations (Q8_K: float d, int8 qs[256], int16 bsums[16]) as the rows see them
std::vector<std::vector<float>> xv((size_t) nt, std::vector<float>((size_t) n));
for (int t = 0; t < nt; ++t)
for (int b = 0; b < n / 256; ++b) {
const uint8_t* p = (const uint8_t*) ap[(size_t) t] + (size_t) b * (f.act_bytes / (size_t) (n / 256));
float d;
std::memcpy(&d, p, 4);
const int8_t* q = (const int8_t*) (p + 4);
for (int j = 0; j < 256; ++j) xv[(size_t) t][(size_t) b * 256 + j] = d * (float) q[j];
}
const long step = std::max(1L, rows / 64);
for (long r = 0; r < rows && sampled < 64; r += step, ++sampled) {
if (tt == nullptr || tt->to_float == nullptr) break;
tt->to_float(w.data() + (size_t) r * rb, wrow.data(), n);
for (int t = 0; t < nt; ++t) {
double ref = 0, l1 = 0;
for (int j = 0; j < n; ++j) {
const double pr = (double) wrow[(size_t) j] * (double) xv[(size_t) t][(size_t) j];
ref += pr;
l1 += std::fabs(pr);
}
const double g = o0[(size_t) t][(size_t) r], o = o1[(size_t) t][(size_t) r];
worst_ref = std::max(worst_ref, std::fabs(g - ref) / (l1 + 1e-30));
worst_ref = std::max(worst_ref, std::fabs(o - ref) / (l1 + 1e-30));
}
}
}
// memory ceiling: a plain read of the same bytes on the same threads
double t_rd = 1e30;
for (int r = 0; r < reps + 1; ++r) {
const auto t0 = clk::now();
std::vector<std::thread> th;
std::vector<uint64_t> sink((size_t) threads);
for (int k = 0; k < threads; ++k)
th.emplace_back([&, k] {
const size_t lo = w.size() / (size_t) threads * (size_t) k, hi = k + 1 == threads ? w.size() : w.size() / (size_t) threads * (size_t) (k + 1);
uint64_t s = 0, v;
for (size_t o = lo; o + 8 <= hi; o += 8) { std::memcpy(&v, &w[o], 8); s += v; }
sink[(size_t) k] = s;
});
for (auto& t : th) t.join();
if (r > 0) t_rd = std::min(t_rd, secs(t0));
}
const double gb = (double) w.size() / 1e9;
std::printf("type %d nt %d threads %d: %.2f GB of weights (%ld rows)\n", type, nt, threads, gb, rows);
std::printf(" ggml-cpu rows %.3f s = %.1f GB/s | Strata AVX2 rows %.3f s = %.1f GB/s (x%.2f) | plain read %.1f GB/s\n", t_gg, gb / t_gg,
t_own, gb / t_own, t_gg / t_own, gb / t_rd);
std::printf(" results: %ld of %ld differ in bits, worst |x-y|/|x| %.2e, %ld beyond 1e-5\n", differ, (long) nt * rows, worst, bad);
std::printf(" vs a double reference on %d sampled rows: worst %.2e of the L1 norm (tol 1e-5); |x-y| max %.2e of |x| max %.2e\n",
sampled, worst_ref, absdiff, absmax);
if (worst_ref > 1e-5 || absdiff > 1e-6 * absmax + 1e-30 || (exact && differ != 0)) {
std::printf("FAIL\n");
return 1;
}
std::printf("OK\n");
return 0;
}
+559
View File
@@ -0,0 +1,559 @@
// Strata. The i-quant routed experts of the DeepSeek-V4.1 path (ds4_iq.cu on the device, ds4_iq_cpu.cpp on the CPU lane)
// against ggml's own decode of the same bytes plus a double reference: the token path (gate/up, down), the window path
// (grouped entries), the prompt sets (gate/up and down), and the CPU lane on the same experts. Random legal blocks: any
// bit pattern with a sane F16 scale is one. This is the H2 gate for a new type (IQ2_XS first): the kernel's integer sums
// must equal ggml's weights times the same activations.
// iq_expert_test [--type 16,17,18,21,22,23,29] [--bench] [--iq256 0|1]
#include "../../src/dsv41/ds4_gguf_cpu.hpp"
#include "../../src/dsv41/ds4_iq.cuh"
#include "strata/dsv41/hip_or_cuda.h" // HIP names on a HIP build, the CUDA runtime otherwise
#include "ggml.h" // ggml_get_type_traits(type)->to_float: ggml's decode of the same blocks
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
namespace iq = strata::ds4::gguf::iq;
namespace gg = strata::ds4::gguf;
#define CK(x) do { hipError_t e_ = (x); if (e_ != hipSuccess) { std::printf("HIP error %s at %d\n", hipGetErrorString(e_), __LINE__); std::exit(2); } } while (0)
template <typename T> static T* up(const std::vector<T>& v) {
T* d; CK(hipMalloc(&d, std::max<size_t>(1, v.size() * sizeof(T)))); CK(hipMemcpy(d, v.data(), v.size() * sizeof(T), hipMemcpyHostToDevice)); return d;
}
template <typename T> static std::vector<T> down_(const T* d, size_t n) {
std::vector<T> v(n); CK(hipMemcpy(v.data(), d, n * sizeof(T), hipMemcpyDeviceToHost)); return v;
}
static float h2f(uint16_t h) {
const int s = h >> 15, e = (h >> 10) & 31, m = h & 1023;
float f = e == 0 ? std::ldexp((float) m, -24) : std::ldexp(1.0f + m / 1024.0f, e - 15);
return s ? -f : f;
}
static uint16_t f2h(float f) { // round to nearest even, normal range
uint32_t u; std::memcpy(&u, &f, 4);
const uint32_t s = (u >> 16) & 0x8000u; int e = (int) ((u >> 23) & 0xff) - 127 + 15; uint32_t m = u & 0x7fffffu;
uint32_t hm = m >> 13; const uint32_t rem = m & 0x1fffu;
uint32_t v = ((uint32_t) e << 10) | hm;
if (rem > 0x1000u || (rem == 0x1000u && (v & 1))) ++v;
return (uint16_t) (s | v);
}
struct Q8 { std::vector<int8_t> q; std::vector<float> d; std::vector<float> xhat; };
// the engine's q8_quant: sc = max|x| / 127 per 32, q = round-half-even(x / sc)
static Q8 quant(const float* x, int k) {
Q8 r; r.q.resize(k); r.d.resize(k / 32); r.xhat.resize(k);
for (int b = 0; b < k / 32; ++b) {
float am = 0; for (int j = 0; j < 32; ++j) am = std::max(am, std::fabs(x[b * 32 + j]));
const float sc = am / 127.0f; r.d[b] = sc;
for (int j = 0; j < 32; ++j) { const int q = am > 0 ? (int) std::nearbyint(x[b * 32 + j] / sc) : 0; r.q[b * 32 + j] = (int8_t) q; r.xhat[b * 32 + j] = (float) q * sc; }
}
return r;
}
static double swiglu(double g, double u, double lim) {
if (lim > 0) { g = std::min(g, lim); u = std::min(std::max(u, -lim), lim); }
return g / (1.0 + std::exp(-g)) * u;
}
static double dotd(const float* w, const float* x, int k, double* sabs = nullptr) {
double s = 0, sa = 0; for (int i = 0; i < k; ++i) { const double t = (double) w[i] * x[i]; s += t; sa += std::fabs(t); } if (sabs) *sabs = sa; return s;
}
// an activation buffer of a ggml type (Q8_K for the i-quant rows) decoded by ggml itself
static std::vector<float> act_values(int type, const void* act, int k) {
std::vector<float> v((size_t) k);
if (type == 15) { // Q8_K: float d, int8 qs[256], int16 bsums[16] - no to_float (an intermediate type)
const int nb = k / 256;
const size_t bs = ggml_row_size((ggml_type) type, k) / (size_t) nb;
for (int b = 0; b < nb; ++b) {
const uint8_t* p = (const uint8_t*) act + (size_t) b * bs;
float d; std::memcpy(&d, p, 4);
const int8_t* qs = (const int8_t*) (p + 4);
for (int j = 0; j < 256; ++j) v[(size_t) b * 256 + j] = d * (float) qs[j];
}
return v;
}
const ggml_type_traits* t = ggml_get_type_traits((ggml_type) type);
if (t == nullptr || t->to_float == nullptr) { std::printf("no to_float for activation type %d\n", type); std::exit(2); }
t->to_float(act, v.data(), k);
return v;
}
struct Mat { std::vector<uint8_t> bytes; std::vector<float> w; int rows = 0, k = 0; };
// random legal blocks of `type` for a rows x k matrix, decoded by ggml itself
static Mat make_mat(std::mt19937_64& rng, int type, int rows, int k) {
Mat m; m.rows = rows; m.k = k;
const int bv = iq::block_values(type), bb = iq::block_bytes(type);
const size_t nblk = (size_t) rows * (k / bv);
m.bytes.resize(nblk * (size_t) bb);
for (auto& b : m.bytes) b = (uint8_t) rng();
for (size_t b = 0; b < nblk; ++b) { // a sane F16 scale: at offset 0 (every type here but IQ1_M has d there)
const uint16_t d = f2h(0.02f + 0.0002f * (float) (rng() % 600));
uint8_t* p = &m.bytes[b * (size_t) bb];
if (type == 29) { // block_iq1_m has no d field: its F16 scale is the top nibbles of its four u16 scales
p[49] = (uint8_t) ((p[49] & 0x0f) | ((d & 0x000f) << 4));
p[51] = (uint8_t) ((p[51] & 0x0f) | (d & 0x00f0));
p[53] = (uint8_t) ((p[53] & 0x0f) | ((d & 0x0f00) >> 4));
p[55] = (uint8_t) ((p[55] & 0x0f) | ((d & 0xf000) >> 8));
} else {
std::memcpy(p, &d, 2);
}
}
m.w.resize((size_t) rows * k);
const ggml_type_traits* tr = ggml_get_type_traits((ggml_type) type);
if (tr == nullptr || tr->to_float == nullptr) { std::printf("ggml has no to_float for type %d\n", type); std::exit(2); }
const size_t rb = (size_t) (k / bv) * (size_t) bb;
for (int r = 0; r < rows; ++r) tr->to_float(&m.bytes[(size_t) r * rb], &m.w[(size_t) r * k], k);
return m;
}
// one decode token of the DeepSeek shape (n_embd 5120, n_ff 2304, top-6 experts): gate/up + down launches, per-layer time
static void bench(int type) {
const int E = 5120, FF = 2304, NE = 6;
const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
auto al = [](size_t n) { return (n + 255) / 256 * 256; };
const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
std::mt19937_64 rng(5);
std::vector<uint8_t> one(blob);
for (auto& b : one) b = (uint8_t) rng();
std::vector<unsigned long long> plan(NE);
for (int e = 0; e < NE; ++e) { uint8_t* d; CK(hipMalloc(&d, blob)); CK(hipMemcpy(d, one.data(), blob, hipMemcpyHostToDevice)); plan[e] = (unsigned long long) d; }
std::vector<int8_t> xq(E, 3), hq((size_t) NE * FF, 3); std::vector<float> xd(E / 32, 0.01f), hd((size_t) NE * FF / 32, 0.01f);
iq::Args a{};
a.plan_ptr = up(plan); a.n_embd = E; a.n_ff = FF; a.limit = 10.0f; a.xq = up(xq); a.xd = up(xd); a.hq = up(hq); a.hd = up(hd); a.tg = a.td = type;
for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
float *dh, *dp; CK(hipMalloc(&dh, (size_t) NE * FF * 4)); CK(hipMalloc(&dp, (size_t) NE * E * 4)); a.h = dh; a.part = dp;
hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1);
for (int rep = 0; rep < 5; ++rep) { iq::gate_up(a, NE, 1, 0); iq::down(a, NE, 1, 0); }
CK(hipDeviceSynchronize());
float ms_gu = 0, ms_dn = 0;
for (int part = 0; part < 2; ++part) {
hipEventRecord(e0);
for (int rep = 0; rep < 100; ++rep) { if (part == 0) iq::gate_up(a, NE, 1, 0); else iq::down(a, NE, 1, 0); }
hipEventRecord(e1); hipEventSynchronize(e1);
float ms; hipEventElapsedTime(&ms, e0, e1);
(part == 0 ? ms_gu : ms_dn) = ms / 100;
}
const double bytes = (double) NE * blob;
std::printf("bench %-7s 6 experts x 40 layers: gate/up %.0f us, down %.0f us, layer %.0f us -> %.0f GB/s, %.2f Tw/s, 40 layers %.1f ms/token\n",
iq::name(type), ms_gu * 1e3, ms_dn * 1e3, (ms_gu + ms_dn) * 1e3,
bytes / ((ms_gu + ms_dn) * 1e-3) / 1e9,
(double) NE * 3 * FF * E / ((ms_gu + ms_dn) * 1e-3) / 1e12, 40.0 * (ms_gu + ms_dn));
}
// --dump F / --cmp F: every device output of a run as raw bits, to a file / against one (a kernel change that keeps the sums
// exact and the float order must leave all of them identical)
static FILE* g_dump = nullptr; static FILE* g_cmp = nullptr; static long g_cmp_bad = 0, g_cmp_n = 0;
static void bits(const char* what, int type, const void* p, size_t bytes) {
if (!g_dump && !g_cmp) return;
if (g_dump) { std::fwrite(p, 1, bytes, g_dump); return; }
std::vector<uint8_t> ref(bytes);
if (std::fread(ref.data(), 1, bytes, g_cmp) != bytes) { std::printf("cmp: golden file too short at %s %s\n", iq::name(type), what); ++g_cmp_bad; return; }
++g_cmp_n;
if (std::memcmp(ref.data(), p, bytes) != 0) {
size_t bad = 0, first = 0; for (size_t i = 0; i < bytes; ++i) if (ref[i] != ((const uint8_t*) p)[i]) { if (!bad) first = i; ++bad; }
std::printf("%-7s %-22s BITS DIFFER: %zu of %zu bytes (first at %zu)\n", iq::name(type), what, bad, bytes, first);
++g_cmp_bad;
}
}
// the real shapes (n_embd 5120, n_ff 2304): the plan path (6 groups of one entry) and the grouped path (windows of 3 and 2)
static void real_shape_bits(int type) {
std::mt19937_64 rng(1000 + type); // (its own stream: the main loop's random experts are the same with or without this)
const int E = 5120, FF = 2304, NG = 2, NEnt = 12;
const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
auto al = [](size_t n) { return (n + 255) / 256 * 256; };
const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
std::vector<uint8_t> hb((size_t) NG * blob);
for (auto& b : hb) b = (uint8_t) rng();
for (size_t b = 0; b < hb.size() / (size_t) iq::block_bytes(type); ++b) { // sane F16 scales (the same placement as make_mat)
const uint16_t d = f2h(0.02f + 0.0002f * (float) (rng() % 600));
uint8_t* p = &hb[b * (size_t) iq::block_bytes(type)];
if (type == 29) { p[49] = (uint8_t) ((p[49] & 0x0f) | ((d & 0x000f) << 4)); p[51] = (uint8_t) ((p[51] & 0x0f) | (d & 0x00f0)); p[53] = (uint8_t) ((p[53] & 0x0f) | ((d & 0x0f00) >> 4)); p[55] = (uint8_t) ((p[55] & 0x0f) | ((d & 0xf000) >> 8)); }
else std::memcpy(p, &d, 2);
}
uint8_t* dblob = up(hb);
std::vector<int8_t> xq(2 * E), hq((size_t) NEnt * FF); std::vector<float> xd(2 * E / 32), hd((size_t) NEnt * FF / 32);
for (auto& v : xq) v = (int8_t) ((int) (rng() % 255) - 127);
for (auto& v : hq) v = (int8_t) ((int) (rng() % 255) - 127);
for (auto& v : xd) v = 0.002f + 0.0001f * (float) (rng() % 100);
for (auto& v : hd) v = 0.002f + 0.0001f * (float) (rng() % 100);
iq::Args a{};
a.n_embd = E; a.n_ff = FF; a.limit = 10.0f; a.xq = up(xq); a.xd = up(xd); a.hq = up(hq); a.hd = up(hd); a.tg = a.td = type;
for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
float *dh, *dp; CK(hipMalloc(&dh, (size_t) NEnt * FF * 4)); CK(hipMalloc(&dp, (size_t) NEnt * E * 4)); a.h = dh; a.part = dp;
std::vector<unsigned long long> plan = {(unsigned long long) dblob, (unsigned long long) (dblob + blob), 0ull, (unsigned long long) dblob};
a.plan_ptr = up(plan);
CK(hipMemset(dh, 0, (size_t) NEnt * FF * 4)); CK(hipMemset(dp, 0, (size_t) NEnt * E * 4));
if (!iq::gate_up(a, 4, 1, 0) || !iq::down(a, 4, 1, 0)) { std::printf("real shape: refused\n"); return; }
CK(hipDeviceSynchronize());
{ auto h = down_(dh, (size_t) NEnt * FF); bits("real plan h", type, h.data(), h.size() * 4); auto p = down_(dp, (size_t) NEnt * E); bits("real plan part", type, p.data(), p.size() * 4); }
std::vector<unsigned long long> gp = {(unsigned long long) dblob, (unsigned long long) (dblob + blob)};
std::vector<int> gs = {0, 3, 5}, ge = {0, 1, 2, 3, 4}, ng = {NG};
a.plan_ptr = nullptr; a.grp_ptr = up(gp); a.grp_start = up(gs); a.grp_ent = up(ge); a.n_groups = up(ng);
CK(hipMemset(dh, 0, (size_t) NEnt * FF * 4)); CK(hipMemset(dp, 0, (size_t) NEnt * E * 4));
if (!iq::gate_up(a, NG, 3, 0) || !iq::down(a, NG, 3, 0)) { std::printf("real shape grouped: refused\n"); return; }
CK(hipDeviceSynchronize());
{ auto h = down_(dh, (size_t) NEnt * FF); bits("real grp h", type, h.data(), h.size() * 4); auto p = down_(dp, (size_t) NEnt * E); bits("real grp part", type, p.data(), p.size() * 4); }
// more windows: a bound of 7 groups with 3 live (dynamic count), 5/1/3 entries (ne_max 5: the 8-entry kernels), then 9 groups of
// one entry with 4 live; entries index the h/hq rows, their input row is entry >> 3
{
std::vector<unsigned long long> gp2 = {(unsigned long long) dblob, (unsigned long long) (dblob + blob), (unsigned long long) dblob, 0ull, 0ull, 0ull, 0ull, 0ull, 0ull};
std::vector<int> gs2 = {0, 5, 6, 9, 9, 9, 9, 9, 9, 9}, ge2 = {3, 1, 4, 0, 2, 7, 5, 6, 8, 11, 10, 9}, ng2 = {3};
a.grp_ptr = up(gp2); a.grp_start = up(gs2); a.grp_ent = up(ge2); a.n_groups = up(ng2);
CK(hipMemset(dh, 0, (size_t) NEnt * FF * 4)); CK(hipMemset(dp, 0, (size_t) NEnt * E * 4));
if (!iq::gate_up(a, 7, 5, 0) || !iq::down(a, 7, 5, 0)) { std::printf("real shape window 2: refused\n"); return; }
CK(hipDeviceSynchronize());
{ auto h = down_(dh, (size_t) NEnt * FF); bits("real win2 h", type, h.data(), h.size() * 4); auto p = down_(dp, (size_t) NEnt * E); bits("real win2 part", type, p.data(), p.size() * 4); }
std::vector<int> gs3 = {0, 1, 2, 3, 4, 4, 4, 4, 4, 4}, ng3 = {4};
std::vector<unsigned long long> gp3 = {(unsigned long long) (dblob + blob), (unsigned long long) dblob, (unsigned long long) (dblob + blob), (unsigned long long) dblob, 0ull, 0ull, 0ull, 0ull, 0ull};
a.grp_ptr = up(gp3); a.grp_start = up(gs3); a.n_groups = up(ng3);
CK(hipMemset(dh, 0, (size_t) NEnt * FF * 4)); CK(hipMemset(dp, 0, (size_t) NEnt * E * 4));
if (!iq::gate_up(a, 9, 1, 0) || !iq::down(a, 9, 1, 0)) { std::printf("real shape window 3: refused\n"); return; }
CK(hipDeviceSynchronize());
{ auto h = down_(dh, (size_t) NEnt * FF); bits("real win3 h", type, h.data(), h.size() * 4); auto p = down_(dp, (size_t) NEnt * E); bits("real win3 part", type, p.data(), p.size() * 4); }
}
CK(hipFree(dblob));
}
// the same DeepSeek decode token over a working set far past L2 (>= 640 MiB of distinct expert blobs, rotated launch by launch),
// so the rate is DRAM's, not L2's: gate/up and down timed apart; ne = entries a group (1: the decode token)
static void bench_big(int type, int mib) {
const int E = 5120, FF = 2304, NE = 6;
const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
auto al = [](size_t n) { return (n + 255) / 256 * 256; };
const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
const int L = std::max(2, (int) (((size_t) mib << 20) / (NE * blob)) + 1); // layers rotated
std::mt19937_64 rng(5);
std::vector<uint8_t> one(blob);
for (auto& b : one) b = (uint8_t) rng();
std::vector<unsigned long long> plan((size_t) L * NE);
for (auto& p : plan) { uint8_t* d; CK(hipMalloc(&d, blob)); CK(hipMemcpy(d, one.data(), blob, hipMemcpyHostToDevice)); p = (unsigned long long) d; }
const int NW = std::getenv("DS4_BENCH_WIN") ? std::max(1, std::min(16, std::atoi(std::getenv("DS4_BENCH_WIN")))) : 0; // window path: NW entries a group
const int NEN = std::max(1, NW) * NE; // entries
std::vector<int8_t> xq((size_t) 8 * E, 3), hq((size_t) NEN * FF, 3); std::vector<float> xd((size_t) 8 * E / 32, 0.01f), hd((size_t) NEN * FF / 32, 0.01f);
for (size_t i = 0; i < xq.size(); ++i) xq[i] = (int8_t) ((int) (rng() % 255) - 127);
for (size_t i = 0; i < hq.size(); ++i) hq[i] = (int8_t) ((int) (rng() % 255) - 127);
if (const char* e = std::getenv("DS4_BENCH_ACTIVE")) { const int na = std::atoi(e); for (int l = 0; l < L; ++l) for (int k = na; k < NE; ++k) plan[(size_t) l * NE + k] = 0; } // (empty plan entries)
unsigned long long* dplan = up(plan);
iq::Args a{};
a.n_embd = E; a.n_ff = FF; a.limit = 10.0f; a.xq = up(xq); a.xd = up(xd); a.hq = up(hq); a.hd = up(hd); a.tg = a.td = type;
for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
float *dh, *dp; CK(hipMalloc(&dh, (size_t) NEN * FF * 4)); CK(hipMalloc(&dp, (size_t) NEN * E * 4)); a.h = dh; a.part = dp;
std::vector<int> gstart(NE + 1), gent(NEN), ngrp(1, NE);
for (int g = 0; g <= NE; ++g) gstart[g] = g * std::max(1, NW);
for (int i = 0; i < NEN; ++i) gent[i] = i;
a.grp_start = up(gstart); a.grp_ent = up(gent); a.n_groups = up(ngrp);
hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1);
double us[2] = {0, 0};
for (int part = 0; part < 2; ++part) {
auto run = [&](int reps) {
hipEventRecord(e0);
for (int rep = 0; rep < reps; ++rep) {
if (NW) a.grp_ptr = dplan + (size_t) (rep % L) * NE; else a.plan_ptr = dplan + (size_t) (rep % L) * NE;
if (part == 0) iq::gate_up(a, NE, std::max(1, NW), 0); else iq::down(a, NE, std::max(1, NW), 0);
}
hipEventRecord(e1); hipEventSynchronize(e1);
float ms; hipEventElapsedTime(&ms, e0, e1);
return (double) ms;
};
double ms = 0; int reps = 2 * L;
while (ms < 300.0) { ms = run(reps); reps *= 2; } // warm-up: clocks ramp, ~300 ms
const int n = std::max(L, (int) (reps / 2 * 40.0 / ms)); // ~40 ms a window
double best = 1e30;
for (int w = 0; w < 7; ++w) best = std::min(best, run(n) * 1e3 / n); // the best of 7 windows (clocks/thermals wander)
us[part] = best;
}
const double bg = (double) NE * (off[2]) , bd = (double) NE * al((size_t) E * rb_d); // bytes read a launch
std::printf("big %-7s ws %4.0f MiB: gate/up %6.1f us (%5.0f GB/s) down %6.1f us (%5.0f GB/s) layer %6.1f us -> %5.0f GB/s, %.2f Tw/s\n",
iq::name(type), (double) L * NE * blob / 1048576.0, us[0], bg / us[0] * 1e-3, us[1], bd / us[1] * 1e-3, us[0] + us[1],
(bg + bd) / (us[0] + us[1]) * 1e-3, (double) NE * 3 * FF * E / ((us[0] + us[1]) * 1e-6) / 1e12);
for (auto p : plan) if (p) hipFree((void*) p);
}
// the light sets (experts of <= 16 rows: DSpark verify windows, short prompts): n_exp experts of `rows` rows each, gate/up and down
static void bench_light(int type, int nexp, int rows, bool tiles = false) {
const int E = 5120, FF = 2304;
const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
auto al = [](size_t n) { return (n + 255) / 256 * 256; };
const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
std::mt19937_64 rng(7);
std::vector<uint8_t> one(blob);
for (auto& b : one) b = (uint8_t) rng();
uint8_t* w; CK(hipMalloc(&w, blob * nexp));
for (int e = 0; e < nexp; ++e) CK(hipMemcpy(w + (size_t) e * blob, one.data(), blob, hipMemcpyHostToDevice));
const int NR = nexp * rows, T = 8;
if (tiles && rows <= 16) { std::printf("tiles: rows > 16 only\n"); return; }
std::vector<int> bounds(nexp + 1), idx(NR);
for (int e = 0; e <= nexp; ++e) bounds[e] = e * rows;
for (int i = 0; i < NR; ++i) idx[i] = i % T;
std::vector<float> x((size_t) T * E);
std::normal_distribution<float> nd(0.f, 1.f);
for (auto& v : x) v = nd(rng);
std::vector<uint16_t> h((size_t) NR * FF, 0x3c00);
iq::SetArgs q{};
q.wbase = w; q.stride = blob; for (int r = 0; r < 3; ++r) q.tr[r] = off[r];
q.bounds = up(bounds); q.row0 = 0; q.max_rows = rows; q.skip_le = 0; q.n_exp = nexp; q.n_embd = E; q.n_ff = FF; q.limit = 7.0f;
q.tg = q.td = type; q.xf = up(x); q.idx = up(idx); q.ldx = E;
uint16_t* dh; CK(hipMalloc(&dh, (size_t) NR * FF * 2)); q.h = dh; q.ldo = FF;
q.xh = up(h);
float* dy; CK(hipMalloc(&dy, (size_t) NR * E * 4));
hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1);
double us[2] = {0, 0};
for (int part = 0; part < 2; ++part) {
auto run = [&](int reps) {
hipEventRecord(e0);
for (int rep = 0; rep < reps; ++rep) {
if (part == 0) { q.h = dh; q.ldo = FF; if (tiles) iq::set_gate_up(q, 0); else iq::light_gate_up(q, 0); }
else { q.y = dy; q.ldo = E; q.ldx = FF; if (tiles) iq::set_down(q, 0); else iq::light_down(q, 0); }
}
hipEventRecord(e1); hipEventSynchronize(e1);
float ms; hipEventElapsedTime(&ms, e0, e1);
return (double) ms;
};
double ms = 0; int reps = 4;
while (ms < 200.0) { ms = run(reps); reps *= 2; }
const int n = std::max(2, (int) (reps / 2 * 40.0 / ms));
double best = 1e30;
for (int wnd = 0; wnd < 5; ++wnd) best = std::min(best, run(n) * 1e3 / n);
us[part] = best;
}
const double bytes = (double) nexp * (off[2] + al((size_t) E * rb_d));
std::printf("%s %-7s %3d experts x %2d rows: gate/up %7.1f us down %7.1f us -> %6.0f GB/s of weights, %.2f Tw/s, %.1f TMAC/s\n", tiles ? "tiles" : "light", iq::name(type), nexp, rows,
us[0], us[1], bytes / ((us[0] + us[1]) * 1e-6) / 1e9, (double) nexp * 3 * FF * E / ((us[0] + us[1]) * 1e-6) / 1e12, (double) NR * 3 * FF * E / ((us[0] + us[1]) * 1e-6) / 1e12);
hipFree(w);
}
int main(int argc, char** argv) {
std::vector<int> types = {16, 17, 22, 18, 21, 23, 29};
std::vector<int> devs;
for (int i = 1; i < argc; ++i) {
if (std::string(argv[i]) == "--bench-tiles") { // [types] [n_exp] [rows list]: the prompt sets' tensor-core tiles
std::vector<int> bt, rl = {32, 128};
int nexp = 48;
if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
else bt = types;
if (i + 1 < argc && argv[i + 1][0] != '-') nexp = std::atoi(argv[++i]);
if (i + 1 < argc && argv[i + 1][0] != '-') { rl.clear(); for (const char* p = argv[++i]; *p;) { rl.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
for (int t : bt) for (int r : rl) bench_light(t, nexp, r, true);
return 0;
} else if (std::string(argv[i]) == "--bench-light") { // [types] [n_exp] [rows list]
std::vector<int> bt, rl = {1, 2, 4};
int nexp = 24;
if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
else bt = types;
if (i + 1 < argc && argv[i + 1][0] != '-') nexp = std::atoi(argv[++i]);
if (i + 1 < argc && argv[i + 1][0] != '-') { rl.clear(); for (const char* p = argv[++i]; *p;) { rl.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
for (int t : bt) for (int r : rl) bench_light(t, nexp, r);
return 0;
} else if (std::string(argv[i]) == "--bench-big") { // [types] [MiB]
std::vector<int> bt; int mib = 640;
if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
else bt = types;
if (i + 1 < argc && argv[i + 1][0] != '-') mib = std::atoi(argv[++i]);
for (int t : bt) bench_big(t, mib);
return 0;
} else if (std::string(argv[i]) == "--bench") {
std::vector<int> bt;
if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
else bt = types;
for (int t : bt) bench(t);
return 0;
} else if (std::string(argv[i]) == "--devices" && i + 1 < argc) { // every check on each device in turn, in this process;
devs.clear(); for (const char* p = argv[++i]; *p;) { devs.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } // the later ones bit-compared to the first
} else if (std::string(argv[i]) == "--dump" && i + 1 < argc) {
g_dump = std::fopen(argv[++i], "wb"); if (!g_dump) { std::printf("cannot write %s\n", argv[i]); return 2; }
} else if (std::string(argv[i]) == "--cmp" && i + 1 < argc) {
g_cmp = std::fopen(argv[++i], "rb"); if (!g_cmp) { std::printf("cannot read %s\n", argv[i]); return 2; }
} else if (std::string(argv[i]) == "--type" && i + 1 < argc) {
types.clear(); for (const char* p = argv[++i]; *p;) { types.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; }
} else if (std::string(argv[i]) == "--iq256" && i + 1 < argc) {
gg::gg_cpu_set_iq256(std::atoi(argv[++i]));
}
}
int fails = 0;
if (devs.size() > 1) { // the first device writes its outputs, the others compare to them
if (g_dump || g_cmp) { std::printf("--devices takes neither --dump nor --cmp\n"); return 2; }
}
for (size_t di = 0; di < std::max<size_t>(1, devs.size()); ++di) {
if (!devs.empty()) {
CK(hipSetDevice(devs[di]));
if (devs.size() > 1) {
if (g_dump) { std::fclose(g_dump); g_dump = nullptr; }
if (di == 0) g_dump = std::fopen("iq_devices.bin", "wb"); else { g_cmp = std::fopen("iq_devices.bin", "rb"); g_cmp_n = g_cmp_bad = 0; }
}
std::printf("---- device %d\n", devs[di]);
}
std::mt19937_64 rng(11);
std::normal_distribution<float> nd(0.f, 1.f);
auto report = [&](const char* what, int type, double worst, double tol) {
const bool ok = worst <= tol;
std::printf("%-7s %-22s worst %.2e (tol %.0e) %s\n", iq::name(type), what, worst, tol, ok ? "ok" : "FAIL");
fails += !ok;
};
for (int type : types) {
if (!iq::supported(type) && !iq::known(type)) { std::printf("%-7s not a type this engine knows\n", iq::name(type)); ++fails; continue; }
const bool dev = iq::supported(type); // (IQ1_S / IQ1_M / IQ4_NL: a known layout, no device kernel - CPU lane only)
const int E = 512, FF = 256, NEXP = 3, T = 4;
const float lim = 7.0f;
const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
auto al = [](size_t n) { return (n + 255) / 256 * 256; };
const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
std::vector<Mat> G(NEXP), U(NEXP), D(NEXP);
auto refh = [&](int e, int r, const float* xv, double& scale) {
double sg, su;
const double g = dotd(&G[e].w[(size_t) r * E], xv, E, &sg), u = dotd(&U[e].w[(size_t) r * E], xv, E, &su);
scale = sg + su + 1e-30;
return swiglu(g, u, lim);
};
std::vector<uint8_t> blobs((size_t) NEXP * blob, 0);
for (int e = 0; e < NEXP; ++e) {
G[e] = make_mat(rng, type, FF, E); U[e] = make_mat(rng, type, FF, E); D[e] = make_mat(rng, type, E, FF);
std::memcpy(&blobs[e * blob + off[0]], G[e].bytes.data(), G[e].bytes.size());
std::memcpy(&blobs[e * blob + off[1]], U[e].bytes.data(), U[e].bytes.size());
std::memcpy(&blobs[e * blob + off[2]], D[e].bytes.data(), D[e].bytes.size());
}
uint8_t* dblob = up(blobs);
std::vector<float> x((size_t) T * E);
for (auto& v : x) v = nd(rng) * (1.0f + 3.0f * (rng() % 7 == 0));
std::vector<Q8> qx(T);
std::vector<int8_t> xq((size_t) T * E); std::vector<float> xd((size_t) T * E / 32);
for (int t = 0; t < T; ++t) { qx[t] = quant(&x[(size_t) t * E], E); std::memcpy(&xq[(size_t) t * E], qx[t].q.data(), E); std::memcpy(&xd[(size_t) t * E / 32], qx[t].d.data(), E / 32 * 4); }
const int8_t* dxq = up(xq); const float* dxd = up(xd);
// ---- the reference h of every expert's rows for token 0 (the CPU lane and the device share it)
std::vector<float> href((size_t) NEXP * FF);
std::vector<Q8> qh(NEXP);
for (int e = 0; e < NEXP; ++e)
for (int r = 0; r < FF; ++r) {
double sc;
href[(size_t) e * FF + r] = (float) refh(e, r, qx[0].xhat.data(), sc);
}
for (int e = 0; e < NEXP; ++e) qh[e] = quant(&href[(size_t) e * FF], FF);
// ---- token path (device; skipped for a type with no device kernel)
if (dev) {
std::vector<unsigned long long> plan(NEXP);
for (int e = 0; e < NEXP; ++e) plan[e] = (unsigned long long) (dblob + e * blob);
iq::Args a{};
a.plan_ptr = up(plan); a.n_embd = E; a.n_ff = FF; a.limit = lim; a.xq = dxq; a.xd = dxd; a.tg = a.td = type;
for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
float* dh; CK(hipMalloc(&dh, (size_t) NEXP * FF * 4)); a.h = dh;
if (!iq::gate_up(a, NEXP, 1, 0)) { std::printf("gate_up refused\n"); return 1; }
CK(hipDeviceSynchronize());
const auto h = down_(dh, (size_t) NEXP * FF);
bits("token h", type, h.data(), h.size() * 4);
double worst = 0;
for (int e = 0; e < NEXP; ++e)
for (int r = 0; r < FF; ++r) {
double sc;
const double ref = refh(e, r, qx[0].xhat.data(), sc);
worst = std::max(worst, std::fabs(h[(size_t) e * FF + r] - ref) / sc);
}
report("token gate_up", type, worst, 1e-5);
std::vector<int8_t> hq((size_t) NEXP * FF); std::vector<float> hd((size_t) NEXP * FF / 32);
for (int e = 0; e < NEXP; ++e) { std::memcpy(&hq[(size_t) e * FF], qh[e].q.data(), FF); std::memcpy(&hd[(size_t) e * FF / 32], qh[e].d.data(), FF / 32 * 4); }
a.hq = up(hq); a.hd = up(hd);
float* dp; CK(hipMalloc(&dp, (size_t) NEXP * E * 4)); a.part = dp;
if (!iq::down(a, NEXP, 1, 0)) { std::printf("down refused\n"); return 1; }
CK(hipDeviceSynchronize());
const auto part = down_(dp, (size_t) NEXP * E);
bits("token part", type, part.data(), part.size() * 4);
worst = 0;
for (int e = 0; e < NEXP; ++e)
for (int r = 0; r < E; ++r) {
double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], qh[e].xhat.data(), FF, &sa);
worst = std::max(worst, std::fabs(part[(size_t) e * E + r] - ref) / (sa + 1e-30));
}
report("token down", type, worst, 1e-6);
// ---- the prompt sets: expert 0 owns rows [0, 37), expert 2 [37, 42)
const int NR = 42;
std::vector<int> bounds = {0, 37, 37, 42}, idx(NR);
for (int i = 0; i < NR; ++i) idx[i] = i % T;
iq::SetArgs q{};
q.wbase = dblob; q.stride = blob; for (int r = 0; r < 3; ++r) q.tr[r] = off[r];
q.bounds = up(bounds); q.row0 = 0; q.max_rows = 37; q.n_exp = 3; q.n_embd = E; q.n_ff = FF; q.limit = lim;
q.tg = q.td = type; q.xf = up(x); q.idx = up(idx); q.ldx = E;
uint16_t* dh16; CK(hipMalloc(&dh16, (size_t) NR * FF * 2)); q.h = dh16; q.ldo = FF;
if (!iq::set_gate_up(q, 0)) { std::printf("set_gate_up refused\n"); return 1; }
CK(hipDeviceSynchronize());
const auto h16 = down_(dh16, (size_t) NR * FF);
bits("set h16", type, h16.data(), h16.size() * 2);
double w2 = 0;
for (int e = 0; e < 3; ++e)
for (int lr = bounds[e]; lr < bounds[e + 1]; ++lr)
for (int r = 0; r < FF; ++r) {
double sc;
const double ref = refh(e, r, &x[(size_t) idx[lr] * E], sc);
w2 = std::max(w2, std::fabs((double) h2f(h16[(size_t) lr * FF + r]) - ref) / sc);
}
// (the prompt sets quantise the activations, so this worst case is data dependent: IQ1_S measured 7.1e-3 .. 1.08e-2 over
// different random-data orders, the same on the older build, with every other check far inside; IQ1_S gets 1.5e-2)
report("set gate_up (f16)", type, w2, type == 19 ? 1.5e-2 : 1e-2);
q.xh = dh16; q.ldx = FF;
float* dy; CK(hipMalloc(&dy, (size_t) NR * E * 4)); q.y = dy; q.ldo = E;
if (!iq::set_down(q, 0)) { std::printf("set_down refused\n"); return 1; }
CK(hipDeviceSynchronize());
const auto y = down_(dy, (size_t) NR * E);
bits("set y", type, y.data(), y.size() * 4);
real_shape_bits(type);
w2 = 0;
for (int e = 0; e < 3; ++e)
for (int lr = bounds[e]; lr < bounds[e + 1]; ++lr) {
std::vector<float> hf(FF);
for (int c = 0; c < FF; ++c) hf[c] = h2f(h16[(size_t) lr * FF + c]);
for (int r = 0; r < E; ++r) {
double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], hf.data(), FF, &sa);
w2 = std::max(w2, std::fabs(y[(size_t) lr * E + r] - ref) / (sa + 1e-30));
}
}
// (the prompt sets' tiles take F16 operands for the i-quants: the tile's own rounding, not the token path's)
report("set down", type, w2, 3e-3);
}
// ---- the CPU lane on the same experts and inputs (ggml-cpu's rows, or Strata's AVX2 ones with DS4_GG_IQ256=1)
{
gg::IqCpu fm; std::string err;
if (!gg::iq_cpu_fmt(type, type, E, FF, fm, err)) { std::printf("%-7s cpu lane: %s\n", iq::name(type), err.c_str()); ++fails; }
else {
std::vector<uint8_t> act(fm.act_bytes), hact(fm.h_bytes);
gg::iq_cpu_quant(fm.gu_act, x.data(), E, act.data());
// (the CPU lane rounds the activation to its own type - Q8_K, one F32 scale per 256 values - so the
// reference is that quantized activation, not the device's per-32 one)
const std::vector<float> xhat = act_values(fm.gu_act, act.data(), E);
double wg = 0, wd = 0;
for (int e = 0; e < NEXP; ++e) {
std::vector<float> hc(FF), yc(E);
float* hp[1] = {hc.data()}; float* yp[1] = {yc.data()};
const void* ap[1] = {act.data()};
gg::iq_cpu_gate_up(fm, &blobs[e * blob + off[0]], &blobs[e * blob + off[1]], ap, 1, hp, 0, FF, lim);
for (int r = 0; r < FF; ++r) {
double sg, su;
const double g = dotd(&G[e].w[(size_t) r * E], xhat.data(), E, &sg);
const double u = dotd(&U[e].w[(size_t) r * E], xhat.data(), E, &su);
wg = std::max(wg, std::fabs(hc[r] - swiglu(g, u, lim)) / (sg + su + 1e-30));
}
gg::iq_cpu_quant(fm.d_act, &href[(size_t) e * FF], FF, hact.data());
const std::vector<float> hhat = act_values(fm.d_act, hact.data(), FF);
const void* hpp[1] = {hact.data()};
gg::iq_cpu_down(fm, &blobs[e * blob + off[2]], hpp, 1, yp, 0, E);
for (int r = 0; r < E; ++r) { double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], hhat.data(), FF, &sa); wd = std::max(wd, std::fabs(yc[r] - ref) / (sa + 1e-30)); }
}
report("cpu gate_up vs ref", type, wg, 1e-5);
report("cpu down vs ref", type, wd, 1e-5);
std::printf("%-7s cpu rows: %s\n", iq::name(type), gg::iq_cpu_own_rows(type) ? "Strata AVX2" : "ggml-cpu");
}
}
CK(hipFree(dblob));
}
if (g_cmp && devs.size() > 1) { std::fclose(g_cmp); g_cmp = nullptr; std::printf("device %d vs device %d: %ld buffers, %ld differ\n", devs[di], devs[0], g_cmp_n, g_cmp_bad); fails += g_cmp_bad != 0; }
}
if (g_cmp) { std::printf("bit-compare vs golden: %ld buffers, %ld differ -> %s\n", g_cmp_n, g_cmp_bad, g_cmp_bad ? "DIFFERENT" : "IDENTICAL"); fails += g_cmp_bad != 0; }
if (g_dump) std::fclose(g_dump);
std::printf("%s\n", fails ? "FAILED" : "ALL OK");
return fails;
}
+153
View File
@@ -0,0 +1,153 @@
// The kept conversations' bookkeeping without a GPU (src/dsv41/ds4_slotmeta.hpp): the .meta file's round trip and
// every way it is refused, and which kept conversation a prompt continues, and from where.
// ds4_slot_test exit 0: all passed
#include "ds4_slotmeta.hpp"
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <string>
#include <vector>
namespace sm = strata::ds4::slotmeta;
namespace fs = std::filesystem;
static int fails = 0;
#define CHECK(c) \
do { \
if (!(c)) { \
std::printf("FAIL line %d: %s\n", __LINE__, #c); \
++fails; \
} \
} while (0)
static std::vector<int32_t> seq(int a, int n) {
std::vector<int32_t> v((size_t) n);
for (int i = 0; i < n; ++i) v[(size_t) i] = a + i;
return v;
}
static std::vector<int> as_int(const std::vector<int32_t>& v) { return std::vector<int>(v.begin(), v.end()); }
static void patch(const std::string& p, size_t off, uint8_t b) {
std::FILE* f = std::fopen(p.c_str(), "r+b");
std::fseek(f, (long) off, SEEK_SET);
std::fwrite(&b, 1, 1, f);
std::fclose(f);
}
static void meta_tests(const fs::path& dir) {
const std::string id = "strata-ds4-session-2 engine=test", path = (dir / "slot-1.meta").string();
const std::vector<int32_t> toks = seq(100, 50);
const std::vector<int64_t> cks = {40, 33, 7};
CHECK(sm::write(path, id, toks, 123456789ull, cks));
CHECK(!fs::exists(path + ".tmp")); // (renamed over, no half file left)
std::vector<int32_t> t;
std::vector<int64_t> c;
uint64_t bytes = 0;
CHECK(sm::read(path, id, 1000, t, bytes, c));
CHECK(t == toks && c == cks && bytes == 123456789ull);
// no checkpoints is valid (a slot of a state that had none)
CHECK(sm::write(path, id, toks, 5, {}));
CHECK(sm::read(path, id, 1000, t, bytes, c) && c.empty() && bytes == 5);
// another model's / engine's identity: refused, never read
CHECK(!sm::read(path, id + "x", 1000, t, bytes, c));
CHECK(!sm::read(path, "other", 1000, t, bytes, c));
// more tokens than the context: refused
CHECK(!sm::read(path, id, 49, t, bytes, c));
CHECK(sm::read(path, id, 50, t, bytes, c));
// a missing file
CHECK(!sm::read((dir / "none.meta").string(), id, 1000, t, bytes, c));
// every cut length, a damaged magic at either end
CHECK(sm::write(path, id, toks, 9, cks));
const size_t full = (size_t) fs::file_size(path);
for (size_t keep = 0; keep < full; ++keep) {
fs::copy_file(path, dir / "cut.meta", fs::copy_options::overwrite_existing);
fs::resize_file(dir / "cut.meta", keep);
if (sm::read((dir / "cut.meta").string(), id, 1000, t, bytes, c)) {
std::printf("FAIL: a .meta cut to %zu of %zu bytes was read\n", keep, full);
++fails;
break;
}
}
fs::copy_file(path, dir / "bad0.meta", fs::copy_options::overwrite_existing);
patch((dir / "bad0.meta").string(), 0, 0x55);
CHECK(!sm::read((dir / "bad0.meta").string(), id, 1000, t, bytes, c));
fs::copy_file(path, dir / "bad1.meta", fs::copy_options::overwrite_existing);
patch((dir / "bad1.meta").string(), full - 1, 0x55);
CHECK(!sm::read((dir / "bad1.meta").string(), id, 1000, t, bytes, c));
// a checkpoint outside the conversation, a zero one, more than four
CHECK(sm::write(path, id, toks, 9, {51}));
CHECK(!sm::read(path, id, 1000, t, bytes, c));
CHECK(sm::write(path, id, toks, 9, {0}));
CHECK(!sm::read(path, id, 1000, t, bytes, c));
CHECK(sm::write(path, id, toks, 9, {4, 3, 2, 1}));
CHECK(sm::read(path, id, 1000, t, bytes, c) && c.size() == 4);
CHECK(sm::write(path, id, toks, 9, {1, 2, 3, 4, 5}));
CHECK(!sm::read(path, id, 1000, t, bytes, c));
// no tokens at all
CHECK(sm::write(path, id, {}, 9, {}));
CHECK(!sm::read(path, id, 1000, t, bytes, c));
// an unwritable place: false, not a crash
CHECK(!sm::write((dir / "nodir" / "x.meta").string(), id, toks, 1, {}));
}
static size_t pick(const std::vector<std::vector<int32_t>>& toks, const std::vector<std::vector<int64_t>>& cks,
const std::vector<int>& prompt, size_t floor, size_t* len) {
std::vector<sm::Cand> c;
for (size_t i = 0; i < toks.size(); ++i) c.push_back({&toks[i], &cks[i]});
return sm::pick(c, prompt, floor, len);
}
static void pick_tests() {
size_t len = 99;
const std::vector<int32_t> a = seq(1000, 3000), b = seq(5000, 2000);
// the next turn of A: A whole, then new tokens
std::vector<int32_t> a_turn = a;
for (int32_t x : seq(9000, 40)) a_turn.push_back(x);
CHECK(pick({a, b}, {{}, {}}, as_int(a_turn), 0, &len) == 0 && len == a.size());
CHECK(pick({b, a}, {{}, {}}, as_int(a_turn), 0, &len) == 1 && len == a.size());
// nothing shared: none, len 0
CHECK(pick({a, b}, {{}, {}}, as_int(seq(7777, 100)), 0, &len) == SIZE_MAX && len == 0);
// a prompt equal to the slot's tokens: the last token is still read, so the slot is not taken whole
CHECK(pick({a}, {{}}, as_int(a), 0, &len) == SIZE_MAX && len == 0);
CHECK(pick({a}, {{2900}}, as_int(a), 0, &len) == 0 && len == 2900);
// a shorter prompt than the slot (a prefix of it): taken at a checkpoint within it, never past it
std::vector<int32_t> head(a.begin(), a.begin() + 2000);
CHECK(pick({a}, {{2900, 1500}}, as_int(head), 0, &len) == 0 && len == 1500);
// a retried prompt: A's prompt end (2950) is a checkpoint; the new prompt agrees up to 2960 then differs
std::vector<int32_t> retry(a.begin(), a.begin() + 2960);
for (int32_t x : seq(8000, 30)) retry.push_back(x);
CHECK(pick({a}, {{2950, 2000, 1000}}, as_int(retry), 0, &len) == 0 && len == 2950);
// diverging before the latest checkpoint: the latest one it still agrees with (the anchor)
std::vector<int32_t> early(a.begin(), a.begin() + 1200);
for (int32_t x : seq(8000, 30)) early.push_back(x);
CHECK(pick({a}, {{2950, 2000, 1000}}, as_int(early), 0, &len) == 0 && len == 1000);
// diverging before every checkpoint: none
std::vector<int32_t> first(a.begin(), a.begin() + 500);
for (int32_t x : seq(8000, 30)) first.push_back(x);
CHECK(pick({a}, {{2950, 2000, 1000}}, as_int(first), 0, &len) == SIZE_MAX && len == 0);
// the floor: what the model itself can go back to wins unless the slot goes further
CHECK(pick({a}, {{}}, as_int(a_turn), 3000, &len) == SIZE_MAX && len == 0);
CHECK(pick({a}, {{}}, as_int(a_turn), 2999, &len) == 0 && len == 3000);
// two slots, the longer match wins; a tie keeps the earlier one
std::vector<int32_t> a_short(a.begin(), a.begin() + 1000);
CHECK(pick({a_short, a}, {{}, {}}, as_int(a_turn), 0, &len) == 1 && len == 3000);
CHECK(pick({a, a}, {{}, {}}, as_int(a_turn), 0, &len) == 0 && len == 3000);
// too short a prompt
CHECK(pick({a}, {{}}, {1000}, 0, &len) == SIZE_MAX && len == 0);
CHECK(pick({a}, {{}}, {}, 0, &len) == SIZE_MAX && len == 0);
// an empty slot list
CHECK(pick({}, {}, as_int(a_turn), 0, &len) == SIZE_MAX && len == 0);
}
int main() {
const fs::path dir = fs::temp_directory_path() / "ds4-slot-test";
std::error_code ec;
fs::remove_all(dir, ec);
fs::create_directories(dir);
meta_tests(dir);
pick_tests();
fs::remove_all(dir, ec);
std::printf(fails ? "FAILED: %d\n" : "slot_test: all passed\n", fails);
return fails ? 1 : 0;
}
+112
View File
@@ -0,0 +1,112 @@
// Strata. ExpertStore (src/dsv41/ds4_store.hpp) on real expert files, no device: the bytes a slot holds equal the file's, the
// unbuffered reads' rate, the policy's hits on a skewed random access stream.
// ds4_store_test <gguf> <layer0 gate off> <layer0 up off> <layer0 down off> <expert bytes (gate/up/down)> [budget GB] [policy 0|1|2] [accesses]
// (offsets from the GGUF's tensor directory: tools/dsv41 header scan; the three tensors of a layer are [384][...] so expert e of
// a matrix lies at off + e * bytes)
#include "ds4_store.hpp"
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <thread>
using namespace strata::ds4;
int main(int argc, char** argv) {
if (argc < 6) {
std::printf("usage: ds4_store_test <gguf> <gate off> <up off> <down off> <matrix bytes> [budget GB] [policy] [accesses]\n");
return 2;
}
const std::string path = argv[1];
const uint64_t offs[3] = {std::strtoull(argv[2], nullptr, 10), std::strtoull(argv[3], nullptr, 10), std::strtoull(argv[4], nullptr, 10)};
const uint64_t mb = std::strtoull(argv[5], nullptr, 10);
const double gb = argc > 6 ? std::atof(argv[6]) : 1.0;
const int policy = argc > 7 ? std::atoi(argv[7]) : 0;
const int n_acc = argc > 8 ? std::atoi(argv[8]) : 2000;
const os::fd_t fd = os::open_ro(path), dfd = os::open_direct(path), pfd = os::open_par(path);
if (fd == os::kBadFd || pfd == os::kBadFd) {
std::printf("cannot open %s\n", path.c_str());
return 2;
}
std::printf("direct handle: %s\n", dfd != os::kBadFd ? "yes" : "NO (buffered)");
ExpertStore::LayerGeo geo;
geo.n_exp = 384;
uint64_t at = 0;
for (int r = 0; r < 3; ++r) {
geo.file[r] = 0;
geo.off[r] = offs[r];
geo.stride[r] = mb;
geo.bytes[r] = mb;
geo.tr[r] = at; // the engine's blob layout with the store's 8192-byte gaps
at += ((mb + 255) & ~(uint64_t) 255) + ExpertStore::kSlack;
}
geo.blob = at;
ExpertStore st;
ExpertStore::Cfg cfg;
cfg.budget_bytes = (size_t) (gb * 1e9);
cfg.threads = std::getenv("STORE_TEST_THREADS") ? std::atoi(std::getenv("STORE_TEST_THREADS")) : 8;
cfg.policy = (ExpertStore::Policy) policy;
cfg.floor_bytes = 4ull << 30;
cfg.ram_avail = [] { return os::ram_avail(); };
if (!st.init(cfg, {geo}, {dfd}, {pfd})) {
std::printf("init failed\n");
return 2;
}
std::printf("slot %.2f MB, up to %zu slots\n", st.slot_bytes() / 1e6, st.slots_max());
// a skewed stream: 70% of the accesses from the 64 hottest experts, the rest uniform; 6 a "token"
std::mt19937_64 rng(7);
auto pick = [&] { return rng() % 100 < 70 ? (int) (rng() % 64) : (int) (rng() % 384); };
std::vector<uint8_t> ref(mb);
int bad = 0;
long checked = 0;
const auto t0 = std::chrono::steady_clock::now();
for (int a = 0; a < n_acc; ++a) {
int es[6];
for (int i = 0; i < 6; ++i) {
es[i] = pick();
for (int j = 0; j < i; ++j)
if (es[j] == es[i]) es[i] = (es[i] + 1 + j) % 384;
}
std::vector<char> ok;
st.ensure(0, es, 6, ok);
if (a % 17 == 0 && !std::getenv("STORE_TEST_NOCMP")) // a sample compared with the file read plainly
for (int i = 0; i < 6; ++i)
if (ok[(size_t) i])
for (int r = 0; r < 3; ++r) {
const int s = st.find(0, es[i]);
os::pread_full(fd, ref.data(), mb, offs[r] + (uint64_t) es[i] * mb);
++checked;
if (s < 0 || std::memcmp(st.mat(s, r), ref.data(), mb) != 0) ++bad;
}
st.release(0, es, 6, ok);
}
// guesses queued behind demand, cancelled, and a shrink: the store must still give the file's bytes
for (int round = 0; round < 3; ++round) {
for (int e = 100; e < 140; ++e) st.prefetch(0, e);
st.cancel_stale(0);
int es[6] = {5 + round, 17, 200, 201, 202, 250 + round};
std::vector<char> ok;
st.ensure(0, es, 6, ok);
for (int i = 0; i < 6; ++i)
if (ok[(size_t) i]) {
const int sl = st.find(0, es[i]);
for (int r = 0; r < 3; ++r) {
os::pread_full(fd, ref.data(), mb, offs[r] + (uint64_t) es[i] * mb);
++checked;
if (sl < 0 || std::memcmp(st.mat(sl, r), ref.data(), mb) != 0) ++bad;
}
}
st.release(0, es, 6, ok);
std::this_thread::sleep_for(std::chrono::milliseconds(800)); // (the guesses read by now)
const size_t g = st.shrink_chunks(1);
std::printf("round %d: shrank %zu chunk(s), %zu slots left, cancelled %lld\n", round, g, st.slots_allocated(), (long long) st.stats().cancelled.load());
}
const double dt = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
const auto& s = st.stats();
std::printf("%d accesses of 6 experts in %.2f s: hits %lld misses %lld evictions %lld fails %lld; read %.2f GB (%.2f GB/s); waited %.2f s; "
"compared %ld matrices, %d differ\n",
n_acc, dt, (long long) s.hits.load(), (long long) s.misses.load(), (long long) s.evictions.load(), (long long) s.fails.load(),
s.bytes_read.load() / 1e9, s.bytes_read.load() / 1e9 / dt, s.wait_ns.load() / 1e9, checked, bad);
return bad == 0 ? 0 : 1;
}
+288
View File
@@ -0,0 +1,288 @@
// Strata. The trellis routed experts of the DeepSeek-V4.1 path (ds4_tq.cu on the device, ds4_tq_cpu.cpp on the CPU lane) against
// a double reference on host-decoded weights (tools/trellis/tqenc: decode_blocks), for the six types (TQK6 / TQK7 / TQK5X /
// TQK4X / TQK5T / TQK4T): the token path, the window path (grouped entries), the prompt sets (gate/up and down) and the CPU
// lane, plus the two lanes against each other. Random legal streams: any bit pattern is one.
// tq_expert_test [--type 145,146,...]
#include "../../src/dsv41/ds4_gguf_cpu.hpp"
#include "../../src/dsv41/ds4_iq.cuh"
#include "../../tools/trellis/tqenc.hpp"
#include "strata/dsv41/hip_or_cuda.h" // HIP names on a HIP build, the CUDA runtime otherwise
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
namespace iq = strata::ds4::gguf::iq;
namespace gg = strata::ds4::gguf;
#define CK(x) do { hipError_t e_ = (x); if (e_ != hipSuccess) { std::printf("HIP error %s at %d\n", hipGetErrorString(e_), __LINE__); std::exit(2); } } while (0)
template <typename T> static T* up(const std::vector<T>& v) {
T* d; CK(hipMalloc(&d, std::max<size_t>(1, v.size() * sizeof(T)))); CK(hipMemcpy(d, v.data(), v.size() * sizeof(T), hipMemcpyHostToDevice)); return d;
}
template <typename T> static std::vector<T> down_(const T* d, size_t n) {
std::vector<T> v(n); CK(hipMemcpy(v.data(), d, n * sizeof(T), hipMemcpyDeviceToHost)); return v;
}
static float h2f(uint16_t h) {
const int s = h >> 15, e = (h >> 10) & 31, m = h & 1023;
float f = e == 0 ? std::ldexp((float) m, -24) : std::ldexp(1.0f + m / 1024.0f, e - 15);
return s ? -f : f;
}
static uint16_t f2h(float f) { // round to nearest even, normal range
uint32_t u; std::memcpy(&u, &f, 4);
const uint32_t s = (u >> 16) & 0x8000u; int e = (int) ((u >> 23) & 0xff) - 127 + 15; uint32_t m = u & 0x7fffffu;
uint32_t hm = m >> 13; const uint32_t rem = m & 0x1fffu;
uint32_t v = ((uint32_t) e << 10) | hm;
if (rem > 0x1000u || (rem == 0x1000u && (v & 1))) ++v;
return (uint16_t) (s | v);
}
struct Q8 { std::vector<int8_t> q; std::vector<float> d; std::vector<float> xhat; };
// the engine's q8_quant: sc = max|x| / 127 per 32, q = round-half-even(x / sc)
static Q8 quant(const float* x, int k) {
Q8 r; r.q.resize(k); r.d.resize(k / 32); r.xhat.resize(k);
for (int b = 0; b < k / 32; ++b) {
float am = 0; for (int j = 0; j < 32; ++j) am = std::max(am, std::fabs(x[b * 32 + j]));
const float sc = am / 127.0f; r.d[b] = sc;
for (int j = 0; j < 32; ++j) { const int q = am > 0 ? (int) std::nearbyint(x[b * 32 + j] / sc) : 0; r.q[b * 32 + j] = (int8_t) q; r.xhat[b * 32 + j] = (float) q * sc; }
}
return r;
}
static double swiglu(double g, double u, double lim) {
if (lim > 0) { g = std::min(g, lim); u = std::min(std::max(u, -lim), lim); }
return g / (1.0 + std::exp(-g)) * u;
}
struct Mat { std::vector<uint8_t> bytes; std::vector<float> w; int rows, k; };
static Mat make_mat(std::mt19937_64& rng, int type, int K, int rows, int k) {
Mat m; m.rows = rows; m.k = k;
const int bsz = 2 + 4 * K, nblk = k / 128;
m.bytes.resize((size_t) rows * nblk * bsz);
for (auto& b : m.bytes) b = (uint8_t) rng();
for (int64_t b = 0; b < (int64_t) rows * nblk; ++b) { const uint16_t d = f2h(0.05f + 0.0005f * (float) (rng() % 600)); std::memcpy(&m.bytes[(size_t) b * bsz], &d, 2); }
m.w.resize((size_t) rows * k);
tqenc::decode_blocks(type, m.bytes.data(), (int64_t) rows * nblk, m.w.data());
return m;
}
static double dotd(const float* w, const float* x, int k, double* sabs = nullptr) {
double s = 0, sa = 0; for (int i = 0; i < k; ++i) { const double t = (double) w[i] * x[i]; s += t; sa += std::fabs(t); } if (sabs) *sabs = sa; return s;
}
// one decode token of the DeepSeek shape (n_embd 5120, n_ff 2304, top-6 experts, distinct blobs) through the token path: gate/up +
// down launches, hipEvent time per layer; and a 5-entry verify window of one expert group
static void bench(int type) {
const int K = iq::tq_kbits(type), E = 5120, FF = 2304, NE = 6;
const size_t rb_g = (size_t) (E / 128) * (2 + 4 * K), rb_d = (size_t) (FF / 128) * (2 + 4 * K);
auto al = [](size_t n) { return (n + 255) / 256 * 256; };
const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
std::mt19937_64 rng(5);
std::vector<uint8_t> one(blob);
for (auto& b : one) b = (uint8_t) rng();
std::vector<unsigned long long> plan(NE);
for (int e = 0; e < NE; ++e) { uint8_t* d; CK(hipMalloc(&d, blob)); CK(hipMemcpy(d, one.data(), blob, hipMemcpyHostToDevice)); plan[e] = (unsigned long long) d; }
std::vector<int8_t> xq(E, 3), hq((size_t) NE * FF, 3); std::vector<float> xd(E / 32, 0.01f), hd((size_t) NE * FF / 32, 0.01f);
iq::Args a{};
a.plan_ptr = up(plan); a.n_embd = E; a.n_ff = FF; a.limit = 10.0f; a.xq = up(xq); a.xd = up(xd); a.hq = up(hq); a.hd = up(hd); a.tg = a.td = type;
for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
float *dh, *dp; CK(hipMalloc(&dh, (size_t) NE * FF * 4)); CK(hipMalloc(&dp, (size_t) NE * E * 4)); a.h = dh; a.part = dp;
hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1);
for (int rep = 0; rep < 5; ++rep) { iq::gate_up(a, NE, 1, 0); iq::down(a, NE, 1, 0); }
CK(hipDeviceSynchronize());
float ms_gu = 0, ms_dn = 0;
for (int part = 0; part < 2; ++part) {
hipEventRecord(e0);
for (int rep = 0; rep < 100; ++rep) { if (part == 0) iq::gate_up(a, NE, 1, 0); else iq::down(a, NE, 1, 0); }
hipEventRecord(e1); hipEventSynchronize(e1);
float ms; hipEventElapsedTime(&ms, e0, e1);
(part == 0 ? ms_gu : ms_dn) = ms / 100;
}
const double bytes = (double) NE * blob;
std::printf("bench %-6s token path, 6 experts: gate/up %.0f us, down %.0f us, layer %.0f us (%.0f GB/s, %.2f Tw/s), x40 = %.1f ms per token\n", iq::name(type), ms_gu * 1e3,
ms_dn * 1e3, (ms_gu + ms_dn) * 1e3, bytes / ((ms_gu + ms_dn) * 1e-3) / 1e9, (double) NE * 3 * FF * E / ((ms_gu + ms_dn) * 1e-3) / 1e12, 40.0 * (ms_gu + ms_dn));
}
int main(int argc, char** argv) {
std::vector<int> types = {145, 146, 224, 225, 226, 227};
for (int i = 1; i < argc; ++i)
if (std::string(argv[i]) == "--bench") { for (int t : {225, 224, 145, 146}) bench(t); return 0; }
else if (std::string(argv[i]) == "--type" && i + 1 < argc) { types.clear(); for (const char* p = argv[++i]; *p;) { types.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
std::mt19937_64 rng(11);
std::normal_distribution<float> nd(0.f, 1.f);
int fails = 0;
auto report = [&](const char* what, int type, double worst, double tol) {
const bool ok = worst <= tol;
std::printf("%-6s %-22s worst %.2e (tol %.0e) %s\n", iq::name(type), what, worst, tol, ok ? "ok" : "FAIL");
fails += !ok;
};
for (int type : types) {
const int K = iq::tq_kbits(type);
const int E = 512, FF = 256, NEXP = 3, T = 4;
const float lim = 7.0f;
const size_t rb_g = (size_t) (E / 128) * (2 + 4 * K), rb_d = (size_t) (FF / 128) * (2 + 4 * K);
// experts: blob = gate | up | down, each 256-aligned
auto al = [](size_t n) { return (n + 255) / 256 * 256; };
const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
std::vector<Mat> G(NEXP), U(NEXP), D(NEXP);
// h of row r of expert e for the input xv (F32 values), and the size of the operands it was made of
auto refh = [&](int e, int r, const float* xv, double& scale) {
double sg, su;
const double g = dotd(&G[e].w[(size_t) r * E], xv, E, &sg), u = dotd(&U[e].w[(size_t) r * E], xv, E, &su);
scale = sg + su + 1e-30;
return swiglu(g, u, lim);
};
std::vector<uint8_t> blobs((size_t) NEXP * blob, 0);
for (int e = 0; e < NEXP; ++e) {
G[e] = make_mat(rng, type, K, FF, E); U[e] = make_mat(rng, type, K, FF, E); D[e] = make_mat(rng, type, K, E, FF);
std::memcpy(&blobs[e * blob + off[0]], G[e].bytes.data(), G[e].bytes.size());
std::memcpy(&blobs[e * blob + off[1]], U[e].bytes.data(), U[e].bytes.size());
std::memcpy(&blobs[e * blob + off[2]], D[e].bytes.data(), D[e].bytes.size());
}
uint8_t* dblob = up(blobs);
// tokens
std::vector<float> x((size_t) T * E);
for (auto& v : x) v = nd(rng) * (1.0f + 3.0f * (rng() % 7 == 0));
std::vector<Q8> qx(T);
std::vector<int8_t> xq((size_t) T * E); std::vector<float> xd((size_t) T * E / 32);
for (int t = 0; t < T; ++t) { qx[t] = quant(&x[(size_t) t * E], E); std::memcpy(&xq[(size_t) t * E], qx[t].q.data(), E); std::memcpy(&xd[(size_t) t * E / 32], qx[t].d.data(), E / 32 * 4); }
const int8_t* dxq = up(xq); const float* dxd = up(xd);
// ---- token path: plan = 3 experts, input row 0
{
std::vector<unsigned long long> plan(NEXP);
for (int e = 0; e < NEXP; ++e) plan[e] = (unsigned long long) (dblob + e * blob);
iq::Args a{};
a.plan_ptr = up(plan); a.n_embd = E; a.n_ff = FF; a.limit = lim; a.xq = dxq; a.xd = dxd; a.tg = a.td = type;
for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
float* dh; CK(hipMalloc(&dh, (size_t) NEXP * FF * 4)); a.h = dh;
if (!iq::gate_up(a, NEXP, 1, 0)) { std::printf("gate_up refused\n"); return 1; }
CK(hipDeviceSynchronize());
const auto h = down_(dh, (size_t) NEXP * FF);
double worst = 0;
std::vector<float> href((size_t) NEXP * FF);
for (int e = 0; e < NEXP; ++e)
for (int r = 0; r < FF; ++r) {
double sc;
const double ref = refh(e, r, qx[0].xhat.data(), sc);
href[(size_t) e * FF + r] = (float) ref;
worst = std::max(worst, std::fabs(h[(size_t) e * FF + r] - ref) / sc);
}
report("token gate_up", type, worst, 1e-5);
// down over the reference h, quantized
std::vector<int8_t> hq((size_t) NEXP * FF); std::vector<float> hd((size_t) NEXP * FF / 32);
std::vector<Q8> qh(NEXP);
for (int e = 0; e < NEXP; ++e) { qh[e] = quant(&href[(size_t) e * FF], FF); std::memcpy(&hq[(size_t) e * FF], qh[e].q.data(), FF); std::memcpy(&hd[(size_t) e * FF / 32], qh[e].d.data(), FF / 32 * 4); }
a.hq = up(hq); a.hd = up(hd);
float* dp; CK(hipMalloc(&dp, (size_t) NEXP * E * 4)); a.part = dp;
if (!iq::down(a, NEXP, 1, 0)) { std::printf("down refused\n"); return 1; }
CK(hipDeviceSynchronize());
const auto part = down_(dp, (size_t) NEXP * E);
worst = 0;
for (int e = 0; e < NEXP; ++e)
for (int r = 0; r < E; ++r) {
double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], qh[e].xhat.data(), FF, &sa);
worst = std::max(worst, std::fabs(part[(size_t) e * E + r] - ref) / (sa + 1e-30));
}
report("token down", type, worst, 1e-6);
// ---- the CPU lane on the same experts and inputs; against the reference and the device
gg::IqCpu fm; std::string err;
if (!gg::iq_cpu_fmt(type, type, E, FF, fm, err)) { std::printf("cpu fmt: %s\n", err.c_str()); ++fails; }
else {
std::vector<uint8_t> act(fm.act_bytes), hact(fm.h_bytes);
gg::iq_cpu_quant(fm.gu_act, x.data(), E, act.data());
bool same = std::memcmp(act.data(), qx[0].d.data(), E / 32 * 4) == 0 && std::memcmp(act.data() + E / 32 * 4, qx[0].q.data(), E) == 0;
std::printf("%-6s cpu activation == device quantizer: %s\n", iq::name(type), same ? "ok" : "FAIL");
fails += !same;
double wg = 0, wd = 0, wx = 0;
for (int e = 0; e < NEXP; ++e) {
std::vector<float> hc(FF), yc(E);
float* hp[1] = {hc.data()}; float* yp[1] = {yc.data()};
const void* ap[1] = {act.data()};
gg::iq_cpu_gate_up(fm, &blobs[e * blob + off[0]], &blobs[e * blob + off[1]], ap, 1, hp, 0, FF, lim);
for (int r = 0; r < FF; ++r) { double sc; refh(e, r, qx[0].xhat.data(), sc); wg = std::max(wg, std::fabs(hc[r] - href[(size_t) e * FF + r]) / sc); wx = std::max(wx, std::fabs(hc[r] - h[(size_t) e * FF + r]) / sc); }
gg::iq_cpu_quant(fm.d_act, &href[(size_t) e * FF], FF, hact.data());
const void* hpp[1] = {hact.data()};
gg::iq_cpu_down(fm, &blobs[e * blob + off[2]], hpp, 1, yp, 0, E);
for (int r = 0; r < E; ++r) { double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], qh[e].xhat.data(), FF, &sa); wd = std::max(wd, std::fabs(yc[r] - ref) / (sa + 1e-30)); }
}
report("cpu gate_up vs ref", type, wg, 1e-5);
report("cpu down vs ref", type, wd, 1e-6);
report("cpu vs device gate_up", type, wx, 1e-5);
}
}
// ---- window path: groups of entries (entry e = t * 8 + i reads input row e >> 3)
{
std::vector<unsigned long long> grp = {(unsigned long long) (dblob + 0 * blob), (unsigned long long) (dblob + 2 * blob)};
std::vector<int> start = {0, 3, 5}, ent = {1, 10, 19, 2, 8}, ng = {2};
iq::Args a{};
a.grp_ptr = up(grp); a.grp_start = up(start); a.grp_ent = up(ent); a.n_groups = up(ng);
a.n_embd = E; a.n_ff = FF; a.limit = lim; a.xq = dxq; a.xd = dxd; a.tg = a.td = type;
for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
const int NE = 24;
float* dh; CK(hipMalloc(&dh, (size_t) NE * FF * 4)); CK(hipMemset(dh, 0, (size_t) NE * FF * 4)); a.h = dh;
iq::gate_up(a, 2, 3, 0);
CK(hipDeviceSynchronize());
const auto h = down_(dh, (size_t) NE * FF);
double worst = 0;
for (int gi = 0; gi < 2; ++gi)
for (int j = start[gi]; j < start[gi + 1]; ++j) {
const int en = ent[j], t = en >> 3, e = gi == 0 ? 0 : 2;
for (int r = 0; r < FF; ++r) {
double sc;
const double ref = refh(e, r, qx[t].xhat.data(), sc);
worst = std::max(worst, std::fabs(h[(size_t) en * FF + r] - ref) / sc);
}
}
report("window gate_up", type, worst, 1e-5);
}
// ---- the prompt sets: expert 0 owns sorted rows [0, 37), expert 2 rows [37, 42); input rows idx[sorted]
{
const int NR = 42;
std::vector<int> bounds = {0, 37, 37, 42}, idx(NR);
for (int i = 0; i < NR; ++i) idx[i] = i % T;
iq::SetArgs q{};
q.wbase = dblob; q.stride = blob; for (int r = 0; r < 3; ++r) q.tr[r] = off[r];
q.bounds = up(bounds); q.row0 = 0; q.max_rows = 37; q.n_exp = 3; q.n_embd = E; q.n_ff = FF; q.limit = lim;
q.tg = q.td = type; q.xf = up(x); q.idx = up(idx); q.ldx = E;
uint16_t* dh16; CK(hipMalloc(&dh16, (size_t) NR * FF * 2)); q.h = dh16; q.ldo = FF;
iq::set_gate_up(q, 0);
CK(hipDeviceSynchronize());
const auto h16 = down_(dh16, (size_t) NR * FF);
double worst = 0;
for (int e = 0; e < 3; ++e)
for (int lr = bounds[e]; lr < bounds[e + 1]; ++lr)
for (int r = 0; r < FF; ++r) {
double sc;
const double ref = refh(e, r, &x[(size_t) idx[lr] * E], sc);
worst = std::max(worst, std::fabs(h2f(h16[(size_t) lr * FF + r]) - ref) / sc);
}
report("set gate_up (f16 out)", type, worst, 1e-3);
// down over those f16 h rows
q.xh = dh16; q.ldx = FF;
float* dy; CK(hipMalloc(&dy, (size_t) NR * E * 4)); q.y = dy; q.ldo = E;
iq::set_down(q, 0);
CK(hipDeviceSynchronize());
const auto y = down_(dy, (size_t) NR * E);
worst = 0;
for (int e = 0; e < 3; ++e)
for (int lr = bounds[e]; lr < bounds[e + 1]; ++lr) {
std::vector<float> hf(FF);
for (int c = 0; c < FF; ++c) hf[c] = h2f(h16[(size_t) lr * FF + c]);
for (int r = 0; r < E; ++r) {
double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], hf.data(), FF, &sa);
worst = std::max(worst, std::fabs(y[(size_t) lr * E + r] - ref) / (sa + 1e-30));
}
}
report("set down", type, worst, 1e-6);
}
}
std::printf("%s\n", fails ? "FAILED" : "ALL OK");
return fails;
}
+137
View File
@@ -0,0 +1,137 @@
// Strata. Parity + speed of the gfx12 WMMA trellis GEMV (src/dsv41/ds4_tqw.cuh) on a R9700 (gfx1201):
// tqw_hip_test [--k 4,5,6,7] [--code 0|1] [--bench]
// Parity: random legal streams (any bit pattern is one), host-decoded weights (tqenc::decode_blocks: the table codebook, or the
// computed code when TQE_CODE=3single, with --code 1) against the kernel's y, relative to sum|w x| per output.
// --bench: the DeepSeek decode shape (12 gate/up matrices of 2304 x 5120), GB/s of weight bytes.
#include "../../src/dsv41/ds4_tqw.cuh"
#include "../../tools/dsv41_lab/wmma_emu.hpp"
#include "../../tools/trellis/tqenc.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
using namespace strata::ds4::tqw;
#define CK(x) do { hipError_t e_ = (x); if (e_ != hipSuccess) { std::printf("HIP error %s at %d\n", hipGetErrorString(e_), __LINE__); std::exit(2); } } while (0)
template <typename T> static T* up(const std::vector<T>& v) { T* d; CK(hipMalloc(&d, v.size() * sizeof(T))); CK(hipMemcpy(d, v.data(), v.size() * sizeof(T), hipMemcpyHostToDevice)); return d; }
template <int K, int NB, int CODE> static void launch(const Job* jd, const uint32_t* lut, int rows, int njobs) {
constexpr int T = 2;
dim3 grid((rows + 16 * T * 4 - 1) / (16 * T * 4), njobs);
gemv<K, NB, T, 1, CODE><<<grid, 128>>>(jd, lut);
}
template <int K, int CODE> static void launch_nb(int nb, const Job* jd, const uint32_t* lut, int rows, int njobs) {
switch (nb) {
case 1: launch<K, 1, CODE>(jd, lut, rows, njobs); break;
case 3: launch<K, 3, CODE>(jd, lut, rows, njobs); break;
default: launch<K, 5, CODE>(jd, lut, rows, njobs); break;
}
}
template <int CODE> static void launch_k(int K, int nb, const Job* jd, const uint32_t* lut, int rows, int njobs) {
switch (K) {
case 4: launch_nb<4, CODE>(nb, jd, lut, rows, njobs); break;
case 5: launch_nb<5, CODE>(nb, jd, lut, rows, njobs); break;
case 6: launch_nb<6, CODE>(nb, jd, lut, rows, njobs); break;
default: launch_nb<7, CODE>(nb, jd, lut, rows, njobs); break;
}
}
static void run(int code, int K, int nb, const Job* jd, const uint32_t* lut, int rows, int njobs) {
if (code) launch_k<1>(K, nb, jd, lut, rows, njobs); else launch_k<0>(K, nb, jd, lut, rows, njobs);
}
int main(int argc, char** argv) {
int code = std::getenv("TQE_CODE") ? 1 : 0;
bool bench = false;
std::vector<int> Ks = {4, 5, 6, 7};
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
if (a == "--bench") bench = true;
else if (a == "--code" && i + 1 < argc) code = std::atoi(argv[++i]);
else if (a == "--k" && i + 1 < argc) { Ks.clear(); for (const char* p = argv[++i]; *p;) { Ks.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
}
std::vector<uint32_t> hl(2048);
{
const float* pt = tqenc::point_table();
for (int i = 0; i < 2048; ++i) hl[i] = tqw::f2h_rn(pt[2 * i]) | ((uint32_t) tqw::f2h_rn(pt[2 * i + 1]) << 16);
}
const uint32_t* dlut = up(hl);
std::mt19937_64 rng(7);
int fails = 0;
const int types[8] = {0, 0, 0, 0, 225, 224, 145, 146};
for (int K : Ks) {
const int type = types[K], bsz = 2 + 4 * K;
const int rows = 96, in = 1536, nblk = in / 128;
std::vector<uint8_t> w((size_t) rows * nblk * bsz);
for (auto& b : w) b = (uint8_t) rng();
for (int64_t b = 0; b < (int64_t) rows * nblk; ++b) { const uint16_t d = tqw::f2h_rn(0.02f + 0.001f * (float) (rng() % 400)); std::memcpy(&w[(size_t) b * bsz], &d, 2); }
std::vector<float> dec((size_t) rows * in);
tqenc::decode_blocks(type, w.data(), (int64_t) rows * nblk, dec.data());
std::vector<uint32_t> words; std::vector<uint16_t> sc;
tqw::repack_tqw(K, w.data(), rows, nblk, words, sc);
for (int nb : {1, 3, 5}) {
std::vector<float> x((size_t) nb * in);
std::uniform_real_distribution<float> u(-1.f, 1.f);
for (auto& v : x) v = u(rng);
const uint32_t* dw = up(words); const uint16_t* ds = up(sc); const float* dx = up(x);
half8_t* xb; CK(hipMalloc(&xb, (size_t) nblk * 8 * 2 * nb * 2 * sizeof(half8_t)));
const size_t nall = (size_t) nblk * 8 * 2 * nb;
prep_b<<<(unsigned) ((nall + 127) / 128), 128>>>(dx, in, nb, in, xb);
float* dy; CK(hipMalloc(&dy, (size_t) nb * rows * 4)); CK(hipMemset(dy, 0, (size_t) nb * rows * 4));
std::vector<Job> jv = {Job{dw, ds, xb, dy, rows, in, rows}};
const Job* dj = up(jv);
run(code, K, nb, dj, dlut, rows, 1);
CK(hipDeviceSynchronize());
std::vector<float> y((size_t) nb * rows);
CK(hipMemcpy(y.data(), dy, y.size() * 4, hipMemcpyDeviceToHost));
double worst = 0;
for (int c = 0; c < nb; ++c)
for (int r = 0; r < rows; ++r) {
double s = 0, sa = 0;
for (int i = 0; i < in; ++i) { const double t = (double) dec[(size_t) r * in + i] * x[(size_t) c * in + i]; s += t; sa += std::fabs(t); }
worst = std::max(worst, std::fabs(y[(size_t) c * rows + r] - s) / (sa + 1e-30));
}
const bool ok = worst < 3e-7;
std::printf("K=%d nb=%d (%s): HIP wmma kernel vs double reference %.2e %s\n", K, nb, code ? "computed" : "table", worst, ok ? "ok" : "FAIL");
fails += !ok;
}
}
if (bench) {
for (int K : Ks) {
const int bsz = 2 + 4 * K, in = 5120, rows = 2304, nblk = in / 128;
std::vector<uint8_t> w((size_t) rows * nblk * bsz);
for (auto& b : w) b = (uint8_t) rng();
std::vector<uint32_t> words; std::vector<uint16_t> sc;
tqw::repack_tqw(K, w.data(), rows, nblk, words, sc);
for (int nb : {1, 5}) {
std::vector<float> x((size_t) nb * in, 0.5f);
const float* dx = up(x);
half8_t* xb; CK(hipMalloc(&xb, (size_t) nblk * 8 * 2 * nb * 2 * sizeof(half8_t)));
const size_t nall = (size_t) nblk * 8 * 2 * nb;
prep_b<<<(unsigned) ((nall + 127) / 128), 128>>>(dx, in, nb, in, xb);
float* dy; CK(hipMalloc(&dy, (size_t) nb * rows * 4));
std::vector<Job> jv; // 12 distinct buffers, so the L2 cannot serve a repeated matrix
for (int j = 0; j < 12; ++j) jv.push_back(Job{up(words), up(sc), xb, dy, rows, in, rows});
const Job* dj = up(jv);
const double bytes = 12.0 * rows * nblk * bsz;
for (int rep = 0; rep < 3; ++rep) run(code, K, nb, dj, dlut, rows, 12);
CK(hipDeviceSynchronize());
const auto t0 = std::chrono::steady_clock::now();
const int reps = 50;
for (int rep = 0; rep < reps; ++rep) run(code, K, nb, dj, dlut, rows, 12);
CK(hipDeviceSynchronize());
const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / reps;
std::printf("bench K=%d nb=%d %s: 12 gate/up matrices %.1f us, %.0f GB/s, %.2f Tw/s\n", K, nb, code ? "computed" : "table", us, bytes / us / 1e3,
12.0 * rows * in / us / 1e6);
}
}
}
std::printf("%s\n", fails ? "FAILED" : "ALL OK");
return fails;
}
+299
View File
@@ -0,0 +1,299 @@
// third_party/ggml/ggml-common-tq.h - the trellis (APR) expert formats of Agention's llama.cpp fork
// (agentionai/llama.cpp 073bc9e68, ggml/src/ggml-common.h; MIT, the same license as the rest of third_party/ggml).
// The block structs and the 2048-point "Hyb" codebook, unchanged, for Strata's device kernels and its CPU trellis
// kernels (src/kernels/cpu/tq_*.cpp). ggml-cpu takes them from the fork itself (-DSTRATA_GGML_DIR).
//
// TQ2_T / TQK6 / TQK7: 128 weights per block, {fp16 d; qs}. qs is 32 trellis steps of K bits (K = 8 / 6 / 7;
// TQ2_T byte-aligned, TQK bit-packed LSB-first, circular, step t's 16-bit window at bit (31 - t)*K; TQ2_T's state
// s_t = qs[(t + 31) % 32] << 8 | qs[t]). Step t gives weights 4t..4t+3: x = (s & 0x7fff) * 0x9e3779b1, points
// lut[x >> 21] and lut[(x >> 10) & 2047] (fp16 pairs), times d.
#pragma once
#include <stdint.h>
#define QK_TQ2_T 128
#define QK_TQK 128
#define TQ_STATE_BITS 15
#define TQ_STATE_MASK ((1u << TQ_STATE_BITS) - 1u)
typedef struct {
uint16_t d; // fp16 scale
uint8_t qs[QK_TQ2_T/4]; // one trellis byte per 4 weights
} block_tq2_t;
static_assert(sizeof(block_tq2_t) == 34, "wrong tq2_t block size/padding");
typedef struct {
uint16_t d;
uint8_t qs[4*6]; // 32 steps x 6 bits
} block_tqk6;
static_assert(sizeof(block_tqk6) == 26, "wrong tqk6 block size/padding");
typedef struct {
uint16_t d;
uint8_t qs[4*7]; // 32 steps x 7 bits
} block_tqk7;
static_assert(sizeof(block_tqk7) == 30, "wrong tqk7 block size/padding");
// device memory in a CUDA / HIP translation unit, ordinary host data everywhere else
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_TQ_LUT_SPACE __device__
#else
#define STRATA_TQ_LUT_SPACE
#endif
// point i = (tq_lut_f16[2i], tq_lut_f16[2i+1]) as fp16 bit patterns; 16-byte aligned so a point reads as one u32
alignas(16) static const STRATA_TQ_LUT_SPACE uint16_t tq_lut_f16[4096] = {
0xbd4d, 0xb8f7, 0xb6ce, 0x3cd5, 0xbd9e, 0x4368, 0x3dce, 0xb8a6, 0x395e, 0xb430, 0x3bc1, 0x3dbc, 0xb92b, 0x3c9c, 0xbca2, 0x3aaa,
0x3cdb, 0xb8e1, 0xbb33, 0x3dfb, 0x3a8d, 0xbb18, 0xbd64, 0x3da0, 0xbf1a, 0x3b83, 0xb389, 0x3659, 0xb40f, 0xabd7, 0x40ee, 0x35a2,
0xc057, 0x3972, 0xbe17, 0x3996, 0xb926, 0xb9b5, 0x393b, 0x3c75, 0x4151, 0xbdef, 0xb5a3, 0xbd09, 0xb408, 0x4012, 0x3b7f, 0x3ece,
0xb688, 0x4011, 0x3b17, 0xbe30, 0x3d9b, 0xb4bf, 0xb870, 0xb8c8, 0xb537, 0x38b2, 0x31be, 0x34b0, 0x3389, 0x3871, 0xba33, 0x38b8,
0xbce0, 0x3b3d, 0x3367, 0x3d3d, 0x3f50, 0x3cbe, 0x30b0, 0xb991, 0x3733, 0x3986, 0xb70e, 0xb6d9, 0xbe8c, 0xbd98, 0xbcca, 0xbe04,
0x36a9, 0x403c, 0xb527, 0x3eae, 0x3c6a, 0x3982, 0xb655, 0xbd5b, 0x3ebb, 0x3596, 0x417e, 0xbbbd, 0x2fe0, 0xb1d3, 0xb858, 0x31c0,
0xb54e, 0xbc10, 0x3cf0, 0xaf8b, 0x38e6, 0x3f5f, 0x3b87, 0xb2f6, 0xb114, 0xb675, 0x29bf, 0x3298, 0xbb7b, 0xb955, 0x34e9, 0xa984,
0xc04a, 0x378f, 0x31a0, 0x3c8c, 0x2dea, 0x3c68, 0x2fe1, 0x2d29, 0x2c33, 0xbd72, 0x379d, 0x3e3e, 0xb918, 0x3cf2, 0xbcbe, 0x38bf,
0x3284, 0xbdd5, 0x3707, 0xbd01, 0xbec1, 0x38c1, 0xb960, 0x3838, 0x3413, 0x3010, 0x376d, 0x3672, 0x302f, 0x3f42, 0x3a61, 0xbe9a,
0x3c06, 0xbc71, 0xbb57, 0xbcf2, 0xa9dc, 0x3c85, 0x3873, 0xb8b2, 0x2d1e, 0x340d, 0x3661, 0xb73f, 0xbb91, 0xb8b7, 0xb956, 0x3943,
0x3958, 0x3985, 0x3b26, 0xb556, 0xae17, 0xc2b9, 0x34e9, 0xb9ea, 0x33d5, 0xb6f4, 0x3826, 0xb1af, 0xb8a4, 0xaf98, 0x3a2d, 0xbc69,
0x3a25, 0x358e, 0x406d, 0x32fd, 0x38a4, 0xb11a, 0xb170, 0xb02e, 0xaa0a, 0xb5cb, 0x3c04, 0x3d45, 0xb258, 0xb55b, 0xb412, 0xbbf5,
0x3d33, 0x3f4b, 0xbc6e, 0x38a9, 0xb8c0, 0xb715, 0x2ec6, 0xbdd9, 0xbeb3, 0x2980, 0x3c54, 0xbb3c, 0x3ba0, 0x2d68, 0x42f9, 0xb209,
0xb557, 0x3337, 0x3870, 0xbda7, 0x2d57, 0x35bd, 0xb8cd, 0x385e, 0x39fe, 0xb68e, 0x3eda, 0xbd74, 0x3643, 0xbd54, 0x3a32, 0x37d4,
0x38f8, 0x2f7f, 0x37f3, 0x380f, 0x1b1e, 0xbc23, 0x25c7, 0x35c8, 0x2e3e, 0xb82a, 0xb85f, 0x3897, 0x3c0c, 0x3cb3, 0xc13e, 0x377b,
0xb3a4, 0x3f09, 0xc006, 0x3c73, 0xbda5, 0x3ad1, 0xb0c6, 0xa3cf, 0xb9d5, 0xb680, 0x384b, 0xb493, 0x3a3c, 0xa985, 0xbcb5, 0xba24,
0xbd0c, 0x3c21, 0x2f68, 0x34dc, 0xbc5d, 0xbdb7, 0xbbbf, 0xbddb, 0xb4c4, 0xb95a, 0xb59b, 0xbdaa, 0x34cf, 0xbdce, 0x3bad, 0x3f9d,
0x3a05, 0x3bd5, 0xb69c, 0x2c64, 0x4003, 0x3adb, 0x3d4c, 0x35e8, 0x308d, 0xb5cc, 0xbd2d, 0xbb86, 0xb124, 0x3cd3, 0x3a0a, 0xb2ab,
0xb507, 0x3d4b, 0xb190, 0x284c, 0x384c, 0xbe83, 0xbc94, 0xb806, 0x31e4, 0xb146, 0xbbe0, 0x3178, 0xbc9d, 0x3819, 0x3824, 0x2e8f,
0xc246, 0x4150, 0xbcf3, 0x3a43, 0x3da9, 0xbdd5, 0xb229, 0x3c47, 0x400e, 0xc001, 0x3bb2, 0xb0c3, 0xbd46, 0x3822, 0xb92d, 0xa4a9,
0x3c72, 0x3cfa, 0x3550, 0x4284, 0xb9e5, 0xbc97, 0xb996, 0x357a, 0xba03, 0xaf70, 0x35e7, 0xbc07, 0xb663, 0x397b, 0x3c59, 0x2942,
0xadf7, 0xb689, 0xb875, 0x3db8, 0x35ea, 0xb63c, 0x3674, 0x3349, 0x3926, 0x3ae0, 0xbb20, 0xb56e, 0x3f05, 0xa9ae, 0x3ce5, 0x3c38,
0x40b8, 0xb1ef, 0xba73, 0xba2b, 0xbdd7, 0x3d3f, 0x3822, 0x3c09, 0xbd87, 0xbce4, 0xba38, 0x36be, 0xb808, 0xbe23, 0xba33, 0xbd77,
0x3b90, 0x3466, 0xc1c5, 0xb805, 0x34c0, 0x375b, 0xb4be, 0xa2db, 0xb96c, 0x3495, 0xb38a, 0xb99a, 0x390a, 0x31d5, 0xa910, 0x3e16,
0x2878, 0x3dd6, 0x3964, 0xbdc0, 0xb783, 0xb3ef, 0xba12, 0xb571, 0xb8ce, 0xc0f2, 0xbd8f, 0x3771, 0x3656, 0x3eba, 0xbe0e, 0x3c39,
0x3ac5, 0x371b, 0x3469, 0x4071, 0xbd99, 0x2e19, 0x3ab2, 0x3cb8, 0x36d9, 0xa92c, 0xbcb4, 0xbc9b, 0xa0fa, 0xb4e2, 0x34ed, 0x31fd,
0x4033, 0xb0a0, 0xbac8, 0x342e, 0x3df5, 0xbccd, 0xbc5a, 0xbc5f, 0x3f32, 0x3ada, 0x3878, 0x39ec, 0x3db1, 0x3ce5, 0xb891, 0xbe93,
0x3c11, 0xb75e, 0xb82c, 0xbb27, 0x36d6, 0xba67, 0xb602, 0x352c, 0x3507, 0xbf3a, 0xb8e9, 0xbcf5, 0xb55e, 0x3773, 0xb832, 0xbd0a,
0xbf01, 0x3989, 0x3edf, 0x3d73, 0xbb3d, 0x3bc8, 0xbf82, 0xb7e0, 0x4053, 0x393f, 0xb07d, 0x2f91, 0xbc8b, 0xb6af, 0x3538, 0x2a46,
0x3c2f, 0xbbfd, 0xbfc9, 0x324e, 0x3a8f, 0xb702, 0xb939, 0xbda9, 0x3ac3, 0x3c3f, 0x3875, 0x3798, 0x3dc4, 0x3e1b, 0xb820, 0x255e,
0xa7e2, 0xbe92, 0xb63f, 0xb7c7, 0x38bd, 0xbcb4, 0x3a2f, 0xb958, 0xbdf2, 0x34fc, 0x3ba1, 0xb5a8, 0x3975, 0x3047, 0xaecc, 0x21da,
0xb7f7, 0x3bc4, 0x39f8, 0x2eb6, 0xbb3f, 0xbb3a, 0xbd9b, 0xb13d, 0x37fa, 0xbab2, 0x3794, 0x3074, 0xbd7e, 0xbad3, 0x3d65, 0x346b,
0x3cfd, 0xba61, 0xadd5, 0xb8fe, 0xbe09, 0xb6ec, 0xc05b, 0xb544, 0x360c, 0x2fdb, 0xb8ba, 0x39e5, 0xb8a8, 0x3e96, 0x40cf, 0x38cf,
0xba8b, 0xac5a, 0xb691, 0xb284, 0xc0b9, 0xb5d5, 0x3864, 0x3d00, 0x3220, 0xa382, 0x3422, 0xbb8f, 0xba85, 0xb85e, 0x3854, 0x3eb3,
0xc110, 0xb885, 0xbdf8, 0x2e60, 0x1cb3, 0xb8ba, 0xb4d3, 0x3636, 0x382a, 0xaf93, 0xbc81, 0x346a, 0x3d66, 0x3148, 0xc0b3, 0x36fe,
0xaf70, 0x4001, 0x3caf, 0x3eac, 0xbd48, 0xb614, 0x3d04, 0x3de8, 0x3f2b, 0x31d0, 0xb955, 0x30ce, 0xb81b, 0x2d33, 0xb328, 0xb657,
0xb7c2, 0x3527, 0xb9f6, 0xc255, 0xbc1a, 0x3c90, 0xbe9c, 0x35f3, 0xc11d, 0x409a, 0x30db, 0xbf2f, 0xbe02, 0x3285, 0xb607, 0x2f14,
0x3c56, 0x35c2, 0x3288, 0x30ac, 0x3c1c, 0xc25c, 0x3ca4, 0xbbd6, 0x3465, 0x29c8, 0x37a3, 0x4129, 0x3151, 0x3225, 0x2ef2, 0xad41,
0xbbcb, 0xbfc1, 0xb0c0, 0xbe71, 0xb17d, 0xbb59, 0x3cfe, 0xbefb, 0xbdb8, 0x39f0, 0x4014, 0x28a7, 0xb771, 0x396a, 0xbbdc, 0xc063,
0xbabe, 0x2898, 0xb683, 0x3de9, 0xbd1f, 0xaa78, 0x4187, 0x3ded, 0x3e18, 0x3d7b, 0xaf3c, 0xab0c, 0x38a7, 0xb524, 0xb964, 0xc38f,
0xbeda, 0x3d02, 0xaa74, 0xb25d, 0x2d90, 0xbe9a, 0xbe23, 0xbbb0, 0xbf6a, 0x3a8c, 0xbbfa, 0x3d87, 0xb53c, 0x3571, 0x385c, 0xc027,
0xb903, 0xb801, 0x3368, 0x3b7b, 0xb70c, 0x3ab8, 0x38b5, 0xb625, 0xb436, 0x3cb1, 0x8d2a, 0x3f2c, 0xb88e, 0x2c53, 0xb2c8, 0x393b,
0xbdbf, 0x3f40, 0xbc1b, 0x39d9, 0xbc3a, 0x306d, 0xb3ba, 0xb8fc, 0xc07b, 0x3c75, 0xb655, 0xb421, 0x3d34, 0xb720, 0x37f1, 0xb6a0,
0xb338, 0xbec7, 0xba58, 0x334e, 0x3aab, 0xb810, 0xb3d7, 0xbe3d, 0xb984, 0x40a2, 0xb5cd, 0xba54, 0x3afa, 0xb63e, 0xbd80, 0x394d,
0xba54, 0x2dda, 0xbaec, 0xb8e4, 0x2b2a, 0xad38, 0xbd82, 0x3886, 0xac6b, 0xc015, 0x368b, 0x3c72, 0x2fb3, 0xbaa7, 0x38fb, 0xb2cb,
0x335d, 0xbfb5, 0xaba9, 0xa535, 0xafb8, 0x38b7, 0x3d00, 0x3524, 0x3b42, 0xaeac, 0x4144, 0xb1a6, 0xb352, 0xba3a, 0x2c72, 0x39f3,
0x4079, 0xb82c, 0xb9e5, 0xb45f, 0x9d20, 0xb9f5, 0xb2ee, 0xbd36, 0xbad5, 0x2f11, 0x3450, 0x3e80, 0x213f, 0xb684, 0x3200, 0xbd07,
0xb839, 0xbc5e, 0xc217, 0x3f5d, 0x3d9a, 0xbe94, 0x3947, 0x3381, 0x9081, 0xb943, 0x3eac, 0x3795, 0xad61, 0x3915, 0xb810, 0x3d5d,
0x39cb, 0x33f2, 0xbfe8, 0x41ed, 0x3ee7, 0xb4a2, 0xb9e5, 0xb88a, 0x36b3, 0xc0da, 0xb57f, 0x406c, 0xba70, 0x3c5c, 0xb936, 0x3ae4,
0x3e2c, 0xb7ff, 0x35b6, 0xb08e, 0xb8d1, 0x3c3a, 0x227e, 0xafed, 0x3a3d, 0x310a, 0x2d00, 0xb926, 0xbbe1, 0x3f76, 0xb8aa, 0x3e15,
0xb31c, 0xc074, 0x40ee, 0xbcb6, 0x3449, 0x3b03, 0x38f5, 0xbd01, 0xbc2d, 0x386a, 0x3f94, 0xbcfc, 0x33a2, 0xb049, 0x3c77, 0xb86e,
0x366c, 0xb91c, 0xb832, 0x35c6, 0x36ab, 0xbc4c, 0xb6b9, 0x3a04, 0xb2c9, 0x3c84, 0x3006, 0xb762, 0x330e, 0x3580, 0x3d32, 0x3926,
0x38f9, 0xbfb2, 0xc00a, 0x3de6, 0x3a35, 0xafad, 0xbe69, 0x3d88, 0xc30f, 0xbe12, 0xb13d, 0x3d26, 0x382a, 0xb7a5, 0x40fa, 0x3ac3,
0xb8a9, 0xc028, 0xb979, 0x3e19, 0xbac1, 0xbdd7, 0xbd42, 0xb802, 0xb631, 0xbe1a, 0xb8fb, 0xac7a, 0x3ff8, 0x3819, 0x3d3f, 0x42e8,
0xb312, 0xb1dc, 0xc036, 0xaa42, 0xbd28, 0xc078, 0xb6f5, 0x36dd, 0xbad4, 0x31fd, 0x3933, 0xb7e9, 0x39b4, 0x31d4, 0xbd13, 0xb4ae,
0x37d3, 0x3c5d, 0x3925, 0xbafd, 0x3b52, 0x3875, 0x2a38, 0xa581, 0x3b51, 0xb450, 0xc248, 0x3ccc, 0xb1aa, 0x3ad2, 0x36eb, 0xbe90,
0x423c, 0x34e3, 0x3ac2, 0x3bc1, 0x3be5, 0x3749, 0xbcd1, 0x3cee, 0x3ac7, 0x4017, 0x3a67, 0xbfc4, 0xb7eb, 0xb9a8, 0xbf94, 0xbf08,
0xb711, 0xa983, 0x3c0f, 0xb609, 0x3ebd, 0xb7f7, 0x34f4, 0xbca7, 0xbac3, 0x38b1, 0xb5d0, 0xb93f, 0x3e04, 0x3f1d, 0xb7fd, 0x305c,
0xaae3, 0xbcaa, 0xbb0f, 0x3d8c, 0xbca4, 0xbd3f, 0xbb3b, 0xbc08, 0x3a90, 0xb9de, 0x377f, 0xad25, 0xb988, 0xbefe, 0xbdf7, 0xbc6c,
0xba23, 0x35c3, 0xbb14, 0x370a, 0x3c45, 0xb3a9, 0xb889, 0x3c72, 0x3a36, 0x3e71, 0x3a90, 0xb8e0, 0x34cb, 0x34a6, 0x40be, 0x3c6c,
0xbe95, 0xbc3f, 0xba4d, 0x2284, 0xb96e, 0xb73e, 0x384d, 0xbc04, 0xb452, 0x3a03, 0x41a8, 0xc100, 0x3c75, 0x2ed2, 0xbc47, 0x3ab6,
0x3746, 0x3a63, 0xb62f, 0x3735, 0xb9dd, 0x3c2f, 0xbba8, 0xb08f, 0xb270, 0x3289, 0x3972, 0x3c1e, 0x3844, 0xb5ae, 0x3cee, 0x3d30,
0xb98f, 0x3fa2, 0x3e16, 0xb150, 0x3c9c, 0x382c, 0x3483, 0xae2e, 0x3b71, 0x3a84, 0xbb53, 0x32f4, 0x3540, 0x3ab2, 0xb6e0, 0xba06,
0xbcc9, 0x3701, 0xb89a, 0x361a, 0xbe12, 0x3a74, 0x3b56, 0x37ae, 0xb6ec, 0x38ee, 0xb47a, 0xb60a, 0x3247, 0x374a, 0x394d, 0x3883,
0xb76f, 0x2c41, 0xbc07, 0xb862, 0x395e, 0xbba5, 0xb71f, 0x3865, 0x3897, 0x2cbc, 0xac7a, 0x35c9, 0xb9df, 0x3ac5, 0xb63b, 0xb8b9,
0xc064, 0x3ff6, 0x3ba3, 0xb829, 0xb904, 0x3b7e, 0xafdb, 0xb78e, 0xbaec, 0x3c22, 0xb53d, 0x39a5, 0xbab6, 0xc0d4, 0xb47e, 0xbddb,
0xba66, 0xc01c, 0x37ec, 0xbcb0, 0xb409, 0x3ac3, 0x2b2b, 0x3e47, 0x3b8a, 0xb8e0, 0x38cd, 0x3a77, 0x3cb0, 0xb724, 0xbaef, 0x381f,
0xba7a, 0xb0f9, 0x3940, 0xb138, 0x3855, 0xb840, 0x39af, 0x35f4, 0x3b0f, 0x2c19, 0x3760, 0x3b83, 0xa813, 0x3801, 0xb801, 0x41d6,
0x3026, 0x3ab3, 0xbca3, 0xa9f5, 0xbf1e, 0x370e, 0xb82b, 0x3467, 0xb4c3, 0xbd57, 0xad4c, 0xb4e9, 0xb8c4, 0xbad6, 0xa8f7, 0xbd66,
0x3e70, 0x3cd2, 0x236c, 0x3421, 0xaa8a, 0x3c22, 0xb9c2, 0x9661, 0x3988, 0xb622, 0xb797, 0xb8aa, 0x254c, 0x305c, 0xbd53, 0x271b,
0x3c11, 0xbaa9, 0xb75b, 0x3601, 0x36d1, 0xb4e9, 0xb856, 0xb15d, 0xbe96, 0xc0b2, 0xb7c5, 0x3e32, 0xb069, 0x3e22, 0xbc18, 0x3b41,
0xc16e, 0x31ca, 0x365a, 0x35f9, 0xb491, 0xb700, 0x3a6a, 0xb41b, 0x2f26, 0x406a, 0xb8a6, 0xbd54, 0x3b9b, 0x39e3, 0xbeae, 0xad0f,
0x3b1b, 0xb166, 0xafd4, 0x3655, 0xbde7, 0xbaa7, 0x37c1, 0xbd6c, 0xbc6d, 0x3cbf, 0x3584, 0x2dbd, 0x3d69, 0xb9f9, 0xb992, 0xac53,
0xbf6b, 0xb2a2, 0x35b5, 0xc157, 0x331a, 0x328e, 0xba14, 0xb7b3, 0x3c44, 0x3809, 0x3c08, 0x3361, 0x3b93, 0xbc1c, 0x3b53, 0xbd21,
0xb9d1, 0x39b2, 0x326b, 0xbad9, 0xb1c8, 0x35e6, 0x38ff, 0xaeff, 0xb831, 0xb734, 0xba96, 0xbbe1, 0x33f8, 0x36fb, 0xb049, 0xc15a,
0x3b22, 0xb7a3, 0xb462, 0xbc3d, 0xbf97, 0xb57c, 0x3c86, 0xbcaa, 0xbcb9, 0x3c6e, 0x39ca, 0xb0f5, 0x379f, 0xb5bf, 0xb629, 0xbcb6,
0x3aab, 0x3f0f, 0xc01a, 0x34fc, 0x3869, 0xb6be, 0xb953, 0x32f4, 0xb85f, 0xbdb7, 0x39f4, 0x411a, 0xbce8, 0x203c, 0x3824, 0x2a59,
0xb26f, 0xa60c, 0xb47f, 0x3d96, 0xb8d0, 0xb53f, 0x3706, 0xb69f, 0xb1c9, 0x36cf, 0xad03, 0x37c1, 0x3d80, 0xbc90, 0xba26, 0xb98e,
0x3c5b, 0x334b, 0xc196, 0xb051, 0xbd24, 0xbd79, 0x3b38, 0x3e2f, 0xba82, 0xb64d, 0x2a56, 0x34ed, 0xb36f, 0x2a01, 0x40e9, 0xbfbc,
0xb7ce, 0xb600, 0x3cce, 0x3a9c, 0x33c6, 0xb23c, 0x3c33, 0x36c8, 0xa776, 0x409e, 0xb822, 0x3c35, 0x3e43, 0x30ef, 0xb9b2, 0xb9f7,
0x3c79, 0xba81, 0x3973, 0xaedb, 0xbfe1, 0xba33, 0x348e, 0x3d8a, 0xb5ac, 0xbfa1, 0xb8d9, 0x31b7, 0x3aee, 0x3481, 0x3d3b, 0xb56e,
0x3d98, 0x2c65, 0x39e0, 0x3d74, 0xb51a, 0x3ae2, 0xae6c, 0x3bb9, 0xbdc8, 0x1d86, 0xb9d9, 0x3840, 0xbc60, 0xc0f1, 0x3e26, 0x396d,
0x3dc5, 0xa478, 0xbf35, 0xc01b, 0xb938, 0x39c8, 0x35d1, 0x3fd0, 0xb3bc, 0x3d41, 0xbca8, 0x3bf9, 0xbd36, 0x32f5, 0x3f59, 0x34c8,
0x3e38, 0x3854, 0x338e, 0xb82e, 0x37b2, 0xa3ce, 0xb683, 0x37fd, 0xc104, 0x3f02, 0xb92f, 0x38b3, 0xb454, 0x3bcd, 0x31f4, 0xba42,
0xbf4d, 0x3878, 0xbf7f, 0x3559, 0xb8e0, 0xbc53, 0xbd77, 0x407e, 0xb69e, 0xb0c6, 0xacce, 0xbabd, 0x3c1b, 0xb92f, 0xb8fa, 0x3a5f,
0xb628, 0x3f13, 0x3893, 0xbacd, 0xc047, 0x3ec8, 0xb70b, 0xba7f, 0xb997, 0xb140, 0x2c0c, 0xb466, 0xba3f, 0x3dde, 0xbe75, 0x3ae1,
0xb466, 0x3879, 0x3d68, 0x3c55, 0xb4d9, 0x3c6e, 0xbe71, 0xb803, 0x3e15, 0x2a52, 0x3e1b, 0xbc37, 0x3585, 0xb747, 0xbf22, 0x3db4,
0xbcdb, 0x31a6, 0xb415, 0x2e23, 0xab25, 0xb884, 0x329e, 0xb5ef, 0x3525, 0xb59c, 0xba76, 0x39c2, 0xb6f5, 0xbf1e, 0xbcdf, 0x2dad,
0x3e8c, 0x4019, 0xb92c, 0xbb4a, 0x3494, 0x2ddb, 0x406e, 0x3afd, 0x3b91, 0xb97a, 0x3c1f, 0xbce1, 0x3eae, 0x3c34, 0xbddd, 0x38ec,
0x390f, 0x3e4f, 0xbc20, 0x3e04, 0x378c, 0xba0b, 0x330d, 0xb8aa, 0x3e34, 0x348e, 0xbaa5, 0x352f, 0xbac3, 0x3d2b, 0xb982, 0xbe71,
0x305c, 0xc1e1, 0xbe05, 0xbe12, 0xb70b, 0x2fc1, 0x3c8b, 0xbe71, 0x35ad, 0x3dcc, 0xb581, 0xb612, 0xb42c, 0xb50c, 0xb1c9, 0xb36c,
0xb443, 0x3977, 0xbd4c, 0x3d11, 0x39b8, 0x3b17, 0x269a, 0xbd27, 0xbce0, 0x3d6c, 0xb86d, 0xb611, 0x35e7, 0xb50c, 0xb453, 0x359c,
0x38c6, 0x38bf, 0xb82a, 0x39a6, 0xa8c2, 0x3bb1, 0xb020, 0x3c8b, 0x2c82, 0x2dfa, 0xbb37, 0xb43e, 0x2b23, 0xbbbd, 0x3c97, 0xbd25,
0x3d21, 0xbb81, 0xb8e5, 0xbe12, 0x3845, 0x3d6a, 0xb571, 0xc0ec, 0x3c69, 0x34ba, 0xb96f, 0x2818, 0xbdde, 0x382d, 0x3f0c, 0x3f33,
0xb44b, 0x3c30, 0xaebd, 0xbef5, 0x3a3b, 0x2683, 0xaaf0, 0xb7f8, 0x405e, 0xb4f5, 0x3c5b, 0xb197, 0x359f, 0xbada, 0x3227, 0xbb77,
0x3877, 0x3dec, 0x34a2, 0xb7c6, 0x3bde, 0xba0e, 0xb758, 0x20cc, 0x3760, 0xb8e8, 0xbdaf, 0x3cb8, 0x3cf3, 0x385d, 0x306f, 0x3078,
0xac7a, 0x34d1, 0xb9b8, 0x402f, 0x2d2e, 0xbc80, 0xb55d, 0xbeef, 0x348e, 0x356a, 0x3511, 0x3b68, 0x35a4, 0x32ea, 0x3e99, 0x3a13,
0x4002, 0xb8c9, 0x3dc1, 0x355a, 0x3556, 0xbb78, 0x3560, 0x37ee, 0xba6e, 0xbc4a, 0xb14d, 0x33eb, 0x22a9, 0x3c4a, 0xbd5b, 0x3a27,
0xc0ca, 0xba1d, 0x4053, 0xbd31, 0x3c1a, 0xb87b, 0x38de, 0x36e3, 0x2663, 0x2b95, 0x3b4f, 0x3685, 0x353c, 0xc020, 0xbe97, 0x4050,
0xbc48, 0xa53a, 0x3e4e, 0xbeea, 0xac24, 0xbb52, 0xb743, 0x40d2, 0xb389, 0x3762, 0xb493, 0xbb02, 0x3cb4, 0x342f, 0xba83, 0x3ace,
0xbc28, 0x3923, 0xc004, 0xc0af, 0xb898, 0xb842, 0x38d0, 0x2760, 0xb83e, 0x405e, 0xaffb, 0x4254, 0x3b69, 0x3c6f, 0xba70, 0x3bed,
0xb0de, 0xba70, 0x3d9c, 0xb635, 0xbde3, 0x3de8, 0x3321, 0x38e5, 0x369f, 0x40ae, 0x36e3, 0xbaf2, 0xaf7b, 0xbb9b, 0xb484, 0xc1f3,
0x3f5a, 0x4097, 0x3da5, 0xaead, 0x3934, 0x1e3a, 0xbc67, 0x409f, 0xb2ed, 0x3a55, 0x3009, 0x385a, 0x3166, 0xb6ac, 0x3832, 0xc3f8,
0xb800, 0xa95f, 0xbc8a, 0x2f61, 0x353c, 0xbeba, 0x3284, 0x3ce3, 0x3fad, 0xade8, 0x3da0, 0xb7c1, 0xb56e, 0x382d, 0x385f, 0x3855,
0xbd34, 0x2ff5, 0xba07, 0xb290, 0xbda4, 0xb6f4, 0xb89b, 0x3ad2, 0x3613, 0xbe27, 0x3838, 0x35fc, 0x28e1, 0x3c96, 0x3c1e, 0xbd62,
0x315a, 0x356b, 0x3b05, 0x3b16, 0xbaf3, 0x3ed5, 0xbf42, 0x3c65, 0x3d3f, 0x378a, 0xbf4e, 0xbd43, 0x3c0d, 0x3964, 0x34c3, 0x3c00,
0x345a, 0xbafe, 0xbf4f, 0xba8b, 0x4240, 0xb95b, 0x3b21, 0xc0a2, 0xb6ed, 0x331d, 0xb57a, 0x3111, 0x3594, 0xb8ca, 0xc16a, 0x3d96,
0xb7a9, 0x3c86, 0xb949, 0xb498, 0x2d89, 0x3c1e, 0xad06, 0x2eeb, 0xbc5b, 0xba8a, 0xbe54, 0xb0b9, 0xbc9a, 0x3e71, 0x3ca7, 0x3ff4,
0xbf8b, 0xbbbc, 0xb894, 0x3fef, 0x3bda, 0x40c9, 0x3bc7, 0xbb66, 0xb87e, 0x3cbb, 0xbb1e, 0xb1f7, 0x3a3d, 0x38f6, 0xad22, 0x3cd9,
0xbdb4, 0xbd81, 0xb005, 0xbd96, 0x3d6e, 0xb91c, 0x38f2, 0xbd5e, 0xb513, 0x2e27, 0x3e5b, 0xbe1c, 0x34b3, 0x366e, 0xbb24, 0xb6cd,
0x36f7, 0xbfb4, 0xb00c, 0x34a3, 0xb1bf, 0x37df, 0xb9d6, 0x33d3, 0x396f, 0x3edf, 0xb5d1, 0xb6f7, 0x2aa1, 0x38b2, 0x36b1, 0x223d,
0xbc6a, 0x3d3e, 0xb777, 0xb7b5, 0xb8ed, 0xb91c, 0x3be6, 0x35f5, 0xc077, 0xbd74, 0xbcdc, 0x3966, 0xbc12, 0x3d0b, 0x3312, 0x28cb,
0xbd0d, 0x4128, 0xbef1, 0xb80e, 0xb758, 0x3eb4, 0xb6d3, 0x352f, 0x343d, 0x3ca3, 0xb733, 0xbaef, 0xbce4, 0xbc1d, 0x3eac, 0x38fa,
0xb9d1, 0x3bce, 0x3953, 0x36ec, 0xbbb4, 0x3985, 0x4005, 0x3fe2, 0x3f4e, 0xb991, 0x39d5, 0xbe2c, 0xb44e, 0xb37f, 0x3acf, 0x30aa,
0xb358, 0x40c3, 0x3c1f, 0x3b9b, 0x39ec, 0x39a7, 0x3d01, 0x4111, 0x367d, 0xbb76, 0x3c75, 0x3a48, 0xb547, 0x3c01, 0x3d2f, 0x3ae0,
0xc3b1, 0xb837, 0x2e1d, 0x36c1, 0xb2d3, 0xbd8e, 0xb23a, 0x3d80, 0xbd29, 0x3c9b, 0x37a8, 0x348c, 0x3c9e, 0xb5aa, 0x3311, 0x40d3,
0x256d, 0x4028, 0x2e47, 0xa66e, 0x390a, 0xb8de, 0x3306, 0x3c03, 0xbc58, 0xbb3f, 0xbc05, 0xbc21, 0x376c, 0x28e2, 0xb536, 0x3dda,
0x2427, 0x3ebb, 0xb70a, 0xbdbf, 0x3cc4, 0xbb10, 0x3d33, 0x2d29, 0xc044, 0xbfd0, 0xbfd3, 0x3726, 0x32d9, 0xad34, 0xc040, 0x3d32,
0x3f66, 0x2b12, 0x377a, 0x3ae9, 0x3088, 0xc02d, 0x384f, 0x38e2, 0x3c2b, 0xacfb, 0xbbda, 0xb9de, 0x2d0a, 0x3945, 0x38f1, 0x40ba,
0x3858, 0x1b91, 0x2f58, 0xba15, 0x3642, 0x3a7f, 0x39d4, 0x387a, 0xb9af, 0x3efc, 0xc007, 0xbcc6, 0xba9b, 0x3938, 0xb635, 0xaa27,
0xa2e3, 0x3509, 0xb38b, 0xbb66, 0xbbc3, 0xb775, 0xbbc7, 0x33f5, 0xc014, 0xb6ba, 0xa91a, 0x340b, 0xc0ad, 0x3dad, 0xa94d, 0xb70e,
0xb9b4, 0xbcf0, 0x2f73, 0xb38a, 0x34f1, 0x304e, 0x3cdf, 0xbfe6, 0xc329, 0x34c3, 0x3c80, 0xbdc0, 0x37bd, 0x39ed, 0x393d, 0xaaa3,
0x3a94, 0xbd49, 0xc288, 0xb4d2, 0x2c3e, 0xbfb6, 0xbca0, 0xb93d, 0xb9d6, 0x3200, 0xac36, 0x3875, 0x3072, 0x33f7, 0x3e47, 0xb8f7,
0xba54, 0x3116, 0x3a12, 0xc037, 0x3ad7, 0xb48c, 0x323b, 0xb798, 0xc11c, 0xbf50, 0xaf13, 0xaf0b, 0x3c1c, 0x2efc, 0x3b04, 0xbc68,
0xb611, 0x38fa, 0xb74f, 0x3f8c, 0x3b22, 0xbf1a, 0xc394, 0x3cef, 0x3ca6, 0x2614, 0x37c3, 0xbe03, 0x3cd0, 0xc072, 0x3f2e, 0xc15f,
0x3c11, 0x34da, 0xb4e7, 0x3cf5, 0xc030, 0x3030, 0xb32a, 0x3837, 0xc1c0, 0xbca2, 0x33dd, 0x3ef1, 0x982a, 0xac37, 0x3c5e, 0xb7b3,
0xb5b6, 0xb9cd, 0xb9e9, 0x2c0c, 0x3832, 0xab2a, 0xacea, 0x419a, 0x3458, 0x3922, 0xc18e, 0x3c1f, 0x2ae8, 0xb762, 0x393d, 0xbe8c,
0xb009, 0xbd47, 0x3d9b, 0x3abd, 0xb95a, 0x3c56, 0x3cfe, 0x3107, 0x37d9, 0xbc56, 0x312d, 0xb846, 0x3752, 0x3d2e, 0x41d2, 0x4030,
0xb2d1, 0x3bf0, 0x30c5, 0xbc39, 0xb1ee, 0xb8aa, 0x405a, 0x3d48, 0x3c11, 0x2a02, 0xb800, 0xc184, 0x3dd2, 0x308d, 0xb975, 0xbd48,
0x32b5, 0xb942, 0x38c6, 0xbe0e, 0x3688, 0xc06f, 0x33b3, 0xbc61, 0x3910, 0xc094, 0x3cb1, 0x38f8, 0xbe18, 0xc2b8, 0x37d6, 0xb3de,
0xab85, 0x3b2e, 0xb8f6, 0x299c, 0x3676, 0xbdb1, 0xb87d, 0x3f26, 0x3068, 0xc117, 0xb7ae, 0x3a16, 0x30ea, 0x3b44, 0xb347, 0x30a9,
0x31a2, 0x39c3, 0x36bf, 0x3021, 0x38f6, 0xbc13, 0xb882, 0x338d, 0xb892, 0x3bf4, 0x385d, 0xba38, 0x3b4e, 0x305d, 0x43aa, 0x387b,
0x36a4, 0xb0c4, 0xb800, 0xb925, 0xb9d7, 0xbdef, 0xbba6, 0x4244, 0x36da, 0x3452, 0x3b75, 0xc191, 0x381f, 0x318b, 0x38a3, 0x405a,
0xba2a, 0x3d74, 0xb9b5, 0x3666, 0x3990, 0x3802, 0xb8ed, 0x37cc, 0x3697, 0x36e9, 0x3d43, 0xb3ef, 0xbaa8, 0x3cbf, 0xbdf3, 0xadc4,
0x2c73, 0xb0b6, 0xbbd5, 0x386a, 0xbaaf, 0xbece, 0x35f2, 0x3d58, 0x358e, 0x3ca3, 0xb987, 0x3d37, 0x3770, 0x3cba, 0x3d8a, 0x400f,
0x37a5, 0x3910, 0x3bce, 0x3148, 0xb10b, 0xb1f2, 0x343f, 0x3a6d, 0x399b, 0xb733, 0x38b6, 0x3550, 0xbe87, 0xb90a, 0xc1ea, 0xbe4b,
0xbe96, 0xbe8f, 0x3999, 0xb92a, 0x3a77, 0xb1c8, 0x366c, 0x3508, 0xb7aa, 0xbcc4, 0xb03d, 0xb591, 0xbecf, 0xb9fc, 0xbb2f, 0x40f5,
0x4073, 0xc0db, 0x421c, 0xbf44, 0x339f, 0x34cd, 0x37bd, 0xb4dc, 0xb531, 0xb44c, 0x3e9d, 0x3b38, 0xba12, 0xa9ff, 0x3655, 0xb9ce,
0xb32e, 0x3441, 0x3f6f, 0x3c08, 0x3a43, 0xb860, 0xbcf7, 0x3dfe, 0xc07a, 0xbc86, 0x3745, 0xbbf6, 0x2987, 0x36a6, 0x35e0, 0x267f,
0xb4b8, 0xb9f1, 0xb865, 0x3a39, 0x2f53, 0xbd26, 0x37b5, 0x388c, 0x3b0e, 0xb889, 0x3c18, 0xa422, 0xb894, 0x1666, 0xb37f, 0xaf72,
0x3772, 0xb081, 0xc090, 0xb0ea, 0x33ad, 0x41d0, 0xb75b, 0x345f, 0x3de3, 0xba82, 0xafd1, 0xb979, 0x3f52, 0x36ec, 0xb928, 0x42c7,
0xbc71, 0xb54e, 0x3b45, 0x356d, 0xb63d, 0x3d77, 0xa722, 0x2873, 0x3ab5, 0xac22, 0xbe38, 0x3ccb, 0xb82f, 0xba9d, 0xb88a, 0x34f9,
0x3dde, 0xb997, 0xc1b1, 0x399d, 0x3d55, 0xc19a, 0xb380, 0x3e72, 0xb701, 0xbd0a, 0xc16c, 0xba7f, 0x39a8, 0x3df0, 0xbf04, 0xb595,
0xba46, 0xb904, 0x3ab7, 0x35c9, 0xb181, 0xb9da, 0xba29, 0x3a40, 0xbee1, 0xb257, 0xc262, 0xbabb, 0x3d35, 0x39fa, 0x2661, 0x3922,
0xb5da, 0x3c35, 0xac1e, 0xbc02, 0xb9c2, 0x375b, 0x343c, 0xb5e8, 0xbc03, 0xbd4a, 0x2c70, 0x3840, 0xb98c, 0x3a48, 0xbd06, 0xb987,
0xc008, 0x3a3f, 0x3676, 0xadf0, 0x391e, 0x437f, 0x4179, 0x38df, 0x3a92, 0x3dd2, 0xb42f, 0xb870, 0x3e99, 0xb0b3, 0x3136, 0x3c3b,
0xb98b, 0x3b57, 0xaf33, 0x3d80, 0xb578, 0x3475, 0x3f58, 0xb620, 0x3a60, 0x386c, 0xaf9c, 0xbc68, 0x3826, 0xb99a, 0xb8c8, 0xb414,
0xb952, 0x374b, 0x40e7, 0xba0c, 0x3a49, 0x4072, 0xb76d, 0xbc2a, 0xbc67, 0xaebb, 0x3a0b, 0xba0d, 0x3f56, 0x3e43, 0x3d02, 0xbc43,
0xb9a2, 0x3e82, 0x3a1f, 0xb796, 0x355d, 0xbc5c, 0x3a70, 0xba8a, 0x333c, 0xbd61, 0x3caf, 0xb9c7, 0xbd93, 0x31f0, 0xbd05, 0xbce5,
0xb4b9, 0xba81, 0xbc7d, 0xbbf2, 0x3740, 0xb976, 0xb53f, 0xbe7b, 0xbced, 0xb266, 0x30be, 0x3bda, 0x3f03, 0xbab0, 0x3bdf, 0xbfc7,
0xadc6, 0xbf88, 0xb00b, 0x2c42, 0x3e4d, 0xc2c9, 0xbe94, 0x4114, 0x3b5a, 0xbcba, 0x3d7c, 0xbd31, 0x3726, 0x37ac, 0x397e, 0x3a3a,
0x2f06, 0xbcd0, 0x3d0c, 0x3cb9, 0x35a6, 0x3f37, 0x41f6, 0xb161, 0xba84, 0x3e57, 0xb423, 0x3e1e, 0x3eb8, 0x2e08, 0xb1c0, 0xbc7f,
0x3bef, 0xc03a, 0xbcc4, 0xbb16, 0x38a5, 0x3c4a, 0x3b7f, 0x3bf8, 0x39c9, 0x2964, 0xbddc, 0xb944, 0x406a, 0x3717, 0xb80f, 0xaef2,
0x38c2, 0xbf14, 0x3633, 0x37eb, 0x2c27, 0x3d19, 0xba23, 0x37d2, 0x31dd, 0x3823, 0xbb12, 0x39a3, 0xb985, 0xb57c, 0xb7fa, 0x36a5,
0xb882, 0x3b5b, 0x3856, 0x34c0, 0x3a69, 0xb60d, 0xc03c, 0x3b6e, 0x3b95, 0x219c, 0xac3a, 0xbdd6, 0x4008, 0x356f, 0xae4c, 0x33cb,
0xbd84, 0x3c41, 0x3ba0, 0x3b3c, 0xbb56, 0x387e, 0x3b22, 0xba14, 0x33cb, 0x3f8d, 0x3508, 0x18e0, 0x3b2d, 0xa89e, 0x3c83, 0x3c7f,
0x3cd9, 0xb82a, 0x39b5, 0x3912, 0x39d4, 0xbb1c, 0xb8ed, 0xb1de, 0x3b0b, 0xbb92, 0x3be0, 0x4178, 0x3716, 0x31e8, 0xb3ff, 0xbc80,
0xba07, 0x393e, 0x39a9, 0xba87, 0xbb2d, 0x4185, 0xb616, 0x32fd, 0xb9d6, 0xbbe7, 0x3645, 0x3cee, 0xb4c6, 0xbcba, 0x3e24, 0xac74,
0x2b37, 0xb9ba, 0x3c42, 0x3142, 0x3505, 0x33e9, 0xbe07, 0xb53e, 0xb609, 0x3b1d, 0xbd2b, 0x36e4, 0x3c8a, 0x36fb, 0x39e9, 0xb8c3,
0x3fba, 0x4295, 0x3766, 0xbf1a, 0x39e3, 0x3ca3, 0x3fc7, 0xb434, 0xb899, 0xbb95, 0x398e, 0xb2e3, 0xbcd6, 0xb5c8, 0x38c5, 0xb442,
0x3cf2, 0x407d, 0xb6e2, 0xb847, 0x3a6a, 0xbdcd, 0x34b0, 0xb342, 0x3a83, 0x2d94, 0x3e96, 0xb644, 0xbead, 0x3e5d, 0xb0bb, 0x39cd,
0xa92f, 0xba58, 0x3c0b, 0xbdf9, 0x39ad, 0xa459, 0x3e21, 0xbd5c, 0x3d83, 0x41c8, 0x3299, 0xbeb7, 0xb260, 0xbc3a, 0xb6c7, 0xb98c,
0x321a, 0x3d96, 0x3834, 0x3a6f, 0x3920, 0x3d35, 0x28a0, 0xbe28, 0xbe36, 0xb9db, 0xb7d3, 0xbbba, 0xbbd1, 0x357f, 0xbd91, 0xc114,
0xb5fd, 0xae9b, 0xc078, 0xb85b, 0xc123, 0xb4c3, 0x38b3, 0xb796, 0xbb1b, 0x3ab8, 0x33b3, 0x37e5, 0x1a62, 0x3a31, 0xb4f1, 0x3a67,
0xbbce, 0x3e7b, 0xb73c, 0xbc7c, 0x408e, 0x4098, 0xbe64, 0x342b, 0x3da6, 0x39c7, 0x4077, 0x1dea, 0xaf4e, 0x3c46, 0x3ebd, 0xbbe8,
0x3936, 0x3cd8, 0x402f, 0x3e99, 0x3c05, 0xb2d2, 0xbc89, 0xb1eb, 0x2dfa, 0x3d84, 0xbed9, 0xbb80, 0x38a5, 0xbb72, 0xbc2c, 0xb173,
0xb84d, 0xb35d, 0xb0ff, 0x3e9f, 0xbc79, 0x3b57, 0xbb5b, 0x307d, 0xb498, 0x3703, 0xbe4a, 0x38be, 0xb878, 0xab2e, 0x3b46, 0xbacc,
0x3ab4, 0x32d8, 0xc20b, 0x365b, 0x35ac, 0x36ed, 0x40e5, 0x2d1b, 0xb594, 0xb0f7, 0xba7a, 0xbe4c, 0xa99c, 0xb070, 0xb21f, 0x2dca,
0xbf8a, 0x3fd8, 0xb83e, 0x391b, 0xbc35, 0x330f, 0x34e7, 0xb698, 0xb482, 0x34c1, 0x36cd, 0xb818, 0x3e69, 0xb449, 0x3646, 0x31ab,
0x38c2, 0x341e, 0x3925, 0xb987, 0x38e5, 0x41b9, 0xb79d, 0xb1ac, 0x36c6, 0x38f9, 0xc103, 0xa977, 0xbead, 0xbce0, 0xbc63, 0xb897,
0x3f5d, 0xb842, 0x3d63, 0x3875, 0xab3a, 0xad0b, 0x25c0, 0xbcd6, 0x38d6, 0xb851, 0xb9a9, 0xc077, 0x3be3, 0xb4a1, 0xc293, 0x39c4,
0x32dc, 0x414b, 0x3ada, 0x38cc, 0xbad6, 0x3b60, 0x3a85, 0xb52e, 0x3d6c, 0x3d6d, 0xb5a4, 0xb855, 0x2ccf, 0x27f6, 0x35b1, 0xbcf6,
0x34df, 0xb4a0, 0xbe85, 0xb62a, 0x39d4, 0xad0d, 0xb542, 0xab88, 0x35dd, 0x345a, 0x353b, 0x3951, 0xb8f8, 0x2f10, 0xbaae, 0x363f,
0x3878, 0x3ca2, 0x35df, 0x38da, 0xb443, 0xbcfd, 0xb87e, 0x2fdb, 0xbc75, 0x36ab, 0x389a, 0x3243, 0x29dc, 0xba70, 0x2ee6, 0x3250,
0xb748, 0x3d29, 0x40a9, 0xbe21, 0xbba6, 0xb60d, 0xbbbc, 0x3c40, 0xb5dd, 0xbb7b, 0x2631, 0x3bf3, 0xbfbb, 0x2ad5, 0x35b7, 0xb417,
0xafde, 0x3831, 0xb651, 0x3145, 0x3cfa, 0xb23f, 0x39ff, 0xb56f, 0xbd12, 0x3f03, 0x33d8, 0x3623, 0x3401, 0x3e04, 0xbe9f, 0x3f6b,
0x30db, 0xa9d7, 0x31d9, 0xb34d, 0x9f5e, 0x3252, 0xc0f6, 0x3c75, 0x348d, 0xb8ec, 0x38d0, 0x3841, 0x3abf, 0x20a8, 0xc090, 0x2b97,
0xbf35, 0xac01, 0xb854, 0x3722, 0xc074, 0x344d, 0x3a91, 0x3972, 0xbe82, 0x39b9, 0xb62c, 0xc02a, 0xbb3a, 0xba61, 0x2fcb, 0x3a29,
0xba51, 0xbb4e, 0xb604, 0x3d17, 0x363e, 0x3b16, 0x3c14, 0x3ab9, 0xb80d, 0x3a9c, 0xb0df, 0x3936, 0xb50c, 0xb8ca, 0xbd85, 0x35f3,
0x2ffc, 0xb02b, 0xc0b9, 0x38fe, 0x390d, 0xba48, 0x408f, 0xbc03, 0xb937, 0x3646, 0xc22b, 0xc0c1, 0xbab4, 0xbad0, 0xb3f6, 0x99a8,
0xbc8c, 0xbf40, 0x2074, 0xbc80, 0xb927, 0xb89b, 0x33be, 0xa9e5, 0x417f, 0x3229, 0xb346, 0x353c, 0x395d, 0xb883, 0x3d69, 0xbadd,
0x3c6c, 0xa743, 0xbd97, 0x3466, 0xbf85, 0x3977, 0x3618, 0x3976, 0x3e77, 0xb9f8, 0xbe06, 0xc024, 0xbc84, 0x325a, 0xbb6c, 0x3d18,
0xb930, 0xbca2, 0xb806, 0xbfb2, 0x3578, 0xb253, 0xb48c, 0x33f1, 0xb9ac, 0xbb21, 0xb012, 0x374a, 0xb0cc, 0x3c0b, 0xaca9, 0x3dc8,
0xb4d9, 0x322c, 0xab2c, 0xb993, 0x3aa6, 0x3a91, 0x42a1, 0x3da6, 0x3151, 0x3e59, 0x3751, 0x2d8e, 0x3365, 0x2d9a, 0xbaaa, 0xb77f,
0xb7f0, 0x32ee, 0x3dd2, 0xbb78, 0x3d0e, 0xbe1c, 0xbe19, 0xbd05, 0xbcfe, 0xbebd, 0xbba1, 0x36b0, 0x3962, 0x4006, 0x380e, 0x370d,
0x3e08, 0x3b9c, 0x2bfe, 0xb2a8, 0x3dd4, 0xc038, 0xc00f, 0xb32c, 0x33b5, 0x39f3, 0x3691, 0xb893, 0xbb79, 0xac1f, 0x3d09, 0xbd82,
0xafcd, 0xb867, 0xc01c, 0xbbb5, 0xbbca, 0xb323, 0xb8d8, 0x3d5d, 0xbbda, 0x2db4, 0xb8ca, 0x38f9, 0xb615, 0x3a87, 0x321c, 0xc099,
0x3a26, 0x3f8c, 0x30a7, 0x36f1, 0x386f, 0xc2a5, 0xb485, 0xb157, 0xb4d2, 0x3f94, 0x2056, 0xb1bb, 0xbb33, 0x35db, 0x35b5, 0xba51,
0xbe3f, 0x845e, 0xb7cd, 0xbd67, 0x2dae, 0xb670, 0x399d, 0xc11f, 0x2c99, 0x378e, 0xb735, 0xbe92, 0x4021, 0x3c61, 0xba18, 0x34c2,
0xb993, 0xb927, 0xb98a, 0xb82a, 0xba9d, 0xbf68, 0xb507, 0xb7f9, 0x40e7, 0xb718, 0x1e42, 0x3cd3, 0x2b48, 0x3a82, 0x3ef1, 0xbf98,
0xb0ad, 0x3a56, 0x34a6, 0xbc12, 0x3fe4, 0x31d6, 0x3d63, 0xa315, 0x22f5, 0xb81a, 0x3b45, 0x32d7, 0x3e26, 0x3689, 0x3d81, 0xbc0c,
0x3d04, 0xbcd3, 0x36b2, 0xb5c8, 0x37bb, 0xb86b, 0xb658, 0x3c81, 0xb81b, 0xba20, 0x356a, 0xadad, 0xbe5d, 0x3048, 0xb9d4, 0x301d,
0xadb0, 0x3d2d, 0xaa8b, 0xb415, 0xb4b2, 0x413f, 0x3c3c, 0xb516, 0xaff4, 0x3572, 0xb682, 0xbbf6, 0xbbce, 0x3bd3, 0x3a19, 0x3d0a,
0x3729, 0x3592, 0xbc5f, 0x3a21, 0x3c5b, 0xb667, 0x3c4b, 0x38c7, 0x3180, 0xaecd, 0xbd82, 0xb9d9, 0xac5a, 0x36d1, 0xc22c, 0x2c34,
0xbcae, 0xb450, 0x3f37, 0x388f, 0xb698, 0xb5fd, 0x23d2, 0x3b4a, 0xb721, 0xae67, 0x3cbc, 0xab02, 0x39d8, 0xbd73, 0x98eb, 0xbaf1,
0x3ad1, 0x381e, 0xb864, 0xbc12, 0xc0e9, 0xc084, 0x3831, 0x3971, 0x3ca9, 0xb2fa, 0xa167, 0x3708, 0x405f, 0xb9ca, 0x3ca1, 0x31ad,
0x383f, 0x339d, 0x389a, 0x364f, 0xb77d, 0x3db4, 0xb56a, 0xb2bc, 0xba8f, 0xb4dd, 0xbf46, 0x32b6, 0x381e, 0xb90a, 0x3db5, 0xbf8a,
0xbc4e, 0x37b4, 0xbc0e, 0xad30, 0x3c84, 0x3d83, 0x3a52, 0x3a04, 0xbc64, 0x4027, 0x3c18, 0x3e6d, 0xbcce, 0xaf48, 0xb052, 0x325c,
0xb876, 0xbf1d, 0xbafa, 0xaf28, 0x3a5b, 0x3498, 0xaab7, 0xbc54, 0x3fdb, 0x3d7e, 0x39e0, 0xbf20, 0xbfc8, 0xaddc, 0xb815, 0xb83b,
0xb793, 0x3798, 0x3915, 0xb6c5, 0xbc75, 0x395b, 0x358f, 0xb960, 0xbc4a, 0xbced, 0xbb4c, 0x34c2, 0x3cfd, 0x2022, 0x2cce, 0x30cf,
0xb632, 0xbc4d, 0x3a35, 0x3308, 0x2f07, 0x38d2, 0xbc58, 0x3c45, 0xbae1, 0xb9ad, 0xbb37, 0x3910, 0xbf4b, 0xb91e, 0x374d, 0xb27e,
0xb59a, 0x367b, 0x3af6, 0x39fb, 0xbb7c, 0x3a2a, 0xbf2d, 0x2d37, 0xb489, 0x3803, 0x3fc6, 0xbdc6, 0x381d, 0x3fe4, 0x33f7, 0xb508,
0x4023, 0xbeb9, 0x3d4c, 0xb0c6, 0xb9aa, 0x38c5, 0xb65d, 0x360a, 0xbd31, 0x3ad7, 0x3f3e, 0x39bf, 0xbc24, 0xb920, 0x3774, 0xb7a3,
0xafd2, 0xbcb9, 0xb627, 0x387a, 0xb7cc, 0x38cb, 0xaf26, 0xb37e, 0xb2c5, 0xbad1, 0xb881, 0xb982, 0xbe79, 0xbf5f, 0xb58c, 0x3cb6,
0xb76a, 0xc084, 0x3888, 0x305f, 0x4386, 0xbb1c, 0x318f, 0x2990, 0xbc45, 0xb415, 0xbd45, 0x3b9a, 0x400b, 0xb6c7, 0x40d8, 0x3f49,
0x3b3e, 0x3953, 0x4121, 0x41a5, 0x3e15, 0x3a86, 0xb745, 0xb50c, 0x394d, 0xbc62, 0x3ce8, 0x36fd, 0xb3fe, 0xb7d3, 0x320d, 0x3663,
0x38fd, 0x39e8, 0xb2dd, 0x38c0, 0x3992, 0xb516, 0xb019, 0xbc1f, 0x35e3, 0xa8c6, 0x3fda, 0x3975, 0x3dba, 0xc0dd, 0x166a, 0x3863,
0xa3cd, 0x3ab2, 0x332f, 0xbcb9, 0xbce3, 0xb88e, 0xbd5e, 0x41f6, 0xba72, 0xbd0a, 0xbac9, 0xc170, 0xbc26, 0xb615, 0xbab0, 0xbca7,
0xc082, 0xbb6c, 0x3f5b, 0x415e, 0x3be8, 0xbe9b, 0x3c55, 0x3f32, 0xa521, 0x410a, 0xbf27, 0xbe1e, 0xbca8, 0x39df, 0xb924, 0xbbf5,
0xb2aa, 0x39c7, 0x3af7, 0x424b, 0xb4c6, 0xaed0, 0x358e, 0x3532, 0x3116, 0x3924, 0xbee5, 0xc199, 0xba6e, 0x3849, 0x3c77, 0xb920,
0x3c82, 0xb481, 0x33de, 0x3c4e, 0xba98, 0x3775, 0xb594, 0x96a7, 0xbd85, 0x4000, 0x2fd0, 0x3fd8, 0x3d71, 0x3bb7, 0x3dc5, 0x3808,
0xbc1c, 0x34a8, 0x3d3d, 0xb86c, 0x3bf1, 0x3841, 0x399c, 0xb9d3, 0xbcee, 0xb752, 0x3ab9, 0xb00a, 0xb744, 0x3198, 0x2fcd, 0x398f,
0x9a32, 0x3d75, 0x360a, 0x3bbc, 0x37e9, 0xbb59, 0xb969, 0xb330, 0xc0a5, 0x3ae6, 0x3e0c, 0x40b0, 0xbcda, 0x343c, 0x34bc, 0xb86c,
0x3cb0, 0x35be, 0xbd82, 0xac1b, 0xbb08, 0xa5a7, 0x34bf, 0xb0f5, 0x3087, 0xb485, 0xa123, 0xbb9c, 0x3df9, 0xb45d, 0x3c17, 0x404c,
0x347a, 0x39a3, 0xb6e8, 0xb913, 0xbd20, 0x38ce, 0xc006, 0x40b0, 0x402a, 0xbb4d, 0x3e7d, 0x3e49, 0x3b8b, 0xb6c8, 0x2d82, 0x3b90,
0x388d, 0xae29, 0x327b, 0x3ad7, 0x3d10, 0xb984, 0x3933, 0x34cc, 0x3002, 0xbbda, 0xbcf3, 0x3819, 0x2c89, 0xbc31, 0x3dbd, 0x38e8,
0xb4e4, 0xbb87, 0xb172, 0x3886, 0x39b9, 0xb829, 0xbd54, 0xb345, 0xb951, 0xba7f, 0x3d9f, 0x36c1, 0xb259, 0x3dd3, 0x3a49, 0x36a4,
0x3b65, 0x3cf2, 0xacae, 0xbe2c, 0xbdae, 0x3ba3, 0x356a, 0x3603, 0x3d0e, 0x3370, 0xb96b, 0x2d88, 0xb8d3, 0x36e3, 0xb804, 0x3b24,
0xc000, 0xbdd0, 0xc006, 0xb8c7, 0x3dc9, 0x3367, 0xb663, 0x344b, 0x3406, 0x341f, 0xac64, 0xc0cf, 0x34c6, 0x3d02, 0x3676, 0x39f8,
0xa4b0, 0x2e04, 0xb4ee, 0x3b5f, 0xbb6d, 0x37d4, 0xb0cc, 0xb491, 0xb1aa, 0xacc8, 0xbea5, 0x3c6c, 0xb99e, 0xbc46, 0xbe17, 0x3b6c,
0xbd5d, 0xbf93, 0xb462, 0x38fa, 0xc0e4, 0x331f, 0x3419, 0x3164, 0xbb25, 0x4066, 0xbd61, 0xbe28, 0x3891, 0xbc66, 0x32be, 0xbc0c,
0x3055, 0x3dee, 0x20f7, 0xb3ab, 0x31ff, 0x3a50, 0xbe6a, 0xbad6, 0xbb8f, 0x3cb5, 0xbe0a, 0x3e97, 0x3110, 0xbc8b, 0x36cb, 0x3c1b,
0xbb83, 0xbe5f, 0xaecd, 0x310b, 0xb4b8, 0x2985, 0x3c4a, 0xb9d9, 0x39c5, 0xbc1d, 0x390b, 0x3d9e, 0x3675, 0xbca4, 0x3ce1, 0xb49c,
0xbb08, 0x3fff, 0x3927, 0x35e3, 0xbd50, 0xbc60, 0x39b6, 0xbd13, 0x4123, 0xc2a2, 0xbeab, 0x37d9, 0xb8ed, 0x3425, 0xbace, 0x3a36,
0xb0c7, 0x4057, 0x3c69, 0x3e0c, 0xb5b0, 0x3a03, 0xba05, 0xbaa0, 0x19c4, 0x9c4c, 0xb72f, 0x3c37, 0x3467, 0xbd02, 0xb522, 0xb537,
0x3673, 0x2c4d, 0xb17b, 0xbdef, 0xb95a, 0x3daa, 0xbbe8, 0xb4e3, 0x3034, 0xbb3a, 0xc116, 0xbd9c, 0x3891, 0xc1d5, 0xbd9f, 0xb874,
0xbc4b, 0x357f, 0xb09a, 0x3f79, 0x3f0c, 0xc07e, 0xbbfe, 0xbca2, 0xbb50, 0x2af5, 0xb02f, 0xbaf7, 0xb629, 0xb509, 0x39c8, 0x36fc,
0xa825, 0x395c, 0xb901, 0x3553, 0xbd9d, 0xbbeb, 0x39f2, 0xb451, 0x37bc, 0x3f3c, 0x35a3, 0x3866, 0x3046, 0x35fb, 0x3999, 0xbcb3,
0xa417, 0x3d1d, 0xbc37, 0x3bec, 0x3c7c, 0x3bfa, 0xbcb8, 0xc1d5, 0x3c1a, 0x3c40, 0xb23c, 0xb73b, 0x3546, 0x3a09, 0xbbf5, 0xbb7f,
0x30e8, 0xbe3f, 0x39fe, 0x3a8b, 0x341a, 0x9b02, 0xbc35, 0x2b91, 0x4256, 0x3a51, 0x3fd1, 0xba43, 0xb55c, 0x393a, 0x3c6f, 0xae6a,
0x3da8, 0xb266, 0xbd17, 0xba78, 0x35cf, 0x3e3a, 0xb5dd, 0x3e4d, 0x345d, 0x32ff, 0xbca2, 0x35a2, 0xb9f1, 0x3c82, 0xbbc5, 0x38f1,
0x3f36, 0xbe7b, 0xbe77, 0xb44a, 0xbd3b, 0x3501, 0x344c, 0xbe42, 0xbc81, 0x3dc3, 0x2613, 0xbf15, 0xbb1c, 0x3c71, 0x345f, 0xba6a,
0xb944, 0x3c03, 0xb5ea, 0xbae1, 0xab67, 0x3e77, 0xc04f, 0xb9db, 0xbe0c, 0xb86e, 0xbc4f, 0xb9cd, 0x3ca8, 0xb07a, 0x36be, 0xb41f,
0xac27, 0x3256, 0x3870, 0xb327, 0xb5f6, 0x3b9d, 0x30ba, 0xb8de, 0x3c1b, 0xb06a, 0x3ae1, 0x3d54, 0xba28, 0x3d08, 0x38a3, 0xb938,
0x3472, 0xb96b, 0x3945, 0x3b80, 0xadbe, 0x3ab1, 0x3ccf, 0x39b5, 0x34a8, 0x3836, 0xb49e, 0x308c, 0x3916, 0xb5ba, 0xbb8a, 0x3b1b,
0xbc56, 0xbe6f, 0xbd9e, 0xb4d5, 0x3e83, 0xa343, 0x3adc, 0xb2fc, 0xba2f, 0x3b55, 0x3cec, 0xb624, 0x261f, 0x37d7, 0xbf76, 0x3eb1,
0x38b1, 0xb9c8, 0xa60d, 0x361c, 0xbca6, 0xc00c, 0xbb55, 0xbc6b, 0x34c5, 0x38ba, 0xb802, 0x383c, 0xbd59, 0x3e68, 0x3a2e, 0xbbad,
0x3c74, 0x3b24, 0x3010, 0x3ebf, 0xb953, 0xbfa8, 0xb16b, 0x3b7c, 0x3952, 0x2c82, 0xb8ef, 0x412c, 0xb7ec, 0x3cdb, 0x3bc9, 0x38e0,
0xbbfb, 0xbaa3, 0x3f28, 0xb1df, 0x3a77, 0xbccf, 0xb1a5, 0xb933, 0x3018, 0x37cb, 0xbec0, 0x31bc, 0xbd2e, 0x3997, 0x3930, 0x3906,
0xb86f, 0x37fd, 0x323d, 0x33e5, 0xa60a, 0x38d7, 0xb30a, 0xb451, 0x3597, 0x3123, 0xc063, 0xbe8a, 0xbe42, 0x37af, 0xaff0, 0x3b21,
0x365f, 0xb277, 0xb5b8, 0x2ad2, 0xc11d, 0x3a45, 0x31fd, 0xb500, 0xbf3f, 0xbc72, 0x3038, 0x24a3, 0x2890, 0xb595, 0xc08f, 0xc1c7,
0xb86e, 0xbcaa, 0x3189, 0x38a6, 0xb408, 0x325d, 0x2ca7, 0x3b05, 0x3c55, 0xbf35, 0x387c, 0x3b7e, 0x3c20, 0x3a0b, 0x3741, 0x3db8,
0x3a12, 0x3c4d, 0xb87c, 0x3d11, 0xbdc9, 0xbed7, 0x2444, 0xbdbb, 0xb9c6, 0x3cc9, 0xae72, 0xba10, 0x38b7, 0x3953, 0xb1e6, 0xbbe2,
0xa918, 0x30b1, 0xbc8f, 0x283d, 0xaeb3, 0xb160, 0x3794, 0x3336, 0x3327, 0x401d, 0xbf99, 0x3d15, 0xad02, 0x3a32, 0x3df6, 0x3c57,
0xbef4, 0x34ed, 0xbc1f, 0x368c, 0x3aed, 0xb95b, 0x38dd, 0x3bf3, 0x4185, 0x3c2f, 0xbbfc, 0x37b5, 0x37f3, 0x355e, 0x3559, 0x3c46,
0xc003, 0x38bc, 0x3b53, 0xbda0, 0xac8d, 0x2acb, 0xb8ac, 0x396c, 0x2be0, 0xbb1f, 0x3ce8, 0x3b90, 0xae9f, 0x3ef8, 0xb33e, 0x3cf4,
0x2c97, 0xb898, 0xbaa5, 0x3f56, 0x3e58, 0xbb16, 0xb33c, 0xc004, 0x400e, 0xbc68, 0x38bd, 0xa939, 0x3a55, 0x3b35, 0x40d6, 0x3db5,
0x4176, 0xb869, 0x30ba, 0xbd7f, 0xba99, 0xb379, 0x3ecf, 0xb915, 0xb19f, 0x30f2, 0x3e11, 0xb632, 0xbe94, 0x3be5, 0x3d28, 0xac5d,
0xb6e7, 0xbb64, 0xb282, 0x4380, 0xbde1, 0x36b5, 0x36c2, 0x3867, 0x3cca, 0x2e1c, 0x31cc, 0x2e2f, 0xb0d4, 0xbcff, 0xbb1c, 0xbd67,
0x309a, 0x3d2c, 0xab7d, 0xbd03, 0xbbe1, 0xbefc, 0xbfbe, 0x3b98, 0xb53c, 0xbc72, 0x2f15, 0x3cca, 0xc106, 0xbc36, 0xb702, 0x3b57,
0x391a, 0xb4da, 0x3861, 0x3afe, 0x3ea8, 0x335b, 0x34e4, 0xbd62, 0x3f1f, 0xbc86, 0xbcf4, 0x35bc, 0xb34a, 0xbf53, 0x3834, 0xbd10,
0x273d, 0x39a1, 0xb839, 0xb4e4, 0x39b8, 0x34da, 0xbed6, 0x3a76, 0x3c50, 0xc0fa, 0xbd35, 0xb061, 0xb1b6, 0x34f0, 0x3ab1, 0xbc18,
0xb91d, 0xb62c, 0xbb36, 0xb829, 0xb940, 0xafab, 0x3d46, 0x3e81, 0xb20b, 0xb822, 0xbe39, 0x35fd, 0x32f1, 0x3966, 0x2e17, 0xb543,
0xbbed, 0x3a89, 0xb2a3, 0xbcc5, 0x3369, 0xb42b, 0xbbd4, 0x1f58, 0xbc48, 0x3ef4, 0x3bbe, 0xac2b, 0xbdf5, 0xb2e4, 0xbcae, 0x3f94,
0xa11a, 0xc068, 0x35bb, 0xb82e, 0x3f77, 0xbbb9, 0xb386, 0x3b46, 0xb675, 0x22f3, 0x3e8b, 0xbcb2, 0xb8ba, 0xba29, 0x4235, 0xbd08,
0x1038, 0x3f9f, 0xade8, 0x399f, 0x3363, 0xb9da, 0x3909, 0x37c8, 0x3c82, 0xbc4c, 0xbc3a, 0xb788, 0xa897, 0x39da, 0xb6d2, 0x3bee,
};
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2026 Peasant Smith and the Project Maya contributors
Copyright (c) 2026 Niko1221 and the Strata contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+15
View File
@@ -0,0 +1,15 @@
# Project Maya (maya-ds4), DeepSeek-V4.1 engine
The files under `src/dsv41/`, `include/strata/dsv41/`, `tests/dsv41/` and `tools/dsv41/` come from
https://github.com/mw00/project-maya (release v1.1.17, commit 8d9a9b5d), its DeepSeek engine `src/ds4`, `tests/ds4_*`,
`tools/ds4` and the kernel sources it builds on (`exl3`, `sampler`). Project Maya is itself built on Strata.
Copyright (c) 2026 Peasant Smith (mw00) and the Project Maya contributors, including needmorevram.
MIT License, the full text is in `LICENSE` beside this file. The notice stays with every copy.
Changes made while porting into Strata are listed in the git history of the `src/dsv41` directory
(the first commit of each file is the unmodified upstream copy).
Later changes taken from Project Maya releases v1.1.18 to v1.1.26 (the same approach re-written onto Strata's engine,
for example the long-prompt layer skip, the thinking budget, conversation slots) are covered by the same copyright
and permission notice, in `LICENSE` beside this file.
+901
View File
@@ -0,0 +1,901 @@
# 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.
"""tools/ds4/pack_gguf.py - the engine's pack for a DeepSeek-V4.1 GGUF (unsloth's DeepSeek-V4.1-Flash-1017 UD-Q8_K_XL
and the like: dense BF16, routed experts MXFP4, Engram tables MXFP8 or Q6_K), beside the model's files (no weights
copied).
python tools/ds4/pack_gguf.py --model ~/models/DeepSeek-V4.1-Flash-1017-GGUF/UD-Q8_K_XL
writes <model>/maya-ds4/ in pack.py's format, so the engine reads both:
ds4.txt the geometry under config.json's names (the GGUF's deepseek41.* keys translated), model_dir, format gguf
tensors.txt every tensor under the checkpoint's names: `file <i> <name>` lines, then
`t <name> <dtype> <file> <offset> <bytes> <dims...>` - dims outermost first (torch order: a matrix is
[out][in]), dtype BF16 / F32 / MXFP4 / MXFP8 (ggml's block layouts, 32 values a block); the routed
experts as one tensor a layer and role ([n_exp][out][in])
engram.bin the Engram hash tables, from the GGUF's metadata (pack.py's layout; no tokenizers package needed)
tokenizer/ the server's tokenizer from the GGUF's vocabulary and merges (pre "deepseek3"), and its chat template
A GGUF has no DSpark drafter: drafter_pack.py makes it from DeepSeek's checkpoint into ../dspark/, and the pack takes it
from there when it is present. Nor a vision tower: vision_pack.py makes it from DeepSeek's checkpoint into ../vision/
(--vision: another folder), and the pack takes it and its geometry (vision.<key>, image_token_id) from there when it is
present; without it the engine reads text only.
A quant that leaves the two Engram tables out (v1.1.16's Maya-S; Maya's quants hold them since) takes them from a set
of GGUF files that holds them, beside it: --engram, else ../Engram/ (unsloth's MXFP8 shard of them, where setups before
v1.1.17 put it) when it is whole.
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import re
import struct
import sys
TYPES = {0: ("F32", 1, 4), 1: ("F16", 1, 2), 8: ("Q8_0", 32, 34), 30: ("BF16", 1, 2), 39: ("MXFP4", 32, 17),
67: ("MXFP8", 32, 33), # ggml type -> (name, values a block, bytes a block); 67: unsloth's fork
43: ("MXFP8", 32, 33), # llama.cpp's own id (unsloth's GGUFs from 2026-10-19 on)
# the low-bit expert types (the Maya quants' experts; the engine's ds4_iq kernels)
10: ("Q2_K", 256, 84), 11: ("Q3_K", 256, 110), 12: ("Q4_K", 256, 144), 13: ("Q5_K", 256, 176),
14: ("Q6_K", 256, 210), 16: ("IQ2_XXS", 256, 66), 17: ("IQ2_XS", 256, 74), 18: ("IQ3_XXS", 256, 98),
20: ("IQ4_NL", 32, 18), 21: ("IQ3_S", 256, 110), 22: ("IQ2_S", 256, 82), 23: ("IQ4_XS", 256, 136),
# the two 1.x-bit types the IST-DAS 2.00 set uses: device kernels since 2026-10-23 (ds4_iq.cu), so packs with
# them load and run entirely on the card. (The integer metadata tensors - engram_token_map and the like - stay
# OUT of this table on purpose: the pack tool skips a tensor whose type it does not know, which is exactly right
# for them, and adding them here made them "unmapped" instead.)
19: ("IQ1_S", 256, 50), 29: ("IQ1_M", 256, 56),
# the trellis types (tools/trellis/tqenc.hpp; 145 / 146 are the agentionai fork's ggml ids, 224-227 Strata's own)
145: ("TQK6", 128, 26), 146: ("TQK7", 128, 30), 224: ("TQK5X", 128, 22), 225: ("TQK4X", 128, 18),
226: ("TQK5T", 128, 22), 227: ("TQK4T", 128, 18)}
# the Engram set a quant without the tables takes them from by default, beside it (or inside its folder): unsloth's
# MXFP8 shard of them, where setups before v1.1.17 put it for Maya-S (--engram: any other)
ENGRAM_SETS = ("Engram",)
class Gguf:
"""One GGUF shard's metadata and tensor infos (offsets absolute in the file)."""
def __init__(self, path: pathlib.Path):
self.path = path
with path.open("rb") as f:
self.f = f
magic = f.read(4)
if magic != b"GGUF":
raise SystemExit("%s: not a GGUF file" % path)
self.version, nt, nkv = struct.unpack("<IQQ", f.read(20))
self.kv = {}
for _ in range(nkv):
k = self._str()
self.kv[k] = self._val(struct.unpack("<I", f.read(4))[0])
self.tensors = []
for _ in range(nt):
name = self._str()
nd = struct.unpack("<I", f.read(4))[0]
dims = list(struct.unpack("<%dQ" % nd, f.read(8 * nd)))
typ, off = struct.unpack("<IQ", f.read(12))
self.tensors.append((name, typ, dims, off))
align = int(self.kv.get("general.alignment", 32))
pos = f.tell()
self.data_start = (pos + align - 1) // align * align
del self.f
def _str(self):
n = struct.unpack("<Q", self.f.read(8))[0]
return self.f.read(n).decode("utf-8", "replace")
def _val(self, t):
fmt = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"}
if t in fmt:
n = struct.calcsize(fmt[t])
return struct.unpack("<" + fmt[t], self.f.read(n))[0]
if t == 8:
return self._str()
if t == 9:
at, n = struct.unpack("<IQ", self.f.read(12))
if at in fmt:
n_b = struct.calcsize(fmt[at])
return list(struct.unpack("<%d%s" % (n, fmt[at]), self.f.read(n * n_b)))
return [self._val(at) for _ in range(n)]
raise SystemExit("%s: metadata type %d" % (self.path, t))
# GGUF name (blk.N. stripped) -> the checkpoint's name under layers.N. (pack.py / the engine)
LAYER = {
"attn_norm.weight": "attn_norm.weight",
"attn_sinks.weight": "attn.attn_sink",
"attn_q_a.weight": "attn.wq_a.weight",
"attn_q_a_norm.weight": "attn.q_norm.weight",
"attn_q_b.weight": "attn.wq_b.weight",
"attn_kv.weight": "attn.wkv.weight",
"attn_kv_a_norm.weight": "attn.kv_norm.weight",
"attn_output_a.weight": "attn.wo_a.slice", # one entry a group (the engine's slices)
"attn_output_b.weight": "attn.wo_b.weight",
"attn_compressor_kv.weight": "attn.compressor.wkv.weight",
"attn_compressor_gate.weight": "attn.compressor.wgate.weight",
"attn_compressor_norm.weight": "attn.compressor.norm.weight",
"indexer.attn_q_b.weight": "attn.indexer.wq_b.weight",
"indexer.attn_k.weight": "attn.indexer.wk.weight",
"indexer.k_norm.weight": "attn.indexer.k_norm.weight",
"indexer.proj.weight": "attn.indexer.weights_proj.weight",
"hc_attn_fn.weight": "hc_attn_fn",
"hc_attn_base.weight": "hc_attn_base",
"hc_attn_scale.weight": "hc_attn_scale",
"hc_ffn_fn.weight": "hc_ffn_fn",
"hc_ffn_base.weight": "hc_ffn_base",
"hc_ffn_scale.weight": "hc_ffn_scale",
"ffn_norm.weight": "ffn_norm.weight",
"ffn_gate_inp.weight": "ffn.gate.weight",
"exp_probs_b.bias": "ffn.gate.bias",
"exp_probs_b_vl.bias": "ffn.gate.bias_vl",
"ffn_gate_shexp.weight": "ffn.shared_experts.w1.weight",
"ffn_up_shexp.weight": "ffn.shared_experts.w3.weight",
"ffn_down_shexp.weight": "ffn.shared_experts.w2.weight",
"ffn_gate_exps.weight": "ffn.experts.w1", # [n_exp][ff][dim]: one entry an expert
"ffn_up_exps.weight": "ffn.experts.w3",
"ffn_down_exps.weight": "ffn.experts.w2", # [n_exp][dim][ff]
"engram_embd.weight": "engram.embed.weight",
"engram_kv.weight": "engram.wkv.weight",
"engram_gate.weight": "engram.gate.weight", # q_weight * k_weight, folded by the converter
# the IST-DAS sets keep q and k apart (the engine multiplies them at load) and the projection as engram_wkv
"engram_wkv.weight": "engram.wkv.weight",
"engram_q.weight": "engram.q_weight",
"engram_k.weight": "engram.k_weight",
}
GLOBAL = {"token_embd.weight": "embed.weight", "output_norm.weight": "norm.weight", "output.weight": "head.weight"}
ALIASES = {
# the same quantity under another key: llama.cpp's / unsloth's spelling -> the alternative (the IST-DAS sets write
# the engine's own names into the GGUF and keep deepseek41.engram_* instead of the dotted Engram keys)
"attention.kv_source_layers": ("kv_source_layer_ids",),
"attention.indexer.source_layers": ("index_source_layer_ids",),
"attention.indexer.candidate_source_layer": ("attention.candidate_source_layer_id",),
"attention.indexer.candidate_top_k_blocks": ("attention.candidate_topk_blocks",),
"attention.indexer.candidate_block_size": ("attention.candidate_block_size",),
"dspark.target_layers": ("dspark_target_layer_ids",),
"dspark.block_size": ("dspark_block_size",),
"dspark.noise_token_id": ("dspark_noise_token_id",),
"dspark.markov_rank": ("dspark_markov_rank",),
"dspark.expert_count": ("dspark_n_routed_experts",),
"dspark.expert_used_count": ("dspark_num_experts_per_tok",),
"engram.layers": ("engram_layer_ids",),
}
def geometry(kv: dict, vocab: int) -> dict:
"""config.json's text_config names (what the engine reads) from the GGUF's deepseek41.* keys."""
a = kv["general.architecture"]
def g(k, d=None):
v = kv.get("%s.%s" % (a, k))
if v is None:
for alt in ALIASES.get(k, ()):
v = kv.get("%s.%s" % (a, alt))
if v is not None:
break
return d if v is None else v
nl = g("block_count")
ratios = list(g("attention.compress_ratios", []))
out = {
"vocab_size": vocab,
"hidden_size": g("embedding_length"),
"num_hidden_layers": nl,
"num_attention_heads": g("attention.head_count"),
"head_dim": g("attention.key_length"),
"qk_rope_head_dim": g("rope.dimension_count"),
"q_lora_rank": g("attention.q_lora_rank"),
"o_lora_rank": g("attention.output_lora_rank"),
"o_groups": g("attention.output_group_count"),
"n_routed_experts": g("expert_count"),
"num_experts_per_tok": g("expert_used_count"),
"moe_intermediate_size": g("expert_feed_forward_length"),
"sliding_window": g("attention.sliding_window"),
"hc_mult": g("hyper_connection.count"),
"hc_sinkhorn_iters": g("hyper_connection.sinkhorn_iterations"),
"hc_eps": g("hyper_connection.epsilon"),
"index_n_heads": g("attention.indexer.head_count"),
"index_head_dim": g("attention.indexer.key_length"),
"index_topk": g("attention.indexer.top_k"),
"candidate_source_layer_id": g("attention.indexer.candidate_source_layer"),
"candidate_topk_blocks": g("attention.indexer.candidate_top_k_blocks"),
"candidate_block_size": g("attention.indexer.candidate_block_size"),
"rope_scaling.original_max_position_embeddings": g("rope.scaling.original_context_length"),
"rope_scaling.factor": g("rope.scaling.factor"),
"rope_scaling.beta_fast": g("rope.scaling.yarn_beta_fast"),
"rope_scaling.beta_slow": g("rope.scaling.yarn_beta_slow"),
"eos_token_id": kv.get("tokenizer.ggml.eos_token_id", 1),
"rms_norm_eps": g("attention.layer_norm_rms_epsilon"),
"routed_scaling_factor": g("expert_weights_scale"),
"swiglu_limit": (g("swiglu_clamp_exp") or [0.0])[0],
"rope_theta": g("rope.freq_base"),
"compress_rope_theta": g("attention.compress_rope_freq_base"),
"compress_ratios": ratios,
"kv_source_layer_ids": list(g("attention.kv_source_layers", [])),
"index_source_layer_ids": list(g("attention.indexer.source_layers", [])),
"engram_layer_ids": list(g("engram.layers", [])),
"max_position_embeddings": g("context_length"),
"dspark_block_size": g("dspark.block_size", 0),
"dspark_noise_token_id": g("dspark.noise_token_id", 0),
"dspark_markov_rank": g("dspark.markov_rank", 0),
"dspark_n_routed_experts": g("dspark.expert_count", 0),
"dspark_num_experts_per_tok": g("dspark.expert_used_count", 0),
"dspark_target_layer_ids": list(g("dspark.target_layers", [])),
}
clamp = g("swiglu_clamp_exp") or []
if clamp and any(abs(c - clamp[0]) > 1e-6 for c in clamp):
raise SystemExit("swiglu_clamp_exp differs between layers %s: the engine takes one swiglu_limit" % clamp[:8])
return out
def ple_to_engram(kv: dict):
"""llama.cpp's own names for the Engram metadata (unsloth's GGUFs from 2026-10-19 on: ple.*, the hash heads' offsets
counted across the layers' tables) -> the engram.* keys this pack reads (each layer's offsets from its own table)."""
a = kv.get("general.architecture")
g = lambda k, d=None: kv.get("%s.%s" % (a, k), d) # noqa: E731
if g("engram.layers") or not g("ple.layers"):
return
layers, ngram, heads = list(g("ple.layers")), g("ple.ngram_size"), g("ple.heads_per_ngram")
offs, sizes = list(g("ple.head_offsets")), list(g("ple.head_vocab_sizes"))
cols = (ngram - 1) * heads
if len(offs) != len(layers) * cols or len(sizes) != len(offs):
raise SystemExit("ple: %d head offsets, %d sizes for %d layers x %d columns" %
(len(offs), len(sizes), len(layers), cols))
per, rows = [], []
for i in range(len(layers)):
o, s = offs[i * cols:(i + 1) * cols], sizes[i * cols:(i + 1) * cols]
per += [x - o[0] for x in o]
rows.append(o[-1] + s[-1] - o[0])
for k, v in (("layers", layers), ("max_ngram_size", ngram), ("head_count", heads),
("head_dim", g("embedding_length_per_layer_input")), ("multipliers", list(g("ple.layer_multipliers"))),
("primes", sizes), ("offsets", per), ("num_embeddings", rows)):
kv["%s.engram.%s" % (a, k)] = v
def int_tensors_to_engram(gs, kv: dict):
"""The IST-DAS sets carry the Engram's hash parameters as integer tensors of the first shard (engram_token_map I32,
engram_primes / engram_offsets / engram_multipliers I64, one row a layer) instead of metadata: read them into the
engram.* keys this pack reads (when the metadata does not have them already)."""
a = kv.get("general.architecture")
want = {"engram_token_map.weight": ("token_map", "i", 4), "engram_primes.weight": ("primes", "q", 8),
"engram_offsets.weight": ("offsets", "q", 8), "engram_multipliers.weight": ("multipliers", "q", 8)}
for g in gs:
for name, typ, dims, off in g.tensors:
if name not in want:
continue
key, fmt, sz = want[name]
if "%s.engram.%s" % (a, key) in kv:
continue
n = 1
for d in dims:
n *= d
with g.path.open("rb") as f:
f.seek(g.data_start + off)
kv["%s.engram.%s" % (a, key)] = list(struct.unpack("<%d%s" % (n, fmt), f.read(n * sz)))
# the IST-DAS spelling of the Engram's scalar keys -> the dotted ones this pack reads
for dotted, theirs in (("engram.layers", "engram.layer_ids"), ("engram.max_ngram_size", "engram_max_ngram_size"),
("engram.head_count", "engram_n_heads"), ("engram.head_dim", "engram_head_dim"),
("engram.pad_token_id", "engram_pad_token_id")):
if "%s.%s" % (a, dotted) not in kv and "%s.%s" % (a, theirs) in kv:
kv["%s.%s" % (a, dotted)] = kv["%s.%s" % (a, theirs)]
def split_ple(g: Gguf, kv: dict):
"""llama.cpp's one Engram tensor (per_layer_token_embd: every layer's table, one after the other) -> each layer's
own blk.N.engram_embd as the earlier GGUFs had it: the same bytes, read in place."""
a = kv["general.architecture"]
ple = [t for t in g.tensors if t[0] == "per_layer_token_embd.weight"]
if not ple:
return
name, typ, dims, off = ple[0]
layers, rows = kv.get("%s.engram.layers" % a, []), kv.get("%s.engram.num_embeddings" % a, [])
if len(dims) != 2 or typ not in TYPES or len(rows) != len(layers) or sum(rows) != dims[1]:
raise SystemExit("%s: %s %s does not split in the Engram layers %s of %s rows" % (g.path.name, name, dims, layers,
rows))
_, per, bpb = TYPES[typ]
row = dims[0] // per * bpb
parts, start = [], 0
for il, n in zip(layers, rows):
parts.append(("blk.%d.engram_embd.weight" % il, typ, [dims[0], n], off + start * row))
start += n
g.tensors = [t for t in g.tensors if t[0] != name] + parts
def short(g: Gguf):
"""Why a GGUF file is shorter than its own tensor directory says (a download still running), or None."""
need = g.data_start
for _, typ, dims, off in g.tensors:
if typ in TYPES:
_, per, bpb = TYPES[typ]
nel = 1
for d in dims:
nel *= d
need = max(need, g.data_start + off + nel // per * bpb)
have = g.path.stat().st_size
return None if have >= need else "%s: %d of %d bytes" % (g.path.name, have, need)
def is_engram_file(g) -> bool:
"""The Engram table's GGUF: general.architecture 'engram' (the first release) or 'deepseek41-engram' (ISTA-DASLab's final files)."""
arch = str(g.kv.get("general.architecture") or "")
return arch == "engram" or arch.endswith("-engram")
def model_kv(gs):
"""The metadata of the model: of the first group whose architecture IS deepseek41 - never an Engram file's, whatever order they come in."""
return next((g.kv for g in gs if g.kv.get("general.architecture") == "deepseek41"), None)
def engram_set(model: pathlib.Path, explicit: str | None):
"""The Engram tables' GGUF set for a quant that leaves them out: (its folder, its files read), or (None, []).
explicit (--engram): that folder, whole; else the first whole one of ENGRAM_SETS beside the quant or in its
folder - one not whole yet (its download still running) is passed over."""
dirs = ([pathlib.Path(explicit).expanduser().resolve()] if explicit else
[d for n in ENGRAM_SETS for d in (model / n, model.parent / n)])
for d in dirs:
paths = [d] if d.is_file() else sorted(d.glob("*.gguf")) if d.is_dir() else [] # (--engram: a folder, or the one file)
if not paths:
if explicit:
raise SystemExit("%s: no .gguf files (--engram: the folder of the Engram tables' GGUF set)" % d)
continue
try:
egs = [Gguf(p) for p in paths]
why = next((w for w in map(short, egs) if w), None)
except (Exception, SystemExit) as e: # noqa: BLE001 - a header cut short raises anything
why = str(e) or type(e).__name__
if why is None:
return d, egs
if explicit:
raise SystemExit("%s: not whole (%s)" % (d, why))
print("%s: not whole (%s) - not used" % (d, why))
return None, []
def write_engram(out: pathlib.Path, kv: dict, vocab: int):
a = kv["general.architecture"]
g = lambda k, d=None: kv.get("%s.%s" % (a, k), d) # noqa: E731
layers = list(g("engram.layers", []))
if not layers:
return 0, 0
ngram, heads, hd = g("engram.max_ngram_size"), g("engram.head_count"), g("engram.head_dim")
tm = list(g("engram.token_map"))
mult, primes, offs = list(g("engram.multipliers")), list(g("engram.primes")), list(g("engram.offsets"))
cols = (ngram - 1) * heads
nl = len(layers)
if len(mult) != nl * ngram or len(primes) != nl * cols or len(offs) != nl * cols:
raise SystemExit("engram: %d multipliers, %d primes, %d offsets for %d layers x %d columns (ngram %d)" %
(len(mult), len(primes), len(offs), nl, cols, ngram))
pad = int(tm[g("engram.pad_token_id")])
full = tm + [0] * max(0, vocab - len(tm))
with out.open("wb") as f:
f.write(struct.pack("<4s6i", b"DSE1", vocab, nl, ngram, heads, hd, pad))
f.write(struct.pack("<%di" % vocab, *full[:vocab]))
f.write(struct.pack("<%dq" % len(mult), *mult))
f.write(struct.pack("<%dq" % len(primes), *primes))
f.write(struct.pack("<%dq" % len(offs), *offs))
return nl, cols
def write_tokenizer(out: pathlib.Path, kv: dict, template: str | None):
tokens = kv["tokenizer.ggml.tokens"]
types = kv.get("tokenizer.ggml.token_type") or [1] * len(tokens)
merges = kv.get("tokenizer.ggml.merges") or []
if len(set(tokens)) != len(tokens):
raise SystemExit("the GGUF's vocabulary has duplicate token strings")
out.mkdir(parents=True, exist_ok=True)
(out / "vocab.json").write_text(json.dumps({t: i for i, t in enumerate(tokens)}, ensure_ascii=False),
encoding="utf-8")
(out / "merges.txt").write_text("\n".join(merges), encoding="utf-8")
(out / "token_type.json").write_text(json.dumps([int(t) for t in types]))
special = {"bos": int(kv.get("tokenizer.ggml.bos_token_id", 0)), "eos": int(kv.get("tokenizer.ggml.eos_token_id", 1)),
"pad": int(kv.get("tokenizer.ggml.padding_token_id", 2))}
(out / "tokenizer.json").write_text(json.dumps({"pre": "deepseek3", "special_ids": special}, indent=1))
if template:
(out / "chat_template.jinja").write_text(template, encoding="utf-8")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--model", required=True, help="the directory of the GGUF's shards")
ap.add_argument("--out", help="default: <model>/maya-ds4")
ap.add_argument("--vision", help="vision_pack.py's folder (default: <model>/../vision; taken when it is there)")
ap.add_argument("--dspark-gguf", help="unsloth's DSpark drafter GGUF (dspark-*-Q8_0.gguf, architecture dflash): its three "
"blocks become mtp.0-2 beside the trunk's tensors (default: the first dspark-*.gguf "
"in <model>/.. when there is one)")
ap.add_argument("--mmproj", help="unsloth's vision tower GGUF (mmproj-*.gguf, clip / deepseek41v): its tensors become the "
"checkpoint's vision.* / aligner.* (default: the first mmproj*.gguf in <model>/..)")
ap.add_argument("--tq-experts", nargs="+", help="folders tq_convert.py wrote (tq.json + tq-L<layer>.bin): the routed experts of the layers "
"listed there are read from it as trellis types (TQK5X ..), the others keep their MXFP4")
ap.add_argument("--dense-override", action="append", help="a folder dense_requant.py wrote (dense.json + dense.bin): its tensors replace the same-named "
"dense matrices of the GGUF (K-quants of the attention / shared experts)")
ap.add_argument("--override-experts", nargs="+", help="requantized GGUF folders, each DIR or DIR:roles (requant_gguf.py output): their routed experts replace the main "
"model's for --override-roles (gate,up,down) in --override-layers (default all): mixed-bit packs")
ap.add_argument("--override-roles", default="down")
ap.add_argument("--override-layers", default="")
ap.add_argument("--tq-layers", help="only these layers (comma list) of the --tq-experts folders")
ap.add_argument("--drafter", help="the DSpark drafter's .json (drafter_pack.py's; default <model>/../dspark/dspark.json)")
ap.add_argument("--dspark-noise-token", type=int, help="the drafter's noise token id (dspark_noise_token_id), for a quant "
"whose GGUF does not state it (the IST-DAS sets): DeepSeek-V4.1-Flash's is 128799")
ap.add_argument("--dspark-markov-rank", type=int, help="the markov head's rank (dspark_markov_rank); default: the drafter's "
"markov tensor shape")
ap.add_argument("--skip-tensors", help="a regex of the GGUF's tensor names to leave out (a --dense-override supplies them "
"instead): e.g. attn_output_a, for a quant that stores the grouped wo_a as one "
"interleaved 3-D tensor instead of o_groups matrices")
ap.add_argument("--engram", help="the folder of the Engram tables' GGUF set, for a quant that leaves them out "
"(default: <model>/../Engram, when it is whole)")
ap.add_argument("--engram-meta", help="a GGUF whose metadata carries the Engram's hash parameters (llama.cpp's ple.* / "
"engram.*: layers, head offsets, vocab sizes, multipliers, token map), for a quant whose own "
"shards leave them out (the IST-DAS sets name the Engram only in deepseek41.engram_* keys and "
"carry no token map); the tables themselves still come from --engram")
ap.add_argument("--shards", nargs="+", help="the GGUF's files in --model (default: every .gguf there - one "
"model's; the setup names them: a folder may hold an earlier layout)")
a = ap.parse_args()
model = pathlib.Path(a.model).expanduser().resolve()
out = pathlib.Path(a.out).expanduser() if a.out else model / "maya-ds4"
shards = [model / n for n in a.shards] if a.shards else sorted(model.glob("*.gguf"))
if not shards or not all(p.is_file() for p in shards):
raise SystemExit("%s: no .gguf files" % model if not shards else
"%s: not there" % next(p for p in shards if not p.is_file()))
gs = [Gguf(p) for p in shards]
if not a.shards: # a folder's *.gguf: the Engram table (architecture 'engram', today 'deepseek41-engram') is not a model shard
keep = [i for i, g in enumerate(gs) if not is_engram_file(g)]
shards, gs = [shards[i] for i in keep], [gs[i] for i in keep]
if not gs:
raise SystemExit("%s: no model shards (only an Engram table)" % model)
kv = model_kv(gs)
if kv is None:
arch = next((g.kv.get("general.architecture") for g in gs), None)
raise SystemExit("%s: not a DeepSeek-V4.1 GGUF (architecture %r)" % (model, arch))
split = int(kv.get("split.count", 1))
if split != len(shards):
counts = sorted({m.group(1) for m in (re.search(r"-of-(\d{5})\.gguf$", p.name) for p in shards) if m})
raise SystemExit("%s: %d of the %d shards are here" % (model, len(shards), split) if len(counts) < 2 else
"%s: the shards of more than one GGUF split (-of-%s): name the model's own with --shards" %
(model, ", -of-".join(counts)))
# a quant whose shards leave the Engram's metadata out (the IST-DAS sets: deepseek41.engram_* only, no token map):
# the hash parameters come from --engram-meta, a GGUF of the same model that still has llama.cpp's ple.* / engram.*
if a.engram_meta:
mg = Gguf(pathlib.Path(a.engram_meta).expanduser().resolve())
for k, v in mg.kv.items():
if ".engram." in k or ".ple." in k or k.endswith(".embedding_length_per_layer_input"):
kv.setdefault(k, v)
ple_to_engram(kv)
for g in gs:
split_ple(g, kv)
# the Engram tables may come from a shared set of GGUF files beside the quant (the same tensor names: engram_set) -
# its engram tensors fill in the ones the quant's shards leave out, its engram metadata too. v1.1.16's Maya-S:
# unsloth's UD-Q8_K_XL shard that holds only the tables, as it is (00008 of 9; before 2026-10-19 shards 00008 and
# 00009 of 10, a table each), so no shard count is checked - every Engram layer's tables must be found, below.
# Looked for only when the quant's shards leave some out.
have = {t[0] for g in gs for t in g.tensors}
arch = kv["general.architecture"]
int_tensors_to_engram(gs, kv)
layers = kv.get("%s.engram.layers" % arch, [])
# An official IST-DAS set (helcig/tmp-oct26-2) carries the Engram gate/kv as their own k, q, wkv tensors and a 3-D attn_output_a, and the
# plain recipe (--engram --engram-meta --dspark-gguf, no --skip-tensors, no --dense-override) packs them as they are. Rebuilding them
# (engram_fold.py + a wo_a override) gave a pack with garbage output on the final 2.00 set (P2003, 2026-10-23), and the pack still loads,
# so it fails in the user's chat, not at install. Say so before it is built.
if any(n.endswith(".engram_wkv.weight") for n in have) and (a.skip_tensors or a.dense_override):
sys.stderr.write("pack_gguf: WARNING: this looks like an official IST-DAS set (it has engram_k/q/wkv tensors) and --skip-tensors / "
"--dense-override are used. The official sets pack correctly WITHOUT them; a pack rebuilt with them produced "
"garbage text on the final 2.00 set. Drop both unless you are testing exactly that.\n")
def has_part(il, part, names):
if "blk.%d.%s.weight" % (il, part) in names:
return True
if part == "engram_kv":
return "blk.%d.engram_wkv.weight" % il in names
if part == "engram_gate":
return "blk.%d.engram_q.weight" % il in names and "blk.%d.engram_k.weight" % il in names
return False
lacking = not layers or any(not has_part(il, part, have)
for il in layers for part in ("engram_embd", "engram_kv", "engram_gate"))
eg_dir, egs = engram_set(model, a.engram) if lacking or a.engram else (None, [])
eg_from = {}
if eg_dir is not None:
eshards = [g.path for g in egs]
for g in egs:
for k, v in g.kv.items():
if ".engram." in k or ".ple." in k or k.endswith(".embedding_length_per_layer_input"):
kv.setdefault(k, v)
ple_to_engram(kv)
for g in egs:
split_ple(g, kv)
for p, g in zip(eshards, egs):
picked = [t for t in g.tensors if re.match(r"blk\.\d+\.engram_", t[0]) and t[0] not in have]
picked = [t for t in picked if t[0].endswith("engram_embd.weight") or not has_part(
int(t[0].split(".")[1]), "engram_kv" if t[0].endswith("engram_kv.weight") else "engram_gate", have)]
if picked:
g.tensors = picked
eg_from[p] = g
# what the --dense-override folders supply: a tensor they provide is not "missing" here even though neither the quant's
# shards nor an Engram set carry it (engram_fold.py supplies the Engram gate and kv from the quant's own k/q/wkv, 2026-10-23)
# the GGUF part names -> the engine's names (LAYER maps "engram_kv.weight" -> "engram.kv.weight")
ov_names = set()
for dsrc in (a.dense_override or []):
try:
ov_names |= set(json.loads((pathlib.Path(dsrc).expanduser().resolve() / "dense.json").read_text()).keys())
except (OSError, ValueError):
pass
for il in kv.get("%s.engram.layers" % arch, []):
for part in ("engram_embd", "engram_kv", "engram_gate"):
nm = "blk.%d.%s.weight" % (il, part)
# a dense override names tensors the way the pack does, not the way the GGUF does
eng_nm = "layers.%d.%s" % (il, LAYER[part + ".weight"])
if (not has_part(il, part, have) and eng_nm not in ov_names
and not any(t[0] == nm for g in eg_from.values() for t in g.tensors)):
raise SystemExit("%s: missing - not in the quant's shards nor in an Engram set (--engram, or "
"<model>/../Engram/: unsloth's UD-Q8_K_XL shard of the Engram tables)" % nm)
rel = lambda p: os.path.relpath(p, model).replace(os.sep, "/") # noqa: E731
gs_all = gs + list(eg_from.values())
names = [g.path.name for g in gs] + [rel(p) for p in eg_from]
tensors, unknown, skipped = [], [], []
skip_re = re.compile(a.skip_tensors) if a.skip_tensors else None
for fi, g in enumerate(gs_all):
for name, typ, dims, off in g.tensors:
if skip_re is not None and skip_re.search(name):
skipped.append("%s (asked for)" % name)
continue
if typ not in TYPES:
if typ in (24, 25, 26, 27, 28): # I8 / I16 / I32 / I64 / F64: metadata carried as tensors, not weights
skipped.append("%s (type %d)" % (name, typ)) # (the IST-DAS sets' engram_token_map.weight)
continue
raise SystemExit("%s: %s has ggml type %d, which the engine does not read" % (g.path.name, name, typ))
tname, per, bpb = TYPES[typ]
nel = 1
for d in dims:
nel *= d
if dims[0] % per:
raise SystemExit("%s: %s rows of %d are not whole %s blocks" % (g.path.name, name, dims[0], tname))
nbytes = nel // per * bpb
m = re.match(r"blk\.(\d+)\.(.+)$", name)
if m and m.group(2) in LAYER:
ck = "layers.%s.%s" % (m.group(1), LAYER[m.group(2)])
elif name in GLOBAL:
ck = GLOBAL[name]
else:
unknown.append(name)
continue
shape = list(reversed(dims)) # ggml ne0 innermost -> torch order, outermost first
base = g.data_start + off
if ck.endswith(".attn.wo_a.slice"):
# [o_groups * o_lora][in] -> o_groups entries of [o_lora][in] (group g: rows g * o_lora ..)
n = int(kv["%s.attention.output_group_count" % kv["general.architecture"]])
if len(shape) == 3 and shape[0] == n: # (the IST-DAS sets: [groups][o_lora][in] in one tensor)
shape = [shape[0] * shape[1], shape[2]]
if len(shape) != 2 or shape[0] % n:
raise SystemExit("%s: %s %s does not split in %d groups" % (g.path.name, name, shape, n))
part = nbytes // n
for i in range(n):
tensors.append(("%s.%d.weight" % (ck, i), tname, fi, base + i * part, part,
[shape[0] // n, shape[1]]))
continue
if ".ffn.experts." in ck:
# [n_exp][out][in] -> an entry an expert: layers.N.ffn.experts.E.w1.weight
n, part = shape[0], nbytes // shape[0]
pre, role = ck.rsplit(".", 1)
for i in range(n):
tensors.append(("%s.%d.%s.weight" % (pre, i, role), tname, fi, base + i * part, part, shape[1:]))
continue
tensors.append((ck, tname, fi, base, nbytes, shape))
if unknown:
raise SystemExit("tensors the pack does not map (%d): %s" % (len(unknown), ", ".join(unknown[:12])))
if skipped:
print("not weights, left out (%d): %s" % (len(skipped), ", ".join(skipped[:8])))
# the DSpark drafter (drafter_pack.py's dspark.bin beside the quants' folders, from DeepSeek's checkpoint): its
# three blocks as mtp.0-2, so the engine drafts with them
files = names
if eg_from:
print("Engram tables from %s (%d shards)" % (eg_dir, len(eg_from)))
# experts of a second requantized model replace the main one's for some roles / layers (the byte layouts are per tensor: any mix of types)
n_ov = 0
for spec in (a.override_experts or []):
dpath, _, drl = spec.partition(":")
od = pathlib.Path(dpath).expanduser().resolve()
roles_ov = {"gate": "w1", "up": "w3", "down": "w2"}
want = {roles_ov[r] for r in (drl or a.override_roles).split(",")}
lay_ov = None
if a.override_layers:
lay_ov = set()
for part in a.override_layers.split(","):
lo, _, hi = part.partition("-")
lay_ov.update(range(int(lo), int(hi or lo) + 1))
ogs = [Gguf(pth) for pth in sorted(od.glob("*.gguf"))]
new = []
for og in ogs:
try:
orel = os.path.relpath(og.path, model).replace(os.sep, "/")
except ValueError:
raise SystemExit("%s must be on the model's drive" % od)
files.append(orel)
ofi = len(files) - 1
for name, typ, dims, off in og.tensors:
m = re.match(r"blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$", name)
if not m or typ not in TYPES:
continue
il, role = int(m.group(1)), {"gate": "w1", "up": "w3", "down": "w2"}[m.group(2)]
if role not in want or (lay_ov is not None and il not in lay_ov):
continue
tname, per, bpb = TYPES[typ]
nel = 1
for d in dims:
nel *= d
nbytes = nel // per * bpb
shape = list(reversed(dims))
n, part = shape[0], nbytes // shape[0]
for i in range(n):
new.append(("layers.%d.ffn.experts.%d.%s.weight" % (il, i, role), tname, ofi, og.data_start + off + i * part, part, shape[1:]))
names_new = {t[0] for t in new}
tensors[:] = [t for t in tensors if t[0] not in names_new] + new
n_ov += len(new)
print("experts overridden from %s: %d tensors (roles %s, layers %s)" % (od, len(new), drl or a.override_roles, a.override_layers or "all"))
# dense matrices requantized by dense_requant.py replace the GGUF's BF16 ones
n_dense = 0
for dsrc in (a.dense_override or []):
dd = pathlib.Path(dsrc).expanduser().resolve()
dj = json.loads((dd / "dense.json").read_text())
try:
relf = os.path.relpath(dd / "dense.bin", model).replace(os.sep, "/")
except ValueError:
raise SystemExit("%s must be on the model's drive" % dd)
if relf not in files:
files.append(relf)
dfi = files.index(relf)
pos = {t[0]: i for i, t in enumerate(tensors)}
n_here = n_add = 0
for name, (tname, fname, off, nb, shape) in dj.items():
if name not in pos:
# a tensor the quant leaves out (a --skip-tensors'd one, or a set that stores it under another layout):
# the override supplies it
tensors.append((name, tname, dfi, off, nb, shape))
pos[name] = len(tensors) - 1
n_add += 1
continue
tensors[pos[name]] = (name, tname, dfi, off, nb, shape)
n_here += 1
n_dense += n_here + n_add
print("dense override from %s: %d tensors replaced, %d added (a later folder wins)" % (dd, n_here, n_add))
# the DSpark drafter from unsloth's GGUF (architecture dflash): blk.N.* -> mtp.N.*, the head tensors under the
# checkpoint's names (fc -> main_proj, enc.output_norm -> main_norm, output_norm -> norm of the last block,
# conf_proj -> confidence_head.proj, markov_w1 / w2 -> markov_head.embed / head)
ds_path = pathlib.Path(a.dspark_gguf).expanduser().resolve() if a.dspark_gguf else next(
iter(sorted(model.parent.glob("dspark-*.gguf"))), None)
dspark_gguf = False
if ds_path is not None:
if not ds_path.is_file():
raise SystemExit("%s: no DSpark GGUF there" % ds_path)
dg = Gguf(ds_path)
if dg.kv.get("general.architecture") != "dflash":
raise SystemExit("%s: not a DSpark (dflash) GGUF" % ds_path)
# the engine's dspark.* geometry: a quant built by another tool (the IST-DAS sets) leaves it out, the drafter
# carries all of it except the noise token (a model constant) and the markov head's rank (the tensor's shape)
for k, dk in (("block_size", "block_size"), ("expert_count", "expert_count"),
("expert_used_count", "expert_used_count"), ("target_layers", "target_layers")):
v = dg.kv.get("dflash." + dk)
if v is not None:
kv.setdefault("%s.dspark.%s" % (arch, k), v)
if a.dspark_noise_token is not None:
kv.setdefault("%s.dspark.noise_token_id" % arch, int(a.dspark_noise_token))
if a.dspark_markov_rank is not None:
kv.setdefault("%s.dspark.markov_rank" % arch, int(a.dspark_markov_rank))
else:
for name, typ, dims, off in dg.tensors:
if "markov" in name and len(dims) == 2:
kv.setdefault("%s.dspark.markov_rank" % arch, int(dims[0]))
break
nb = int(dg.kv["dflash.block_count"])
files.append(rel(ds_path))
fi = len(files) - 1
HEAD = {"fc.weight": "mtp.0.main_proj.weight", "enc.output_norm.weight": "mtp.0.main_norm.weight",
"output_norm.weight": "mtp.%d.norm.weight" % (nb - 1),
"conf_proj.weight": "mtp.%d.confidence_head.proj.weight" % (nb - 1),
"markov_w1.weight": "mtp.%d.markov_head.embed.weight" % (nb - 1),
"markov_w2.weight": "mtp.%d.markov_head.head.weight" % (nb - 1)}
groups = int(kv["%s.attention.output_group_count" % kv["general.architecture"]])
bad = []
for name, typ, dims, off in dg.tensors:
if typ not in TYPES:
raise SystemExit("%s: %s has ggml type %d, which the engine does not read" % (ds_path.name, name, typ))
tname, per, bpb = TYPES[typ]
nel = 1
for d in dims:
nel *= d
nbytes = nel // per * bpb
m = re.match(r"blk\.(\d+)\.(.+)$", name)
if m and m.group(2) in LAYER:
ck = "mtp.%s.%s" % (m.group(1), LAYER[m.group(2)])
elif name in HEAD:
ck = HEAD[name]
else:
bad.append(name)
continue
shape = list(reversed(dims))
base = dg.data_start + off
if ck.endswith(".attn.wo_a.slice"):
part = nbytes // groups
for i in range(groups):
tensors.append(("%s.%d.weight" % (ck, i), tname, fi, base + i * part, part, [shape[0] // groups, shape[1]]))
elif ".ffn.experts." in ck:
n, part = shape[0], nbytes // shape[0]
pre, role = ck.rsplit(".", 1)
for i in range(n):
tensors.append(("%s.%d.%s.weight" % (pre, i, role), tname, fi, base + i * part, part, shape[1:]))
else:
tensors.append((ck, tname, fi, base, nbytes, shape))
if bad:
raise SystemExit("DSpark GGUF tensors the pack does not map (%d): %s" % (len(bad), ", ".join(bad[:12])))
dspark_gguf = True
print("DSpark drafter from %s: %d blocks" % (ds_path.name, nb))
# the vision tower from unsloth's mmproj GGUF (clip, projector deepseek41v): llama.cpp's names -> the checkpoint's;
# the F32 norms / biases / marker rows are read as BF16 by the engine; mlp.w1 is the file's gate and up
mm_path = pathlib.Path(a.mmproj).expanduser().resolve() if a.mmproj else next(
iter(sorted(model.parent.glob("mmproj*.gguf"))), None)
mm_geo = {}
if mm_path is not None:
if not mm_path.is_file():
raise SystemExit("%s: no mmproj GGUF there" % mm_path)
mg = Gguf(mm_path)
if mg.kv.get("clip.projector_type") != "deepseek41v":
raise SystemExit("%s: not a DeepSeek-V4.1 vision GGUF (projector %r)" % (mm_path, mg.kv.get("clip.projector_type")))
files.append(rel(mm_path))
fi = len(files) - 1
FIX = {"v.patch_embd.weight": "vision.patch_embed.proj.weight", "v.patch_embd.bias": "vision.patch_embed.proj.bias",
"v.post_ln.weight": "vision.norm.weight", "mm.1.weight": "aligner.w1.weight", "mm.1.bias": "aligner.w1.bias",
"mm.2.weight": "aligner.w2.weight", "mm.2.bias": "aligner.w2.bias", "v.token_embd.img_start": "image_start",
"v.image_newline": "image_newline", "v.token_embd.img_end": "image_end"}
BLK = {"ln1.weight": "norm1.weight", "ln2.weight": "norm2.weight", "attn_qkv.weight": "attn.wqkv.weight",
"attn_qkv.bias": "attn.wqkv.bias", "attn_out.weight": "attn.wo.weight", "attn_out.bias": "attn.wo.bias",
"ffn_gate.weight": "mlp.gate.weight", "ffn_up.weight": "mlp.up.weight", "ffn_down.weight": "mlp.w2.weight"}
bad = []
for name, typ, dims, off in mg.tensors:
if typ not in TYPES:
raise SystemExit("%s: %s has ggml type %d, which the engine does not read" % (mm_path.name, name, typ))
tname, per, bpb = TYPES[typ]
nel = 1
for d in dims:
nel *= d
m = re.match(r"v\.blk\.(\d+)\.(.+)$", name)
if m and m.group(2) in BLK:
ck = "vision.blocks.%s.%s" % (m.group(1), BLK[m.group(2)])
elif name in FIX:
ck = FIX[name]
else:
bad.append(name)
continue
shape = list(reversed(dims))
if name == "v.patch_embd.weight": # conv [out][3][14][14] -> [out][3 * 14 * 14], the same bytes
shape = [shape[0], nel // shape[0]]
tensors.append((ck, tname, fi, mg.data_start + off, nel // per * bpb, shape))
if bad:
raise SystemExit("mmproj tensors the pack does not map (%d): %s" % (len(bad), ", ".join(bad[:12])))
k = lambda n, d=None: mg.kv.get("clip.vision." + n, d) # noqa: E731
toks = kv.get("tokenizer.ggml.tokens", [])
img_id = next((i for i, t in enumerate(toks) if t == "<|deepseek_image|>"), None)
if img_id is None:
raise SystemExit("the vocabulary has no <|deepseek_image|> token")
mm_geo = {"vision.num_hidden_layers": k("block_count"), "vision.hidden_size": k("embedding_length"),
"vision.num_attention_heads": k("attention.head_count"), "vision.intermediate_size": k("feed_forward_length"),
"vision.patch_size": k("patch_size"), "vision.downsample_ratio": k("projector.scale_factor"),
"vision.rope_theta": 10000, "vision.max_image_tokens": 1024, "vision.min_pixels": k("image_min_pixels"),
"image_token_id": img_id}
print("vision tower from %s: %d blocks, image token %d" % (mm_path.name, mm_geo["vision.num_hidden_layers"], img_id))
# trellis experts from tq_convert.py: per layer the three roles stacked [n_exp][rows][row bytes] in one file
tq_layers = []
if a.tq_experts:
by_layer, tq_dirs = {}, {}
for d in a.tq_experts:
tqd = pathlib.Path(d).expanduser().resolve()
for key, ent in json.loads((tqd / "tq.json").read_text()).items():
m = re.match(r"layers\.(\d+)\.ffn\.experts\.(w[123])$", key)
if not m:
raise SystemExit("tq.json: %s is not a layer's expert role" % key)
by_layer.setdefault(int(m.group(1)), {})[m.group(2)] = ent
tq_dirs[(int(m.group(1)), m.group(2))] = tqd
if a.tq_layers:
keep = {int(x) for x in a.tq_layers.split(",")}
by_layer = {il: r for il, r in by_layer.items() if il in keep}
TQTYPES = {v[0]: k for k, v in TYPES.items()}
for il, roles in sorted(by_layer.items()):
if sorted(roles) != ["w1", "w2", "w3"]:
raise SystemExit("tq.json: layer %d lacks a role (has %s)" % (il, sorted(roles)))
if len({r[0] for r in roles.values()}) != 1 or roles["w1"][0] != roles["w3"][0]:
raise SystemExit("tq.json: layer %d: gate and up must be one type" % il)
drop = re.compile(r"layers\.%d\.ffn\.experts\.\d+\.w[123]\.weight$" % il)
kept = [t for t in tensors if not drop.match(t[0])]
if len(kept) == len(tensors):
raise SystemExit("layer %d has no routed experts in the GGUF to replace" % il)
tensors[:] = kept
for role, (tname, fname, off, total, shape) in roles.items():
if tname not in TQTYPES:
raise SystemExit("tq.json: unknown type %s" % tname)
n_exp, rows, cols = shape
per = total // n_exp
f = tq_dirs[(il, role)] / fname
if not f.is_file() or f.stat().st_size < off + total:
raise SystemExit("%s: missing or short" % f)
try:
relf = os.path.relpath(f, model).replace(os.sep, "/")
except ValueError:
raise SystemExit("%s must be on the model's drive" % f)
if relf not in files:
files.append(relf)
fi = files.index(relf)
for e in range(n_exp):
tensors.append(("layers.%d.ffn.experts.%d.%s.weight" % (il, e, role), tname, fi, off + e * per, per, [rows, cols]))
tq_layers.append(il)
print("trellis experts from %s: layers %s" % (", ".join(a.tq_experts), tq_layers))
drafter = pathlib.Path(a.drafter).expanduser().resolve() if a.drafter else model.parent / "dspark" / "dspark.json"
if a.drafter and not drafter.is_file():
raise SystemExit("%s: no drafter there" % drafter)
drafter_in = (drafter.is_file() and drafter.with_suffix(".bin").is_file()) and not dspark_gguf
if drafter_in:
files.append(rel(drafter.with_suffix(".bin")))
groups = int(kv["%s.attention.output_group_count" % kv["general.architecture"]])
for name, dt, off, nb, shape in json.loads(drafter.read_text())["tensors"]:
if name.endswith(".attn.wo_a.weight"): # (one entry a group, as the trunk's)
for i in range(groups):
tensors.append(("%s.slice.%d.weight" % (name[:-len(".weight")], i), dt, len(files) - 1,
off + i * (nb // groups), nb // groups, [shape[0] // groups, shape[1]]))
continue
tensors.append((name, dt, len(files) - 1, off, nb, shape))
# the vision tower (vision_pack.py's vision.bin, from DeepSeek's checkpoint): its tensors under the checkpoint's
# names, the picture span's marker rows, and the geometry config.json gives them
vdir = pathlib.Path(a.vision).expanduser().resolve() if a.vision else model.parent / "vision"
vision = {}
if (vdir / "vision.json").is_file() and (vdir / "vision.bin").is_file():
try:
rel = os.path.relpath(vdir / "vision.bin", model).replace(os.sep, "/")
except ValueError: # (Windows: another drive)
raise SystemExit("%s: the vision folder must be on the model's drive" % vdir)
if " " in rel:
raise SystemExit("%s: the vision folder's path relative to the model has a space" % vdir)
files.append(rel)
info = json.loads((vdir / "vision.json").read_text())
for name, dt, off, nb, shape in info["tensors"]:
tensors.append((name, dt, len(files) - 1, off, nb, shape))
vision = info["config"]
if mm_geo and not vision:
vision = mm_geo
vocab = next(t[5][0] for t in tensors if t[0] == "embed.weight")
geo = geometry(kv, vocab)
out.mkdir(parents=True, exist_ok=True)
with (out / "ds4.txt").open("w") as f:
for k, v in geo.items():
if v is None:
continue
if isinstance(v, bool):
v = int(v)
f.write("%s %s\n" % (k, ",".join(str(x) for x in v) if isinstance(v, list) else v))
for k, v in vision.items():
f.write("%s %s\n" % (k, v))
f.write("format gguf\n")
f.write("model_dir %s\n" % model)
with (out / "tensors.txt").open("w") as f:
for i, name in enumerate(files):
f.write("file %d %s\n" % (i, name))
for name, dt, fi, off, nb, shape in tensors:
f.write("t %s %s %d %d %d %s\n" % (name, dt, fi, off, nb, " ".join(map(str, shape))))
nl, cols = write_engram(out / "engram.bin", kv, vocab)
# the server's chat template: the GGUF's own (unsloth's, byte-identical to DeepSeek's encoding.py on the 9 cases we
# checked: chat, thinking, effort, system, multi-turn, tools, tool results). Project Maya's tools/ds4/chat_template.jinja
# lost the tool associations and later system instructions (their #299), so it is NOT used here.
template = kv.get("tokenizer.chat_template")
if not template:
sys.exit("%s: the GGUF has no tokenizer.chat_template; refusing to fall back to the old Maya template (#299)" % model)
write_tokenizer(out / "tokenizer", kv, template)
by = {}
for t in tensors:
by[t[1]] = by.get(t[1], 0) + t[4]
extras = [w for w, there in (("the DSpark drafter", drafter_in or dspark_gguf), ("the vision tower", bool(vision)), ("trellis experts in layers %s" % tq_layers, bool(tq_layers)), ("%d dense matrices requantized" % n_dense, bool(n_dense)), ("%d experts from %s" % (n_ov, a.override_experts), bool(n_ov))) if there]
print("%s: %d tensors in %d files (%s), Engram %d layers x %d hash columns%s -> %s" %
(model.name, len(tensors), len(files), ", ".join("%s %.1f GB" % (k, v / 1e9) for k, v in sorted(by.items())),
nl, cols, "".join(", " + w for w in extras), out))
return 0
if __name__ == "__main__":
sys.exit(main())
+104
View File
@@ -0,0 +1,104 @@
"""16 tokens of a fixed prompt through strata-dsv41 and a check of the TEXT (setup runs this once after the pack is built).
python tools/dsv41/smoke.py --exe strata-dsv41 --pack <pack> [--gpus 0] [--tokens 16]
A pack that loads can still give garbage (a wrong pack recipe does exactly that), so the answer is read, not just the exit code:
the model is asked for the capital of France and the reply must be words, with "Paris" in it. Exit 0 and the text on success; exit 1
and one plain line (and the engine's last lines) when the reply is not sensible; exit 2 when the engine did not run at all.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tools"))
PROMPT = "<|begin▁of▁sentence|><|User|>What is the capital of France? Answer in one short sentence.<|Assistant|></think>"
def tokenizer(pack: Path):
import strata_tokenizer as ST
tpath = pack / "tokenizer"
vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8"))
tokens = [None] * len(vocab)
for t, i in vocab.items():
tokens[i] = t
merges = (tpath / "merges.txt").read_text(encoding="utf-8").split("\n")
types = json.loads((tpath / "token_type.json").read_text())
tcfg = {}
try:
tcfg = json.loads((tpath / "tokenizer.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
pass
return ST.Tokenizer(tokens, merges, types, tcfg.get("pre") or "qwen35", tcfg.get("special_ids") or None)
def sensible(text: str) -> tuple[bool, str]:
"""Words, not noise: letters in a normal share, more than two different words, no replacement characters, and Paris in it."""
t = text.strip()
words = re.findall(r"[A-Za-z]{2,}", t)
if not t:
return False, "the answer is empty"
if "�" in t:
return False, "the answer has broken characters"
if len(set(w.lower() for w in words)) < 3:
return False, "the answer is not made of words"
letters = sum(c.isalpha() or c.isspace() or c in ".,'-" for c in t) / len(t)
if letters < 0.8:
return False, "the answer is mostly symbols"
if "paris" not in t.lower():
return False, "the answer to a question with a known answer (the capital of France) does not contain it"
return True, "ok"
def main() -> int:
for st in (sys.stdout, sys.stderr): # the reply has DeepSeek's special tokens (fullwidth bars): a Windows console code page cannot print them
try:
st.reconfigure(encoding="utf-8", errors="replace")
except (AttributeError, OSError):
pass
ap = argparse.ArgumentParser()
ap.add_argument("--exe", required=True)
ap.add_argument("--pack", required=True)
ap.add_argument("--gpus")
ap.add_argument("--tokens", type=int, default=16)
ap.add_argument("--timeout", type=int, default=5400)
a = ap.parse_args()
pack = Path(a.pack)
tok = tokenizer(pack)
ids = tok.encode(PROMPT, parse_special=True)
with tempfile.TemporaryDirectory() as d:
f = Path(d) / "ids.txt"
f.write_text(",".join(str(i) for i in ids), encoding="ascii")
cmd = [a.exe, "--pack", str(pack), "--ids", "@" + str(f), "--n", str(a.tokens), "--max-context", "1024", "--dspark", "auto",
"--window", "16"]
if a.gpus:
cmd += ["--gpus", a.gpus]
try:
r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=a.timeout, env=dict(os.environ))
except (OSError, subprocess.TimeoutExpired) as e:
print(f"the engine did not finish the test run: {e}")
return 2
err = (r.stderr or "").strip().splitlines()
if r.returncode != 0:
print(f"the engine stopped with an error (exit {r.returncode}): " + " | ".join(err[-3:]))
return 2
out = [int(x) for x in re.findall(r"-?\d+", (r.stdout or "").strip().splitlines()[-1] if (r.stdout or "").strip() else "")]
text = tok.decode(out)
good, why = sensible(text)
print(text.strip())
if not good:
print(f"test question failed: {why}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+182
View File
@@ -0,0 +1,182 @@
"""A short tune for DeepSeek-V4.1-Flash (strata-dsv41): the few settings the engine has, measured on this computer.
python tools/dsv41/tune.py --config <launch config .json> [--mode quick|thorough] [--runs N]
What it does (a few short decode runs through the engine's own command line; each loads the model, so about 1-3 minutes each):
1. the launch's own settings (the baseline);
2. the same with the DSpark drafter forced on (`--dspark on --dspark-conf 0.65`) against `--dspark auto`, which leaves it unloaded on a
small card: kept only when it is clearly faster; with it on, a draft block of 3 against the pack's own (5);
3. the CPU threads: the number of physical cores against every logical thread (SMT), when they differ: kept only when clearly faster.
The RAM store (`--ssd-cache`) sizes itself from the free memory at start, so it is left as the engine's own; the line says so.
A setting is changed only for a gain of more than 5% (run-to-run noise on this engine is about 5%). Whatever is kept is written into
the config's args; a run that fails or a computer that is too busy leaves the config as it was, with one plain line. Always exits 0.
The context stays what the person chose.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tools"))
sys.path.insert(0, str(Path(__file__).resolve().parent))
GAIN = 1.05
DECODE = re.compile(r"decode:\s*\d+ tokens in [\d.]+ ms \(([\d.]+) tok/s\)")
def say(msg: str) -> None:
print(msg, flush=True)
def parse_speed(stderr: str) -> float | None:
m = DECODE.findall(stderr or "")
return float(m[-1]) if m else None
def drop(args: list[str], flag: str) -> list[str]:
"""`args` without `flag` and its value."""
out, i = [], 0
while i < len(args):
if args[i] == flag:
i += 2
continue
out.append(args[i])
i += 1
return out
def with_flag(args: list[str], flag: str, *values: str) -> list[str]:
return [*drop(args, flag), flag, *values]
def physical_cores() -> int | None:
try:
import psutil
return psutil.cpu_count(logical=False)
except Exception: # noqa: BLE001
return None
def measure(exe: str, args: list[str], ids_file: Path, n: int, timeout: int, env: dict) -> float | None:
"""Decode tokens a second of one CLI run, or None when it did not run to the end."""
cmd = [exe, *[a for a in args if a not in ("--serve",)], "--ids", "@" + str(ids_file), "--n", str(n)]
try:
r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env)
except (OSError, subprocess.TimeoutExpired):
return None
if r.returncode != 0:
return None
return parse_speed(r.stderr)
def prompt_ids(pack: Path) -> list[int]:
import smoke
tok = smoke.tokenizer(pack)
return tok.encode(smoke.PROMPT, parse_special=True)
def lib_env(cfg: dict) -> dict:
env = dict(os.environ)
dirs = [str(d) for d in cfg.get("lib_dirs") or [] if d]
key = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
if dirs:
env[key] = os.pathsep.join(dirs + [env.get(key, "")])
return env
def tune(config: Path, mode: str = "quick", n: int = 48, timeout: int = 1500, measure_fn=measure) -> dict:
"""Returns {"changed": [...], "speeds": {...}, "lines": [plain sentences]}; writes the config when something was kept."""
cfg = json.loads(config.read_text(encoding="utf-8-sig"))
exe, args = cfg.get("exe"), [str(a) for a in cfg.get("args") or []]
res = {"changed": [], "speeds": {}, "lines": []}
if not exe or "--pack" not in args:
res["lines"].append("This launch has no DeepSeek engine settings to tune, so it starts as it is.")
return res
pack = Path(args[args.index("--pack") + 1])
env = lib_env(cfg)
try:
ids = prompt_ids(pack)
except Exception as e: # noqa: BLE001
res["lines"].append(f"The tuner could not prepare its test question ({e}), so the standard settings run.")
return res
with tempfile.TemporaryDirectory() as d:
f = Path(d) / "ids.txt"
f.write_text(",".join(str(i) for i in ids), encoding="ascii")
base_args = [a for a in args if a != "--serve"]
say("Tuning DeepSeek: measuring the standard settings first ...")
base = measure_fn(exe, base_args, f, n, timeout, env)
if base is None:
res["lines"].append("The standard settings did not finish a test run here, so nothing was tuned and they stay as they are.")
return res
res["speeds"]["standard"] = base
best, best_args = base, base_args
say(f" standard settings: {base:.2f} tokens a second")
trials = [("the drafter on (DSpark)", lambda a: with_flag(with_flag(a, "--dspark", "on"), "--dspark-conf", "0.65"))]
trials.append(("a shorter draft block (3)", lambda a: with_flag(a, "--dspark-block", "3")))
cores, logical = physical_cores(), os.cpu_count() or 0
if cores and logical and logical > cores and "--cpu-threads" not in base_args:
trials.append((f"{cores} CPU threads (one for each physical core)", lambda a, c=cores: with_flag(a, "--cpu-threads", str(c))))
if mode == "thorough" and cores:
trials.append(("every logical CPU thread", lambda a, c=logical: with_flag(a, "--cpu-threads", str(c))))
queue = list(trials)
while queue:
label, make = queue.pop(0)
if label == "a shorter draft block (3)":
if "on" != (best_args[best_args.index("--dspark") + 1] if "--dspark" in best_args else ""):
continue # only with the drafter on: with `auto` it may not even be loaded
cand = make(best_args)
say(f" trying {label} ...")
v = measure_fn(exe, cand, f, n, timeout, env)
if v is None:
res["lines"].append(f"The test with {label} did not finish; that setting stays as it was.")
continue
res["speeds"][label] = v
say(f" {v:.2f} tokens a second")
if v > best * GAIN:
best, best_args = v, cand
res["changed"].append(label)
tried = ", ".join(f"{k} {v:.1f}" for k, v in res["speeds"].items())
if res["changed"]:
new = [a for a in best_args]
cfg["args"] = new
cfg.setdefault("tuned", {})["dsv41"] = {"speeds": res["speeds"], "changed": res["changed"]}
config.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
res["lines"].append(f"Done: {', '.join(res['changed'])} - answers about {100 * (best / base - 1):.0f}% faster "
f"({base:.1f} -> {best:.1f} tokens a second). The RAM store sizes itself when the model starts.")
else:
res["lines"].append(f"Your computer already runs DeepSeek best with the standard settings ({base:.1f} tokens a second); nothing changed.")
if len(res["speeds"]) > 1:
res["lines"].append(f"Tried (tokens a second): {tried}.")
else:
res["lines"].append("Only the standard settings could be timed here, so there was nothing to compare.")
return res
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--config", required=True)
ap.add_argument("--mode", default="quick", choices=["quick", "thorough"])
ap.add_argument("--tokens", type=int, default=48)
ap.add_argument("--timeout", type=int, default=1500)
ap.add_argument("--output", default="human")
a = ap.parse_args()
try:
res = tune(Path(a.config), a.mode, a.tokens, a.timeout)
except Exception as e: # noqa: BLE001 - a tune never stops a launch
res = {"changed": [], "speeds": {}, "lines": [f"The tuner stopped ({type(e).__name__}), so the standard settings run."]}
for line in res["lines"]:
say(line)
if a.output == "json":
say(json.dumps({"result": res}))
return 0
if __name__ == "__main__":
sys.exit(main())
+601
View File
@@ -0,0 +1,601 @@
// tools/trellis/tqenc.cpp - see tqenc.hpp.
#include "tqenc.hpp"
#include "ggml-common-tq.h"
#include "tq_computed.hpp"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
#if defined(__AVX2__) && defined(__FMA__)
#include <immintrin.h>
#define TQENC_AVX2 1
#endif
namespace tqenc {
namespace {
constexpr float kInf = 1e30f;
// ---------------------------------------------------------------------------------------------------------------
// fp16
} // namespace
float half_to_float(uint16_t h) {
const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
uint32_t exp = (h >> 10) & 0x1fu, man = h & 0x3ffu, bits;
if (exp == 0x1fu) {
bits = sign | 0x7f800000u | (man << 13);
} else if (exp != 0) {
bits = sign | ((exp + 112u) << 23) | (man << 13);
} else if (man == 0) {
bits = sign;
} else {
const float m = (float) man * (1.0f / 16777216.0f);
return sign ? -m : m;
}
float f;
std::memcpy(&f, &bits, 4);
return f;
}
uint16_t float_to_half(float f) {
uint32_t x;
std::memcpy(&x, &f, 4);
const uint32_t sign = (x >> 16) & 0x8000u;
const uint32_t ax = x & 0x7fffffffu;
if (ax >= 0x7f800000u) return (uint16_t) (sign | 0x7c00u | (ax > 0x7f800000u ? 0x200u : 0u)); // inf / nan
if (ax >= 0x477ff000u) return (uint16_t) (sign | 0x7c00u); // >= 65520 rounds to inf
if (ax < 0x33000001u) return (uint16_t) sign; // <= 2^-25: rounds to zero (ties to even)
int e = (int) (ax >> 23) - 127;
uint32_t man = (ax & 0x7fffffu) | 0x800000u;
if (e < -14) { // subnormal half
const int shift = -14 - e + 13; // total right shift of the 24-bit mantissa
const uint32_t half = 1u << (shift - 1), rest = man & ((1u << shift) - 1);
uint32_t q = man >> shift;
if (rest > half || (rest == half && (q & 1))) ++q;
return (uint16_t) (sign | q);
}
uint32_t q = ((uint32_t) (e + 15) << 10) | ((man >> 13) & 0x3ffu);
const uint32_t rest = man & 0x1fffu;
if (rest > 0x1000u || (rest == 0x1000u && (q & 1))) ++q; // a carry into the exponent is correct
return (uint16_t) (sign | q);
}
int type_kbits(int type) {
switch (type) {
case TQ2_T: return 8;
case TQK6: return 6;
case TQK7: return 7;
case TQK5X: case TQK5T: return 5;
case TQK4X: case TQK4T: return 4;
default: return 0;
}
}
bool type_computed(int type) { return type == TQK5X || type == TQK4X; }
double codebook_rms(int type);
namespace {
// ---------------------------------------------------------------------------------------------------------------
// codebook: the decoder's int16 table (round half away from zero of fp16 * 8192, as tq_cpu.cpp fill_table), SoA floats
struct Codebook {
int16_t tab[kStates * 4];
alignas(64) float soa[4][kStates];
double rms = 1.072; // of the weights: the first scale guess is rms(block) / this
explicit Codebook(bool computed) {
if (computed) { // tq_computed.hpp
double ss = 0;
for (uint32_t s = 0; s < (uint32_t) kStates; ++s) {
strata::kernels::cpu::tq_detail::comp_state4(s, tab + 4 * s);
for (int j = 0; j < 4; ++j) {
soa[j][s] = (float) tab[4 * s + j] * (1.0f / 8192.0f);
ss += (double) soa[j][s] * soa[j][s];
}
}
rms = std::sqrt(ss / (4.0 * kStates));
return;
}
double ss = 0;
for (uint32_t s = 0; s < (uint32_t) kStates; ++s) {
const uint32_t x = s * 0x9e3779b1u;
const uint32_t pts[2] = {x >> 21, (x >> 10) & 2047u};
for (int h = 0; h < 2; ++h)
for (int j = 0; j < 2; ++j) {
const float v = half_to_float(tq_lut_f16[2 * pts[h] + j]) * 8192.0f;
const int16_t q = (int16_t) (v < 0.0f ? v - 0.5f : v + 0.5f);
tab[4 * s + 2 * h + j] = q;
soa[2 * h + j][s] = (float) q * (1.0f / 8192.0f);
ss += (double) soa[2 * h + j][s] * soa[2 * h + j][s];
}
}
rms = std::sqrt(ss / (4.0 * kStates));
}
};
const Codebook& cb(bool computed) {
static const Codebook table(false), comp(true);
return computed ? comp : table;
}
struct Geo {
const Codebook* cbk = nullptr;
int K = 0;
bool t2 = false; // TQ2_T (byte stream, the other shift direction)
int G = 0; // predecessor groups
};
Geo geo_for(int type) {
Geo g;
g.cbk = &cb(type_computed(type));
g.K = type_kbits(type);
g.t2 = type == TQ2_T;
g.G = g.t2 ? 128 : (1 << (15 - g.K));
return g;
}
// group of a state as a successor / as a predecessor
inline int gsucc(const Geo& g, uint32_t s) { return g.t2 ? (int) (s >> 8) : (int) (s & (uint32_t) (g.G - 1)); }
inline int gpred(const Geo& g, uint32_t s) { return g.t2 ? (int) (s & 0x7f) : (int) (s >> g.K); }
// weight index (0..127) of component j of processing position p
inline int widx(const Geo& g, int p, int j) { return g.t2 ? 4 * p + j : 4 * (31 - p) + j; }
struct Scratch {
alignas(64) float D[2][kStates]; // the two live columns of the DP
alignas(64) uint16_t bp[32][2048]; // per step and predecessor group: the best predecessor state
alignas(64) float m[2048];
alignas(64) int32_t am[2048];
alignas(64) float zero[kStates];
};
Scratch& scratch() {
thread_local std::unique_ptr<Scratch> s;
if (!s) {
s.reset(new Scratch);
std::memset(s->zero, 0, sizeof s->zero);
std::memset(s->m, 0, sizeof s->m);
}
return *s;
}
inline float min_range(const float* p, int n) {
#if TQENC_AVX2
if (n >= 8) {
__m256 v = _mm256_loadu_ps(p);
for (int i = 8; i + 8 <= n; i += 8) v = _mm256_min_ps(v, _mm256_loadu_ps(p + i));
__m128 a = _mm_min_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
a = _mm_min_ps(a, _mm_movehl_ps(a, a));
a = _mm_min_ss(a, _mm_shuffle_ps(a, a, 1));
return _mm_cvtss_f32(a);
}
#endif
float m = p[0];
for (int i = 1; i < n; ++i) m = std::min(m, p[i]);
return m;
}
// out[i] = add[i] + sum_j h_j (t_j - cb_j[s0 + i])^2 for i in [0, n)
inline void step_cost(const Codebook& C, float* out, const float* add, int s0, int n, const float* t, const float* h) {
const float *c0 = C.soa[0] + s0, *c1 = C.soa[1] + s0, *c2 = C.soa[2] + s0, *c3 = C.soa[3] + s0;
int i = 0;
#if TQENC_AVX2
const __m256 t0 = _mm256_set1_ps(t[0]), t1 = _mm256_set1_ps(t[1]), t2 = _mm256_set1_ps(t[2]), t3 = _mm256_set1_ps(t[3]);
const __m256 h0 = _mm256_set1_ps(h[0]), h1 = _mm256_set1_ps(h[1]), h2 = _mm256_set1_ps(h[2]), h3 = _mm256_set1_ps(h[3]);
for (; i + 8 <= n; i += 8) {
const __m256 e0 = _mm256_sub_ps(t0, _mm256_loadu_ps(c0 + i)), e1 = _mm256_sub_ps(t1, _mm256_loadu_ps(c1 + i));
const __m256 e2 = _mm256_sub_ps(t2, _mm256_loadu_ps(c2 + i)), e3 = _mm256_sub_ps(t3, _mm256_loadu_ps(c3 + i));
__m256 a = _mm256_fmadd_ps(_mm256_mul_ps(h0, e0), e0, _mm256_loadu_ps(add + i));
a = _mm256_fmadd_ps(_mm256_mul_ps(h1, e1), e1, a);
a = _mm256_fmadd_ps(_mm256_mul_ps(h2, e2), e2, a);
a = _mm256_fmadd_ps(_mm256_mul_ps(h3, e3), e3, a);
_mm256_storeu_ps(out + i, a);
}
#endif
for (; i < n; ++i) {
const float e0 = t[0] - c0[i], e1 = t[1] - c1[i], e2 = t[2] - c2[i], e3 = t[3] - c3[i];
out[i] = add[i] + h[0] * e0 * e0 + h[1] * e1 * e1 + h[2] * e2 * e2 + h[3] * e3 * e3;
}
}
// the broadcast variant: out[i] = a + cost(s0 + i)
inline void step_cost_bc(const Codebook& C, float* out, float a, int s0, int n, const float* t, const float* h) {
alignas(32) float tmp[256];
for (int i = 0; i < n; ++i) tmp[i] = a;
step_cost(C, out, tmp, s0, n, t, h);
}
// min and first index of the minimum over p[0..n)
inline float min_arg_range(const float* p, int n, int* arg) {
const float m = min_range(p, n);
int i = 0;
#if TQENC_AVX2
const __m256 vm = _mm256_set1_ps(m);
for (; i + 8 <= n; i += 8) {
const int mask = _mm256_movemask_ps(_mm256_cmp_ps(_mm256_loadu_ps(p + i), vm, _CMP_EQ_OQ));
if (mask) { *arg = i + __builtin_ctz((unsigned) mask); return m; }
}
#endif
for (; i < n; ++i)
if (p[i] == m) { *arg = i; return m; }
*arg = 0;
return m;
}
// T[p][4]: targets of processing position p (weights / d), H[p][4]: importance. rot: the sequence is processed from
// position rot (cyclically); fixed_c >= 0: tail-biting with the successor group of the first state and the predecessor
// group of the last state both == fixed_c. Writes the states by position into st[32]; returns the path cost.
float viterbi(const Geo& g, const float (*T)[4], const float (*H)[4], int rot, int fixed_c, uint16_t* st) {
Scratch& sc = scratch();
const int K = g.K, G = g.G;
float* cur = sc.D[0];
// q = 0
{
const int p = rot & 31;
step_cost(*g.cbk, cur, sc.zero, 0, kStates, T[p], H[p]);
if (fixed_c >= 0) {
if (g.t2) { // gsucc(s) = s >> 8 == c: the 256 states [c<<8, c<<8 + 256) allowed
for (int s = 0; s < kStates; ++s)
if ((s >> 8) != fixed_c) cur[s] = kInf;
} else { // s & (G-1) == c
for (int s = 0; s < kStates; ++s)
if ((s & (G - 1)) != fixed_c) cur[s] = kInf;
}
}
}
for (int q = 1; q < 32; ++q) {
const float* prev = cur;
cur = sc.D[q & 1];
const int p = (rot + q) & 31;
float* m = sc.m;
uint16_t* bp = sc.bp[q];
if (g.t2) {
// m[a] = min over h of prev[a + 128 h], argmin h
for (int a = 0; a < 128; ++a) { m[a] = prev[a]; sc.am[a] = 0; }
for (int h = 1; h < 256; ++h) {
const float* row = prev + 128 * h;
int a = 0;
#if TQENC_AVX2
const __m256i vh = _mm256_set1_epi32(h);
for (; a + 8 <= 128; a += 8) {
const __m256 r = _mm256_loadu_ps(row + a), mm = _mm256_loadu_ps(m + a);
const __m256 lt = _mm256_cmp_ps(r, mm, _CMP_LT_OQ); // strictly smaller: the first minimum stays
_mm256_storeu_ps(m + a, _mm256_blendv_ps(mm, r, lt));
const __m256i old = _mm256_loadu_si256((const __m256i*) (sc.am + a));
_mm256_storeu_si256((__m256i*) (sc.am + a), _mm256_castps_si256(_mm256_blendv_ps(
_mm256_castsi256_ps(old), _mm256_castsi256_ps(vh), lt)));
}
#endif
for (; a < 128; ++a)
if (row[a] < m[a]) { m[a] = row[a]; sc.am[a] = h; }
}
for (int a = 0; a < 128; ++a) bp[a] = (uint16_t) (a + 128 * sc.am[a]);
for (int b = 0; b < 128; ++b) step_cost_bc(*g.cbk, cur + 256 * b, m[b], 256 * b, 256, T[p], H[p]);
} else {
const int span = 1 << K;
for (int a = 0; a < G; ++a) {
int arg;
m[a] = min_arg_range(prev + (size_t) a * span, span, &arg);
bp[a] = (uint16_t) ((a << K) + arg);
}
for (int base = 0; base < kStates; base += G) step_cost(*g.cbk, cur + base, m, base, G, T[p], H[p]);
}
}
// final state
const float* last = cur;
int best = -1;
float bc = 3e38f;
if (fixed_c < 0) {
for (int s = 0; s < kStates; ++s)
if (last[s] < bc) { bc = last[s]; best = s; }
} else if (g.t2) {
for (int h = 0; h < 256; ++h) {
const int s = fixed_c + 128 * h;
if (last[s] < bc) { bc = last[s]; best = s; }
}
} else {
for (int i = 0; i < (1 << K); ++i) {
const int s = (fixed_c << K) + i;
if (last[s] < bc) { bc = last[s]; best = s; }
}
}
if (best < 0 || bc >= kInf * 0.5f) return kInf;
uint32_t s = (uint32_t) best;
st[(rot + 31) & 31] = (uint16_t) s;
for (int q = 31; q >= 1; --q) {
s = sc.bp[q][gsucc(g, s)];
st[(rot + q - 1) & 31] = (uint16_t) s;
}
return bc;
}
// junction group of a free pass: gpred of the state at orig position 31 (== gsucc of the state at position 0)
inline int junction_group(const Geo& g, const uint16_t* st) { return gpred(g, st[31]); }
struct Search {
const Geo* g;
const Params* p;
float T[32][4];
float H[32][4];
uint16_t st[32];
int passes = 0;
// one tail-biting search at scale d (weights already divided: set_targets); returns the path cost in scaled units
float run() {
static const int rots[8] = {16, 8, 24, 12, 20, 4, 28, 0};
float best = kInf;
uint16_t tmp[32], free_st[32];
if (p->exact) {
for (int c = 0; c < g->G; ++c) {
const float v = viterbi(*g, T, H, 0, c, tmp);
++passes;
if (v < best) { best = v; std::memcpy(st, tmp, sizeof tmp); }
}
return best;
}
int seen[8], ns = 0;
const int nc = std::max(1, std::min(p->ncand, 8));
for (int r = 0; r < nc; ++r) {
viterbi(*g, T, H, rots[r], -1, free_st);
++passes;
const int c = junction_group(*g, free_st);
bool dup = false;
for (int i = 0; i < ns; ++i) dup |= seen[i] == c;
if (dup) continue;
seen[ns++] = c;
const float v = viterbi(*g, T, H, 0, c, tmp);
++passes;
if (v < best) { best = v; std::memcpy(st, tmp, sizeof tmp); }
}
return best;
}
};
void pack_stream(const Geo& g, const uint16_t* st, uint8_t* qs) {
const int K = g.K;
std::memset(qs, 0, (size_t) 4 * K);
if (g.t2) {
for (int t = 0; t < 32; ++t) qs[t] = (uint8_t) (st[t] & 0xff);
return;
}
for (int u = 0; u < 32; ++u) {
const uint32_t x = st[u] & ((1u << K) - 1u);
for (int b = 0; b < K; ++b)
if ((x >> b) & 1u) qs[(u * K + b) >> 3] |= (uint8_t) (1u << ((u * K + b) & 7));
}
}
} // namespace
float debug_viterbi(int type, const float (*T)[4], const float (*H)[4], int rot, int fixed_c, uint16_t* st) {
return viterbi(geo_for(type), T, H, rot, fixed_c, st);
}
int debug_groups(int type) { return geo_for(type).G; }
int debug_widx(int type, int p, int j) { return widx(geo_for(type), p, j); }
void debug_pack(int type, const uint16_t* st, uint8_t* qs) { pack_stream(geo_for(type), st, qs); }
const float* codebook_state(int type, uint32_t state) {
static thread_local float v[4];
for (int j = 0; j < 4; ++j) v[j] = cb(type_computed(type)).soa[j][state & 0x7fff];
return v;
}
const int16_t* codebook_table(int type) { return cb(type_computed(type)).tab; }
double codebook_rms(int type) { return cb(type_computed(type)).rms; }
const float* point_table() {
static float pts[4096];
static std::once_flag once;
std::call_once(once, [] {
for (int i = 0; i < 4096; ++i) {
const float x = half_to_float(tq_lut_f16[i]) * 8192.0f;
const int16_t q = (int16_t) (x < 0.0f ? x - 0.5f : x + 0.5f);
pts[i] = (float) q * (1.0f / 8192.0f);
}
});
return pts;
}
uint32_t block_state(int type, const uint8_t* qs, int t) {
const int K = type_kbits(type);
if (type == TQ2_T) return (((uint32_t) qs[(t + 31) & 31] << 8) | qs[t]) & 0x7fffu;
const int total = 32 * K;
uint32_t s = 0;
for (int i = 0; i < 15; ++i) {
const int b = ((31 - t) * K + i) % total;
s |= (uint32_t) ((qs[b >> 3] >> (b & 7)) & 1u) << i;
}
return s;
}
void decode_blocks(int type, const uint8_t* src, int64_t nblocks, float* out) {
const int K = type_kbits(type), bb = 2 + 4 * K;
for (int64_t b = 0; b < nblocks; ++b) {
const uint8_t* blk = src + (size_t) b * bb;
const uint16_t dh = (uint16_t) (blk[0] | (blk[1] << 8));
const float d = half_to_float(dh);
for (int t = 0; t < 32; ++t) {
const uint32_t s = block_state(type, blk + 2, t);
for (int j = 0; j < 4; ++j) out[b * 128 + 4 * t + j] = d * cb(type_computed(type)).soa[j][s];
}
}
}
BlockResult encode_block(int type, const float* w, const float* h, uint8_t* dst, const Params& prm) {
BlockResult r;
const Geo g = geo_for(type);
const int K = g.K, bb = 2 + 4 * K;
std::memset(dst, 0, (size_t) bb);
double sumw2 = 0, sumhw2 = 0, amax = 0;
for (int i = 0; i < 128; ++i) {
if (!std::isfinite(w[i]) || (h && !std::isfinite(h[i]))) { r.status = 2; r.err = NAN; return r; }
const double hi = h ? h[i] : 1.0;
sumw2 += (double) w[i] * w[i];
sumhw2 += hi * (double) w[i] * w[i];
amax = std::max(amax, (double) std::fabs(w[i]));
}
if (amax == 0.0) { r.status = 1; return r; }
const double rms = std::sqrt(sumw2 / 128.0);
// initial scale: the codebook has unit-ish rms
const double kCbRms = g.cbk->rms;
static const double mult[7] = {1.0, 0.9, 1.1, 0.8, 1.2, 0.7, 1.3};
Search se;
se.g = &g;
se.p = &prm;
for (int p = 0; p < 32; ++p)
for (int j = 0; j < 4; ++j) se.H[p][j] = h ? h[widx(g, p, j)] : 1.0f;
double best_err = 1e300;
uint16_t best_st[32] = {};
uint16_t best_d = 0;
bool have = false;
auto fit = [&](const uint16_t* st, uint16_t dh, double& err) {
// err of (st, dh): sum h (w - d cv)^2
const float d = half_to_float(dh);
double e = 0;
for (int p = 0; p < 32; ++p)
for (int j = 0; j < 4; ++j) {
const int wi = widx(g, p, j);
const float rec = d * g.cbk->soa[j][st[p]];
const double df = (double) w[wi] - rec;
e += (h ? h[wi] : 1.0) * df * df;
}
err = e;
};
const int tries = prm.fixed_scale ? 1 : std::max(1, std::min(prm.scale_tries, 7));
for (int tr = 0; tr < tries; ++tr) {
double dd = rms / kCbRms * mult[tr];
uint16_t dh = float_to_half((float) std::min(dd, 65504.0));
if (dh == 0) dh = 1; // the smallest subnormal: weights below ~3e-8 are noise at this scale
if (prm.fixed_scale) dh = prm.fixed_scale;
for (int it = 0; it <= (prm.fixed_scale ? 0 : prm.iters); ++it) {
const float d = half_to_float(dh);
for (int p = 0; p < 32; ++p)
for (int j = 0; j < 4; ++j) se.T[p][j] = w[widx(g, p, j)] / d;
if (se.run() >= kInf * 0.5f) break;
double e;
fit(se.st, dh, e);
if (e < best_err) {
best_err = e;
best_d = dh;
std::memcpy(best_st, se.st, sizeof best_st);
have = true;
}
if (e == 0.0 || prm.fixed_scale) break;
// least-squares scale for this path
double num = 0, den = 0;
for (int p = 0; p < 32; ++p)
for (int j = 0; j < 4; ++j) {
const int wi = widx(g, p, j);
const double hi = h ? h[wi] : 1.0, c = g.cbk->soa[j][se.st[p]];
num += hi * w[wi] * c;
den += hi * c * c;
}
if (den <= 0 || num <= 0) break;
uint16_t nh = float_to_half((float) std::min(num / den, 65504.0));
if (nh == 0 || nh == dh) break;
double en;
fit(se.st, nh, en);
if (en < best_err) {
best_err = en;
best_d = nh;
std::memcpy(best_st, se.st, sizeof best_st);
}
if (en >= e) break; // the scale step did not help this path: stop refining this start
dh = nh;
}
r.searches = se.passes;
}
if (!have || best_err >= sumhw2) { // nothing beats a zero block (weights below the fp16 scale resolution)
std::memset(dst, 0, (size_t) bb);
r.status = 1;
r.err = sumhw2;
return r;
}
dst[0] = (uint8_t) (best_d & 0xff);
dst[1] = (uint8_t) (best_d >> 8);
pack_stream(g, best_st, dst + 2);
r.err = best_err;
r.scale = half_to_float(best_d);
r.searches = se.passes;
return r;
}
double encode_blocks(int type, const float* w, const float* h, int64_t nblocks, uint8_t* dst, const Params& p,
int nthreads, double* err_out, int64_t* nonfinite, int64_t* zero_blocks) {
const int bb = block_bytes(type);
if (nthreads <= 0) nthreads = (int) std::max(1u, std::thread::hardware_concurrency());
nthreads = (int) std::min<int64_t>(nthreads, std::max<int64_t>(1, nblocks));
std::atomic<int64_t> next{0}, nf{0}, zb{0};
std::vector<double> sums((size_t) nthreads, 0.0);
auto work = [&](int ti) {
double s = 0;
for (;;) {
const int64_t b0 = next.fetch_add(4);
if (b0 >= nblocks) break;
const int64_t b1 = std::min(nblocks, b0 + 4);
for (int64_t b = b0; b < b1; ++b) {
const BlockResult r = encode_block(type, w + b * 128, h ? h + b * 128 : nullptr, dst + (size_t) b * bb, p);
if (r.status == 2) { nf.fetch_add(1); }
else s += r.err;
if (r.status == 1) zb.fetch_add(1);
if (err_out) err_out[b] = r.err;
}
}
sums[ti] = s;
};
std::vector<std::thread> th;
for (int i = 1; i < nthreads; ++i) th.emplace_back(work, i);
work(0);
for (auto& t : th) t.join();
if (nonfinite) *nonfinite = nf.load();
if (zero_blocks) *zero_blocks = zb.load();
double tot = 0;
for (double s : sums) tot += s;
return tot;
}
} // namespace tqenc
// ---------------------------------------------------------------------------------------------------------------
// C API for the Python wrapper (tools/tqenc.py, ctypes)
extern "C" {
#if defined(_WIN32)
#define TQE_EXPORT __declspec(dllexport)
#else
#define TQE_EXPORT __attribute__((visibility("default")))
#endif
TQE_EXPORT int tqe_block_bytes(int type) { return tqenc::block_bytes(type); }
TQE_EXPORT int tqe_kbits(int type) { return tqenc::type_kbits(type); }
TQE_EXPORT void tqe_decode(int type, const uint8_t* src, int64_t nblocks, float* out) {
tqenc::decode_blocks(type, src, nblocks, out);
}
// returns the summed block error; stats[0] = nonfinite blocks, stats[1] = zero blocks
TQE_EXPORT double tqe_encode(int type, const float* w, const float* h, int64_t nblocks, uint8_t* dst, int iters,
int ncand, int exact, int scale_tries, int nthreads, double* err_out, int64_t* stats) {
tqenc::Params p;
p.iters = iters;
p.ncand = ncand;
p.exact = exact;
p.scale_tries = scale_tries;
int64_t nf = 0, zb = 0;
const double e = tqenc::encode_blocks(type, w, h, nblocks, dst, p, nthreads, err_out, &nf, &zb);
if (stats) { stats[0] = nf; stats[1] = zb; }
return e;
}
TQE_EXPORT const int16_t* tqe_table(int type) { return tqenc::codebook_table(type); }
}
+106
View File
@@ -0,0 +1,106 @@
// tools/trellis/tqenc.hpp - tail-biting Viterbi ENCODER for the trellis expert formats (TQ2_T, TQK6, TQK7 of the
// agentionai llama.cpp fork, ggml types 144-146) and two experimental lower-rate versions (TQK5X, TQK4X, and the table-based TQK5T, TQK4T).
//
// Standalone (no ggml, no Strata engine): it only needs third_party/ggml/ggml-common-tq.h (the 2048-point codebook).
// The decoders it must match are src/kernels/cpu/tq_states.hpp / tq_cpu.cpp (tools/trellis/tqenc_test.cpp checks
// bit for bit against them, and the scalar / AVX2 / AVX-512 kernels against the encoder's own reconstruction).
//
// THE FORMAT (see tq_states.hpp, include/strata/kernels/cpu/tq_cpu.hpp, docs/GYRO.md):
// block = 128 weights = {fp16 d (little endian); qs[4*K]}, 32 steps t of 4 weights (weights 4t..4t+3).
// State of step t: 15 bits. weights = d * codebook(state); the state's hash x = state * 0x9e3779b1 picks two
// points lut[x >> 21] and lut[(x >> 10) & 2047] (fp16 pairs) = four values. The decoder works on the int16 table
// round(fp16 * 8192) (tq_state_table), so that table, divided by 8192, is the codebook here.
// TQK (K = 4,5,6,7): state(t) = bits [(31-t)K, (31-t)K + 15) of the qs bit stream (LSB first), circular modulo
// 32K bits. With u = 31 - t the states form a shift trellis: state(u+1) = (state(u) >> K) | (new K bits <<
// (15-K)); the K low bits of state(u) are stream symbol u. Tail-biting: state(0) closes the cycle.
// TQ2_T (K = 8): state(t) = ((qs[(t+31)%32] << 8) | qs[t]) & 0x7fff: a shift trellis in the other direction
// (state(t) = ((state(t-1) & 0x7f) << 8) | qs[t]).
// Both are a "de Bruijn" trellis of 2^15 states with 2^K branches per state, so one Viterbi step is a min over G
// groups of predecessors followed by a broadcast add (G = 2^(15-K) groups for TQK, 128 for TQ2_T), not 2^15 * 2^K
// additions. Tail-biting = a cycle of 32 states: the group of state(0) as successor equals the group of state(31)
// as predecessor. The search fixes that group c (exact: all G values; approximate: c taken from a free Viterbi pass
// on the cyclically rotated sequence, QTIP's approach, optionally the best of several rotations).
//
// New experimental types (EXPERIMENTAL_VERSION 2; not in any ggml enum or GGUF reader; ids away from the fork's 143-149):
// TQK5X (224, 22 bytes / 128 weights, 1.375 bpw) and TQK4X (225, 18 bytes, 1.125 bpw): the TQK rule with K = 5 / 4 and the
// COMPUTED codebook (src/kernels/cpu/tq_computed.hpp: two LCG words per state masked into four fp16, no table);
// TQK5T (226) and TQK4T (227): version 1, the same K = 5 / 4 layout with the fork's hashed point table (what the first
// pilots used). Same bit order, circular stream, 15-bit mask and fp16 scale in all of them.
#pragma once
#include <cstddef>
#include <cstdint>
namespace tqenc {
inline constexpr int kBlock = 128;
inline constexpr int kStates = 1 << 15;
inline constexpr int kExperimentalVersion = 2;
// ggml type ids of the fork (decoders exist) and the experimental ones (encoder + Strata CPU decoder only)
enum Type : int {
TQ2_T = 144, TQK6 = 145, TQK7 = 146, // the fork's types (hashed point table)
TQK5X = 224, TQK4X = 225, // experimental version 2: K = 5 / 4 with the computed (LUT-free) codebook, tq_computed.hpp
TQK5T = 226, TQK4T = 227 // experimental version 1: K = 5 / 4 with the fork's point table (the first pilots)
};
/// Whether the type's codebook is the computed one (TQK5X, TQK4X).
bool type_computed(int type);
/// rms of the codebook values (the first scale guess is rms(block) / this): 1.072 for the table, 0.88 for the computed code.
double codebook_rms(int type);
/// bits per step (8, 6, 7, 5, 4), 0 for any other type.
int type_kbits(int type);
inline int block_bytes(int type) { return type_kbits(type) ? 2 + 4 * type_kbits(type) : 0; }
struct Params {
int iters = 3; ///< scale refinement rounds after the first search (path given d -> d given path)
int ncand = 1; ///< tail-biting start-group candidates (rotations 16, 8, 24, 12, 20, 4, 28 ...); 1 = QTIP's
int exact = 0; ///< 1: try every start group (the exact tail-biting optimum at the current scale; slow)
int scale_tries = 1; ///< initial scales d0 * {1, 0.9, 1.1, 0.8, 1.2, ...}: the best of the first n searches
uint16_t fixed_scale = 0; ///< nonzero: this fp16 scale is used as is (no refinement); tests, planted solutions
};
struct BlockResult {
double err = 0; ///< sum_i h_i (w_i - rec_i)^2 for the stored block (h = 1 without importance weights)
float scale = 0; ///< the stored fp16 scale
int searches = 0; ///< Viterbi passes run
int status = 0; ///< 0 ok, 1 zero block (all weights zero or below fp16 resolution), 2 nonfinite input
};
/// The codebook entry of a state as the decoder sees it: four floats (int16 table / 8192, exact).
const float* codebook_state(int type, uint32_t state); // 4 floats
const int16_t* codebook_table(int type); // 32768 * 4 int16, the decoder's tq_state_table()
/// The 2048 codebook points as the decoder sees them (x, y interleaved): round(fp16 * 8192) / 8192. The GPU encoder
/// uploads this table; it must be built by the host compiler (ggml-common-tq.h makes its table __device__ under hipcc).
const float* point_table(); // 4096 floats
/// The state of step t (0..31) of a block's stream, by the decoder's rule, written bit by bit (independent of
/// tq_states.hpp). qs = the 4K stream bytes.
uint32_t block_state(int type, const uint8_t* qs, int t);
/// Decodes `nblocks` blocks (block_bytes(type) each) to 128 floats each: d * codebook, d the fp16 scale.
void decode_blocks(int type, const uint8_t* src, int64_t nblocks, float* out);
/// Encodes one block of 128 weights (importance weights h[128] or null) into block_bytes(type) bytes.
BlockResult encode_block(int type, const float* w, const float* h, uint8_t* dst, const Params& p);
/// Encodes nblocks consecutive blocks on `nthreads` threads (0: hardware concurrency). err_out (nblocks doubles) and
/// the returned sum of block errors are the objective sum h (w - rec)^2. Sets *nonfinite to the number of blocks
/// with a NaN/Inf input weight (those are written as zero blocks).
double encode_blocks(int type, const float* w, const float* h, int64_t nblocks, uint8_t* dst, const Params& p,
int nthreads, double* err_out, int64_t* nonfinite, int64_t* zero_blocks);
/// TEST HOOK: one Viterbi pass over a scaled target (T[p][4] = weights / d of processing position p, H[p][4]) and the
/// legal-path states by position. rot = first position processed, fixed_c = tail-biting group (-1 free).
float debug_viterbi(int type, const float (*T)[4], const float (*H)[4], int rot, int fixed_c, uint16_t* st);
/// Group sizes: predecessor groups G of a type; processing position p -> weight index of component j.
int debug_groups(int type);
int debug_widx(int type, int p, int j);
/// the stream bytes (4K) of a state path by position, as the encoder packs them
void debug_pack(int type, const uint16_t* st, uint8_t* qs);
// fp16 helpers (round to nearest even, like the hardware; exposed for the tests)
uint16_t float_to_half(float f);
float half_to_float(uint16_t h);
} // namespace tqenc