diff --git a/CMakeLists.txt b/CMakeLists.txt index 4228edd8..deccab84 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1250,7 +1250,7 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) endif() add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp - src/kernels/cpu/expert_layout.cpp src/kernels/cpu/q2_avx2.cpp) + src/kernels/cpu/expert_layout.cpp src/kernels/cpu/q2_avx2.cpp src/kernels/cpu/hadamard.cpp) target_include_directories(strata_kernels_cpu PUBLIC include) # Plan v0.3 P6: only the kernel files get the AVX-512 / AVX2 flags; the pool and the probe run on any x86-64, # and the engine picks the kernels at run time (cpu_avx512_ok). @@ -1358,7 +1358,8 @@ 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 @@ -1366,6 +1367,8 @@ if(STRATA_NATIVE_EXPERTS) 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/nvfp4_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") # 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") # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): 128-bit integer lanes, @@ -1379,6 +1382,10 @@ if(STRATA_NATIVE_EXPERTS) set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + # the trellis kernels: AVX2 + FMA, and AVX-512 F/BW/VL/VBMI/VNNI (exactly what cpu_avx512_ok() checks) + 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;-mavx512vnni;-mavx512vbmi;-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx") # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): SSE4.2 + AVX with # AVX2/FMA/F16C explicitly off, so a -march=native build host cannot leak AVX2 code into the file that @@ -1442,6 +1449,12 @@ if(STRATA_NATIVE_EXPERTS) add_test(NAME q8k_quant_parity_avx COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_ISA=avx $) endif() set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + # APR: the agention llama.cpp fork has MMQ instances for its trellis expert types (f62fdead0); any other ggml + # tree leaves them to the FP16 prompt path + if(STRATA_GGML_DIR AND EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/template-instances/mmq-instance-tqk6.cu") + list(APPEND _strata_mmq_types tq2_t tqk6 tqk7) + set(_strata_mmq_tq ON) + endif() # #296: OrcaRouter Q4_K_S's Q5_0 experts (Q4_K and Q5_1 come with STRATA_MMQ_KQUANTS on CUDA, S5's branch) if(STRATA_ORCA_Q4KS_MMQ) list(APPEND _strata_mmq_types q5_0) @@ -1581,6 +1594,9 @@ if(STRATA_NATIVE_EXPERTS) if(STRATA_ORCA_Q4KS_MMQ) target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) endif() + if(_strata_mmq_tq) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQ=1) + endif() target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) if(STRATA_BUILD_TESTS) @@ -1661,6 +1677,9 @@ if(STRATA_NATIVE_EXPERTS) if(STRATA_ORCA_Q4KS_MMQ) target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) endif() + if(_strata_mmq_tq) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQ=1) + endif() target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) @@ -1706,7 +1725,8 @@ if(STRATA_NATIVE_EXPERTS) if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(native_expert_parity src/kernels/native_expert_parity.cpp) target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + # strata_engine: the --load-check mode runs the engine's start-up checks (NativeDense, check_experts_gguf) + target_link_libraries(native_expert_parity PRIVATE strata_engine strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) add_executable(native_expert_bench src/kernels/native_expert_bench.cpp) target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) @@ -1738,6 +1758,16 @@ if(STRATA_NATIVE_EXPERTS) set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) endforeach() add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min) + # APR: the trellis expert types and the Hadamard activation rotation, when ggml comes from the agention fork + # (the only tree with these types; marked by its ggml-cuda/tq.cuh) + if(STRATA_GGML_DIR AND EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/tq.cuh") + foreach(_pair tqk6/tqk7 tq2_t/tq2_t) + string(REPLACE "/" "_" _name "${_pair}") + add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) + add_test(NAME native_expert_parity_hadamard_${_name} COMMAND native_expert_parity --synthetic-hadamard ${_pair}) + set_tests_properties(native_expert_parity_${_name} native_expert_parity_hadamard_${_name} PROPERTIES TIMEOUT 300) + endforeach() + endif() # #290: the BF16 token embedding (--embd-gguf) gathered and dequantized bit for bit add_test(NAME native_expert_parity_bf16_embd COMMAND native_expert_parity --bf16-embd) endif() @@ -1791,6 +1821,22 @@ if(STRATA_BUILD_TESTS) set_tests_properties(q2_bitplane_parity PROPERTIES ENVIRONMENT "STRATA_Q2_BITPLANE=1") endif() + if(STRATA_NATIVE_EXPERTS) + # APR port: a Hadamard-folded trellis expert (TQ2_T / TQK6 / TQK7) on the CPU path vs llama.cpp's graph for the + # same weights (synthetic; needs STRATA_GGML_DIR = a ggml with the trellis types, else it reports and fails) + add_executable(native_hadamard_test src/kernels/cpu/native_hadamard_test.cpp) + target_link_libraries(native_hadamard_test PRIVATE strata_kernels_cpu strata_artifact) + add_test(NAME native_hadamard_test COMMAND native_hadamard_test) + set_tests_properties(native_hadamard_test PROPERTIES TIMEOUT 300) + # the CPU trellis kernels (tq_cpu.hpp): AVX2 / AVX-512 vs the scalar kernel bit for bit, vs ggml-cpu's vec_dot + # and to_float, plain and with the Hadamard rotation; `tq_cpu_parity --bench` is the micro-benchmark + add_executable(tq_cpu_parity src/kernels/cpu/tq_cpu_parity.cpp) + target_link_libraries(tq_cpu_parity PRIVATE strata_kernels_cpu) + add_test(NAME tq_cpu_parity COMMAND tq_cpu_parity) + add_test(NAME tq_cpu_parity_avx2 COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_AVX2=1 $) + set_tests_properties(tq_cpu_parity tq_cpu_parity_avx2 PROPERTIES TIMEOUT 300) + endif() + add_executable(expert_parity src/kernels/cpu/expert_parity.cpp) target_link_libraries(expert_parity PRIVATE strata_kernels_cpu) # The pack is a REQUIRED input, not an optional one: this test compares against a real expert blob, and a diff --git a/apps/host/src/lib/native-catalog.ts b/apps/host/src/lib/native-catalog.ts index 0813f75b..aee650b4 100644 --- a/apps/host/src/lib/native-catalog.ts +++ b/apps/host/src/lib/native-catalog.ts @@ -2,16 +2,16 @@ import type {NativeFamily,NativeSize} from './native'; import {tr} from './i18n'; export interface CatalogVersion extends NativeSize{sourceFamily:string;edition:string;images:boolean} export interface CatalogModel extends Omit{sizes:CatalogVersion[]} -export function nativeVersionLabel(model:string){return tr(({Q2_0:'Fastest',IQ2_XS:'Compact',IQ3_XXS:'Balanced',IQ3_S:'High quality',IQ1_M:'Coding'} as Record)[model]??model);} +export function nativeVersionLabel(model:string){return tr(({Q2_0:'Fastest',IQ2_XS:'Compact',IQ3_XXS:'Balanced',IQ3_S:'High quality',IQ1_M:'Coding','Gyro-S':'Smallest','Gyro-M':'Small memory'} as Record)[model]??model);} export const catalogVersionLabel=(version:CatalogVersion)=>{const label=nativeVersionLabel(version.model);return [tr(version.edition),label===version.model&&version.edition?'':label].filter(Boolean).join(' · ');}; /** Display groups are distinct from the engine's installation family IDs. */ export function nativeCatalogModels(families:NativeFamily[]):CatalogModel[]{ if(!families.length)return[]; const groups:CatalogModel[]=[{family:'qwen3.8',title:'Qwen3.8-Flash-Next',about:'',experimental:false,images:false,sizes:[]},{family:'qwen3.6',title:'Qwen3.6-35B-A3B',about:'',experimental:false,images:false,sizes:[]}]; for(const family of families){ - const target=/qwen3[._-]?6|35b[-_]?a3b/i.test(family.title+' '+family.family)?groups[1]:['qwen','swift','coder','unsloth'].includes(family.family)||/qwen3[._-]?8|flash.next/i.test(family.title)?groups[0]:undefined; + const target=/qwen3[._-]?6|35b[-_]?a3b/i.test(family.title+' '+family.family)?groups[1]:['qwen','swift','coder','unsloth','gyro'].includes(family.family)||/qwen3[._-]?8|flash.next/i.test(family.title)?groups[0]:undefined; if(!target)continue; - const edition=target===groups[0]?({swift:'Swift 1.5',coder:'Coder',unsloth:'Unsloth'} as Record)[family.family]??'':''; + const edition=target===groups[0]?({swift:'Swift 1.5',coder:'Coder',unsloth:'Unsloth',gyro:'Gyro'} as Record)[family.family]??'':''; target.images ||= family.images; target.sizes.push(...family.sizes.map(size=>({...size,sourceFamily:family.family,edition,images:family.images}))); } diff --git a/apps/host/tests/languages-and-catalog.test.mjs b/apps/host/tests/languages-and-catalog.test.mjs index d197f013..1cd8a25f 100644 --- a/apps/host/tests/languages-and-catalog.test.mjs +++ b/apps/host/tests/languages-and-catalog.test.mjs @@ -44,6 +44,14 @@ test('only the two requested display families exist; engine IDs and per-version assert.deepEqual(nativeCatalogModels([]),[]); }); +test('the Gyro sizes join the Qwen3.8 group as their own edition, without images',()=>{ + setTranslationLanguage('en'); + const groups=nativeCatalogModels([family('qwen','Qwen3.8-Flash-Next',true,[size('q2_0','Q2_0')]),family('gyro','Qwen3.8-Flash-Next (Gyro)',false,[size('gyro-gyro-s','Gyro-S'),size('gyro-gyro-m','Gyro-M')])]); + assert.deepEqual(groups[0].sizes.map(item=>[item.sourceFamily,item.model,item.edition,item.images]),[['qwen','Q2_0','',true],['gyro','Gyro-S','Gyro',false],['gyro','Gyro-M','Gyro',false]]); + assert.equal(catalogVersionLabel(groups[0].sizes[1]),'Gyro · Smallest');assert.equal(catalogVersionLabel(groups[0].sizes[2]),'Gyro · Small memory'); + assert.equal(groups[1].sizes.length,0); +}); + test('empty default chat titles follow the interface language while chosen names stay verbatim',()=>{ setTranslationLanguage('de');const empty={title:'New conversation',messages:[]};assert.notEqual(sessionTitle(empty),'New conversation');assert.equal(sessionTitle({...empty,defaultTitle:false}),'New conversation');assert.equal(sessionTitle({title:'Ready',messages:[]}), 'Ready');assert.equal(sessionTitle({...empty,messages:[{role:'user',content:'hello'}]}),'New conversation');setTranslationLanguage('en'); }); diff --git a/docs/GYRO.md b/docs/GYRO.md new file mode 100644 index 00000000..ca8d890b --- /dev/null +++ b/docs/GYRO.md @@ -0,0 +1,269 @@ +# Gyro (agentionai rotor quants) on Strata + +Gyro-S and Gyro-M are Qwen3.8-Flash-Next quantizations by agentionai +([agentionai/Qwen3.8-Flash-Next-Gyro-GGUF](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF)): the routed +experts are stored as trellis-coded blocks (ggml types TQ2_T, TQK6, TQK7) in a Hadamard-rotated basis. Strata reads the +published files unchanged. **Setup lists them as a model family of their own** ("Qwen3.8-Flash-Next (Gyro)"); neither +is anybody's default. + +| | Gyro-S | Gyro-M | +| --- | --- | --- | +| File | `Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf` | `Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf` | +| **Download** (the n-gram table is inside the file) | **58.5 GB** | **92.0 GB** | +| **Memory it needs** (VRAM + RAM together) | **27.6 GB** | **35 GB** | +| Experts (trellis) | TQK6 gate/up, TQK7 down | TQ2_T | +| In plain words | the smallest option, for PCs with little memory; lower quality than the 2-3-bit sizes | about IQ3_XXS quality with about 20% less GPU memory; decodes about 20% slower than Q2_0 on 12 GB cards | + +About half of each file is the n-gram (PLE) table: it stays on the SSD and is read row by row for every token, so keep +the file on a fast local drive. The memory figure is what the weights take once loaded. + +Not defaults, by measurement (our evaluation, 2026-10): against Q2_0 at the same GPU bytes Gyro-M halves the KL +divergence (0.159 against 0.312 on 128 chunks) and is level with IQ3_XXS (0.157), but decodes 17-21% slower on a 12 GB +card (RTX 3060) and an R9700, and its reasoning set scored lower than Q2_0's (49/60 against 57/60). Gyro-S is 13% worse +in KL than IQ2_XS (0.268 against 0.236) with 24% fewer bytes. So: pick Gyro-S where nothing bigger fits, Gyro-M when +the 20% memory saving over IQ3_XXS matters. Setup and the MCP server mention them only where the other sizes do not +fit the PC; they warn, never refuse. Gyro-L (agentionai's 50 GiB file, 2026-10-12) is not supported: it uses another +trellis family (types 147-149) that the engine does not have. + +## Install + +```sh +./setup.sh --setup --family gyro --model Gyro-S # or Gyro-M; Windows: START-HERE.bat --setup ... +``` + +Setup downloads the pinned revision of the file (size and SHA-256 checked), prepares the pack (`tools/iq_pack.py +--compat-bf16`: the Hadamard table and the dense weights, 1.5 GB), the draft head (Strata's own MTP head, prepared from +the original model as for every Qwen3.8-Flash-Next file) and the start script. Needs engine 0.1.46 or newer; a +ready-made engine that is older is replaced by one compiled from this source. + +**Supported:** NVIDIA (CUDA, Linux and Windows) and AMD (HIP, experimental: the authors validated gfx1151; we ran +gfx1201 with identical output to rc2). **Not supported:** Intel Arc (SYCL) and Apple Metal: the engines there have no +trellis kernels; the Metal engine refuses the file at load with the reason. Images are off for these files. + +**Prompt speed and the ggml build.** The trellis prompt kernels (MMQ) come from agentionai's llama.cpp fork +(MIT, `STRATA_GGML_DIR`). A build against upstream ggml works and gives the same answers, but reads prompts through the +FP16 path, which is slower. For the fast prompt path compile with the fork's ggml: + +```sh +git clone https://github.com/agentionai/llama.cpp ../agention-llama.cpp +cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON \ + -DCMAKE_CUDA_ARCHITECTURES=86 -DSTRATA_GGML_DIR=$PWD/../agention-llama.cpp +# AMD: -DSTRATA_ENABLE_HIP=ON -DSTRATA_PREFILL_MMQ=ON -DCMAKE_HIP_ARCHITECTURES=gfx1201 -DSTRATA_GGML_DIR=... +``` + +## Credit and licenses + +The trellis types, the Hadamard rotation, the CPU and GPU kernels and the pack step were written by Laurent Zuijdwijk +(agentionai) in agentionai/Strata `rc2` (9ff02c9, MIT, Strata v0.1.40.3 plus Gyro) and ported here commit by commit with +his authorship kept; `third_party/ggml/ggml-common-tq.h` and the MMQ instances come from agentionai/llama.cpp (MIT, the +ggml authors). The weights are agentionai's quantization of Qwen3.8-Flash-Next under the Qwen Community License 1.0 +(). + +## How it runs (by hand) + +The rest of this page is the authors' own guide for a manual install and their measurements on their machines (RTX 5090, +3090, 4090 and a Strix Halo, with Strata rc2). The numbers are theirs; ours are in the next section. + +## 1. Build + +Setup does these steps for you; by hand, from this checkout. For the fast prompt path Strata's GGML dependency is the agentionai llama.cpp fork, which has the trellis types: + +```sh +git clone --depth 1 https://github.com/agentionai/llama.cpp ../agention-llama.cpp +# NVIDIA. RTX 50 series: use CUDA 13 (CUDA 12.8 crashes the prompt path on sm_120: issues #220, #224) +cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON \ + -DCMAKE_CUDA_ARCHITECTURES=120 -DSTRATA_GGML_DIR=$PWD/../agention-llama.cpp +# AMD (experimental: kernel parity and an end-to-end run validated on gfx1151; in a non-root container add +# --group-add $(getent group render | cut -d: -f3), otherwise HIP finds no device) +cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_HIP=ON -DSTRATA_PREFILL_MMQ=ON \ + -DCMAKE_HIP_ARCHITECTURES=gfx1201 -DSTRATA_GGML_DIR=$PWD/../agention-llama.cpp +cmake --build build -j +python3 -m venv .venv && .venv/bin/pip install -r requirements.txt +``` + +## 2. Download and pack + +```sh +.venv/bin/pip install huggingface_hub hf_transfer +HF_HUB_ENABLE_HF_TRANSFER=1 .venv/bin/hf download agentionai/Qwen3.8-Flash-Next-Gyro-GGUF \ + Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf --local-dir models +.venv/bin/python tools/iq_pack.py \ + --gguf models/Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf --out packs/gyro-s --compat-bf16 +build/native_expert_parity --load-check packs/gyro-s models/Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf +``` + +The pack is 1.5 GB (dense weights, tokenizer, the Hadamard and expert tables); the experts are read from the +GGUF. Keep the GGUF on a fast local SSD: the n-gram table is read from it for every token. +`--load-check` must end with `0 failures`. + +## 3. Draft head + +```sh +.venv/bin/python tools/mtp_fetch.py fetch --out mtp +.venv/bin/python tools/mtp_pack.py --src mtp --experts q2_0 --out mtp/mtp-q2_0.gguf +.venv/bin/python tools/mtp_rt.py --gguf mtp/mtp-q2_0.gguf --out mtp/rt +cp data/draft_vocab.bin mtp/rt/draft_vocab.bin +``` + +## 4. Serve + +Save as `strata-gyro-s.json` at the repository root: + +```json +{ + "exe": "build/strata", + "args": [ + "--pack", "packs/gyro-s", + "--native", "models/Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf", + "--expert-profile", "data/expert-profile.bin", "--expert-cache", "auto", + "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", + "--mtp", "mtp/rt", "--max-context", "131072", "--kv", "int8" + ], + "cwd": ".", + "tokenizer": "packs/gyro-s/tokenizer", + "model_name": "gyro-s-strata", + "log": "strata-gyro-s.log", + "host": "127.0.0.1", + "port": 8080 +} +``` + +```sh +.venv/bin/python -m serve.server --engine strata --config strata-gyro-s.json --port 8080 +``` + +The web interface is at `http://127.0.0.1:8080`; API clients use `http://127.0.0.1:8080/v1` (OpenAI) or +`/v1/messages` (Anthropic). `--expert-cache auto` sizes the expert cache to the free VRAM: on a 32 GB card at +128k context it holds 23,464 of 24,576 experts (22.9 GiB). On smaller cards it holds fewer and streams the rest +from RAM; nothing else changes. + +## Measured here (the port, 2026-10-15/16) + +One AMD Radeon AI PRO R9700 (gfx1201, ROCm 7), one card of four, exclusive box lock, `--prefill auto --spec 4 --spec-min-p 0.5 +--mtp --kv int8`, 22K context, interleaved pairs (the arm that goes first alternates), medians, the files of the first +Gyro release (2026-10-07). A = agentionai/Strata rc2 9ff02c9, B = this port. + +| B, ggml of | file | decode tok/s A / B (B/A) | pairs B faster | prompt 4K ms A / B | prompt 20K ms A / B | +| --- | --- | ---: | --- | ---: | ---: | +| agentionai fork | Gyro-S | 85.4 / 89.7 (1.051) | 5/5 | 5418 / 5313 (0.98) | 14358 / 13859 (0.97) | +| agentionai fork | Gyro-M | 72.7 / 82.7 (1.136) | 5/5 | 5183 / 5520 (1.07) | 13421 / 14164 (1.06) | +| upstream | Gyro-S | 85.3 / 89.6 (1.050) | 5/5 | 5425 / 6939 (1.28) | 14364 / 21677 (1.51) | + +Decode is faster than rc2's because the port sits on the newer Strata (0.1.45); the same engine change makes IQ3_XXS 7% faster +(rc2 86.9, port 93.1 tok/s, 2 pairs). Prompts of the ISTA files gained 11-16% from it too (IQ3_XXS 4K 6184 to 5480 ms, 20K +16587 to 13864 ms); Gyro-M's prompts did not and are 5-7% slower than rc2's, Gyro-S's are 2-3% faster. The cause for Gyro-M is +not isolated (`STRATA_GFX12_DEFAULTS=0` does not give it back). With **upstream ggml** (the ready-made engine) the trellis +prompt kernels are missing and prompts go through the FP16 path: 28% (4K) to 51% (20K) slower than rc2, and a different +rounding (the answer after a 4K prompt can differ). Decode is unaffected. That is why a source build against the fork's ggml is +the fast configuration. + +Identity (the fixed gate flags, 10 prompts, exact_pp 4096 and 20000 tokens, same card for both arms): + +- Q2_0 and IQ3_XXS, f-split against the port (upstream ggml): 10/10 identical, residual dumps and outputs IDENTICAL. +- Gyro-S and Gyro-M, rc2 against the port (fork ggml): 10/10 identical; exact_pp 4096 / 20000 residual dumps and outputs + IDENTICAL when run alone (a run beside other engines on the box once showed a different dump: not reproducible alone). +- The pack step (`tools/iq_pack.py --compat-bf16`) writes byte-identical files to rc2's tools for Gyro-S. + +## Measured (the authors', rc2) + +All runs: greedy or the stated sampling, same prompt tokens as llama.cpp, MTP draft `--spec 4 --spec-min-p 0.5`, +int8 KV. "llama.cpp" is the agentionai fork with the CUDA trellis fixes (in its `main` since 2026-10-04). + +### RTX 5090 (32 GB), Gyro-S, all experts on the GPU (2026-10-03) + +Decode tokens/s, single prompts of 34-177 tokens, 384 new tokens, `--max-context 16384` (all 24,576 experts cached): + +| | prose | JSON | code | +|---|---:|---:|---:| +| Strata | 139.9 | 221.3 | 209.0 | + +Server, rc2's `gyro_setup.sh` config (128k context, 23,463 experts cached), thinking off, temperature 0.7, +top-k 20, top-p 0.95, min-p 0.05, 512 new tokens, 3 repetitions: + +| | prose | JSON | code | copy | +|---|---:|---:|---:|---:| +| Strata | 131.7 | 200.1 | 195.2 | 201.8 | +| llama.cpp, MTP draft | 116.8 | 213.0 | 179.0 | 220.7 | +| llama.cpp, no draft | 121.8 | 123.2 | 122.5 | 121.2 | + +Long real-text prompts, prefill tokens/s: 4k tokens 3,456 (llama.cpp 2,520), 16k tokens 4,883 (llama.cpp 2,471). + +### RTX 5090, Gyro-M (2026-10-03) + +The experts (29.9 GiB) do not all fit next to the KV cache; `auto` caches 18,007 of 24,576. Same server protocol: +prose 113.8, JSON 170.8, code 153.0, copy 175.7 tokens/s; prefill 4k 3,369, 16k 4,854 tokens/s. llama.cpp needs +`-ncmoe 8` for this file on a 32 GB card and decodes at 70.8 tokens/s without a draft. + +### RTX 3090 (24 GB), 2026-10-03 + +Same server protocol, 128k context, `auto` cache: + +| | experts cached | prose | JSON | code | copy | prefill 4k | prefill 16k | +|---|---:|---:|---:|---:|---:|---:|---:| +| Gyro-S | 15,756 | 31.8 | 45.2 | 42.2 | 45.1 | 1,402 | 1,863 | +| Gyro-M | 11,811 | 27.8 | 39.4 | 34.4 | 37.7 | 1,363 | 1,910 | +| llama.cpp, Gyro-S, `-ncmoe 10`, 32k context, no draft | (10 layers on the CPU) | 16.0 | 16.2 | 16.2 | 16.5 | 468 (`-ncmoe 11`) | 479 | + +On a 24 GB card, cache misses run on the CPU, so the CPU matters: this box had a Zen 2 EPYC (AVX2, no AVX-512). +The llama.cpp row is the build before the CUDA trellis fixes; those added about 3 % at 24 GB, where the CPU layers +dominate. + +The Strata rows predate Strata's own CPU kernels for the trellis types (`src/kernels/cpu/tq_*.cpp`, AVX2 and +AVX-512, picked at run time). Before them a cache miss ran ggml-cpu's `vec_dot`, one token at a time; the new kernels +take about 45 % of its time per expert on AVX2 and decode a block once for all the tokens of a verify window +(`build/tq_cpu_parity --bench` measures them on your CPU). `STRATA_NO_TQ_KERNELS=1` goes back to ggml-cpu; +`STRATA_TQ_ISA=avx2` or `scalar` caps the instruction set (for comparisons). + +### Smaller caches (RTX 5090, 2026-10-02, before the int8 decode kernels) + +| Expert cache | prose | JSON | code | +|---|---:|---:|---:| +| 24,576 slots (all experts) | 116.4 | 194.3 | 173.5 | +| 22,000 slots | 111.4 | 175.7 | 166.1 | +| 9,000 slots (about a 16 GB card's room) | 81.4 | 74.0 | 96.8 | +| 3,000 slots (about an 8 GB card's room) | 48.0 | 52.4 | 57.9 | + +The smaller caches were emulated on the 5090 (fast GPU, PCIe 5.0 x16 at ~51 GB/s). A real 8 or 16 GB card is a +slower GPU, often on a slower link: read those rows as "it stays usable", not as a prediction for a specific card. +The decoded output was read and is fluent and correct; token-level parity against llama.cpp has not been +checked. A real chat at 128k context worked through the web interface. + +### Two GPUs (2026-10-04, 2× RTX 4090, no NVLink/P2P) + +- **Layer split** (Strata splits the layers across both cards automatically) works with Gyro, including the + idle-card prompt helper (`STRATA_PREFILL_HELP=1`). Repeated runs give identical output. +- **Decode with a second card** (`--peer-device 1` or `--expert-cache-device1 auto`) works and matches single-GPU output. +- **Prompt processing on the peer card** needs GPU-to-GPU access (NVLink or data-centre GPUs); without it Strata keeps + the prompt on the first GPU and logs `no P2P`. + +Single RTX 4090 smoke run (Gyro-S, MTP draft, greedy): code 107.5, prose 84.3, JSON 76.3 tokens/s. + +## Numerics + +- **Decode** (Strata's own expert kernels) reads the trellis weights through an int8 copy of the codebook with one + global scale (`tq_lut_i8`, relative RMS error 0.85 % of the codebook's standard deviation, far below the + quantization error itself), against q8_1 activations. +- **Prompt processing** decodes them otherwise: the FP16 path through the fp16 codebook (`tq_lut_f16`, what GGML's + own dequantizer reads); the MMQ path through the llama.cpp fork's kernels, which read the int8 codebook as well + on the fork's current `main`. +- So decode and prompt results agree within tolerance, not bit for bit. `native_expert_parity` checks one expert + on the decode kernels against GGML's float dequantizer and a float SwiGLU: relative L1 error below 3e-2, the + bound every expert type gets there. Its "bitwise equal" lines compare Strata's decode-once and per-entry decode + kernels with each other, not with a float reference. + +## Known limits + +- **Not in this port** (rc2 has them; see the list at the end of this page): the prompt helper on a second GPU for a Gyro + pack. Setup of two cards still runs the layer split and the decode peer; the prompt peer says it is not used for a + Hadamard-folded pack and the prompt stays on the first card. Gyro-L, Intel Arc (SYCL) and Apple Metal are not supported. +- **Source builds:** the SYCL tree builds with these sources (P1006, 0 errors) but has no trellis GPU kernels; the Metal + engine builds and refuses the file at load (`native_expert_supported`). + +- **Not measured yet:** token parity against llama.cpp. +- **Benchmark mode only:** `strata --tokens-file ... --max-new N` decodes N tokens past the end of the answer; + compare speeds only up to the answer's end. +- **AMD:** the trellis kernels pass parity on gfx1151 (ROCm 7.2.1) and a short end-to-end run there generated + correctly (~28-31 tokens/s); no speed tuning or RDNA4 run yet. +- **Gyro-M:** 29.9 GiB of experts do not all fit a 32 GB card next to the KV cache; `auto` streams the rest. +- **Not validated end to end yet** (Strata runs them and logs a warning): an AMD GPU other than gfx1151, and + prompt processing on a peer GPU over P2P. diff --git a/docs/MODELS.md b/docs/MODELS.md index ebfeb100..9427d7b1 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -144,6 +144,26 @@ speed bound and NVIDIA/AMD/Intel details: [QUANTS.md](QUANTS.md); the files: [UD START-HERE.bat --setup --family unsloth --model UD-Q5_K_XL ``` + + +### Gyro-S and Gyro-M (agentionai) + +The fifth version in setup's menu (`--family gyro`) is **agentionai's Gyro quantizations** of the same model: trellis-coded +experts in a rotated basis. They are the smallest options and never setup's default. The download includes the +28 GB n-gram table; the memory figure is VRAM and RAM together. + +| Size | Download | Memory it needs (VRAM + RAM) | In plain words | +| --- | ---: | ---: | --- | +| **Gyro-S** | 58.5 GB | 27.6 GB | the smallest option, for PCs with little memory; lower quality | +| **Gyro-M** | 92.0 GB | 35 GB | about IQ3_XXS quality with about 20% less GPU memory; decodes about 20% slower than Q2_0 on 12 GB cards | + +NVIDIA, and AMD (experimental); not Intel Arc or the Mac. Images are off. Details, measurements and credit: +[GYRO.md](GYRO.md). + +``` +START-HERE.bat --setup --family gyro --model Gyro-S +``` + ### OrcaRouter Uncensored IQ3_XXS For **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](ORCA.md). It needs an diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp index 7e646a4b..5b67f54b 100644 --- a/include/strata/artifact/gguf_reader.hpp +++ b/include/strata/artifact/gguf_reader.hpp @@ -115,6 +115,15 @@ inline const char* ggml_type_name(uint32_t t) { return "Q1_0"; case 42: return "Q2_0"; + // Agention's llama.cpp fork: the APR trellis expert types (docs/GYRO.md) + case 143: + return "PTQ1_0"; + case 144: + return "TQ2_T"; + case 145: + return "TQK6"; + case 146: + return "TQK7"; default: return "?"; } @@ -225,6 +234,24 @@ inline bool block_geometry(uint32_t t, int& elems, int& bytes) { elems = 64; bytes = 18; return true; + // APR trellis types: 128 values = fp16 scale + 32 steps of K bits (K = 8 TQ2_T, 6 TQK6, 7 TQK7); + // PTQ1_0 = 26 B of base-3 digits + fp16 scale + case 143: + elems = 128; + bytes = 28; + return true; + case 144: + elems = 128; + bytes = 34; + return true; + case 145: + elems = 128; + bytes = 26; + return true; + case 146: + elems = 128; + bytes = 30; + return true; default: return false; } diff --git a/include/strata/core/peer_experts.hpp b/include/strata/core/peer_experts.hpp index a6e3766a..cd9d53bd 100644 --- a/include/strata/core/peer_experts.hpp +++ b/include/strata/core/peer_experts.hpp @@ -98,6 +98,8 @@ private: void* h_meta_ = nullptr; void* d_meta_ = nullptr; // groups: ptr | start | dst | tok | count uint8_t* d_q8_ = nullptr; void* d_scratch_ = nullptr; + const float* d_sx_ = nullptr; // APR: device sign vectors (x: H, h: FF); nullptr = identity + const float* d_sh_ = nullptr; std::vector row_of_; ///< compact row -> original entry int64_t launched_rows_ = 0; bool launched_direct_ = false; diff --git a/include/strata/core/remote_experts.hpp b/include/strata/core/remote_experts.hpp index d499c031..4e3be387 100644 --- a/include/strata/core/remote_experts.hpp +++ b/include/strata/core/remote_experts.hpp @@ -87,6 +87,9 @@ private: float* d_out_ = nullptr; uint8_t* d_q8_ = nullptr; float* d_scales_ = nullptr; + float* d_xr_ = nullptr; // APR: the Hadamard-rotated expert input (CAP x H) + const float* d_sx_ = nullptr; // APR: device sign vectors (x: H, h: FF); nullptr = identity + const float* d_sh_ = nullptr; void* d_scratch_ = nullptr; void* d_meta_ = nullptr; ///< one contiguous upload of grouped indices, instead of five small copies int32_t* d_start_ = nullptr; diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index e3d26155..d1215afb 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -528,6 +528,10 @@ private: static constexpr int64_t kPcieGroupRows = 4; // the PCIe call's groups side by side (of <= 16) uint8_t* hit_xq_ = nullptr; uint8_t* nat_xq_ = nullptr; // plan v0.3 P6: q8_1 activations for a native pack's grouped experts + float* nat_xr_ = nullptr; // APR: the Hadamard-rotated expert input (the shared expert and the CPU keep xm); nullptr + // unless some layer's gate/up is folded + const float* had_sx_ = nullptr; // APR: device sign vectors for x (n_embd) and h (n_ff); nullptr = identity + const float* had_sh_ = nullptr; float* hit_xs_ = nullptr; void* hit_scratch_ = nullptr; float *head_mixed_ = nullptr, *head_inj_ = nullptr, *head_logits_ = nullptr; diff --git a/include/strata/kernels/cpu/expert_layout.hpp b/include/strata/kernels/cpu/expert_layout.hpp index 6b3fddb6..b78528c7 100644 --- a/include/strata/kernels/cpu/expert_layout.hpp +++ b/include/strata/kernels/cpu/expert_layout.hpp @@ -96,6 +96,8 @@ const ExpertLayout& expert_layout(); bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err); /// The newest native_experts.txt this engine reads. v4 = v3 plus the per-role shard column `gate,up,down`, /// written only when some layer's roles are in different shards (every other pack stays v3, byte for byte). -inline constexpr int kExpertLayoutVersion = 4; +/// v5 = v4 plus `hadamard.txt` beside it: Hadamard-folded experts (hadamard.hpp), written only for such models, +/// so an engine that cannot rotate the activations refuses the pack instead of running it wrong. +inline constexpr int kExpertLayoutVersion = 5; } // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/hadamard.hpp b/include/strata/kernels/cpu/hadamard.hpp new file mode 100644 index 00000000..43b3fcfc --- /dev/null +++ b/include/strata/kernels/cpu/hadamard.hpp @@ -0,0 +1,51 @@ +// include/strata/kernels/cpu/hadamard.hpp - the activation-side transform of Hadamard-folded experts. +// +// Some GGUFs (Agention's APR "Gyro" files) store their routed experts in a block-Hadamard-rotated basis: the +// encoder replaced each expert weight W by W' = W * diag(s) * H_b^T per block of b input columns, where H_b is +// the normalized Sylvester-Walsh-Hadamard matrix (entry (-1)^popcount(r & c) / sqrt(b)) and s a +/-1 sign +// vector of the input width. The GGUF says so in its `prism.hadamard.*` metadata. Since H_b is orthonormal and +// symmetric, W x = W' (H_b (s * x)): the runtime must apply y = H_b (s * x), per block of b values, to every +// activation that enters a folded weight - the gate/up input x and the down input h - before quantizing it. +// Skipping it on any path (CPU or GPU, decode or prompt) gives plausible-looking garbage, so a pack that carries +// rotated experts is refused by an engine path that cannot apply it. +// +// tools/iq_pack.py reads the metadata and writes `/hadamard.txt` (and native_experts.txt v5, so an engine +// older than this refuses the pack). The format: +// +// # strata hadamard v1 ... (comment lines start with #) +// block 128 the rotation block (a power of two) +// signs one line per sign-vector width (none = identity signs) +// layer which roles of layer l are folded (gate == up: one input) +#pragma once + +#include +#include +#include +#include + +namespace strata::kernels::cpu { + +struct HadamardSpec { + int block = 0; ///< 0: no Hadamard-folded experts + std::map> signs; ///< width -> +1/-1 per input value (empty: identity signs) + std::vector roles; ///< per layer: bit 0 gate, bit 1 up, bit 2 down + bool any() const { return block > 0; } + bool gu(int64_t layer) const { return block > 0 && (roles[(size_t) layer] & 3u) != 0; } + bool down(int64_t layer) const { return block > 0 && (roles[(size_t) layer] & 4u) != 0; } +}; + +/// Parses `path` (hadamard.txt) for a model of `n_layers` layers. False with a reason when it is malformed. +bool hadamard_parse(const std::string& path, int64_t n_layers, HadamardSpec& h, std::string& err); + +/// The process-wide spec (set by expert_layout_load from the pack; empty for every other pack). +const HadamardSpec& hadamard_spec(); +void hadamard_set(HadamardSpec h); +/// The sign vector of `width` in the process-wide spec, or nullptr (identity signs). The pointer stays valid +/// until the next hadamard_set. +const float* hadamard_signs(int width); + +/// In place: x[i] *= signs[i] (when signs is not null), then each block of `block` values -> H_block x / sqrt(block). +/// `n` must be a multiple of `block`. +void hadamard_rotate(float* x, int n, int block, const float* signs); + +} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/cpu/native_expert.hpp b/include/strata/kernels/cpu/native_expert.hpp index 895f90c2..fbac3505 100644 --- a/include/strata/kernels/cpu/native_expert.hpp +++ b/include/strata/kernels/cpu/native_expert.hpp @@ -32,6 +32,12 @@ struct NativeFmt { /// projection's FP32 output: gate * s_gate, up * s_up, down * s_down. Do not fold s_down into up: the hidden /// drops to ~1e-5 and its q8 block scale becomes an FP16 subnormal (expert error 2-12% instead of 1.1%). size_t tail_off = 0; + /// prism.hadamard (hadamard.hpp): the experts of this layer are stored in a rotated basis, and + /// native_quant_act / native_quant_h apply y = H_block (signs * x) before quantizing. had_block 0 = none. + int had_block = 0; + bool had_gu = false, had_d = false; + const float* gu_signs = nullptr; ///< n_embd signs for x (nullptr: identity) + const float* d_signs = nullptr; ///< n_ff signs for h (nullptr: identity) }; constexpr int kNvfp4Type = 40; constexpr size_t kNvfp4Tail = 16; @@ -41,9 +47,9 @@ bool native_experts_available() noexcept; /// Fills `f` for a layer; false (with a reason) when ggml-cpu has no dot product for a type. bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err); -/// x (n_embd floats) -> the gate/up activation (act_bytes). +/// x (n_embd floats) -> the gate/up activation (act_bytes), rotated first when the layer is Hadamard-folded. void native_quant_act(const NativeFmt& f, const float* x, void* dst); -/// h (n_ff floats) -> the down activation (h_bytes). +/// h (n_ff floats) -> the down activation (h_bytes), rotated first when the layer is Hadamard-folded. void native_quant_h(const NativeFmt& f, const float* h, void* dst); /// From how many tokens native_gu_rows gives this gate/up type to a multi-token kernel (#152; ggml-cpu's per-token dot diff --git a/include/strata/kernels/cpu/tq_cpu.hpp b/include/strata/kernels/cpu/tq_cpu.hpp new file mode 100644 index 00000000..132cb99e --- /dev/null +++ b/include/strata/kernels/cpu/tq_cpu.hpp @@ -0,0 +1,84 @@ +// include/strata/kernels/cpu/tq_cpu.hpp - the trellis expert formats (TQ2_T / TQK6 / TQK7, ggml types 144-146 of the +// agention llama.cpp fork) on the CPU: decode-and-dot against Q8_0 activations (ggml's block_q8_0), one or several +// tokens per call, on AVX-512, AVX2 or plain C++. +// +// THE FORMAT (third_party/ggml/ggml-common-tq.h): a 128-weight block is {fp16 d; 32 steps of K bits} (K = 8 / 6 / 7). +// Step t has a 15-bit state; the state's hash picks two points (pairs) of a 2048-point fp16 codebook, which are +// weights 4t..4t+3, times d. +// +// THE DECODE: a 32768 x 4 int16 table maps a state straight to its four weights at scale 2^13 (256 KiB, the +// approach of the fork's ggml-cpu vec_dot): one 8-byte lookup per four weights, no hash. The int16 rounding is +// exact for codebook values >= 2^-3 in magnitude and within 2^-14 below that; it is the same table, rounded the +// same way, as the fork's ggml-cpu kernels. +// +// THE ARITHMETIC, identical on every ISA so every path gives the same bits (and so does any token-group size): +// S[i][k] = sum_j w16[i][32k + j] * q8[i][k][j] exact in int32 (|w16| < 2^15, |q8| <= 127) +// acc[k] = fma((float) S[i][k], d_w[i] * d_a[i][k], acc[k]) for blocks i in order, k = 0..3 +// dot = ((acc[0] + acc[1]) + (acc[2] + acc[3])) * 2^-13 +// i.e. four float accumulators, one per Q8_0 sub-block position, each a fixed sequential chain. It differs from +// ggml-cpu's vec_dot (same integers, other float summation order) by float rounding only. +// +// THE KERNELS: `tq_isa()` picks AVX-512 (F/BW/VL/VBMI/VNNI, cpu_avx512_ok) or AVX2 (cpu_avx2_ok) at run time; the +// scalar kernel is the reference (on a CPU without AVX2 the engine keeps ggml-cpu's vec_dot, see tq_kernels_enabled). +// STRATA_TQ_ISA=scalar|avx2|avx512 caps the choice (tests, A/B); STRATA_NO_TQ_KERNELS=1 makes native_expert.cpp use +// ggml-cpu's vec_dot instead (the previous path). +#pragma once + +#include +#include + +namespace strata::kernels::cpu { + +enum class TqIsa : int { scalar = 0, avx2 = 1, avx512 = 2 }; + +/// TQ2_T (144), TQK6 (145), TQK7 (146). +bool tq_supported(int ggml_type) noexcept; +/// Bits per step: 8, 6, 7 (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). +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 (filled on first use; thread-safe). +const int16_t* tq_state_table(); + +/// 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 = 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 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 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 uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt, + float* const* out, int r0, int r1); +} // namespace tq_detail + +} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index 0a39f646..bc5c5a04 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -48,6 +48,10 @@ struct NativeExpertLayout { size_t up_off = 0, down_off = 0; // byte offsets inside the blob size_t bytes = 0; // the whole blob size_t tail_off = 0; // NVFP4: {s_gate, s_up, s_down, 0} at the blob's end; 0 = none + // APR (prism.hadamard): the down weights are Hadamard-folded, so native_expert_grouped rotates h before + // quantizing it (hadamard_rows). had_block 0 = none; d_signs is a DEVICE vector of n_ff signs or nullptr. + int had_block = 0; + const float* d_signs = nullptr; }; NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); /// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the @@ -83,6 +87,16 @@ void native_grouped_set_v1(bool v1); /// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase /// (0 all, 1 gate/up + SwiGLU + quantize, 2 down). void native_expert_set_mode(int mode, int phase); + +/// APR (prism.hadamard): y = H_block (signs * x) per block of `block` values of each of `rows` rows of `width` +/// (x == y allowed). `signs`: a device vector of `width` signs, or nullptr (identity). The same floats as the CPU's +/// hadamard_rotate. The f16 form rotates in place, computing in float. +void hadamard_rows(const float* x, float* y, int64_t rows, int64_t width, int block, const float* signs, void* stream); +void hadamard_rows_f16(uint16_t* x, int64_t rows, int64_t width, int block, const float* signs, void* stream); +/// A device copy (on the current device) of the host sign vector `host` of `width` signs, made on first use and +/// kept for the process. Call it at setup, not inside a CUDA graph capture. nullptr for a nullptr `host`. +const float* hadamard_device_signs(const float* host, int width); + /// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry; /// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give /// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured. diff --git a/metal/CMakeLists.txt b/metal/CMakeLists.txt index fee0e95c..3e1b38c0 100644 --- a/metal/CMakeLists.txt +++ b/metal/CMakeLists.txt @@ -97,7 +97,8 @@ set(STRATA_METAL_HOST_SOURCES ${S}/kernels/ngram.cpp ${S}/ngram/ple_reader.cpp ${S}/platform/direct_file.cpp ${S}/prefill/prefill.cpp ${S}/spec/suffix_drafter.cpp ${S}/spec/controller.cpp ${S}/spec/draft_policy.cpp ${S}/spec/draft_source.cpp - ${S}/kernels/cpu/pool.cpp ${S}/kernels/cpu/expert_layout.cpp ${S}/kernels/cpu/native_expert.cpp) + ${S}/kernels/cpu/pool.cpp ${S}/kernels/cpu/expert_layout.cpp ${S}/kernels/cpu/native_expert.cpp + ${S}/kernels/cpu/hadamard.cpp ${S}/kernels/cpu/tq_cpu.cpp) # Gyro: the Hadamard rotation, the scalar trellis rows set_source_files_properties(${S}/core/device.cu ${S}/core/pinned.cu PROPERTIES LANGUAGE CXX) # The kernel library: Metal implementations (src/engine/*.cpp) and, for every entry point not ported yet, a stub diff --git a/metal/src/engine/stubs_gyro.cpp b/metal/src/engine/stubs_gyro.cpp new file mode 100644 index 00000000..4c2f336e --- /dev/null +++ b/metal/src/engine/stubs_gyro.cpp @@ -0,0 +1,25 @@ +// metal/src/engine/stubs_gyro.cpp - the Gyro (agentionai trellis experts) entry points the Metal engine does not implement: +// the GPU Hadamard rotations of src/kernels/cuda/iq_kernels.cu. native_expert_supported() (iq_host.cpp) does not list the +// trellis types, so a Gyro pack stops at load with its reason and these are never reached with a supported file. +// Each stops the engine with its name, like stubs.cpp. + +#include + +#include "strata/kernels/iq_kernels.hpp" + +namespace strata::metal_engine { +void missing(const char* name); +} + +namespace strata::kernels { +void hadamard_rows(const float*, float*, int64_t, int64_t, int, const float*, void*) { + strata::metal_engine::missing("strata::kernels::hadamard_rows"); +} +void hadamard_rows_f16(uint16_t*, int64_t, int64_t, int, const float*, void*) { + strata::metal_engine::missing("strata::kernels::hadamard_rows_f16"); +} +const float* hadamard_device_signs(const float*, int) { + strata::metal_engine::missing("strata::kernels::hadamard_device_signs"); + return nullptr; +} +} // namespace strata::kernels diff --git a/setup.py b/setup.py index b6e2a571..3ec17849 100644 --- a/setup.py +++ b/setup.py @@ -85,6 +85,7 @@ HF_REVISIONS = { "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF": "5348543e0147355ac9cbcb031184a3546350988e", # 2026-09-29 "unsloth/Qwen3.8-Flash-Next-GGUF": "38bb39ee97821de2c9009abb7e93950eec396e66", # 2026-09-30 "unsloth/Qwen3.6-35B-A3B-MTP-GGUF": "5bc3e238d916f48a861bac2f8a1990a0e9b7e98d", # 2026-10-12 + "agentionai/Qwen3.8-Flash-Next-Gyro-GGUF": "1ada08422e404aca51ab9df665f089f34c419c6b", # 2026-10-13 } @@ -258,6 +259,18 @@ NVFP4_REPOS = { # the first release engine with NVFP4 experts (a source build of this checkout has them whatever its number says) NVFP4_ENGINE = (0, 1, 44) +# agentionai's Gyro files (Qwen3.8-Flash-Next with trellis-coded, Hadamard-rotated experts, TQ2_T / TQK6 / TQK7): one +# GGUF per size, the n-gram table inside it (hence the 58 / 92 GB downloads for 27.6 / 35 GB of memory). The engine +# reads them from 0.1.46 on (ported from agentionai/Strata rc2, MIT); the sizes and SHA-256 are the Hub's LFS pointers +# of the revision pinned in HF_REVISIONS. The model's license is Qwen's. +GYRO_ENGINE = (0, 1, 46) +GYRO_FILES = { + "Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf": + (58487015808, "c6ea1b08ca312f99095b27588ba35976b53f948268e7f91e7761926aa01d9c87"), + "Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf": + (91965774272, "7aa36d15131d255179ab6c87fa9c9f81a0b541fc9e81e959d4c3e29eb20feb5f"), +} + MODELS = { # the original model only for now: Swift 1.5's Q2_0 files split one layer's experts across the two shards, which # the pack tool (tools/iq_pack.py) cannot prepare yet (#171) @@ -312,6 +325,17 @@ MODELS = { # (the HIP and SYCL engines have no NVFP4 kernels). Images: both packs keep Qwen's vision tower unquantized, so the # original's image encoder (ISTA's mmproj, the same file as for every Flash-Next model) reads pictures for them; # checked end to end on an RTX 5070 and an RTX 3060 against IQ3_XXS's answers on the same picture. + # Gyro (agentionai): "ram_gb" is the memory the weights need in total, VRAM and RAM together ("mem_total"): Gyro-S + # 27.6 GB, Gyro-M 35 GB (the rest of the download is the n-gram table, read from the SSD). Neither is anyone's + # default: setup and the MCP server mention them where the other sizes do not fit. No images yet (untested). + "Gyro-S": {"about": "the smallest option, for PCs with little memory (27.6 GB of VRAM + RAM together); lower quality " + "than the 2-3-bit sizes, and the 2-bit Q2_0 decodes faster", + "download_gb": 58.5, "ram_gb": 27.6, "arena_gb": 25.8, "families": ("gyro",), "mem_total": True, + "file": "Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf", "shards": 1, "engine": GYRO_ENGINE, "vision": False}, + "Gyro-M": {"about": "about IQ3_XXS quality with about 20% less GPU memory (35 GB of VRAM + RAM together); decodes " + "about 20% slower than Q2_0 on 12 GB cards", + "download_gb": 92.0, "ram_gb": 35.0, "arena_gb": 32.1, "families": ("gyro",), "mem_total": True, + "file": "Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf", "shards": 1, "engine": GYRO_ENGINE, "vision": False}, "NVFP4": {"about": "4-bit NVFP4 experts, GPTQ (sergqwer's strata-nvfp4 pack); RTX 50 has FP4 tensor cores, other " "NVIDIA cards run it at 8-bit precision", "download_gb": 128.0, "ram_gb": 80, "arena_gb": 68.0, "families": ("nvfp4",), "nvidia_only": True, "vision": True, "repo": NVFP4_GPTQ_REPO, @@ -434,6 +458,16 @@ FAMILIES = { "sha256": {**UNSLOTH_SHARDS, **UNSLOTH_IQ4_XS_SHARDS, **UNSLOTH_BIG_SHARDS}}, # MODEL-UPDATE Phase 4: the original model with NVFP4 experts, as ready-made packs (NVFP4_REPOS): the files come # as the engine reads them (no GGUF to pack), each size has its own repository ("repo" in MODELS) + # agentionai's Gyro quantizations (see GYRO_FILES): after the regular families, never the default + "gyro": {"title": "Qwen3.8-Flash-Next (Gyro)", "by": "Gyro quantizations by agentionai", + "about": "Gyro-S (27.6 GB of memory) and Gyro-M (35 GB): the smallest sizes, for PCs with little memory; " + "58 and 92 GB downloads (the files include the n-gram table)", + "hf": hf("agentionai/Qwen3.8-Flash-Next-Gyro-GGUF"), "file": "Qwen3.8-Flash-Next-{q}.gguf", "shards": 1, + "tag": "gyro-", "name": "qwen3.8-flash-next-gyro", "vision": False, "pack_args": ["--compat-bf16"], + "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", + "sha256": GYRO_FILES, + "license": "Qwen Community License 1.0 (Qwen3.8-Flash-Next's; the Gyro files are agentionai's quantization): " + "https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF"}, "nvfp4": {"title": "Qwen3.8-Flash-Next (NVFP4)", "by": "NVFP4 packs by sergqwer (strata-nvfp4)", "about": "4-bit NVFP4 experts, NVIDIA cards; a 128 GB download, ~80 GB of RAM to keep every expert in RAM", "tag": "nvfp4-", "name": "qwen3.8-flash-next-nvfp4", "ready": True, @@ -2323,14 +2357,20 @@ STRIX_HALO_MIN_GB = 80 # UD-IQ4_XS keeps all of its experts in memory fr RECOMMENDED_SIZES = {"qwen": ("IQ3_S",), "swift": ("IQ3_S",), "unsloth": ("UD-Q4_K_XL", "UD-IQ4_XS")} # owner's pick, 0.1.44 -def recommended_size(family: str, names: list, ram: float) -> str: +def mem_have(model: str, ram: float, vram: float = 0.0) -> float: + """The memory this PC offers a model, in the unit of its MODELS "ram_gb": RAM, or for a "mem_total" model (Gyro) the + VRAM and the RAM together.""" + return ram + vram if MODELS[model].get("mem_total") else ram + + +def recommended_size(family: str, names: list, ram: float, vram: float = 0.0) -> str: """The size the menu pre-selects (and --yes takes): the family's recommended size when this PC's RAM fits it (UD-Q4_K_XL before UD-IQ4_XS), else the largest size that fits, else the first. Recommend, never force: every other size stays a choice.""" for m in RECOMMENDED_SIZES.get(family, ()): - if m in names and ram >= MODELS[m]["ram_gb"]: + if m in names and mem_have(m, ram, vram) >= MODELS[m]["ram_gb"]: return m - fitting = [m for m in names if ram >= MODELS[m]["ram_gb"]] + fitting = [m for m in names if mem_have(m, ram, vram) >= MODELS[m]["ram_gb"]] if fitting: return max(fitting, key=lambda m: MODELS[m]["download_gb"]) return "UD-IQ4_XS" if family == "unsloth" and "UD-IQ4_XS" in names else names[0] @@ -2411,6 +2451,9 @@ def family_menu_note(family: str, hip: bool, gpu, avx2: bool = True, avx512: boo "expert in RAM" + (f"; {cpu}" if cpu else "") + "]") if family == "unsloth" and hip: return " [UD-IQ4_XS is the 4-bit choice on AMD and Intel cards; NVFP4 runs on NVIDIA only]" + if family == "gyro": + return (" [for PCs with little memory: VRAM + RAM together 27.6 GB (Gyro-S) or 35 GB (Gyro-M)" + + ("; AMD is experimental, not for Intel Arc" if hip else "") + "]") return "" @@ -6413,7 +6456,7 @@ def main() -> int: + ": Strata will run, but most experts stay on the CPU and it will be slow") ram = ram_gb() cpu, avx2, avx512 = cpu_info() - need = min(d["ram_gb"] for d in MODELS.values()) + need = min(d["ram_gb"] for d in MODELS.values() if not d.get("mem_total")) # Gyro counts VRAM + RAM: not a RAM floor low_ok = low_ram_fits("IQ1_M", ram, low_ram_vram(gpu)) and a.low_ram != "off" # the smallest model, mapped if ram < need - 4 and not a.check and not low_ok: # every model keeps ALL its experts in RAM (23+ GB); VRAM only holds a copy of the most-used ones, so a @@ -6459,7 +6502,10 @@ def main() -> int: say() any_fits = False for m, d in MODELS.items(): - verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit" + have_gb = mem_have(m, ram, gpu["vram_gb"]) + verdict = "fits" if have_gb >= d["ram_gb"] else "tight" if have_gb >= d["ram_gb"] - 8 else "does not fit" + if d.get("mem_total"): # Gyro: VRAM + RAM together; the rest of the download is read from the SSD + verdict += f" ({ram:.0f} GB RAM + {gpu['vram_gb']:.0f} GB VRAM)" if d.get("budget") and not unsloth_budget(m, ram, gpu): # Phase 2: all of them in RAM verdict = ("EXPERIMENTAL, " if d.get("experimental") else "") + "fits (all of its experts in RAM)" elif d.get("budget"): @@ -6478,8 +6524,8 @@ def main() -> int: if hip and d.get("repo"): # the ready-made NVFP4 packs: no AMD kernels at all verdict = "NVIDIA only (the AMD engine has no NVFP4 kernels)" else: - any_fits = any_fits or not verdict.startswith("does not fit") - say(f" {m:8s} needs ~{d['ram_gb']} GB RAM: {verdict}") + any_fits = any_fits or (not verdict.startswith("does not fit") and not d.get("mem_total")) + say(f" {m:8s} needs ~{d['ram_gb']} GB {'of VRAM + RAM' if d.get('mem_total') else 'RAM'}: {verdict}") if not any_fits: # #977: every size says "does not fit", so the verdict says so too (and the exit code, for scripts). It only # reports: --model NAME --yes still installs one anyway. @@ -6536,6 +6582,13 @@ def main() -> int: for i, m in enumerate(names, 1): d = MODELS[m] fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" + if d.get("mem_total"): # Gyro: the download includes the n-gram table, the memory figure does not + have_gb = mem_have(m, ram, gpu["vram_gb"]) + fit = "" if have_gb >= d["ram_gb"] else \ + f" <- needs {d['ram_gb']} GB of VRAM + RAM together, you have {have_gb:.0f}" + say(f" {i}) {m}{size_tag(family, m, installed)} {d['about']}; download {d['download_gb']:.1f} GB " + f"(the n-gram table is in the file), memory {d['ram_gb']} GB{fit}") + continue if d.get("budget"): keeps = (f"~{resident_budget_gib(m, ram)} GB" if unsloth_budget(m, ram, gpu, a.resident_budget_gib) else "all") @@ -6546,7 +6599,7 @@ def main() -> int: fit = (f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, low_ram_vram(gpu)):.0f}%, " + ("the rest in RAM)" if low_ram_resident(m, ram, low_ram_vram(gpu)) else "the rest from the SSD)")) say(f" {i}) {m:8s}{size_tag(family, m, installed)} {d['about']}; download {d['download_gb']:.0f} GB, uses ~{d['arena_gb']:.0f} GB of RAM{fit}") - rec = str(names.index(installed or recommended_size(family, names, ram)) + 1) + rec = str(names.index(installed or recommended_size(family, names, ram, gpu["vram_gb"])) + 1) model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1] budget, q4_split = None, False in_budget = bool(MODELS[model].get("budget")) and unsloth_budget(model, ram, gpu, a.resident_budget_gib) @@ -6600,11 +6653,20 @@ def main() -> int: multi, sel, chosen = [], [gpu["index"]], [gpu] # (the low-RAM mode's variant is decided once the context is known, below; on several GPUs it is the mapped one # before RESIDENT_SPLIT_ENGINE, #642) - if not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4: + if MODELS[model].get("mem_total"): + if mem_have(model, ram, gpu["vram_gb"]) < MODELS[model]["ram_gb"]: # recommend, never force: a warning + warn(f"{model} needs {MODELS[model]['ram_gb']} GB of VRAM and RAM together; this PC has " + f"{mem_have(model, ram, gpu['vram_gb']):.0f} GB ({ram:.0f} GB RAM + {gpu['vram_gb']:.0f} GB VRAM): it " + "may be slow, run out of memory or not start") + elif not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4: confirm_paging(model, ram, a.low_ram, a.yes, bool(a.model)) ok(f"size: {model}") if MODELS[model].get("license"): # the ready-made packs: each size has its own license say(f" Its license: {MODELS[model]['license']}") + if family == "gyro": # a tip, nothing changes (recommend, never force) + say(" Tip: Gyro's prompt kernels come from agentionai's llama.cpp fork. The engine setup installs reads prompts " + "through a slower path (measured 20-30% slower on an AMD R9700; answers speed is the same); compile with " + "-DSTRATA_GGML_DIR= for the fast one (docs/GYRO.md).") tag = fam["tag"] + model # names of the pack, config and start script small = min(x["vram_gb"] for x in chosen) # each card keeps its layers' KV of the whole context rec_ctx = 32768 if small < 14 else 65536 if small < 20 else 131072 @@ -6811,17 +6873,18 @@ def main() -> int: # ---- 4. the engine step(4, "the Strata engine") llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision) - if ready and meta.get("source") != "local" and \ + if (ready or family == "gyro") and meta.get("source") != "local" and \ tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) < MODELS[model]["engine"]: - # a ready-made engine from before NVFP4 cannot read these experts: one compiled from this source can - warn(f"the ready-made engine {meta.get('version')} has no NVFP4 experts yet: compiling the engine from this source") + # a ready-made engine from before NVFP4 / Gyro cannot read these experts: one compiled from this source can + warn(f"the ready-made engine {meta.get('version')} has no {'NVFP4' if ready else 'Gyro'} experts yet: compiling " + "the engine from this source") eng = build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk) meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk) engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) need_engine = MODELS[model].get("engine", UNSLOTH_ENGINE) # checked before the 94-188 GB download - if MODELS[model].get("budget") and engine_ver < need_engine: + if (MODELS[model].get("budget") or family == "gyro") and engine_ver < need_engine: fail(f"{model} needs engine {'.'.join(map(str, need_engine))} or newer; this one is {meta.get('version')}", "update Strata (or compile the engine with --build) and run setup again") ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}") diff --git a/src/core/peer_experts.cpp b/src/core/peer_experts.cpp index 6c8f567e..5a2164ca 100644 --- a/src/core/peer_experts.cpp +++ b/src/core/peer_experts.cpp @@ -2,6 +2,7 @@ #include "strata/core/peer_experts.hpp" #include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/hadamard.hpp" #include "strata/kernels/elementwise.hpp" #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/quantize_act.hpp" @@ -73,6 +74,7 @@ void PeerExperts::close() { d_x_ = d_out_ = h_x_ = h_out_ = nullptr; d_meta_ = h_meta_ = d_scratch_ = nullptr; d_q8_ = nullptr; + d_sx_ = d_sh_ = nullptr; stream_ = refill_ = nullptr; refill_ev_ = nullptr; device_ = -1; @@ -131,6 +133,10 @@ bool PeerExperts::open(int device, const std::vector ck(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activations", err) && ck(cudaMalloc(&d_scratch_, scratch), "scratch", err); if (!alloc_ok) { close(); return false; } + if (strata::kernels::cpu::hadamard_spec().any()) { // APR: this device's copies of the sign vectors + d_sx_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) H), (int) H); + d_sh_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) ff), (int) ff); + } // the pairs the primary does not hold, in rank order, as many as fit size_t free_b = 0, total_b = 0; @@ -234,9 +240,12 @@ bool PeerExperts::launch(int64_t layer, const float* x, const int32_t* ids, int6 Meta* dm = (Meta*) d_meta_; const auto& lay = strata::kernels::cpu::expert_layout(); if (lay.native) { - strata::kernels::quantize_q8_1_rows(d_x_, n_tok, H, d_q8_, s); const auto& f = lay.fmt[(size_t) layer]; - const auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); + // APR: Hadamard-folded gate/up take H (s * x); d_x_ is this device's private copy, rotated in place + if (f.had_gu) strata::kernels::hadamard_rows(d_x_, d_x_, n_tok, H, f.had_block, d_sx_, s); + strata::kernels::quantize_q8_1_rows(d_x_, n_tok, H, d_q8_, s); + auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); + if (f.had_d) { L.had_block = f.had_block; L.d_signs = d_sh_; } strata::kernels::native_expert_grouped(L, dm->ptr, dm->start, dm->count, dm->dst, dm->tok, groups, rows, d_q8_, d_scratch_, d_out_, s); } else { diff --git a/src/core/remote_experts.cpp b/src/core/remote_experts.cpp index f01bf6fe..4148fcec 100644 --- a/src/core/remote_experts.cpp +++ b/src/core/remote_experts.cpp @@ -2,6 +2,7 @@ #include "strata/core/remote_expert_opt.hpp" #include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/hadamard.hpp" #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/quantize_act.hpp" #include "strata/kernels/s2_expert_grouped.hpp" @@ -100,6 +101,7 @@ void RemoteExperts::close() { if (d_out_) cudaFree(d_out_); if (d_q8_) cudaFree(d_q8_); if (d_scales_) cudaFree(d_scales_); + if (d_xr_) cudaFree(d_xr_); if (d_scratch_) cudaFree(d_scratch_); if (d_meta_) cudaFree(d_meta_); if (h_x_) cudaFreeHost(h_x_); @@ -115,6 +117,8 @@ void RemoteExperts::close() { h_meta_ = d_meta_ = nullptr; d_q8_ = nullptr; d_scales_ = nullptr; + d_xr_ = nullptr; + d_sx_ = d_sh_ = nullptr; d_scratch_ = nullptr; d_start_ = d_dst_ = d_tok_ = d_count_ = nullptr; d_ptr_ = nullptr; @@ -206,12 +210,18 @@ bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts, check(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activation", err, device) && check(cudaMalloc((void**) &d_scales_, (size_t) CAP * (H / 32) * sizeof(float)), "activation scales", err, device) && check(cudaMalloc(&d_scratch_, scratch), "scratch", err, device) && - check(cudaMalloc(&d_meta_, meta_bytes), "group metadata", err, device); + check(cudaMalloc(&d_meta_, meta_bytes), "group metadata", err, device) && + (!strata::kernels::cpu::hadamard_spec().any() || + check(cudaMalloc((void**) &d_xr_, (size_t) CAP * H * sizeof(float)), "rotated input", err, device)); if (!allocated) { close(); return false; } if (!check(cudaStreamCreateWithFlags(&read_stream_, cudaStreamNonBlocking), "cache read stream", err, device)) { close(); return false; } + if (strata::kernels::cpu::hadamard_spec().any()) { // APR: this device's copies of the sign vectors + d_sx_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) H), (int) H); + d_sh_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) FF), (int) FF); + } // Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers // directly - two copies fewer per layer, each of which is a PCIe round trip. STRATA_REMOTE_ZEROCOPY=0 copies. const char* zc = std::getenv("STRATA_REMOTE_ZEROCOPY"); @@ -312,9 +322,15 @@ bool RemoteExperts::begin(int64_t layer, const float* x, const int32_t* ids, int if (!staged) return false; const auto& lay = strata::kernels::cpu::expert_layout(); if (lay.native) { - strata::kernels::quantize_q8_1_rows(zero_copy_ ? z_x_ : d_x_, n_tok, H, d_q8_, s); const auto& fmt = lay.fmt[(size_t) layer]; + const float* xe = zero_copy_ ? z_x_ : d_x_; + if (fmt.had_gu) { // APR: Hadamard-folded gate/up take H (s * x) + strata::kernels::hadamard_rows(xe, d_xr_, n_tok, H, fmt.had_block, d_sx_, s); + xe = d_xr_; + } + strata::kernels::quantize_q8_1_rows(xe, n_tok, H, d_q8_, s); auto L = strata::kernels::native_expert_layout(fmt.gu_type, fmt.d_type, fmt.n_embd, fmt.n_ff); + if (fmt.had_d) { L.had_block = fmt.had_block; L.d_signs = d_sh_; } strata::kernels::native_expert_grouped(L, d_ptr_, d_start_, d_count_, d_dst_, d_tok_, groups_, (int64_t) dst_.size(), d_q8_, d_scratch_, zero_copy_ && !reduce ? z_out_ : d_out_, s); } else { diff --git a/src/core/verify.cpp b/src/core/verify.cpp index ee75bc59..59d4fe63 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -22,6 +22,7 @@ #include "strata/core/peer_experts.hpp" #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/hadamard.hpp" #include "strata/kernels/bf16_gemv.hpp" #include "strata/kernels/native_router.hpp" #include "strata/kernels/native_moe.hpp" @@ -687,6 +688,13 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& sink_.ctx = this; } + // APR: the rotated copy of the expert input (nat_xr_, T x N floats) only where a layer's gate/up is + // Hadamard-folded; its one reader is that layer's f.had_gu branch in the expert-input step below + bool had_gu_any = false; + { + const auto& lay = strata::kernels::cpu::expert_layout(); + for (size_t l = 0; lay.native && l < lay.fmt.size(); ++l) had_gu_any = had_gu_any || lay.fmt[l].had_gu; + } // ---- the device arena: the same sequence counted, then carved auto carve = [&](Bump& b) { tok_ = b.take(T); step_ = b.take(T * strata::kernels::kStepCount); @@ -715,6 +723,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& staging_ = b.take((uint64_t) kStagingBlobs * strata::kernels::cpu::expert_layout().max_blob); hit_xq_ = b.take(T * (N / 32) * 34); hit_xs_ = b.take(T * (N / 32)); nat_xq_ = b.take(T * (N / 32) * 36); + nat_xr_ = had_gu_any ? b.take(T * N) : nullptr; hit_scratch_ = b.take(std::max( strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff), strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), g.n_ff))); @@ -767,6 +776,10 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& return false; } } + { // APR (prism.hadamard, hadamard.txt): the sign vectors on this device, before any graph capture + had_sx_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) g.n_embd), (int) g.n_embd); + had_sh_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) g.n_ff), (int) g.n_ff); + } sink_.staging = (unsigned long long) staging_; sink_.staging_cap = kStagingBlobs; (void) TS; @@ -1640,8 +1653,17 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (sh_fork) cudaEventRecord(ev_join_, sh_cs_); } if (strata::kernels::cpu::expert_layout().native) { - if (!qdedup) - if (!q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); + // APR: Hadamard-folded gate/up take H (s * x); xm itself stays as it is (the shared expert above and the + // doorbell copy for the CPU pool, which rotates its own in native_quant_act). The q8_1 image of xm that + // STRATA_QFUSE / STRATA_VERIFY_QDEDUP may already have written is of the unrotated input, so a folded layer + // always rewrites it from the rotated rows (same stream, after the shared expert has read it). + const auto& f = strata::kernels::cpu::expert_layout().fmt[(size_t) l]; + if (f.had_gu) { // nat_xr_ exists: init carved it because this layer is folded (had_gu_any) + hadamard_rows(xm, nat_xr_ + (size_t) tb * N, n, N, f.had_block, had_sx_, cs); + quantize_q8_1_rows(nat_xr_ + (size_t) tb * N, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); + } else if (!qdedup && !q8_ffn) { + quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); + } } else quantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs); stamp(l, 18, grp); @@ -1677,7 +1699,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (lay.native) { // the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down) const auto& f = lay.fmt[(size_t) l]; - const NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); + NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); + if (f.had_d) { L.had_block = f.had_block; L.d_signs = had_sh_; } // APR: h is rotated in there native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap, nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, dst_buf, cs, gy); } else { diff --git a/src/kernels/cpu/expert_layout.cpp b/src/kernels/cpu/expert_layout.cpp index 001fa5d4..b6924950 100644 --- a/src/kernels/cpu/expert_layout.cpp +++ b/src/kernels/cpu/expert_layout.cpp @@ -1,5 +1,6 @@ // src/kernels/cpu/expert_layout.cpp - plan v0.3 P6: the per-layer expert table. See the header. #include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/hadamard.hpp" #include #include @@ -391,6 +392,7 @@ bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n std::ifstream in(pack_dir + "/native_experts.txt"); if (!in) { L.total = (uint64_t) n_layers * (uint64_t) n_expert * (uint64_t) BLOB; + hadamard_set({}); g_layout = L; return true; } @@ -487,6 +489,48 @@ bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n at += L.bytes[(size_t) l] * (uint64_t) L.n_expert; } L.total = at; + // v5: Agention's Hadamard-folded experts (prism.hadamard, hadamard.hpp). The pack must say which layers are + // rotated and with what signs; a v5 pack without hadamard.txt (or the reverse) is refused, never run unrotated. + { + std::ifstream probe(pack_dir + "/hadamard.txt"); + const bool have = (bool) probe; + if (L.version >= 5 && !have) { + err = "native_experts.txt v5 declares Hadamard-folded experts, but " + pack_dir + "/hadamard.txt is missing"; + return false; + } + if (have && L.version < 5) { + err = pack_dir + "/hadamard.txt exists but native_experts.txt is v" + std::to_string(L.version) + + ": the pack is inconsistent (repack with tools/iq_pack.py)"; + return false; + } + HadamardSpec h; + if (have && !hadamard_parse(pack_dir + "/hadamard.txt", n_layers, h, err)) return false; + hadamard_set(std::move(h)); + const HadamardSpec& hs = hadamard_spec(); + for (int64_t l = 0; hs.any() && l < n_layers; ++l) { + NativeFmt& f = L.fmt[(size_t) l]; + f.had_block = hs.block; + f.had_gu = hs.gu(l); + f.had_d = hs.down(l); + if ((f.had_gu && f.n_embd % hs.block) || (f.had_d && f.n_ff % hs.block)) { + err = "hadamard.txt: block " + std::to_string(hs.block) + " does not divide layer " + + std::to_string(l) + "'s expert widths"; + return false; + } + // the Q2_0 rows quantize their activations with Strata's own act_quant_any, which does not rotate + if ((f.had_gu && f.gu_type == 42) || (f.had_d && f.d_type == 42)) { + err = "hadamard.txt: layer " + std::to_string(l) + " folds a Q2_0 expert, which this engine cannot rotate"; + return false; + } + f.gu_signs = f.had_gu ? hadamard_signs((int) f.n_embd) : nullptr; + f.d_signs = f.had_d ? hadamard_signs((int) f.n_ff) : nullptr; + // explicit signs are per width: a width without a vector would silently mean identity signs + if (!hs.signs.empty() && ((f.had_gu && !f.gu_signs) || (f.had_d && !f.d_signs))) { + err = "hadamard.txt: no sign vector for layer " + std::to_string(l) + "'s expert width"; + return false; + } + } + } g_layout = L; return true; #endif diff --git a/src/kernels/cpu/hadamard.cpp b/src/kernels/cpu/hadamard.cpp new file mode 100644 index 00000000..3a9fc0c7 --- /dev/null +++ b/src/kernels/cpu/hadamard.cpp @@ -0,0 +1,110 @@ +// src/kernels/cpu/hadamard.cpp - see include/strata/kernels/cpu/hadamard.hpp. +#include "strata/kernels/cpu/hadamard.hpp" + +#include +#include +#include +#include + +namespace strata::kernels::cpu { +namespace { +HadamardSpec g_spec; +} + +const HadamardSpec& hadamard_spec() { return g_spec; } +void hadamard_set(HadamardSpec h) { g_spec = std::move(h); } + +const float* hadamard_signs(int width) { + const auto it = g_spec.signs.find(width); + return it == g_spec.signs.end() ? nullptr : it->second.data(); +} + +bool hadamard_parse(const std::string& path, int64_t n_layers, HadamardSpec& h, std::string& err) { + std::ifstream in(path); + if (!in) { err = "cannot read " + path; return false; } + h = HadamardSpec{}; + h.roles.assign((size_t) n_layers, 0); + std::vector seen((size_t) n_layers, 0); + std::string line; + bool versioned = false; + while (std::getline(in, line)) { + if (line.empty()) continue; + if (line[0] == '#') { + static const char tag[] = "# strata hadamard v"; + if (line.compare(0, sizeof tag - 1, tag) == 0) { + if (std::atoi(line.c_str() + sizeof tag - 1) != 1) { + err = path + ": an unknown hadamard.txt version (this engine reads v1)"; + return false; + } + versioned = true; + } + continue; + } + std::istringstream ss(line); + std::string key; + ss >> key; + if (key == "block") { + long long b = 0; + if (!(ss >> b) || b < 2 || b > 4096 || (b & (b - 1)) != 0 || h.block) { + err = path + ": a bad or repeated block line: " + line; + return false; + } + h.block = (int) b; + } else if (key == "signs") { + long long w = 0; + if (!(ss >> w) || w <= 0 || w > (1 << 20) || h.signs.count((int) w)) { + err = path + ": a bad or repeated signs line"; + return false; + } + std::vector v((size_t) w); + for (auto& x : v) { + int s = 0; + if (!(ss >> s) || (s != 1 && s != -1)) { err = path + ": sign values must be +1 or -1"; return false; } + x = (float) s; + } + std::string extra; + if (ss >> extra) { err = path + ": a signs line longer than its width"; return false; } + h.signs.emplace((int) w, std::move(v)); + } else if (key == "layer") { + long long l = -1; + int g = -1, u = -1, d = -1; + if (!(ss >> l >> g >> u >> d) || l < 0 || l >= n_layers || (g | u | d) & ~1 || seen[(size_t) l]) { + err = path + ": a bad or repeated layer line: " + line; + return false; + } + if (g != u) { // gate and up read one activation: a transform for one of them only is not runnable + err = path + ": layer " + std::to_string(l) + " folds only one of gate/up"; + return false; + } + seen[(size_t) l] = 1; + h.roles[(size_t) l] = (uint8_t) (g | (u << 1) | (d << 2)); + } else { + err = path + ": an unknown line: " + line; + return false; + } + } + if (!versioned || h.block == 0) { err = path + ": no version header or no block line"; return false; } + for (const auto& [w, v] : h.signs) + if (w % h.block) { err = path + ": sign width " + std::to_string(w) + " is not whole blocks"; return false; } + return true; +} + +void hadamard_rotate(float* x, int n, int block, const float* signs) { + if (signs) + for (int i = 0; i < n; ++i) x[i] *= signs[i]; + const float scale = 1.0f / std::sqrt((float) block); + for (int b0 = 0; b0 < n; b0 += block) { + float* v = x + b0; + // the in-place fast Walsh-Hadamard transform in natural (Sylvester) order: entry (-1)^popcount(r & c) + for (int len = 1; len < block; len <<= 1) + for (int i = 0; i < block; i += len << 1) + for (int j = i; j < i + len; ++j) { + const float a = v[j], c = v[j + len]; + v[j] = a + c; + v[j + len] = a - c; + } + for (int i = 0; i < block; ++i) v[i] *= scale; + } +} + +} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp index 1ab75b64..48434018 100644 --- a/src/kernels/cpu/native_expert.cpp +++ b/src/kernels/cpu/native_expert.cpp @@ -10,6 +10,8 @@ #include "strata/kernels/cpu/nvfp4_avx2.hpp" #include "strata/kernels/cpu/nvfp4_avx512.hpp" #include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/hadamard.hpp" +#include "strata/kernels/cpu/tq_cpu.hpp" #include "ggml.h" #include "ggml-cpu.h" @@ -18,12 +20,21 @@ #include #include #include +#include namespace strata::kernels::cpu { namespace { const ggml_type_traits_cpu* traits(int type) { return ggml_get_type_traits_cpu((ggml_type) type); } +// Do the trellis rows take Strata's own kernels (tq_cpu.hpp)? Always, unless STRATA_NO_TQ_KERNELS=1 asks for ggml-cpu's +// vec_dot AND this ggml has the type (the agentionai fork; an upstream ggml does not, and must never be asked about it). +bool tq_rows_own(int type) { + if (!tq_supported(type)) return false; + if (tq_kernels_enabled()) return true; + return type >= (int) GGML_TYPE_COUNT || traits(type) == nullptr || traits(type)->vec_dot == nullptr; +} + void init_once() { static std::once_flag once; std::call_once(once, [] { ggml_cpu_init(); }); @@ -49,31 +60,39 @@ bool kq256_supported(int type) noexcept { return type == 12 || type == 7 || type bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err) { init_once(); - const ggml_type_traits_cpu* tg = traits(gu_type); - const ggml_type_traits_cpu* td = traits(d_type); - if (tg == nullptr || tg->vec_dot == nullptr || td == nullptr || td->vec_dot == nullptr) { - err = "native experts: ggml-cpu has no dot product for type " + std::to_string(tg && tg->vec_dot ? d_type : gu_type); + // The trellis types (Gyro, ggml types 144-146) are not in a ggml built from upstream (and an upstream ggml indexes its + // type table by the id, so asking it about 144 reads past the table): their geometry and activation format (Q8_0) + // are known here, and their rows run on tq_cpu.hpp. + const bool tq_g = tq_supported(gu_type), tq_d = tq_supported(d_type); + const ggml_type_traits_cpu* tg = tq_g ? nullptr : traits(gu_type); + const ggml_type_traits_cpu* td = tq_d ? nullptr : traits(d_type); + if ((!tq_g && (tg == nullptr || tg->vec_dot == nullptr)) || (!tq_d && (td == nullptr || td->vec_dot == nullptr))) { + err = "native experts: ggml-cpu has no dot product for type " + + std::to_string(!tq_g && !(tg && tg->vec_dot) ? gu_type : d_type); return false; } - const ggml_type_traits_cpu* ag = traits(tg->vec_dot_type); - const ggml_type_traits_cpu* ad = traits(td->vec_dot_type); + const ggml_type vdt_g = tq_g ? GGML_TYPE_Q8_0 : tg->vec_dot_type; + const ggml_type vdt_d = tq_d ? GGML_TYPE_Q8_0 : td->vec_dot_type; + const ggml_type_traits_cpu* ag = traits(vdt_g); + const ggml_type_traits_cpu* ad = traits(vdt_d); if (ag == nullptr || ag->from_float == nullptr || ad == nullptr || ad->from_float == nullptr) { err = "native experts: ggml-cpu cannot quantize an activation for this layer"; return false; } - if (n_embd % ggml_blck_size((ggml_type) gu_type) || n_ff % ggml_blck_size((ggml_type) d_type) || - n_embd % ggml_blck_size(tg->vec_dot_type) || n_ff % ggml_blck_size(td->vec_dot_type)) { + if ((tq_g ? n_embd % kTqBlock : n_embd % ggml_blck_size((ggml_type) gu_type)) || + (tq_d ? n_ff % kTqBlock : n_ff % ggml_blck_size((ggml_type) d_type)) || + n_embd % ggml_blck_size(vdt_g) || n_ff % ggml_blck_size(vdt_d)) { err = "native experts: expert geometry is not whole blocks"; return false; } f.gu_type = gu_type; f.d_type = d_type; - f.gu_act = (int) tg->vec_dot_type; - f.d_act = (int) td->vec_dot_type; + f.gu_act = (int) vdt_g; + f.d_act = (int) vdt_d; f.n_embd = n_embd; f.n_ff = n_ff; - f.gu_row = ggml_row_size((ggml_type) gu_type, n_embd); - f.d_row = ggml_row_size((ggml_type) d_type, n_ff); + f.gu_row = tq_g ? (size_t) (n_embd / kTqBlock) * tq_block_bytes(gu_type) : ggml_row_size((ggml_type) gu_type, n_embd); + f.d_row = tq_d ? (size_t) (n_ff / kTqBlock) * tq_block_bytes(d_type) : ggml_row_size((ggml_type) d_type, n_ff); f.up_off = f.gu_row * (size_t) n_ff; f.down_off = 2 * f.up_off; f.bytes = f.down_off + f.d_row * (size_t) n_embd; @@ -83,8 +102,8 @@ bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt f.tail_off = f.bytes; f.bytes += kNvfp4Tail; } - f.act_bytes = ggml_row_size(tg->vec_dot_type, n_embd); - f.h_bytes = ggml_row_size(td->vec_dot_type, n_ff); + f.act_bytes = ggml_row_size(vdt_g, n_embd); + f.h_bytes = ggml_row_size(vdt_d, n_ff); if (f.act_bytes > kNativeActBytes || f.h_bytes > kNativeHBytes) { err = "native experts: activation larger than the pool's buffers"; return false; @@ -110,12 +129,24 @@ bool q8k_avx1(int type) { } // namespace void native_quant_act(const NativeFmt& f, const float* x, void* dst) { + if (f.had_gu) { // Hadamard-folded gate/up: quantize H (s * x), never x itself (hadamard.hpp) + thread_local std::vector tmp; + tmp.assign(x, x + f.n_embd); + hadamard_rotate(tmp.data(), (int) f.n_embd, f.had_block, f.gu_signs); + x = tmp.data(); + } if (q8k_avx2(f.gu_act)) { q8k_quant_avx2(x, dst, f.n_embd); return; } if (q8k_avx1(f.gu_act)) { q8k_quant_avx1(x, dst, f.n_embd); return; } traits(f.gu_act)->from_float(x, dst, f.n_embd); } void native_quant_h(const NativeFmt& f, const float* h, void* dst) { + if (f.had_d) { + thread_local std::vector tmp; + tmp.assign(h, h + f.n_ff); + hadamard_rotate(tmp.data(), (int) f.n_ff, f.had_block, f.d_signs); + h = tmp.data(); + } if (q8k_avx2(f.d_act)) { q8k_quant_avx2(h, dst, f.n_ff); return; } if (q8k_avx1(f.d_act)) { q8k_quant_avx1(h, dst, f.n_ff); return; } traits(f.d_act)->from_float(h, dst, f.n_ff); @@ -173,6 +204,12 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* kq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); return; } + // The trellis types (TQ2_T / TQK6 / TQK7): Strata's own kernels (tq_cpu.hpp), for every group size - they decode + // a block once for all the tokens and give each token the same bits whatever the group (no #152 rule needed). + if (tq_rows_own(f.gu_type)) { + tq_gu_rows(tq_isa(), f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); + return; + } // A format with only an AVX-2 kernel (IQ4_XS, #415) takes it on AVX-2 CPUs only: an AVX-512 CPU keeps ggml-cpu for // it, as before (its rows would round differently). Each kernel only for the formats it implements: falling // through an empty switch would leave ff unwritten instead of falling back to ggml-cpu. @@ -240,6 +277,10 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const // Both multi-token kernels below are /arch:AVX2 translation units (kq_avx2.cpp and iq_avx2.cpp), // so a CPU without AVX2 has to reach ggml-cpu's vec_dot instead - same reasoning as the gate/up // rows above, where `avx512` tested cpu_avx512_ok() and `avx2` did not. + if (tq_rows_own(f.d_type)) { // the trellis types, as in native_gu_rows + tq_rows(tq_isa(), f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); + return; + } if (cpu_avx2_ok() && kq && nt >= 2 && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, any group size kq256_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); return; diff --git a/src/kernels/cpu/native_hadamard_test.cpp b/src/kernels/cpu/native_hadamard_test.cpp new file mode 100644 index 00000000..de5b923f --- /dev/null +++ b/src/kernels/cpu/native_hadamard_test.cpp @@ -0,0 +1,311 @@ +// src/kernels/cpu/native_hadamard_test.cpp - APR port, stage 3: one Hadamard-folded trellis expert (TQ2_T / TQK6 / +// TQK7, ggml types 144-146) on Strata's CPU path against llama.cpp's own graph for the same weights and input. +// +// Strata's path: native_quant_act (signs, FWHT, Q8_0) -> native_gu_rows (ggml-cpu vec_dot + SwiGLU) +// -> native_quant_h (signs, FWHT, Q8_0) -> native_down_rows +// The reference: the ops llama.cpp's build_lora_mm_id builds for a prism.hadamard weight - ggml_mul(x, signs), +// llama_mul_mat_hadamard (reshape to [128, n/128], ggml_mul_mat(rot, .)), ggml_mul_mat(W', .) - +// computed by ggml-cpu from the same checkout (STRATA_GGML_DIR = the agention llama.cpp fork). +// The rotation itself is computed two different ways (FWHT here, a dense 128x128 matmul there), so the two outputs +// agree to float rounding plus the odd Q8_0 rounding flip, not bit for bit; the test bounds the relative error. +// +// native_hadamard_test synthetic: random W, rotated and quantized here; also checks the +// folded expert against the UNROTATED float expert (W x) and that +// skipping the rotation is caught +// native_hadamard_test --pack --gguf [layer expert]... real experts of a prism.hadamard GGUF +// (Gyro-S / Gyro-M) through the pack tools/iq_pack.py made of it +#include "strata/kernels/cpu/hadamard.hpp" +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/pool.hpp" +#include "strata/artifact/gguf_reader.hpp" + +#include "ggml.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace strata::kernels::cpu; + +namespace { + +constexpr int H = 2560, FF = 640, B = 128; + +struct Expert { + int gu_type = 0, d_type = 0; + std::vector gate, up, down; // ggml rows: gate/up [FF rows of H], down [H rows of FF] + std::vector s_h, s_ff; // sign vectors (empty: identity) +}; + +double rel(const std::vector& a, const std::vector& b) { + double num = 0, den = 0; + for (size_t i = 0; i < a.size(); ++i) { + num += (double) (a[i] - b[i]) * (a[i] - b[i]); + den += (double) b[i] * b[i]; + } + return std::sqrt(num / (den > 0 ? den : 1)); +} + +float silu(float g) { return g / (1.f + std::exp(-g)); } + +// Strata's CPU path for one token; `loaded` = the layer's NativeFmt as expert_layout_load made it from a pack +std::vector strata_expert(const Expert& e, const std::vector& x, bool rotate, + const NativeFmt* loaded = nullptr) { + NativeFmt f; + std::string err; + if (!native_fmt(e.gu_type, e.d_type, H, FF, f, err)) { std::fprintf(stderr, "native_fmt: %s\n", err.c_str()); std::exit(1); } + if (rotate && loaded) { + f = *loaded; + } else if (rotate) { + f.had_block = B; + f.had_gu = f.had_d = true; + f.gu_signs = e.s_h.empty() ? nullptr : e.s_h.data(); + f.d_signs = e.s_ff.empty() ? nullptr : e.s_ff.data(); + } + std::vector blob(f.bytes); + std::memcpy(blob.data(), e.gate.data(), e.gate.size()); + std::memcpy(blob.data() + f.up_off, e.up.data(), e.up.size()); + std::memcpy(blob.data() + f.down_off, e.down.data(), e.down.size()); + std::vector act(kNativeActBytes), hq(kNativeHBytes); + std::vector ff(FF), out(H); + native_quant_act(f, x.data(), act.data()); + const void* a[1] = {act.data()}; + float* ffp[1] = {ff.data()}; + native_gu_rows(f, blob.data(), a, 1, ffp, 0, FF); + native_quant_h(f, ff.data(), hq.data()); + const void* hp[1] = {hq.data()}; + float* op[1] = {out.data()}; + native_down_rows(f, blob.data(), hp, 1, op, 0, H); + return out; +} + +// llama.cpp's graph for the same expert (the fork's build_lora_mm + llama_mul_mat_hadamard), one token +std::vector llama_expert(const Expert& e, const std::vector& x) { + ggml_init_params ip = {(size_t) 256 << 20, nullptr, false}; + ggml_context* ctx = ggml_init(ip); + // the normalized Sylvester-Walsh-Hadamard matrix exactly as llama_model_base builds prism.hadamard.128 + ggml_tensor* rot = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, B, B); + float* R = (float*) rot->data; + const float scale = 1.0f / sqrtf((float) B); + for (uint32_t r = 0; r < (uint32_t) B; ++r) + for (uint32_t c = 0; c < (uint32_t) B; ++c) { + uint32_t p = r & c; + p ^= p >> 16; p ^= p >> 8; p ^= p >> 4; p ^= p >> 2; p ^= p >> 1; + R[r * B + c] = (p & 1) ? -scale : scale; + } + auto hadamard = [&](ggml_tensor* cur, const std::vector& signs) { + if (!signs.empty()) { + ggml_tensor* s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, (int64_t) signs.size()); + std::memcpy(s->data, signs.data(), signs.size() * sizeof(float)); + cur = ggml_mul(ctx, cur, s); + } + ggml_tensor* res = ggml_reshape_2d(ctx, cur, B, ggml_nelements(cur) / B); + res = ggml_mul_mat(ctx, rot, res); + return ggml_reshape_4d(ctx, res, cur->ne[0], cur->ne[1], cur->ne[2], cur->ne[3]); + }; + ggml_tensor* wg = ggml_new_tensor_2d(ctx, (ggml_type) e.gu_type, H, FF); + ggml_tensor* wu = ggml_new_tensor_2d(ctx, (ggml_type) e.gu_type, H, FF); + ggml_tensor* wd = ggml_new_tensor_2d(ctx, (ggml_type) e.d_type, FF, H); + std::memcpy(wg->data, e.gate.data(), e.gate.size()); + std::memcpy(wu->data, e.up.data(), e.up.size()); + std::memcpy(wd->data, e.down.data(), e.down.size()); + ggml_tensor* xt = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, H); + std::memcpy(xt->data, x.data(), H * sizeof(float)); + ggml_tensor* xr = hadamard(xt, e.s_h); + ggml_tensor* g = ggml_mul_mat(ctx, wg, xr); + ggml_tensor* u = ggml_mul_mat(ctx, wu, xr); + ggml_tensor* h = ggml_mul(ctx, ggml_silu(ctx, g), u); + ggml_tensor* out = ggml_mul_mat(ctx, wd, hadamard(h, e.s_ff)); + ggml_cgraph* gf = ggml_new_graph(ctx); + ggml_build_forward_expand(gf, out); + ggml_graph_compute_with_ctx(ctx, gf, 4); + std::vector y(H); + std::memcpy(y.data(), out->data, H * sizeof(float)); + ggml_free(ctx); + return y; +} + +// W' = W diag(s) H^T per 128-column block (what the APR encoder folds), then quantized with ggml +std::vector fold_and_quantize(const std::vector& w, int rows, int cols, const std::vector& s, + int type, std::vector& folded) { + folded.assign(w.begin(), w.end()); + for (int r = 0; r < rows; ++r) hadamard_rotate(folded.data() + (size_t) r * cols, cols, B, s.data()); + // (H symmetric and orthonormal: row-wise H (s * w_r) is exactly the fold W diag(s) H^T) + std::vector q(ggml_row_size((ggml_type) type, cols) * rows); + ggml_quantize_chunk((ggml_type) type, folded.data(), q.data(), 0, rows, cols, nullptr); + return q; +} + +int synthetic(int gu_type, int d_type) { + std::mt19937 rng(1234 + gu_type * 7 + d_type); + std::normal_distribution nd(0.f, 1.f); + std::uniform_int_distribution coin(0, 1); + Expert e; + e.gu_type = gu_type; + e.d_type = d_type; + std::vector wg((size_t) FF * H), wu((size_t) FF * H), wd((size_t) H * FF), x(H); + for (auto& v : wg) v = nd(rng) * 0.02f; + for (auto& v : wu) v = nd(rng) * 0.02f; + for (auto& v : wd) v = nd(rng) * 0.02f; + for (auto& v : x) v = nd(rng); + x[17] = 40.f; // a massive channel, as the real residual stream has: the case the rotation exists for + e.s_h.resize(H); + e.s_ff.resize(FF); + for (auto& v : e.s_h) v = coin(rng) ? 1.f : -1.f; + for (auto& v : e.s_ff) v = coin(rng) ? 1.f : -1.f; + std::vector fg, fu, fd; + e.gate = fold_and_quantize(wg, FF, H, e.s_h, gu_type, fg); + e.up = fold_and_quantize(wu, FF, H, e.s_h, gu_type, fu); + e.down = fold_and_quantize(wd, H, FF, e.s_ff, d_type, fd); + + // the unrotated float expert W x: what the folded, quantized expert must approximate + std::vector h(FF), ref(H); + for (int r = 0; r < FF; ++r) { + double g = 0, u = 0; + for (int c = 0; c < H; ++c) { g += (double) wg[(size_t) r * H + c] * x[c]; u += (double) wu[(size_t) r * H + c] * x[c]; } + h[r] = silu((float) g) * (float) u; + } + for (int r = 0; r < H; ++r) { + double o = 0; + for (int c = 0; c < FF; ++c) o += (double) wd[(size_t) r * FF + c] * h[c]; + ref[r] = (float) o; + } + const auto ours = strata_expert(e, x, true); + const auto llama = llama_expert(e, x); + const auto unrot = strata_expert(e, x, false); + const double e_ll = rel(ours, llama), e_ref = rel(ours, ref), e_llref = rel(llama, ref), e_un = rel(unrot, ref); + std::printf("synthetic %s/%s: strata vs llama.cpp graph %.2e | vs unrotated float expert: strata %.4f, llama.cpp " + "%.4f | strata WITHOUT the rotation %.4f\n", ggml_type_name((ggml_type) gu_type), + ggml_type_name((ggml_type) d_type), e_ll, e_ref, e_llref, e_un); + // strata == llama.cpp to rounding, and both approximate W x equally well. With Q8_0 weights the quantization + // error is ~1%, so the fold's convention itself is checked: the rotated path must reproduce the unrotated float + // expert and the unrotated path must not. (The trellis types' own error at 1.6-2.1 bpw on Gaussian weights, + // compounded through SwiGLU, is large with this test's placeholder ggml encoder; there only agreement counts.) + const bool hi = gu_type == 8 && d_type == 8; + const bool ok = e_ll < 2e-3 && std::fabs(e_ref - e_llref) < 0.01 && (!hi || (e_ref < 0.03 && e_un > 0.8)); + std::printf(" %s\n", ok ? "ok" : "FAILED"); + return ok ? 0 : 1; +} + +// A real expert, the pack's loader path: expert_layout_load() reads native_experts.txt v5 + hadamard.txt (from +// tools/iq_pack.py), and the layer's NativeFmt is what the engine's CPU pool would use. (The signs come from the +// pack: strata::GgufFile keeps only the first 64 items of a metadata array, so it cannot read sign_values.) +int real(const char* pack, const char* path, int layer, int expert) { + std::string err; + if (!expert_layout_load(pack, 48, 512, err)) { std::fprintf(stderr, "expert_layout_load: %s\n", err.c_str()); return 1; } + const ExpertLayout& lay = expert_layout(); + const HadamardSpec& hs = hadamard_spec(); + if (!lay.native || !hs.any() || lay.version != 5) { std::fprintf(stderr, "%s: not a v5 (Hadamard) native pack\n", pack); return 1; } + const NativeFmt& lf = lay.fmt[(size_t) layer]; + if (lf.had_block != B || !lf.had_gu || !lf.had_d) { std::fprintf(stderr, "layer %d is not folded in the pack\n", layer); return 1; } + strata::GgufFile g(path); + Expert e; + if (const float* sh = hadamard_signs(H)) e.s_h.assign(sh, sh + H); + if (const float* sf = hadamard_signs(FF)) e.s_ff.assign(sf, sf + FF); + auto slice = [&](const char* role, std::vector& dst, int& type) { + const std::string name = "blk." + std::to_string(layer) + ".ffn_" + role + "_exps.weight"; + const strata::TensorInfo* t = g.find(name); + if (!t || t->shape.size() != 3) { std::fprintf(stderr, "missing %s\n", name.c_str()); std::exit(1); } + type = (int) t->type; + const size_t per = ggml_row_size((ggml_type) type, (int64_t) t->shape[0]) * t->shape[1]; + const uint8_t* p = g.tensor_data(*t) + per * (size_t) expert; + dst.assign(p, p + per); + }; + int dt = 0, ut = 0; + slice("gate", e.gate, e.gu_type); + slice("up", e.up, ut); + slice("down", e.down, dt); + e.d_type = dt; + if (e.gu_type != lf.gu_type || e.d_type != lf.d_type) { std::fprintf(stderr, "the pack and the GGUF disagree\n"); return 1; } + std::mt19937 rng(99); + std::normal_distribution nd(0.f, 1.f); + std::vector x(H); + for (auto& v : x) v = nd(rng); + x[17] = 40.f; + const auto ours = strata_expert(e, x, true, &lf); + const auto llama = llama_expert(e, x); + const auto unrot = strata_expert(e, x, false); + const double e_ll = rel(ours, llama), e_un = rel(unrot, llama); + std::printf("%s layer %d expert %d (%s/%s, signs %s): strata vs llama.cpp graph %.2e | without the rotation %.3f\n", + path, layer, expert, ggml_type_name((ggml_type) e.gu_type), ggml_type_name((ggml_type) e.d_type), + e.s_h.empty() ? "identity" : "explicit", e_ll, e_un); + bool ok = e_ll < 2e-3 && e_un > 0.3; + std::printf(" %s\n", ok ? "ok" : "FAILED"); + + // the engine's CPU entry point: ExpertPool::run_split_multi_native with the pack's NativeFmt, three tokens + // routed to this expert (x quantized by native_quant_act, as expert_source.cpp does for the doorbell copy) + { + constexpr int NT = 3; + ExpertPool pool(4, false, false); + std::vector blob(lf.bytes); + std::memcpy(blob.data(), e.gate.data(), e.gate.size()); + std::memcpy(blob.data() + lf.up_off, e.up.data(), e.up.size()); + std::memcpy(blob.data() + lf.down_off, e.down.data(), e.down.size()); + std::vector> xs(NT, std::vector(H)), outs(NT, std::vector(H)); + std::vector> acts(NT, std::vector(kNativeActBytes)); + ExpertJobMulti job; + job.blob = blob.data(); + job.nt = NT; + for (int t = 0; t < NT; ++t) { + for (auto& v : xs[t]) v = nd(rng); + xs[t][(size_t) (101 * t + 5)] = 30.f; + native_quant_act(lf, xs[t].data(), acts[t].data()); + job.nact[t] = acts[t].data(); + job.out[t] = outs[t].data(); + } + pool.run_split_multi_native(lf, &job, 1); + double worst = 0; + for (int t = 0; t < NT; ++t) worst = std::max(worst, rel(outs[t], llama_expert(e, xs[t]))); + const bool pok = worst < 2e-3; + std::printf(" ExpertPool::run_split_multi_native, %d tokens: worst vs llama.cpp graph %.2e %s\n", NT, worst, + pok ? "ok" : "FAILED"); + ok = ok && pok; + } + return ok ? 0 : 1; +} + +// the FWHT against the dense matrix llama.cpp builds, on one block +int fwht_check() { + std::mt19937 rng(7); + std::normal_distribution nd(0.f, 1.f); + std::vector x(B), y(B), s(B); + for (auto& v : x) v = nd(rng); + for (int i = 0; i < B; ++i) s[i] = (i * 37 % 5) < 2 ? -1.f : 1.f; + y = x; + hadamard_rotate(y.data(), B, B, s.data()); + double worst = 0; + for (int r = 0; r < B; ++r) { + double acc = 0; + for (int c = 0; c < B; ++c) acc += ((__builtin_popcount(r & c) & 1) ? -1.0 : 1.0) * s[c] * x[c]; + worst = std::max(worst, std::fabs(acc / std::sqrt((double) B) - y[r])); + } + std::printf("FWHT vs dense normalized Sylvester matrix: max abs diff %.2e %s\n", worst, worst < 1e-5 ? "ok" : "FAILED"); + return worst < 1e-5 ? 0 : 1; +} + +} // namespace + +int main(int argc, char** argv) { + if (!native_experts_available()) { std::fprintf(stderr, "built without native experts\n"); return 1; } + int rc = fwht_check(); + if (argc >= 5 && std::strcmp(argv[1], "--pack") == 0 && std::strcmp(argv[3], "--gguf") == 0) { + for (int i = 5; i + 1 < argc || i == 5; i += 2) { // [layer expert]... + const int layer = argc > i ? std::atoi(argv[i]) : 0, expert = argc > i + 1 ? std::atoi(argv[i + 1]) : 0; + rc |= real(argv[2], argv[4], layer, expert); + } + return rc; + } + // ggml type ids of the agention fork: 144 TQ2_T, 145 TQK6, 146 TQK7 + if (GGML_TYPE_COUNT <= 146) { std::fprintf(stderr, "this ggml has no trellis types (build with STRATA_GGML_DIR = the agention fork)\n"); return 1; } + rc |= synthetic(8, 8); // Q8_0: the fold's convention, against the unrotated float expert + rc |= synthetic(145, 146); // Gyro-S + rc |= synthetic(144, 144); // Gyro-M + return rc; +} diff --git a/src/kernels/cpu/tq_avx2.cpp b/src/kernels/cpu/tq_avx2.cpp new file mode 100644 index 00000000..00918edf --- /dev/null +++ b/src/kernels/cpu/tq_avx2.cpp @@ -0,0 +1,87 @@ +// 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 + +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 +void rows_t(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*) tq_state_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(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(qs, wr, 4 * m), tq_state(qs, wr, 4 * m + 1), + tq_state(qs, wr, 4 * m + 2), tq_state(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 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>(w, row_bytes, n, a, nt, out, r0, r1); + else if (kb == 6) rows_t<6>(w, row_bytes, n, a, nt, out, r0, r1); + else rows_t<7>(w, row_bytes, n, a, nt, out, r0, r1); +} + +} // namespace strata::kernels::cpu::tq_detail diff --git a/src/kernels/cpu/tq_avx512.cpp b/src/kernels/cpu/tq_avx512.cpp new file mode 100644 index 00000000..b4511884 --- /dev/null +++ b/src/kernels/cpu/tq_avx512.cpp @@ -0,0 +1,95 @@ +// 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 + +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 +inline __m512i rows8(const long long* tab, const uint8_t* qs, uint64_t wr, int t0) { + const __m256i lo = rows4(tab, tq_state(qs, wr, t0), tq_state(qs, wr, t0 + 1), tq_state(qs, wr, t0 + 2), + tq_state(qs, wr, t0 + 3)); + const __m256i hi = rows4(tab, tq_state(qs, wr, t0 + 4), tq_state(qs, wr, t0 + 5), + tq_state(qs, wr, t0 + 6), tq_state(qs, wr, t0 + 7)); + return _mm512_inserti64x4(_mm512_castsi256_si512(lo), hi, 1); +} + +template +void rows_t(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*) tq_state_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(qs); + // states 8k .. 8k+7 -> weights 32k .. 32k+31 = Q8_0 sub-block k + const __m512i w0 = rows8(tab, qs, wr, 0), w1 = rows8(tab, qs, wr, 8); + const __m512i w2 = rows8(tab, qs, wr, 16), w3 = rows8(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 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>(w, row_bytes, n, a, nt, out, r0, r1); + else if (kb == 6) rows_t<6>(w, row_bytes, n, a, nt, out, r0, r1); + else rows_t<7>(w, row_bytes, n, a, nt, out, r0, r1); +} + +} // namespace strata::kernels::cpu::tq_detail diff --git a/src/kernels/cpu/tq_cpu.cpp b/src/kernels/cpu/tq_cpu.cpp new file mode 100644 index 00000000..1240d7f7 --- /dev/null +++ b/src/kernels/cpu/tq_cpu.cpp @@ -0,0 +1,215 @@ +// 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 "ggml-common-tq.h" + +#include +#include +#include +#include +#include +#include +#include + +// 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]; + +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); + } + } +} + +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 +void rows_scalar_t(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; + const int16_t* tab = tq_state_table(); + 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(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; +} + +bool tq_supported(int t) noexcept { return t == 144 || t == 145 || t == 146; } + +int tq_kbits(int t) noexcept { return t == 144 ? 8 : t == 145 ? 6 : t == 146 ? 7 : 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 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>(w, row_bytes, n, a, nt, out, r0, r1); + else if (kb == 6) rows_scalar_t<6>(w, row_bytes, n, a, nt, out, r0, r1); + else rows_scalar_t<7>(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 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 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, w, row_bytes, n, a, nt, out, r0, r1); break; + case TqIsa::avx2: tq_detail::tq_rows_avx2(kb, w, row_bytes, n, a, nt, out, r0, r1); break; +#endif + default: tq_detail::tq_rows_scalar(kb, 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 + tq_state_table(); + const ActSet& s = unpack_all(act, n, nt); + rows_on(isa, tq_kbits(ggml_type), 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(); + tq_state_table(); + const ActSet& s = unpack_all(act, n, nt); + thread_local std::vector 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, blob, gu_row, n, s.ptr, nt, gp, r0, r1); + rows_on(isa, kb, 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 diff --git a/src/kernels/cpu/tq_cpu_parity.cpp b/src/kernels/cpu/tq_cpu_parity.cpp new file mode 100644 index 00000000..2f860ee6 --- /dev/null +++ b/src/kernels/cpu/tq_cpu_parity.cpp @@ -0,0 +1,565 @@ +// src/kernels/cpu/tq_cpu_parity.cpp - the CPU trellis kernels (tq_cpu.hpp: TQ2_T / TQK6 / TQK7) against their scalar +// reference, against ggml-cpu's own vec_dot and to_float, and their speed. CPU only (no GPU runtime needed). +// +// tq_cpu_parity every check below for tqk6/tqk7 and tq2_t/tq2_t, plain and Hadamard +// tq_cpu_parity --synthetic GU/DOWN one expert pair (types by ggml name, e.g. tqk6/tqk7) +// tq_cpu_parity --synthetic-hadamard GU/DOWN the same with the block-128 Hadamard rotation of the activations +// tq_cpu_parity --bench [--quick] [--only K] the micro-benchmark (run it pinned: taskset -c ); +// --only: the kernels whose name contains K +// +// Checks, per matrix (random stream bytes and scales, so every state is reached, and ggml-quantized Gaussian rows): +// (1) AVX2 and AVX-512 kernels == the scalar kernel, bit for bit, for groups of 1..8 tokens +// (2) a token's row in a group of k == the same token alone, bit for bit (no group-size dependence) +// (3) vs ggml-cpu's vec_dot on the same Q8_0 activations: the same integers summed in another float order, so +// ~1e-7 relative +// (4) vs ggml's to_float weights . the dequantized Q8_0 activations in double: the int16 state table's rounding +// (exact for |codebook| >= 2^-3, within 2^-14 below) plus float rounding, ~1e-6 relative +// and per expert (native_gu_rows -> native_quant_h -> native_down_rows, the engine's entry points, which now take +// these kernels) against the same expert computed with ggml-cpu's vec_dot: float rounding plus the odd Q8_0 +// rounding flip of the intermediate. +#include "strata/kernels/cpu/tq_cpu.hpp" +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/hadamard.hpp" + +#include "ggml.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace strata::kernels::cpu; + +namespace { + +constexpr int H = 2560, FF = 640; + +int type_by_name(const std::string& s) { + for (int t = 0; t < GGML_TYPE_COUNT; ++t) { + const char* n = ggml_type_name((ggml_type) t); + if (n != nullptr && s == n) return t; + } + return -1; +} + +uint16_t f2h(float f) { return ggml_fp32_to_fp16(f); } + +// rows x n weights of `type`: random stream bytes and scales (every state reachable, both scale signs), and the +// last rows (up to 32, ggml's trellis encoder is slow) ggml's own encoding of Gaussian rows +std::vector make_matrix(int type, int rows, int n, uint32_t seed) { + const size_t rb = ggml_row_size((ggml_type) type, n); + std::vector m(rb * rows); + std::mt19937 rng(seed); + std::uniform_int_distribution byte(0, 255); + std::uniform_real_distribution scale(0.002f, 0.05f); + const size_t bsz = rb / (size_t) (n / 128); + const int half = rows - std::min(rows / 2, 32); + for (int r = 0; r < half; ++r) + for (int b = 0; b < n / 128; ++b) { + uint8_t* blk = m.data() + (size_t) r * rb + (size_t) b * bsz; + const uint16_t d = f2h((byte(rng) & 1 ? -1.f : 1.f) * scale(rng)); + std::memcpy(blk, &d, 2); + for (size_t j = 2; j < bsz; ++j) blk[j] = (uint8_t) byte(rng); + } + std::normal_distribution nd(0.f, 0.02f); + std::vector wf((size_t) (rows - half) * n); + for (auto& v : wf) v = nd(rng); + ggml_quantize_chunk((ggml_type) type, wf.data(), m.data() + (size_t) half * rb, 0, rows - half, n, nullptr); + return m; +} + +std::vector make_x(int n, uint32_t seed) { + std::mt19937 rng(seed); + std::normal_distribution nd(0.f, 1.f); + std::vector x(n); + for (auto& v : x) v = nd(rng); + x[(size_t) (seed % (uint32_t) n)] = 40.f; // a massive channel, as the residual stream has + return x; +} + +std::vector q8_0(const std::vector& x) { + std::vector q(ggml_row_size(GGML_TYPE_Q8_0, (int64_t) x.size())); + ggml_get_type_traits_cpu(GGML_TYPE_Q8_0)->from_float(x.data(), q.data(), (int64_t) x.size()); + return q; +} + +bool same_bits(const float* a, const float* b, size_t n) { return std::memcmp(a, b, n * sizeof(float)) == 0; } + +// one matrix: checks (1) - (4); returns failures +int check_matrix(int type, int rows, int n, uint32_t seed, bool hadamard) { + int fails = 0; + const size_t rb = ggml_row_size((ggml_type) type, n); + const auto m = make_matrix(type, rows, n, seed); + constexpr int NT = kTqMaxTokens; + std::vector> act(NT); + std::vector> xr(NT); + std::vector signs(n); + for (int i = 0; i < n; ++i) signs[i] = ((i * 2654435761u) >> 7) & 1 ? -1.f : 1.f; + const void* ap[NT]; + for (int t = 0; t < NT; ++t) { + xr[t] = make_x(n, seed * 31 + t); + if (hadamard) hadamard_rotate(xr[t].data(), n, 128, signs.data()); + act[t] = q8_0(xr[t]); + ap[t] = act[t].data(); + } + auto run = [&](TqIsa isa, int nt, const void* const* a, std::vector& o) { + o.assign((size_t) nt * rows, 0.f); + float* op[NT]; + for (int t = 0; t < nt; ++t) op[t] = o.data() + (size_t) t * rows; + // two row ranges, as the pool splits them + tq_rows(isa, type, m.data(), rb, n, a, nt, op, 0, rows / 3); + tq_rows(isa, type, m.data(), rb, n, a, nt, op, rows / 3, rows); + }; + std::vector ref, got; + run(TqIsa::scalar, NT, ap, ref); + // (1) every ISA this CPU has, every group size, == scalar bit for bit; (2) group-size independence + for (TqIsa isa : {TqIsa::scalar, TqIsa::avx2, TqIsa::avx512}) { + if (!tq_isa_ok(isa)) { std::printf(" %-6s not on this CPU: skipped\n", tq_isa_name(isa)); continue; } + bool ok = true; + for (int nt = 1; nt <= NT; ++nt) + for (int t0 = 0; t0 + nt <= NT; t0 += nt) { + run(isa, nt, ap + t0, got); + ok = ok && same_bits(got.data(), ref.data() + (size_t) t0 * rows, (size_t) nt * rows); + } + std::printf(" %-6s groups of 1..%d tokens vs the scalar kernel's 8-token run: %s\n", tq_isa_name(isa), NT, + ok ? "bitwise equal" : "DIFFERENT"); + fails += !ok; + } + // (3) ggml-cpu's vec_dot, (4) to_float in double + const auto* tc = ggml_get_type_traits_cpu((ggml_type) type); + const auto* tt = ggml_get_type_traits((ggml_type) type); + const auto* q8t = ggml_get_type_traits(GGML_TYPE_Q8_0); + double num3 = 0, num4 = 0, den = 0, max3 = 0; + std::vector wf(n), af(n); + for (int t = 0; t < 2; ++t) { + q8t->to_float(act[t].data(), af.data(), n); + for (int r = 0; r < rows; ++r) { + float g = 0; + tc->vec_dot(n, &g, 0, m.data() + (size_t) r * rb, 0, act[t].data(), 0, 1); + tt->to_float(m.data() + (size_t) r * rb, wf.data(), n); + double d = 0, mag = 0; + for (int i = 0; i < n; ++i) { d += (double) wf[i] * af[i]; mag += std::fabs((double) wf[i] * af[i]); } + const double ours = ref[(size_t) t * rows + r]; + num3 += (ours - g) * (ours - g); + num4 += (ours - d) * (ours - d); + den += d * d; + max3 = std::max(max3, std::fabs(ours - g) / (mag + 1e-30)); + } + } + const double r3 = std::sqrt(num3 / den), r4 = std::sqrt(num4 / den); + const bool ok3 = r3 < 1e-5 && max3 < 1e-5, ok4 = r4 < 1e-4; + std::printf(" vs ggml-cpu vec_dot: rel %.2e (worst row %.2e of sum|w a|) %s | vs to_float in double: rel %.2e %s\n", + r3, max3, ok3 ? "ok" : "FAILED", r4, ok4 ? "ok" : "FAILED"); + return fails + !ok3 + !ok4; +} + +// a whole expert through the engine's entry points vs the same expert on ggml-cpu's vec_dot +int check_expert(int gu, int dn, bool hadamard) { + NativeFmt f; + std::string err; + if (!native_fmt(gu, dn, H, FF, f, err)) { std::printf("native_fmt: %s\n", err.c_str()); return 1; } + std::vector sh(H), sf(FF); + for (int i = 0; i < H; ++i) sh[i] = (i * 7 % 3) ? 1.f : -1.f; + for (int i = 0; i < FF; ++i) sf[i] = (i * 5 % 3) ? -1.f : 1.f; + if (hadamard) { + f.had_block = 128; + f.had_gu = f.had_d = true; + f.gu_signs = sh.data(); + f.d_signs = sf.data(); + } + std::vector blob(f.bytes); + const auto g = make_matrix(gu, FF, H, 101), u = make_matrix(gu, FF, H, 202), d = make_matrix(dn, H, FF, 303); + std::memcpy(blob.data(), g.data(), g.size()); + std::memcpy(blob.data() + f.up_off, u.data(), u.size()); + std::memcpy(blob.data() + f.down_off, d.data(), d.size()); + constexpr int NT = 3; + double worst = 0; + bool bitwise_group = true; + std::vector> outs(NT, std::vector(H)); + std::vector> acts(NT, std::vector(kNativeActBytes)); + std::vector> ffs(NT, std::vector(FF)); + std::vector> hqs(NT, std::vector(kNativeHBytes)); + const void* a[NT]; + float* ffp[NT]; + const void* hp[NT]; + float* op[NT]; + for (int t = 0; t < NT; ++t) { + const auto x = make_x(H, 7 + t); + native_quant_act(f, x.data(), acts[t].data()); + a[t] = acts[t].data(); + ffp[t] = ffs[t].data(); + hp[t] = hqs[t].data(); + op[t] = outs[t].data(); + } + native_gu_rows(f, blob.data(), a, NT, ffp, 0, FF); + for (int t = 0; t < NT; ++t) native_quant_h(f, ffs[t].data(), hqs[t].data()); + native_down_rows(f, blob.data(), hp, NT, op, 0, H); + const auto* tg = ggml_get_type_traits_cpu((ggml_type) gu); + const auto* td = ggml_get_type_traits_cpu((ggml_type) dn); + for (int t = 0; t < NT; ++t) { + std::vector ff(FF), out(H); + for (int r = 0; r < FF; ++r) { + float gg = 0, uu = 0; + tg->vec_dot(H, &gg, 0, blob.data() + (size_t) r * f.gu_row, 0, a[t], 0, 1); + tg->vec_dot(H, &uu, 0, blob.data() + f.up_off + (size_t) r * f.gu_row, 0, a[t], 0, 1); + ff[r] = (gg / (1.f + std::exp(-gg))) * uu; + } + std::vector hq(kNativeHBytes); + native_quant_h(f, ff.data(), hq.data()); + for (int r = 0; r < H; ++r) + td->vec_dot(FF, &out[r], 0, blob.data() + f.down_off + (size_t) r * f.d_row, 0, hq.data(), 0, 1); + double num = 0, den = 0; + for (int r = 0; r < H; ++r) { num += std::pow((double) outs[t][r] - out[r], 2); den += (double) out[r] * out[r]; } + worst = std::max(worst, std::sqrt(num / den)); + // the same token alone through the engine path: the same bits as in the group of three + std::vector ff1(FF), o1(H); + float* f1[1] = {ff1.data()}; + float* o1p[1] = {o1.data()}; + const void* a1[1] = {a[t]}; + native_gu_rows(f, blob.data(), a1, 1, f1, 0, FF); + std::vector h1(kNativeHBytes); + native_quant_h(f, ff1.data(), h1.data()); + const void* h1p[1] = {h1.data()}; + native_down_rows(f, blob.data(), h1p, 1, o1p, 0, H); + bitwise_group = bitwise_group && same_bits(o1.data(), outs[t].data(), H); + } + const bool ok = worst < 2e-3 && bitwise_group; + std::printf(" expert %s/%s%s through native_gu_rows/native_down_rows (%s, %s): vs ggml-cpu vec_dot rel %.2e, " + "alone vs in a group of %d: %s %s\n", + ggml_type_name((ggml_type) gu), ggml_type_name((ggml_type) dn), hadamard ? " +hadamard" : "", + tq_kernels_enabled() ? "tq kernels" : "ggml-cpu", tq_isa_name(tq_isa()), worst, NT, + bitwise_group ? "bitwise equal" : "DIFFERENT", ok ? "ok" : "FAILED"); + return ok ? 0 : 1; +} + +int synthetic(int gu, int dn, bool hadamard) { + int fails = 0; + std::printf("%s/%s%s (tq kernels: %s, best ISA here %s)\n", ggml_type_name((ggml_type) gu), + ggml_type_name((ggml_type) dn), hadamard ? " +hadamard" : "", tq_kernels_enabled() ? "on" : "off", + tq_isa_name(tq_isa())); + std::printf(" %s, 96 rows of %d (gate/up shape)\n", ggml_type_name((ggml_type) gu), H); + fails += check_matrix(gu, 96, H, 1000 + gu, hadamard); + std::printf(" %s, 256 rows of %d (down shape)\n", ggml_type_name((ggml_type) dn), FF); + fails += check_matrix(dn, 256, FF, 2000 + dn, hadamard); + fails += check_expert(gu, dn, hadamard); + return fails; +} + +// ------------------------------------------------------------------------------------------------ the benchmark + +double now_us() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +struct BenchExpert { + std::vector gu, dn; // gate rows then up rows; down rows + size_t gu_row, d_row; +}; + +// one variant: compute one expert (gate+up rows, then down rows) for `nt` tokens +using ExpertFn = std::function; + +// the core clock right now: a chain of dependent adds runs at one per cycle (GCC / Clang on x86-64; 0 elsewhere) +double core_ghz() { +#if defined(__GNUC__) && defined(__x86_64__) + uint64_t x = 0; + const long n = 1000000; + const double t0 = now_us(); + for (long i = 0; i < n; ++i) __asm__ volatile("add $1, %0\n\tadd $1, %0\n\tadd $1, %0\n\tadd $1, %0" : "+r"(x)); + return 4.0 * n / ((now_us() - t0) * 1e3); +#else + return 0.0; +#endif +} + +constexpr double kBlocksPerExpert = 2.0 * FF * (H / 128) + (double) H * (FF / 128); // 128-weight blocks + +// one slice of `ms` milliseconds cycling over the experts: ns per expert call and the clock around it (negated when +// the clock moved by more than 5% during the slice: such samples count only when a variant has no other) +std::pair time_slice(const std::vector& ex, const ExpertFn& fn, int nt, double ms, + size_t& next) { + const double g0 = core_ghz(); + int it = 0; + const double t0 = now_us(); + double t1 = t0; + do { + fn(ex[next++ % ex.size()], nt); + ++it; + t1 = now_us(); + } while (t1 - t0 < ms * 1000.0 || it < 2); + const double g1 = core_ghz(); + const double ghz = 0.5 * (g0 + g1); + return {(t1 - t0) * 1e3 / it, ghz > 0 && std::fabs(g1 - g0) > 0.05 * g0 ? -ghz : ghz}; +} + +double median(std::vector v) { + if (v.empty()) return 0.0; + std::sort(v.begin(), v.end()); + return v[v.size() / 2]; +} + +// `threads` threads, each cycling over its own experts: aggregate weight GB/s +double time_parallel(const std::vector& ex, const ExpertFn& fn, int threads, double ms) { + std::atomic done{0}; + std::atomic stop{false}; + std::vector th; + const double t0 = now_us(); + for (int k = 0; k < threads; ++k) + th.emplace_back([&, k] { + long c = 0; + for (size_t i = (size_t) k; !stop.load(std::memory_order_relaxed); i += (size_t) threads, ++c) + fn(ex[i % ex.size()], 1); + done += c; + }); + std::this_thread::sleep_for(std::chrono::milliseconds((int) ms)); + stop = true; + for (auto& t : th) t.join(); + const double us = now_us() - t0; + const double bytes = (double) (ex[0].gu_row * 2 * FF + ex[0].dn.size()) * (double) done.load(); + return bytes / (us * 1e3); +} + +int bench(bool quick, const std::string& only) { + const int ncold = quick ? 48 : 96; // ~50-130 MB of weights: past the last-level cache + std::printf("CPU: %s | AVX-512 kernels: %s, AVX2: %s | ggml-cpu built for this CPU (-march=native unless " + "STRATA_PORTABLE)\n", cpu_name().c_str(), cpu_avx512_ok() ? "yes" : "no", cpu_avx2_ok() ? "yes" : "no"); + std::printf("expert = gate+up %d x %d and down %d x %d of one type, %d distinct experts cycled (their weights come " + "from DRAM, as a cache miss's do)\n\n", FF, H, H, FF, ncold); + struct Variant { std::string name; int type; ExpertFn fn; bool ok; }; + std::vector vars; + auto add_tq = [&](int type) { + for (TqIsa isa : {TqIsa::scalar, TqIsa::avx2, TqIsa::avx512}) { + vars.push_back({std::string("strata ") + tq_isa_name(isa), type, + [type, isa](const BenchExpert& e, int nt) { + thread_local std::vector a, h; + thread_local std::vector ff, out; + a.resize(ggml_row_size(GGML_TYPE_Q8_0, H) * kTqMaxTokens); + h.resize(ggml_row_size(GGML_TYPE_Q8_0, FF) * kTqMaxTokens); + ff.resize((size_t) FF * kTqMaxTokens); + out.resize((size_t) H * kTqMaxTokens); + const void* ap[kTqMaxTokens]; + const void* hp[kTqMaxTokens]; + float* fp[kTqMaxTokens]; + float* op[kTqMaxTokens]; + for (int t = 0; t < nt; ++t) { + ap[t] = a.data() + t * ggml_row_size(GGML_TYPE_Q8_0, H); + hp[t] = h.data() + t * ggml_row_size(GGML_TYPE_Q8_0, FF); + fp[t] = ff.data() + (size_t) t * FF; + op[t] = out.data() + (size_t) t * H; + } + tq_gu_rows(isa, type, e.gu.data(), e.gu_row, e.gu_row * FF, H, ap, nt, fp, 0, FF); + tq_rows(isa, type, e.dn.data(), e.d_row, FF, hp, nt, op, 0, H); + }, + tq_isa_ok(isa)}); + } + vars.push_back({"ggml-cpu vec_dot", type, + [type](const BenchExpert& e, int nt) { + const auto* tc = ggml_get_type_traits_cpu((ggml_type) type); + thread_local std::vector a(ggml_row_size(GGML_TYPE_Q8_0, H)), + h(ggml_row_size(GGML_TYPE_Q8_0, FF)); + thread_local std::vector ff(FF), out(H); + for (int t = 0; t < nt; ++t) { + for (int r = 0; r < FF; ++r) { + float g, u; + tc->vec_dot(H, &g, 0, e.gu.data() + (size_t) r * e.gu_row, 0, a.data(), 0, 1); + tc->vec_dot(H, &u, 0, e.gu.data() + (size_t) (FF + r) * e.gu_row, 0, a.data(), 0, 1); + ff[r] = (g / (1.f + std::exp(-g))) * u; + } + for (int r = 0; r < H; ++r) + tc->vec_dot(FF, &out[r], 0, e.dn.data() + (size_t) r * e.d_row, 0, h.data(), 0, 1); + } + }, + true}); + }; + auto add_q2 = [&](bool avx512) { + vars.push_back({avx512 ? "strata Q2_0 avx512" : "strata Q2_0 avx2", 42, + [avx512](const BenchExpert& e, int nt) { + thread_local ActQ a1[MAXT], a2[MAXT]; + thread_local bool init = false; + if (!init) { // real scales and codes (the kernel reads every field) + const auto x = make_x(H, 3), h = make_x(FF, 4); + for (int t = 0; t < MAXT; ++t) { act_quant_q8_1_avx2(x.data(), H, a1[t]); act_quant_q8_1_avx2(h.data(), FF, a2[t]); } + init = true; + } + thread_local float g[MAXT][FF], u[MAXT][FF], out[MAXT][H]; + const ActQ* ap[MAXT]; + const ActQ* hp[MAXT]; + float* gp[MAXT]; + float* up[MAXT]; + float* op[MAXT]; + for (int t = 0; t < nt; ++t) { ap[t] = &a1[t]; hp[t] = &a2[t]; gp[t] = g[t]; up[t] = u[t]; op[t] = out[t]; } + auto rows = avx512 ? q2_0_gguf_rows_multi : q2_0_gguf_rows_multi_avx2; + rows(e.gu.data(), e.gu_row, H / 64, ap, nt, gp, 0, FF); + rows(e.gu.data() + e.gu_row * FF, e.gu_row, H / 64, ap, nt, up, 0, FF); + for (int t = 0; t < nt; ++t) + for (int r = 0; r < FF; ++r) g[t][r] = (g[t][r] / (1.f + std::exp(-g[t][r]))) * u[t][r]; + rows(e.dn.data(), e.d_row, FF / 64, hp, nt, op, 0, H); + }, + avx512 ? cpu_avx512_ok() : cpu_avx2_ok()}); + }; + for (int type : {145, 146, 144}) add_tq(type); + add_q2(false); + add_q2(true); + // the Q2_0 pack's own AVX-512 kernel (the repacked 1,382,400-byte blob that setup makes on AVX-512 CPUs) + vars.push_back({"strata Q2_0 avx512 pack", 42, + [](const BenchExpert& e, int nt) { + thread_local ActQ a1, a2; + thread_local bool init = false; + if (!init) { + const auto x = make_x(H, 3), h = make_x(FF, 4); + act_quant_q8_1(x.data(), H, a1); + act_quant_q8_1(h.data(), FF, a2); + init = true; + } + thread_local float ff[FF], out[H]; + for (int t = 0; t < nt; ++t) { // its multi-token kernels are the same per token + s2_expert_gu_rows(e.gu.data(), a1, ff, 0, FF); + s2_expert_down_rows(e.gu.data(), a2, out, 0, H); + } + }, + cpu_avx512_ok()}); + + auto make_experts = [&](int type, int count) { + std::vector v((size_t) count); + for (int k = 0; k < count; ++k) { + BenchExpert& e = v[(size_t) k]; + e.gu_row = ggml_row_size((ggml_type) type, H); + e.d_row = ggml_row_size((ggml_type) type, FF); + // (Q2_0: room for one repacked blob too, which the pack kernel reads from the same buffer) + e.gu.resize(type == 42 ? std::max(e.gu_row * 2 * FF, (size_t) BLOB) : e.gu_row * 2 * FF); + e.dn.resize(e.d_row * H); + std::mt19937 rng(77 + k); + for (auto& b : e.gu) b = (uint8_t) rng(); + for (auto& b : e.dn) b = (uint8_t) rng(); + // sane fp16 scales at every block start (Q2_0: 18-byte blocks, TQ: 26/30/34) + const size_t bsz = type == 42 ? 18 : ggml_row_size((ggml_type) type, 128); + const uint16_t d = f2h(0.01f); + for (size_t o = 0; o + bsz <= e.gu.size(); o += bsz) std::memcpy(e.gu.data() + o, &d, 2); + for (size_t o = 0; o + bsz <= e.dn.size(); o += bsz) std::memcpy(e.dn.data() + o, &d, 2); + if (type == 42) { // the same bytes also hold one repacked Q2_0 blob (codes, then fp16 scales) + for (size_t o = O_GU_SCALES; o + 2 <= BLOB; o += 2) std::memcpy(e.gu.data() + o, &d, 2); + } + } + return v; + }; + // Single thread, the variants of a type interleaved in short slices over several rounds (this machine's clock + // moves; a slice whose clock moved is dropped), medians reported: ns and core cycles per 128-weight block, us + // per expert, weight GB/s; and per token in a group of three (a verify window's tokens routed to one expert). + // The activations are zero-filled (the kernels do not branch on values) except Q2_0's, which are real. + const int rounds = quick ? 5 : 15; + const double slice_ms = quick ? 40 : 60; + std::printf("%-6s %-24s %9s %8s %8s %8s | %10s %8s\n", "type", "kernel", "us/expert", "ns/blk", "cyc/blk", "GB/s", + "x3: us/tok", "cyc/blk"); + for (int type : {145, 146, 144, 42}) { + const auto cold = make_experts(type, ncold); + const double eb = (double) (cold[0].gu_row * 2 * FF + cold[0].dn.size()); // weight bytes per expert + std::vector vs; + for (const auto& v : vars) + if (v.type == type && v.name.find(only) != std::string::npos) { + if (v.ok) vs.push_back(&v); + else std::printf("%-6s %-24s (not on this CPU)\n", ggml_type_name((ggml_type) type), v.name.c_str()); + } + std::vector> ns1(vs.size()), cy1(vs.size()), ns3(vs.size()), cy3(vs.size()); + std::vector> ns1m(vs.size()), cy1m(vs.size()), ns3m(vs.size()), cy3m(vs.size()); + size_t next = 0; + for (auto* v : vs) v->fn(cold[0], 3); // warm-up: tables, buffers + for (int r = 0; r < rounds; ++r) + for (size_t k = 0; k < vs.size(); ++k) { + const bool slow = vs[k]->name.find("scalar") != std::string::npos; + const auto a = time_slice(cold, vs[k]->fn, 1, slow ? slice_ms / 2 : slice_ms, next); + const auto b = time_slice(cold, vs[k]->fn, 3, slow ? slice_ms / 2 : slice_ms, next); + if (a.second >= 0) { ns1[k].push_back(a.first); cy1[k].push_back(a.first * a.second); } + else { ns1m[k].push_back(a.first); cy1m[k].push_back(-a.first * a.second); } + if (b.second >= 0) { ns3[k].push_back(b.first); cy3[k].push_back(b.first * b.second); } + else { ns3m[k].push_back(b.first); cy3m[k].push_back(-b.first * b.second); } + } + std::vector steady(vs.size()); + for (size_t k = 0; k < vs.size(); ++k) { + steady[k] = ns1[k].size(); + if (ns1[k].empty()) { ns1[k] = ns1m[k]; cy1[k] = cy1m[k]; } + if (ns3[k].empty()) { ns3[k] = ns3m[k]; cy3[k] = cy3m[k]; } + } + for (size_t k = 0; k < vs.size(); ++k) { + const double n1 = median(ns1[k]), c1 = median(cy1[k]), n3 = median(ns3[k]), c3 = median(cy3[k]); + std::printf("%-6s %-24s %9.1f %8.1f %8.1f %8.2f | %10.1f %8.1f (%zu/%d steady)\n", + ggml_type_name((ggml_type) type), vs[k]->name.c_str(), n1 / 1e3, n1 / kBlocksPerExpert, + c1 / kBlocksPerExpert, eb / n1, n3 / 3e3, c3 / kBlocksPerExpert, steady[k], rounds); + } + std::fflush(stdout); + } + // several workers at once (as the pool runs a layer's misses): aggregate GB/s on the cold set + const int nthr = (int) std::max(1u, std::min(4u, std::thread::hardware_concurrency())); + std::printf("\n%d threads at once, cold experts, one token: aggregate weight GB/s (us per expert per thread)\n", nthr); + for (int type : {145, 146, 144, 42}) { + const auto cold = make_experts(type, ncold); + const double eb = (double) (cold[0].gu_row * 2 * FF + cold[0].dn.size()); + std::vector vs; + for (const auto& v : vars) + if (v.type == type && v.ok && v.name.find("scalar") == std::string::npos && v.name.find(only) != std::string::npos) + vs.push_back(&v); + std::vector> g(vs.size()); + for (int r = 0; r < (quick ? 2 : 4); ++r) + for (size_t k = 0; k < vs.size(); ++k) g[k].push_back(time_parallel(cold, vs[k]->fn, nthr, quick ? 150 : 250)); + for (size_t k = 0; k < vs.size(); ++k) { + const double gbs = median(g[k]); + std::printf("%-6s %-24s %8.2f GB/s (%7.1f us per expert per thread)\n", ggml_type_name((ggml_type) type), + vs[k]->name.c_str(), gbs, eb / (gbs * 1e3) * nthr); + } + std::fflush(stdout); + } + // the per-token Hadamard rotation of one layer's activation (once per token per layer, shared by its experts) + { + std::vector x = make_x(H, 5), s(H, 1.f); + const int it = 20000; + const double t0 = now_us(); + for (int i = 0; i < it; ++i) hadamard_rotate(x.data(), H, 128, s.data()); + std::printf("\nHadamard rotation of one %d-wide activation (block 128): %.2f us\n", H, (now_us() - t0) / it); + } + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + ggml_cpu_init(); + if (GGML_TYPE_COUNT <= 146) { + std::fprintf(stderr, "this ggml has no trellis types (build with STRATA_GGML_DIR = the agention llama.cpp fork)\n"); + return 1; + } + if (argc >= 2 && std::strcmp(argv[1], "--bench") == 0) { // --bench [--quick] [--only ] + bool quick = false; + std::string only; + for (int i = 2; i < argc; ++i) { + if (std::strcmp(argv[i], "--quick") == 0) quick = true; + else if (std::strcmp(argv[i], "--only") == 0 && i + 1 < argc) only = argv[++i]; + } + return bench(quick, only); + } + if (argc >= 3 && (std::strcmp(argv[1], "--synthetic") == 0 || std::strcmp(argv[1], "--synthetic-hadamard") == 0)) { + const std::string pair = argv[2]; + const size_t sl = pair.find('/'); + const int gu = type_by_name(pair.substr(0, sl)), dn = sl == std::string::npos ? gu : type_by_name(pair.substr(sl + 1)); + if (!tq_supported(gu) || !tq_supported(dn)) { std::fprintf(stderr, "not a trellis pair: %s\n", argv[2]); return 2; } + const int f = synthetic(gu, dn, std::strcmp(argv[1], "--synthetic-hadamard") == 0); + std::printf("%d failures\n", f); + return f ? 1 : 0; + } + int f = 0; + for (bool had : {false, true}) { + f += synthetic(145, 146, had); // Gyro-S + f += synthetic(144, 144, had); // Gyro-M + } + std::printf("%d failures\n", f); + return f ? 1 : 0; +} diff --git a/src/kernels/cpu/tq_states.hpp b/src/kernels/cpu/tq_states.hpp new file mode 100644 index 00000000..bb4eaa7a --- /dev/null +++ b/src/kernels/cpu/tq_states.hpp @@ -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 +#include + +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(qs) for the TQK windows past the end. +template +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 +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 +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 diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 47e0e76e..fd0e180e 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -16,10 +16,17 @@ #define GGML_COMMON_DECL_CUDA #define GGML_COMMON_IMPL_CUDA #include "ggml-common.h" +#include "ggml-common-tq.h" // APR trellis types (agention llama.cpp fork) +#include "tq_lut_i8.cuh" // int8 copy of the trellis codebook (one global scale) for the dp4a dot +#include +#include #include #include #include +#include +#include +#include #include namespace strata::kernels { @@ -600,6 +607,97 @@ __device__ __forceinline__ float vec_dot_nvfp4_q8_1(const void* __restrict__ vbq return sum; } +// ---------------------------------------------------------------- APR trellis types (ggml 144 TQ2_T, 145 TQK6, 146 TQK7) +// Transcribed from the agention llama.cpp fork's ggml-cuda/tq.cuh (6d3f2b1b8; format in ggml-common-tq.h). A +// 128-value block is 8 lanes of 4 trellis steps (16 values); the dot of lane l reads q8_1 block l/2, ints 4(l&1).. +template struct TqInfo; +template<> struct TqInfo<144> { using block_t = block_tq2_t; }; // byte-aligned, no K +template<> struct TqInfo<145> { using block_t = block_tqk6; static constexpr int K = 6; }; +template<> struct TqInfo<146> { using block_t = block_tqk7; static constexpr int K = 7; }; +__device__ __forceinline__ float tq_h2f(uint32_t bits) { return __half2float(__ushort_as_half((unsigned short) bits)); } +// the four unscaled weights of the step with state s: (a.x, a.y, b.x, b.y) +__device__ __forceinline__ void tq_step(uint32_t s, float2& a, float2& b) { + const uint32_t* lut = (const uint32_t*) tq_lut_f16; + const uint32_t x = (s & TQ_STATE_MASK) * 0x9e3779b1u; + const uint32_t pa = lut[x >> 21], pb = lut[(x >> 10) & 2047u]; + a = make_float2(tq_h2f(pa & 0xFFFFu), tq_h2f(pa >> 16)); + b = make_float2(tq_h2f(pb & 0xFFFFu), tq_h2f(pb >> 16)); +} +// the states of steps 4l..4l+3 of one block (qs is 2-byte aligned: every trellis block has an even size) +template +__device__ __forceinline__ void tq_states4(const uint8_t* qs, int l, uint32_t s[4]) { + const uint16_t* qs16 = (const uint16_t*) qs; + if constexpr (TY == 144) { // s_t = qs[(t + 31) % 32] << 8 | qs[t] + const uint32_t w01 = qs16[2 * l + 0], w23 = qs16[2 * l + 1]; + const uint32_t prev = qs[(4 * l + 31) & 31]; + const uint32_t b0 = w01 & 0xFF, b1 = w01 >> 8, b2 = w23 & 0xFF, b3 = w23 >> 8; + s[0] = (prev << 8) | b0; + s[1] = (b0 << 8) | b1; + s[2] = (b1 << 8) | b2; + s[3] = (b2 << 8) | b3; + } else { + // step t's state: the 16 stream bits from bit (31 - t)*K, circular over 2K u16 words; steps 4l..4l+3 all + // lie in the four words from (28 - 4l)*K >> 4 + constexpr int K = TqInfo::K, nwords = 2 * K; + const int off3 = (28 - 4 * l) * K, wb = off3 >> 4, r = off3 & 15; + const int wi1 = wb + 1 >= nwords ? wb + 1 - nwords : wb + 1; + const int wi2 = wb + 2 >= nwords ? wb + 2 - nwords : wb + 2; + const int wi3 = wb + 3 >= nwords ? wb + 3 - nwords : wb + 3; + const uint64_t v = (uint64_t) qs16[wb] | ((uint64_t) qs16[wi1] << 16) | ((uint64_t) qs16[wi2] << 32) | + ((uint64_t) qs16[wi3] << 48); +#pragma unroll + for (int i = 0; i < 4; ++i) s[i] = (uint32_t) (v >> (r + (3 - i) * K)) & 0xFFFFu; + } +} +// lane iqs/4 of block kbx against the q8_1 blocks aligned with the block's start (4 per trellis block). Split in +// two, like the IQ types' decode-once kernels below: tq_load decodes the lane's 16 codebook values (weight side only), +// tq_apply does the activation side. vec_dot_tq_q8_1 is apply(load()), and the decode-once kernels call tq_load once +// per weight part and tq_apply per entry: the same integer and float operations in the same order, so the two kernel +// families are bitwise equal to EACH OTHER (native_expert_parity: "decode-once vs per-entry kernels"). Neither is +// bitwise equal to a float decode of the weights, see Numerics. +// The lane's 16 codebook values as 4 ints of packed int8: a trellis step's 4 weights are two 2-byte entries = one +// int, so the apply side is 4 dp4a instead of 16 int8->float + 16 FMAs, and a decoded lane takes 5 registers +// instead of 17. +// +// Numerics. Decode (these kernels) reads the int8 codebook tq_lut_i8: one global scale TQ_LUT_I8_SCALE, relative +// RMS error 0.85% of the codebook std, far below the trellis quantization error. The prompt path decodes the +// trellis otherwise: the FP16 path (dq_tq below) through the fp16 codebook tq_lut_f16, which is what ggml's to_float +// reads, and the MMQ path through the GGML fork's tile loader (the int8 codebook too on the fork's main since +// 2026-10-03; the fp16 codebook requantized to int8 per 16 weights before that and with GGML_CUDA_TQ_F32_DOT). +// Decode and prompt therefore agree within tolerance, not bitwise. native_expert_parity bounds this path: one +// expert (int8 codebook, q8_1 activations) against ggml's float dequantizer and a float SwiGLU, relative L1 error +// sum|gpu - ref| / sum|ref| < 3e-2 (the bound every expert type's CPU and GPU paths get there); the prompt path's +// fp16 dequantizers against to_float at < 1e-6, their fp16 output equal to the fp16 of the float one. +struct TqLane { int q[4]; float d; }; +template +__device__ __forceinline__ TqLane tq_load(const void* __restrict__ vbq, int kbx, int iqs) { + const auto* b = (const typename TqInfo::block_t*) vbq + kbx; + uint32_t s[4]; + tq_states4(b->qs, iqs / 4, s); + TqLane r; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const uint32_t x = (s[i] & TQ_STATE_MASK) * 0x9e3779b1u; + r.q[i] = (int) ((uint32_t) tq_lut_i8[x >> 21] | ((uint32_t) tq_lut_i8[(x >> 10) & 2047u] << 16)); + } + r.d = tq_h2f(b->d); + return r; +} +__device__ __forceinline__ float tq_apply(const TqLane& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const int l = iqs / 4; + const block_q8_1* b8 = bq8_1 + l / 2; + const int* q8 = (const int*) b8->qs + 4 * (l & 1); + int sumi = 0; +#pragma unroll + for (int i = 0; i < 4; ++i) sumi = ggml_cuda_dp4a(r.q[i], q8[i], sumi); + return r.d * (__low2float(b8->ds) * TQ_LUT_I8_SCALE) * (float) sumi; +} +template +__device__ __forceinline__ float vec_dot_tq_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + return tq_apply(tq_load(vbq, kbx, iqs), bq8_1, iqs); +} + // ---------------------------------------------------------------- the formats // qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls. template struct Fmt; @@ -637,21 +735,28 @@ template<> struct Fmt<6> { static constexpr int qk = 32, ipb = QI5_0 / VDR_Q5_0, __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_0_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q8_0_q8_1(v, y, kbx, iqs); } }; +// APR trellis types: 8 lanes of 4 steps per 128-value block, iqs = 4 * lane +template<> struct Fmt<144> { static constexpr int qk = 128, ipb = 8, step = 4; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tq_q8_1<144>(v, y, kbx, iqs); } }; +template<> struct Fmt<145> { static constexpr int qk = 128, ipb = 8, step = 4; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tq_q8_1<145>(v, y, kbx, iqs); } }; +template<> struct Fmt<146> { static constexpr int qk = 128, ipb = 8, step = 4; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tq_q8_1<146>(v, y, kbx, iqs); } }; // The formats of each role, one list each so a type cannot be in one switch and missing from another. Every // entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one. #ifdef STRATA_Q6K_EXPERTS // opt-in build (-DSTRATA_Q6K_EXPERTS=ON): one more instance per kernel, loaded at start -#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8) X(40) +#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8) X(40) X(144) X(145) #else -#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) X(40) +#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) X(40) X(144) X(145) #endif // Q5_K / Q6_K downs: Qwen3.6-35B-A3B (FF 512, whole 256-blocks per row); Flash-Next's FF 640 never selects them #ifdef STRATA_Q6K_EXPERTS -#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(14) X(40) +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(14) X(40) X(144) X(146) #else -#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(40) +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(40) X(144) X(146) #endif -#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) X(40) +#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) X(40) X(144) X(145) X(146) template<> struct Fmt<40> { static constexpr int qk = 64, ipb = 2, step = 4; // NVFP4: 2 calls of 32 values __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_nvfp4_q8_1(v, y, kbx, iqs); } }; @@ -1035,6 +1140,21 @@ template<> struct Split<40> { // NVFP4: vec_dot_nvfp4_q8_1's two 16-value sub- return sum; } }; +// APR trellis types: the lane's 16 decoded codebook values (tq_load / tq_apply above) +template<> inline constexpr bool kSplit<144> = true; +template<> inline constexpr bool kSplit<145> = true; +template<> inline constexpr bool kSplit<146> = true; +template struct SplitTq { + using W = TqLane; + template // (no grid table to stage: the codebook is read where it is) + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { + return tq_load(vbq, kbx, iqs); + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { return tq_apply(r, bq8_1, iqs); } +}; +template<> struct Split<144> : SplitTq<144> {}; +template<> struct Split<145> : SplitTq<145> {}; +template<> struct Split<146> : SplitTq<146> {}; // One row against the n <= NC activations x + off[0..n) (n >= 1, warp-uniform; offsets in q8_1 blocks, 32-bit to // spare registers), the whole warp. Per activation this is row_dot: the same calls k, lane-strided the same way, @@ -1378,7 +1498,7 @@ __global__ void __launch_bounds__(256) native_gu_multi_kernel(const unsigned lon const uint32_t* s_grid = stage_iq_grid(s_grid_buf, threadIdx.x, 256); const int nb = (int) (L.n_embd / Fmt::qk), xb = (int) (L.n_embd / 32); if constexpr (SUB16) { - if (xb == 80) { + if (xb == 80 && nb * Fmt::ipb == 80) { // row_dot_80_sub16 covers exactly 80 dots (not the 128-value TQ blocks) const int subwarp = threadIdx.x >> 4, t = threadIdx.x & 15; const int row = blockIdx.x * 16 + subwarp; // 0 .. 2*n_ff if (row >= 2 * L.n_ff) return; @@ -1458,6 +1578,34 @@ __global__ void __launch_bounds__(256) native_gu_multi_kernel(const unsigned lon } } +// APR (prism.hadamard): y = H_block (signs * x) per block of each row, block = blockDim.x (a power of two <= 1024), +// one thread block per (row block, row). The butterflies are the CPU's (hadamard.cpp) in the same order, so the +// rotated values are the same floats. +template __device__ __forceinline__ float ld_f(const T* p) { return (float) *p; } +template<> __device__ __forceinline__ float ld_f<__half>(const __half* p) { return __half2float(*p); } +template __device__ __forceinline__ void st_f(T* p, float v) { *p = v; } +template<> __device__ __forceinline__ void st_f<__half>(__half* p, float v) { *p = __float2half(v); } +template +__global__ void hadamard_rows_kernel(const T* __restrict__ x, T* __restrict__ y, int64_t width, + const float* __restrict__ signs, float scale) { + extern __shared__ float hbuf[]; + const int n = blockDim.x, i = threadIdx.x; + const int64_t col = (int64_t) blockIdx.x * n + i, at = (int64_t) blockIdx.y * width + col; + float v = ld_f(x + at); + if (signs) v *= signs[col]; + hbuf[i] = v; + for (int len = 1; len < n; len <<= 1) { + __syncthreads(); + if ((i & len) == 0) { + const float a = hbuf[i], c = hbuf[i + len]; + hbuf[i] = a + c; + hbuf[i + len] = a - c; + } + } + __syncthreads(); + st_f(y + at, hbuf[i] * scale); +} + __global__ void swiglu_entries_kernel(const float* __restrict__ gate, const float* __restrict__ up, float* __restrict__ h, long long n) { const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; @@ -2026,6 +2174,27 @@ __device__ void dq_nvfp4(const void* vx, int64_t ibs, dst_t* yy, int tid) { } } +// APR trellis types: one 256-value call = two 128-blocks; thread tid decodes block tid/16, lane (tid/2)%8, steps +// 2(tid%2)..2(tid%2)+1 (8 values) +template +__device__ void dq_tq(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const int blk = tid >> 4, l = (tid >> 1) & 7, half = tid & 1; + const auto* b = (const typename TqInfo::block_t*) vx + 2 * ibs + blk; + const float d = tq_h2f(b->d); + uint32_t s[4]; + tq_states4(b->qs, l, s); + dst_t* y = yy + blk * 128 + 16 * l + 8 * half; +#pragma unroll + for (int i = 0; i < 2; ++i) { + float2 a, c; + tq_step(s[2 * half + i], a, c); + y[4 * i + 0] = cvt(d * a.x); + y[4 * i + 1] = cvt(d * a.y); + y[4 * i + 2] = cvt(d * c.x); + y[4 * i + 3] = cvt(d * c.y); + } +} + // Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others, // so the default is unreachable. template @@ -2043,9 +2212,7 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, case 42: dq_q2_0(vx, ibs, y, tid); break; case 12: dq_q4_k(vx, ibs, y, tid); break; case 13: dq_q5_k(vx, ibs, y, tid); break; -#ifdef STRATA_Q6K_EXPERTS - case 14: dq_q6_k(vx, ibs, y, tid); break; -#endif + case 14: dq_q6_k(vx, ibs, y, tid); break; // the Q6K_EXPERTS kernels, and the token embedding (Gyro-S) case 7: dq_q5_1(vx, ibs, y, tid); break; case 6: dq_q5_0(vx, ibs, y, tid); break; case 2: dq_q4_0(vx, ibs, y, tid); break; @@ -2053,6 +2220,9 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, case 40: dq_nvfp4(vx, ibs, y, tid); break; case 8: dq_q8_0(vx, ibs, y, tid); break; case 30: dq_bf16(vx, ibs, y, tid); break; + case 144: dq_tq<144>(vx, ibs, y, tid); break; + case 145: dq_tq<145>(vx, ibs, y, tid); break; + case 146: dq_tq<146>(vx, ibs, y, tid); break; default: break; } } @@ -2094,9 +2264,9 @@ __global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const v bool is_iq(int t) { return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 || #ifdef STRATA_Q6K_EXPERTS - t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40; + t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40 || t == 144 || t == 145 || t == 146; #else - t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40; + t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40 || t == 144 || t == 145 || t == 146; #endif } // values per block of the types the grouped expert kernels take (0 = none) @@ -2844,6 +3014,9 @@ template void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L, float* gate, float* up) { + // the sub-16 rows (row_dot_80_sub16) assume 80 dots per row: (n_embd / qk) * ipb == 80. The APR trellis types + // (qk 128, ipb 8: 160 dots at n_embd 2560) take the full-warp multi kernel, as before the sub-16 kernels. + const bool g_no_sub16_gu = ::strata::kernels::g_no_sub16_gu || (L.n_embd / Fmt::qk) * Fmt::ipb != 80; if constexpr (!kSplit) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (g_old_kernels) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if constexpr (kStageIqGrid) { @@ -2876,7 +3049,8 @@ void iq_set_old_kernels(bool old) { g_old_kernels = old; } bool iq_old_kernels() { return g_old_kernels; } bool iq_supported(int t) noexcept { return is_iq(t); } -bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30; } +// BF16 and Q6_K: embedding only (dq_dispatch has them; no expert or prompt-path kernels take them) +bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30 || t == 14; } size_t iq_row_bytes(int t, int64_t n) noexcept { switch (t) { @@ -2900,6 +3074,9 @@ size_t iq_row_bytes(int t, int64_t n) noexcept { case 40: return (size_t) (n / 64) * sizeof(block_nvfp4); case 8: return (size_t) (n / 32) * sizeof(block_q8_0); case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32) + case 144: return (size_t) (n / 128) * sizeof(block_tq2_t); // APR trellis types + case 145: return (size_t) (n / 128) * sizeof(block_tqk6); + case 146: return (size_t) (n / 128) * sizeof(block_tqk7); default: return 0; } } @@ -2966,9 +3143,67 @@ void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, in check("iq_dequant_gu_f16"); } +// A bad block is a pack or caller error (expert_layout_load already refuses a block that does not divide the expert +// widths): it exits with a message, like check() does for a failed launch. +namespace { +void hadamard_bad_block(const char* what, int block, int64_t width) { + std::fprintf(stderr, "%s: Hadamard block %d is not a power of two in [2, 1024] dividing the row width %lld " + "(hadamard.txt's block and the expert widths disagree)\n", what, block, (long long) width); + std::exit(1); +} +constexpr int64_t kHadamardMaxRows = 65535; // gridDim.y +bool hadamard_block_ok(int block, int64_t width) { + return block >= 2 && block <= 1024 && (block & (block - 1)) == 0 && width % block == 0; +} +} // namespace + +void hadamard_rows(const float* x, float* y, int64_t rows, int64_t width, int block, const float* signs, void* stream) { + if (rows <= 0) return; + if (!hadamard_block_ok(block, width)) hadamard_bad_block("hadamard_rows", block, width); + // gridDim.y is limited to 65535: a prompt chunk's T * K rows (16K tokens x 10 experts) go up in slices + for (int64_t r0 = 0; r0 < rows; r0 += kHadamardMaxRows) { + const int64_t n = std::min(kHadamardMaxRows, rows - r0); + hadamard_rows_kernel<<>>(x + r0 * width, y + r0 * width, width, signs, + 1.0f / std::sqrt((float) block)); + } + check("hadamard_rows"); +} + +void hadamard_rows_f16(uint16_t* x, int64_t rows, int64_t width, int block, const float* signs, void* stream) { + if (rows <= 0) return; + if (!hadamard_block_ok(block, width)) hadamard_bad_block("hadamard_rows_f16", block, width); + for (int64_t r0 = 0; r0 < rows; r0 += kHadamardMaxRows) { // gridDim.y <= 65535, as in hadamard_rows + const int64_t n = std::min(kHadamardMaxRows, rows - r0); + hadamard_rows_kernel<__half><<>>((const __half*) x + r0 * width, (__half*) x + r0 * width, + width, signs, 1.0f / std::sqrt((float) block)); + } + check("hadamard_rows_f16"); +} + +const float* hadamard_device_signs(const float* host, int width) { + if (host == nullptr || width <= 0) return nullptr; + static std::mutex mu; + static std::map, float*> table; // (device, host vector, width) + int dev = 0; + cudaGetDevice(&dev); + std::lock_guard lock(mu); + float*& d = table[std::make_tuple(dev, host, width)]; + if (d == nullptr) { + if (cudaMalloc((void**) &d, (size_t) width * sizeof(float)) != cudaSuccess || + cudaMemcpy(d, host, (size_t) width * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) { + std::fprintf(stderr, "hadamard_device_signs: %s\n", cudaGetErrorString(cudaGetLastError())); + std::exit(1); + } + } + return d; +} + bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept { const int qg = gu_qk(gu_type), qd = d_qk(d_type); - return qg > 0 && qd > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 && + // a type without row bytes would make every row (and the up/down offsets) 0: refused, not run wrong + return qg > 0 && qd > 0 && iq_row_bytes(gu_type, n_embd) > 0 && iq_row_bytes(d_type, n_ff) > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 && n_embd % 256 == 0 && (n_ff * n_embd) % 256 == 0; } @@ -3709,7 +3944,8 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long } const bool v1 = g_grouped_v1; const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups; - const int gu_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_embd == 2560 && gu_split(L.gu_type)) ? 16 : GU_ROWS; + const int gu_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_embd == 2560 && gu_split(L.gu_type) && + gu_qk(L.gu_type) != 128) ? 16 : GU_ROWS; // qk 128 (APR trellis): no sub-16 rows, see launch_gu const dim3 ggu((unsigned) ((2 * L.n_ff + gu_rows - 1) / gu_rows), (unsigned) gy); #if STRATA_EXP_LAYOUTS #if defined(STRATA_HIP_GFX906) @@ -3788,8 +4024,11 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long #else const bool sw_v1 = v1; #endif - if (sw_v1) { + // APR: Hadamard-folded down weights take the rotated h, so h exists as floats first (the separate passes) + if (sw_v1 || L.had_block > 0) { swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh); + if (L.had_block > 0) // APR: the down weights are Hadamard-folded, so is their input (in place, every entry row) + hadamard_rows(h, h, cap_entries, L.n_ff, L.had_block, L.d_signs, s); quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh); } else { swiglu_q8_1_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, grp_start, n_groups, diff --git a/src/kernels/cuda/tq_lut_i8.cuh b/src/kernels/cuda/tq_lut_i8.cuh new file mode 100644 index 00000000..ee4fd609 --- /dev/null +++ b/src/kernels/cuda/tq_lut_i8.cuh @@ -0,0 +1,137 @@ +#pragma once +// int8 copy of the TQ codebook tq2t_lut_f16 (2048 2-D points): point i = (lo byte, hi byte) as int8, +// value ~= TQ_LUT_I8_SCALE * int8. One global scale (max |point| = 3.984375 -> 127); relative RMS error +// 0.0085 of the codebook std, far below the trellis quantization error. +// Generated from ggml-common.h (the tq2t codebook). +#include +#define TQ_LUT_I8_SCALE (3.984375f/127.0f) +alignas(16) static const __device__ uint16_t tq_lut_i8[2048] = { + 0xecd6, 0x27f2, 0x76d3, 0xed2e, 0xf815, 0x2e1f, 0x25eb, 0x1bdb, 0xed27, 0x30e3, 0xe41a, 0x2dd5, 0x1ec7, 0x0df8, 0xfef8, 0x0b4f, + 0x16bb, 0x16cf, 0xe9eb, 0x2415, 0xd155, 0xd8f5, 0x41f8, 0x361e, 0x41f3, 0xcf1c, 0xf72d, 0xedee, 0x13f6, 0x0906, 0x1208, 0x13e7, + 0x1dd9, 0x2a07, 0x263a, 0xea05, 0x160e, 0xf2f2, 0xd3cc, 0xd0da, 0x430d, 0x35f6, 0x1623, 0xd5f3, 0x0b36, 0xe158, 0xfa04, 0x06ef, + 0xe0f5, 0xfc27, 0x3b14, 0xf91e, 0xf3fb, 0x0701, 0xebe2, 0xff0a, 0x0fbc, 0x2406, 0x2303, 0x0304, 0xd502, 0x320f, 0x27ec, 0x13da, + 0xd206, 0xd80e, 0x13ca, 0x11eb, 0x0408, 0x0d0f, 0x3a04, 0xcb19, 0xdd20, 0xd9e3, 0x24ff, 0xed12, 0x0803, 0xf20d, 0xede2, 0x15eb, + 0x1615, 0xf51c, 0x95fd, 0xe80a, 0xf208, 0xfa11, 0xfcee, 0xdd19, 0x0b18, 0x0747, 0xfb12, 0xfcfb, 0xf4fe, 0x2a20, 0xf5fa, 0xe0f8, + 0x3a29, 0x13dd, 0xf2ed, 0xd103, 0x01cb, 0xe322, 0x031e, 0xfa6f, 0x07f5, 0xd312, 0x0b03, 0x11ed, 0xf318, 0xd537, 0xd60c, 0x1019, + 0x0414, 0x1010, 0xdf00, 0x0c01, 0xef03, 0x12ef, 0x2520, 0x0fac, 0x38f8, 0x23c0, 0x1bd3, 0x00fb, 0xf3e9, 0xf711, 0xff19, 0xe8da, + 0x21d8, 0x0a04, 0xd2dd, 0xd1e1, 0xebf7, 0xd3f5, 0xd20a, 0x3d1f, 0x1f18, 0x02f3, 0x1b40, 0x0c2a, 0xf405, 0xe2d7, 0x26fb, 0xf918, + 0x2af6, 0x01fa, 0xcc11, 0xf0dc, 0xfb06, 0x05e1, 0x10db, 0x0310, 0x559c, 0x19d9, 0xd22d, 0x22fa, 0xc041, 0xfb1f, 0x10d6, 0xffeb, + 0x2823, 0x680b, 0xdbe9, 0x0bea, 0xfce8, 0xe00c, 0x16f3, 0x0123, 0xf3fd, 0x2eee, 0xf40c, 0x070d, 0x1b15, 0xf5e4, 0xff38, 0x2227, + 0xfa4b, 0xe7e6, 0x2ad1, 0x2010, 0xd9d4, 0x0de7, 0xcff0, 0xd4e7, 0x091e, 0xf0a4, 0x0f09, 0x00f7, 0x09ea, 0xeaf8, 0x0614, 0x30ff, + 0x2f01, 0xd215, 0xf8f1, 0xf5e8, 0xb1ed, 0x0fd4, 0x360d, 0x22d0, 0x0e1b, 0x4709, 0x03d3, 0x261b, 0xff0e, 0xdbdb, 0xf600, 0x060a, + 0xfb43, 0x08e5, 0xda2f, 0xdddd, 0x1b39, 0x1812, 0x272d, 0xccee, 0xf120, 0xe4ef, 0xe60e, 0x0af4, 0xc60a, 0xd8ec, 0x0ff5, 0xd8ef, + 0x16c8, 0x2b37, 0x1fe3, 0xf0c4, 0x1545, 0x04fc, 0xf3dc, 0x020a, 0xe021, 0x06c2, 0xf21a, 0xd3eb, 0x221b, 0x0f12, 0x312e, 0x01f0, + 0xccff, 0xf1f4, 0xdb13, 0xeb19, 0x0ad1, 0xf51e, 0x0416, 0x00fd, 0x1ff0, 0x0318, 0xe3e3, 0xfbd3, 0xe510, 0x040f, 0xe5d4, 0x092b, + 0xe728, 0xecfd, 0xf2d0, 0xf6bb, 0x040c, 0x17ed, 0x34ed, 0x134d, 0xfee6, 0xfaf3, 0xf4b5, 0x2811, 0x0006, 0xe208, 0xefe6, 0x3511, + 0xeeaf, 0x03d0, 0xed00, 0x0cf6, 0xfc11, 0x09dc, 0x052b, 0x0eb5, 0x40fc, 0x3525, 0xf4d6, 0x2f28, 0x0639, 0x05eb, 0x03f0, 0xf3f9, + 0x0af1, 0x9be8, 0x24df, 0x0ccb, 0x49af, 0xc705, 0x06d0, 0x04f4, 0x0b23, 0x0507, 0x9b21, 0xe125, 0x0109, 0x520f, 0x0605, 0xfd03, + 0xc2e1, 0xcdfb, 0xe3fb, 0xc828, 0x18d2, 0x0141, 0x16f1, 0xbae1, 0x01e5, 0x2ff3, 0xfed7, 0x2f58, 0x2c31, 0xfefc, 0xf613, 0x88eb, + 0x28c9, 0xfafe, 0xcb03, 0xe1cf, 0x1ac5, 0x2ce0, 0x0bf6, 0xbe11, 0xf0ec, 0x1e07, 0x1bf2, 0xf413, 0x25f8, 0x3900, 0x02ee, 0x15f9, + 0x3ad2, 0x17df, 0x04de, 0xecf8, 0x24b9, 0xf8f3, 0xf229, 0xf310, 0xcaf9, 0x07e7, 0xf01b, 0xcef8, 0x4aea, 0xe7f4, 0xf41c, 0x15d4, + 0x03e7, 0xede4, 0xfd02, 0x12d4, 0xbffe, 0x230d, 0xe504, 0xf914, 0xc307, 0xfffe, 0x13fc, 0x0a28, 0xfd1d, 0xfa54, 0xe7f9, 0x1802, + 0xef47, 0xf7e9, 0xe800, 0xd6f9, 0x04e5, 0x3409, 0xf300, 0xd806, 0xddef, 0x3b9f, 0xcc2d, 0x0715, 0xeb00, 0x0f35, 0x14fd, 0x2bf0, + 0x0817, 0x5ec1, 0xf737, 0xeee9, 0xb30d, 0x46f5, 0x23e6, 0x1beb, 0xf031, 0xfb0b, 0x22ed, 0xfc00, 0x0519, 0xeb02, 0x3be1, 0x30ed, + 0xb9f9, 0xda4f, 0x1c09, 0xd814, 0x12df, 0xd83c, 0xfc08, 0xee24, 0xec0d, 0x0cef, 0xde0d, 0x18f3, 0x24f9, 0xf104, 0x0b07, 0x1529, + 0xc314, 0x2fc0, 0xfc19, 0x2ccd, 0xd090, 0x29fb, 0xf111, 0x1b4f, 0xbeed, 0x31ea, 0xd1e5, 0xf0d6, 0xcff4, 0xfeec, 0x1040, 0x6e2a, + 0xfaf9, 0xfebd, 0xb9d7, 0x0ef2, 0x06e5, 0xf015, 0x0617, 0xf7d8, 0x2310, 0xe414, 0x121d, 0xff02, 0xf71d, 0x269c, 0x1bfa, 0xcc0e, + 0x0a63, 0x1f1b, 0x0f1f, 0x27da, 0x411b, 0xc21a, 0xe9f0, 0xc8c4, 0xfff2, 0xf420, 0xf036, 0xdb0a, 0x13e5, 0xebf4, 0x3930, 0x04f0, + 0xdbfe, 0x2ce4, 0xd6db, 0xe0e3, 0xe91a, 0xfd0f, 0xc8ea, 0xddd0, 0x0be8, 0x0ee4, 0xf822, 0x23ee, 0x3319, 0xed1a, 0x090a, 0x234c, + 0xdecc, 0x00e7, 0xf2ea, 0xe011, 0x18f7, 0xb05a, 0x0324, 0x1bde, 0x190e, 0x0ef4, 0x21e9, 0xfbe1, 0x07fa, 0x2116, 0xf511, 0x2927, + 0x3dea, 0xfb30, 0x1125, 0xfd09, 0x1a1e, 0x07e3, 0x1b0a, 0xe8f2, 0x0eda, 0x0cee, 0x1ad0, 0x0f1d, 0x14f2, 0xf4f7, 0x0f06, 0x1215, + 0x02f1, 0xefe0, 0xe215, 0x12f2, 0x0212, 0x0cfe, 0x1be9, 0xedf4, 0x3fba, 0xef1e, 0x1eec, 0xf1fc, 0x21e4, 0x16f6, 0xb3e5, 0xd1f7, + 0xbfe7, 0xdb10, 0x1bf8, 0x3202, 0xed1e, 0x1a13, 0xf225, 0x10e4, 0xfbe6, 0xfb15, 0xef11, 0x0c17, 0x021c, 0x1e0f, 0x10ff, 0x5df0, + 0x1b04, 0xffdb, 0x0ec7, 0x09ef, 0xd5f7, 0xf6fd, 0xe5ed, 0xd5ff, 0x2633, 0x0800, 0x21fe, 0x00e9, 0xf416, 0xedf1, 0x0401, 0x01d6, + 0xe520, 0x0cf1, 0xf60e, 0xfbef, 0xb5cc, 0x31f1, 0x31fc, 0x1ddf, 0x06a9, 0x0c0d, 0xf2f7, 0xf81a, 0x4604, 0xd6ed, 0x171e, 0xfdcb, + 0xfb1c, 0x0dfc, 0xe5d1, 0xd50f, 0x26dd, 0x030b, 0xe82b, 0xfeea, 0xf9c5, 0xab0b, 0x0707, 0xf1e8, 0x1022, 0x0720, 0xdf1e, 0xd71d, + 0x17e9, 0xe506, 0x0cfa, 0xfd14, 0xf2ef, 0xe1e6, 0x0e08, 0xabfc, 0xf11c, 0xdef7, 0xf5c4, 0xdb24, 0x23da, 0xfb17, 0xf50f, 0xdaf4, + 0x381b, 0x0abf, 0xf312, 0x07eb, 0xd2ef, 0x5118, 0x00d9, 0x0210, 0xfffa, 0x2df7, 0xf6ed, 0xf30e, 0x0efa, 0x0ffe, 0xdc2c, 0xeae8, + 0x0723, 0xfca7, 0xd4d7, 0x311d, 0xf3e6, 0x0a02, 0x01f9, 0xc24e, 0xf4f0, 0x1a26, 0xfa08, 0x0e21, 0x4aff, 0x22f0, 0x0532, 0xe8e9, + 0xe624, 0xfd16, 0xe7c1, 0x2c09, 0xc3f5, 0x06ed, 0x091c, 0xf52a, 0x022d, 0x2b17, 0x1bf6, 0x1ffd, 0x00d2, 0x11e9, 0xb1dd, 0x1631, + 0xff2e, 0xbfc7, 0x17eb, 0x3e0c, 0x2af8, 0x20db, 0x07d6, 0x0a3b, 0x1132, 0xef08, 0x000f, 0x10f3, 0x38b0, 0x13eb, 0x1ff7, 0xe706, + 0x12c6, 0x0bc4, 0xdeed, 0x48d4, 0xfbf3, 0xe5fe, 0xeb21, 0x19ec, 0x38f4, 0xe512, 0x36bc, 0xe6f2, 0xfbea, 0xf702, 0x2fe7, 0x1bcd, + 0x12f7, 0x232b, 0x23f6, 0xf0cd, 0x0230, 0xde31, 0xf20b, 0x2dc7, 0x06d9, 0x03f8, 0xeefe, 0xf407, 0xf50a, 0x17e6, 0xc7f2, 0x03d9, + 0x4134, 0xe3eb, 0x0309, 0x1c47, 0xea1e, 0xd921, 0x2135, 0x14d1, 0x3214, 0x30df, 0xe80f, 0xed07, 0x0931, 0x0ae6, 0x29e5, 0xcdea, + 0xa204, 0xd0d0, 0x04f2, 0xcd24, 0x2e0b, 0xf4f5, 0xf6f8, 0xf9fa, 0x16f8, 0x28d6, 0x1c17, 0xd701, 0x2bd9, 0xf4ee, 0xf60c, 0x0bf7, + 0x1313, 0x17ef, 0x1fff, 0x24fc, 0x0302, 0xf8e3, 0xe102, 0xd725, 0xe229, 0xd0ec, 0x2b11, 0xb2f5, 0x0923, 0x01ea, 0x11d1, 0x3938, + 0x21f7, 0xc9fd, 0x0119, 0xf0fe, 0xf646, 0xfa23, 0xe50b, 0xe206, 0x2f12, 0xf109, 0xe81f, 0x00f1, 0xec0f, 0x26d3, 0x1127, 0x0404, + 0x0afe, 0x43e9, 0xdc03, 0xc9f5, 0x0b09, 0x1e0a, 0x070b, 0x1835, 0xed40, 0x0b2e, 0xe20b, 0x100b, 0xdee6, 0x08fb, 0x2200, 0x19d5, + 0xe8b4, 0xd745, 0xee21, 0x0e13, 0x0201, 0x0d1d, 0xbe0a, 0x45cb, 0xffde, 0xc932, 0xe3fe, 0x4df2, 0x0ff8, 0xe4f7, 0x0825, 0x1be6, + 0x14df, 0xb5c0, 0xefee, 0x0113, 0x46ef, 0x65fc, 0x231e, 0x20e6, 0xe6fb, 0xf42d, 0x2fd1, 0x1407, 0x4b0d, 0xe40e, 0xe2fc, 0xa1f7, + 0x493b, 0xfd2d, 0x0015, 0x4add, 0x19f9, 0x1104, 0xf305, 0x8111, 0xfff0, 0x04dc, 0xca0a, 0x2706, 0xfd3d, 0xf12d, 0x11f5, 0x1111, + 0x04d7, 0xf9e8, 0xf2d3, 0x1bee, 0xcf0c, 0x0c11, 0x2501, 0xd521, 0x0b05, 0x1c1c, 0x36e4, 0x23c6, 0x0f2a, 0xd6c6, 0x1520, 0x2009, + 0xe409, 0xe6c6, 0xeb64, 0xb61c, 0x07f2, 0x05f5, 0xed0b, 0x2daa, 0x24f1, 0xf7eb, 0x2103, 0x03fd, 0xe6dd, 0xfbce, 0x33db, 0x3f25, + 0xe1c4, 0x3fee, 0x4c1f, 0xe31f, 0x26ee, 0xfae4, 0x1419, 0x27fd, 0xd4d3, 0xd3fc, 0xec2b, 0xd514, 0x03f6, 0xcf33, 0x0d09, 0xf2e4, + 0xc30e, 0x09fc, 0x10fa, 0x08e9, 0x3716, 0xf2f4, 0x1302, 0x000d, 0x2add, 0xf1f1, 0xecec, 0x0c1f, 0xd5b9, 0x16d9, 0x28e0, 0x0107, + 0x52d8, 0xf0c9, 0x35f1, 0x0af2, 0x2508, 0xe4f2, 0xdfd9, 0x1435, 0x1fe9, 0x0e15, 0x16e1, 0x3f40, 0xea3a, 0xcf17, 0xf9f7, 0x051b, + 0x4cf9, 0x1e21, 0x1718, 0x5128, 0xe20d, 0x1924, 0x20f5, 0x1b29, 0xef85, 0x0d03, 0xd4f9, 0x2cfa, 0x25d7, 0x090f, 0xf525, 0x4d07, + 0x4201, 0xff03, 0xed14, 0x2007, 0xe3dd, 0xdfe0, 0x010f, 0x2ff6, 0x3601, 0xd2f2, 0xe426, 0x0329, 0xc2bc, 0x0ec2, 0xfd07, 0x29bc, + 0x023b, 0x1c0f, 0xbd05, 0x1311, 0xfe21, 0xe9e1, 0x1503, 0x4b14, 0x0011, 0xe804, 0x1a0c, 0x1217, 0x38e9, 0xdac0, 0x15e6, 0xfef4, + 0x0a00, 0xe3f8, 0xf1e1, 0x08e1, 0xf3bf, 0x08ff, 0x2db5, 0xf2ff, 0xd9e9, 0xf804, 0x040a, 0xc127, 0x098e, 0xd224, 0x180f, 0xfe15, + 0xd61a, 0xf698, 0xc302, 0xebdb, 0x06e9, 0x12fe, 0x0804, 0xec32, 0x05e7, 0xbd18, 0xf71b, 0xf106, 0xc6af, 0xfcfc, 0x0321, 0xdd1c, + 0x14f4, 0x3cf1, 0xc71c, 0x2787, 0x0125, 0xd00f, 0xb926, 0xaa39, 0x0a20, 0x28f6, 0x04bd, 0x11f9, 0xdba4, 0x3708, 0xfe00, 0xf123, + 0xe9f5, 0x02e8, 0xfe11, 0x59fe, 0x1409, 0x21a7, 0xf102, 0xcc15, 0xd6fc, 0x1b2d, 0x23eb, 0x0528, 0xdd10, 0xef05, 0x290f, 0x435d, + 0x20f9, 0xde05, 0xedfa, 0x2a45, 0x0120, 0xa8f0, 0x052e, 0xd6ea, 0xeb07, 0xd013, 0xb90d, 0xdd08, 0xb714, 0x1425, 0x95cf, 0xf810, + 0x1dfe, 0x01ec, 0xd30d, 0x39ee, 0xaf04, 0x18f1, 0x1d05, 0x05f9, 0x1706, 0x040d, 0xe014, 0x08ee, 0x20ee, 0xe711, 0x041d, 0x127a, + 0xfb0d, 0xecf0, 0xd1e9, 0x64e2, 0x090e, 0xa71e, 0x0610, 0x4512, 0x2be7, 0x0de9, 0x1016, 0x10ec, 0x0e0d, 0xf82a, 0x26e5, 0xfdd1, + 0xfb02, 0x12e1, 0xcae5, 0x2b0c, 0x250b, 0x2aea, 0x260f, 0x412c, 0x140f, 0x051f, 0xfafb, 0x1a08, 0xf216, 0x0b13, 0xeccc, 0xcea2, + 0xcccc, 0xeb16, 0xfa1a, 0x0a0d, 0xdaf1, 0xf5fc, 0xe8ca, 0x4fe3, 0xb347, 0xc661, 0x0a08, 0xf60f, 0xf7f6, 0x1d35, 0xffe8, 0xe90d, + 0x08f9, 0x203b, 0xef19, 0x30d8, 0xdcb9, 0xe00e, 0x0d01, 0x010c, 0xe8f7, 0x19ee, 0xd704, 0x120f, 0xee1c, 0xff21, 0x00ee, 0xfcf9, + 0xfc0f, 0xfbb7, 0x5d08, 0x09f1, 0xe62f, 0xeafc, 0x0e3a, 0x6ceb, 0xf5dd, 0x0b1d, 0x2cf4, 0x01ff, 0xfe1b, 0x26ce, 0xe6ef, 0x0aee, + 0xea2f, 0x16a5, 0xa72a, 0x33f9, 0xd8f2, 0xe6aa, 0x2f17, 0xf5c8, 0xece7, 0x0c1b, 0xe9fb, 0x19e7, 0xfac9, 0xe59a, 0x1829, 0x1401, + 0x22f4, 0xe0fe, 0x0fe9, 0xf408, 0xd6e0, 0x1102, 0x19ea, 0xead8, 0x19c0, 0xfd0d, 0x7714, 0x1357, 0x2e1a, 0xeef8, 0xfb35, 0x2205, + 0x1dea, 0x2cfc, 0x09f5, 0xf43b, 0x1219, 0xddfc, 0xea11, 0xf8ed, 0x0feb, 0xe84e, 0x4719, 0xdff1, 0xfddd, 0xe818, 0x323a, 0xde28, + 0x34ea, 0xf118, 0xdd0b, 0xe61a, 0xd507, 0xe925, 0x06d4, 0xd9d8, 0xe6f7, 0xe0dc, 0xea0e, 0xccf6, 0xfad9, 0x1f05, 0xe538, 0xc21f, + 0xc4fd, 0x02fc, 0x9432, 0x51cc, 0xda1d, 0xd72c, 0x0f0e, 0x1916, 0xda03, 0x2628, 0x390b, 0xfb5f, 0x33e6, 0x31f8, 0x0336, 0xdcfa, + 0xbd20, 0xe4da, 0x2213, 0x201e, 0x0117, 0xebd1, 0x0e46, 0xfdf0, 0xc813, 0x100c, 0x2902, 0x10e8, 0x1006, 0x16e4, 0xf5ea, 0x0df0, + 0x1dee, 0x0911, 0xf41a, 0x1ebd, 0x001e, 0xd1fe, 0x0b40, 0x08fd, 0x22d4, 0x1d1e, 0x12e3, 0xe81c, 0x3c08, 0x000a, 0xff1d, 0x2424, + 0xef27, 0x1417, 0xe417, 0xfaec, 0xe21c, 0x571f, 0x060e, 0xdcf8, 0x15e8, 0xe617, 0x58e3, 0x07f4, 0xe1e9, 0x270c, 0xdaf6, 0xfe31, + 0xe902, 0x0522, 0x080a, 0xf6d0, 0x1cf4, 0x0ed7, 0x0e24, 0xed18, 0x693e, 0xc70f, 0x2517, 0xf83e, 0xe2ee, 0xf916, 0xf4d9, 0xf813, + 0x4827, 0xeff2, 0xd21a, 0xf909, 0x031a, 0xf434, 0x33cb, 0x17fb, 0xe7ff, 0xd020, 0xff17, 0xd531, 0x5c2c, 0xca07, 0xdefa, 0xeaf2, + 0x2d06, 0x1a11, 0x2914, 0xcf01, 0xe9cf, 0xe1f0, 0x0be1, 0xafd4, 0xfdf4, 0xefb9, 0xf7ae, 0xf113, 0x1be4, 0x1008, 0x1900, 0x1af6, + 0x34e1, 0xdcf2, 0x4949, 0x08cd, 0x172d, 0x0047, 0x22fc, 0xe036, 0x2715, 0x3543, 0xf920, 0xfadc, 0x2c03, 0xe2c9, 0xe213, 0xfbdf, + 0xf9ef, 0x35fb, 0x1ddc, 0x04e3, 0x0ef7, 0x13ce, 0xfeee, 0xe51d, 0x071b, 0x0da0, 0x0e0b, 0x034e, 0xfbf5, 0xcee6, 0xfcff, 0x03fa, + 0x3fc4, 0x14ef, 0x07de, 0xf30a, 0x09f7, 0xf00e, 0xf733, 0x060c, 0x0813, 0xea14, 0x5b14, 0xfaf1, 0x140d, 0xffb0, 0xd9cb, 0xeedd, + 0xef3b, 0x122b, 0xfdfe, 0xd901, 0xef13, 0xb9e9, 0xf71f, 0x1797, 0x5407, 0x131b, 0x1de5, 0xf61a, 0x2b2b, 0xeff5, 0x0102, 0xd80b, + 0xf70a, 0xf4cc, 0xfd17, 0xfef6, 0x090c, 0x150a, 0x04ec, 0x0ce5, 0x2512, 0x130c, 0xd8f8, 0x04ee, 0x0ddc, 0x0612, 0xe601, 0x0603, + 0x29f1, 0xcf4a, 0xf4e2, 0x22e1, 0xe2f4, 0x2001, 0x02c2, 0xf80b, 0x11fc, 0x05f3, 0xfa28, 0xf518, 0x38d8, 0x0c08, 0x3008, 0x3bcb, + 0xff05, 0xf906, 0x0600, 0x24b1, 0xec09, 0x1113, 0x001b, 0x02b7, 0xfec7, 0x0eef, 0x09b9, 0x161a, 0x17cc, 0xbef4, 0xe7e3, 0x1904, + 0xe3e7, 0x29f4, 0x1c0c, 0x1b20, 0x1af0, 0x15fb, 0xedf6, 0x0cd4, 0xfc04, 0x14b5, 0xe714, 0xe049, 0x0ceb, 0xb49e, 0xe5e5, 0x00f8, + 0xc6dc, 0xdc00, 0xeeeb, 0xff08, 0x0658, 0x0af9, 0xee15, 0xe52b, 0xff23, 0x09d3, 0x16c4, 0x160c, 0xe834, 0xbed0, 0x06dc, 0x29e2, + 0xdbeb, 0xc3f0, 0xfa0b, 0x08f7, 0xe4e9, 0x0ffc, 0x20fb, 0x2efe, 0x06f6, 0xeafe, 0x1a1a, 0x2d6a, 0x3305, 0x030f, 0x0307, 0xf1e5, + 0x07f0, 0xe22e, 0xcf28, 0xd8cf, 0xcad8, 0x0de2, 0x4015, 0x0e10, 0x1e30, 0xf902, 0xbd2e, 0xf9bf, 0x1808, 0xee0d, 0xfee2, 0xd428, + 0xeefc, 0xe1bf, 0xf9e1, 0x2bed, 0x03e1, 0x14ed, 0x1af4, 0xb706, 0x3c18, 0x0e05, 0x9612, 0xfbf7, 0x3cf6, 0xfa00, 0x0ce3, 0xe70b, + 0x00ce, 0xd5f0, 0xf303, 0xae16, 0x0f02, 0xccf2, 0x2342, 0x09e8, 0xebea, 0xefea, 0xc5e6, 0xf0f6, 0xf24e, 0x2600, 0x1a02, 0xc337, + 0x19fb, 0xe009, 0x063f, 0x002b, 0xf000, 0x071d, 0x0d31, 0xe02c, 0xda28, 0xf40d, 0xee0f, 0x24f3, 0xe8f0, 0xfd0b, 0x04cd, 0x04e9, + 0x29fd, 0xf8fe, 0x54f7, 0xf622, 0x0bfc, 0xe0f3, 0x1fe1, 0x2818, 0x0b0e, 0x18dd, 0xf323, 0x1322, 0xfd05, 0xe9d4, 0x0efe, 0x029e, + 0xf7db, 0x1239, 0xf4f3, 0x1d00, 0xfdf2, 0xfe26, 0xd517, 0xe400, 0x101b, 0xe0ef, 0xb8b2, 0x1611, 0xf925, 0x0e00, 0xe946, 0x0625, + 0x0811, 0x0d12, 0x2df1, 0xf9f5, 0xf6e6, 0x07c6, 0xec10, 0xc42d, 0x0fde, 0xfde0, 0x2c24, 0x1819, 0x42dd, 0x3321, 0xfcda, 0x06fc, + 0xc7ee, 0xfce4, 0x0919, 0xdefe, 0x2c3f, 0xc717, 0xfdc2, 0xeff0, 0x0ff1, 0xf314, 0x15dc, 0xeb0b, 0xd9de, 0x09e3, 0x0028, 0x0502, + 0xdef4, 0x0719, 0x1303, 0x22dd, 0xe9e5, 0x14e3, 0xecc6, 0xfa0f, 0x0df5, 0x181c, 0x19e2, 0x03c7, 0x10f7, 0xd23e, 0x3f10, 0xf608, + 0xca42, 0xfb2a, 0x13e9, 0x0cf3, 0x1bd7, 0x173a, 0xecdf, 0xf10f, 0xdafc, 0x12f4, 0x13f0, 0xf9fc, 0xe5f9, 0xeaee, 0xc5cc, 0x26f5, + 0xb8f1, 0x0412, 0xe478, 0x0106, 0xf8de, 0x1ed6, 0xf240, 0x3a4d, 0x151d, 0x5a52, 0x1a30, 0xf6f2, 0xdd15, 0x0e27, 0xf0f8, 0x0d06, + 0x1814, 0x13f9, 0xf616, 0xdffc, 0xff0c, 0x163f, 0xb22e, 0x1100, 0x1b00, 0xda07, 0xeed9, 0x5fd5, 0xd8e6, 0xa9e5, 0xf4df, 0xdbe5, + 0xe2b8, 0x563b, 0xcb20, 0x3923, 0x50ff, 0xcfc7, 0x17db, 0xe0ec, 0x17f9, 0x641c, 0xfdf6, 0x0a0b, 0x1405, 0xa7c9, 0x11e6, 0xec24, + 0xf724, 0x2208, 0x0fe6, 0x00f5, 0x40d4, 0x3f04, 0x1f2b, 0x102e, 0x09df, 0xee2a, 0x1120, 0xe916, 0xf1d9, 0xfc1b, 0x06f2, 0x1604, + 0x2b00, 0x1f0c, 0xe310, 0xf9ea, 0x1bb6, 0x4b30, 0x08d9, 0xee09, 0x0b25, 0xfed4, 0xffe4, 0xfb09, 0xf705, 0xe200, 0xf730, 0x4421, + 0x1609, 0xecf2, 0x13d7, 0x4bc0, 0xe342, 0x3234, 0xf21e, 0x1e03, 0xfd12, 0x1b06, 0xea28, 0x0a15, 0xe104, 0x10d9, 0xdf02, 0x142e, + 0xe2f6, 0x12fb, 0xef17, 0xf9d6, 0xe6eb, 0x0d2d, 0x2efa, 0x0d19, 0x271d, 0xcffe, 0x1ed3, 0x0c0b, 0x0728, 0x03ea, 0x0eed, 0x1cf0, + 0xd2c0, 0xedc0, 0x072e, 0x09f3, 0x0808, 0xb3fe, 0x280a, 0x180d, 0x03ff, 0x1df6, 0x10e2, 0xf7fb, 0xfefa, 0x23cb, 0xdeea, 0x1ecf, + 0xc4d5, 0x14f7, 0x07b2, 0x0508, 0x46e4, 0xcfd5, 0xdd12, 0xe007, 0x2f04, 0xf800, 0x1906, 0xe5cd, 0x26e2, 0x35d0, 0xdc05, 0x210e, + 0xcde2, 0x05fd, 0x01f7, 0xe922, 0xdf17, 0x2d14, 0xdb0d, 0xf727, 0x40e4, 0x0c15, 0xddd6, 0xd817, 0x9652, 0x10cb, 0x08ec, 0x19e5, + 0x45fb, 0x3023, 0x18f5, 0xe6e8, 0x0000, 0x22f2, 0xd809, 0xf6f6, 0x020d, 0xd1fb, 0x2deb, 0xf6e0, 0xe304, 0xd3af, 0xa312, 0xeed3, + 0x0bde, 0x3cfb, 0xb838, 0xdbe0, 0x02e3, 0xe4fc, 0xf6f4, 0x0e17, 0x15ff, 0x0bec, 0xe0d3, 0xf718, 0x3a0f, 0x120b, 0x0c04, 0xdb16, + 0x29ff, 0x20de, 0x2024, 0xa3da, 0x2221, 0xf2fa, 0x180b, 0xe2e0, 0xce05, 0x1a18, 0x0008, 0x02de, 0x1965, 0xe73e, 0x15f5, 0xfd23, + 0xfa2d, 0xe6d7, 0x320c, 0x32f4, 0x0709, 0x0bdb, 0x24e8, 0x14e1, 0xcc39, 0xf7cc, 0x0ad6, 0xce09, 0x2edc, 0xc801, 0x23e4, 0xe609, + 0x20eb, 0xe5f4, 0x34fe, 0xe9bb, 0xeed0, 0xe9de, 0xfc25, 0xf80d, 0x06fe, 0xf912, 0x1ef4, 0xed05, 0xfc21, 0x2a1b, 0x28e7, 0xeb12, + 0xea09, 0x1e15, 0x1bfd, 0x1726, 0x1109, 0x05f7, 0xf514, 0x1ce2, 0xcddd, 0xf6d3, 0x0034, 0xf91b, 0x1de7, 0xf427, 0x1001, 0x35c5, + 0xe913, 0x0cff, 0xc0db, 0xdde3, 0x130a, 0x11f0, 0x33d5, 0xe119, 0x1c23, 0x3604, 0xc3eb, 0x1efb, 0x0215, 0x52ec, 0x27f0, 0x131f, + 0xe6e0, 0xfa39, 0xda1a, 0xebfa, 0x1004, 0x06ca, 0x16d7, 0x1415, 0x10ee, 0x0806, 0x13ff, 0xf7f9, 0x050b, 0xccba, 0x0fce, 0x1cfc, + 0xfa0d, 0x02f5, 0x19af, 0xf606, 0xddc6, 0x0104, 0xf501, 0xa4b7, 0xdbee, 0x1306, 0x06f8, 0x1c02, 0xc723, 0x1e12, 0x1821, 0x2e0e, + 0x2218, 0x28ee, 0xc9d2, 0xd201, 0x26e9, 0xe8fd, 0x1513, 0xe1fa, 0x05ff, 0x01dc, 0xfbfd, 0x070f, 0x4207, 0x28c3, 0x19fe, 0x2330, + 0x0ac9, 0x0ddf, 0xeb1c, 0x2013, 0x2158, 0x0fe0, 0x0b10, 0x220b, 0x13c0, 0xd31d, 0x02fe, 0x16ed, 0xe402, 0x1e27, 0x38fd, 0x27f9, + 0xee02, 0x3ae6, 0xe433, 0xc0f9, 0xdd41, 0xff13, 0x1d19, 0x2d4d, 0xee57, 0xd405, 0xf9e6, 0xec36, 0x05fa, 0xf430, 0x1fcc, 0xfe29, + 0xe3f2, 0x78fa, 0x0dd1, 0x120d, 0x0326, 0x0306, 0xd8fb, 0xd5e4, 0x2905, 0xd8fe, 0xc8e1, 0x1ec2, 0xddf6, 0x2604, 0xdeb0, 0x1df2, + 0xf614, 0x1c11, 0x0735, 0xd50a, 0xdc39, 0x0bd9, 0xc6f9, 0xd811, 0x1601, 0xf6ef, 0x0a17, 0x1aca, 0xb122, 0xfcd7, 0x0afa, 0xdf1b, + 0xf4ec, 0xefe3, 0xfceb, 0x342a, 0xf0fa, 0x0cce, 0x1607, 0xf603, 0x1ae0, 0xdaf9, 0xf807, 0x00e1, 0x37de, 0xfe1f, 0xf9d1, 0x3cdb, + 0xba00, 0xef0b, 0xe13b, 0x1df9, 0x00f3, 0xdb34, 0xe7ed, 0xd863, 0x3d00, 0x16fd, 0xe907, 0x1014, 0xde24, 0xf1de, 0x17ff, 0x20f2, +}; diff --git a/src/kernels/native_expert_parity.cpp b/src/kernels/native_expert_parity.cpp index 3c979ebb..bbd4a485 100644 --- a/src/kernels/native_expert_parity.cpp +++ b/src/kernels/native_expert_parity.cpp @@ -3,11 +3,14 @@ // build/native_expert_parity [layer ...] real rows (a split model's shards are found by name) // build/native_expert_parity --synthetic GU/DOWN ... random weights quantized by ggml (e.g. q4_K/q5_1) // build/native_expert_parity --q5_1-min the Q5_1 min term on crafted activations +// (the CPU-only checks of the trellis kernels, AVX2 / AVX-512 / scalar, are in tq_cpu_parity) // // (a) float reference: ggml's own dequantizer (`to_float`) and a float SwiGLU expert, (b) the CPU path // (ggml-cpu vec_dot with its quantized activations), (c) the GPU path (`native_expert_grouped`, q8_1 -// activations). (b) and (c) each differ from (a) by their activation rounding only (a few 1e-3 relative). (c) runs -// twice, with the kernels that decode a weight part once for all entries and with the per-entry ones: bitwise equal. +// activations). (b) and (c) each differ from (a) by their activation rounding (a few 1e-3 relative) and, for the +// trellis types on the GPU, by its int8 codebook (tq_lut_i8, see iq_kernels.cu "Numerics"); both must stay within +// relative L1 error 3e-2 of (a). (c) runs twice, with the kernels that decode a weight part once for all entries and +// with the per-entry ones: those two are bitwise equal to each other. // (d) the GPU dequantizers of the prompt path and the embedding against `to_float` (Q8_0: bit for bit). // The synthetic mode and (d) follow eddoursul/Strata 8029fa9. #include "strata/artifact/gguf_reader.hpp" @@ -17,8 +20,18 @@ #include "strata/kernels/cpu/iq_avx2.hpp" #include "strata/kernels/cpu/kq_avx2.hpp" #include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/hadamard.hpp" +#include "strata/kernels/cpu/tq_cpu.hpp" #include "ggml-cpu.h" #include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/core/native_dense.hpp" +#include "strata/core/expert_source.hpp" + +#include +#include +#include #include "ggml.h" @@ -73,13 +86,17 @@ int check_blob(const cpu::NativeFmt& f, const std::vector& blob, int se std::vector x((size_t) NT * H); for (auto& v : x) v = nd(rng); std::vector ref((size_t) NT * H), got_c((size_t) NT * H), got_g((size_t) NT * H); + // APR (--hadamard): the folded expert's reference takes H (s * x) and H (s * h), as llama.cpp's graph does + std::vector xr(x); + if (f.had_gu) for (int k = 0; k < NT; ++k) cpu::hadamard_rotate(xr.data() + k * H, (int) H, f.had_block, f.gu_signs); for (int k = 0; k < NT; ++k) { std::vector h(FF); for (int64_t r = 0; r < FF; ++r) { double g = 0, u = 0; - for (int64_t i = 0; i < H; ++i) { g += (double) G[r * H + i] * x[k * H + i]; u += (double) U[r * H + i] * x[k * H + i]; } + for (int64_t i = 0; i < H; ++i) { g += (double) G[r * H + i] * xr[k * H + i]; u += (double) U[r * H + i] * xr[k * H + i]; } h[r] = (float) (g / (1.0 + std::exp(-g)) * u); } + if (f.had_d) cpu::hadamard_rotate(h.data(), (int) FF, f.had_block, f.d_signs); for (int64_t r = 0; r < H; ++r) { double o = 0; for (int64_t i = 0; i < FF; ++i) o += (double) D[r * FF + i] * h[i]; @@ -183,6 +200,42 @@ int check_blob(const cpu::NativeFmt& f, const std::vector& blob, int se gu_diff, dn_diff); if (gu_diff || dn_diff) ++failures; } + // the trellis types (tq_cpu.hpp, which native_gu_rows / native_down_rows above used): every ISA this CPU has + // against the scalar kernel BIT FOR BIT, and against ggml-cpu's vec_dot (float summation order only) + for (int role = 0; role < 2; ++role) { + const int type = role == 0 ? f.gu_type : f.d_type; + if (!cpu::tq_supported(type)) continue; + const int n = role == 0 ? (int) H : (int) FF, rows = role == 0 ? (int) FF : (int) H; + const size_t rb = role == 0 ? f.gu_row : f.d_row; + const uint8_t* w = blob.data() + (role == 0 ? 0 : f.down_off); + const void* const* acts = role == 0 ? a : hp; + std::vector ref((size_t) NT * rows), got((size_t) NT * rows); + float* rp[NT]; + float* gp[NT]; + for (int k = 0; k < NT; ++k) { rp[k] = ref.data() + (size_t) k * rows; gp[k] = got.data() + (size_t) k * rows; } + cpu::tq_rows(cpu::TqIsa::scalar, type, w, rb, n, acts, NT, rp, 0, rows); + const auto* tc = ggml_get_type_traits_cpu((ggml_type) type); + double num = 0, den = 0; + for (int k = 0; k < NT; ++k) + for (int r = 0; r < rows; ++r) { + float v = 0; + tc->vec_dot(n, &v, 0, w + (size_t) r * rb, 0, acts[k], 0, 1); + num += std::pow((double) v - ref[(size_t) k * rows + r], 2); + den += (double) v * v; + } + const double rg = std::sqrt(num / (den + 1e-30)); + std::printf(" %s %s rows: scalar kernel vs ggml vec_dot rel %.2e", ggml_type_name((ggml_type) type), + role == 0 ? "gate" : "down", rg); + if (rg > 1e-5) ++failures; + for (cpu::TqIsa isa : {cpu::TqIsa::avx2, cpu::TqIsa::avx512}) { + if (!cpu::tq_isa_ok(isa)) continue; + cpu::tq_rows(isa, type, w, rb, n, acts, NT, gp, 0, rows); + const bool same = std::memcmp(got.data(), ref.data(), got.size() * sizeof(float)) == 0; + std::printf(" | %s %s", cpu::tq_isa_name(isa), same ? "bitwise equal" : "DIFFERENT"); + if (!same) ++failures; + } + std::printf("\n"); + } // UD-Q4_K_XL's formats: the multi-token AVX2 kernels (kq_avx2.cpp) against ggml-cpu's vec_dot per token, // BIT FOR BIT, for 1..8 tokens; then the time of 4 tokens (a verify window) both ways for (int role = 0; role < 2; ++role) { @@ -285,7 +338,8 @@ int check_blob(const cpu::NativeFmt& f, const std::vector& blob, int se } // (c) the GPU: one group holding the NT entries { - const auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, H, FF); + auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, H, FF); + if (f.had_d) { L.had_block = f.had_block; L.d_signs = strata::kernels::hadamard_device_signs(f.d_signs, (int) FF); } void *dblob, *dx, *dxq, *dscr; float* dout; unsigned long long* dptr; @@ -309,6 +363,32 @@ int check_blob(const cpu::NativeFmt& f, const std::vector& blob, int se cudaMemcpy(dn, &one, 4, cudaMemcpyHostToDevice); cudaMemcpy(ddst, idx, NT * 4, cudaMemcpyHostToDevice); cudaMemcpy(dtok, idx, NT * 4, cudaMemcpyHostToDevice); + if (f.had_gu) { // APR: the GPU rotation of x (in place here), then its floats against the CPU's + strata::kernels::hadamard_rows((const float*) dx, (float*) dx, NT, H, f.had_block, + strata::kernels::hadamard_device_signs(f.gu_signs, (int) H), s); + std::vector gx(x.size()); + cudaStreamSynchronize(s); + cudaMemcpy(gx.data(), dx, gx.size() * 4, cudaMemcpyDeviceToHost); + const bool same = std::memcmp(gx.data(), xr.data(), gx.size() * 4) == 0; + std::printf(" gpu hadamard_rows vs cpu hadamard_rotate: %s (rel %.2e)\n", + same ? "bitwise equal" : "differ", rel(gx, xr)); + if (!(rel(gx, xr) < 1e-6)) ++failures; + // the f16 form (prompt path) on the unrotated x: within fp16 rounding of the float rotation + std::vector xh(x.size()), xh_out(x.size()); + for (size_t i = 0; i < x.size(); ++i) xh[i] = ggml_fp32_to_fp16(x[i]); + uint16_t* dxh = nullptr; + cudaMalloc((void**) &dxh, xh.size() * 2); + cudaMemcpy(dxh, xh.data(), xh.size() * 2, cudaMemcpyHostToDevice); + strata::kernels::hadamard_rows_f16(dxh, NT, H, f.had_block, + strata::kernels::hadamard_device_signs(f.gu_signs, (int) H), s); + cudaStreamSynchronize(s); + cudaMemcpy(xh_out.data(), dxh, xh.size() * 2, cudaMemcpyDeviceToHost); + cudaFree(dxh); + std::vector xf(x.size()); + for (size_t i = 0; i < xf.size(); ++i) xf[i] = ggml_fp16_to_fp32(xh_out[i]); + std::printf(" gpu hadamard_rows_f16 vs cpu float rotation: rel %.2e\n", rel(xf, xr)); + if (!(rel(xf, xr) < 2e-3)) ++failures; + } strata::kernels::quantize_q8_1_rows((const float*) dx, NT, H, dxq, s); strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s); cudaStreamSynchronize(s); @@ -535,6 +615,157 @@ int check_bf16_embd(cudaStream_t s) { return failures; } +// APR: a GGUF's token_embd as the engine gathers it (iq_embed_rows, any embed_type_supported type: Gyro-S's Q6_K), +// `n` random rows against ggml's to_float, bit for bit; then iq_dequant_f32 of one row +int check_gguf_embd(const char* path, int n, cudaStream_t s) { + const strata::GgufModel model(strata::gguf_split_paths(path)); + size_t at = 0; + const strata::TensorInfo* t = model.find("token_embd.weight", &at); + if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) H) { std::printf("%s: no token_embd [2560, V]\n", path); return 1; } + const int type = (int) t->type; + const int64_t V = (int64_t) t->shape[1]; + if (!strata::kernels::embed_type_supported(type)) { std::printf("token_embd type %d: no GPU dequantizer\n", type); return 1; } + const size_t rb = strata::kernels::iq_row_bytes(type, H); + if (rb != ggml_row_size((ggml_type) type, H)) { std::printf("row bytes %zu != ggml %zu\n", rb, ggml_row_size((ggml_type) type, H)); return 1; } + const uint8_t* table = model.shard(at).tensor_data(*t); + std::mt19937 rng(17); + std::vector tok((size_t) n); + for (auto& v : tok) v = (int32_t) (rng() % (uint64_t) V); + tok[0] = 0; tok[(size_t) n - 1] = (int32_t) (V - 1); + // the rows the test reads, packed contiguously as a small table (the engine maps the whole one) + std::vector small((size_t) n * rb); + for (int i = 0; i < n; ++i) std::memcpy(small.data() + (size_t) i * rb, table + (size_t) tok[(size_t) i] * rb, rb); + std::vector idx((size_t) n); + for (int i = 0; i < n; ++i) idx[(size_t) i] = n - 1 - i; // gathered in reverse + void* dt = nullptr; int32_t* dtok = nullptr; float* dout = nullptr; + cudaMalloc(&dt, small.size()); + cudaMalloc((void**) &dtok, (size_t) n * 4); + cudaMalloc((void**) &dout, (size_t) n * H * 4); + cudaMemcpy(dt, small.data(), small.size(), cudaMemcpyHostToDevice); + cudaMemcpy(dtok, idx.data(), (size_t) n * 4, cudaMemcpyHostToDevice); + strata::kernels::iq_embed_rows(type, dt, rb, dtok, n, H, dout, s); + cudaStreamSynchronize(s); + std::vector got((size_t) n * H), want((size_t) H); + cudaMemcpy(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost); + const auto* tr = ggml_get_type_traits((ggml_type) type); + size_t rows_differ = 0, values_differ = 0; + for (int i = 0; i < n; ++i) { + tr->to_float(small.data() + (size_t) idx[(size_t) i] * rb, want.data(), H); + const size_t d = (size_t) std::count_if(want.begin(), want.end(), [&, k = (size_t) 0](const float& w) mutable { + return std::memcmp(&w, &got[(size_t) i * H + k++], 4) != 0; }); + values_differ += d; + rows_differ += d != 0; + } + strata::kernels::iq_dequant_f32(type, dt, H, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got.data(), dout, (size_t) H * 4, cudaMemcpyDeviceToHost); + tr->to_float(small.data(), want.data(), H); + const bool one = std::memcmp(got.data(), want.data(), (size_t) H * 4) == 0; + cudaFree(dt); cudaFree(dtok); cudaFree(dout); + std::printf("%s token_embd (%s, %lld rows): %d random rows gathered on the GPU, %zu rows / %zu values differ from " + "ggml to_float; iq_dequant_f32 row: %s\n", path, ggml_type_name((ggml_type) type), (long long) V, n, + rows_differ, values_differ, one ? "bitwise equal" : "DIFFERS"); + return (rows_differ || !one) ? 1 : 0; +} + +// APR: a GGUF's PLE table through PleTable (the engine's reader; mapped and direct SSD I/O), `n` random rows of 16 +// heads against ggml's to_float of the same bytes, bit for bit (Gyro-M's Q8_0 table; IQ4_NL for the others) +int check_gguf_ple(const char* path, int n) { + const strata::GgufModel model(strata::gguf_split_paths(path)); + size_t at = 0; + const strata::TensorInfo* t = model.find("per_layer_token_embd.weight", &at); + if (!t) { std::printf("%s: no per_layer_token_embd.weight\n", path); return 1; } + const std::string shard = model.shard(at).path(); + const uint8_t* table = model.shard(at).tensor_data(*t); + const int type = (int) t->type; + const size_t rb = ggml_row_size((ggml_type) type, 160); + const uint64_t rows = t->shape[1]; + const auto* tr = ggml_get_type_traits((ggml_type) type); + std::mt19937 rng(23); + std::vector r16((size_t) n * 16); + for (auto& v : r16) v = (uint32_t) (rng() % rows); + r16[0] = 0; r16.back() = (uint32_t) (rows - 1); + int failures = 0; + for (const auto mode : {strata::kernels::PleIo::Mmap, strata::kernels::PleIo::Direct}) { + strata::kernels::PleTable ple; + strata::kernels::PleIoOptions io; + io.mode = mode; + std::string err; + if (!ple.open(shard, err, io)) { std::printf("PleTable open (%s): %s\n", mode == strata::kernels::PleIo::Direct ? "direct" : "mmap", err.c_str()); ++failures; continue; } + std::vector got(r16.size() * 160), want(160); + if (!ple.gather_batch(r16.data(), (size_t) n, got.data(), err)) { std::printf("gather_batch: %s\n", err.c_str()); ++failures; continue; } + size_t rows_differ = 0; + for (size_t i = 0; i < r16.size(); ++i) { + tr->to_float(table + (size_t) r16[i] * rb, want.data(), 160); + rows_differ += std::memcmp(want.data(), got.data() + i * 160, 160 * 4) != 0; + } + std::printf("%s PLE table (%s via PleTable as %s, %s I/O): %zu random rows, %zu differ from ggml to_float\n", + path, ggml_type_name((ggml_type) type), ple.format(), + mode == strata::kernels::PleIo::Direct ? "direct" : "mmap", r16.size(), rows_differ); + if (rows_differ) ++failures; + } + return failures; +} + +// APR: the engine's start-up checks for a pack made from a published GGUF, without a GPU allocation: the expert +// table (native_experts.txt v5 + hadamard.txt), GPU expert kernels for every layer's formats, the GGUF expert +// offsets (check_experts_gguf), every quantized tensor the index serves from the GGUF has a native kernel (NativeDense +// projections, the head) or dequantizer (the embedding), and the PLE table opens with the engine's reader. +int check_load(const char* pack, const char* gguf) { + int failures = 0; + std::string err; + auto fail = [&](const std::string& m) { std::printf(" FAIL %s\n", m.c_str()); ++failures; }; + if (!cpu::expert_layout_load(pack, 48, 512, err)) { fail("expert_layout_load: " + err); return failures; } + const auto& lay = cpu::expert_layout(); + const auto& hs = cpu::hadamard_spec(); + int folded = 0; + for (int64_t l = 0; l < (int64_t) lay.fmt.size(); ++l) { + const auto& f = lay.fmt[(size_t) l]; + folded += f.had_gu && f.had_d; + if (!strata::kernels::native_expert_supported(f.gu_type, f.d_type, f.n_embd, f.n_ff)) + fail("layer " + std::to_string(l) + ": no GPU expert kernels for " + std::to_string(f.gu_type) + "/" + + std::to_string(f.d_type)); + } + std::printf(" experts: native_experts.txt v%d, %zu layers (%s/%s ...), %.2f GiB; hadamard block %d, %d layers folded\n", + lay.version, lay.fmt.size(), ggml_type_name((ggml_type) lay.fmt[0].gu_type), + ggml_type_name((ggml_type) lay.fmt[0].d_type), lay.total / 1073741824.0, hs.block, folded); + if (!strata::core::check_experts_gguf(gguf, lay, err)) fail("check_experts_gguf: " + err); + else std::printf(" check_experts_gguf: ok\n"); + const std::vector shards = strata::gguf_split_paths(gguf); + std::set served; + if (!strata::core::NativeDense::served_names(shards, true, served, err)) fail("served_names: " + err); + const strata::GgufModel model(shards); + std::ifstream idx(std::string(pack) + "/index.txt"); + std::string line; + int from_gguf = 0, ok_rows = 0; + while (std::getline(idx, line)) { + if (line.empty() || line[0] == '#') continue; + std::istringstream ss(line); + std::string name, file, kind; + ss >> name >> file >> kind; + if (kind != "0") continue; // a dense.bin row + ++from_gguf; + size_t at = 0; + const strata::TensorInfo* t = model.find(name, &at); + if (!t) { fail(name + ": not in the GGUF"); continue; } + bool ok = served.count(name) > 0; + if (name == "token_embd.weight") ok = strata::kernels::embed_type_supported((int) t->type); + if (name == "output.weight") ok = strata::kernels::native_mmvq_supported((int) t->type); + if (!ok) fail(name + " (" + t->type_name() + "): served from the GGUF but no kernel takes it"); + else ++ok_rows; + } + std::printf(" index: %d tensors served from the GGUF, %d with a kernel (incl. token_embd %s, output %s)\n", + from_gguf, ok_rows, model.find("token_embd.weight")->type_name(), model.find("output.weight")->type_name()); + size_t pat = 0; + if (model.find("per_layer_token_embd.weight", &pat)) { + strata::kernels::PleTable ple; + strata::kernels::PleIoOptions io; // the engine's default: direct SSD reads + if (!ple.open(model.shard(pat).path(), err, io)) fail("PleTable: " + err); + else std::printf(" PLE table: %s, %llu rows, direct I/O: ok\n", ple.format(), (unsigned long long) ple.rows()); + } + return failures; +} + } // namespace int main(int argc, char** argv) { @@ -542,8 +773,12 @@ int main(int argc, char** argv) { if (argc < 2) { std::fprintf(stderr, "usage: native_expert_parity [layer ...]\n" " native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n" + " native_expert_parity --synthetic-hadamard GU/DOWN ... (the same, Hadamard-folded: APR)\n" " native_expert_parity --q5_1-min\n" - " native_expert_parity --bf16-embd\n"); + " native_expert_parity --bf16-embd\n" + " native_expert_parity --load-check (start-up checks, no GPU load)\n" + " native_expert_parity --gguf-embd [rows] (token_embd rows vs to_float)\n" + " native_expert_parity --gguf-ple [tokens] (PLE rows via PleTable vs to_float)\n"); return 2; } // #152's width check tests the opt-in rule (the multi-token kernels from one token on) @@ -558,11 +793,24 @@ int main(int argc, char** argv) { cudaStream_t s; cudaStreamCreate(&s); const std::string mode = argv[1]; - if (mode == "--q5_1-min") { + if (mode == "--load-check" && argc >= 4) { + std::printf("load check: pack %s, GGUF %s\n", argv[2], argv[3]); + failures += check_load(argv[2], argv[3]); + } else if (mode == "--gguf-embd" && argc >= 3) { + failures += check_gguf_embd(argv[2], argc > 3 ? std::atoi(argv[3]) : 300, s); + } else if (mode == "--gguf-ple" && argc >= 3) { + failures += check_gguf_ple(argv[2], argc > 3 ? std::atoi(argv[3]) : 20); + } else if (mode == "--q5_1-min") { failures += check_q5_1_min(s); } else if (mode == "--bf16-embd") { failures += check_bf16_embd(s); - } else if (mode == "--synthetic") { + } else if (mode == "--synthetic" || mode == "--synthetic-hadamard") { + // --synthetic-hadamard: the same with the layer Hadamard-folded (APR, prism.hadamard): random signs, block 128 + const bool had = mode == "--synthetic-hadamard"; + static std::vector sx((size_t) H), sh((size_t) FF); + std::mt19937 srng(5); + for (auto& v : sx) v = (srng() & 1) ? 1.f : -1.f; + for (auto& v : sh) v = (srng() & 1) ? 1.f : -1.f; for (int i = 2; i < argc; ++i) { const std::string arg = argv[i]; const size_t slash = arg.find('/'); @@ -576,7 +824,13 @@ int main(int argc, char** argv) { ++failures; continue; } - failures += check_blob(f, synthetic_blob(f, i), i, "synthetic", s); + if (had) { + f.had_block = 128; + f.had_gu = f.had_d = true; + f.gu_signs = sx.data(); + f.d_signs = sh.data(); + } + failures += check_blob(f, synthetic_blob(f, i), i, had ? "hadamard" : "synthetic", s); } } else { const strata::GgufModel model(strata::gguf_split_paths(argv[1])); diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index 9b78fcc9..21a9c2e7 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -263,6 +263,9 @@ bool supported(int t) { case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S: case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS: case GGML_TYPE_Q8_0: // the draft layer's dense matrices (E-9) +#ifdef STRATA_MMQ_TQ + case GGML_TYPE_TQ2_T: case GGML_TYPE_TQK6: case GGML_TYPE_TQK7: // APR experts (agention fork's MMQ) +#endif return true; #ifdef STRATA_MMQ_KQUANTS // Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF projections (STRATA_DENSE_MMQ) @@ -431,6 +434,11 @@ void Context::run(const Product& p, void* stream) { case GGML_TYPE_IQ4_NL: mul_mat_q_case(ctx, a, s); break; case GGML_TYPE_IQ4_XS: mul_mat_q_case(ctx, a, s); break; case GGML_TYPE_Q8_0: mul_mat_q_case(ctx, a, s); break; +#ifdef STRATA_MMQ_TQ + case GGML_TYPE_TQ2_T: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_TQK6: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_TQK7: mul_mat_q_case(ctx, a, s); break; +#endif #if defined(STRATA_MMQ_KQUANTS) && defined(STRATA_KQ_DSO) case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q6_K: case GGML_TYPE_Q5_1: { const int e = kq::run((int) t, &a, s); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 3d6d0ec1..0f68a300 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -23,6 +23,7 @@ #include "strata/kernels/native_ple_postops.hpp" #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/hadamard.hpp" #include "strata/kernels/qsa.hpp" #include "strata/kernels/kv_stream.hpp" #include "strata/kernels/cvec.hpp" @@ -755,6 +756,9 @@ struct PeerPrefill { int32_t* host_pair = nullptr; std::vector bounds_host; core::PinnedRing up_ring; // #1996: this device's pageable uploads (bounds, routed rows) go up from pinned slots + // APR (prism.hadamard): per layer, this device's copy of the down projection's sign vector (nullptr: identity or + // not folded). The gate/up input arrives already rotated (the primary sends its rotated copy, m.Xr). + std::vector had_sh; std::vector owned; int64_t layers = 0, experts = 0, rows = 0, over_cap = 0; // stats ~PeerPrefill() { @@ -873,6 +877,7 @@ struct Prefill::Impl { *shared = nullptr, *sg = nullptr; int32_t *ids = nullptr, *slot_dev = nullptr, *src_dev = nullptr; uint16_t *Xs = nullptr, *Hh = nullptr, *sh_h = nullptr; + float* Xr = nullptr; // APR: Hadamard-rotated copy of `mixed` for the MMQ path // step 2b (MMQ): the activations quantized per layer, H in FP32 and its group's quantized rows, the identity // row map, the group bounds, the group buffers of gathered experts void *Xq = nullptr, *Hq = nullptr; @@ -964,6 +969,9 @@ struct Prefill::Impl { std::vector tok_host; PinnedUpload tok_up; core::PinnedRing up_ring; // #1996: every other upload of the prompt path whose host side is pageable + // APR (prism.hadamard): per layer, this device's copies of the gate/up (n_embd) and down (n_ff) sign vectors + // (nullptr: identity signs or not folded), resolved once in init so a prompt chunk reads a pointer + std::vector had_sx, had_sh; std::unique_ptr pp; // multi-GPU: the peer GPU's expert share (set_peer) // layer split: the next stage's GPU as a stream-only peer (set_stage_helper); its buffers are that stage's own // prompt buffers, bound per prompt, and it takes the place of `pp` for a run it helps @@ -1204,6 +1212,9 @@ uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) { a.take(mb.hq, ok); a.take(T * K, ok); a.take(T * K, ok); a.take(MMQ_GROUP * 4, ok); a.take(T * K, ok); + // APR: the rotated copy of `mixed` for the MMQ path (carve's m.Xr) - it must be counted here too, or the MoE + // set outgrows the region `carve` sizes from this, and `init` fails with "do not fit" at any chunk + if (strata::kernels::cpu::hadamard_spec().any()) a.take(T * N, ok); } return a.used; } @@ -1224,6 +1235,26 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert < 1 || ss.k != K) { err = "prefill: geometry differs from the artifact's"; return false; } + { // a native pack's experts: this path's expert buffers and products (and so their Hadamard rotations) are + // N wide in and 640 wide in the middle; the sign vectors are looked up at the layout's own widths + const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); + for (size_t l = 0; lay.native && l < lay.fmt.size(); ++l) + if (lay.fmt[l].n_embd != N || lay.fmt[l].n_ff != 640) { + err = "prefill: layer " + std::to_string(l) + "'s experts are " + std::to_string(lay.fmt[l].n_embd) + + " x " + std::to_string(lay.fmt[l].n_ff) + ", not the artifact's 2560 x 640"; + return false; + } + // APR: the sign vectors on this device, once (hadamard_device_signs takes a mutex and, the first time per + // device, cudaMallocs its copy): run_impl reads m.had_sx / m.had_sh + m.had_sx.assign(lay.native ? lay.fmt.size() : 0, nullptr); + m.had_sh.assign(m.had_sx.size(), nullptr); + for (size_t l = 0; l < m.had_sx.size(); ++l) { + if (lay.fmt[l].had_gu) + m.had_sx[l] = strata::kernels::hadamard_device_signs(lay.fmt[l].gu_signs, (int) lay.fmt[l].n_embd); + if (lay.fmt[l].had_d) + m.had_sh[l] = strata::kernels::hadamard_device_signs(lay.fmt[l].d_signs, (int) lay.fmt[l].n_ff); + } + } cudaGetDevice(&m.device); if (stage_le_ < 0) stage_le_ = g.n_layers; if (stage_lb_ < 0 || stage_lb_ >= stage_le_ || stage_le_ > g.n_layers || (stage_le_ < g.n_layers) != (next_ != nullptr)) { @@ -1441,6 +1472,8 @@ bool Prefill::carve(size_t T, void* alloc) { m.Xscale = c.take(T * K, ok); m.Hscale = c.take(T * K, ok); m.grp_tail = c.take(MMQ_GROUP * 4, ok); m.row_sd = c.take(T * K, ok); + // APR: the rotated expert input (only for Hadamard-folded packs) + m.Xr = strata::kernels::cpu::hadamard_spec().any() ? c.take(T * N, ok) : nullptr; } if (base == nullptr) ok = false; } @@ -1719,6 +1752,20 @@ double split_help_frac(int64_t T) { } } // namespace +namespace { +// APR: the down projections' sign vectors on the current device (the peer's or the helper's), one per layer, +// resolved once at setup (hadamard_device_signs: a mutex and, the first time on that device, a cudaMalloc) into +// P.had_sh, which a prompt chunk reads directly. The gate/up signs are not needed there: the primary sends its +// already rotated input (m.Xr). +void peer_had_signs(PeerPrefill& P) { + const auto& lay = strata::kernels::cpu::expert_layout(); + P.had_sh.assign(lay.native ? lay.fmt.size() : 0, nullptr); + for (size_t l = 0; l < P.had_sh.size(); ++l) + if (lay.fmt[l].had_d) + P.had_sh[l] = strata::kernels::hadamard_device_signs(lay.fmt[l].d_signs, (int) lay.fmt[l].n_ff); +} +} // namespace + bool Prefill::set_stage_helper(Prefill* helper, std::string& err) { Impl& m = *impl_; m.help_pp.reset(); @@ -1752,6 +1799,7 @@ bool Prefill::set_stage_helper(Prefill* helper, std::string& err) { for (int i = 0; ok && i < kSplitHelpRing; ++i) ok = cudaEventCreateWithFlags(&pp->pcopied[(size_t) i], cudaEventDisableTiming) == cudaSuccess && cudaEventCreateWithFlags(&pp->pused[(size_t) i], cudaEventDisableTiming) == cudaSuccess; + if (ok) peer_had_signs(*pp); // APR: on the helper's device cudaSetDevice(prev); if (!ok) { err = "prefill: the layer split's prompt help (streams and events)"; return false; } helper_ = helper; @@ -1837,6 +1885,11 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e for (const auto& f : lay.fmt) if (lay.native && f.tail_off) { err = "prefill peer: not for NVFP4 experts yet"; return false; } } + if (strata::kernels::cpu::hadamard_spec().any()) { // APR: the peer's MMQ share does not rotate; declined + std::fprintf(stderr, "strata: prefill peer: not used for a Hadamard-folded (APR) pack\n"); + m.pp.reset(); + return true; + } auto pp = std::make_unique(); pp->peer = peer; pp->p2p = peer->p2p(); @@ -1945,6 +1998,7 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e pp->ctx = std::make_unique(); pp->run_ctx = pp->ctx.get(); mmq::iota(pp->ident, pp->cap_rows, pp->s); + peer_had_signs(*pp); // APR: on the peer's device ok = cudaStreamSynchronize(pp->s) == cudaSuccess; } if (ok && !pp->p2p) { // the host route's mapped buffers, sized for the largest chunk @@ -1992,6 +2046,11 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e pp->compact ? (pp->ps_frac > 0.0 ? (", compact group buffers, streams " + std::to_string((int) (pp->ps_frac * 100 + 0.5)) + "% of the primary's streamed experts through a " + std::to_string(pp->RP) + "-slot ring").c_str() : ", compact group buffers") : "", fb >> 20); + // APR: this path rotates on the peer too (peer_had_signs), but no P2P pair has run it end to end with a + // Hadamard-folded pack yet (the validated two-GPU runs had no P2P, so their prompts stayed on the first GPU) + if (strata::kernels::cpu::hadamard_spec().any()) + std::fprintf(stderr, "strata prefill: warning: prompt processing on a P2P peer GPU is not validated end to end " + "with Hadamard-folded experts yet\n"); m.pp = std::move(pp); return true; } @@ -3192,14 +3251,23 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // keep MMQ; without the variable nothing here runs. A native pack's layer takes the native kernels // (moe_fused_iq.hpp) where they cover its two formats, else MMQ (or the FP16 path: IQ1_M). const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); + // APR (prism.hadamard): folded gate/up take H (s * x), folded down H (s * h), on the FP16 and MMQ + // paths and on the multi-GPU prompt paths (the peer, the layer split's helper: MMQ); the fused + // kernels do not rotate (and have no trellis types), so a folded layer takes MMQ instead + const bool had_gu = lay.native && lay.fmt[(size_t) l].had_gu; + const bool had_d = lay.native && lay.fmt[(size_t) l].had_d; const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l]; + const int had_block = lay.native ? lay.fmt[(size_t) l].had_block : 0; + const float* had_sx = had_gu ? m.had_sx[(size_t) l] : nullptr; // resolved in init + const float* had_sh = had_d ? m.had_sh[(size_t) l] : nullptr; const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42; const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; // --peer-device: MMQ only, whether or not the peer took the prompt path (set_peer can decline), as // fused_ring() sized the ring and the buffers for it const bool no_peer = !core::peer_portable(); const bool fused_only = mmq_plan().any && mmq_plan().fo[(size_t) l]; - const bool fused_nat = (use_mmq || fused_only) && stream_all && no_peer && lay.native && fused::native_supported(mmq_gt, mmq_dt); + const bool fused_nat = (use_mmq || fused_only) && stream_all && no_peer && lay.native && !had_gu && !had_d && + fused::native_supported(mmq_gt, mmq_dt); const bool fused_l = (use_mmq && stream_all && no_peer && !lay.native && fused::enabled()) || fused_nat; // #583 / #954: the fused layout's GU/H/Xq hold the grouping tables and the int8 rows, sized for // stream_all_min() - 1 tokens of MMQ's rows, so a layer that takes MMQ or the FP16 path at the FULL @@ -3623,9 +3691,16 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0; const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0; pt.mark(kPfGather, cs); + // the routed experts' input: `mixed`, or (APR) its rotated copy, which the peer / the layer + // split's helper also take (one rotation for both cards; `mixed` itself feeds the shared expert) + const float* xsrc = m.mixed; if (use_mmq) { // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed` - mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale); + if (had_gu) { + strata::kernels::hadamard_rows(m.mixed, m.Xr, T, N, had_block, had_sx, m.cs); + xsrc = m.Xr; + } + mmq::quantize(xsrc, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale); // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down // reads the group's own quantized H) const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP; @@ -3648,6 +3723,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } } else { gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs); + // APR: Hadamard-folded gate/up take H (s * x); Xs is this layer's private gathered copy + // (rotated in fp16 storage, fp32 arithmetic: see the down projection's note below) + if (had_gu) strata::kernels::hadamard_rows_f16(m.Xs, T * K, N, had_block, had_sx, m.cs); } // multi-GPU: the peer's share, enqueued before the primary's own experts so both cards work at once peer_now = use_mmq && !order_peer.empty(); @@ -3817,6 +3895,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = 1280; P.run_ctx->run(gu, ps); mmq::swiglu(P.GU_g, P.H_g, nr, 640, !lay.native, ps); + if (had_d) // APR: folded down weights take H (s * h), on this card as on the primary + strata::kernels::hadamard_rows(P.H_g, P.H_g, nr, 640, had_block, P.had_sh[(size_t) l], ps); mmq::quantize(P.H_g, nullptr, P.Hq_g, mmq_dt, 640, 640, nr, ps); const int b = (int) (g2 & 1); if (P.dm_live[b]) cudaStreamWaitEvent(ps, P.ev_dm[b], 0); // its last rows have left @@ -3894,6 +3974,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = 1280; P.run_ctx->run(gu, ps); mmq::swiglu(P.GU + r0 * 1280, P.H + r0 * 640, nr, 640, !lay.native, ps); + if (had_d) // APR: as above + strata::kernels::hadamard_rows(P.H + r0 * 640, P.H + r0 * 640, nr, 640, had_block, + P.had_sh[(size_t) l], ps); mmq::quantize(P.H + r0 * 640, nullptr, P.Hq, mmq_dt, 640, 640, nr, ps); mmq::Product dn; dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db; @@ -4136,6 +4219,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri m.grp_tail, r0, m.cs); else mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs); + if (had_d) + strata::kernels::hadamard_rows(m.H + r0 * 640, m.H + r0 * 640, nr, 640, had_block, had_sh, m.cs); pt.mark(kPfGemmD, cs); mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs, m.Hscale); mmq::Product dn; @@ -4173,6 +4258,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri pt.mark(kPfGemmGU, cs); m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * 1280, ne, 1280, N); swiglu_interleaved(m.GU + o0 * 1280, m.Hh + o0 * 640, ne, m.cs); + // APR, deliberately in place on the fp16 H: hadamard_rows_f16 reads fp16, runs the + // butterflies in fp32 and rounds once on the store, so against an fp32 rotation the only + // extra error is the one fp16 rounding of the SwiGLU output before it (~2^-11 relative per + // value; the GEMM reads fp16 either way). An fp32 rotation would need a T*K*640 float + // buffer (~200 MiB at an 8k chunk) or a fused SwiGLU + rotation kernel, for the fallback + // of types and builds without MMQ (the MMQ path rotates fp32 H). native_expert_parity + // bounds the fp16 rotation against the float one at relative L1 error < 2e-3. The + // gate/up input (Xs above) is handled the same way. + if (had_d) strata::kernels::hadamard_rows_f16(m.Hh + o0 * 640, ne, 640, had_block, had_sh, m.cs); pt.mark(kPfGemmD, cs); m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640); return true; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ba697c2e..cdfaf110 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -44,6 +44,7 @@ #include "strata/kernels/cpu/pool.hpp" #include "strata/platform/aux_cpus.hpp" #include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/hadamard.hpp" #include "strata/kernels/ngram.hpp" #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/s2_expert_grouped.hpp" @@ -3014,6 +3015,28 @@ int main(int argc, char** argv) { // (strata_kq): asking for the formats opens it now, before the expert cache takes the free VRAM (void) strata::prefill::mmq::supported(f.gu_type); (void) strata::prefill::mmq::supported(f.d_type); +#endif + } + // APR (prism.hadamard) packs: every expert path rotates its activations (CPU pool: native_quant_act / _h; + // GPU verify, remote GPUs, prompt FP16 path: hadamard_rows). Validated end to end on CUDA (sm_86, sm_89 with + // a two-GPU layer split and peer decode, sm_120) and on HIP gfx1151. Other HIP architectures run the same + // kernels but have not been run end to end with such a pack: said here, not refused (the P2P prompt peer + // says the same in Prefill::set_peer). The former opt-in STRATA_APR is no longer read. + if (strata::kernels::cpu::hadamard_spec().any()) { + std::fprintf(stderr, "strata generate: APR pack: Hadamard-folded experts (block %d)\n", + strata::kernels::cpu::hadamard_spec().block); +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) + int dev = 0; + cudaDeviceProp p{}; + if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess) { + std::string arch(p.gcnArchName); + if (const size_t colon = arch.find(':'); colon != std::string::npos) arch.resize(colon); + if (arch != "gfx1151") + std::fprintf(stderr, "strata generate: warning: Hadamard-folded experts are validated end to end " + "on gfx1151 among AMD GPUs, not yet on %s\n", arch.c_str()); + } else { + (void) cudaGetLastError(); + } #endif } } diff --git a/strata_control/models.py b/strata_control/models.py index 30ef2d03..eec730d6 100644 --- a/strata_control/models.py +++ b/strata_control/models.py @@ -33,7 +33,7 @@ MAX_IMPORT_SHARDS = 128 SHARD = re.compile(r"(.+)-(\d{5})-of-(\d{5})\.gguf\Z", re.I) SUPPORTED_SELECTIONS = frozenset({"qwen/Q2_0", "qwen/IQ2_XS", "qwen/IQ3_XXS", "qwen/IQ3_S", "swift/IQ2_XS", "swift/IQ3_XXS", "coder/IQ1_M", - "unsloth/UD-IQ4_XS", "unsloth/UD-Q4_K_XL"}) + "unsloth/UD-IQ4_XS", "unsloth/UD-Q4_K_XL", "gyro/Gyro-S", "gyro/Gyro-M"}) def settings_path() -> Path: diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt index fd42efbf..ba639519 100644 --- a/sycl/CMakeLists.txt +++ b/sycl/CMakeLists.txt @@ -119,7 +119,7 @@ add_library(strata_spec STATIC ${_spec}) target_link_libraries(strata_spec PUBLIC strata_includes) strata_resolve(_cpu src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp src/kernels/cpu/expert_layout.cpp - src/kernels/cpu/q2_avx2.cpp) + src/kernels/cpu/q2_avx2.cpp src/kernels/cpu/hadamard.cpp) # hadamard.cpp: expert_layout.cpp reads hadamard.txt add_library(strata_kernels_cpu STATIC ${_cpu}) set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/expert.cpp PROPERTIES COMPILE_OPTIONS "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") @@ -183,12 +183,16 @@ if(STRATA_NATIVE_EXPERTS) strata_resolve(_cpu_native src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp src/kernels/cpu/kq_avx1.cpp # 0.1.31: the Q4_K/Q5_K/Q5_1/Q8_0 expert rows src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp # 0.1.42: AVX1 (no AVX2) Q2_0 / i-quant rows - src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp) # NVFP4 expert rows (native_expert.cpp calls them) + src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp # NVFP4 expert rows (native_expert.cpp calls them) + src/kernels/cpu/tq_cpu.cpp src/kernels/cpu/tq_avx2.cpp src/kernels/cpu/tq_avx512.cpp) # Gyro trellis CPU rows (native_expert.cpp calls them; the SYCL GPU path does not run these types) target_sources(strata_kernels_cpu PRIVATE ${_cpu_native}) target_include_directories(strata_kernels_cpu PRIVATE ${STRATA_ROOT}/third_party/ggml) set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx512.cpp ${STRATA_ROOT}/src/kernels/cpu/nvfp4_avx512.cpp PROPERTIES COMPILE_OPTIONS "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512vnni;-mavx512vbmi;-mavx2;-mfma;-mf16c") set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx") diff --git a/tests/hip/prefill_mmq_parity.cpp b/tests/hip/prefill_mmq_parity.cpp index c477d5b3..4a204781 100644 --- a/tests/hip/prefill_mmq_parity.cpp +++ b/tests/hip/prefill_mmq_parity.cpp @@ -10,6 +10,8 @@ #include #include #include +#include +#include #include #include #include @@ -55,10 +57,10 @@ std::vector decode_matrix(ggml_type type, const std::vector & q, return out; } -std::vector make_q2_matrix(int64_t rows, int64_t cols, int expert, int trial) { - const ggml_type type = GGML_TYPE_Q2_0; +std::vector make_q2_matrix(int64_t rows, int64_t cols, int expert, int trial, + ggml_type type = GGML_TYPE_Q2_0) { const auto * tr = ggml_get_type_traits(type); - if (!tr || !tr->from_float_ref) throw std::runtime_error("Q2_0 host quantizer unavailable"); + if (!tr || !tr->from_float_ref) throw std::runtime_error("host quantizer unavailable"); const size_t rb = row_bytes(type, cols); std::vector out((size_t) rows * rb); std::vector row((size_t) cols); @@ -171,8 +173,17 @@ Metrics run_product(Context & ctx, hipStream_t stream, const std::string & name, } } } + { + size_t bad = 0, first = got.size(); + uint32_t first_bits = 0; + for (size_t i = 0; i < got.size(); ++i) + if (!std::isfinite(got[i])) { if (!bad++) { first = i; std::memcpy(&first_bits, &got[i], 4); } } + if (bad) + throw std::runtime_error(name + ": " + std::to_string(bad) + " non-finite or unwritten MMQ outputs, first at row " + + std::to_string(first / (size_t) out_rows) + " col " + std::to_string(first % (size_t) out_rows) + + " bits " + std::to_string(first_bits)); + } for (size_t i = 0; i < got.size(); ++i) { - if (!std::isfinite(got[i])) throw std::runtime_error(name + ": non-finite or unwritten MMQ output"); const double d = (double) got[i] - ref[i]; err2 += d * d; ref2 += (double) ref[i] * ref[i]; max_abs = std::max(max_abs, (float) std::fabs(d)); } @@ -199,9 +210,10 @@ Metrics run_product(Context & ctx, hipStream_t stream, const std::string & name, return m; } -std::vector> synthetic_q2(int experts, int64_t out_rows, int64_t cols, int trial) { +std::vector> synthetic_q2(int experts, int64_t out_rows, int64_t cols, int trial, + ggml_type type = GGML_TYPE_Q2_0) { std::vector> w; - for (int e = 0; e < experts; ++e) w.push_back(make_q2_matrix(out_rows, cols, e, trial)); + for (int e = 0; e < experts; ++e) w.push_back(make_q2_matrix(out_rows, cols, e, trial, type)); return w; } @@ -311,6 +323,24 @@ int main(int argc, char ** argv) { 1280, 2560, synthetic_of_type(type, 1, 1280, 2560, 5), counts, make_activations(rows, 2560, 77), src, dst); } + // APR trellis experts (ggml types 144-146), when the build has their MMQ instances (agention fork): gate/up + // 1280 x 2560 and down 2560 x 640 (5 blocks per row: the last 256-slice reads past the row, against zero + // activations) + for (const ggml_type t : {(ggml_type) 145, (ggml_type) 146, (ggml_type) 144}) { + if (!supported((int) t)) { std::cout << "type " << (int) t << ": no MMQ instance in this build\n"; continue; } + const std::vector counts{2, 3}; + const auto src = permutation(5, 1, false), dst = permutation(5, 2, true); + const std::string tn = ggml_type_name(t); + const char* rep = std::getenv("MMQ_PARITY_REPEAT"); // repeat each product (flakiness screen) + const int reps = rep ? std::max(1, std::atoi(rep)) : 1; + const auto wgu = synthetic_q2(2, 1280, 2560, 5, t), wd = synthetic_q2(2, 2560, 640, 6, t); + for (int r = 0; r < reps; ++r) { + run_product(ctx, stream, "synthetic-" + tn + "-GU", t, 1280, 2560, wgu, counts, + make_activations(5, 2560, 5), src, dst); + run_product(ctx, stream, "synthetic-" + tn + "-down", t, 2560, 640, wd, counts, + make_activations(5, 640, 6), src, dst); + } + } if (argc == 2) run_real_iq3_first_expert(ctx, stream, argv[1]); } hip_check(hipStreamSynchronize(stream), "final synchronize"); diff --git a/third_party/ggml/ggml-common-tq.h b/third_party/ggml/ggml-common-tq.h new file mode 100644 index 00000000..1ce3773b --- /dev/null +++ b/third_party/ggml/ggml-common-tq.h @@ -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 + +#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, +}; diff --git a/tools/embd_bf16_pack.py b/tools/embd_bf16_pack.py index 1ed2d642..a633b332 100644 --- a/tools/embd_bf16_pack.py +++ b/tools/embd_bf16_pack.py @@ -7,6 +7,12 @@ and reads one row per token, so BF16 costs 0.6 GB of RAM more and no VRAM; `--em The output is a one-tensor GGUF: `token_embd.weight`, ne = [n_embd, n_vocab], type BF16, the bytes copied straight out of the safetensors file - nothing decoded or rounded. + + python tools/embd_bf16_pack.py --gguf --out + +instead dequantizes a GGUF's own token_embd.weight to BF16 (round-to-nearest-even, through gguf-py), for a file whose +embedding type has no GPU dequantizer in the engine (Agention's Gyro-S stores it as Q6_K). That is the GGUF's values +rounded to BF16, not the checkpoint's. """ import argparse import json @@ -35,11 +41,63 @@ def kv_string(key, val): return gguf_string(key) + struct.pack(" BF16, %.2f GB" % (vocab, dim, t.type_name, vocab * dim * 2 / 1e9), flush=True) + head = write_header(dim, vocab, src.name, "token embedding, %s dequantized to BF16" % t.type_name) + out.parent.mkdir(parents=True, exist_ok=True) + tmp = out.with_suffix(out.suffix + ".part") + rows = 8192 + with open(tmp, "wb") as w: + w.write(head) + for r0 in range(0, vocab, rows): + r1 = min(vocab, r0 + rows) + raw = np.asarray(mm[base + r0 * row: base + r1 * row]).reshape(r1 - r0, row) + vals = quants.dequantize(raw, Q[t.type_name]).astype(np.float32) + if not np.isfinite(vals).all(): + sys.exit("token_embd.weight has non-finite values") + w.write(quants.quantize(vals, Q.BF16).tobytes()) + if tmp.stat().st_size != len(head) + vocab * dim * 2: + sys.exit("size check failed") + tmp.replace(out) + print("wrote %s (header %d B)" % (out, len(head))) + + def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--model", required=True, help="the checkpoint directory (model.safetensors.index.json)") + src = ap.add_mutually_exclusive_group(required=True) + src.add_argument("--model", help="the checkpoint directory (model.safetensors.index.json)") + src.add_argument("--gguf", help="a model GGUF whose token_embd.weight is dequantized to BF16") ap.add_argument("--out", required=True) a = ap.parse_args() + if a.gguf: + from_gguf(pathlib.Path(a.gguf).absolute(), pathlib.Path(a.out)) + return model, out = pathlib.Path(a.model), pathlib.Path(a.out) wmap = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"] @@ -57,13 +115,7 @@ def main(): sys.exit("%s: data size does not match its shape" % name) print("%s: %d x %d BF16, %.2f GB" % (name, vocab, dim, n / 1e9), flush=True) - kvs = [kv_string("general.architecture", "strata-embd"), - kv_string("general.name", "token embedding, BF16 as shipped"), - kv_string("strata.embd.source", model.name)] - head = b"GGUF" + struct.pack(" str: + """native_experts.txt as expert_layout writes it (v3, or v4 with per-role shards) -> the same table marked v5 + (Hadamard-folded experts, hadamard.txt beside it), or an error string naming the version it cannot mark.""" + head, rest = text.split("\n", 1) if "\n" in text else (text, "") + m = NATIVE_HEAD.match(head) + if not m or m.group(1) not in ("3", "4"): + found = "v" + m.group(1) if m else "without a version header (%r)" % head[:40] + return ("cannot mark native_experts.txt %s as v5 for Hadamard-folded experts: only v3 and v4 tables are " + "supported" % found) + return "# strata native experts v5:" + head[m.end():] + " - v5: Hadamard-folded experts, see hadamard.txt\n" + rest + + +HADAMARD_ROLE = re.compile(r"^blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$") + + +def hadamard_spec(meta: dict, layout, n_embd: int, n_ff: int): + """prism.hadamard.* (Agention's APR files: routed experts stored in a block-Hadamard-rotated basis; the runtime + must rotate their input activations, see include/strata/kernels/cpu/hadamard.hpp) -> the text of hadamard.txt, + None for a model without the metadata, or an error string. Anything this engine cannot apply is refused: a + folded weight it would run unrotated computes plausible garbage.""" + if "prism.hadamard.version" not in meta: + return None + if int(meta["prism.hadamard.version"]) != 1: + return "unsupported prism.hadamard.version %s" % meta["prism.hadamard.version"] + block = int(meta.get("prism.hadamard.block_size", 0)) + if block <= 1 or block & (block - 1): + return "invalid prism.hadamard.block_size %r" % block + if meta.get("prism.hadamard.transform") != "normalized-sylvester-walsh-hadamard": + return "unsupported prism.hadamard.transform %r" % meta.get("prism.hadamard.transform") + if meta.get("prism.hadamard.axis") != "input-last-dimension": + return "unsupported prism.hadamard.axis %r" % meta.get("prism.hadamard.axis") + mode = meta.get("prism.hadamard.sign_mode") + if mode not in ("identity", "explicit"): + return "unsupported prism.hadamard.sign_mode %r" % mode + if meta.get("prism.hadamard.inverse_weight_names"): + return ("prism.hadamard.inverse_weight_names (a rotated token embedding) is not supported by this engine: " + "%s" % ", ".join(meta["prism.hadamard.inverse_weight_names"][:4])) + names = meta.get("prism.hadamard.weight_names") or [] + if not names: + return "prism.hadamard.weight_names is empty" + n_layers = len(layout) + roles = [0] * n_layers + for name in names: + m = HADAMARD_ROLE.match(name) + if not m or int(m.group(1)) >= n_layers: + return ("prism.hadamard folds %s; this engine applies the activation rotation to the routed experts " + "(blk.N.ffn_{gate,up,down}_exps) only" % name) + bit = {"gate": 1, "up": 2, "down": 4}[m.group(2)] + if roles[int(m.group(1))] & bit: + return "duplicate prism.hadamard weight %s" % name + roles[int(m.group(1))] |= bit + for l, r in enumerate(roles): + if bool(r & 1) != bool(r & 2): + return "layer %d: prism.hadamard folds only one of gate/up (they share one input)" % l + if r and 42 in (layout[l][1] if r & 3 else -1, layout[l][2] if r & 4 else -1): + return "layer %d: a Hadamard-folded Q2_0 expert (the engine's Q2_0 rows cannot rotate)" % l + lines = ["# strata hadamard v1: prism.hadamard (normalized-sylvester-walsh-hadamard, input-last-dimension, " + "sign_mode %s), written by tools/iq_pack.py" % mode, "block %d" % block] + widths = {n_embd for r in roles if r & 3} | {n_ff for r in roles if r & 4} + if any(w % block for w in widths): + return "prism.hadamard block %d does not divide the expert widths %s" % (block, sorted(widths)) + if mode == "explicit": + sw = [int(w) for w in meta.get("prism.hadamard.sign_widths") or []] + sv = [int(v) for v in meta.get("prism.hadamard.sign_values") or []] + if not sw or sum(sw) != len(sv) or any(w <= 0 or w % block for w in sw) or len(set(sw)) != len(sw): + return "prism.hadamard sign_widths / sign_values are inconsistent" + if any(v not in (1, -1) for v in sv): + return "prism.hadamard sign values must be +1/-1" + at, table = 0, {} + for w in sw: + table[w] = sv[at:at + w] + at += w + missing = sorted(widths - set(table)) + if missing: + return "prism.hadamard has no sign vector for width(s) %s" % missing + for w in sorted(table): + lines.append("signs %d %s" % (w, " ".join(str(v) for v in table[w]))) + for l, r in enumerate(roles): + if r: + lines.append("layer %d %d %d %d" % (l, r & 1, (r >> 1) & 1, (r >> 2) & 1)) + return "\n".join(lines) + "\n" + + def experts_source(model: Model, text: str, total: int) -> dict: """What experts.bin is cut from: the shards (names and sizes) and the hash of native_experts.txt (every per-role file and offset, the formats and the blob sizes). A same-size experts.bin of another model or @@ -539,6 +625,22 @@ def main() -> int: layout, text, n_expert, offset = got if any(t.type_name == "NVFP4" for *_, ts in layout for t in ts): a.experts_bin = True # the GGUF holds the weights without the scale tails: the engine must read experts.bin + # ---- prism.hadamard: rotated experts need hadamard.txt beside native_experts.txt, which becomes v5 so an engine + # that cannot rotate refuses the pack (instead of running the folded experts on unrotated activations) + t0 = layout[0][5] + had = hadamard_spec(g.metadata, layout, int(t0[0].shape[0]), int(t0[2].shape[0])) + if isinstance(had, str) and not had.startswith("# strata hadamard"): + print("prism.hadamard: " + had) + return 1 + if had is not None: + text = native_experts_v5(text) + if not text.startswith("# strata native experts v5:"): + print("prism.hadamard: " + text) + return 1 + print("prism.hadamard: %d layer(s) of Hadamard-folded experts (block %s, %s signs): hadamard.txt, " + "native_experts.txt v5" % (sum(1 for ln in had.splitlines() if ln.startswith("layer ")), + g.metadata["prism.hadamard.block_size"], + g.metadata["prism.hadamard.sign_mode"])) path = out / "experts.bin" sidecar = out / "experts.bin.src.json" want = experts_source(model, text, offset) @@ -608,6 +710,12 @@ def main() -> int: # ---- the experts. native_experts.txt is written to a temporary name and renamed only when every layer is # in: a stop part-way (a layer split across shards, #171) left a partial native_experts.txt that the next setup # run took as a finished pack (#172). It is the pack's completion marker, so it is published last. + htmp = out / "hadamard.txt.tmp" + if had is not None: + htmp.write_text(had, encoding="utf-8", newline="\n") + htmp.replace(out / "hadamard.txt") + else: + (out / "hadamard.txt").unlink(missing_ok=True) # a previous Hadamard model's, packed into this folder tmp = out / "native_experts.txt.tmp" with open(tmp, "w", encoding="utf-8", newline="\n") as fo: fo.write(text) diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 4e5a4bd6..f3a8ae61 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -77,6 +77,14 @@ FALLBACK_MODELS = { "Q8_0": {"about": "8-bit, the reference quality (every expert Q8_0); for a 192 GB PC", "download_gb": 188.2, "ram_gb": 136, "arena_gb": 128.3, "families": ("unsloth",), "budget": True, "vision": True}, + "Gyro-S": {"about": "the smallest option, for PCs with little memory (27.6 GB of VRAM + RAM together); lower quality " + "than the 2-3-bit sizes, and the 2-bit Q2_0 decodes faster", + "download_gb": 58.5, "ram_gb": 27.6, "arena_gb": 25.8, "families": ("gyro",), "mem_total": True, + "vision": False}, + "Gyro-M": {"about": "about IQ3_XXS quality with about 20% less GPU memory (35 GB of VRAM + RAM together); decodes " + "about 20% slower than Q2_0 on 12 GB cards", + "download_gb": 92.0, "ram_gb": 35.0, "arena_gb": 32.1, "families": ("gyro",), "mem_total": True, + "vision": False}, "NVFP4": {"about": "4-bit NVFP4 experts, GPTQ (sergqwer's strata-nvfp4 pack); RTX 50 has FP4 tensor cores, other " "NVIDIA cards run it at 8-bit precision", "download_gb": 128.0, "ram_gb": 80, "arena_gb": 68.0, "families": ("nvfp4",), "vision": True}, @@ -95,10 +103,15 @@ FALLBACK_FAMILIES = { "~80 GB (UD-IQ4_XS) to ~136 GB (Q8_0) of RAM, else " "part of them read from the SSD", "tag": "unsloth-", "vision": True}, + "gyro": {"title": "Qwen3.8-Flash-Next (Gyro)", "about": "Gyro-S (27.6 GB of memory) and Gyro-M (35 GB): the smallest " + "sizes, for PCs with little memory; 58 and 92 GB " + "downloads (the files include the n-gram table)", + "tag": "gyro-"}, "nvfp4": {"title": "Qwen3.8-Flash-Next (NVFP4)", "about": "4-bit NVFP4 experts, NVIDIA cards; a 128 GB download, " "~80 GB of RAM to keep every expert in RAM", "tag": "nvfp4-"}, } +GYRO_ROOM_GB = 4.0 # recommend() suggests a Gyro size only when VRAM + RAM exceed its memory figure by this much FALLBACK_CONTEXTS = [8192, 32768, 65536, 131072, 204800, 262144, 393216, 524288] BENCH_PROMPT = ("Write a short story (about 300 words) about a lighthouse keeper who finds a message in a bottle. " "Plain prose, no title.") @@ -773,6 +786,14 @@ class Strata: elif low_fits("IQ1_M"): fam, model, why = "coder", "IQ1_M", (f"{ram:.0f} GB of RAM is below the Coder's 32 GB, but the GPU's " f"{vram:.0f} GB make up for it (setup's low-RAM mode: slower)") + elif "Gyro-S" in models and ram + vram >= models["Gyro-S"]["ram_gb"] + GYRO_ROOM_GB: + # Gyro (agentionai): only where the sizes above do not fit. Their memory figure (Gyro-S 27.6 GB, Gyro-M 35 GB) + # is VRAM + RAM together and the system needs room beside it, so GYRO_ROOM_GB more is asked for here. + # Gyro-M when this PC has that much, else Gyro-S. + model = "Gyro-M" if ram + vram >= models["Gyro-M"]["ram_gb"] + GYRO_ROOM_GB else "Gyro-S" + fam, why = "gyro", (f"{ram:.0f} GB of RAM is below the Coder's 32 GB, but RAM + VRAM = {ram + vram:.0f} GB " + f"holds {model} ({models[model]['ram_gb']} GB of memory in total; the quality is lower " + "than the 2-3-bit sizes, and it needs the whole download on a fast SSD)") else: return {"family": None, "model": None, "why": f"{ram:.0f} GB of RAM: Strata needs 32 GB or more " "(the smallest model, the Coder, keeps ~23 GB of experts in " @@ -806,7 +827,8 @@ class Strata: tag = (fd.get("tag", "") + m).lower() verdict = None if ram is not None: - verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit" + have_gb = ram + vram if d.get("mem_total") else ram # Gyro: VRAM and RAM together + verdict = "fits" if have_gb >= d["ram_gb"] else "tight" if have_gb >= d["ram_gb"] - 8 else "does not fit" try: if d.get("budget") and S and hasattr(S, "unsloth_budget") and not S.unsloth_budget(m, ram): verdict = ("experimental: " if d.get("experimental") else "") + "fits (all of its experts in RAM)" @@ -816,7 +838,7 @@ class Strata: if ram >= d["ram_gb"] else "slow here: part of its experts in RAM, the rest read from the SSD (setup " "asks first)" if ram >= 48 else "does not fit") - elif S and S.low_ram_needed(m, ram) and S.low_ram_fits(m, ram, vram): + elif not d.get("mem_total") and S and S.low_ram_needed(m, ram) and S.low_ram_fits(m, ram, vram): verdict = "fits in the low-RAM mode (slower: the GPU holds part of the experts)" except Exception: # noqa: BLE001 pass diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 9758b41e..580bf274 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -548,5 +548,102 @@ class SplitArtifactTests(unittest.TestCase): self.assertEqual((pack / "experts.bin").read_bytes(), want) +class HadamardTests(unittest.TestCase): + """prism.hadamard (Agention's APR files) -> hadamard.txt; anything the engine cannot rotate is refused.""" + N_EMBD, N_FF = 256, 128 + + def meta(self, **kw): + names = ["blk.%d.ffn_%s_exps.weight" % (l, r) for l in range(2) for r in ("gate", "up", "down")] + m = {"prism.hadamard.version": 1, "prism.hadamard.block_size": 128, + "prism.hadamard.transform": "normalized-sylvester-walsh-hadamard", + "prism.hadamard.axis": "input-last-dimension", "prism.hadamard.sign_mode": "explicit", + "prism.hadamard.weight_names": names, + "prism.hadamard.sign_widths": [self.N_FF, self.N_EMBD], + "prism.hadamard.sign_values": [1, -1] * (self.N_FF // 2) + [-1, 1] * (self.N_EMBD // 2)} + m.update(kw) + return m + + def layout(self, gu=145, d=146): + return [(l, gu, d, 0, 0, None) for l in range(2)] + + def test_no_metadata(self): + self.assertIsNone(iq_pack.hadamard_spec({}, self.layout(), self.N_EMBD, self.N_FF)) + + def test_explicit_signs_written(self): + text = iq_pack.hadamard_spec(self.meta(), self.layout(), self.N_EMBD, self.N_FF) + lines = text.splitlines() + self.assertTrue(lines[0].startswith("# strata hadamard v1")) + self.assertEqual(lines[1], "block 128") + self.assertEqual(lines[2].split()[:4], ["signs", str(self.N_FF), "1", "-1"]) + self.assertEqual(len(lines[3].split()), 2 + self.N_EMBD) + self.assertEqual(lines[4:], ["layer 0 1 1 1", "layer 1 1 1 1"]) + + def test_refusals(self): + bad = { + "transform": self.meta(**{"prism.hadamard.transform": "dct"}), + "dense weight": self.meta(**{"prism.hadamard.weight_names": ["blk.0.attn_q.weight"]}), + "inverse": self.meta(**{"prism.hadamard.inverse_weight_names": ["token_embd.weight"]}), + "gate only": self.meta(**{"prism.hadamard.weight_names": ["blk.0.ffn_gate_exps.weight"]}), + "missing width": self.meta(**{"prism.hadamard.sign_widths": [self.N_EMBD], + "prism.hadamard.sign_values": [1] * self.N_EMBD}), + "bad sign": self.meta(**{"prism.hadamard.sign_values": [2] * (self.N_FF + self.N_EMBD)}), + "block": self.meta(**{"prism.hadamard.block_size": 96}), + } + for what, m in bad.items(): + with self.subTest(what): + got = iq_pack.hadamard_spec(m, self.layout(), self.N_EMBD, self.N_FF) + self.assertIsInstance(got, str) + self.assertFalse(got.startswith("# strata hadamard")) + got = iq_pack.hadamard_spec(self.meta(), self.layout(gu=42), self.N_EMBD, self.N_FF) + self.assertIn("Q2_0", got) + + +class NativeExpertsV5Tests(unittest.TestCase): + """The v5 mark (Hadamard-folded experts) rewrites only the tables the packer writes, v3 and v4.""" + ROWS = "0 145 146 0 100 1 2 3\n1 145 146 100 100 4 5 6\n" + + def table(self, version, tail="(n_expert 2, total 200)"): + return "# strata native experts v%s: layer gu_type d_type offset ... %s\n" % (version, tail) + self.ROWS + + def test_v3_and_v4_become_v5(self): + for v in ("3", "4"): + with self.subTest(v): + got = iq_pack.native_experts_v5(self.table(v)) + head, rest = got.split("\n", 1) + self.assertTrue(head.startswith("# strata native experts v5: layer gu_type")) + self.assertTrue(head.endswith("(n_expert 2, total 200) - v5: Hadamard-folded experts, see hadamard.txt")) + self.assertEqual(rest, self.ROWS) + + def test_other_versions_are_refused_by_name(self): + for v in ("2", "5", "6", "10"): + with self.subTest(v): + got = iq_pack.native_experts_v5(self.table(v)) + self.assertFalse(got.startswith("# strata native experts")) + self.assertIn("v%s" % v, got) + self.assertIn("v3 and v4", got) + got = iq_pack.native_experts_v5("# something else\n" + self.ROWS) + self.assertIn("without a version header", got) + + def test_packer_refuses_before_writing(self): + real = iq_pack.expert_layout + + def v6_layout(model, src): + layout, text, n_expert, offset = real(model, src) + return layout, text.replace("native experts v3:", "native experts v6:", 1), n_expert, offset + + with tempfile.TemporaryDirectory() as d: + root = Path(d) + paths = split_model(root, split_layer=False) + out = root / "pack" + with patch.object(iq_pack, "expert_layout", v6_layout), \ + patch.object(iq_pack, "hadamard_spec", return_value="# strata hadamard v1\nblock 32\n"): + rc, log = run_pack(paths[0], out) + self.assertEqual(rc, 1) + self.assertIn("native_experts.txt v6", log) + self.assertIn("only v3 and v4", log) + self.assertFalse((out / "native_experts.txt").exists()) + self.assertFalse((out / "hadamard.txt").exists()) + + if __name__ == "__main__": unittest.main() diff --git a/tools/test_setup_gyro.py b/tools/test_setup_gyro.py new file mode 100644 index 00000000..e4bcf627 --- /dev/null +++ b/tools/test_setup_gyro.py @@ -0,0 +1,80 @@ +"""The Gyro entries of setup's catalog (agentionai/Qwen3.8-Flash-Next-Gyro-GGUF): sizes, pins, the VRAM + RAM memory rule, +never a default, and the MCP server's recommendation naming them only where nothing else fits. Offline.""" +import pathlib +import sys +import unittest + +ROOT = pathlib.Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 +import strata_mcp as M # noqa: E402 + + +def hardware(ram, vram): + return {"ram_gb": ram, "gpus": [{"usable": True, "vram_gb": vram, "vendor": "nvidia", "index": 0, "name": "RTX"}], + "cpu": {"avx2": True}} + + +class GyroCatalog(unittest.TestCase): + def test_the_two_sizes_and_their_numbers(self): + self.assertEqual(setup.FAMILIES["gyro"]["file"].format(q="Gyro-S"), "Qwen3.8-Flash-Next-Gyro-S.gguf") + for model, name, download, memory in (("Gyro-S", "Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf", 58.5, 27.6), + ("Gyro-M", "Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf", 92.0, 35.0)): + d = setup.MODELS[model] + self.assertEqual(setup.model_file(setup.FAMILIES["gyro"], model, 1), name) + self.assertEqual((d["download_gb"], d["ram_gb"]), (download, memory)) + size, sha = setup.GYRO_FILES[name] + self.assertAlmostEqual(size / 1e9, download, delta=0.05) + self.assertEqual(len(sha), 64) + self.assertEqual(setup.model_shards(setup.FAMILIES["gyro"], model), 1) + self.assertIs(d.get("vision"), False) + self.assertTrue(d["mem_total"]) + self.assertEqual(d["families"], ("gyro",)) + + def test_pinned_revision_and_license(self): + repo = "agentionai/Qwen3.8-Flash-Next-Gyro-GGUF" + self.assertEqual(len(setup.HF_REVISIONS[repo]), 40) + self.assertIn(setup.HF_REVISIONS[repo], setup.FAMILIES["gyro"]["hf"]) + self.assertIn("Qwen Community License 1.0", setup.FAMILIES["gyro"]["license"]) + + def test_never_the_default_family(self): + self.assertEqual(setup.menu_families(False)[0], "qwen") + self.assertNotIn("gyro", setup.RECOMMENDED_SIZES) + + def test_memory_is_vram_plus_ram(self): + self.assertEqual(setup.mem_have("Gyro-S", 16.0, 12.0), 28.0) + self.assertEqual(setup.mem_have("Q2_0", 16.0, 12.0), 16.0) + names = ["Gyro-S", "Gyro-M"] + self.assertEqual(setup.recommended_size("gyro", names, 24.0, 12.0), "Gyro-M") # 36 GB + self.assertEqual(setup.recommended_size("gyro", names, 16.0, 12.0), "Gyro-S") # 28 GB + self.assertEqual(setup.recommended_size("gyro", names, 8.0, 8.0), "Gyro-S") # nothing fits: the first + + def test_mcp_table_matches(self): + for m in ("Gyro-S", "Gyro-M"): + for k in ("download_gb", "ram_gb", "arena_gb", "mem_total", "vision"): + self.assertEqual(setup.MODELS[m][k], M.FALLBACK_MODELS[m][k], (m, k)) + self.assertEqual(setup.FAMILIES["gyro"]["tag"], M.FALLBACK_FAMILIES["gyro"]["tag"]) + + def test_mcp_recommends_gyro_only_where_nothing_else_fits(self): + s = M.Strata(ROOT) + for ram, vram, family in ((64.0, 12.0, "qwen"), (48.0, 12.0, "qwen"), (32.0, 12.0, "coder")): + self.assertEqual(s.recommend(hardware(ram, vram))["family"], family, (ram, vram)) + got = s.recommend(hardware(20.0, 12.0)) # 32 GB in total, the Coder's 32 GB of RAM missing + self.assertEqual((got["family"], got["model"]), ("gyro", "Gyro-S")) + got = s.recommend(hardware(24.0, 16.0)) # 40 GB in total: the Coder fits in the low-RAM mode, so it wins + self.assertEqual((got["family"], got["model"]), ("coder", "IQ1_M")) + self.assertIsNone(s.recommend(hardware(12.0, 8.0))["family"]) + self.assertIsNone(s.recommend(hardware(16.0, 11.0))["family"]) # 27 GB: below Gyro-S's 27.6 + room + + def test_mcp_table_verdict_counts_vram(self): + s = M.Strata(ROOT) + fam = next(f for f in s.model_table(hardware(16.0, 16.0)) if f["family"] == "gyro") + by = {x["model"]: x for x in fam["sizes"]} + self.assertEqual(by["Gyro-S"]["on_this_pc"], "fits") + self.assertEqual(by["Gyro-M"]["on_this_pc"], "tight") + self.assertFalse(by["Gyro-S"]["images"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_menu.py b/tools/test_setup_menu.py index 59ed91a9..f6778a82 100644 --- a/tools/test_setup_menu.py +++ b/tools/test_setup_menu.py @@ -20,7 +20,7 @@ import setup # noqa: E402 class FamilyOrder(unittest.TestCase): def test_the_menu_order_on_nvidia(self): fams = setup.menu_families(False) + list(setup.OWN_PATH_FAMILIES) - self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth", "nvfp4", "qwen36"]) + self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth", "gyro", "nvfp4", "qwen36"]) def test_the_default_stays_the_first_family(self): self.assertEqual(setup.menu_families(False)[0], "qwen") @@ -29,7 +29,7 @@ class FamilyOrder(unittest.TestCase): def test_nvfp4_is_not_listed_on_amd_and_intel(self): fams = setup.menu_families(True) self.assertNotIn("nvfp4", fams) - self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth"]) + self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth", "gyro"]) self.assertIn("nvfp4", setup.FAMILIES) # --family nvfp4 still exists, and says why not def test_the_unsloth_line_names_the_alternative_on_amd_and_intel(self):