Empty the tree: UnbiasedStrata 2 starts over from PolyStrata
Every tracked file, .gitignore, .gitmodules and both submodules (llama.cpp at
3cf03257, llama-muse at 335916a) are removed so the next commit can import
PolyStrata v0.1.45-poly.1 unmodified and be the diff baseline of the fork.
UnbiasedStrata 1 remains at tags unbiasedstrata-1 (main, b124b59) and
unbiasedstrata-1-muse-spark-native (4c824e6).
Verified: git ls-files is empty; the working directory holds only .git.
This commit is contained in:
1 parent
b124b59ce4
commit
d1022a66f0
397 files changed
-114362
No files matched your search
@@ -1,2 +0,0 @@
|
||||
# launch scripts keep LF line endings wherever the repository is cloned
|
||||
*.sh text eol=lf
|
||||
@@ -1,2 +0,0 @@
|
||||
/build*/
|
||||
*.log
|
||||
@@ -1,4 +0,0 @@
|
||||
[submodule "third_party/llama.cpp"]
|
||||
path = third_party/llama.cpp
|
||||
url = https://github.com/ggml-org/llama.cpp.git
|
||||
shallow = true
|
||||
-1444
File diff suppressed because it is too large.
Load diff
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Niko1221 and the Strata contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,68 +0,0 @@
|
||||
# UnbiasedStrata build. Needs CMake 3.24+, a C++20 compiler and the CUDA toolkit. Nothing is downloaded.
|
||||
BUILD_DIR ?= build
|
||||
# One binary for every single NVIDIA GPU from Pascal up: GTX 10 (61), Volta (70), RTX 20 / GTX 16 (75), RTX 30 (86),
|
||||
# RTX 40 (89), RTX 50 (120). Pascal and Volta are the experimental build (STRATA_EXPERIMENTAL_SM60; needs a CUDA 12.x
|
||||
# toolkit, 13 dropped them): any arch below 75 in the list switches it on. sm_120 needs CUDA 12.8+. An arch the
|
||||
# installed nvcc cannot compile is dropped from the list with a note (CUDA 12.4 has no 120; CUDA 13 has no 61 / 70),
|
||||
# so the default builds on any toolkit; `make build CUDA_ARCHS=61` keeps a single-card build short
|
||||
# (docs/qwen36-port/pascal-build.md).
|
||||
CUDA_ARCHS ?= 61;70;75;86;89;120
|
||||
NVCC_ARCHS := $(shell nvcc --list-gpu-arch 2>/dev/null | sed 's/compute_//' | tr '\n' ' ')
|
||||
ifneq ($(NVCC_ARCHS),)
|
||||
CUDA_ARCHS_DROPPED := $(strip $(foreach a,$(subst ;, ,$(CUDA_ARCHS)),$(if $(filter $(firstword $(subst -, ,$(a))),$(NVCC_ARCHS)),,$(a))))
|
||||
ifneq ($(CUDA_ARCHS_DROPPED),)
|
||||
$(info make: nvcc cannot compile CUDA arch(s) $(CUDA_ARCHS_DROPPED); building without them)
|
||||
CUDA_ARCHS := $(subst $(eval) ,;,$(strip $(foreach a,$(subst ;, ,$(CUDA_ARCHS)),$(if $(filter $(firstword $(subst -, ,$(a))),$(NVCC_ARCHS)),$(a),))))
|
||||
endif
|
||||
endif
|
||||
SM60 := $(shell echo "$(CUDA_ARCHS)" | tr ';' '\n' | sed 's/-.*//' | grep -E '^[0-9]+$$' | awk '$$1 < 75 { print "ON"; exit }')
|
||||
SM60_FLAG := $(if $(SM60),-DSTRATA_EXPERIMENTAL_SM60=ON,)
|
||||
# capped: inside a container nproc reports the host's CPUs, not the container's quota
|
||||
JOBS ?= $(shell n=$$(nproc 2>/dev/null || echo 4); [ $$n -gt 16 ] && n=16; echo $$n)
|
||||
|
||||
.PHONY: build clean
|
||||
|
||||
build:
|
||||
@test -f third_party/llama.cpp/ggml/CMakeLists.txt || \
|
||||
{ echo "third_party/llama.cpp is empty: run 'git submodule update --init' first"; exit 1; }
|
||||
@git -C third_party/llama.cpp apply --check --reverse ../../patches/llama.cpp-qwen3-coder-any-argument-order.patch 2>/dev/null || \
|
||||
git -C third_party/llama.cpp apply ../../patches/llama.cpp-qwen3-coder-any-argument-order.patch
|
||||
cmake -S . -B $(BUILD_DIR) -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON \
|
||||
-DSTRATA_PORTABLE=ON -DSTRATA_MMQ_KQUANTS=ON -DSTRATA_BUILD_TESTS=OFF "-DCMAKE_CUDA_ARCHITECTURES=$(CUDA_ARCHS)" $(SM60_FLAG) $(CMAKE_EXTRA)
|
||||
cmake --build $(BUILD_DIR) -j $(JOBS) --target unbiased-strata
|
||||
@echo "built: $(BUILD_DIR)/unbiased-strata"
|
||||
|
||||
clean:
|
||||
rm -rf $(BUILD_DIR)
|
||||
|
||||
# Protocol and child supervision regressions; no CUDA/model required.
|
||||
.PHONY: test-frontend
|
||||
test-frontend:
|
||||
mkdir -p $(BUILD_DIR)/frontend-tests
|
||||
$(CXX) -std=c++20 -Wall -Wextra -Werror frontend/child_watch_test.cpp -o $(BUILD_DIR)/frontend-tests/child-watch-test
|
||||
$(BUILD_DIR)/frontend-tests/child-watch-test
|
||||
$(CXX) -std=c++20 -Wall -Wextra -Werror frontend/engine_test.cpp -o $(BUILD_DIR)/frontend-tests/engine-test
|
||||
$(BUILD_DIR)/frontend-tests/engine-test
|
||||
$(CXX) -std=c++20 -Wall -Wextra -Werror -pthread frontend/engine_backpressure_test.cpp -o $(BUILD_DIR)/frontend-tests/engine-backpressure-test
|
||||
$(BUILD_DIR)/frontend-tests/engine-backpressure-test
|
||||
|
||||
# Model-template compatibility; CPU only, after the regular build produced llama libraries.
|
||||
.PHONY: test-chat-parser
|
||||
test-chat-parser:
|
||||
@test -n "$(MODEL)" || { echo 'set MODEL to the first GGUF shard'; exit 2; }
|
||||
mkdir -p $(BUILD_DIR)/frontend-tests
|
||||
$(CXX) -std=c++20 -O0 -Ifrontend -Ithird_party/llama.cpp/include -Ithird_party/llama.cpp/common \
|
||||
-Ithird_party/llama.cpp/ggml/include -Ithird_party/llama.cpp/vendor -Ithird_party/llama.cpp/tools/mtmd \
|
||||
frontend/chat_parser_test.cpp \
|
||||
-o $(BUILD_DIR)/frontend-tests/chat-parser-test $(BUILD_DIR)/llama.cpp/tools/mtmd/libmtmd.a \
|
||||
$(BUILD_DIR)/llama.cpp/vendor/hash/libvendor-hash.a $(BUILD_DIR)/llama.cpp/common/libllama-common.a \
|
||||
$(BUILD_DIR)/llama.cpp/src/libllama.a $(BUILD_DIR)/llama.cpp/vendor/cpp-httplib/libcpp-httplib.a \
|
||||
$(BUILD_DIR)/ggml/src/libggml.a $(BUILD_DIR)/ggml/src/libggml-cpu.a $(BUILD_DIR)/ggml/src/libggml-base.a \
|
||||
$(BUILD_DIR)/llama.cpp/common/libllama-common-base.a -lpthread -ldl -lm
|
||||
$(BUILD_DIR)/frontend-tests/chat-parser-test "$(MODEL)"
|
||||
|
||||
# Against a running server: a request may ask for more tokens than the context has left (REGINA-112).
|
||||
.PHONY: test-serve
|
||||
test-serve:
|
||||
@test -n "$(PORT)" || { echo 'set PORT to a running server ([HOST:]PORT)'; exit 2; }
|
||||
python3 tests/python/serve_max_tokens_check.py $(PORT)
|
||||
@@ -1,261 +0,0 @@
|
||||
# UnbiasedStrata
|
||||
|
||||
[Strata](https://github.com/Niko1221/Strata)'s inference engine and llama.cpp's tokenizer, chat-template and
|
||||
HTTP code, built into one binary that serves Qwen3.8-Flash-Next (one 24 GB+ card, 128 GB RAM) and
|
||||
Qwen3.6-35B-A3B (any single NVIDIA card from 6 to 32 GB, Pascal or newer) over an OpenAI-style API. No
|
||||
network is needed to build or run it: rsync the source, run `make build`, start the binary. No Python, no
|
||||
installer.
|
||||
|
||||
## Requirements
|
||||
|
||||
| | Build | Run |
|
||||
| --- | --- | --- |
|
||||
| Network access | no | no |
|
||||
| CMake 3.24+, C++20 compiler (tested: g++ 13.3) | yes | no |
|
||||
| CUDA | toolkit 12.x (tested: 12.4 and 12.8; 12.8+ for RTX 50; CUDA 13 dropped Pascal and Volta) | `libcudart.so.12`, `libcublas.so.12`, `libcublasLt.so.12` and the NVIDIA driver |
|
||||
|
||||
Hardware: Linux, x86-64 with AVX2, one NVIDIA card.
|
||||
|
||||
| Model | Card | RAM |
|
||||
| --- | --- | --- |
|
||||
| Qwen3.8-Flash-Next | 24 GB or more (RTX 30, 40 or 50) | 128 GB |
|
||||
| Qwen3.6-35B-A3B | 6 to 32 GB, Pascal (GTX 10 series, sm_61) or newer, one card | enough to hold the experts the card does not: 32 GB for Q4_K_XL on an 11 GB card, 16 GB for IQ3_XXS (the table under Sizing) |
|
||||
|
||||
The model can be on a local disk or on a network volume; what the card does not hold is read into RAM at
|
||||
start, and what RAM does not hold is read from the file on a miss, so a slow store costs start-up time and,
|
||||
on the small cards, decode speed.
|
||||
|
||||
## Build
|
||||
|
||||
```
|
||||
rsync -a UnbiasedStrata/ host:UnbiasedStrata/ # or: git clone, then git submodule update --init
|
||||
ssh host 'cd UnbiasedStrata && make build' # produces build/unbiased-strata
|
||||
```
|
||||
|
||||
The tree is 6 MB plus the pinned llama.cpp submodule in `third_party/` (about 170 MB checked out). The
|
||||
build fetches nothing. `make build JOBS=N` sets the job count; `CUDA_ARCHS` defaults to
|
||||
`61;70;75;86;89;120`, one binary for every card from Pascal up, minus any architecture the installed
|
||||
`nvcc` cannot compile (12.4 has no 120, 13 has no 61 or 70; the build says what it dropped). `make build
|
||||
CUDA_ARCHS=61` builds for one card in about 3 minutes. An architecture below 75 in the list turns on
|
||||
`STRATA_EXPERIMENTAL_SM60`, the Pascal/Volta build (FP32 and dp4a paths; no tensor cores). The
|
||||
chat-parser patch in `patches/` is applied to the submodule at configure time.
|
||||
|
||||
## Run
|
||||
|
||||
```
|
||||
# Qwen3.8-Flash-Next
|
||||
./unbiased-strata --model /models/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf \
|
||||
--pack /models/pack-iq3-xxs --mtp /models/mtp
|
||||
# Qwen3.6-35B-A3B at the full 262,144-token context (the engine sizes itself to the card; see Sizing)
|
||||
./unbiased-strata --model /models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf \
|
||||
--pack /models/qwen36-q4 --mtp /models/qwen36-mtp-draft --ctx 262144 -- --kv q4_0
|
||||
```
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Endpoints | `POST /v1/chat/completions` (streaming or not), `GET /v1/models`, `GET /health`, on `127.0.0.1:8080` |
|
||||
| Options | `--ctx N` (32768), `--threads N` (default: physical cores, or half the CPU quota in a container), `--host`, `--port`, `--mmproj PATH`, `--vision-tokens N` (1024); engine flags after `--`: `--kv fp16\|q4_0\|int8`, `--vram-cap MiB` and `--ram-cap GiB` (plan as a smaller card or host), `--expert-cache N`, `--prompt-cache N` (checkpoints kept between requests) |
|
||||
| Sampling | greedy unless `temperature` > 0 |
|
||||
| Reasoning | returned as `reasoning_content`; `"reasoning_effort": "none"` turns it off |
|
||||
| Tools | OpenAI format (`tools`, `tool_calls`) |
|
||||
| Images | with `--mmproj`, OpenAI `image_url` parts holding a base64 `data:image/...` URL (PNG, JPEG, BMP or GIF), several per message |
|
||||
| Not supported | more than one GPU, batch requests |
|
||||
|
||||
Images: `--mmproj /models/mmproj-Qwen3.8-Flash-Next-BF16.gguf` loads the model's own vision encoder (from the same
|
||||
Hugging Face repository as the GGUF; 0.9 GB). The encoder runs on the CPU, so the card keeps its expert cache:
|
||||
about 25 s and 1,000 prompt tokens for a 1-megapixel screenshot on 8 threads, 0.2 s for a small image; a repeated
|
||||
image is served from a cache. `GET /v1/models` then lists `image` under `input_modalities`. Without `--mmproj` an
|
||||
image request is refused with a 400.
|
||||
|
||||
The engine runs as a child process. When it exits or its stall watchdog fires, the front end exits with a failure
|
||||
status, for a supervisor such as systemd (`Restart=on-failure`) to restart; `/health` and `/v1/models` answer 503
|
||||
while the engine is down. Reasoning streams as it is generated; content and tool calls are sent once the whole
|
||||
message is parsed, so a partial tool-call JSON never changes arguments already sent. `make test-frontend` checks
|
||||
the child handling and the protocol without a model; `make test-chat-parser MODEL=<shard 1>` checks the chat
|
||||
template and tool-call parsing against the real GGUF.
|
||||
|
||||
## The supported models
|
||||
|
||||
### Qwen3.8-Flash-Next
|
||||
|
||||
Qwen3.8-Flash-Next (125B parameters, mixture of experts), the full model at IQ3_XXS quantization, from
|
||||
[ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF),
|
||||
directory `IQ3_XXS`, revision `ed59f920`. No other model, quantization or pruned variant is supported. The
|
||||
draft (MTP) head is required.
|
||||
|
||||
Everything below must be on disk before start. Nothing is fetched.
|
||||
|
||||
| What | Size | SHA-256 or source |
|
||||
| --- | --- | --- |
|
||||
| `Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf` (weights) | 47.04 GB | `219ea929900dfa9ef091f3aa473fdba6874b65fcb36526d7d851ac9e95856d15` |
|
||||
| `Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf` (n-gram table), beside shard 1 | 28.80 GB | `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113` |
|
||||
| Pack: `index.txt`, `dense.bin`, `native_experts.txt`, `conversions.json`, `expert-profile.bin` | 1.5 GB | made once with upstream's tools; not published yet |
|
||||
| Draft head: `experts.bin`, `dense.bin`, `dense.txt`, `draft_vocab.bin` | 0.8 GB | made once with upstream's tools; not published yet |
|
||||
|
||||
About 78 GB in total. The commands that make the pack and draft head, and the SHA-256 of every file they
|
||||
produce, are in [UPSTREAM.md](UPSTREAM.md).
|
||||
|
||||
### Qwen3.6-35B-A3B
|
||||
|
||||
Qwen3.6-35B-A3B (35B parameters, 3B active: 40 layers, 256 experts of which 8 route per token, 30 Gated
|
||||
DeltaNet layers and 10 full-attention layers, 262,144-token context), unsloth's UD quantizations from
|
||||
[unsloth/Qwen3.6-35B-A3B-GGUF](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF) and
|
||||
[unsloth/Qwen3.6-35B-A3B-MTP-GGUF](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-MTP-GGUF). Two
|
||||
quantizations, with the pack and draft pack made by this repository's own tools (`tools/iq_pack.py`,
|
||||
`tools/make_profile.py`, `tools/mtp_qwen36_pack.py`; commands and every file's SHA-256 in
|
||||
[UPSTREAM.md](UPSTREAM.md)):
|
||||
|
||||
| What | Size | SHA-256 |
|
||||
| --- | --- | --- |
|
||||
| `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf`, **the default** (K-quants: the fast AVX2 path for the experts the CPU computes) | 22.36 GB | `707a55a8a4397ecde44de0c499d3e68c1ad1d240d1da65826b4949d1043f4450` |
|
||||
| `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` from the **-MTP** repository (the same trunk plus the draft block `blk.40`; serves as the model file too) | 22.85 GB | `55983c5a75a1ab969824077b3bb3de4146e82a9234072b48ad4e8f92ad3fe9f1` |
|
||||
| `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf`, for 6 and 8 GB cards | 13.21 GB | `9c964e657212fea1f24905dd7b0a89b82fd807d19fab0b41da14251b07b88fbe` |
|
||||
| Pack `qwen36-q4/` or `qwen36-iq3/` (`index.txt`, `dense.bin`, `native_experts.txt`, `conversions.json`, `expert-profile.bin`, `tokenizer/`) | 65 MB | per file in UPSTREAM.md |
|
||||
| Draft pack `qwen36-mtp-draft/` (`experts.bin`, `dense.bin`, `dense.txt`, `native_experts.txt`, `mtp.json`, `draft_vocab.bin`), cut from the -MTP file's draft block; serves both quantizations | 0.5 GB | per file in UPSTREAM.md |
|
||||
|
||||
No other Qwen3.6 file is accepted: the IQ4_XS-MTP file's draft block (Q3_K experts) and the 27B dense model
|
||||
are refused by name. Images work with `--mmproj` and the model's own encoder (`mmproj-F16.gguf` from the -MTP repository,
|
||||
899 MB); the encoder runs on the CPU, so the first use of a full-screen image costs 24 s on an i9-9900K and
|
||||
about 70 s on a Ryzen 7 1700, and repeats are served from a cache.
|
||||
|
||||
#### Sizing
|
||||
|
||||
At start the engine prints its plan for the card it finds: the fixed set for the requested context (the
|
||||
dense weights, the drafter, the KV cache, the session, a reserve), then every remaining megabyte as expert
|
||||
slots, filled by the route-trace profile's rank. If the fixed set does not fit, the KV cache is streamed
|
||||
to RAM above a resident window, then the context is lowered toward 131,072, then the engine refuses with
|
||||
the numbers and suggests the IQ3_XXS file. It never silently picks a shorter context. The experts that do
|
||||
not fit in VRAM are read from pinned RAM when the host has it, else from the file on a miss; `/health`
|
||||
reports the VRAM hits, RAM reads and file reads per request. `--vram-cap` and `--ram-cap` make a big card
|
||||
plan like a small one.
|
||||
|
||||
| VRAM | Q4_K_XL at 262,144, q4_0 KV: fixed set, experts resident | IQ3_XXS: fixed set, experts resident |
|
||||
| --- | --- | --- |
|
||||
| 24 GB (RTX 4090) | 4,823 MiB; 9,980 of 10,240 (97%) | 4,331 MiB; all 10,240, 8.8 GB spare |
|
||||
| 11 GB (GTX 1080 Ti) | 4,461 MiB; 3,575 (35%) | 4,019 MiB; 6,748 (66%) |
|
||||
| 8 GB | 1,949 (19%) | 3,873 (38%) |
|
||||
| 6 GB | 598 (6%) | 1,486 (15%) |
|
||||
|
||||
The 24 GB row is measured; the others are the planner's figures from the same files under `--vram-cap`
|
||||
(docs/qwen36-port/step2-notes.md section 5, step4-pack.md section 5).
|
||||
|
||||
**RAM is a requirement, not a tier.** The engine assumes the card and the host RAM together hold the expert set;
|
||||
every expert the card does not hold is pinned in RAM. What the host must hold is the expert bytes minus the card's
|
||||
share, plus the engine's own 3 to 4 GB and the OS:
|
||||
|
||||
| VRAM | Q4_K_XL experts off the card | RAM to have | IQ3_XXS experts off the card | RAM to have |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 24 GB | none | 8 GB | none | 8 GB |
|
||||
| 16 GB | 8 GB | 16 GB | none | 8 GB |
|
||||
| 11 GB | 13 GB | 32 GB (24 is tight) | 4 GB | 12 GB |
|
||||
| 8 GB | 15 GB | 32 GB | 7 GB | 16 GB |
|
||||
| 6 GB | 17 GB | 32 GB | 9 GB | 16 GB |
|
||||
|
||||
Below those figures the engine still starts, maps the rest from the file and says so in its plan, but that is a
|
||||
fallback, not a supported configuration: measured once on the GTX 1080 Ti at Q4_K_XL under a 12 GiB memory bound,
|
||||
decode fell from 52 tokens/s to 12 to 15, the NVMe's rate, with about 12 experts per token read from the file.
|
||||
|
||||
## Status
|
||||
|
||||
Checked on one machine: RTX 3090, 32 vCPUs of an EPYC 7763, 125 GB RAM, CUDA 12.8, in a container.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Build | from an rsynced tree with no git metadata; the binary holds no download code |
|
||||
| Serving | chat, streaming, reasoning, tool calls; a coding agent (pi) wrote and ran a program through it |
|
||||
| RTX 4090 (24 GB), 82 GB RAM, Debian, bare metal | serving with tool calls and images, through pi (file attachments and clipboard paste) and curl, over several days of use |
|
||||
| Start from local disk | 19 s with the files in the OS file cache |
|
||||
| Start from a network volume | 12 min for 76 GB (S3-backed RunPod volume, 120 to 330 MB/s). The volume refused reads twice with "cannot allocate memory"; the loader retried and went on |
|
||||
| Not tested | RTX 50 cards; a cold start from local disk |
|
||||
|
||||
Qwen3.6-35B-A3B, checked on the RTX 4090 (VM, 16 vCPU i9-9900K, 62 GB RAM, CUDA 12.4):
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Correctness | the engine's logits held to a numpy reference and to llama.cpp at every position of the real files (greedy top-1 64/64 on three prompts at IQ3_XXS, 61-64/64 at Q4_K_XL, mean KL 1e-3 to 7e-3); the expert-miss path (what every card below 24 GB runs on) held with the same prompts under `--vram-cap` |
|
||||
| Serving | chat, streaming of reasoning and answer per token, tool calls streamed and not, multi-turn prompt checkpoints at 262,144 context, at 24 GB, under an 11 GB cap (Q4_K_XL) and a 6 GB cap (IQ3_XXS); a coding agent (pi) wrote and ran a program through it |
|
||||
| Pascal | built and unit-tested on a GTX 1080 Ti (sm_61: every kernel parity test, the pack, the drafter, the verify window); the expert-miss path held to llama.cpp's logits there too |
|
||||
|
||||
Speed against llama.cpp on the same card (RTX 4090, `--vram-cap` for the smaller budgets, 262,144 context,
|
||||
no RAM cap, drafter on; llama.cpp with `--n-cpu-moe N` chosen to fit the same budget, no speculation). Decode
|
||||
is a 1,200-token answer to a 2.4K prompt; prefill is a 32K prompt. Tokens/s, engine / llama.cpp:
|
||||
|
||||
| Budget | Q4_K_XL decode | Q4_K_XL prefill | IQ3_XXS decode | IQ3_XXS prefill |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 24 GB | 251 / 159 (1.6x) | 4,319 / 8,604 (0.50x) | 318 / 167 (1.9x) | 4,426 / 8,245 (0.54x) |
|
||||
| 16 GB | 180 / 41 (4.4x) | 4,232 / 1,798 (2.4x) | 319 / 44 (7.3x) | 4,401 / 2,637 (1.7x) |
|
||||
| 12 GB | 122 / 38 (3.3x) | 3,877 / 1,475 (2.6x) | 256 / 40 (6.4x) | 4,381 / 2,223 (2.0x) |
|
||||
| 11 GB | 104 / 37 (2.8x) | 3,723 / 1,420 (2.6x) | 234 / 39 (6.1x) | 4,375 / 2,137 (2.1x) |
|
||||
| 8 GB | 64 / 33 (2.0x) | 3,003 / 1,212 (2.5x) | 135 / 34 (4.0x) | 4,320 / 1,854 (2.3x) |
|
||||
| 6 GB | 45 / 30 (1.5x) | 517 / 1,108 (0.47x) | 81 / 32 (2.5x) | 1,121 / 1,713 (0.65x) |
|
||||
|
||||
The llama.cpp 24 GB Q4_K_XL row is at 131,072 context; it does not load at 262,144 with every layer on the card.
|
||||
Prompt processing is the weak side: with every expert resident llama.cpp is twice as fast, and at 6 GB the engine
|
||||
spends the prompt copying experts to the card. Full tables, profiler windows and plots are in the regina
|
||||
repository's `analysis/qwen36-35b-single-gpu-ladder/engine-4090/`.
|
||||
|
||||
On the GTX 1080 Ti (VM, 14 vCPU of a Ryzen 7 1700, 52 GB RAM), against llama.cpp on the same card and host
|
||||
(`--n-cpu-moe N` at the lowest N that fits each budget, 8 threads, no speculation, the model file in RAM).
|
||||
262,144 context on both sides. Tokens/s, engine / llama.cpp:
|
||||
|
||||
| Budget | Q4_K_XL decode | Q4_K_XL prefill 3.1K | Q4_K_XL prefill 32K | IQ3_XXS decode | IQ3_XXS prefill 3.1K | IQ3_XXS prefill 32K |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| 11 GB (the card) | 66 / 28 (2.4x) | 941 / 570 (1.7x) | 462 / 545 (0.85x) | 81 / 33 (2.5x) | 910 / 904 (1.0x) | 453 / 714 (0.63x) |
|
||||
| 8 GB (`--vram-cap 8192`) | 54 / 25 (2.1x) | 911 / 488 (1.9x) | 442 / 487 (0.91x) | 69 / 28 (2.5x) | 900 / 747 (1.2x) | 453 / 637 (0.71x) |
|
||||
| 6 GB (`--vram-cap 6144`) | 42 / 24 (1.8x) | 361 / 452 (0.80x) | 265 / 460 (0.58x) | 55 / 24 (2.3x) | 748 / 614 (1.2x) | 437 / 562 (0.78x) |
|
||||
|
||||
Decode is 1.8 to 2.5 times llama.cpp; the GPU computes 85% of the decode window against llama.cpp's 39 to 45%.
|
||||
A long prompt is slower than llama.cpp at every budget on this card. The draft head is worth a third of the decode
|
||||
speed (49 tokens/s without drafts at Q4_K_XL on the full card). Tables and plots: regina
|
||||
`analysis/qwen36-35b-single-gpu-ladder/engine-1080ti/` and `llama-1080ti-52g/`.
|
||||
|
||||
Speed, one run of each, same machine and model files, greedy sampling, reasoning off. Generation is the mean
|
||||
of 8 different prompts of 400 tokens; prompt speed is the mean of 2 different prompts of about 20,000 tokens.
|
||||
|
||||
| | Generation, tokens/s | Prompt, tokens/s |
|
||||
| --- | --- | --- |
|
||||
| This fork | 107 (87 to 116) | 2,483 |
|
||||
| Upstream, with `--pool-workers 15 --ple-io ram` | 78 (61 to 93) | 2,439 |
|
||||
| Upstream, arguments as its installer writes them | 20 (16 to 21) | 2,368 |
|
||||
|
||||
Upstream as installed started 127 CPU workers on the container's 32 vCPUs and read the n-gram table from
|
||||
disk per token; the middle row removes both. The remaining gap to the fork is not explained yet: the two
|
||||
builds differ in compile flags and in how the n-gram table is held in RAM, and each row is a single run.
|
||||
|
||||
## Known problems
|
||||
|
||||
- Text in a message that looks like a control token (`<think>`, `<tool_call>`) is tokenized as that control
|
||||
token. Upstream's tokenizer keeps it as plain text.
|
||||
- Replies are not reproducible token for token between runs or between this fork and upstream, even with
|
||||
greedy sampling, so "same output" cannot be checked by comparing text.
|
||||
For Qwen3.6-35B-A3B the cause is traced: an expert the card does not hold is computed by a different
|
||||
kernel on the CPU, and the cache keeps changing which experts those are for the first few requests; replies
|
||||
diverge only where two tokens are within about 0.3 logits, and every state holds to llama.cpp's logits.
|
||||
`--adapt-every 0 --suffix-draft 0` makes a request repeat token for token. `--pcie-frac 1.0` does too
|
||||
only while a layer misses fewer than 16 experts per window; past that the rest are computed on the CPU.
|
||||
- Qwen3.6-35B-A3B: between user turns the prompt cache reuses the previous prompt but not the previous reply,
|
||||
because the model's template re-renders an earlier reply without its reasoning. Tool loops reuse nearly
|
||||
everything (1,867 of 1,948 tokens in a pi session); `chat_template_kwargs.preserve_thinking` with
|
||||
`reasoning_content` sent back reuses the reply too, at the cost of keeping old reasoning in context.
|
||||
A tool call arrives as one delta, not streamed. Images are checked on one screenshot only, and not
|
||||
against llama.cpp; the RTX 50 and Volta builds have not
|
||||
run on a card. Prompt processing is slower than llama.cpp with every expert on the card, at 6 GB, and for long
|
||||
prompts on a GTX 1080 Ti.
|
||||
|
||||
## Compared with upstream Strata (6f32ec0)
|
||||
|
||||
| | Upstream | This fork |
|
||||
| --- | --- | --- |
|
||||
| Engine source (`src/`, `include/`) | 272 files | 58 files changed for the Qwen3.6 port (the model geometry read from the GGUF, the plain-residual block, dense attention, the SiLU-gated DeltaNet, the expert kernels for the UD quantizations, the VRAM planner, the drafter pack) plus retrying reads from slow stores; docs/qwen36-port/ has the per-step notes |
|
||||
| Build | clones llama.cpp during CMake | pinned submodule, fetches nothing; one patch, applied at configure time: tool-call arguments in any order (see UPSTREAM.md) |
|
||||
| Setup | Python installer downloads the model and builds the pack and draft head | none; files must already exist |
|
||||
| Server | Python | C++, in the same binary (`frontend/`), with the image encoder from llama.cpp's `mtmd` |
|
||||
| Python | 33,745 lines | 0 |
|
||||
| C, C++ and CUDA | 208,254 lines (with tests and the Intel port) | 84,086 lines |
|
||||
| Tracked files | 851, 27 MB | 292, 6 MB |
|
||||
| Configurations | several models, NVIDIA, AMD and Intel, Linux and Windows, multi-GPU | two models, one NVIDIA card (Pascal to RTX 50), Linux |
|
||||
|
||||
## Credits and licence
|
||||
|
||||
MIT, as upstream. The engine is the work of Niko1221 and the Strata contributors; see [LICENSE](LICENSE) and
|
||||
[UPSTREAM.md](UPSTREAM.md). llama.cpp and ggml are MIT. The model files have their own licences.
|
||||
-122
@@ -1,122 +0,0 @@
|
||||
# Relationship to upstream
|
||||
|
||||
## Sources
|
||||
|
||||
| What | Where | Version |
|
||||
| --- | --- | --- |
|
||||
| Engine | https://github.com/Niko1221/Strata | commit `6f32ec070f23ced9f50e704d854d775da52591ab`, engine 0.1.39 |
|
||||
| ggml (CPU backend, CUDA matrix kernels) | https://github.com/ggml-org/llama.cpp, as the submodule `third_party/llama.cpp` | commit `3cf03257f219afbe7334045ff7c6a06ac68c627d`, the one upstream Strata pins |
|
||||
|
||||
The first commit of this repository is the upstream snapshot as published. One file was not imported:
|
||||
`bench/results/2026-09-30-community-rtx-5090/engine.log`, which upstream's own ignore rules exclude.
|
||||
`git diff <first commit> HEAD -- src include CMakeLists.txt` shows every change to the engine and its build.
|
||||
|
||||
## What this fork changed
|
||||
|
||||
- **Build:** ggml is taken from the submodule. Upstream cloned llama.cpp during the build.
|
||||
- **Removed:** the Python installer and launchers, the Python server and web app, the Python tools, the
|
||||
Intel SYCL port, Docker files, benchmark results, the test suite, translations, and all docs except
|
||||
`docs/upstream/DETAILS.md` and the paper.
|
||||
- **Added:** `frontend/`, the C++ front end (tokenizer, chat template, output parser and HTTP API, using
|
||||
llama.cpp's code from the submodule), and a build target that links it with the engine into one binary.
|
||||
- **ggml / llama.cpp common (`third_party/llama.cpp`):** one change, kept as
|
||||
`patches/llama.cpp-qwen3-coder-any-argument-order.patch`, applied to the submodule's working tree at CMake
|
||||
configure time (and by `make build`); Qwen3.6's template routes to the same parser:
|
||||
the Qwen3-Coder tool-call grammar accepts a call's arguments in any order. Upstream requires the
|
||||
required arguments first; Qwen3.8 Flash-Next often writes the optional ones first (`limit`, `offset`,
|
||||
`path`), and because the grammar's tool-call group is optional and has no end anchor, such a call was
|
||||
dropped silently: the client got `finish_reason=stop` and an empty answer (2026-10-08).
|
||||
- **Engine source (`src/`, `include/`):** three changes, all for loading from a slow or remote store. The
|
||||
engine's own program is compiled into the binary with its entry point renamed; the front end starts it
|
||||
as a child process.
|
||||
- `include/strata/platform/robust_read.hpp` (new): positional reads that retry an error a network store
|
||||
gives for a moment, and lower the number of parallel readers while it does.
|
||||
- `src/core/expert_source.cpp`: the expert loader reads through it, reports progress, and names the file,
|
||||
offset and error when it fails.
|
||||
- `src/kernels/ngram.cpp`: `--ple-io ram` reads the n-gram table into memory of its own with 16 readers,
|
||||
where upstream locked the file mapping (which fails under a container's `ulimit -l`).
|
||||
|
||||
Code paths for other models, AMD cards and Windows are still present in the engine source. They are not
|
||||
built by `make build`, not tested and not supported here.
|
||||
|
||||
## Prepared model files
|
||||
|
||||
The pack and the draft head are produced once with upstream Strata's tools at the commit above. These are
|
||||
the commands that were used, with `U` an upstream checkout, `G` this repository's
|
||||
`third_party/llama.cpp/gguf-py`, and Python 3 with `numpy` and `regex`:
|
||||
|
||||
```
|
||||
export STRATA_GGUF_PY=$G
|
||||
# the pack, from the model's first shard (the second must be beside it)
|
||||
python $U/tools/iq_pack.py --gguf Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf --out pack-iq3-xxs
|
||||
cp $U/data/expert-profile.bin pack-iq3-xxs/
|
||||
|
||||
# the draft head, from the original checkpoint's 31 draft-head tensors (about 5 GB, fetched over HTTP)
|
||||
python $U/tools/mtp_fetch.py fetch --out mtp-bf16
|
||||
python $U/tools/mtp_fetch.py verify --out mtp-bf16
|
||||
python $U/tools/mtp_pack.py --src mtp-bf16 --experts q2_0 --out mtp-bf16/mtp-q2_0.gguf
|
||||
python $U/tools/mtp_rt.py --gguf mtp-bf16/mtp-q2_0.gguf --out mtp
|
||||
cp $U/data/draft_vocab.bin mtp/
|
||||
```
|
||||
|
||||
The model shards used were revision `ed59f92082b1e93c0e96d60a8b11aab089b52f09` of
|
||||
ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF, verified against their published SHA-256 checksums. The
|
||||
prepared files have not been published yet. Building them twice gave the same bytes; their SHA-256:
|
||||
|
||||
```
|
||||
68beec784ea64aeecace591b33debb8ba331a9ad257a3e1b68c5c701dd22b267 pack-iq3-xxs/conversions.json
|
||||
d2af3d8331e5c7a1985d1d589747230f9d56719a6d33c7cddc9ee6b81cde6b13 pack-iq3-xxs/dense.bin
|
||||
8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf pack-iq3-xxs/expert-profile.bin
|
||||
1afe12b36cd2d13bf122b741fa0e81e1f751319cc3c451e54ba75524d825f148 pack-iq3-xxs/index.txt
|
||||
ae28cf7a2a1c9063c4b55d6c8cf86d4d079dcddcf597f9e8697c9157d462c0ee pack-iq3-xxs/native_experts.txt
|
||||
c724dc0b0822ada5d2977bf5bde821605feabaa64ea2e0045b67ca656329070a mtp/dense.bin
|
||||
991456cf4eb266eb8a888c349e548d11bc640f5dbd9149439aa9786af0f732fd mtp/dense.txt
|
||||
b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91 mtp/draft_vocab.bin
|
||||
09398406be61f1f54c93861f449e48b8df0bfccbc9ec9b2b7636775a6ea9244f mtp/experts.bin
|
||||
```
|
||||
|
||||
## Prepared files for Qwen3.6-35B-A3B
|
||||
|
||||
Made with this repository's own tools (Python 3 with `numpy`; `STRATA_GGUF_PY` at `third_party/llama.cpp/gguf-py`),
|
||||
from unsloth's files: `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` and `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` of
|
||||
[unsloth/Qwen3.6-35B-A3B-GGUF](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF), and the `-MTP` repository's
|
||||
`Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (41 blocks; the draft block is `blk.40`) for the draft pack.
|
||||
|
||||
```
|
||||
export STRATA_GGUF_PY=$PWD/third_party/llama.cpp/gguf-py
|
||||
# the pack, one per model file (the tokenizer, the dense weights' index, the expert table, the route profile)
|
||||
python3 -I tools/iq_pack.py --gguf Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --out qwen36-q4
|
||||
python3 -I tools/iq_pack.py --gguf Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --out qwen36-iq3
|
||||
cp data/qwen36-expert-profile.bin qwen36-q4/expert-profile.bin # tools/make_profile.py from the route trace
|
||||
cp data/qwen36-expert-profile.bin qwen36-iq3/expert-profile.bin
|
||||
# the draft pack, from the -MTP file's draft block; serves either trunk
|
||||
python3 -I tools/mtp_qwen36_pack.py --gguf Qwen3.6-35B-A3B-UD-Q4_K_XL-MTP.gguf --out qwen36-mtp-draft
|
||||
```
|
||||
|
||||
`--draft-vocab none` leaves `draft_vocab.bin` out (the drafter then scores the whole vocabulary: a few percent
|
||||
higher acceptance, 345 MiB more VRAM for the head). Building twice gives the same bytes. SHA-256:
|
||||
|
||||
```
|
||||
9c964e657212fea1f24905dd7b0a89b82fd807d19fab0b41da14251b07b88fbe Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf
|
||||
707a55a8a4397ecde44de0c499d3e68c1ad1d240d1da65826b4949d1043f4450 Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf
|
||||
55983c5a75a1ab969824077b3bb3de4146e82a9234072b48ad4e8f92ad3fe9f1 Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf (the -MTP repository's file)
|
||||
7c20e11993ff853fe5698843d610b2a87927b04f9a4607551f4e023a39bc71ba qwen36-q4/conversions.json
|
||||
53467f9b49bbc57d570eb8802125144dd4b4d7fd6a658d685ef72005d75a5f4f qwen36-q4/dense.bin
|
||||
eb2ed6c8d86ebe0c16bb7a09af6c24fc4059627cc95e35def07c41568a30283c qwen36-q4/expert-profile.bin
|
||||
1a4725f13e24691a3d6fd10dba4bb6cb217c4831ff8d5529865fc01f39413c79 qwen36-q4/index.txt
|
||||
257d84e2d36a2e6572cd0dd8382283defe28bc07c2c97ece22ab6c1bd2f5bff4 qwen36-q4/native_experts.txt
|
||||
39bf397e3fb8591ab84cb9142dbd43f665c3bff456e9772c47dc04db5ca28195 qwen36-iq3/conversions.json
|
||||
53467f9b49bbc57d570eb8802125144dd4b4d7fd6a658d685ef72005d75a5f4f qwen36-iq3/dense.bin
|
||||
eb2ed6c8d86ebe0c16bb7a09af6c24fc4059627cc95e35def07c41568a30283c qwen36-iq3/expert-profile.bin
|
||||
685d475659736b415a5801413f116a4371970d3cb24b16e53625b98019895c73 qwen36-iq3/index.txt
|
||||
820053214b08d3eab1378705fb7c345a724ed0fe16544df07b2f519423bb10e8 qwen36-iq3/native_experts.txt
|
||||
4a93092f5716d289367b97ce107d8b08b2236a8e1954bc7f746881875c73d03a qwen36-mtp-draft/dense.bin
|
||||
dd5990d0ef0926252cad59090fa1d00f138db2e3f316eb96691db83940cde339 qwen36-mtp-draft/dense.txt
|
||||
b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91 qwen36-mtp-draft/draft_vocab.bin
|
||||
9126741d7e98f0e470cd04bf7ce3c91a89c08c116af02aa2d8d666c4195fdb15 qwen36-mtp-draft/experts.bin
|
||||
1e5ad8c088196bc95b49534ce68db9c278635c8a68f7b605ef1776589dea29d7 qwen36-mtp-draft/mtp.json
|
||||
048604044d93d7dd4e4e1140deba8ccf681b5c7c11e330e9434a570af42bcfa2 qwen36-mtp-draft/native_experts.txt
|
||||
```
|
||||
|
||||
(`dense.bin` is byte-identical between the two packs: the dense weights unsloth keeps unquantized are the same in
|
||||
both files. The tokenizer directory's files are listed in `qwen36-*/index.txt`.)
|
||||
@@ -1,110 +0,0 @@
|
||||
# Opt-in HIP configuration. Strata's CUDA-shaped kernels target wave32 RDNA2 / RDNA3 / RDNA4 (64 KiB LDS per
|
||||
# workgroup, a signed dot4 instruction). CMake/compiler discovery stays machine-independent; pass CMAKE_HIP_COMPILER when it
|
||||
# is not on PATH.
|
||||
if(NOT DEFINED CMAKE_HIP_ARCHITECTURES OR CMAKE_HIP_ARCHITECTURES STREQUAL "")
|
||||
set(CMAKE_HIP_ARCHITECTURES gfx1100 CACHE STRING "Strata HIP target architecture(s), e.g. gfx1100 or gfx1100;gfx1201")
|
||||
endif()
|
||||
# Validated on real cards: gfx1100 (RX 7900 XT / XTX) and gfx1201 (RX 9070 / 9070 XT, Radeon AI PRO R9700) by the
|
||||
# maintainers; gfx1101 (RX 7800 XT, #254) and gfx1200 (RX 9060 XT, #256) by their owners. gfx1102 (RX 7600) has the
|
||||
# same LDS limit and dot4 instruction and passed ctest (#192), but no model run has been reported yet. RDNA2 gfx1030 (RX 6800 / 6900) has the
|
||||
# same LDS limit and wave32 but an older dot4 instruction (v_dot4_i32_i8, hip_compat/intrinsics.hpp); a community
|
||||
# report ran it (#311), the maintainers have not.
|
||||
set(_strata_hip_validated gfx1100 gfx1201)
|
||||
set(_strata_hip_community gfx1101 gfx1200)
|
||||
set(_strata_hip_unvalidated gfx1012 gfx1102 gfx1030 gfx1031)
|
||||
# CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use
|
||||
# spaces, which foreach(IN LISTS) would otherwise treat as one element.
|
||||
string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}")
|
||||
set(STRATA_HIP_ARCH_LIST "")
|
||||
foreach(_arch IN LISTS _strata_hip_norm)
|
||||
if(_arch STREQUAL "")
|
||||
continue()
|
||||
endif()
|
||||
string(REGEX REPLACE ":.*$" "" _base "${_arch}") # gfx1100:xnack- -> gfx1100
|
||||
if(_base IN_LIST _strata_hip_validated)
|
||||
elseif(_base IN_LIST _strata_hip_community)
|
||||
message(STATUS "Strata HIP: ${_base} was validated by community reports (docs/AMD_HIP.md)")
|
||||
elseif(_base IN_LIST _strata_hip_unvalidated)
|
||||
message(WARNING "Strata HIP: ${_base} builds, but it is not validated on a real card yet; please report results")
|
||||
else()
|
||||
message(FATAL_ERROR
|
||||
"Strata HIP supports wave32 gfx1100, gfx1101, gfx1200 and gfx1201 (unvalidated: ${_strata_hip_unvalidated}); "
|
||||
"CMAKE_HIP_ARCHITECTURES is '${CMAKE_HIP_ARCHITECTURES}'")
|
||||
endif()
|
||||
list(APPEND STRATA_HIP_ARCH_LIST "${_base}")
|
||||
endforeach()
|
||||
list(REMOVE_DUPLICATES STRATA_HIP_ARCH_LIST)
|
||||
if(NOT STRATA_HIP_ARCH_LIST)
|
||||
message(FATAL_ERROR "Strata HIP: CMAKE_HIP_ARCHITECTURES is empty")
|
||||
endif()
|
||||
# The compiled architectures reach the runtime device check (src/core/device.cu) as "gfx1100,gfx1201": a binary
|
||||
# carried to a card it has no code for stops at startup with a clear message instead of "invalid device function".
|
||||
string(REPLACE ";" "," STRATA_HIP_ARCHS "${STRATA_HIP_ARCH_LIST}")
|
||||
|
||||
enable_language(HIP)
|
||||
find_package(hip CONFIG REQUIRED)
|
||||
find_package(hipblas CONFIG REQUIRED)
|
||||
# Older distro hipBLAS has no workspace API. The compatibility shim uses
|
||||
# rocBLAS directly for that version; newer hipBLAS keeps its existing path.
|
||||
set(STRATA_HIP_BLAS_TARGETS roc::hipblas)
|
||||
if(hipblas_VERSION VERSION_LESS "1.0")
|
||||
find_package(rocblas CONFIG REQUIRED)
|
||||
list(APPEND STRATA_HIP_BLAS_TARGETS roc::rocblas)
|
||||
endif()
|
||||
find_package(hipblaslt CONFIG QUIET)
|
||||
|
||||
if(NOT TARGET hip::host)
|
||||
message(FATAL_ERROR "The ROCm hip CMake package did not provide hip::host")
|
||||
endif()
|
||||
if(NOT TARGET roc::hipblas)
|
||||
message(FATAL_ERROR "The ROCm hipblas CMake package did not provide roc::hipblas")
|
||||
endif()
|
||||
if(TARGET roc::hipblaslt)
|
||||
set(STRATA_HIPBLASLT_AVAILABLE ON)
|
||||
else()
|
||||
set(STRATA_HIPBLASLT_AVAILABLE OFF)
|
||||
message(STATUS "Strata: hipBLASLt not found; solution-table dispatch is unavailable")
|
||||
endif()
|
||||
|
||||
# HIP's link step produces a PIE; make Strata and ggml objects PIC for the ROCm linker.
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(STRATA_HIP_COMPAT_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include/strata/hip_compat")
|
||||
add_library(strata_hip_runtime INTERFACE)
|
||||
target_include_directories(strata_hip_runtime BEFORE INTERFACE
|
||||
"${STRATA_HIP_COMPAT_INCLUDE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"")
|
||||
option(STRATA_GFX1012_PORTABLE_DOT "Use the portable signed-byte dot control on gfx1012" OFF)
|
||||
if(STRATA_GFX1012_PORTABLE_DOT)
|
||||
target_compile_definitions(strata_hip_runtime INTERFACE STRATA_GFX1012_PORTABLE_DOT=1)
|
||||
endif()
|
||||
target_link_libraries(strata_hip_runtime INTERFACE hip::host)
|
||||
# The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host
|
||||
# compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takes
|
||||
# -include like it does on Linux; an MSVC-style front end (cl / clang-cl) takes /FI instead. Forward slashes, so /FI
|
||||
# does not read the path's backslashes as escapes.
|
||||
file(TO_CMAKE_PATH "${STRATA_HIP_COMPAT_INCLUDE_DIR}/cuda_runtime.h" _strata_hip_force)
|
||||
if(MSVC)
|
||||
target_compile_options(strata_hip_runtime INTERFACE "$<$<COMPILE_LANGUAGE:CXX>:/FI${_strata_hip_force}>")
|
||||
else()
|
||||
target_compile_options(strata_hip_runtime INTERFACE
|
||||
"$<$<COMPILE_LANGUAGE:CXX>:-include>" "$<$<COMPILE_LANGUAGE:CXX>:${_strata_hip_force}>")
|
||||
endif()
|
||||
target_compile_options(strata_hip_runtime INTERFACE
|
||||
"$<$<COMPILE_LANGUAGE:HIP>:-include>" "$<$<COMPILE_LANGUAGE:HIP>:${_strata_hip_force}>")
|
||||
|
||||
# CMake does not infer HIP from Strata's existing CUDA-shaped .cu suffixes.
|
||||
file(GLOB_RECURSE _strata_hip_sources CONFIGURE_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/*.cu"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/bench/*.cu"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/tests/*.cu")
|
||||
if(_strata_hip_sources)
|
||||
set_source_files_properties(${_strata_hip_sources} PROPERTIES LANGUAGE HIP)
|
||||
endif()
|
||||
foreach(_source IN ITEMS tests/hip/intrinsics.cpp tests/hip/native_qsa_score.cpp)
|
||||
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${_source}")
|
||||
set_source_files_properties("${_source}" PROPERTIES LANGUAGE HIP)
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
message(STATUS "Strata: HIP enabled, arch ${STRATA_HIP_ARCHS}")
|
||||
@@ -1,39 +0,0 @@
|
||||
# cmake/qwen36_attn_fixtures.cmake - the synthetic qwen35moe GGUFs at the engine's head_dim (256) and the oracle's
|
||||
# dumps of their attention layer, for qsa_dense_parity (Qwen3.6 step 3, docs/qwen36-port/step3-attn.md).
|
||||
#
|
||||
# cmake -DPYTHON=<python3 with numpy> -DSOURCE_DIR=<repo> -DOUT=<dir> -P cmake/qwen36_attn_fixtures.cmake
|
||||
#
|
||||
# Three fixtures, one per query-heads-per-KV-head the kernels are built for: g8 (16 / 2, Qwen3.6's ratio), g12
|
||||
# (24 / 2, Flash-Next's), g2 (4 / 2, the oracle's own GQA case). Each: <OUT>/<name>.gguf and <OUT>/<name>-dump/
|
||||
# with every seam of ref/qwen36.py on 40 tokens. Writes <OUT>/SKIP (and exits 0) when numpy or gguf-py is
|
||||
# missing, so the test that needs the files skips (77) instead of passing on nothing.
|
||||
file(MAKE_DIRECTORY "${OUT}")
|
||||
set(_synth "${SOURCE_DIR}/tools/qwen36_synth_gguf.py")
|
||||
set(_oracle "${SOURCE_DIR}/ref/qwen36.py")
|
||||
set(_text "dense attention over sixteen heads, G=8!") # 40 ASCII tokens (the fixture's vocabulary is the byte set)
|
||||
foreach(_case "g8;16,2;3" "g12;24,2;5" "g2;4,2;11")
|
||||
list(GET _case 0 _name)
|
||||
list(GET _case 1 _heads)
|
||||
list(GET _case 2 _seed)
|
||||
execute_process(COMMAND ${PYTHON} -I ${_synth} "${OUT}/${_name}.gguf" --heads ${_heads} --head-dim 256 --no-nextn
|
||||
--seed ${_seed}
|
||||
RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
|
||||
if(NOT _rc EQUAL 0)
|
||||
message("${_out}${_err}")
|
||||
if(_err MATCHES "ModuleNotFoundError" OR _out MATCHES "gguf-py" OR _err MATCHES "gguf-py")
|
||||
message("qwen36_attn_fixtures: numpy or gguf-py is missing - skipping")
|
||||
file(WRITE "${OUT}/SKIP" "${_out}${_err}")
|
||||
return()
|
||||
endif()
|
||||
message(FATAL_ERROR "qwen36_attn_fixtures: ${_synth} ${_name} failed (${_rc})")
|
||||
endif()
|
||||
file(REMOVE_RECURSE "${OUT}/${_name}-dump")
|
||||
execute_process(COMMAND ${PYTHON} -I ${_oracle} "${OUT}/${_name}.gguf" --text "${_text}" --dump "${OUT}/${_name}-dump"
|
||||
RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
|
||||
if(NOT _rc EQUAL 0)
|
||||
message("${_out}${_err}")
|
||||
message(FATAL_ERROR "qwen36_attn_fixtures: ${_oracle} on ${_name} failed (${_rc})")
|
||||
endif()
|
||||
endforeach()
|
||||
file(REMOVE "${OUT}/SKIP")
|
||||
message("qwen36_attn_fixtures: 3 fixtures and their dumps in ${OUT}")
|
||||
@@ -1,28 +0,0 @@
|
||||
# cmake/qwen36_block_fixtures.cmake - the oracle's dumps of the synthetic qwen35moe file on a verify window's worth of
|
||||
# tokens, for tests/cuda/qwen36_block_test.cpp (the plain block held to the dumps seam by seam).
|
||||
#
|
||||
# cmake -DPYTHON=<python3 with numpy> -DSOURCE_DIR=<repo> -DSYNTH=<dir with toy.gguf> -DOUT=<dir> -P cmake/qwen36_block_fixtures.cmake
|
||||
#
|
||||
# Writes <OUT>/o8/<seam>.f32 and manifest.txt (ref/qwen36.py --dump) for 8 tokens ("hello wo": the fixture's vocabulary is
|
||||
# the ASCII bytes). Exit 3 when numpy or the vendored gguf-py is missing (the SKIP marker, as qwen36_synth_fixtures.cmake).
|
||||
file(MAKE_DIRECTORY "${OUT}")
|
||||
if(EXISTS "${SYNTH}/SKIP" OR NOT EXISTS "${SYNTH}/toy.gguf")
|
||||
file(WRITE "${OUT}/SKIP" "no synthetic fixture in ${SYNTH}")
|
||||
message("qwen36_block_fixtures: no toy.gguf in ${SYNTH} - skipping")
|
||||
return()
|
||||
endif()
|
||||
file(REMOVE_RECURSE "${OUT}/o8")
|
||||
execute_process(COMMAND ${PYTHON} -I "${SOURCE_DIR}/ref/qwen36.py" "${SYNTH}/toy.gguf"
|
||||
--tokens 104,101,108,108,111,32,119,111 --dump "${OUT}/o8"
|
||||
RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
|
||||
if(NOT _rc EQUAL 0)
|
||||
message("${_out}${_err}")
|
||||
if(_err MATCHES "ModuleNotFoundError")
|
||||
message("qwen36_block_fixtures: numpy or gguf-py is missing - skipping")
|
||||
file(WRITE "${OUT}/SKIP" "${_err}")
|
||||
return()
|
||||
endif()
|
||||
message(FATAL_ERROR "qwen36_block_fixtures: ref/qwen36.py failed (${_rc})")
|
||||
endif()
|
||||
file(REMOVE "${OUT}/SKIP")
|
||||
message("qwen36_block_fixtures: dumps in ${OUT}/o8")
|
||||
@@ -1,35 +0,0 @@
|
||||
# cmake/qwen36_oracle_dumps.cmake - the Qwen3.6 kernel fixture and the oracle's seam dumps for the GPU parity tests.
|
||||
#
|
||||
# cmake -DPYTHON=<python3 with numpy> -DSOURCE_DIR=<repo> -DOUT=<dir> -P cmake/qwen36_oracle_dumps.cmake
|
||||
#
|
||||
# Writes OUT/k.gguf with tools/qwen36_synth_gguf.py at the geometry the engine's CUDA GDN kernels are pinned to
|
||||
# (state 128, 2 k-heads / 4 v-heads: VPK 2 like the real 16 / 32), the real router shape (256 experts, top-8), the
|
||||
# shared expert at its real width (512) in Q8_0, and the weights the engine reads as BF16 already BF16-representable;
|
||||
# then runs ref/qwen36.py on the 11-token "hello world" sequence twice: OUT/o_f32 (F32 activations) and OUT/o_q8
|
||||
# (--act-quant q8: activations rounded to Q8 before every quantized matmul, as the engine's native MMVQ path does).
|
||||
# Every tensor llama.cpp names with cb() lands in those directories as <name>.f32 (docs/qwen36-port/oracle-crosscheck.md).
|
||||
#
|
||||
# Exit 3 (and OUT/SKIP written) when numpy or the vendored gguf-py is missing, so the tests that need the files skip.
|
||||
file(MAKE_DIRECTORY "${OUT}")
|
||||
set(_synth "${SOURCE_DIR}/tools/qwen36_synth_gguf.py")
|
||||
set(_oracle "${SOURCE_DIR}/ref/qwen36.py")
|
||||
set(_tokens "104,101,108,108,111,32,119,111,114,108,100")
|
||||
set(_step1 ${PYTHON} -I ${_synth} "${OUT}/k.gguf" --gdn 2,4,128 --experts 256,8 --shexp-ff 512 --quant-shexp q8_0 --bf16-exact --no-nextn)
|
||||
set(_step2 ${PYTHON} -I ${_oracle} "${OUT}/k.gguf" --tokens ${_tokens} --dump "${OUT}/o_f32")
|
||||
set(_step3 ${PYTHON} -I ${_oracle} "${OUT}/k.gguf" --tokens ${_tokens} --dump "${OUT}/o_q8" --act-quant q8)
|
||||
foreach(_name _step1 _step2 _step3)
|
||||
set(_cmd ${${_name}})
|
||||
execute_process(COMMAND ${_cmd} RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
|
||||
if(NOT _rc EQUAL 0)
|
||||
message("${_out}${_err}")
|
||||
if(_err MATCHES "ModuleNotFoundError" OR _err MATCHES "gguf-py was not found")
|
||||
message("qwen36_oracle_dumps: numpy or gguf-py is missing - skipping")
|
||||
file(WRITE "${OUT}/SKIP" "${_err}")
|
||||
return()
|
||||
endif()
|
||||
message(FATAL_ERROR "qwen36_oracle_dumps: `${_cmd}` failed (${_rc})")
|
||||
endif()
|
||||
endforeach()
|
||||
file(REMOVE "${OUT}/SKIP")
|
||||
file(WRITE "${OUT}/tokens.txt" "${_tokens}\n")
|
||||
message("qwen36_oracle_dumps: k.gguf, o_f32/, o_q8/ in ${OUT}")
|
||||
@@ -1,27 +0,0 @@
|
||||
# cmake/qwen36_synth_fixtures.cmake - writes the synthetic qwen35moe GGUFs the Qwen3.6 geometry tests read.
|
||||
#
|
||||
# cmake -DPYTHON=<python3 with numpy> -DSOURCE_DIR=<repo> -DOUT=<dir> -P cmake/qwen36_synth_fixtures.cmake
|
||||
#
|
||||
# Exit 3 when numpy or the vendored gguf-py is missing (a trimmed third_party): the tests that need the files skip.
|
||||
cmake_policy(SET CMP0007 NEW) # keep the empty flag of "toy.gguf;" (cmake < 4 drops it and list(GET 1) fails)
|
||||
file(MAKE_DIRECTORY "${OUT}")
|
||||
set(_tool "${SOURCE_DIR}/tools/qwen36_synth_gguf.py")
|
||||
foreach(_case "toy.gguf;" "toy-nonextn.gguf;--no-nextn" "toy-fused-gate-up.gguf;--fused-gate-up"
|
||||
"toy-fused-qkv.gguf;--fused-qkv")
|
||||
list(GET _case 0 _name)
|
||||
list(GET _case 1 _flag)
|
||||
execute_process(COMMAND ${PYTHON} -I ${_tool} "${OUT}/${_name}" ${_flag}
|
||||
RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
|
||||
if(NOT _rc EQUAL 0)
|
||||
message("${_out}${_err}")
|
||||
if(_err MATCHES "ModuleNotFoundError")
|
||||
message("qwen36_synth_fixtures: numpy or gguf-py is missing - skipping")
|
||||
# cmake -P cannot set the exit code directly: a FATAL_ERROR exits 1, so write the marker the test reads
|
||||
file(WRITE "${OUT}/SKIP" "${_err}")
|
||||
return()
|
||||
endif()
|
||||
message(FATAL_ERROR "qwen36_synth_fixtures: ${_tool} ${_flag} failed (${_rc})")
|
||||
endif()
|
||||
endforeach()
|
||||
file(REMOVE "${OUT}/SKIP")
|
||||
message("qwen36_synth_fixtures: 4 files in ${OUT}")
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,475 +0,0 @@
|
||||
# Plan: UnbiasedStrata on Qwen3.6-35B-A3B, any single NVIDIA card from Pascal up, 256K context
|
||||
|
||||
Written 2026-10-11, revised the same day three times: after reading
|
||||
[Project Maya](https://github.com/mw00/project-maya); after the target widened from one card to a range;
|
||||
after the llama.cpp-backend fallback was removed. Status: proposed, nothing started.
|
||||
|
||||
Engine base: this repository's Strata snapshot (`6f32ec0`, engine 0.1.39). Maya is a method reference only.
|
||||
llama.cpp appears in two roles only: the external speed baseline (bare `llama-server`, never inside the
|
||||
binary) and the numerical oracle for parity. There is no fallback path.
|
||||
|
||||
## 0. Target and what "adapt" means
|
||||
|
||||
**Target:** one NVIDIA GPU, compute capability 6.1 or newer (GTX 10 series through RTX 50), **6 GB to 32 GB**
|
||||
of VRAM, Linux, x86-64 with AVX2. The engine sizes itself at start: fixed weights first, then the KV cache
|
||||
for the requested context, then every remaining byte of VRAM becomes expert-cache slots. The same binary
|
||||
and the same model files on every card; only speed differs. Q4 is the default quant. Context 262,144 where
|
||||
it fits, never below 131,072 without saying so. **Multi-GPU is out of scope**; the front end already
|
||||
refuses `--gpus`, and that stays.
|
||||
|
||||
The Strata engine in `src/` runs one architecture, Qwen3.8-Flash-Next (`qwen4_exp_text`). Qwen3.6-35B-A3B
|
||||
(`qwen3_5_moe_text`) is the same family one generation earlier, with the extras removed. From the two
|
||||
models' `config.json`:
|
||||
|
||||
| | Qwen3.8-Flash-Next (what the engine runs) | Qwen3.6-35B-A3B (the target) |
|
||||
| --- | --- | --- |
|
||||
| Hidden / layers | 2560 / 48 | 2048 / 40 |
|
||||
| Layer pattern | 3 linear attention then 1 full attention (`full_attention_interval` 4) | the same |
|
||||
| Linear attention (GDN) | 16 k-heads, 48 v-heads, 128-dim, conv 4 | 16 k-heads, **32** v-heads, 128-dim, conv 4 |
|
||||
| Full attention | 24 heads, 2 KV heads, head_dim 256, partial rotary 0.25, output gate, **plus a sparse indexer (QSA)** | 16 heads, 2 KV heads, head_dim 256, partial rotary 0.25, output gate, **dense** |
|
||||
| MoE | 512 experts, top-10, intermediate 640, shared 640 | 256 experts, top-8, intermediate 512, shared 512 |
|
||||
| Residual | hyper-connections (`hc` 4 streams) | plain residual |
|
||||
| PLE / n-gram table | yes (28.8 GB shard 2) | none |
|
||||
| MTP | 1 draft layer | 1 draft layer |
|
||||
| Vocabulary | 248,320 | 248,320, the same tokenizer |
|
||||
| Context | 262K | 262K native |
|
||||
|
||||
Everything Qwen3.6 has, the engine has a kernel for; what it lacks, the engine treats as optional (PLE) or
|
||||
needs a bypass for (hyper-connections, the QSA indexer). Maya's port study (`docs/GLM5-FLASH.md` in that
|
||||
repo) crossed a larger *kernel* gap for GLM-5.3-Flash in about a week: study 2026-09-29, verified
|
||||
streaming runner 2026-10-01, v1.0.0 on 2026-10-07. The Qwen3.6 kernel gap is smaller (no MLA, no sparse
|
||||
indexer to write, no manifold hyper-connections, a SiLU-for-sigmoid change in the GDN gate). The
|
||||
*plumbing* gap is not small: `docs/qwen36-port/geometry-inventory.md` (154 rows, 2026-10-11) shows the
|
||||
hc = 4 gated residual and the QSA indexer assumed structurally in every block, the output head, the
|
||||
verify window, the MTP drafter and prefill; prefill refusing any geometry but 2560/4/320/top-10; native
|
||||
packs decoding only through the verify window; and `ModelGeometry` reading only the expert counts and
|
||||
rope keys from the file. Expect Maya-scale work, with the risk in plumbing rather than kernels.
|
||||
|
||||
**The deliverable:** this tree's engine running Qwen3.6-35B-A3B natively, by Maya's method, behind the
|
||||
existing front end (`frontend/`: OpenAI API, tokenizer, chat template, tool-call parser, vision), which is
|
||||
model-agnostic and stays. The payoff is what llama.cpp's `--n-cpu-moe` cannot do: hot experts cached in
|
||||
VRAM by usage across all layers, the CPU computing the misses concurrently with the GPU, instead of whole
|
||||
layers' experts on the CPU serially. On a 6 GB card that is the difference between a cache holding the
|
||||
hottest 7% of experts and a layer cut holding none.
|
||||
|
||||
Hypotheses:
|
||||
|
||||
- **H1.** Under llama.cpp `--n-cpu-moe N` the GPU is idle most of each decode step, and the idle share
|
||||
grows with N, so it is worst on the smallest cards. (The baseline sweep measures it.)
|
||||
- **H2.** The idle is CPU expert matmul, not PCIe transfer.
|
||||
- **H3.** 256K context fits at Q4 on every card of 11 GB or more; 128K fits on 8 GB; 6 GB at Q4 holds
|
||||
the 256K fixed set only when prefill borrows cache slots, else it takes 131K or the IQ3 file, and the
|
||||
engine must say which it chose.
|
||||
- **H4.** Qwen3.6's routing is skewed enough that a VRAM expert cache serves well above its slot fraction
|
||||
of routes at every budget from 6 GB up. The replay measures the whole curve before any CUDA.
|
||||
- **H5.** The ported engine's decode scales as `1 / max(cpu, gpu)` rather than `1 / (cpu + gpu)`, and beats
|
||||
the llama.cpp baseline at every VRAM budget, by the most at the small end.
|
||||
- **H6.** With 12 GiB of RAM beside the 1080 Ti, Q4 reaches the disk tier and the profile-ranked VRAM
|
||||
and RAM tiers keep disk reads under one expert per token on a warm conversation; IQ3 never reaches the
|
||||
disk. The replay with three tiers predicts this; the engine's tier counters confirm it.
|
||||
|
||||
H4 and H5 are not a go/no-go for building the engine; the port is the deliverable regardless. They decide
|
||||
how the README describes the result and where the expert-cache tuning effort goes.
|
||||
|
||||
**Measured on 2026-10-11 (Phase 0; details in `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`):**
|
||||
|
||||
| | Q4_K_XL at 11 GB | IQ3_XXS at 11 GB |
|
||||
| --- | --- | --- |
|
||||
| llama.cpp, 256K, fit edge (`--n-cpu-moe` 32 / 18), smoke test, cold cache, 400 tokens | 8.8 tok/s decode, 129 prefill, GPU busy 15% | 24.6 tok/s decode, 434 prefill, GPU busy 41% |
|
||||
| llama.cpp, the sweep (warm, 1,200 tokens, `baseline-1080ti.md`) | **the number to beat: N = 30, the lowest N that fits (10,415 MiB): 13.4 tok/s decode on the regina request, 16.3 on the short one.** At N = 32: 13.5 / 12.2, 152 prefill; nvprof at N = 32: busy 13.8%, memcpy 0.6%, gaps 86%; warm nvprof at N = 30: busy 15.0%, memcpy 0.6%, 3.1 MiB of activations per token over PCIe; 14 to 21 MiB per token from disk | 33.5 tok/s decode, 907 prefill; GPU busy 56% (nvidia-smi); warm nvprof at N = 20: busy 24.8% under a 2.1x profiler slowdown, memcpy 0.8%; no disk reads |
|
||||
| Sweep slope | 0.67 to 0.93 points of GPU busy and 0.5 to 0.7 tok/s per layer moved to the CPU (the N = 32 point was the first run and carried steal) | one point and 0.58 tok/s per layer |
|
||||
| Route trace, top 40% of experts per layer | 76% of routes (215K routed tokens) | |
|
||||
| Replay at the censused sizes, LFU with 3 spares per layer, prefill borrowing cache slots | 78 slots per layer: 83.2% hit, 36.6 RAM and 17.0 disk reads per token | 149 slots: 95.4% hit, 14.6 RAM and 0 disk reads |
|
||||
| Replay, no borrowing (prompt buffer held in VRAM) | 52 slots: 72.2% hit, 35.8 disk reads | 103 slots: 89.4% hit, 0 disk reads |
|
||||
| Predicted decode, overlap / serial (gpu 17 ms, CPU lane 0.15 ms per expert, disk 1.3 ms; parameters, not measurements), borrowing | 36.2 / 22.4 tok/s | 58.8 / 52.1 tok/s |
|
||||
|
||||
Readings: H1 holds (the GPU idles 86% of each Q4 step by the kernel timeline, 44% at IQ3). H2 holds (memcpy is 0.6% of the window; the idle is CPU matmul and, at Q4, page-ins). H4 holds (83% hit from 35% of the
|
||||
experts). With 12 GiB of RAM the Q4 arm is disk-limited (17 disk reads per token, about 22 ms, more than
|
||||
the whole GPU step), so on this rung IQ3 is the quant that reaches the GPU ceiling and Q4 needs either
|
||||
16 GiB of RAM or 12 GB of VRAM. Prefill borrowing cache slots is worth 11 points of hit rate at Q4. Prefill hit rates are linear in slots (a prompt touches nearly every
|
||||
expert per layer per ubatch), so prompts stream experts over PCIe, as Strata already does. The overlap
|
||||
column saturates at `1000 / gpu_ms`; the GPU step itself is the next thing to measure properly (nvprof,
|
||||
in the sweep).
|
||||
|
||||
## 1. The card ladder
|
||||
|
||||
Real cards in the homelab cover the range, with Pascal at three sizes:
|
||||
|
||||
| Budget | Card | Where | Arch | Role |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 6 GB | GTX 1060 | g7 (192.168.50.185), laptop | sm_61 | the floor; regina's `g7/README.md` has llama.cpp numbers here already |
|
||||
| 8 GB | GTX 1070 Ti | host .4 (`llama-qwen36-35b-mtp.service`, live) | sm_61 | second Pascal point |
|
||||
| 11 GB | GTX 1080 Ti | .57 at PCI `2a:00`, in **VM 211 `gpu-qwen36`** at 192.168.50.43 (cloned from 210 on 2026-10-11: 8 vCPU, 12 GiB, 100 GB on `local-lvm`, Debian 13, driver 550, CUDA 12.4, gcc-13) | sm_61 | the primary measurement card, and the development card until a pod is rented |
|
||||
| 32 GB, rented | A6000 or similar on RunPod | on demand; this fork was already checked on a RunPod 3090 container (README) | sm_86 | only for the 32 GB rung and if the 4090 becomes busy again; the user has approved spending on this |
|
||||
| 24 GB | RTX 4090 | VM 221 (192.168.50.151) on pve2: 16 vCPU, 62 GB RAM, CUDA 12.4, driver 550; root disk nearly full (build trees under `/models/work`, 174 GB free); system gcc is 14, so builds need gcc-13 as the host compiler | sm_89 | **idle since 2026-10-11 17:20, the user's call: the fast-compile development card for Phase 2 steps 3 to 5 and the 24 GB rung.** Both llama-server units there are inactive; leave them so. No RunPod needed while it stays free |
|
||||
| 12, 16, 32 GB | RTX A6000 (48 GB) **capped** | VM 220 (192.168.50.8) on .57 | sm_86 | **in use by another agent**; the emulated rungs wait for it |
|
||||
|
||||
The cap is Maya's `STRATA_GLM_VRAM_GB` idea: the engine limits its own total VRAM so the expert pool gets
|
||||
what a card of that size would leave it. It is built in Phase 2 step 2; the 1080 Ti emulates the 6 and 8 GB
|
||||
rungs with it (the real 1060 and 1070 Ti then check launch failures, FP16 paths and PCIe), and the A6000
|
||||
emulates 12, 16 and 32 GB whenever it is free.
|
||||
|
||||
Consequence of the 1080 Ti being the only local card: **the Pascal build comes first, not last.** Every
|
||||
parity harness and the streaming runner are brought up under `STRATA_EXPERIMENTAL_SM60=ON` on sm_61 from
|
||||
the start, so Pascal surprises surface in the first week. The rented sm_86 pod runs the same harnesses in
|
||||
parallel for fast iteration; a kernel passes when it passes on both.
|
||||
|
||||
Constraints across the ladder:
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| CUDA | one toolkit that compiles sm_61 and sm_120 both: **CUDA 12.8** (12.x is the last with Pascal; 13 dropped it). Upstream saw RTX 50 crashes with 12.8-built engines (issues #220, #224), so RTX 50 is "built, not measured" until a card exists here. Fat binary `CUDA_ARCHS=61;70;75;86;89;120` |
|
||||
| Pascal specifics | dp4a exists on sm_61 (not sm_60, which gets the shim); no tensor cores; no `__nanosleep`; FP16 math at 1/64 rate on GP102/GP104/GP106, so every kernel's *arithmetic* on these cards must be FP32 or dp4a int8 (fp16 *storage* with conversion, as in the KV pools and prefill's stores, is full rate and stays); the prompt MoE's dp4a MMQ path must be enabled on sm_61. Strata refuses sm < 75 unless `STRATA_EXPERIMENTAL_SM60=ON`; that flag becomes the default build (Phase 2, step 6). Nobody has run this engine on Pascal; Maya requires Volta or newer |
|
||||
| Build verification | `cuobjdump --list-elf \| grep sm_` after every build; two past incidents here were wrong-arch binaries |
|
||||
| Profilers | current Nsight Systems: Turing and newer only. Nsight Compute: no Pascal since 2019.5. On Pascal use the `nsys` bundled with CUDA 12.x (2023.x) or `nvprof`; on Turing and newer current `nsys`. Same analysis script either way |
|
||||
| .57 host | Ryzen 7 1700 (Zen 1, AVX2, no AVX-512), 62 GiB usable DDR4-2133. Checked 2026-10-11: VM 220 shrunk to 36 GiB by another agent, host 18 GiB available before VM 211, about 6 GiB after. The 1080 Ti's link is **Gen3 x8** (`LnkSta: 8GT/s, Width x8`), so the June Gen1 problem is gone. VM 220 shares the memory bandwidth and the 8 physical cores (VM 220 has 12 vCPU, VM 211 has 8: oversubscribed when both are busy), so each run's metadata records VM 220's load and measurement windows prefer its idle hours |
|
||||
| Stale pointer | `docs/NEW-GPU-VM.md` says "both GTX 1080 Ti"; slot 29:00 now holds the A6000 |
|
||||
|
||||
## 2. Models, the memory hierarchy, and the budget table the engine must reproduce at start
|
||||
|
||||
**Decision 2026-10-13 (step 5, the user):** the hierarchy is two tiers, VRAM plus host RAM, assumed to hold the
|
||||
expert set; spilling to the NVMe is out of scope. Measured on the 1080 Ti at Q4_K_XL: 52 tok/s with the set
|
||||
pinned in the VM's 35 GB, 12 to 15 tok/s under a 12 GiB bound (disk-bound, the replay's prediction; llama.cpp
|
||||
13.4). The README states the RAM a card needs per quantization; the 12 GiB rows below are kept as the measured
|
||||
cost of breaking the assumption, not as a supported rung. H6 and the disk-read instruments are therefore
|
||||
informational.
|
||||
|
||||
**The hierarchy on the primary rung is three tiers, by the user's decision:** 11 GB of VRAM in the 1080 Ti,
|
||||
about 12 GiB of VM RAM (roughly 9 to 10 GB usable for a pinned expert tier after the OS, the process and
|
||||
the KV), then the VM's NVMe disk for the rest. Strata already has the pieces: the VRAM expert cache, the
|
||||
pinned RAM tier, and the low-RAM modes (`--mmap-experts` serving misses from the model file through the
|
||||
page cache; `--resident-experts` copying exactly the non-VRAM experts into RAM when they fit). At Q4 they
|
||||
do not all fit in 12 GiB, so the mapped mode and the disk are in play; at IQ3_XXS the whole expert set fits
|
||||
VRAM plus RAM. Every per-budget number below is therefore a pair: where the experts live, and how many
|
||||
reads per token reach the disk.
|
||||
|
||||
| Arm | File | Size | Where it already is |
|
||||
| --- | --- | --- | --- |
|
||||
| **Q4, default** | `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (unsloth, repo commit `a483e9e`) | ~21 GB | not on hand; download once on the Mac, SHA-256 against the repo, copy over LAN |
|
||||
| Q4 + MTP | `Qwen3.6-35B-A3B-UD-Q4_K_M-MTP.gguf` | 22.66 GB | `.4:/mnt/models/qwen3.6/MTP/`, Mac `~/models/qwen3.6/MTP/` |
|
||||
| Q3 | `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` | 13.21 GB | `.4`, `.151:/models`, g7 `/home/rk/models` |
|
||||
|
||||
K-quants for the default because most experts run on the CPU on most of the ladder, and K-quant dot
|
||||
products are the fast AVX2 path. The engine needs the MTP block: Strata's draft protocol is built around
|
||||
the model's own MTP layer. Settled on 2026-10-11: the `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` from unsloth's MTP
|
||||
repository (rev 5bc3e238) already carries the draft block as `blk.40` (753 tensors), so it is the default
|
||||
file, and its `blk.40` serves as the draft pack for the IQ3 arm too (the plain IQ3 file has no draft block).
|
||||
|
||||
Fixed VRAM before any expert slot. Measured and censused on 2026-10-11; the authoritative table is
|
||||
`docs/QWEN36-35B-A3B.md` section 4.1, summarized:
|
||||
|
||||
| Item | Q4_K_XL | IQ3_XXS |
|
||||
| --- | --- | --- |
|
||||
| Non-expert weights on the GPU | 2,038 MiB | 1,597 MiB |
|
||||
| Draft block (dense 40 MiB + its experts + ring KV + logits) | ~520 MiB | ~520 MiB (the Q4 file's) |
|
||||
| KV, q4_0, 10 attention layers, 262K | 1,440 MiB | 1,440 MiB |
|
||||
| Session, CUDA context, reserve | ~0.7 to 1.2 GB | same |
|
||||
| Prompt buffers | 0 when prefill borrows cache slots (a profile exists); 1,904 MiB at chunk 2048 otherwise | 0 / 1,878 MiB |
|
||||
| **Decode-time fixed set at 262K** | **~4.8 GB borrowing, ~6.7 without** | **~4.3 / ~6.2** |
|
||||
| Trunk experts, total / per expert (mean, max) | 18,726 MiB / 1.83 MiB, 2.20 max | 10,594 MiB / 1.04 MiB, 1.17 max |
|
||||
|
||||
What each budget leaves for experts at Q4, 262K (the llama.cpp layer cut on the right is the baseline's
|
||||
equivalent, for the comparison only):
|
||||
|
||||
| Budget | Q4 expert slots in VRAM, prefill borrowing (of 10,240) | IQ3 slots | `--n-cpu-moe` equivalent |
|
||||
| --- | --- | --- | --- |
|
||||
| 6 GB | ~525 (5%); without borrowing the fixed set does not fit at 262K, so 131K or the IQ3 file | ~1,350 (13%) | 40 (all) |
|
||||
| 8 GB | ~1,570 (15%) | ~3,200 (31%) | ~37 |
|
||||
| 11 GB (the 1080 Ti, 11,264 MiB), 12 GiB RAM, NVMe | ~3,550 (35%) in VRAM; ~4,950 (48%) pinned in RAM; ~1,740 (17%) on disk | ~6,700 (66%) in VRAM, the rest in RAM, no disk tier | ~32 (llama.cpp's CPU experts at Q4 exceed 12 GiB, so its baseline on this rung is page-cache bound too) |
|
||||
| 12 GB | ~3,650 (36%) | ~6,880 (67%) | ~31 |
|
||||
| 16 GB | ~5,740 (56%) | all | ~26 |
|
||||
| 24 GB | all, ~1 GB spare | all | 0 |
|
||||
| 32 GB | all; the spare VRAM goes to f16 KV or a bigger prompt chunk | all | 0 |
|
||||
|
||||
The sizing rule the engine implements (Phase 2, step 2): take the fixed total for the requested context;
|
||||
if it does not fit, lower the context toward 131,072, then refuse with the exact numbers and the IQ3 file's
|
||||
name. **KV streaming is not a lever for this model**: Strata streams by resolving the *selected* cells, and
|
||||
dense attention selects every cell (study, 3.3 item 6), so the KV stays in VRAM. Never silently pick a
|
||||
shorter context. Then the RAM tier: free RAM minus a headroom for the OS and the KV
|
||||
stream, filled with the next experts by profile rank; whatever remains stays mapped from the GGUF on disk
|
||||
and is read on a miss. The start-up log states all three counts.
|
||||
|
||||
CPU-side ceiling for the misses: ~12 MiB of expert weight per CPU-computed layer-token at Q4. On the .57
|
||||
host (DDR4-2133, ~30 GB/s) that is ~60 to 70 tok/s before compute; Zen 1's 8 cores will be the lower
|
||||
bound. Prior Pascal data: GTX 1060 6 GB, IQ3_XXS, N = 32: 16 tok/s at 8K depth, 11 at 32K, 355 tok/s
|
||||
prefill, all llama.cpp.
|
||||
|
||||
## 3. Phase 0: environment, baseline, and the replay
|
||||
|
||||
Human steps (Proxmox state is the user's):
|
||||
|
||||
1. (Decided: VM 220 stays up; host RAM already freed for a 12 GiB VM.)
|
||||
2. (Done 2026-10-11.) VM 211 `gpu-qwen36`, a full clone of VM 210: **8 vCPU, 12 GiB RAM, balloon 0,
|
||||
100 GB on `local-lvm` (NVMe)**, `--hostpci0 0000:2a:00,pcie=1`. No `rombar=0`: that was needed only
|
||||
for the boot-VGA card at 29:00 (homelab ticket 002); the 1080 Ti at 2a:00 never needed it. VM 220
|
||||
keeps running. The disk is the third tier, so `fio` its read throughput and 4K random latency once,
|
||||
into `phase0-notes.md`.
|
||||
3. Inside the VM: pin the kernel/driver pair, install `build-essential cmake nvtop linux-perf`, CUDA 12.8
|
||||
(the template has 12.4; 12.8 needs a 570-series driver, still a Pascal-capable branch), confirm
|
||||
`nvidia-smi`, check `LnkSta`, set `perf_event_paranoid` to 1.
|
||||
4. Copy the GGUFs over LAN; `sha256sum` each.
|
||||
|
||||
Agent steps (fresh sonnet agent; brief = this section plus the hosts):
|
||||
|
||||
5. Build bare `llama-server` at the submodule's pinned commit `3cf0325`, `-DGGML_CUDA=ON`, arches
|
||||
`61;86;89`, static; verify with `cuobjdump`. Also the latest release (v0.6.0) for its MTP arm. One
|
||||
build per rung, each verified for its own arch. This binary is the baseline and the oracle, nothing
|
||||
else.
|
||||
6. Profiler check on the 1080 Ti: CUDA 12.x `nsys status -e`, a 10-second `nsys profile -t cuda` of
|
||||
`llama-bench`, `nvprof --print-gpu-trace` as fallback. Record which works.
|
||||
7. Smoke test at 256K on the 1080 Ti with `llama-server`: `-ngl 99 --n-cpu-moe 32 -fa on -c 262144
|
||||
-ctk q4_0 -ctv q4_0 -b 2048 -ub 2048 --parallel 1 --cache-ram 0 -lv 4 -t 8`. Save the `-lv 4` buffer
|
||||
lines; they replace the estimates in Section 2.
|
||||
|
||||
**The baseline sweep (sonnet to drive, haiku to monitor).** Regina's harness (`scripts/sweep_ncpumoe.py`,
|
||||
`plot_ncpumoe_sweep.py`): the N sweep with VRAM (`nvidia-smi` and `-lv 4`), host RAM (`RssFile`), prefill
|
||||
and decode from `timings`, one real launch per point. One env spec per card; the A6000 budgets via
|
||||
`CUDA_VISIBLE_DEVICES` plus a side process holding the surplus VRAM. Regina's hygiene: 30 s settle, drop
|
||||
caches, warmup discarded, `--cache-ram 0`, `--parallel 1`. Workload per point: the Opus system prompt
|
||||
(~27K tokens) + "implement Minesweeper", `n_predict 800`, plus one 3K-prefill / 1200-decode request.
|
||||
Reasoning off, `temp 0`, `seed 42`.
|
||||
|
||||
Instruments, logged per run (the same three serve the engine later):
|
||||
|
||||
- **Level 0, always:** `nvidia-smi --query-gpu=timestamp,utilization.gpu,memory.used,power.draw
|
||||
--format=csv -lms 100`. `utilization.gpu` is the GPU-busy share at 100 ms resolution. nvtop in a tmux
|
||||
pane is for the human, not the record.
|
||||
- **Level 1, per point:** a decode-phase kernel timeline (`nsys` or `nvprof`). A script computes busy
|
||||
fraction, gap histogram, memcpy vs kernel share (the H2 test), per-token period, profiler overhead.
|
||||
- **Level 2:** `perf stat` on the server PID, so gaps match CPU time in ggml matmul threads.
|
||||
- **Timeline videos, prefill and decode (added 2026-10-13, the user's standing requirement).** For the
|
||||
engine and for llama.cpp, on the 1080 Ti and the 4090, a real-time video of the request's timeline in the
|
||||
style of `~/projects/ub-strata/strata.mp4`: lanes for CPU cores used (100 ms per-core `/proc/stat`
|
||||
samples), GPU kernels, PCIe H2D / D2H bytes and GPU copy / idle, a playhead, the engine-reported tok/s
|
||||
on completion, and the busy fraction stated both with and without the engine's host-wait spin kernel.
|
||||
Two windows per point: the **prefill** of a long prompt (the regina request's 3.1K prompt, and a 32K
|
||||
prompt where the budget allows) and the **decode** of the short request. Stacked engine-over-llama.cpp
|
||||
comparisons at the fit edges. The traces come from the same nsys / nvprof captures as Level 1, so the
|
||||
profiled request must cover the prefill as well as the decode. Pipeline: `scripts/decode_video_json.py`,
|
||||
`scripts/decode_video_render.swift`, `scripts/render_decode_videos.sh` in regina (adapted from
|
||||
`~/Code/strata-workspace/strata-investigation`); output under
|
||||
`analysis/qwen36-35b-single-gpu-ladder/video/` with a README carrying the method's honesty statements.
|
||||
|
||||
| # | Where | Arm | N values | ctx | Question |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| B1 | 1080 Ti | Q4 | fit edge, +2, +4, +8, 40 | 262144 | H1, H3 on the primary card; with 12 GiB of RAM the CPU experts page from disk, so `RssFile` and disk reads are recorded per point |
|
||||
| B1b | 1060, 1070 Ti, 4090, A6000 at 12/16/32 | Q4 | the fit edge for that budget, and 40 | 262144, or 131072 where 262K does not fit | the baseline row of the ladder table |
|
||||
| B2 | 1080 Ti | Q4 | fixed N | 262144 | depth 8K, 32K, 128K |
|
||||
| B3 | 1080 Ti, 1060 | Q3 | fit edge, +4, +8, 40 | 262144 | K-quant vs i-quant CPU cost; the 6 GB default |
|
||||
| B4 | 1080 Ti | Q4 + MTP | fixed N | 262144 | multi-token verify on CPU experts (llama.cpp's MTP) |
|
||||
|
||||
B1, B1b and B3 are the baseline. B2 and B4 run when a card is idle. File-based drivers under `tmux`,
|
||||
`DRIVER_DONE` markers. B1 takes 2 to 4 hours at 256K context.
|
||||
|
||||
**E0, the route trace and cache replay (sonnet agent; any GPU host, even the Mac).** From Maya; it
|
||||
answers H4 for the whole ladder before any CUDA and it produces the expert profile the engine loads:
|
||||
|
||||
8. Record routes: a small patch to llama.cpp's `examples/eval-callback` writing one line per token and MoE
|
||||
layer with the 8 selected expert ids (`ffn_moe_topk`). Corpus: regina's coding tasks, the Opus system
|
||||
prompt, a few long chats; ~200K routed tokens.
|
||||
9. Replay: adapt Maya's `tools/glm_tier_replay.py` (MIT; models LFU residents + spares + the CPU-lane
|
||||
pick) to 40 layers × 256 experts **and three tiers** (VRAM slots, RAM slots, disk), and sweep the VRAM
|
||||
slot count from 0 to 10,240 landing on each budget from Section 2, at Q4 and IQ3, with the RAM tier
|
||||
fixed at what 12 GiB leaves. Policies: LFU, LRU, Belady ceiling.
|
||||
10. Output: `phase0-replay.md` with VRAM hits, RAM hits and disk reads per token **vs slots**, the seven
|
||||
budgets marked, and the predicted engine decode ceiling per budget against the baseline, using the
|
||||
measured disk latency from step 2 for the disk term. The trace also seeds `expert-profile.bin`.
|
||||
|
||||
Exit criteria: the baseline ladder row with the 1080 Ti's full N sweep; a working profiler on Pascal; the
|
||||
hit-rate curve with the budgets marked; Section 2's estimates replaced by measured buffer sizes.
|
||||
|
||||
## 4. Phase 1: images and the baseline write-up
|
||||
|
||||
Under `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`:
|
||||
|
||||
1. `gpu-busy-vs-N.png`: Level-1 busy fraction and Level-0 utilization vs N on the 1080 Ti, both arms. H1.
|
||||
2. `timeline-N<k>.png`: a 200 ms strip of one decode step, kernels vs memcpys vs gaps. H2.
|
||||
3. `ladder-baseline.png`: decode and prefill vs VRAM budget (6, 8, 11, 12, 16, 24, 32), llama.cpp at the
|
||||
fit edge. The engine's points go on the same axes in Phase 2 step 5. The headline image.
|
||||
4. `vram-vs-N.png`: VRAM vs N with the budget lines and the 262K/131K KV points.
|
||||
5. `dmon-strip-N<k>.png`: the raw 100 ms trace over prefill then decode.
|
||||
6. `replay-hitrate-vs-slots.png`: hit rate vs slots per policy, budgets marked. H4.
|
||||
|
||||
Analysis reads the PNGs and CSVs. The write-up answers with numbers: busy fraction and its slope in N;
|
||||
memcpy vs gap; the default quant per budget; the baseline ladder row; the simulated hit rate per budget
|
||||
and the predicted engine gain, largest-to-smallest card. A fresh agent reviews it, given the data but not
|
||||
the conclusion. This write-up is what the engine must beat; it does not decide whether the engine is built.
|
||||
|
||||
## 5. Phase 2: the engine port, Maya's recipe on a smaller gap
|
||||
|
||||
The design document for this phase is `docs/QWEN36-35B-A3B.md` (2026-10-11): the model exactly from the
|
||||
real GGUF's metadata, the component-by-component gap analysis with file:line citations, the memory plan
|
||||
with the censused fixed set, the ladder, the envelope, the execution plan with effort weights (step 2
|
||||
15%, step 3 45%, step 4 20%, step 5 10%, step 6 5%, step 7 5%) and the risks. Where it and this plan
|
||||
differed, the plan was corrected to the study on 2026-10-11 (its section 8 lists the eight points).
|
||||
|
||||
Where: step 2 on VM 211 (the 1080 Ti, the Pascal build from the first step, Section 1). From step 3 on,
|
||||
kernel work and parity iterate on the 4090 in VM 221 (sm_89, idle since 2026-10-11) and every kernel
|
||||
also passes on the 1080 Ti before its step closes; the 4090 is also the 24 GB rung for step 5. Each step has a parity harness in Strata's negative-test discipline (every wrong reading must
|
||||
differ materially before the right one is judged), as Maya's section 6 did. Steps 1 to 4 need no GPU time
|
||||
beyond seconds of parity runs, so they proceed while the Phase 0 sweeps hold the cards.
|
||||
|
||||
1. **Oracle and fixture (sonnet, no GPU).** Found on 2026-10-11 (`docs/qwen36-port/upstream-tooling.md`):
|
||||
upstream never published its Python oracles (`ref/` holds only `load.py`; `gdn.py`, `moe.py`,
|
||||
`qsa.py`, `docs/semantics.md` are cited but absent), most parity tests carry a host C++ reference
|
||||
inside the test file, two embed generated `.inc` vectors, and the ggml-oracle tests link a llama.cpp
|
||||
build through `STRATA_ORACLE_SOURCE_DIR`. So: `tools/` and `tests/` restored from the import commit `12a7825`
|
||||
(done, commit c00942d: development tooling only, the binary still needs no Python), then write `ref/qwen36.py` new on `ref/load.py`, following the submodule's
|
||||
`qwen35moe.cpp` graph with dumps named by its `cb()` calls; `tools/qwen36_synth_gguf.py` from
|
||||
`test_iq_pack.py`'s `write_gguf()`; invariant tests (top-8 renormalization, GDN state shapes, the
|
||||
output gate). Cross-check with the submodule's `llama-eval-callback` on the same synthetic GGUF.
|
||||
One model difference already known: Flash-Next's GDN output norm gates with sigmoid(z), `qwen35moe`
|
||||
with SiLU(z); `gdn.cu` and `gdn_parity` encode the sigmoid reading, so that is the first negative
|
||||
test. `make_profile.py` hardcodes 48 layers and 512 experts; the MTP tools hardcode Flash-Next tensor
|
||||
names; `iq_pack.py`'s `FORM` table has no `qwen35moe` entry. Dependencies: numpy, regex, gguf-py; no
|
||||
torch, no GPU.
|
||||
**Done 2026-10-11 on branch `qwen36-oracle`** (commits 9630539, f1ef81d, 0c850c3, 2094992, unmerged):
|
||||
the oracle matches llama.cpp's own graph on 2,155 comparisons across 14 cases (max abs error 1.1e-4,
|
||||
identical top-k everywhere, the nextn block included); seven rival readings each fail; 21 invariant
|
||||
tests (24 after review). Independent review: no blockers; the GQA fixture (4 query heads over 2 KV
|
||||
heads) added after review and matching on every seam; `ref/load.py`'s dequant bit-identical to ggml's
|
||||
for Q6_K, IQ2_S, IQ3_XXS and IQ4_XS. **Tolerance policy** (`docs/qwen36-port/oracle-crosscheck.md`):
|
||||
the oracle has a Q8 activation mode (`--act-quant q8`) and a per-layer protocol (`--force-topk`,
|
||||
`--force-inputs`) that starts each layer from llama.cpp's inputs; against that, the per-seam relative
|
||||
spread on the real file is 5e-8 (norm), 7e-7 (qkv), 8e-5 (gdn_out), 1.1e-4 (attn_out), 2.3e-3
|
||||
(moe_out), 4e-7 (logits). Those are the kernel parity tolerances. Without forcing, errors compound
|
||||
5 to 30 times and about half the top-k slots flip, so exact top-k agreement stays an F32-fixture-only
|
||||
test. Branch commits after review: e452c51, 0e5344d, 44b0619. Real-file facts the engine
|
||||
needs: the plain GGUF has no nextn block (only the `-MTP` files do, as block 40); nothing is fused;
|
||||
the router, `ssm_alpha`, `ssm_beta` are F32; down experts are IQ3_XXS in 37 layers and IQ4_XS in
|
||||
layers 34, 38, 39; the untied 2048 × 248,320 head is Q6_K.
|
||||
2. **Geometry, metadata, sizing (default model).** Per the inventory: `ModelGeometry` is a set of
|
||||
Flash-Next defaults; only `qwen4exp.expert_count`, `expert_used_count` and the rope keys are read, and
|
||||
`check_architecture` rejects anything but `qwen4exp`. So: read every field of `ModelGeometry` from
|
||||
the `qwen35moe.*` keys (hidden, layers, head counts, `ssm.*`, `n_ff`, interval); add `hc = 1` as "no
|
||||
gated residual" with a plain-residual path and the `attn_norm` / `post_attention_norm` /
|
||||
`output_norm` tensors the engine never references today; fix the one leak in the native expert path
|
||||
(`expert_layout.cpp:284` passes compile-time 2560/640 to `native_fmt`); make `--ple-gguf` optional at
|
||||
the command line (the kernels already allow no PLE); refuse llama.cpp's fused `ffn_gate_up_exps` and
|
||||
`attn_qkv` forms by name (no shipped Qwen3.6 file uses them; the oracle's fused cases document the
|
||||
layouts if one appears); the draft geometry follows the target; the draft vocab size comes from the
|
||||
pack. The per-layer prefetch hints already exist (`FileExpertSource::warm`, `MADV_WILLNEED` on
|
||||
predicted ids): verify they fire on the Qwen3.6 pack's offsets rather than porting Maya's. **The VRAM planner:** free VRAM minus the fixed set for the requested
|
||||
context; KV streaming engaged when the fixed set does not fit (`--kv-resident`); the context lowered
|
||||
toward 131,072 only after that; a refusal with numbers below it; the remainder becomes expert slots;
|
||||
then the RAM tier from free RAM minus headroom (`--resident-experts` machinery), the rest mapped
|
||||
from disk (the existing `--mmap-experts` source with its `MADV_WILLNEED` warm); `--vram-cap` and
|
||||
`--ram-cap` for emulation. This step is what makes "6 GB to 32 GB" one binary, and it is where the
|
||||
engine's tier counters (VRAM, RAM, disk reads per token) are exposed in the log and on `/health`.
|
||||
3. **Kernels and the block (default model).** In order of risk, each with a parity harness:
|
||||
- the GDN mixer: head pairing `h % h_k` already handles 32 v-heads against 16 k-heads; the gate
|
||||
changes from sigmoid(z) to SiLU(z) in four kernels (`gdn.cu`, `fused_gdn.cu`,
|
||||
`native_gdn_preprocess.cu`, the prefill GDN kernels), with the sigmoid reading as the negative test;
|
||||
- the full-attention layer as *dense* attention: the decode kernel reads KV through an index list and
|
||||
does not care how the list was built, so a "select every cell" producer replaces the indexer; the
|
||||
kernels fixed at 12 query heads per KV head (Qwen3.6 has 8) and the short-context kernel fixed at
|
||||
24 heads become parameters; the prompt path is `qsa_prompt_attn.cu` (on Pascal, the batched decode
|
||||
kernel), parameterized the same way; `native_flash_attn.cu` is a 256-cell diagnostic adapter, not a
|
||||
fallback;
|
||||
- the router at top-8 over 256 (generic already; parity at the selection boundary) and the shared
|
||||
expert at 512 (its Q8_K rule needs a multiple of 256, which 512 satisfies);
|
||||
- the block without hyper-connections: `layer.cpp` *and* `verify.cpp`, because native packs decode
|
||||
only through the verify window, and that window requires the fused hc kernels (fixed at
|
||||
2560/4/320), top-10 and the native indexer today;
|
||||
- prefill: `Prefill::init` refuses anything but 2560/4/320/10 and its GDN, split-q, route and MoE
|
||||
kernels carry literals (48 v-heads, 24 heads, 1280, 640, top-10); parameterize or fork them.
|
||||
Then the layer composition test: one GDN+MoE and one attention+MoE layer against the oracle's dumps.
|
||||
The canonical Q2_0 CPU expert kernel bakes Flash-Next's shapes; Qwen3.6 rides the native pack path
|
||||
(per-layer runtime geometry, ggml dot products, Unsloth's Q4_K/Q5_K types already included), as the
|
||||
Coder with its 256 experts per layer does.
|
||||
4. **Pack and runner.** `iq_pack.py` taught `qwen35moe` and its BF16-preserve list; the MTP head: the
|
||||
engine's drafter reads its own Q8_0 directory with vLLM-style names, canonical Q2_0 experts at
|
||||
2560/640 and the default geometry, and Qwen3.6's single `nextn.eh_proj` over the concatenated
|
||||
embedding and hidden state does not match the two separate projections it expects, so the drafter
|
||||
needs a Qwen3.6 pack format and a small graph change (Maya's `mtp_gguf.py` is the model);
|
||||
`make_profile.py` (hardcoded 48 × 512 today) from the E0 trace;
|
||||
the streaming runner held to the oracle at every position of a short sequence; then the real Q4 file
|
||||
end to end, greedy, compared with llama.cpp's output distribution (not token-for-token; the README's
|
||||
known-problems entry says why).
|
||||
5. **Serve and measure on the 1080 Ti at 11 GB, then capped to 8 and 6; the 12, 16, 24 and 32 rungs when a card frees up.** CPU lane and PCIe
|
||||
share calibrated as Maya's `--calibrate` does, against this engine's own session; the Phase 0
|
||||
harness and instruments; the engine's points onto `ladder-baseline.png`. The H5 measurement. The
|
||||
front end's `make test-chat-parser MODEL=<gguf>` against Qwen3.6's template (the homelab services
|
||||
use a patched `qwen3.6-enhanced.jinja`); the Qwen3-Coder any-argument-order patch checked for
|
||||
misfires on this model's tool-call grammar.
|
||||
6. **The other Pascal cards and the fat binary.** The sm_61 build has been the working build since step
|
||||
1; this step makes `STRATA_EXPERIMENTAL_SM60=ON` the default for the fat binary
|
||||
(`CUDA_ARCHS=61;70;75;86;89;120`, CUDA 12.8) and runs the 1070 Ti and the 1060 against B1b. The
|
||||
sm_75+ paths (tensor-core prompt attention, thread-block clusters) stay compiled in for the cards that
|
||||
have them and are checked on the 4090 or A6000 when one is free.
|
||||
7. **README/UPSTREAM.** The supported model and its checksums, the ladder table with the engine against
|
||||
the baseline, the sizing rule in words, the Pascal caveats (CUDA 12.x, FP32 paths, no Nsight Compute).
|
||||
|
||||
**The base is this repository's `src/` and `include/`: Strata at `6f32ec0`, engine 0.1.39.** Maya's engine
|
||||
is not merged, cherry-picked or vendored: it forked from Strata around engine 0.1.27 and has rewritten the
|
||||
expert tiers, the mixers and the server since, so its C++ does not apply to this tree without a port of its
|
||||
own. Taken from Maya (MIT, by reference to a pinned commit): the method and the Python-side tooling; the
|
||||
list of places Strata's geometry was hardcoded, each re-found and fixed here; the route-log format,
|
||||
`glm_tier_replay.py` and `glm_expert_prior.py` adapted as standalone scripts; the VRAM cap and the
|
||||
CPU-lane calibration as *designs*, implemented against this engine. Left out: the Python installer, the
|
||||
dashboard, the Anthropic API, all multi-GPU work. One binary, no Python at run time, no network, one GPU.
|
||||
|
||||
## 6. Acceptance
|
||||
|
||||
Per budget, at the default quant, the engine must meet:
|
||||
|
||||
| Criterion | Threshold | Basis |
|
||||
| --- | --- | --- |
|
||||
| A1 context | 262,144 on 11 GB and up; 131,072 on 8 GB; on 6 GB whichever the sizing rule picks, stated at start | the stated goal and floor |
|
||||
| A2 decode | beats the baseline's fit-edge decode on the same rung; absolute floors ≥ 15 tok/s at 8K depth and ≥ 10 at 32K on 11 GB, ≥ 10 / 7 on 6 GB, ≥ 60 / 45 on 24 GB | the 1060 did 16/11 at IQ3 under llama.cpp; the 4090 did 100+ |
|
||||
| A3 prefill | ≥ 300 tok/s on Pascal, ≥ 2,000 on Ada | the 1060 did 355 |
|
||||
| A4 stability | 7 consecutive requests, no OOM, ≥ 100 MiB VRAM headroom | g7's "+78 MiB per request" |
|
||||
| A5 serving | chat, streaming, reasoning, tool calls and images through the front end, pi writing and running a program through it, on the 1060, the 1080 Ti and the 4090 with no flags but the model | the README's existing status bar |
|
||||
|
||||
If A2's "beats the baseline" fails on a rung after the cache tuning of step 5, the README reports the
|
||||
rung's numbers against the baseline as they are. The engine still ships for that rung; the comparison is
|
||||
the honest part of the result, not a gate.
|
||||
|
||||
## 7. Agents: who does what, and how cheaply
|
||||
|
||||
Rules:
|
||||
|
||||
- `ark` is human-only. If a phase should run under ark, the plan says so and the user starts it.
|
||||
- One fresh agent per phase boundary, briefed with this file, the phase section, the hosts, the run
|
||||
directory, and the previous phase's write-up (not its transcript).
|
||||
- Fork (same context) only to continue an in-progress phase after a wakeup.
|
||||
- Nothing an agent runs changes Proxmox state. Agents do not touch the live `.4` service except by
|
||||
starting a second server on another port with the production unit stopped, and restoring it.
|
||||
- Unattended sweeps: a file-based driver under tmux, polled on a `/loop` or wakeup every 15 to 30
|
||||
minutes, `DRIVER_DONE` markers.
|
||||
|
||||
Tiering:
|
||||
|
||||
| Work | Model | Why |
|
||||
| --- | --- | --- |
|
||||
| `-lv 4` logs to CSV; `dmon.csv` parsing; nsys/nvprof export to busy-fraction and gap histograms; checksums; marker checks; replay runs at given slot counts; B1b single points on a card with a ready script | **haiku** | mechanical, re-runnable |
|
||||
| Env specs, drivers, plots; llama.cpp builds per arch; the eval-callback route-dump patch; the replay adaptation; the oracle and synthetic fixture (Phase 2 step 1) | **sonnet** | code with a known shape and an example to copy |
|
||||
| The Phase 1 write-up; geometry, the VRAM planner, kernels, pack, runner, the Pascal build (Phase 2 steps 2 to 7); diff review before the user ships | **default (Fable)** | judgment and engine code |
|
||||
| Independent review of the Phase 1 write-up and of each parity harness before it is trusted | fresh **default** agent, given data but not the conclusion | an agent handed a hypothesis tends to confirm it |
|
||||
|
||||
Safe parallelism: the 1080 Ti sweep, the B1b points on the other cards, E0 on the Mac, and Phase 2 steps
|
||||
1 to 4 on the A6000 are independent of each other. If the user wants a multi-agent fan-out for Phase 2,
|
||||
they say "use a workflow".
|
||||
|
||||
## 8. Order of work and checkpoints
|
||||
|
||||
1. User: VM 220 decision; the 1080 Ti VM; GGUFs copied to every rung.
|
||||
2. Agent (sonnet): `llama-server` builds per arch, profiler check, smoke test → `phase0-notes.md`.
|
||||
**Checkpoint: the first `-lv 4` table on the 1080 Ti; Section 2's estimates replaced.**
|
||||
3. Agent (sonnet, then haiku): E0 → `phase0-replay.md` and the expert profile. **Checkpoint: the hit-rate
|
||||
curve with the seven budgets marked.** In parallel, Phase 2 step 1 on the Mac.
|
||||
4. Agents: B1 on the 1080 Ti; B1b on the 1060, 1070 Ti, 4090 and capped A6000; B3. **Checkpoint: the
|
||||
baseline ladder row.** In parallel, Phase 2 steps 2 to 4 on the A6000.
|
||||
5. Agent (default): plots and the baseline write-up; separate reviewer. **Checkpoint: the number to beat
|
||||
on every rung.**
|
||||
6. Agent (default): Phase 2 step 5 across the capped budgets. **Checkpoint: the engine's points on the
|
||||
ladder plot against the baseline, and pi served through the front end on the 4090.**
|
||||
7. Agent (default): step 6 on the three Pascal cards. **Checkpoint: `unbiased-strata --model <gguf>`
|
||||
serving pi on the 1060 and the 1080 Ti with no flags but the model; A1 to A5 on every rung.**
|
||||
8. Step 7, the README. B2 and B4 whenever a card is idle.
|
||||
|
||||
Measurements land in `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`, infra notes in
|
||||
`~/homelab/investigations/<date>-vm-1080ti-qwen36.md` with a LOG.md entry, the model-support outcome and
|
||||
the ladder table in this repo's README, and the port study in `docs/QWEN36-35B-A3B.md`. Tickets: one
|
||||
`homelab` for the VM, one `regina` for the harness, one `UnbiasedStrata`-prefixed ticket per Phase 2
|
||||
step, filed when the work starts.
|
||||
@@ -1,594 +0,0 @@
|
||||
# Running Qwen3.6-35B-A3B on UnbiasedStrata - the study
|
||||
|
||||
What it takes for Qwen3.6-35B-A3B (llama.cpp architecture `qwen35moe`) to run on this tree's Strata
|
||||
engine, component by component, with the numbers the decision needs. Written 2026-10-11 against engine
|
||||
0.1.39 (`CMakeLists.txt:11`, the `6f32ec0` snapshot; tree `8634357`). It is the Phase 2 design document
|
||||
of `docs/PLAN-qwen36-35b-a3b.md` and the counterpart of Project Maya's `docs/GLM5-FLASH.md`, whose shape
|
||||
it copies. Every `file:line` is this tree; "row N" is `docs/qwen36-port/geometry-inventory.md`; the model
|
||||
facts come from `docs/qwen36-port/gguf-metadata.md` and `ref/qwen36.py` on branch `qwen36-oracle`; the
|
||||
measurements from regina's `phase0-notes.md` and `replay/phase0-replay.md`.
|
||||
|
||||
Strata is a native implementation of one architecture, Qwen3.8-Flash-Next (`qwen4exp`), with its memory
|
||||
tiers and its speculation stack built around that shape. Qwen3.6-35B-A3B is the same family one generation
|
||||
earlier with three things removed (the hyper-connection residual, the sparse-attention indexer, the PLE
|
||||
table) and one numerical change in the GDN gate. The kernel gap is small. The plumbing gap is not: the
|
||||
removed pieces are assumed structurally in every block, in the verify window that is the only decode path
|
||||
for native packs, in the drafter and in prefill, and `ModelGeometry` is never populated from the model file.
|
||||
|
||||
---
|
||||
|
||||
## 1. The model, exactly
|
||||
|
||||
From the shipped GGUFs (`gguf-metadata.md`, dumped with `tools/gguf_reader.py`; sizes and SHA-256s in
|
||||
`phase0-notes.md`):
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Architecture | `general.architecture = qwen35moe`; `block_count` 40 (41 in the MTP files); `embedding_length` 2048; `context_length` 262,144 |
|
||||
| Layer pattern | `full_attention_interval` 4: layer `il` is recurrent unless `(il+1) % 4 == 0`, so attention at 3, 7, ..., 39 (10 layers), GDN at the other 30 |
|
||||
| GDN | `ssm.conv_kernel` 4, `ssm.state_size` 128, `ssm.group_count` 16 (k-heads), `ssm.time_step_rank` 32 (v-heads), `ssm.inner_size` 4096; conv channels 8192 = 2x2048 + 4096. Output gate `rms_norm(o) * ssm_norm * SiLU(z)` (`qwen35moe.cpp:267-276`) |
|
||||
| Full attention | 16 heads, 2 KV heads, `key_length`/`value_length` 256, `rope.dimension_count` 64 (0.25 of 256), `rope.dimension_sections` [11, 11, 10, 0], `freq_base` 1e7, eps 1e-6; `attn_q` is 2x wide (query then gate per head, interleaved); output `* sigmoid(gate)`. **Dense**: no indexer |
|
||||
| MoE | 256 experts, top-8, `expert_feed_forward_length` 512, shared expert 512 with a 1-D `ffn_gate_inp_shexp` scalar gate. Softmax over all 256, top-8 weights renormalised to sum 1 (`norm_w = true` hard-coded, `qwen35moe.cpp:506`); no `expert_weights_scale` (never loaded for this architecture) |
|
||||
| Residual | plain: `attn_norm`, `post_attention_norm`, `output_norm`, all multiplicative RMS weights (no "+1") |
|
||||
| MTP | `nextn_predict_layers` **absent in the plain file, 1 in the MTP files**; `blk.40` holds one attention + MoE block plus `nextn.eh_proj` [4096, 2048] over `concat(enorm(emb), hnorm(h))`, `nextn.enorm`, `nextn.hnorm`, `nextn.shared_head_norm`; no `embed_tokens`, no `shared_head_head` (the draft head is the main `output.weight`) |
|
||||
| Vocabulary | 248,320 tokens, `pre = qwen35`, BOS/EOS/PAD 248044/248046/248055; the same tokenizer the engine's `--eos-ids` default already names (row 152) |
|
||||
| Float tensors | the router `ffn_gate_inp`, `ssm_alpha`, `ssm_beta`, the shexp gate and every norm are **F32** in the plain file; the nextn block's router and shexp gate are BF16 |
|
||||
| Mixed quantization | per layer and per role: IQ3_XXS file has IQ2_S gate/up everywhere, IQ3_XXS down on 37 layers and IQ4_XS on 3 (34, 38, 39); the nextn block in the MTP files is Q3_K/Q4_K experts with Q8_0 projections |
|
||||
| Fused forms | none shipped: gate and up are separate `ffn_gate_exps`/`ffn_up_exps`, attention layers carry separate `attn_q`/`attn_k`/`attn_v`; `attn_qkv` exists only in the 30 GDN layers (the conv input) |
|
||||
|
||||
The byte census of the three files on hand (gguf-py over the headers, 2026-10-11; `blk.40` separated):
|
||||
|
||||
| File | Non-expert on the GPU (`output` + projections + norms) | `token_embd` | Trunk experts (40 x 256) | Per expert mean / max | `blk.40` dense / experts |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| `UD-Q4_K_XL` (MTP repo, rev 5bc3e238, 21,784 MiB) | **2,038 MiB** (Q8_0 1,939 + F32 100) | 515 MiB Q8_0 | **18,726 MiB** (Q4_K 11,232, Q5_K 6,864, Q6_K 630) | 1.829 / 2.195 MiB (layer 39) | 40 / 464 MiB |
|
||||
| `UD-IQ3_XXS` (12,589 MiB) | **1,597 MiB** (Q6_K 1,497 + F32 100) | 398 MiB Q6_K | **10,594 MiB** (IQ2_S 6,560, IQ3_XXS 3,626, IQ4_XS 408) | 1.035 / 1.172 MiB | none |
|
||||
| `UD-IQ4_XS-MTP` (17,355 MiB) | 2,038 MiB | 515 MiB | 14,514 MiB | 1.417 / 1.883 MiB | 40 / 364 MiB |
|
||||
|
||||
The two non-expert figures are what llama.cpp's `-lv 4` reported on the 1080 Ti once the GPU-resident
|
||||
expert layers are subtracted: Q4 `CUDA0 model` 5,917 MiB minus layers 32 to 39 (3,878 MiB) = 2,039; IQ3
|
||||
7,475 minus layers 18 to 39 (5,878) = 1,597 (`phase0-notes.md`, smoke table). The token embedding stays in
|
||||
host memory in both llama.cpp and this engine (`generate.cpp:2190`, "token embedding in mapped host
|
||||
memory"), so it is not in the fixed set. The plan's Section 2 estimated ~3.1 GB for this item; the real
|
||||
figure is 2.0 GiB.
|
||||
|
||||
## 2. What the engine already is
|
||||
|
||||
The implemented geometry is a struct of Flash-Next defaults (`include/strata/core/layout.hpp:27-59`):
|
||||
n_embd 2560, 48 layers, full attention every 4th, GDN 16 k-heads / 48 v-heads / state 128 / conv 4 with
|
||||
conv channels 10240 and value dim 6144 stored as members (row 2), QSA 24 heads / 2 KV heads / 256 with a
|
||||
4-head 128-wide indexer, hyper-connections `hc` 4 with a 320-wide bottleneck, 512 experts x top-10 x 640.
|
||||
`is_qsa_layer` is `layer % 4 == 3` (`layout.hpp:63`). Per layer (`src/core/layer.cpp:1170-1286`,
|
||||
`1319-1342`):
|
||||
|
||||
gr_read(attn) -> GDN | QSA -> gr_write(attn) -> gr_read(ffn) -> moe_route [doorbell] ... moe_finish -> gr_write(ffn)
|
||||
|
||||
The unit is a captured per-layer CUDA graph replayed by a host loop (`include/strata/core/session.hpp:1-15`)
|
||||
that rings a doorbell at the router so a CPU expert pool starts on the misses while the GPU continues.
|
||||
Experts live in three tiers: a VRAM cache of slots filled by a profile and swapped by decayed usage
|
||||
(`include/strata/core/expert_cache.hpp`), a RAM tier (pinned arena, or `--resident-experts` /
|
||||
`--resident-budget-gib` keeping the complement of the VRAM cache in a compact copy,
|
||||
`generate.cpp:1506-1520`, `expert_source.cpp:1331`), and the model file mapped from disk
|
||||
(`--mmap-experts`, `expert_source.cpp:618-680`) with a `MADV_WILLNEED` warm hint per role on predicted
|
||||
ids (`expert_source.cpp:1129-1160`, called at `1264`). Decode for a *native* pack (experts served from the
|
||||
GGUF in their own ggml types, `include/strata/kernels/cpu/native_expert.hpp`) runs only through the verify
|
||||
window (`expert_source.cpp:1869-1875`, row 114): windows of up to `kVerifyMaxT = 8` rows
|
||||
(`verify_kernels.hpp:21`) drafted by the model's own MTP layer, a separate Q8_0 pack in VRAM
|
||||
(`src/core/mtp.cpp:150-216`, `mtp.hpp:1-20`), plus a prompt-lookup drafter (`generate.cpp:522-524`).
|
||||
Prompts go through a chunked prefill with the experts streamed over PCIe through a ring that borrows
|
||||
cache slots (`generate.cpp:2723`, `4404-4425`; `docs/upstream/DETAILS.md`, "How it works"). The front
|
||||
end (`frontend/`) is model-agnostic: OpenAI API, llama.cpp's chat parser (`frontend/chat_parser_test.cpp`),
|
||||
vision through `mtmd` (`frontend/vision.hpp:4-87`), and it refuses `--gpus` (`frontend/main.cpp:558`).
|
||||
|
||||
## 3. Component-by-component gap analysis
|
||||
|
||||
### 3.1 Applies unchanged
|
||||
|
||||
| Piece | Why |
|
||||
| --- | --- |
|
||||
| Layer pattern | `is_qsa_layer` (`layout.hpp:63`) gives 3, 7, ..., 39 for 40 layers; `n_qsa_layers() = 40/4 = 10` (row 55). Every per-layer loop in `session.cpp` uses `g.n_layers` (row 27). |
|
||||
| GDN decode kernels | State 128, head pairing `head % h_k` (`native_gdn.cu:51`, `fused_gdn.cu:29`), grids from `h_v`, `h_v % h_k == 0` checked (`native_gdn.cu:99-101`, `fused_gdn.cu:148-153`); 32 % 16 = 0. The conv (`d_conv == 4 && state 128`, `layer.cpp:247-248`) matches. |
|
||||
| Router | `router_top10` is a generic softmax top-k over runtime `n_expert <= 512`, `k <= 32` (`router_top10.hpp:21`, row 124); `moe_route` takes it whenever the pack is not 512/10 (`layer.cpp:370`). Semantics equal llama.cpp's: softmax over all, stable descending argsort, renormalise with the 2^-14 clamp (`router_top10.hpp:3-5`; `oracle-crosscheck.md`, "Router and experts"). |
|
||||
| Shared expert | Shape-driven (`layer.cpp:418-451`); its Q8_K activation rule needs `n_ff % 256 == 0` (`shared_expert.cu:237-239`), which 640 failed and 512 satisfies (row 127). |
|
||||
| Native expert kernels | CPU: `native_fmt` is ggml-cpu trait-driven, whole-block checks only (`native_expert.cpp:40-60`); 2048 and 512 are multiples of 256. `kNativeActBytes` 4096 / `kNativeHBytes` 1024 hold a 2048-wide Q8_K (2,336 B) and a 512-wide one (584 B) (row 111). GPU: `iq_kernels.cu:1076-1140` read `L.n_embd`/`L.n_ff` per layer; Q4_K/Q5_K gate-up and Q5_1/Q8_0 down are already present (row 120); the IQ2_S/IQ3_XXS/IQ4_XS/Q6_K of the shipped files are ggml types ggml-cpu has `vec_dot` for. |
|
||||
| Expert cache and tiers | Residency `[n_layers x n_expert]`, slots, the profile header checked against `(n_layers, n_expert)` (`expert_cache.cpp:43`); the file source, the complement copy, the warm hint; all parameterised at runtime (rows 118, 109). |
|
||||
| KV formats and streaming machinery | fp16 / int8 / q4_0 / K8V4 pools at `head_dim 256` (`kv_q4.cu:176`, row 103); paged pools, `--kv-resident`, the resident floor 20,480 cells (`layer.cpp:556`). The *use* of streaming changes (section 4.2). |
|
||||
| RoPE | `n_rot 64`, `head_dim 256` (`native_rope.cu:121`), interleaved M-RoPE sections 11/11/10/0 with `t = h = w` for text (`mrope.hpp:3-12`); the oracle pins the same pairs `(p, p+32)` (`oracle-crosscheck.md`, "Full attention"). |
|
||||
| Vocabulary, sampler, head | `n_vocab` is a kernel argument, merge handles <= 262,144 (`sampler.cu:607`); the native head takes `[n_in, n_out]` with `n_in % 256 == 0` (`native_head.cpp:21`); the drafter reads `n_vocab_ = output.weight.ne1` (`mtp.cpp:430`). |
|
||||
| Speculation protocol | Verify windows, draft policy, prompt lookup; the drafter's *weights* change (3.10). |
|
||||
| Front end | Tokenizer, template, tool-call parser, vision (row 154). |
|
||||
| MTP drafter's attention | Already dense over every cell (`mtp.hpp:16-18`, row 76): the one dense-attention path in the tree. |
|
||||
|
||||
### 3.2 GDN: head pairing, SiLU gate, four kernels (small)
|
||||
|
||||
The geometry changes are runtime except two stored members, `ssm_conv_channels` and `ssm_value_dim`,
|
||||
which must become 8192 and 4096 (row 2; `session.cpp:41-44` derives the state size from them). The one
|
||||
numerical change: the output gate is `sigmoid(z)` in the engine and `SiLU(z)` in Qwen3.6 (row 39;
|
||||
`layer.hpp:16` records the difference). Four kernels carry it:
|
||||
|
||||
| Kernel | Line | Path |
|
||||
| --- | --- | --- |
|
||||
| `gdn_out_norm` | `src/kernels/cuda/gdn.cu:148` | legacy decode |
|
||||
| `gdn_step_norm_kernel` | `src/kernels/cuda/fused_gdn.cu:69` (`1/(1+__expf(-zz))`) | the default native decode, inside the fused step |
|
||||
| out-norm kernel | `src/kernels/cuda/native_gdn_preprocess.cu:110-112` | native unfused |
|
||||
| `gdn_rec_kernel`, `gdn_out_norm_kernel` | `src/prefill/kernels.cu:324, 612` (`sigm(z)`) | prompt |
|
||||
|
||||
The oracle's negative control shows the sigmoid reading moves the layer output by 1.07 relative L1 and the
|
||||
logits by 0.92 (`oracle-crosscheck.md`, negative controls), so the trap is far above the 5% gate.
|
||||
`src/kernels/gdn_parity.cpp:104` pins `h_v = 48` and its reference `sigmoid_f` (`:42`); both are re-pinned
|
||||
at 32 v-heads with SiLU, the sigmoid reading becoming the negative case. The prompt GDN kernels are
|
||||
specialised on `VPK = HV / HK = 3` value heads per key head (`prefill/kernels.cu:478`) and launched on the
|
||||
`HV`/`HK`/`C` constants (`kernels.cu:18-19`, rows 89 to 91); they are the prefill item in 3.6.
|
||||
|
||||
### 3.3 Dense attention replacing QSA (the largest kernel item, and a memory item)
|
||||
|
||||
The decode kernel gathers K/V through `ids` and a page table and does not care how `ids` was built
|
||||
(`qsa_decode_attn.cu:100-120`, row 102). So dense attention is a "select every cell" producer feeding the
|
||||
existing kernel. What stands in the way:
|
||||
|
||||
1. **The producer.** `qsa_layer` runs the indexer unconditionally: the raw key projection (`layer.cpp:945`),
|
||||
the append (`:962-964`), the block scores and top-k (`:966-975`), with `indexer.{k,q}_proj.weight` and
|
||||
`indexer.{k,q}_norm.weight` dereferenced as required tensors (`:891-897`, row 45). The verify window
|
||||
does the same per row (`verify.cpp:757-761`, `772-870`, row 145). A dense path skips those steps and
|
||||
writes `ids = 0..n_kv-1` from `st.step`; the selection width `qsa_selection_width(n_kv, s) =
|
||||
min(n_kv, 2051)` (`qsa.hpp:144-147`) and the capacity `cap = qsa_selection_width(kTopkMaxCells, s)`
|
||||
(`layer.cpp:876`, `verify.cpp:352`, `prefill.cpp:865`) become `n_kv` and `max_cells`.
|
||||
2. **The 12-versus-8 literal.** `G = 12` query heads per KV head, refused with `exit(1)` unless
|
||||
`n_head == 12 * n_head_kv` (`qsa_decode_attn.cu:17, 453, 497`; `qsa_prompt_attn.cu:22, 1447`; row 93, 94).
|
||||
Qwen3.6 is 8. `G` becomes a template parameter instantiated at 8 and 12.
|
||||
3. **The 24-head short-context kernel.** `native_flash_attn.cu:196-206` refuses anything but 24/2/256 and
|
||||
contexts above 256; it is a diagnostic adapter (`layer.hpp:53`, "context <= 256") and is not on the
|
||||
prompt path. It stays as it is.
|
||||
4. **State without the indexer.** `qsa_state_bytes` carves `idx_tail`, `idx_dead`, `idx_pooled` with
|
||||
`pooled_rows = max_cells/4 + 2` (`layer.cpp:559-575`, row 43): at 262,144 cells that is 65,538 x 128 x
|
||||
4 B = 32 MiB per attention layer, 320 MiB over ten, all dead. The drafter's ring already passes a state
|
||||
"which has no indexer" with `pooled_rows = 2` (`layer.cpp:527-531`); the dense state takes the same.
|
||||
5. **The split-K scratch scales with the context.** `qsa_decode_attn_scratch_floats(cap, s) = (cap/64) x
|
||||
n_head x 258 + 64` (`qsa_decode_attn.cu:489-491`). Today `cap` is 2,051; with `cap = 262,144` and 16
|
||||
heads it is 64.5 MiB *per query row*: 516 MiB for the 8-row verify window (`verify.cpp:422`) and
|
||||
`attn_batch` times that in prefill (`prefill.cpp:888`). The dense kernel needs either a larger chunk
|
||||
per block or an online-softmax merge that does not keep a partial per 64-cell chunk.
|
||||
6. **KV streaming no longer saves VRAM.** Streaming keeps the authoritative K/V in host memory and resolves
|
||||
the *selected* blocks into VRAM slots before the read (`layer.hpp:230-236`, `qsa_kv_resolve` at
|
||||
`layer.cpp:976`). With every cell selected every token, every block must be resident every token: the
|
||||
mechanism degenerates to copying the whole KV (1,440 MiB at q4_0) over PCIe per token. Section 4.2
|
||||
and section 8 draw the consequence for the plan's sizing rule.
|
||||
|
||||
KV formats, the Hadamard-rotated q4_0 pool, the page table and the RoPE tables carry over unchanged
|
||||
(`layer.cpp:938-1010`, row 46). The prompt attention has three device paths: cp.async + mma on sm_80+,
|
||||
mma on Turing, an m8n8k4 kernel on Volta, and for `cc < 70` the host returns false
|
||||
(`qsa_prompt_attn.cu:1433`) so prefill falls back to the batched decode kernel
|
||||
(`prefill.cpp:2222-2228`). On Pascal that fallback is the prompt attention; it needs `G = 8` and the
|
||||
scratch fix above, nothing else.
|
||||
|
||||
### 3.4 Router and shared expert (small; one measured-not-asserted parity)
|
||||
|
||||
Both are generic already (3.1). Two form questions remain. The router kernel reads a BF16 weight
|
||||
(`layer.cpp:361-366`, `project_bf16`), `fused_gdn_ab` reads BF16 `ssm_alpha`/`ssm_beta`
|
||||
(`layer.cpp:285-287`), and `moe_shared` refuses a `ffn_gate_inp_shexp` that is not engine form BF16
|
||||
(`layer.cpp:427-437`). All four are F32 in the shipped file (`gguf-metadata.md`, "What was unexpected").
|
||||
The pack rounds them: exactly when the low 16 bits are zero, else only under `--compat-bf16`
|
||||
(`upstream-tooling.md` section 4, the ORCA precedent). That is a numerical change against llama.cpp, which
|
||||
multiplies in F32, and it lands on the one place where rounding is not a rounding error: a flipped top-8
|
||||
selection is a different expert (`layer.hpp:131-139`). The oracle's real-file smoke already shows the
|
||||
F32-versus-quantized router disagreeing on 6 of 32 (token, slot) choices in layer 0 and 12 to 23 in layers
|
||||
30 to 39 (`oracle-crosscheck.md`, "Not covered"), so the harness measures a flip rate at the
|
||||
`logits -> top-8` boundary with the quantized-mode gates Maya calibrated (selection equal at probed layers
|
||||
on an F32 fixture; a bounded rate on the real file), not bitwise equality. `router_top10_parity.cpp`'s tie
|
||||
fixtures (all-equal logits, a 12-way tie, the unreachable clamp) carry over at 256/8.
|
||||
|
||||
### 3.5 The block without hyper-connections: `layer.cpp` *and* `verify.cpp` (the largest plumbing item)
|
||||
|
||||
`hc` sizes the residual `R` (hc, n_embd), `inject`, `gr_rs` and the GR workspace (`layer.cpp:1127-1145`),
|
||||
and every block reads four `hc_attn_*` and four `hc_ffn_*` tensors with required forms
|
||||
(`layer.cpp:1231-1255`, row 22). No `hc = 1` meaning exists (row 4): the GR math on one stream is not a
|
||||
plain residual, and the names Qwen3.6 ships (`attn_norm`, `post_attention_norm`, `output_norm`) are
|
||||
referenced nowhere in `src/` (rows 22, 23). The plain block is
|
||||
|
||||
x = rms_norm(R, attn_norm) -> mixer -> R += out
|
||||
x = rms_norm(R, post_attention_norm) -> MoE -> R += out head: rms_norm(R, output_norm) -> output.weight
|
||||
|
||||
(`qwen35moe.cpp` layer loop; the oracle's `attn_norm-N`, `attn_residual-N`, `attn_post_norm-N`, `l_out-N`,
|
||||
`result_norm` seams). The weighted RMS norm kernel exists (`native_qsa_rms_norm_weighted`, used at
|
||||
`layer.cpp:879` and `mtp.cpp:488`). The places that must grow the plain path:
|
||||
|
||||
| Site | What assumes hc |
|
||||
| --- | --- |
|
||||
| `layer.cpp:1170-1286` `block_layer_pre`, `1319-1342` `block_layer_post` | the two GR halves, the fused-GR fast path (`fused = g_fused_gr && fused_gr_supported(2560, 4, 320)`, `:1195`; `fused_gr.cu:1164-1166`), `pending_ffn` folding |
|
||||
| `layer.cpp:1088-1107` `lm_head_mix` | `output_hc_{norm,down,up}` |
|
||||
| `session.cpp:141-148` | first token = `hc` copies of the embedding (one copy at hc = 1, row 26) |
|
||||
| `verify.cpp:331-340` | refuses unless `fused_gr_supported && ss.k == 10 && state 128 && d_conv 4` and `layer_verify_compatible` demands the fused GR and the native indexer (`layer.cpp:476-486`, row 141) |
|
||||
| `verify.cpp:356-434` | `R_`, `xn_` as `T*HC*N`, `inj_`, `lo_ (T*hc_lr)`, `idx_raw_L_`, `qidx_`, `tail_snap_` |
|
||||
| `verify.cpp:1123-1125` | the head mix |
|
||||
| `verify_kernels.cu:256-291` | `broadcast_streams` / `add_streams_broadcast` (runtime `hc`, row 140) |
|
||||
| `mtp.cpp:503-507, 564-568, 613-625`; `prefill.cpp:972-1086` | the drafter's three hc groups (3.10) |
|
||||
|
||||
Because native packs decode only in verify windows (row 114) and the window refuses a layer without fused
|
||||
GR and the indexer (row 141, 142), the plain block has to land in `verify.cpp` for a single token to come
|
||||
out. The verify window's `ss.k == 10` refusal becomes `k == 8` from the file. `cvec` (the control-vector
|
||||
apply over `hc*n_embd`, row 140) is runtime-shaped and needs no change.
|
||||
|
||||
### 3.6 Prefill (the most literal-heavy subsystem)
|
||||
|
||||
`Prefill::init` refuses unless `n_embd == 2560 && hc == 4 && hc_lr == 320 && k == 10`
|
||||
(`prefill.cpp:737`, row 132); the file-wide constants are `N 2560, HC 4, D, LR 320, K 10, NE 512, C 10240,
|
||||
ZV 6144, HV 48` (`prefill.cpp:90-91`) and `N, HC, D, LR, S, HK 16, HV 48, C 10240` in the kernels
|
||||
(`prefill/kernels.cu:18-19`). The literals, each with its Qwen3.6 value:
|
||||
|
||||
| Site | Literal | Qwen3.6 |
|
||||
| --- | --- | --- |
|
||||
| `prefill.cpp:649-650, 883-884` | `Qf` as `T * 12288` (24 x 512), `q`/`attn` as `T * ZV`; `idx_raw`, `q_idx` | 8,192 (16 x 512), 4,096; the two indexer buffers dead |
|
||||
| `prefill.cpp:681-685, 704-721, 896-907` | MoE buffers `T*K*1280`, `T*K*640`, `1280 * 2560`, `2560 * 640`; `mmq::fits(gt, 1280)`, `matrix_bytes(dt, N, 640)` | `2*n_ff` 1024, `n_ff` 512, `n_embd` 2048 |
|
||||
| `prefill.cpp:854-856, 1000-1026, 1375-1380` | `grs`, `gated`, `inj`, `xq`, `ident` from `HC`, `D`, `LR` | removed with hc |
|
||||
| `prefill/kernels.cu:211-215, 285-304, 345-364, 387-432, 478-570, 893-924` | GDN kernels indexed on `HV`, `HK`, `C`, launched `<<<HV, ...>>>`; `VPK = 3` (`:478`) | 32, 16, 8192; `VPK = 2` |
|
||||
| `prefill/kernels.cu:616-657` | `route_kernel<REG>`: `REG 8` exists for 256 experts but the rank loop and `ids[t*10 + rank]`, `lane < 10` bake top-10 | `k` as a parameter |
|
||||
| `prefill/kernels.cu:752-761` | `split_q_kernel`, `gate_attn_kernel` over `T * 24 * 256` and `h * 512` | 16 heads |
|
||||
| `prefill/moe_fused_iq.cu:59` | `GU_ROWS_K = 2560, D_ROWS_K = 640` (the native-pack fused prompt MoE) | 2048, 512 |
|
||||
| `prefill.cpp:1724` loop, `1303` `RP = 48` | layers from `g.n_layers` (fine, row 134); `RP` | check |
|
||||
|
||||
The GDN kernels are forked per geometry (template on `HV, HK, C`) rather than made runtime, because their
|
||||
shared-memory staging (`sq[2][TB][S]`, `kernels.cu:482-484`) is sized from them. `src/prefill/gdn_rec_parity.cu`
|
||||
mirrors the constants (row 91) and is re-pinned with them. The chunked-versus-single-token equivalence (a
|
||||
prefix through prefill then decoded must agree with token-by-token decode) is the harness that already
|
||||
exists for this path (`tests/cuda/prefill_*_test.cpp`, restored in `c00942d`).
|
||||
|
||||
### 3.7 The native pack path (one leak, otherwise runtime)
|
||||
|
||||
The canonical Q2_0 CPU expert kernel bakes `H 2560, FF 640, NE 512, BLOB 1,382,400`
|
||||
(`include/strata/kernels/cpu/expert.hpp:34-47`, row 107) and `expert_pool_dispatch` refuses any other
|
||||
width (`expert_source.cpp:1863-1868`); Qwen3.6 does not go through it. It rides the native path, as the
|
||||
Coder (256 of 512 experts) does. The path is runtime per layer (`NativeFmt` with `n_embd`, `n_ff`, gate/up
|
||||
and down ggml types, `native_expert.hpp:22-31`) with one leak: `expert_layout_load` builds every layer's
|
||||
format with the compile-time `H, FF` (`src/kernels/cpu/expert_layout.cpp:284`, `native_fmt(gt, dt, H, FF,
|
||||
f, err)`) and then checks `f.bytes == blob`, so a 2048/512 pack fails the "blob is X B but its formats make
|
||||
Y" check (row 108). The fix is the loader taking `n_embd`/`n_ff` from the geometry the caller resolved,
|
||||
which means the call at `generate.cpp:2008-2010` (today `g0.n_layers, g0.n_expert` from a default struct,
|
||||
row 10) must run after the metadata read of 3.8, not before it.
|
||||
|
||||
`native_experts.txt` already carries a type per layer and per role (gate/up share one, down may differ,
|
||||
`upstream-tooling.md` section 4; v3 header `(n_expert N)`, `expert_layout.cpp:271`), so the IQ3_XXS file's
|
||||
37/3 down split and the Q4_K_XL's Q6_K layers need no format change. The engine reads experts as three
|
||||
separate `ffn_{gate,up,down}_exps` tensors (`expert_source.cpp:2475-2500`, row 116); the shipped files are
|
||||
separate, and a fused `ffn_gate_up_exps` is refused by name rather than split (section 8, item 5).
|
||||
|
||||
### 3.8 Metadata and `ModelGeometry`
|
||||
|
||||
`check_architecture` requires `general.architecture == "qwen4exp"` and reads six `qwen4exp.*` keys with
|
||||
defaults 48/2560/24/2 (`include/strata/artifact/gguf_reader.hpp:576-597`); its callers are the native dense
|
||||
loader, the native head and embedding, and the GGUF reader (`native_dense.cpp:103`, `native_head.cpp:29`,
|
||||
`:113`, row 18). Every Qwen3.6 load dies there first. Beyond the guard, only `expert_count`,
|
||||
`expert_used_count` and the rope keys are read, under `qwen4exp.` and only with `--native`
|
||||
(`generate.cpp:2089-2096`, rows 8, 9). What `ModelGeometry` must read, all present in the file
|
||||
(`gguf-metadata.md`, metadata table; row 153):
|
||||
|
||||
| Field | Key |
|
||||
| --- | --- |
|
||||
| `n_embd`, `n_layers` | `qwen35moe.embedding_length`, `block_count` minus `nextn_predict_layers` (0 when absent) |
|
||||
| `qsa_interval` | `full_attention_interval` |
|
||||
| `ssm_state_size`, `ssm_k_heads`, `ssm_v_heads`, `ssm_d_conv`; conv channels and value dim derived | `ssm.state_size`, `ssm.group_count`, `ssm.time_step_rank`, `ssm.conv_kernel`, `ssm.inner_size` |
|
||||
| `n_head`, `n_head_kv`, `head_dim`, `n_rot`, sections, base, eps | `attention.head_count`, `head_count_kv`, `key_length`, `rope.dimension_count`, `rope.dimension_sections`, `rope.freq_base`, `attention.layer_norm_rms_epsilon` |
|
||||
| `n_expert`, `k`, `n_ff` (routed and shared) | `expert_count`, `expert_used_count`, `expert_feed_forward_length`, `expert_shared_feed_forward_length` |
|
||||
| `hc` | 1 (no key; the architecture string decides) |
|
||||
|
||||
The oracle's `read_hparams` (`ref/qwen36.py:125-150`) is the reference for defaults and derived values.
|
||||
Other default-geometry sites: the routing trace's `layer >= 48` bounds (`generate.cpp:771, 795`, row 13),
|
||||
the embedding load with `g0.n_embd` and the literal 248320 (`generate.cpp:2184-2186`, row 11), the draft
|
||||
geometry (`generate.cpp:3026`, 3.10), and the standalone planner's `Geometry` and `expert_blob`
|
||||
(`include/strata/plan/plan.hpp:22-52`, row 19), which is off the serving path.
|
||||
|
||||
### 3.9 PLE, optional at the CLI
|
||||
|
||||
The kernels already run without it: `block_layer_pre` applies the PLE only at layer 1 when `ple != nullptr
|
||||
&& ple->ready()` (`layer.hpp:524-545`, row 30), prefill and verify guard on `ple_on` (rows 68, 69). The CLI
|
||||
does not: `--native` refuses to start without `--ple-gguf` or a shard holding `per_layer_token_embd.weight`
|
||||
(`generate.cpp:1800-1815`), and without `--native` the flag is "required" with `--no-ple` called a
|
||||
"diagnostic ablation" (`:1843-1855`, rows 62, 63). The change is to make the absence of the tensor the
|
||||
normal case when the architecture has no PLE. The fixed `NG_HIST x NG_HC_DIM` history buffer (about 360 KB,
|
||||
`session.cpp:50-52`, row 29) and the `blk.1.ple_key` special cases (row 65) are dead but harmless.
|
||||
|
||||
### 3.10 The MTP drafter
|
||||
|
||||
The drafter is its own pack: `<rt_dir>/dense.txt`, `dense.bin` (every dense weight Q8_0), `experts.bin`
|
||||
written by `tools/mtp_rt.py` (`mtp.cpp:150-216`, row 70). It expects vLLM-style names
|
||||
(`fc_embedding`, `fc_hidden`, `pre_fc_norm_*`, `self_attn.*`, `mlp.shared_expert.*`, `mlp.gate`,
|
||||
`mlp.shared_expert_gate`, three `*hyper_connection*` groups; `mtp.cpp:210-212, 488-495, 503-507, 575`),
|
||||
canonical Q2_0 experts of `n_expert x BLOB` bytes in VRAM through `moe_group_resident` /
|
||||
`moe_grouped_s2` (`mtp.cpp:191, 579-583`; `s2_expert_grouped.cu:37-46` bakes 2560/640, row 121), and the
|
||||
default geometry (`generate.cpp:3026`, "the canonical model's MTP head (512 experts)", row 12).
|
||||
|
||||
Qwen3.6's draft block (`gguf-metadata.md`, "The nextn block"): `concat(rms_norm(emb) * enorm, rms_norm(h)
|
||||
* hnorm)` (embedding first) through one `eh_proj [4096, 2048]`, then a plain attention + MoE block
|
||||
(`attn_norm`, joint q+gate, q/k norm, IMRoPE, causal over its own KV, sigmoid gate, `attn_output`,
|
||||
residual, `post_attention_norm`, the same top-8 MoE plus gated shared expert, residual), `shared_head_norm`,
|
||||
the main `output.weight`. Pairing: token k with the trunk's output-normed hidden state of k-1
|
||||
(`oracle-crosscheck.md`, "Nextn / MTP"; verified at every nextn seam, 50 of 50). What the drafter keeps:
|
||||
dense attention over its own KV ring (rows 76), the main head and the `draft_vocab.bin` subset (row 77,
|
||||
the same 248,320 vocabulary, so `data/draft_vocab*.bin` carry over), `token_embd` embeds (row 78). What
|
||||
changes: the two input projections become one `eh_proj` over the concatenation (`mtp.cpp:488-495`); the
|
||||
three hc groups become three norms (`:503-507, 564-568, 613-625`; the prefill-side pass at
|
||||
`prefill.cpp:972-1086` the same); the draft experts are 256 K-quant blobs (Q5_K/Q4_K, 464 MiB in the
|
||||
Q4_K_XL file; Q3_K/Q4_K, 364 MiB in the IQ4_XS file) served by the native GPU expert kernels
|
||||
(`iq_kernels.cu`, row 120) instead of the Q2_0 grouped kernel; the geometry follows the target.
|
||||
|
||||
A Qwen3.6 draft pack: `dense.txt`/`dense.bin` with llama.cpp's names (`nextn.eh_proj`, `nextn.enorm`,
|
||||
`nextn.hnorm`, `nextn.shared_head_norm`, `attn_norm`, `post_attention_norm`, `attn_{q,k,v,output}`,
|
||||
`attn_{q,k}_norm`, `ffn_gate_inp` BF16, `ffn_gate_inp_shexp` BF16, `ffn_*_shexp`), the projections kept
|
||||
Q8_0 as stored (39 MiB), and a `native_experts.txt`-style line for the one layer's three expert tensors.
|
||||
Because the drafter is separate from the trunk file, the pack cut from the Q4_K_XL file's `blk.40` serves
|
||||
the IQ3_XXS trunk too (the plain IQ3 file has no nextn block). Draft acceptance is an empirical question per
|
||||
model; llama.cpp's own MTP arm (B4) is the external reference.
|
||||
|
||||
### 3.11 Tokenizer, chat template, vision
|
||||
|
||||
Same vocabulary and the same `qwen35` pre-tokenizer family (`gguf-metadata.md`; `tools/strata_tokenizer.py`
|
||||
refuses schemes it has not transcribed, `upstream-tooling.md` section 2). The front end uses llama.cpp's
|
||||
chat parser (`frontend/chat_parser_test.cpp`) and carries the Qwen3-Coder any-argument-order patch
|
||||
(`chat_parser_test.cpp:48`); the plan's step 5 checks it against Qwen3.6's template with
|
||||
`make test-chat-parser MODEL=<gguf>` (`Makefile:35-41`). Vision loads an mmproj through `mtmd`
|
||||
(`frontend/vision.hpp:79-87`); the `Qwen3.6-35B-A3B-MTP-GGUF-mmproj-F16.gguf` is on the VM with its SHA-256
|
||||
(`phase0-notes.md`). Nothing in the engine changes for either.
|
||||
|
||||
## 4. The memory plan
|
||||
|
||||
### 4.1 The fixed set, from measurements
|
||||
|
||||
| Item | Q4_K_XL, 262,144 | IQ3_XXS, 262,144 | Source |
|
||||
| --- | ---: | ---: | --- |
|
||||
| Non-expert weights on the GPU | 2,038 MiB | 1,597 MiB | `-lv 4` minus resident expert layers (section 1); census |
|
||||
| Draft block: 40 MiB dense + 256 experts in VRAM + ring KV + 8 x 248,320 logits | ~520 MiB | ~520 MiB (the Q4 draft pack) | census; `mtp.hpp:19`; `mtp.cpp:430-436` |
|
||||
| KV, q4_0, 10 layers | 1,440 MiB | 1,440 MiB | `phase0-notes.md` smoke rows (both arms) |
|
||||
| Session: RoPE table 64 MiB, scratch; **plus 320 MiB of indexer state unless 3.3 item 4 removes it** | ~164 MiB | ~164 MiB | `layer.cpp:559-576` |
|
||||
| CUDA context | ~230 to 300 MiB | same | nvidia-smi 9,487 (peak 9,565) minus the three buffers, Q4 row |
|
||||
| Reserve | 300 MiB (`kSmallReserveMib`) to 700 (default) | same | `generate.cpp:424, 3249` |
|
||||
| Prompt buffers: borrowed from the cache with a profile, else chunk-sized | 0 (borrow) / 1,904 MiB at chunk 2048 | 0 / 1,878 MiB | `generate.cpp:2723`; llama.cpp `-ub 2048` compute buffer |
|
||||
| **Decode-time fixed set** | **~4,760 MiB** borrowing; ~6,660 without | **~4,320** borrowing; ~6,200 without | sum |
|
||||
| Trunk experts (file) | 18,726 MiB; 1.829 MiB mean, 2.195 max | 10,594 MiB; 1.035 mean, 1.172 max | census |
|
||||
| Dense split-K attention scratch at `cap = 262,144` | 64.5 MiB per query row (516 for the verify window) | same | `qsa_decode_attn.cu:489-491` |
|
||||
|
||||
The replay and the plan used a 5.8 GB (Q4) / 4.6 GB (IQ3) fixed set that includes the 1.9 GB prompt buffer
|
||||
and excludes the drafter, and 17.4 GB / 10.5 GB of experts (`phase0-replay.md`, "Budget to slots"). The
|
||||
census moves the expert total up by 7% at Q4 and the fixed set down by the prompt buffer when prefill
|
||||
borrows; the two roughly cancel at the 11 GB rung (table 4.4).
|
||||
|
||||
### 4.2 The VRAM planner (Phase 2 step 2)
|
||||
|
||||
What exists: `--expert-cache auto` reads free VRAM, subtracts the reserve and the prompt estimate, grants
|
||||
slots at `max_blob` (`generate.cpp:3232-3300`), then for a native pack with a profile re-prices the slots
|
||||
per layer so the same VRAM holds the profile's hottest experts at their own blob sizes
|
||||
(`generate.cpp:3307-3327`, "~30% more IQ3_XXS experts than slots of the largest blob"); the prompt path
|
||||
borrows the last slots (`:4404-4425`); below `min_slots` the reserve shrinks to 300 MiB and then the start
|
||||
refuses with the numbers (`:3267-3290`, "no VRAM is left for the expert cache"). What the step adds, in the
|
||||
plan's order with one change:
|
||||
|
||||
1. Fixed set first: weights, drafter, KV for the requested context, session. **KV streaming is not a lever
|
||||
for this model** (3.3 item 6): the resident-window floor of 20,480 cells (`layer.cpp:556`) exists for a
|
||||
selection of 2,051 cells, and dense attention reads every cell. So the rule's first fallback, "stream
|
||||
the KV to RAM above a resident window", is replaced by: hold the KV in VRAM, and if the fixed set does
|
||||
not fit, lower the context toward 131,072, then refuse with the numbers and the IQ3 file's name. Never
|
||||
silently shorten.
|
||||
2. Every remaining byte becomes expert slots, sized per layer from the profile as today.
|
||||
3. The RAM tier: free RAM minus a headroom (`--resident-experts` uses 4 GiB, `generate.cpp:1508`;
|
||||
`--resident-budget-gib N` sets it, `:1516-1520`), filled with the next experts by profile rank
|
||||
(`pin_cache_complement`, `expert_source.cpp:1331`); whatever remains stays mapped from the GGUF
|
||||
(`--mmap-experts`, `:618-680`) with the `MADV_WILLNEED` warm on predicted ids (`:1129-1160`).
|
||||
4. Emulation: `--vram-cap MiB` clamps every `cudaMemGetInfo` free figure the planner reads (`:3297, 3313`)
|
||||
to `cap - used` and, so the driver sees the same pressure the real card would, allocates a blocker of
|
||||
`total - cap` at start; `--ram-cap GiB` bounds `resident_budget` and the pinned arena. The page cache
|
||||
cannot be capped from inside the process; the 12 GiB VM does that physically, and on a larger host a
|
||||
cgroup `memory.max` does.
|
||||
5. The start-up log and `/health` state the three counts (VRAM slots, RAM copies, mapped) and per-token
|
||||
counters: VRAM hits (`cache_hits`), RAM-copy hits, warm-hint count (`warm_count_`), and disk reads as
|
||||
the major-fault delta from `/proc/self/stat`, since a page-cache miss is not otherwise observable.
|
||||
|
||||
### 4.3 The 6-to-32 GB ladder
|
||||
|
||||
Budgets in the replay's decimal convention (6 GB = 5,722 MiB) except the 1080 Ti (11,264 MiB) and a 24 GB
|
||||
card (24,576 MiB). Slots at the census mean blob; "borrow" is the decode-time fixed set of 4.1, "no borrow"
|
||||
adds the chunk-2048 prompt buffer.
|
||||
|
||||
| Budget | Q4 replay basis (5.8 GB fixed, 1.70 MB/expert) | Q4 derived, no borrow | Q4 derived, borrow | IQ3 replay basis | IQ3 derived, borrow |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| 6 GB | 80 (1%) | 0 (fixed set does not fit) | ~525 (5%) | 1,360 (13%) | ~1,350 (13%) |
|
||||
| 8 GB | 1,280 (12%) | ~525 (5%) | ~1,570 (15%) | 3,280 (32%) | ~3,200 (31%) |
|
||||
| 11 GB (decimal) | 3,040 (30%) | ~2,090 (20%) | ~3,130 (31%) | 6,240 (61%) | ~5,960 (58%) |
|
||||
| 1080 Ti, 11,264 MiB | | ~2,510 (25%) | ~3,550 (35%) | | ~6,700 (66%) |
|
||||
| 12 GB | 3,640 (36%) | ~2,610 (26%) | ~3,650 (36%) | 7,200 (70%) | ~6,880 (67%) |
|
||||
| 16 GB | 6,000 (59%) | ~4,700 (46%) | ~5,740 (56%) | all | all |
|
||||
| 24 GB (24,576 MiB) | all | ~9,790 (96%) | all, ~1,090 MiB spare | all | all |
|
||||
| 32 GB | all | all | all | all | all |
|
||||
|
||||
The RAM tier at the replay's 9.5 GB usable: Q4 ~4,950 experts at the census blob (the replay's 5,590 was at
|
||||
1.70 MB), IQ3 ~8,760. The disk tier at Q4 on the 1080 Ti is then 10,240 - 3,550 - 4,950 = ~1,740 experts
|
||||
(17%) with borrowing and ~2,780 (27%) without; the replay modelled 1,610 (16%). At IQ3 everything fits VRAM
|
||||
plus RAM at every rung from 6 GB (`phase0-replay.md`, finding 5). The planner's own log at `--vram-cap`
|
||||
6/8/11/12/16/24/32 is the check of this table, within one slot of the derivation.
|
||||
|
||||
## 5. Expected envelope per budget
|
||||
|
||||
From `phase0-replay.md` (LFU, profile seed, second half of a 214,940-token trace of the IQ3_XXS model,
|
||||
decode only; the Q4 arm reuses the IQ3 routes). The parameters are parameters: `gpu_ms` 17 (an upper
|
||||
estimate from the smoke rows' busy share; 12 is a flag away), `cpu_lane_ms` 0.15 per expert (llama.cpp
|
||||
IQ3 N=18 implies 0.17), `disk_ms` 1.3 (fio 1 MiB random QD4; parallel faults may halve it), `pcie_ms` 0
|
||||
(promotions counted, not charged: 47.7 copies per token at Q4 11 GB, about 12 ms at 0.26 ms each, is the
|
||||
largest omission; charging it takes Q4 11 GB LFU from 42.5 to 27.8 tok/s). "Overlap" is
|
||||
`1000 / max(gpu, cpu, disk)`, "serial" the sum.
|
||||
|
||||
| Budget | Q4 VRAM hit | Q4 disk reads/tok | Q4 tok/s overlap / serial | IQ3 VRAM hit | IQ3 disk/tok | IQ3 tok/s overlap / serial |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 6 GB | 0.0% | 70.7 | 7.7 / 6.8 | 59.7% | 0 | 51.7 / 27.5 |
|
||||
| 8 GB | 57.9% | 51.5 | 12.6 / 10.4 | 84.4% | 0 | 58.8 / 40.9 |
|
||||
| 11 GB | 82.6% | 13.2 | 42.5 / 24.7 | 96.0% | 0 | 58.8 / 52.9 |
|
||||
| 12 GB | 86.8% | 7.1 | 58.8 / 31.8 | 97.7% | 0 | 58.8 / 55.2 |
|
||||
| 16 GB | 95.5% | 0 | 58.8 / 52.2 | 100% | 0 | 58.8 / 58.8 |
|
||||
| 24, 32 GB | 100% | 0 | 58.8 / 58.8 | 100% | 0 | 58.8 / 58.8 |
|
||||
|
||||
58.8 is `1000 / gpu_ms` and the overlap column saturates there by construction. The Belady ceiling at Q4
|
||||
11 GB is 91.0% hit, 6.6 disk reads, 58.8 / 34.6. Against it, the llama.cpp smoke points on the same card:
|
||||
Q4 N=32 **8.78 tok/s** decode, 128.6 prefill, GPU busy 15%; IQ3 N=18 **24.58** decode, 433.9 prefill, GPU
|
||||
busy 41% (`phase0-notes.md`). The plan's floors (A2: 15/10 tok/s at 8K/32K on 11 GB, 10/7 on 6 GB, 60/45 on
|
||||
24 GB; A3: 300 tok/s prefill on Pascal) sit inside these predictions except the Q4 6 GB row, which the
|
||||
plan already routes to the IQ3 file. With the census tiers (4.3) the Q4 11 GB disk term is 17 to 27% of
|
||||
experts rather than 16%, so its disk reads per token sit above 13.2; the replay is re-run with the census
|
||||
blob sizes as part of step 2, not re-derived here. Prefill is not modelled; the engine's chunked MMQ path
|
||||
amortises expert bytes across the chunk, and on Pascal the prompt MoE's fast path is a risk (section 7).
|
||||
|
||||
## 6. Execution plan (Phase 2, steps 2 to 7)
|
||||
|
||||
Step 1, the oracle and fixture, is done on `qwen36-oracle`: `ref/qwen36.py` agrees with the pinned
|
||||
llama.cpp graph on 2,155 comparisons over 116 seam families at 1.1e-4 worst absolute error, the router's
|
||||
integers identical, and all seven rival readings fail at the seam that makes them (`oracle-crosscheck.md`).
|
||||
Every harness below holds the engine to those dumps by llama.cpp's `cb()` names. Each step has a parity
|
||||
harness in the repo's negative-test discipline (`gdn_parity.cpp`: every wrong reading must differ by more
|
||||
than 5% relative L1 before the right one is judged, `upstream-tooling.md` section 3), runs on the 1080 Ti
|
||||
under `STRATA_EXPERIMENTAL_SM60=ON` (sm_61) from the first build and on a rented sm_86 card for compile
|
||||
speed; a kernel passes when it passes on both. Steps 2 to 4 need seconds of GPU per run and proceed while
|
||||
the Phase 0 sweeps hold the card. Effort weights sum to 100 for steps 2 to 7.
|
||||
|
||||
**Step 2, geometry, metadata, sizing (15%).** Files: `gguf_reader.hpp:576-597` (accept `qwen35moe`, read
|
||||
the 3.8 key set), `layout.hpp:27-59` (`hc = 1`, derived conv channels and value dim, no indexer fields),
|
||||
`generate.cpp:2008-2010, 2073-2096, 2184-2186, 771, 795` (geometry from the file before the layout load;
|
||||
the embedding dims from it), `expert_layout.cpp:284` (the leak), `expert_source.cpp:2475-2500` (fused
|
||||
forms refused by name), `generate.cpp:1800-1815, 1843-1855` (PLE optional), the planner
|
||||
(`generate.cpp:3232-3327`) with the 4.2 rule, `--vram-cap`, `--ram-cap`, the counters, `tools/make_profile.py`
|
||||
(`N_LAYER = 48`). Harness: `ModelGeometry` from the synthetic GGUF (`tools/qwen36_synth_gguf.py`) and the
|
||||
real file equals the oracle's `HParams` field by field; the planner's log at the seven caps reproduces
|
||||
table 4.3. Negative tests: a `qwen4exp` file refused with its name; a 48 x 512 profile refused
|
||||
(`expert_cache.cpp:43`); a `--fused-gate-up` fixture refused by tensor name; `--vram-cap` below the fixed
|
||||
set refuses with the context it would need. No GPU beyond the planner's run.
|
||||
|
||||
**Step 3, kernels and the block (45%).** In order of risk:
|
||||
|
||||
- *GDN (3.2):* SiLU in the four kernels; `gdn_parity.cpp` at `h_v 32` with sigmoid as the negative, plus the
|
||||
existing four traps (pairing, decay order, conv direction, l2 epsilon); `gdn_rec_parity.cu` at `VPK 2`.
|
||||
Seams: `conv_output_silu-0`, `new_state-0`, `final_output-0`.
|
||||
- *Dense attention (3.3):* the identity-`ids` producer; `G` templated at 8; the indexer skipped in
|
||||
`qsa_layer` and the verify attention step; the state without indexer buffers; `cap = max_cells`; the
|
||||
split-K scratch bounded. Harness: `qsa_parity.cpp`'s attention cases with `ids` identity against the
|
||||
oracle's `kq_soft_max-3`, `kqv-3`, `attn_gated-3`, and a 300-cell case where the old width (2,051) and
|
||||
the dense width differ. Negative tests: `G = 12` on 16 heads (refused, not mis-indexed), the gate skipped
|
||||
(1.03 relative L1 at `attn_gated-3`), adjacent-pair RoPE (0.20 at `kqv-3`), both from the oracle's
|
||||
controls.
|
||||
- *Router and shared expert (3.4):* `router_top10_parity.cpp` at 256/8 with its tie fixtures; the BF16
|
||||
rounding of the F32 router measured as a flip rate on the real file's first 8 tokens with the quantized-
|
||||
mode gates; `shared_expert_parity.cpp` at 512 with the 1-D F32-to-BF16 gate. Seams: `ffn_moe_topk-N`,
|
||||
`ffn_moe_weights_norm-N`, `ffn_shexp_gated-N`.
|
||||
- *The block without hyper-connections (3.5):* `layer.cpp` and `verify.cpp` both, `session.cpp:141-148`,
|
||||
the head. Harness: the layer composition test, Maya's shape: layer 0 (GDN + MoE) and layer 3 (attention +
|
||||
MoE) of the synthetic model through the engine's kernels, every seam held to the dumps; then the verify
|
||||
window on an 8-token sequence against the oracle's `l_out-N` per position, with the window's row
|
||||
arithmetic required to equal the single-token path (the discipline `verify.cpp:773-774` already states).
|
||||
Negative tests: the GR read with identity weights (not a plain norm), the post-attention norm skipped,
|
||||
`k = 10` on an 8-expert file.
|
||||
- *Prefill (3.6):* the constants and the eight literal sites; the GDN kernels forked at 32/16/8192; the
|
||||
route kernel at `k`; the split-q and gate kernels at 16 heads; `moe_fused_iq.cu` at 2048/512. Harness:
|
||||
the restored `tests/cuda/prefill_*_test.cpp` plus chunked-prefill-then-decode against token-by-token
|
||||
decode on a 40-token sequence (the oracle's `base_c7` case: chunks of 7). Negative tests: `VPK 3` on 32
|
||||
heads, top-10 routing on 8.
|
||||
|
||||
**Step 4, pack, drafter, runner (20%).** `tools/iq_pack.py`: a `qwen35moe` entry in `FORM`/`ROUTERS`
|
||||
(`ssm_alpha`, `ssm_beta`, `ffn_gate_inp`, `ffn_gate_inp_shexp` F32 to BF16 under `--compat-bf16` with
|
||||
`compat-bf16.json`; norms, `ssm_a`, `ssm_dt.bias`, `ssm_conv1d` F32 copied; projections served natively),
|
||||
`native_experts.txt` v3 per layer; `tools/test_iq_pack.py`'s `write_gguf()` fixtures at the new
|
||||
architecture. The draft pack of 3.10 from the MTP file's `blk.40` (a new `tools/mtp_qwen36_pack.py`
|
||||
replacing `mtp_pack.py`/`mtp_rt.py`), `mtp.cpp` and `prefill.cpp:972-1086` on the plain graph, the draft
|
||||
experts through the native GPU kernels, `generate.cpp:3026` following the target. `make_profile.py` from
|
||||
the E0 trace (40 x 256). Harness: the drafter's one-row forward against the oracle's `--mtp` dumps
|
||||
(`mtp_eh_proj`, `mtp_attn_gated`, `mtp_ffn_out`, `result_output`; 50 nextn seams); the streaming runner
|
||||
held to the oracle at every position of the 11- and 40-token cases, autoregressive and chunked
|
||||
(`base_ar`, `base_c7`); then the real Q4 file, greedy, against llama.cpp's output distribution (top-1
|
||||
agreement and KL per teacher-forced position, Maya's quantized-mode gates: no monotone positional drift,
|
||||
selection equal at probed layers). Negative test: a 4 KB weight corruption must move the logits by more
|
||||
than 1e-2 (the mutation-sensitivity gate).
|
||||
|
||||
**Step 5, serve and measure (10%).** The 1080 Ti at 11 GB, then `--vram-cap` 8 and 6; the other rungs when
|
||||
a card frees up. `tools/calibrate.py` for `--pcie-frac`, `--spec-min-p`, `--pool-workers`; regina's harness
|
||||
and the three instruments (`nvidia-smi` 100 ms, `nvprof` on Pascal, `perf stat`); the engine's points on
|
||||
`ladder-baseline.png`; H5. `make test-chat-parser MODEL=<gguf>` against the template; the any-argument-order
|
||||
patch checked for misfires; images through `--mmproj`. Acceptance A1 to A5 per rung.
|
||||
|
||||
**Step 6, the Pascal cards and the fat binary (5%).** `CMakeLists.txt:138-176`: `STRATA_EXPERIMENTAL_SM60`
|
||||
default ON, `CMAKE_CUDA_ARCHITECTURES=61;70;75;86;89;120`, CUDA 12.8 (the sm_120-with-12.8 warning at
|
||||
`:166-169` stays; RTX 50 is built, not measured). `cuobjdump --list-elf | grep sm_` after every build. The
|
||||
1070 Ti and the 1060 against B1b; the sm_75+ paths checked on the 4090 or A6000 when one is free.
|
||||
|
||||
**Step 7, README (5%).** The supported model and checksums, the ladder against the baseline, the sizing
|
||||
rule in words, the Pascal caveats.
|
||||
|
||||
The critical path runs through step 3's block-and-verify rewrite and its composition harness; the dense
|
||||
attention kernel is the one new kernel, the rest is parameterisation and removal.
|
||||
|
||||
## 7. Risks
|
||||
|
||||
1. **Nobody has run this engine on Pascal.** The build refuses `cc < 75` without the experimental flag;
|
||||
the flag is "community-tested, not in the ready-made engine" for sm_60/sm_70 (`CMakeLists.txt:150-160`),
|
||||
and Maya requires Volta. The 1080 Ti is sm_61, so `__dp4a` is native and only the `__nanosleep` shim
|
||||
applies (`dp4a.hpp:27-40`).
|
||||
2. **FP16 on GP102/GP104/GP106 runs at 1/64 rate.** 21 kernel files touch half types. Conversions
|
||||
(`__half2float`, the `hf()` stores in `prefill/kernels.cu:614, 761`, the fp16 K/V reads in
|
||||
`qsa_decode_attn.cu`) are full rate; half *arithmetic* is not. The audit must separate the two in
|
||||
`native_mmvq.cu`, `iq_kernels.cu`, `s_gemv.cu`, `shared_expert.cu` and the prefill kernels. The prompt
|
||||
MoE is the exposed case: the MMQ (dp4a) path is gated by `mmq::built()`/`mmq::fits`
|
||||
(`prefill.cpp:676-684`) and its tests exit 77 below sm_80 (`CMakeLists.txt:1076`); the fallback is the
|
||||
FP16 GEMM path over dequantized fp16 weights (`prefill.cpp:907`), which is exactly the slow case. The
|
||||
A3 floor of 300 tok/s prefill on Pascal depends on the dp4a MMQ running on sm_61, where llama.cpp's own
|
||||
MMQ does run.
|
||||
3. **Prompt attention on Pascal is the decode kernel.** `qsa_prompt_attn_batch` returns false for
|
||||
`cc < 70` (`qsa_prompt_attn.cu:1433`) and prefill falls back to `qsa_decode_attn_batch` over the chunk
|
||||
(`prefill.cpp:2222-2228`): correct, but a 2,048-query chunk through a decode-shaped kernel is a
|
||||
throughput risk, and its split-K scratch is the 64.5 MiB-per-row item of 3.3.
|
||||
4. **Memory items the plan did not count:** the draft block (~520 MiB), the dead indexer state (320 MiB
|
||||
at 256K unless removed), the dense scratch, and the uniform-slot grant before the per-layer re-pricing
|
||||
(`generate.cpp:3307-3327`), which is 17% of capacity at Q4 (2.195 versus 1.829 MiB) if the profile is
|
||||
absent and the re-pricing does not run.
|
||||
5. **KV streaming does not apply** (3.3 item 6): a 6 GB card at 256K holds the KV in VRAM or lowers the
|
||||
context; there is no third option in this engine without a CPU attention path.
|
||||
6. **Numerical:** BF16 rounding of the F32 router and GDN gates (3.4); the router's flip rate is measured
|
||||
on the real file, and the acceptance gates are top-1 and KL, not per-logit tolerances, as Maya's
|
||||
cross-check found (two flips in 512 explained by 1e-5 selection gaps).
|
||||
7. **Verify-only decode.** Every token of a native pack goes through `verify.cpp` with `--spec T >= 2`
|
||||
(`generate.cpp:2178`); the plain IQ3 file has no draft block, so its drafter is the Q4 file's `blk.40`
|
||||
(3.10). Draft acceptance on Qwen3.6 is unmeasured; the prompt-lookup drafter alone leaves short windows.
|
||||
8. **The replay's model:** `pcie_ms` 0, one IQ3 trace reused for Q4, a cache that never resets, no
|
||||
prefill, `gpu_ms` an upper estimate (`phase0-replay.md`, "Limits"); the census blob sizes shift the Q4
|
||||
disk tier up (4.3). The engine's counters, not the replay, decide H4 and H6.
|
||||
9. **The host.** VM 211 has 8 vCPU of a Zen 1 shared with VM 220 and AVX2 only; the native expert path then
|
||||
runs ggml-cpu `vec_dot` for the i-quants and the AVX-2 kernels for the rest (`generate.cpp:2068-2072`).
|
||||
The 0.15 ms CPU lane is the replay's assumption; `perf stat` measures it.
|
||||
10. **Upstream tooling gaps:** no published Python oracle for the Flash-Next kernels, so the parity files'
|
||||
C++ references are the only pins of the existing semantics (`upstream-tooling.md` section 1); the
|
||||
`bench/micro` llama.cpp-oracle tests cannot be restored.
|
||||
|
||||
## 8. Disagreements with the plan
|
||||
|
||||
1. **Section 2, the sizing rule's first fallback ("stream the KV to RAM above a resident window").** Not
|
||||
available for dense attention (3.3 item 6): streaming resolves the selected cells, and every cell is
|
||||
selected. The rule becomes KV in VRAM, then lower the context, then refuse. H3's "6 GB needs the KV
|
||||
streamed" is replaced by: 6 GB at Q4 holds the fixed set at 256K only if prefill borrows from the cache
|
||||
(~525 slots, table 4.3), else it takes 131,072 or the IQ3 file.
|
||||
2. **Section 2, the fixed set.** Non-expert weights are 2,038 MiB at Q4 and 1,597 at IQ3, not ~3.1 / ~1.9
|
||||
GB; the prompt buffer is 1.9 GB at chunk 2048, not 0.8; the drafter (~520 MiB) is missing from the
|
||||
table. The plan says Phase 0 numbers replace the estimates; this study does so and adds the drafter.
|
||||
3. **Section 2, the expert totals.** Q4 trunk experts are 18,726 MiB (19.6 GB), 1.829 MiB mean and 2.195
|
||||
max per expert, not 17.4 GB / 1.7 MiB; IQ3 agrees (10,594 MiB). The 11 GB rung's tiers at Q4 shift to
|
||||
~3,550 VRAM / ~4,950 RAM / ~1,740 disk with borrowing, and the replay's 13.2 disk reads per token is a
|
||||
lower bound until it is re-run at the census sizes.
|
||||
4. **Section 5 step 3, "`native_flash_attn.cu` is the fallback for prompts."** It is a diagnostic adapter
|
||||
for contexts up to 256 with 24 heads hard-coded (`native_flash_attn.cu:196-206`, `layer.hpp:53`). The
|
||||
prompt path is `qsa_prompt_attn.cu`, and on Pascal it is the batched decode kernel (risk 3). The dense
|
||||
prompt attention comes from parameterising those two, not from `native_flash_attn.cu`.
|
||||
5. **Section 5 step 2, "accept llama.cpp's fused `ffn_gate_up_exps` and `attn_qkv` forms or split them at
|
||||
pack time."** No shipped Qwen3.6 file uses either (`gguf-metadata.md`). The study scopes this to a
|
||||
named refusal in `check_experts_gguf` and `native_dense.cpp:31-33`; the oracle's fused cases stay as
|
||||
evidence of the layouts should a file appear.
|
||||
6. **Section 5 step 2, "per-layer prefetch hints as Maya's section 7 added."** This tree already has them:
|
||||
`FileExpertSource::warm` issues `MADV_WILLNEED` per role (`PrefetchVirtualMemory` on Windows) for the
|
||||
predicted ids (`expert_source.cpp:1129-1160`, `1264`). Nothing is ported from Maya; step 2 verifies the
|
||||
hint fires on the Qwen3.6 pack's offsets and counts it.
|
||||
7. **Section 2, "which file" (Q4_K_M-MTP, or Q4_K_XL plus a separately packed head).** The Q4_K_XL from the
|
||||
MTP repository (rev 5bc3e238, SHA in `phase0-notes.md`) already carries `blk.40` (753 tensors). It is
|
||||
the default file, and its `blk.40` is the draft pack for both arms (3.10).
|
||||
8. **Section 1, "every kernel path on these cards must be FP32 or dp4a int8."** Agreed for arithmetic;
|
||||
fp16 *storage* with conversion (the KV pools, the fp16 stores in prefill) is full rate on Pascal and
|
||||
stays. The prompt MoE's dp4a MMQ must be enabled on sm_61 (risk 2), which the plan does not list.
|
||||
|
||||
Nothing else in Sections 0, 2 and 5 is contradicted: the target, the three tiers on the primary rung, the
|
||||
Q4 default with the IQ3 arm, the Pascal-first build, the step order and the acceptance thresholds stand.
|
||||
@@ -1,290 +0,0 @@
|
||||
# Flash-Next geometry and extras baked into the Strata engine (6f32ec0, engine 0.1.39)
|
||||
|
||||
Scope: `src/` and `include/`. Target: Qwen3.6-35B-A3B (hidden 2048, 40 layers, GDN 16 k-heads / 32 v-heads,
|
||||
16 attention heads / 2 KV heads of 256, dense attention, 256 experts top-8 of 512 plus a shared 512, no
|
||||
hyper-connections, no PLE, MTP 1 layer, vocabulary 248,320). No fixes are proposed here.
|
||||
|
||||
Derived Qwen3.6 numbers used below: GDN conv channels 8192 (2*2048 + 4096), GDN value dim 4096, attention
|
||||
`q_full` width 8192 (16 * 2 * 256), attention output width 4096, GQA group 8 (16 / 2), 40 layers = 30 GDN + 10 attention.
|
||||
|
||||
Classes:
|
||||
|
||||
- **RT**: already a runtime parameter (`ModelGeometry`, pack metadata, tensor shape). Fine as is.
|
||||
- **CT**: a compile-time constant that disagrees with Qwen3.6. Must change.
|
||||
- **CT-ok**: a compile-time constant that is an upper bound or a value Qwen3.6 shares. Needs no change.
|
||||
- **ST**: a structural assumption. Needs a code path, not a number.
|
||||
|
||||
Line numbers are from the current tree. Where a path only runs for the canonical Q2_0 pack (not the `--native` GGUF
|
||||
pack that Qwen3.6 would use), the note says "canonical only".
|
||||
|
||||
## A. The central finding: `ModelGeometry` is a default, and only two fields are ever read from the model file
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 1 | include/strata/core/layout.hpp:28-30 | `n_embd = 2560`, `n_layers = 48`, `qsa_interval = 4` | CT | Struct defaults. Nothing reads `n_embd`/`n_layers` from the file. Interval 4 already matches Qwen3.6. |
|
||||
| 2 | include/strata/core/layout.hpp:33-38 | `ssm_k_heads 16`, `ssm_v_heads 48`, `ssm_conv_channels 10240`, `ssm_value_dim 6144` | CT | Conv channels and value dim are stored members, not derived from heads. Changing `ssm_v_heads` alone leaves them wrong. Heads 16 and state 128 and d_conv 4 already match. |
|
||||
| 3 | include/strata/core/layout.hpp:41-45 | `n_head 24`, `idx_q_heads 4`, `idx_key_dim 128` | CT | `n_head` must be 16. `n_head_kv 2` and `head_dim 256` match. Indexer fields are meaningless for Qwen3.6. |
|
||||
| 4 | include/strata/core/layout.hpp:48-49 | `hc = 4`, `hc_lr = 320` | CT / ST | No "hc = 1" meaning exists. `hc` sizes `R`, `inject`, every GR buffer. See section B. |
|
||||
| 5 | include/strata/core/layout.hpp:52-53 | `n_expert = 512`, `n_ff = 640` | CT | One `n_ff` serves routed and shared experts. Qwen3.6 has 512 for both, so one field still works. |
|
||||
| 6 | include/strata/core/layout.hpp:55-58 | `hc_dim() = hc*n_embd`, `n_qsa_layers = n_layers/interval`, `n_gdn_layers` | RT | Derived correctly from the fields. |
|
||||
| 7 | src/program/generate.cpp:2073-2074 | `ModelGeometry g;` with the comment "canonical defaults", and `K = 10` | CT | `g` and `K` start from Flash-Next defaults. |
|
||||
| 8 | src/program/generate.cpp:2089-2092 | Only `qwen4exp.expert_count` -> `g.n_expert` and `qwen4exp.expert_used_count` -> `K` are read, and only when `--native` is given | RT (partial) | The only model-file overrides of geometry. `block_count`, `embedding_length`, head counts, `ssm.*`, `expert_feed_forward_length` are never read. |
|
||||
| 9 | src/program/generate.cpp:2093-2096 | Rope keys read under the `qwen4exp.` prefix | CT | Key prefix must become `qwen35moe.`. Values (base 1e7) happen to match. |
|
||||
| 10 | src/program/generate.cpp:2008-2010 | `const ModelGeometry g0;` passed to `expert_layout_load(o.pack, g0.n_layers, g0.n_expert)` | CT | Runs before the line-2091 override, so it sees 48 layers and 512 experts. The `native_experts.txt` header can still correct `n_expert` (expert_layout.cpp:271). |
|
||||
| 11 | src/program/generate.cpp:2184-2186 | `NativeEmbed::load(..., g0.n_embd, 248320, ...)` | CT | Default `n_embd` 2560 would reject a 2048-wide `token_embd.weight`. The 248320 literal equals Qwen3.6's vocabulary. |
|
||||
| 12 | src/program/generate.cpp:3026 | `static const ModelGeometry draft_geometry{}` handed to `mtp.load` | CT | The comment says the draft layer is "the canonical model's MTP head (512 experts)". Draft geometry does not follow the target. |
|
||||
| 13 | src/program/generate.cpp:771, 795 | Routing trace rejects `layer >= 48` | CT | Literal 48 in two bounds checks. |
|
||||
| 14 | src/program/generate.cpp:5769 | `kImagePad = 248056` (comment: `qwen4exp.ple.image_token_id`) | CT-ok | Only feeds the PLE hash for image cells. Dead without PLE. |
|
||||
| 15 | include/strata/core/session.hpp:48 | `SessionState::k = 10` | CT | Experts per token default. Overwritten from `K` at session init. |
|
||||
| 16 | include/strata/core/expert_source.hpp:194 | `int k_ = 10` | CT-ok | Default only; set per layer at runtime. |
|
||||
| 17 | include/strata/artifact/gguf_reader.hpp:576-578 | `Qwen4ExpGuard{block_count 48, hidden 2560, head_count 24, head_count_kv 2}` | CT | Struct defaults for the architecture guard. |
|
||||
| 18 | include/strata/artifact/gguf_reader.hpp:581-597 | `check_architecture` requires `general.architecture == "qwen4exp"` and reads `qwen4exp.block_count`, `.embedding_length`, `.expert_count`, `.expert_used_count`, `.attention.head_count`, `.attention.head_count_kv` | CT / ST | Callers: native_dense.cpp:103, native_head.cpp:29 and :113, gguf_reader.cpp:57. Every Qwen3.6 load is refused here first. |
|
||||
| 19 | include/strata/plan/plan.hpp:22-42, 49-52, 83, 133 | Standalone planner `Geometry` (48 layers, 12 QSA, 48 v-heads, 10240 channels, indexer cache term), `Costs::expert_blob = 1382400`, `vram_pool_bytes() = 5,943,000,000`, "slots of 1,382,400 B" | CT | Used only by src/plan/plan_main.cpp and src/core/device_main.cpp. Not on the serving path. Has no streaming-KV or RAM-tier model. |
|
||||
| 20 | src/core/graph.cpp (whole file) | None | RT | No geometry. Graphs are keyed by `(LayerType, n_tokens)`. |
|
||||
|
||||
## B. Layer composition: `layer.hpp`, `layer.cpp`, `session.cpp`
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 21 | src/core/layer.cpp:1170-1286 (`block_layer_pre`), 1319-1342 (`block_layer_post`) | Every layer is `gr_read(attn) -> mixer -> gr_write(attn) -> gr_read(ffn) -> router ... moe_finish -> gr_write(ffn)` | ST | The gated-residual read/write wraps both mixer and FFN on every layer. No plain "rms_norm -> mixer -> residual add" branch exists. |
|
||||
| 22 | src/core/layer.cpp:1231-1255 | Four GR tensors per half, prefixes `hc_attn_` and `hc_ffn_` (`norm`, `down`, `up`, `inject`), required engine forms (norm F32, other three BF16) | ST | Qwen3.6 has `attn_norm` and `post_attention_norm` (plain RMS norms) instead. Neither name is referenced anywhere in src/. |
|
||||
| 23 | src/core/layer.cpp:1088-1107 (`lm_head_mix`) | Final mix is `gr_read` with `output_hc_norm/down/up` | ST | Qwen3.6 needs `output_norm.weight` (plain RMS norm). That name is not referenced anywhere in src/. Same in verify.cpp:1123-1125. |
|
||||
| 24 | src/core/layer.cpp:1127-1145 (`block_buffers_bytes/init`) | `R` is `(hc, n_embd)`; `inject`, `inject2`, `gr_rs`, `gr_workspace_bytes(GrShapes{n_embd, hc, hc_lr})` | RT | Sized from `g.hc`. Works for hc = 1 in size, but the GR math is meaningless there. |
|
||||
| 25 | src/core/layer.cpp:1146-1158 (`dump_stride_floats`) | C1-oracle dump layout is `2*n_embd + 2*hc + n_head*head_dim + ...` | RT | Debug only. |
|
||||
| 26 | src/core/session.cpp:141-148 | The first token's residual is `hc` copies of the embedding | RT / ST | Loops `g.hc` times. With hc = 1 it is one copy. |
|
||||
| 27 | src/core/session.cpp:1, 228, 331, 424 etc. | Comments say "48 layers", but loops use `g.n_layers` | RT | Verified: loops at 55, 77, 194-205, 283, 301, 331, 391, 424, 662, 788, 856, 921 all use `g.n_layers`. |
|
||||
| 28 | src/core/session.cpp:41-44 | `gdn_state_floats = S*v_heads*S + conv_channels*(d_conv-1)` | RT | From `ModelGeometry`. Correct once row 2 is fixed. |
|
||||
| 29 | src/core/session.cpp:50-52, 71, 124-126, 159-162 | `ple_hist_bytes() = NG_HIST * NG_HC_DIM * 4` (9 x 10240 floats) is always carved and zeroed | CT-ok | Fixed ~360 KB per session, allocated even with no PLE. Harmless but dead. |
|
||||
| 30 | include/strata/core/layer.hpp:524-587 and src/core/layer.cpp:1192-1229 | PLE runs only at `layer == 1`, and only when `ple != nullptr && ple->ready()` | RT | PLE is optional in the block. See rows 62 to 66 for what forces it on. |
|
||||
| 31 | src/core/layer.cpp:355 | `moe_route` requires `1 <= k <= 64`; `moe_finish`/`moe_combine_parts` the same (456, 472) | RT | K = 8 is fine. |
|
||||
| 32 | src/core/layer.cpp:370 | Native fused router only when `n_expert == 512 && k == 10`, else generic `router_top10` | RT | Guarded at runtime. 256/8 takes the generic kernel (row 87). |
|
||||
| 33 | src/core/layer.cpp:396 | `moe_route_window` batched path excluded when native router active at 512/10 | RT | Same guard. |
|
||||
| 34 | src/core/layer.cpp:335-354 | `moe_buffers_*` sized from `n_expert`, `k`, `n_ff` | RT | |
|
||||
| 35 | src/core/layer.cpp:418-451 (`moe_shared`) | Shared expert has a sigmoid scalar gate `ffn_gate_inp_shexp` that must be engine form BF16 (`Bf16InF32`); the three projections need S-forms | ST | Qwen3.6 has the same scalar gate. Its GGUF dtype (F32 or BF16) has to match what the loader produces; see the tensor tables below. |
|
||||
| 36 | src/core/layer.cpp:223-333 (`gdn_layer`) | Sizes from `g.ssm_*`; recurrence head pairing is `head % h_k` | RT | Matches ggml `repeat` tiling. Needs `h_v % h_k == 0` (32 % 16 = 0). |
|
||||
| 37 | src/core/layer.cpp:247-248 | Fused conv path requires `d_conv == 4 && state_size == 128`; fused step requires `state_size == 128` (306) | CT-ok | Qwen3.6 matches. |
|
||||
| 38 | src/core/layer.cpp:276 | `scale_inplace(b.h, qk, 1/sqrt(S))` on the legacy (non-native) path | RT | |
|
||||
| 39 | src/core/layer.cpp:288-318 and kernels (rows 76-79) | GDN output gate is `rms_norm(o) * ssm_norm * sigmoid(z)` | **ST / CT** | **Qwen3.6 uses SiLU(z), not sigmoid(z).** llama.cpp qwen35moe.cpp:273 `ggml_silu(gate)`, qwen4exp.cpp:481 says "the one numerical difference from Qwen3.5's GDN". The layer.hpp:16 comment records it. This is the only numerical (not geometric) GDN difference. |
|
||||
| 40 | src/core/layer.cpp:505 (`qsa_shapes`) | Starts from `qsa_real_shapes()` then overrides `n_head`, `n_head_kv`, `head_dim`, `idx_*` from `ModelGeometry` | RT / CT | `n_rot = 64`, `idx_block = 4`, `idx_top_k = 2048`, `page_size = 4` stay compile-time (rows 41 to 44). `n_rot 64` matches Qwen3.6 (0.25 * 256). |
|
||||
| 41 | include/strata/kernels/qsa.hpp:98-113 (`qsa_real_shapes`) | `n_head 24`, `idx_n_head 4`, `idx_dim 128`, `idx_block 4`, `idx_top_k 2048`, `page_size 4` | CT | Used by layer.cpp:505, mtp.cpp:71, verify.cpp:~100, prefill.cpp:862 etc. |
|
||||
| 42 | include/strata/kernels/qsa.hpp:144-147, 282 | `qsa_selection_width = min(n_kv, idx_top_k + idx_block - 1)`; `kTopkMaxCells = 32768` | ST | Attention reads only the selected cells, via `ids`. With the indexer absent there is no selection, so every cell must attend. |
|
||||
| 43 | src/core/layer.cpp:559-575, 761-790 | `qsa_state_bytes` / `qsa_buffers_bytes` include `idx_pooled`, `idx_tail`, `idx_dead`, `pooled_rows = max_cells/idx_block + 2`, indexer scratch, `cell_scores` | ST | The KV state always carries indexer state (about `max_cells/4 * 128 * 4` B per layer). The drafter already passes `ring_cells > 0` for a state "which has no indexer" (layer.cpp:527-531, `pooled_rows = 2`). |
|
||||
| 44 | src/core/layer.cpp:876-1019 (`qsa_layer`) | Always runs: `indexer.k_proj` BF16 projection (962), indexer key append (945-948), `indexer.q_proj` + norm + rope (962-964), block scores + top-k (966-975), KV resolve, gather/attend over the selected `ids` | ST | The indexer is not optional in this function. It requires `indexer.{k,q}_proj.weight` BF16 and `indexer.{k,q}_norm.weight` (line 891 and the `Req` list). A dense path would skip steps 3, 5-indexer, 7, 8-score/select and attend over `0..n_kv`. |
|
||||
| 45 | src/core/layer.cpp:891-897 | `w_idxk = v.get("indexer.k_proj.weight")` and `w_idxq` are dereferenced, with a BF16 form check | ST | Null here is an error, not a skip. |
|
||||
| 46 | src/core/layer.cpp:938-1010 | KV in 4 formats (fp16 / int8 / q4_0 / k8v4), hybrid rotations (`fwht256`), paged pools | RT | `head_dim 256` only (kv_q4.cu:176). Same for Qwen3.6. |
|
||||
| 47 | src/core/layer.cpp:556 | `qsa_kv_resident_min() = 20480` cells | CT-ok | Streaming floor. Independent of geometry. |
|
||||
|
||||
## C. Loader, layout, metadata
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 48 | src/core/layout.cpp:50-80 | `check_one` requires per layer: `hc_attn_{down,up,inject}`, `hc_ffn_{down,up,inject}` with `hc_dim x hc_lr` shapes | ST | `blk.N.hc_*` do not exist in a Qwen3.6 GGUF. |
|
||||
| 49 | src/core/layout.cpp:60-63 | `ffn_gate_inp [n_embd, n_expert]`, `ffn_{gate,up}_shexp [n_embd, n_ff]`, `ffn_down_shexp [n_ff, n_embd]` | RT | Use `ModelGeometry`. |
|
||||
| 50 | src/core/layout.cpp:65-70 | GDN: `attn_qkv [n_embd, conv_channels]`, `attn_gate [n_embd, value_dim]`, `ssm_out [value_dim, n_embd]`, `ssm_conv1d [d_conv, channels]`, `ssm_alpha/beta [n_embd, v_heads]` | RT | Same orientation as llama.cpp qwen35moe. |
|
||||
| 51 | src/core/layout.cpp:72-79 | Attention: `attn_q [n_embd, 2*n_head*head_dim]`, `attn_k/v [n_embd, n_kv*head_dim]`, `attn_output`, and `indexer.q_proj`, `indexer.k_proj` | RT / ST | Attention shapes RT. The two indexer tensors are ST (required). |
|
||||
| 52 | src/core/layout.cpp:97-106 | 1-D set: `hc_attn_norm`, `hc_ffn_norm` (`hc_dim`, F32), `ffn_gate_inp_shexp` (BF16), `ssm_a`, `ssm_dt.bias`, `ssm_norm`, `attn_q_norm`, `attn_k_norm`, `indexer.q_norm`, `indexer.k_norm` | ST | Same split as rows 48 and 51. |
|
||||
| 53 | src/core/layout.cpp:162-169 | `check_all` counts `g.n_qsa_layers()` / `g.n_gdn_layers()` | RT | |
|
||||
| 54 | src/core/layout.cpp:141, 149; layout.hpp:91 | `check_layer` / `check_all` have no call site in src/ | n/a | Grep finds none. The shape assertions are not enforced at load in this tree. Parity tools outside src/ may call them. |
|
||||
| 55 | include/strata/core/layout.hpp:63 | `is_qsa_layer = layer % interval == interval - 1` | RT | Layers 3, 7, ..., 39 for Qwen3.6. |
|
||||
| 56 | src/core/weights.cpp:91, 123, 146-191 | Loads whatever `<pack>/index.txt` lists (19 fields per row), into an arena | RT | Name-driven and shape-driven. The model-specific part is the pack builder (`tools/pack_index.py`, `tools/iq_pack.py`, not in this tree). |
|
||||
| 57 | src/core/native_dense.cpp:31-33 | Native dense GGUF suffixes: `.attn_qkv`, `.attn_gate`, `.ssm_out`, `.attn_q`, `.attn_k`, `.attn_v`, `.attn_output`, `.ffn_{gate,up,down}_shexp` (all `.weight`) | RT | The names match llama.cpp. A fused attention-layer `attn_qkv` (a llama.cpp option) would not match the engine's separate q/k/v. |
|
||||
| 58 | src/core/native_dense.cpp:102-104, 169-172 | Needs `general.architecture` passing `check_architecture`; each native tensor must already be in the canonical table with a matching 2-D shape | ST | See row 18. Also requires a pack index entry per tensor. |
|
||||
| 59 | src/core/native_head.cpp:29, 32-39 | `output.weight` must be `[n_in, n_out]`; `n_in % 256 == 0` | RT | 2048 % 256 = 0. `n_out` comes from the pack. |
|
||||
| 60 | src/core/native_head.cpp:108-128 | `token_embd.weight` must be `[n_embd, n_vocab]` | RT | Caller passes the literals from row 11. |
|
||||
| 61 | src/core/layer.cpp:1033-1087 (`embed_row`) | `w->ne0 != g.n_embd` is an error | RT | Follows `g.n_embd`. |
|
||||
|
||||
## D. PLE and the n-gram table
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 62 | src/program/generate.cpp:1800-1815 | `--native` requires `--ple-gguf` (or a shard holding `per_layer_token_embd.weight`); `--native` plus `--no-ple` is refused | ST | Qwen3.6 has no such tensor, so every native launch is refused. |
|
||||
| 63 | src/program/generate.cpp:1843-1855 | Without `--native`, `--ple-gguf` is "required"; `--no-ple` is called a "diagnostic ablation" | ST | PLE is mandatory at the CLI, optional in the kernels. |
|
||||
| 64 | src/program/generate.cpp:2395-2500 | When a PLE table is opened, the pack must contain `blk.1.ple_{key,value,norm_key,norm_query,norm_conv,conv1d}.weight` or the launch fails ("a DIFFERENT MODEL") | ST | Skipped when `--no-ple`. |
|
||||
| 65 | src/core/native_dense.cpp:29-30, 65-73, 156; generate.cpp:2207-2209, 1956 | Special-casing of `blk.1.ple_key.weight` | ST | Dead without PLE. |
|
||||
| 66 | include/strata/kernels/ngram.hpp:31-49 | `NG_N_EMBD 2560`, `PLE_HEAD_DIM 160`, `NGRAM_SIZE 3`, `HEADS_PER_NGRAM 8`, `PLE_N_HEADS 16`, `NG_HC 4`, `NG_HC_DIM 10240`, `NG_HIST 9`, `PLE_TABLE_ROWS 320001536`, `PLE_EOS_TOKEN_ID 248044` | CT-ok | All PLE-only. Dead if PLE is skipped. `NG_HIST` x `NG_HC_DIM` still sizes a session buffer (row 29). |
|
||||
| 67 | src/kernels/cuda/ple.cu:238; native_ple_postops.cu:35, 98; include/strata/kernels/native_ple_postops.hpp:6 | `static_assert(NG_N_EMBD == 2560 ...)`; `N = 2560, H = 4, HISTORY = 9` | CT-ok | Compiles regardless; never launched without PLE. |
|
||||
| 68 | src/prefill/prefill.cpp:543-549, 806-814, 924-925, 1401, 1590-1599, 1683-1714, 1920 | Prefill allocates `ple_emb`, `ple_norm`, pinned PLE staging; runs the PLE at layer 1 when `ss.ple.ready()` | RT | Guarded by `ple_on`. Buffers are still allocated (about `T * 2560 * 4`, `NG_HC_DIM * 4`). |
|
||||
| 69 | src/core/verify.cpp:370, 408, 559, 636-675, 1311, 1405 | Verify window stages and runs the PLE at layer 1 when `ss.ple.ready() && ple_stage()` | RT | Guarded. |
|
||||
|
||||
## E. MTP drafter (`mtp.cpp`, `mtp.hpp`)
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 70 | src/core/mtp.cpp:150-216 | Loads `<rt_dir>/dense.txt`, `dense.bin`, `experts.bin` produced by `tools/mtp_rt.py` (not in this tree), all dense weights as Q8_0 | ST | The drafter does not read the GGUF. |
|
||||
| 71 | src/core/mtp.cpp:210-212 | Required tensors: `fc_embedding.weight`, `fc_hidden.weight`, `self_attn.{q,k,v,o}_proj.weight`, `mlp.shared_expert.{gate,up,down}_proj.weight` | ST | vLLM-style names. Qwen3.6's MTP has one `nextn.eh_proj [2*n_embd, n_embd]` over `[enorm(emb), hnorm(h)]`, not two separate projections. |
|
||||
| 72 | src/core/mtp.cpp:488-495 | `pre_fc_norm_embedding` -> `fc_embedding`; `pre_fc_norm_hidden` over `hc*n_embd` -> `fc_hidden` per stream -> `R = h + e` broadcast over `hc` streams | ST | Qwen3.6: `eh_proj(concat(enorm(emb), hnorm(h)))`, one stream. |
|
||||
| 73 | src/core/mtp.cpp:503-507, 564-568, 613-625 | Three hyper-connection groups: `attn_hyper_connection.*`, `mlp_hyper_connection.*`, `hyper_connection_mixer.*` | ST | Same gated-residual structure as rows 21-23. |
|
||||
| 74 | src/core/mtp.cpp:191, 200, 306-308, 579 | Drafter experts are `n_expert * cpu::BLOB` bytes in VRAM, canonical Q2_0 at 2560/640, run through `moe_group_resident` | CT | `BLOB = 1,382,400`. Qwen3.6 Q2_0 blob would be `3 * 2048 * 512 * 18/64` = 884,736 B. Message text says "the 512 experts do not fit". |
|
||||
| 75 | src/core/mtp.cpp:575, 598 | Draft router `mlp.gate.weight` BF16 `[n_embd, n_expert]`; `mlp.shared_expert_gate.weight` BF16 | RT | Shape-driven. |
|
||||
| 76 | src/core/mtp.cpp:71-78, 218-249 | Draft KV is dense attention (no indexer state read), shapes from `ModelGeometry` | RT | The header says it is "identical to the model's sparse selection below 2,051 cells". The only existing dense-attention path. |
|
||||
| 77 | src/core/mtp.cpp:428-454 | Head is the main `output.weight`; `n_vocab_ = wo->ne1`; optional `draft_vocab.bin` subset | RT | Vocabulary size is a runtime value. Subset files (`data/draft_vocab_*.bin`) are token ids into the same 248,320 vocabulary. |
|
||||
| 78 | src/core/mtp.cpp:477, 488 | Draft embeds from `token_embd.weight` | RT | |
|
||||
| 79 | src/core/mtp.cpp:251-268 | Buffers from `g.hc`, `g.hc_lr`, `g.n_head` | RT | |
|
||||
| 80 | src/prefill/prefill.cpp:972-1086 | MTP prefill reads `attn_hyper_connection.hc_norm.weight`, uses `LR`, `HC`, `fc_hidden` per stream | ST / CT | Same vLLM-style structure as row 72. |
|
||||
|
||||
## F. GDN kernels
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 81 | src/kernels/cuda/native_gdn.cu:37, 100-102, 117 | `S = 128`; grid `h_v` x `S/4`; requires `h_v % h_k == 0`, `h_v <= 65535` | RT | Heads from `GdnShapes`. State layout `(S, h_v, S)`. |
|
||||
| 82 | src/kernels/cuda/native_gdn.cu:51 | `q_head = head % h_k` | RT | Modulo pairing. |
|
||||
| 83 | src/kernels/cuda/fused_gdn.cu:12-14, 22-24, 127-129, 148-153 | `S = 128`, `RG = 4`; grid `h_v`; `qk_heads` blocks for conv+L2; `h_v % h_k == 0` | RT | |
|
||||
| 84 | src/kernels/cuda/gdn.cu:46-59, 156 | `MAX_H = 8` heads per block, `S <= 128` | RT | Legacy path; only a performance shape. |
|
||||
| 85 | src/kernels/cuda/gdn.cu:148 | `y = o * rms * ssm_norm * sigmoid_f(z)` | **CT** | **SiLU for Qwen3.6.** See row 39. |
|
||||
| 86 | src/kernels/cuda/fused_gdn.cu:69 | `... * (1/(1+exp(-zz)))` in `gdn_step_norm_kernel` | **CT** | **SiLU for Qwen3.6.** The default decode path for native packs. |
|
||||
| 87 | src/kernels/cuda/native_gdn_preprocess.cu:110-112 | `weighted * sigmoid(z)` in the out-norm kernel | **CT** | **SiLU for Qwen3.6.** The same file's `conv_silu` (53-67) and `beta_sigmoid` (86-88) are correct for both models. |
|
||||
| 88 | src/prefill/kernels.cu:324, 612 | `sigm(z)` in `gdn_rec_kernel` and `gdn_out_norm_kernel` | **CT** | **SiLU for Qwen3.6.** Prompt path. |
|
||||
| 89 | src/prefill/kernels.cu:18-19 | `N = 2560, HC = 4, D = N*HC, LR = 320`; `S = 128, HK = 16, HV = 48, C = 10240` | CT | Constants for every prompt-path GDN, GR and gate kernel. |
|
||||
| 90 | src/prefill/kernels.cu:211-215, 285-304, 345-364, 387-432, 478-570, 893-924 | GDN prompt kernels index with `HV`, `HK`, `C`; launched `<<<HV, ...>>>`, `<<<HV*NCB>>>`, `<<<HK*NCB>>>` | CT | Includes `VPK = HV/HK = 3` value heads per key head (478): 2 for Qwen3.6. `gdn_rec_kh_kernel` is specialised on it. |
|
||||
| 91 | src/prefill/gdn_rec_parity.cu | Parity harness for the above | CT | Mirrors the same constants. |
|
||||
| 92 | include/strata/kernels/gdn.hpp:11, 64; layer.hpp:10, 21, 23, 546 | Comments cite 10240 / 48 / 2560 | n/a | Comments only. |
|
||||
|
||||
## G. Attention kernels (the QSA path)
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 93 | src/kernels/cuda/qsa_decode_attn.cu:16-17, 110, 272, 453, 497 | `HD = 256`, `G = 12` (query heads per KV head); refuses with `exit(1)` unless `n_head == 12 * n_head_kv` | CT | The main decode kernel. Qwen3.6 has G = 8. |
|
||||
| 94 | src/kernels/cuda/qsa_prompt_attn.cu:21-22, 115-116, 1442-1447 | `HD = 256`, `G = 12`; refuses unless `n_head == 12 * n_head_kv` | CT | The prompt attention kernels (tensor-core). |
|
||||
| 95 | src/kernels/cuda/native_flash_attn.cu:55, 196-197, 206 | `kv = head / 12`; refuses unless `n_head == 24 && n_head_kv == 2 && head_dim == 256`; grid 24; context 1..256 | CT | Short-context adapter only. |
|
||||
| 96 | src/kernels/cuda/qsa.cu:96 | Generic `qsa_attend`/`kv_append`/`kv_gather`; requires `n_head % n_head_kv == 0` | RT | Reference-quality path. |
|
||||
| 97 | src/kernels/cuda/native_rope.cu:121 | `head_dim in {128, 256}`, `n_rot == 64` | CT-ok | Matches Qwen3.6 (partial rotary 0.25 of 256). |
|
||||
| 98 | include/strata/kernels/mrope.hpp:3-12 | Interleaved M-RoPE sections 11/11/10/0; text has `t = h = w` | CT-ok | Qwen3.6 uses the same sections. |
|
||||
| 99 | src/kernels/cuda/native_qsa_score.cu:31, 194 | Indexer: `D = 128, HEADS = 4, R = 4`, `idx_top_k == 2048` | ST | Indexer-only. Not reachable without the indexer. |
|
||||
| 100 | src/kernels/cuda/native_qsa_indexer.cu:35, 231, 259 | `D = 128, R = 4, ROT = 64` | ST | Indexer-only. |
|
||||
| 101 | src/kernels/cuda/qsa_select.cu:17-19, 161-165, 467-475, 1081, 1115, 1220 | `IDX_DIM 128`, `IDX_HEADS 4`, `R 4`; requires `cap >= qsa_selection_width(kTopkMaxCells, s)` | ST | Indexer-only. With the indexer absent nothing here runs, and nothing else produces the `ids` that `qsa_decode_attn` consumes. |
|
||||
| 102 | src/kernels/cuda/qsa_decode_attn.cu | The kernel gathers K/V through `ids` and `pools.page_table`, so it is selection-agnostic | RT | An identity `ids` would attend over every cell. No other dense decode kernel exists. |
|
||||
| 103 | src/kernels/cuda/kv_q4.cu:176, kv_q8.cu | `head_dim == 256` | CT-ok | Matches Qwen3.6. |
|
||||
| 104 | src/kernels/cuda/kv_stream.cu:23 | `RT = 1024` resolve block | CT-ok | Streaming resolve granularity. Reads `ids`. |
|
||||
| 105 | src/prefill/kernels.cu:752-761, 1016, 1020 | `split_q_kernel`, `gate_attn_kernel`: `T * 24 * 256`, `24 * 512` | CT | Prompt-path q/gate split and gate. 16 heads for Qwen3.6. |
|
||||
| 106 | src/prefill/prefill.cpp:649-650, 883-884 | `T * 12288` (= 24 * 512) for `Qf`; `T * 512` for `Kc/Vc` (2*256, unchanged); `T * ZV` for `q` and attn; `T * 128`, `T * 512` for `idx_raw`, `q_idx` | CT | `12288` and `ZV = 6144` must change. `512` for K/V stays. The two indexer buffers are dead without the indexer. |
|
||||
|
||||
## H. Experts, router, shared expert
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 107 | include/strata/kernels/cpu/expert.hpp:34-36, 40-47 | `H = 2560`, `FF = 640`, `NE = 512`, `BLOB = 1,382,400`, `ROW_GU`, `SC_GU` | CT | Canonical Q2_0 blob geometry. Canonical only. Used by the rows below. |
|
||||
| 108 | src/kernels/cpu/expert_layout.cpp:284 | `native_fmt(gt, dt, H, FF, f, err)` | **CT** | **The one compile-time leak in the native-pack path.** The layout loader builds each layer's `NativeFmt` with 2560/640 and then checks `f.bytes == blob`. A 2048/512 pack fails the "blob is X B but its formats make Y" check. |
|
||||
| 109 | src/kernels/cpu/expert_layout.cpp:233-244, 271 | `native_experts.txt` header "(n_expert N)" overrides `n_expert`; absent file means canonical pack, total = `n_layers*n_expert*BLOB` | RT | |
|
||||
| 110 | include/strata/kernels/cpu/expert_layout.hpp:20, 32, 35-37 | `n_expert = NE` default, `max_blob = BLOB` default | CT-ok | Overwritten for native packs. |
|
||||
| 111 | include/strata/kernels/cpu/native_expert.hpp:17-19; src/kernels/cpu/native_expert.cpp:64 | `kNativeActBytes = 4096`, `kNativeHBytes = 1024` upper bounds, checked at layout time | CT-ok | 2048-wide Q8_K is 2336 B; 512-wide Q8_K is 584 B. Both fit. |
|
||||
| 112 | src/kernels/cpu/native_expert.cpp:40-60 | `native_fmt(gu_type, d_type, n_embd, n_ff)` is runtime; requires whole ggml blocks | RT | 2048 and 512 are multiples of 256 and 32. K-quants and Q8_K activations work for n_ff = 512 (unlike 640). |
|
||||
| 113 | src/core/expert_source.cpp:1863-1868 (`expert_pool_dispatch`) | Refuses `n_embd != H` ("compiled for a 2560-wide activation") | CT | Canonical single-token path only. |
|
||||
| 114 | src/core/expert_source.cpp:1869-1875 | `expert_pool_dispatch` refuses a native pack outright ("single-token expert path does not take a native pack") | **ST** | **Native-pack experts run only in verify windows.** generate.cpp:~2180 also requires `--spec T >= 2` and `--prefill`. Every decoded token therefore goes through verify.cpp. |
|
||||
| 115 | src/core/expert_source.cpp:367-376, 2328; include/strata/core/expert_source.hpp:241 | Canonical size checks with `BLOB`; `ExpertDispatch::n_expert = cpu::NE`; hit path uses `cpu::H` | CT | Canonical only. `n_expert` is overwritten at generate.cpp:3683. |
|
||||
| 116 | src/core/expert_source.cpp:2475-2500 (`check_experts_gguf`) | Native experts are read from `blk.N.ffn_{gate,up,down}_exps.weight` as three separate tensors, each `[cols, rows, n_expert]` | ST | llama.cpp may fuse gate and up into `ffn_gate_up_exps` (`create_tensor_gate_up_exps`, llama-model.cpp:3253). The engine accepts only the separate form. |
|
||||
| 117 | src/core/expert_source.cpp:1979-1980 | `MAXT * 10 <= kMaxWindowEntries (128)` | CT-ok | 8 * 10 = 80; with k = 8 it is 64. |
|
||||
| 118 | src/core/expert_cache.cpp, include/strata/core/expert_cache.hpp | Slots, residency `[n_layers * n_expert]`, profile file `(n_layers, n_expert)` header, `n_layers/n_expert <= 65535` | RT | All sizes passed in. The profile header is checked against `(n_layers, n_expert)` (cache.cpp:43). |
|
||||
| 119 | src/kernels/cuda/iq_kernels.cu:1076-1140, 2543 | Native GPU expert kernels read `L.n_embd` and `L.n_ff` per layer; the fast sub-warp paths apply only when `n_ff == 640` (else 8-row fallback) | RT | Runtime guard. |
|
||||
| 120 | src/kernels/cuda/iq_kernels.cu:309-350, 512-518 | Unsloth UD-Q4_K_XL expert types already supported: Q4_K / Q5_K gate-up, Q5_1 / Q8_0 down | RT | Native GPU expert dequant kernels exist for the Qwen3.6 UD quant family. |
|
||||
| 121 | src/kernels/cuda/s2_expert_grouped.cu:37-46, 139-195, 301-346 | `H = 2560`, `FF = 640`, `ROW_GU`, `SC_GU`, blob offsets | CT | Canonical Q2_0 VRAM-hit kernels. Used for the MTP drafter's experts (row 74), not for native packs. |
|
||||
| 122 | src/core/remote_experts.cpp:16-18, 246; src/core/peer_experts.cpp:25-26, 115, 130; src/core/remote_expert_opt.cu:13-14 | `H`, `FF` from `cpu::`, `CAP = MAXT * 10`, `k != 10` refused | CT | Multi-GPU expert tiers. Out of scope for a single card. |
|
||||
| 123 | src/program/generate.cpp:3721 | `moe_hit_grouped_scratch_bytes(K, g.n_embd, cpu::FF)` | CT-ok | Over-allocates by 640 vs 512. |
|
||||
| 124 | src/kernels/cuda/router_top10.cu:65-215; include/strata/kernels/router_top10.hpp:21 | Generic top-k softmax router: `n_expert <= 512`, `k <= 32`, runtime `n_expert` and `k` | RT | Handles 256 / 8. |
|
||||
| 125 | src/kernels/cuda/native_router.cu:49, 54, 73, 97, 111-122 | Fused pinned router: `512` logits, `10` outputs, `REG 16`, hard-coded in the kernel and the validity checks | CT | Used only when `n_expert == 512 && k == 10` (row 32). Otherwise bypassed. |
|
||||
| 126 | src/kernels/cuda/native_moe.cu:62-63, 79-80 | `native_moe_combine` requires `1 <= k <= 15` | RT | |
|
||||
| 127 | src/kernels/cuda/shared_expert.cu:191, 237-239, 325-328 | `n_tok 1..8`; Q8_K activation needs `n_ff % 256 == 0` | RT | 640 failed this; 512 passes. Header comments in s_gemv.hpp:122-124 and layer.cpp:419-437 ("Q8_K is structurally impossible") describe Flash-Next only. |
|
||||
| 128 | src/prefill/kernels.cu:616-657, 928-936 | Prompt `route_kernel<REG>`: `REG 16` for 512, `REG 8` for 256; rank loop `< 10`, writes `ids[t*10 + rank]`, `lane < 10` | CT | A 256 variant exists, but top-10 is baked into the kernel. |
|
||||
| 129 | src/prefill/kernels.cu:660-692, 947, 951; moe_fused.cu:46-53, 199-203, 343; moe_mmq.cu:60-75, 249 | Canonical Q2_0 blob dequant and fused kernels: `1280 * 640`, `2560 * 160`, `n * 640`, `10 * AB` | CT | Canonical only. |
|
||||
| 130 | src/prefill/moe_fused_iq.cu:59 | `GU_ROWS_K = 2560, D_ROWS_K = 640` | CT | Native-pack fused prompt MoE. Used as K of gate/up and of down. |
|
||||
| 131 | src/prefill/prefill.cpp:90-91 | `N = 2560, HC = 4, D = N*HC, LR = 320, K = 10, NE = 512; C = 10240, ZV = 6144, HV = 48` | CT | File-wide constants. |
|
||||
| 132 | src/prefill/prefill.cpp:737 | `Prefill::init` refuses unless `g.n_embd == N && g.hc == HC && g.hc_lr == LR && ss.k == K` | CT / ST | Hard refusal; every chunked-prefill launch fails on Qwen3.6. |
|
||||
| 133 | src/prefill/prefill.cpp:681-685, 704-721, 896-907, 1294-1322, 1391 | Prompt MoE buffers: `T*K*1280`, `T*K*640`, `q8_bytes(.., 640)`, `1280 * 2560`, `2560 * 640`, `RP = 48` (1303) | CT | `1280 = 2*n_ff`, `640 = n_ff`, `2560 = n_embd`. |
|
||||
| 134 | src/prefill/prefill.cpp:1724 and loops | Iterates `g.n_layers` and `is_qsa_layer` | RT | |
|
||||
| 135 | src/prefill/prefill.cpp:854-856, 1000-1026, 1375-1380 | `grs`, `gated`, `inj`, `xq`, `ident` sized from `HC`, `D`, `LR` | CT | Hyper-connection buffers in prefill. |
|
||||
| 136 | include/strata/prefill/kernels.hpp:15-16, 40, 52, 54, 58, 79 | Declarations documented as `2560 / 4 / 320`, `48 v heads`, `512, top-10`, `[1280, 2560]`, `640`, `[T, 24, 512]` | CT | Comments describing the constants above. |
|
||||
|
||||
## I. Hyper-connection (gated residual) kernels
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 137 | src/kernels/cuda/fused_gr.cu:20-28, 253-254, 320-321, 1164-1166 | `N = 2560, HC = 4, LR = 320, D = 10240`; `DOWN_BLOCKS = LR/8`, `UP_BLOCKS = N/32`, `UPM_BLOCKS = N/16`; `fused_gr_supported()` returns `n_embd == N && hc == HC && hc_lr == LR` | CT | Default decode and verify GR kernels. |
|
||||
| 138 | src/core/layer.cpp:1195, 1319-1342, verify.cpp:336 | `fused = g_fused_gr && ... fused_gr_supported(...)`; verify refuses without it | CT / ST | Row 142. |
|
||||
| 139 | src/kernels/cuda/gr.cu, native_gr_norm.cu, native_gr_postops.cu | Generic `GrShapes{n_embd, hc, hc_lr}` unfused path | RT | The generic GR is runtime-shaped, but its semantics (down/up/inject mixing) are the hyper-connection. |
|
||||
| 140 | src/kernels/cuda/cvec.cu:11-17; verify_kernels.cu:256-291 (`broadcast_streams`, `add_streams_broadcast`) | Control-vector apply on `hc*n_embd`; stream broadcast | RT | `MAXK = 16` supports `n_embd <= 4096`. |
|
||||
|
||||
## J. Verify window (`verify.cpp`) and the speculation protocol
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 141 | src/core/verify.cpp:331-334 and layer.cpp:476-486 (`layer_verify_compatible`) | The verify window needs native BF16 projections, fused GR, fused native GDN, split-K decode attention, block top-k selection, **native QSA indexer** | ST | Verify is the only decode path for native packs (row 114). It cannot be built on a layer that has no fused GR and no indexer. |
|
||||
| 142 | src/core/verify.cpp:336-340 | Refuses unless `fused_gr_supported && ss.k == 10 && ssm_state_size == 128 && ssm_d_conv == 4` ("geometry differs from the artifact's") | CT / ST | |
|
||||
| 143 | src/core/verify.cpp:356-434 | Buffers `R_ (T*HC*N)`, `inj_`, `lo_ (T*hc_lr)`, `xn_ (T*HC*N)`, `idx_raw_L_`, `qidx_`, `tail_snap_` | RT / ST | Sized from `g.hc`, `g.hc_lr`, `idx_*`. |
|
||||
| 144 | src/core/verify.cpp:550-559 | `IQ = idx_q_heads`, `ID = idx_key_dim`, `NE = n_expert`, `TS = (idx_block-1)*ID` | RT | |
|
||||
| 145 | src/core/verify.cpp:757-761, 772-870, 1271-1311 | Attention step: `need(v, "indexer.k_proj.weight")`, `indexer.q_proj`, `indexer.q_norm`, `indexer.k_norm`; indexer append, block scores, top-k per window row; commit restores the indexer tail | ST | Same as row 44, for the multi-token path. |
|
||||
| 146 | src/core/verify.cpp:916 | Batched native router only when `NE == 512 && K == 10` | RT | Guarded. |
|
||||
| 147 | src/core/verify.cpp:1123-1125 | Head mix needs `output_hc_{norm,down,up}.weight` | ST | Row 23. |
|
||||
| 148 | src/core/verify.cpp:347-349 | `n_vocab_ = output.weight.ne1` | RT | |
|
||||
| 149 | include/strata/kernels/verify_kernels.hpp:21 | `kVerifyMaxT = 8` | CT-ok | Draft window cap. |
|
||||
| 150 | src/kernels/cuda/verify_kernels.cu:366, 397-401, 506 | Grid `48 * 8`; `kVerifyMaxT * 10 <= kResidentPlanMax` | CT-ok | The 48 is a block count, not a layer count. |
|
||||
|
||||
## K. Vocabulary, sampler, metadata keys
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 151 | src/kernels/cuda/sampler.cu:102-700 | `n_vocab` is a kernel argument everywhere; the split top-k merge handles `n_vocab <= 262,144` (607) | RT | 248,320 fits. |
|
||||
| 152 | src/program/generate.cpp:479-481 | Default EOS ids `{248044, 248046}` | CT-ok | Same tokenizer; override with `--eos-ids`. |
|
||||
| 153 | include/strata/artifact/gguf_reader.hpp:581-597 | All keys read use the `qwen4exp.` prefix | CT | Row 18. The Qwen3.6 GGUF uses `qwen35moe.*`. Also needed and not read anywhere: `qwen35moe.ssm.{conv_kernel,inner_size,state_size,time_step_rank,group_count}`, `.expert_feed_forward_length`, `.expert_shared_feed_forward_length`, `.full_attention_interval`, `.rope.dimension_sections`, `.nextn_predict_layers`. |
|
||||
| 154 | frontend/ | Tokenizer, template, tool-call parser, vision | n/a | Model-agnostic per the plan. Not part of this inventory. |
|
||||
|
||||
## Tensor names the loader expects (engine side) against llama.cpp qwen35moe
|
||||
|
||||
Engine names come from layout.cpp:50-106, layer.cpp, native_dense.cpp:31-33 and expert_source.cpp:2491.
|
||||
llama.cpp names come from `third_party/llama.cpp/src/models/qwen35moe.cpp:43-138` and `src/llama-arch.cpp:435-587`
|
||||
(pinned commit 3cf0325).
|
||||
|
||||
**One GDN layer, `blk.N.`**
|
||||
|
||||
| Engine expects | Shape / form | llama.cpp qwen35moe | Match |
|
||||
|---|---|---|---|
|
||||
| `hc_attn_norm.weight`, `hc_attn_down.weight`, `hc_attn_up.weight`, `hc_attn_inject.weight` | `[hc_dim]` F32; BF16 | none | **Engine-only (hyper-connection)** |
|
||||
| `hc_ffn_norm.weight`, `hc_ffn_down.weight`, `hc_ffn_up.weight`, `hc_ffn_inject.weight` | same | none | **Engine-only** |
|
||||
| (none) | | `attn_norm.weight` `[n_embd]` | **llama.cpp-only** |
|
||||
| (none) | | `post_attention_norm.weight` `[n_embd]` (pre-FFN norm; there is no `ffn_norm`) | **llama.cpp-only** |
|
||||
| `attn_qkv.weight` | `[n_embd, conv_channels]` | `attn_qkv.weight` `[n_embd, 2*key_dim + value_dim]` | yes |
|
||||
| `attn_gate.weight` | `[n_embd, value_dim]` | `attn_gate.weight` | yes |
|
||||
| `ssm_conv1d.weight` | `[d_conv, conv_channels]` F32 | `ssm_conv1d.weight` | yes |
|
||||
| `ssm_alpha.weight`, `ssm_beta.weight` | `[n_embd, v_heads]` BF16 | same names, `{n_embd, n_v_heads}` | yes, dtype to confirm |
|
||||
| `ssm_a` | `[v_heads]` F32 | `ssm_a` (no `.weight`) | yes |
|
||||
| `ssm_dt.bias` | `[v_heads]` F32 | `ssm_dt.bias` | yes |
|
||||
| `ssm_norm.weight` | `[128]` F32 | `ssm_norm.weight` `{head_v_dim}` | yes |
|
||||
| `ssm_out.weight` | `[value_dim, n_embd]` | `ssm_out.weight` | yes |
|
||||
| `ffn_gate_inp.weight` | `[n_embd, n_expert]` BF16 | same | yes, dtype to confirm |
|
||||
| `ffn_gate_exps.weight`, `ffn_up_exps.weight`, `ffn_down_exps.weight` | `[n_embd, n_ff, n_expert]` x2, `[n_ff, n_embd, n_expert]` | same, or fused `ffn_gate_up_exps.weight` `[n_embd, 2*n_ff, n_expert]` | yes if unfused |
|
||||
| `ffn_gate_shexp.weight`, `ffn_up_shexp.weight`, `ffn_down_shexp.weight` | `[n_embd, n_ff]`, `[n_ff, n_embd]` | same | yes |
|
||||
| `ffn_gate_inp_shexp.weight` | `[n_embd]` engine form BF16 | `ffn_gate_inp_shexp.weight` `{n_embd}` | yes, dtype to confirm |
|
||||
|
||||
**One attention layer, `blk.N.` (layers 3, 7, ..., 39)**
|
||||
|
||||
| Engine expects | Shape / form | llama.cpp qwen35moe | Match |
|
||||
|---|---|---|---|
|
||||
| the six `hc_*` tensors and two `hc_*_norm` as above | | none | **Engine-only** |
|
||||
| (none) | | `attn_norm.weight`, `post_attention_norm.weight` | **llama.cpp-only** |
|
||||
| `attn_q.weight` | `[n_embd, 2*n_head*head_dim]` (q then gate per head, interleaved) | `attn_q.weight` `{n_embd, head_dim*n_head*2}` | yes |
|
||||
| `attn_k.weight`, `attn_v.weight` | `[n_embd, n_kv*head_dim]` | same | yes, unless the GGUF fuses them into `attn_qkv.weight` (`create_tensor_qkv`) |
|
||||
| `attn_output.weight` | `[n_head*head_dim, n_embd]` | `attn_output.weight` | yes |
|
||||
| `attn_q_norm.weight`, `attn_k_norm.weight` | `[head_dim]` F32 | same | yes |
|
||||
| `indexer.q_proj.weight`, `indexer.k_proj.weight`, `indexer.q_norm.weight`, `indexer.k_norm.weight` | BF16 / F32 | none | **Engine-only (QSA indexer)** |
|
||||
| the same five MoE tensors, three shexp tensors, `ffn_gate_inp_shexp` as a GDN layer | | same | as above |
|
||||
|
||||
**Global tensors**
|
||||
|
||||
| Engine expects | llama.cpp qwen35moe |
|
||||
|---|---|
|
||||
| `token_embd.weight` `[n_embd, n_vocab]` | same |
|
||||
| `output.weight` `[n_embd, n_vocab]` (native head; mtp.cpp:428 and verify.cpp:347 read `ne1`) | `output.weight` (optional; falls back to `token_embd.weight`) |
|
||||
| `output_hc_norm.weight`, `output_hc_down.weight`, `output_hc_up.weight` | `output_norm.weight` `{n_embd}` |
|
||||
| `blk.1.ple_{key,value,norm_key,norm_query,norm_conv,conv1d}.weight` and `per_layer_token_embd.weight` | none |
|
||||
| MTP: `<rt_dir>/dense.txt` names `fc_embedding`, `fc_hidden`, `pre_fc_norm_embedding`, `pre_fc_norm_hidden`, `self_attn.*`, `mlp.*`, three `*hyper_connection*` groups | `blk.40.nextn.eh_proj.weight` `{2*n_embd, n_embd}`, `blk.40.nextn.enorm.weight`, `blk.40.nextn.hnorm.weight`, optional `blk.40.nextn.{embed_tokens,shared_head_head,shared_head_norm}.weight`, plus a full attention + MoE block under `blk.40.` (attn_norm, post_attention_norm, attn_q/k/v/output, attn_q_norm, attn_k_norm, ffn_gate_inp, ffn_*_exps, ffn_*_shexp, ffn_gate_inp_shexp) |
|
||||
|
||||
## Summary of which subsystems are runtime-parameterized
|
||||
|
||||
1. **Already parameterized:** the GDN decode kernels (state 128, head counts and head pairing by `h % h_k`, grids from `h_v`), the generic router, the shared expert (and 512 now satisfies its Q8_K rule), the native CPU and GPU expert kernels (`NativeFmt` and `L.n_embd`/`L.n_ff` per layer, UD-Q4_K_XL types already present), the expert cache, the weight loader, the sampler, `output.weight` and vocabulary size, and the drafter's dense-attention KV.
|
||||
2. **The geometry struct is never populated from the model.** Only `expert_count` and `expert_used_count` (and rope keys) are read, under a `qwen4exp.` prefix, and only with `--native`. `n_embd`, `n_layers`, head counts, `ssm.*` and `n_ff` stay at Flash-Next defaults. `check_architecture` refuses any other architecture string.
|
||||
3. **The gated residual is structural.** Every block, the output head, the verify window, the drafter and prefill assume `hc` streams with down/up/inject mixing. The fused kernels are hard-coded to 2560/4/320, and `hc = 1` has no plain-norm meaning. The plain `attn_norm`, `post_attention_norm` and `output_norm` tensors are never referenced.
|
||||
4. **Dense attention is structural.** `qsa_layer`, `verify.cpp`, the KV state size and the selection width all assume the indexer. The decode and prompt attention kernels are compile-time for group 12 (Qwen3.6 is 8) and the short-context kernel is compile-time for 24 heads. The attention kernel reads through `ids`, so it is selection-agnostic, but no producer of dense `ids` exists.
|
||||
5. **GDN output gate differs numerically:** Qwen3.6 applies SiLU(z) where the engine applies sigmoid(z) in four kernels (gdn.cu, fused_gdn.cu, native_gdn_preprocess.cu, prefill/kernels.cu). This is a semantic change, not a size change.
|
||||
6. **Native-pack decode is verify-window only.** The single-token expert dispatch refuses native packs, and the verify window demands fused GR, K = 10, and the native indexer. Any hc = 1 or dense-attention work has to land in verify.cpp as well as layer.cpp.
|
||||
7. **Prefill is the most compile-time-heavy subsystem.** `Prefill::init` refuses non-2560/4/320/10, and GDN, gate, split-q, route and MoE buffers all use literal constants (HV 48, 24 heads, 1280, 640, top-10).
|
||||
8. **One leak inside otherwise-runtime expert code:** `expert_layout.cpp:284` passes compile-time `H, FF` to `native_fmt`, so a 2048/512 pack fails the blob-size check.
|
||||
9. **PLE is optional in kernels but mandatory in the CLI.** `--native` refuses to start without `--ple-gguf`, and a table implies `blk.1.ple_*` tensors. Qwen3.6 has neither. A small session buffer (about 360 KB) is allocated regardless.
|
||||
10. **MTP drafter is separate from the GGUF** (Q8_0 `rt_dir` from `tools/mtp_rt.py`, canonical Q2_0 experts at 2560/640, three hyper-connection groups, two fc projections). It gets the canonical default geometry, not the target's. The `tools/` packers are not in this tree, so the pack and MTP tensor names are defined by scripts that were not inspected.
|
||||
@@ -1,102 +0,0 @@
|
||||
# Qwen3.6-35B-A3B GGUF: metadata and tensors as shipped
|
||||
|
||||
Dumped 2026-10-11 with `tools/gguf_reader.py` (no gguf-py) from two files:
|
||||
|
||||
- **Plain**: `/Users/robertkarl/models/qwen3.6/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` (Unsloth `UD-IQ3_XXS`, 733 tensors, `general.file_type` 23, 13.2 GB). The file the port is built against.
|
||||
- **MTP**: `/Users/robertkarl/models/qwen3.6/MTP/Qwen3.6-35B-A3B-UD-IQ4_XS-MTP.gguf` (753 tensors, 41 blocks). Same architecture plus the nextn block. Shown only where it differs.
|
||||
|
||||
GGUF dims below are **ne order** (fastest first). The numpy / `ref/load.py` shape is the reverse, `(out, in[, experts])`.
|
||||
"llama.cpp reads it" cites the pinned submodule (`third_party/llama.cpp`, commit 3cf0325).
|
||||
|
||||
## Metadata
|
||||
|
||||
| key | value | llama.cpp reads it |
|
||||
| --- | --- | --- |
|
||||
| `general.architecture` | `qwen35moe` | `llama-arch.cpp:42` |
|
||||
| `qwen35moe.block_count` | 40 (MTP file: 41) | `llama-model.cpp:1259`; trunk layers = block_count - nextn |
|
||||
| `qwen35moe.nextn_predict_layers` | **absent** in the plain file; 1 in the MTP file | `llama-model.cpp:1261`, optional, default 0 |
|
||||
| `qwen35moe.context_length` | 262144 | `llama-model.cpp:1254` |
|
||||
| `qwen35moe.embedding_length` | 2048 | `:1255` |
|
||||
| `qwen35moe.attention.head_count` / `head_count_kv` | 16 / 2 | `:1328`, `:1336` |
|
||||
| `qwen35moe.attention.key_length` / `value_length` | 256 / 256 | `:1372`, `:1375` |
|
||||
| `qwen35moe.attention.layer_norm_rms_epsilon` | 1e-6 (stored as f32 9.99999997e-07) | `qwen35moe.cpp:7`, required |
|
||||
| `qwen35moe.rope.dimension_count` | 64 (= 0.25 * 256) | `:1380` |
|
||||
| `qwen35moe.rope.dimension_sections` | `[11, 11, 10, 0]` (sum 32 = 64 / 2) | `qwen35moe.cpp:9`, required, 4 entries |
|
||||
| `qwen35moe.rope.freq_base` | 1e7 | `:1347` |
|
||||
| `qwen35moe.expert_count` / `expert_used_count` | 256 / 8 | `:1263`, `:1265` |
|
||||
| `qwen35moe.expert_feed_forward_length` | 512 | `qwen35moe.cpp:5` |
|
||||
| `qwen35moe.expert_shared_feed_forward_length` | 512 | `qwen35moe.cpp:6` |
|
||||
| `qwen35moe.ssm.conv_kernel` | 4 | `qwen35moe.cpp:12` |
|
||||
| `qwen35moe.ssm.state_size` | 128 (head dim of k and v) | `:14` |
|
||||
| `qwen35moe.ssm.group_count` | 16 (k heads) | `:16` |
|
||||
| `qwen35moe.ssm.time_step_rank` | 32 (v heads) | `:15` |
|
||||
| `qwen35moe.ssm.inner_size` | 4096 (= 32 * 128, the value dim) | `:13` |
|
||||
| `qwen35moe.full_attention_interval` | 4 | `:22`; layer `il` is recurrent when `(il+1) % 4 != 0` |
|
||||
| `tokenizer.ggml.model` / `pre` | `gpt2` / `qwen35` | vocab, 248320 tokens, 247587 merges |
|
||||
| `tokenizer.ggml.{bos,eos,padding}_token_id` | 248044 / 248046 / 248055 | `add_bos_token` false |
|
||||
| `tokenizer.chat_template` | 8424 characters | frontend, not llama.cpp's graph |
|
||||
| `general.*`, `quantize.imatrix.*` | name, license, Unsloth provenance, imatrix file | not used by the graph |
|
||||
|
||||
Keys that are **not** in the file and **not** read by the `qwen35moe` loader: `expert_weights_norm`, `expert_weights_scale`,
|
||||
`attention.recurrent_layers` (read if present, `qwen35moe.cpp:20`), `feed_forward_length`, `expert_group_count`, rope scaling.
|
||||
`HParams` defaults then apply: `expert_weights_scale` stays 0.0 (`llama-hparams.h:124`, the key is never loaded for this architecture),
|
||||
so no scaling; `norm_w` is hard-coded `true` at the call site (`qwen35moe.cpp:506`), so the top-8 weights always renormalize to sum 1.
|
||||
A GGUF cannot change either; a stray `qwen35moe.expert_weights_scale` key is ignored (checked with `--expert-weights-scale` on the fixture).
|
||||
|
||||
## Tensors (plain file, 733)
|
||||
|
||||
| name | ne | dtype in the IQ3_XXS file | count |
|
||||
| --- | --- | --- | --- |
|
||||
| `token_embd.weight` | 2048, 248320 | Q6_K | 1 |
|
||||
| `output.weight` | 2048, 248320 | Q6_K (not tied) | 1 |
|
||||
| `output_norm.weight` | 2048 | F32 | 1 |
|
||||
| `blk.N.attn_norm.weight` | 2048 | F32 | 40 |
|
||||
| `blk.N.post_attention_norm.weight` | 2048 | F32 | 40 |
|
||||
| `blk.N.ffn_gate_inp.weight` (router) | 2048, 256 | F32 | 40 |
|
||||
| `blk.N.ffn_gate_exps.weight` | 2048, 512, 256 | IQ2_S | 40 |
|
||||
| `blk.N.ffn_up_exps.weight` | 2048, 512, 256 | IQ2_S | 40 |
|
||||
| `blk.N.ffn_down_exps.weight` | 512, 2048, 256 | IQ3_XXS (37), IQ4_XS (3: layers 34, 38, 39) | 40 |
|
||||
| `blk.N.ffn_gate_inp_shexp.weight` | **2048** (1-D) | F32 | 40 |
|
||||
| `blk.N.ffn_{gate,up}_shexp.weight` | 2048, 512 | Q6_K | 80 |
|
||||
| `blk.N.ffn_down_shexp.weight` | 512, 2048 | Q6_K | 40 |
|
||||
| GDN layers (30: 0-2, 4-6, ..., 36-38): | | | |
|
||||
| `blk.N.attn_qkv.weight` | 2048, 8192 (= 2*2048 + 4096) | Q6_K | 30 |
|
||||
| `blk.N.attn_gate.weight` (z) | 2048, 4096 | Q6_K | 30 |
|
||||
| `blk.N.ssm_conv1d.weight` | 4, 8192 | F32 | 30 |
|
||||
| `blk.N.ssm_alpha.weight`, `ssm_beta.weight` | 2048, 32 | F32 | 60 |
|
||||
| `blk.N.ssm_a` (no `.weight` suffix) | 32 | F32 | 30 |
|
||||
| `blk.N.ssm_dt.bias` | 32 | F32 | 30 |
|
||||
| `blk.N.ssm_norm.weight` | 128 | F32 | 30 |
|
||||
| `blk.N.ssm_out.weight` | 4096, 2048 | Q6_K | 30 |
|
||||
| Attention layers (10: 3, 7, ..., 39): | | | |
|
||||
| `blk.N.attn_q.weight` (query and gate, interleaved per head) | 2048, 8192 (= 16 * 2 * 256) | Q6_K | 10 |
|
||||
| `blk.N.attn_k.weight`, `attn_v.weight` | 2048, 512 (= 2 * 256) | Q6_K | 20 |
|
||||
| `blk.N.attn_output.weight` | 4096, 2048 | Q6_K | 10 |
|
||||
| `blk.N.attn_q_norm.weight`, `attn_k_norm.weight` | 256 | F32 | 20 |
|
||||
|
||||
Values worth knowing (layer 0 and 3): `ssm_a` is **negative**, -72.3 to -0.019 (it is `-exp(A_log)`, so `gate = softplus(alpha + dt_bias) * ssm_a` is already a log decay);
|
||||
`ssm_dt.bias` -5.3 to 15.6; every RMS-norm weight is stored multiplicatively (`attn_norm` mean 1.03, `output_norm` mean 2.63), so no "+1" is applied anywhere;
|
||||
`ssm_conv1d` is within +-0.41; `ffn_gate_inp_shexp` is a 2048-vector with mean 0.
|
||||
|
||||
## The nextn block (MTP file only)
|
||||
|
||||
`blk.40` is the draft block, 20 tensors: the same ones an attention layer plus MoE carries (`attn_norm`, `post_attention_norm`, `attn_q/k/v/output`,
|
||||
`attn_q_norm/k_norm`, `ffn_gate_inp`, `ffn_{gate,up,down}_exps`, `ffn_gate_inp_shexp`, `ffn_{gate,up,down}_shexp`) plus
|
||||
`nextn.eh_proj.weight` (4096, 2048: one projection over `[enorm(token embedding), hnorm(hidden)]` concatenated, embedding first),
|
||||
`nextn.enorm.weight`, `nextn.hnorm.weight`, `nextn.shared_head_norm.weight` (each 2048, F32).
|
||||
There is **no** `nextn.embed_tokens` and **no** `nextn.shared_head_head`: the block embeds with `token_embd.weight` and the draft head is the main `output.weight`
|
||||
(`qwen35moe.cpp:583`, `:733`); the head norm is `shared_head_norm` when present, else `output_norm`.
|
||||
In that file the nextn router `blk.40.ffn_gate_inp.weight` and `ffn_gate_inp_shexp.weight` are **BF16** while the trunk's are F32; the
|
||||
experts are Q3_K gate/up and Q4_K down (trunk: IQ3_S / IQ4_XS).
|
||||
|
||||
## What was unexpected
|
||||
|
||||
- **The plain GGUF has no nextn block at all.** `nextn_predict_layers` is absent and `block_count` is 40. The MTP head exists only in the separate `-MTP.gguf` builds, which carry 41 blocks.
|
||||
- **Gate and up are not fused** (`ffn_gate_exps` + `ffn_up_exps`), and attention layers are **not** fused (`attn_q`, `attn_k`, `attn_v`). `attn_qkv` exists, but only in the 30 GDN layers where it feeds the conv, next to a separate `attn_gate` (z). llama.cpp accepts the fused forms (`llama-model.cpp:3253-3300`, `ffn_gate_up_exps` with gate rows first, `attn_qkv` with Q|K|V rows), and the fixture and oracle support both, but no shipped file uses them.
|
||||
- **`expert_weights_norm` and `expert_weights_scale` are not in the file and cannot matter**: the architecture hard-codes renormalization and never loads a scale (see above).
|
||||
- **The router and the GDN `ssm_alpha` / `ssm_beta` are F32**, not BF16. `ref/load.py`'s `FORM` table in `iq_pack.py` must not assume the Flash-Next BF16 forms for them.
|
||||
- **`attn_q` is 2x wide**: per head 256 query values then 256 gate values, interleaved, which is how `attn_output_gate` is stored. There is no separate gate tensor.
|
||||
- **`ssm_a` carries no `.weight` suffix** and `ssm_dt` is named `ssm_dt.bias`.
|
||||
- **`ffn_gate_inp_shexp` is 1-D** (a vector, producing one scalar per token), not a 2048x1 matrix.
|
||||
- **Per-layer quantization is mixed** (down experts: IQ3_XXS in 37 layers and IQ4_XS in 3; the MTP block uses a different family altogether), so any pack format must carry a type per layer and per role, as `native_experts.txt` already does.
|
||||
- `ref/load.py` did not know IQ2_S, IQ3_XXS, IQ3_S (gate/up/down of this file); it is extended in the same commit that adds the oracle.
|
||||
@@ -1,313 +0,0 @@
|
||||
# Qwen3.6 oracle cross-check against the pinned llama.cpp graph
|
||||
|
||||
Run 2026-10-11 on this branch (`qwen36-oracle`), CPU only, F32 synthetic fixtures, against `third_party/llama.cpp` at 3cf0325.
|
||||
`ref/qwen36.py` (the numpy oracle) and the submodule's own graph agree on **every named tensor of every case**: 2,155 comparisons over 116 seam
|
||||
families, worst absolute error **1.1e-4** (on a tensor whose values reach 3.8), the router's integer outputs identical. The printed stats of
|
||||
`llama-eval-callback` agree on all 209 named nodes it prints. A reading that is wrong in any of the 8 places a port could plausibly get wrong
|
||||
fails the comparison at the layer that makes it. Dequantization of the real file's types is bit-identical to ggml's (below).
|
||||
|
||||
## Reproduce
|
||||
|
||||
One command builds the submodule's `libllama` and `llama-eval-callback` (CPU, outside the repo), builds the dumper, writes the fixtures, runs
|
||||
every case and exits 1 on any failed seam. About 4 seconds once built; the first build takes a few minutes.
|
||||
|
||||
```
|
||||
export STRATA_GGUF_PY=$PWD/third_party/llama.cpp/gguf-py # optional: tools/_paths.py finds it there anyway
|
||||
tools/qwen36_crosscheck.sh /path/to/scratch [REAL-MTP.gguf] # 2nd argument: a real qwen35moe file, for the --like-real case
|
||||
python3 -I tools/test_qwen36_oracle.py # 21 invariant tests, no llama.cpp build needed
|
||||
```
|
||||
|
||||
The same steps by hand, for one case (`$B` is the build directory, `$W` a scratch directory):
|
||||
|
||||
```
|
||||
cmake -S third_party/llama.cpp -B $B -DCMAKE_BUILD_TYPE=Release -DGGML_METAL=OFF -DGGML_BLAS=OFF \
|
||||
-DLLAMA_CURL=OFF -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_SERVER=OFF
|
||||
cmake --build $B --target llama-eval-callback -j8
|
||||
c++ -std=c++17 -O1 tools/qwen36_dump_llama.cpp -o $B/qwen36-dump -Ithird_party/llama.cpp/include \
|
||||
-Ithird_party/llama.cpp/ggml/include -L$B/bin -lllama -lggml -lggml-base -Wl,-rpath,$B/bin
|
||||
|
||||
python3 tools/qwen36_synth_gguf.py $W/base.gguf # add --like-real REAL.gguf / --fused-gate-up / --fused-qkv / --no-nextn
|
||||
T=104,101,108,108,111,32,119,111,114,108,100 # "hello world": the fixture's vocabulary is the 128 ASCII bytes
|
||||
python3 ref/qwen36.py $W/base.gguf --tokens $T --dump $W/o --mtp # oracle dumps (+ $W/o_mtp)
|
||||
$B/qwen36-dump $W/base.gguf $W/d $T 0 mtp # llama.cpp's graph, every named tensor in full (+ $W/d_mtp)
|
||||
python3 tools/qwen36_compare_dumps.py $W/o $W/d # per-seam max |difference|; exit 1 on a failure
|
||||
|
||||
$B/bin/llama-eval-callback -m $W/base.gguf -p "hello world" -ctk f32 -ctv f32 -fa off -c 64 -t 1 -ngl 0 > $W/eval.txt 2>&1
|
||||
python3 tools/qwen36_check_eval_callback.py $W/o $W/eval.txt --require-tail
|
||||
```
|
||||
|
||||
`-ctk f32 -ctv f32 -fa off` matter: the default F16 KV cache would put half-precision rounding into attention, and `qwen36-dump` sets the same.
|
||||
Both tools use one thread, so the only differences left are float32 summation order.
|
||||
|
||||
## Cases (all in `tools/qwen36_crosscheck.sh`)
|
||||
|
||||
| case | fixture | tokens | what it adds |
|
||||
| --- | --- | --- | --- |
|
||||
| `base_11` | default, seed 0 | 11 ("hello world") | the baseline; also the nextn block |
|
||||
| `base_40` | default | 40 | longer GDN history, attention over 40 keys |
|
||||
| `base_ar` | default | 40, one token per decode call | llama.cpp's autoregressive GDN path: state and KV carried through 40 calls; only the last call is dumped |
|
||||
| `base_c7` | default | 40, chunks of 7 | state carried across 5 calls of 7, then 5 |
|
||||
| `seed7` | seed 7 | 11 | different weights, so a coincidence in seed 0 cannot hide a bug; nextn |
|
||||
| `fused_gu` | `--fused-gate-up --seed 3` | 11 | `ffn_gate_up_exps` (gate rows then up rows) for trunk and nextn; nextn |
|
||||
| `fused_qkv` | `--fused-qkv --no-nextn --seed 4` | 11 | `attn_qkv` in the attention layer (Q, K, V rows in that order) |
|
||||
| `gqa4_2` | `--heads 4,2 --seed 11` | 40 | **non-degenerate GQA**: 4 query heads over 2 KV heads, so `kv = h // (n_head/n_head_kv)` is tested (every other fixture has one KV head, where any mapping passes); nextn |
|
||||
| `stray_scl` | `--expert-weights-scale 2.5 --seed 5` | 11 | the key is in the file; llama.cpp ignores it, so must the oracle; nextn |
|
||||
| `like_real` | `--like-real <MTP build>` | 40 | rope base 1e7, real eps, interval, head ratios, and the exact tensor-name set of the real file (32 of 32 patterns); nextn |
|
||||
|
||||
Geometry of the default fixture: hidden 64; layers 0-2 Gated DeltaNet, layer 3 full attention; GDN 4 k-heads / 8 v-heads of 16; conv kernel 4;
|
||||
attention 2 heads / 1 KV head of 32 with 8 rotated dims (25 %) and IMRoPE sections [2,1,1,0]; 8 experts, top 2, ff 32, shared ff 32; vocabulary 128;
|
||||
one nextn block at index 4.
|
||||
|
||||
## Results
|
||||
|
||||
All 10 trunk cases: `0 failed` of 211 seams (215 with fused gate/up, 212 with fused qkv). The 6 nextn cases: `0 failed` of 50 (51 fused). Per seam family
|
||||
(max over all layers and the first nine cases, 2,155 comparisons; the `gqa4_2` case adds 261 more, all within tolerance; "max abs value" is the largest magnitude of the llama.cpp tensor):
|
||||
|
||||
#### Trunk (`qwen35moe` graph, 9 cases)
|
||||
|
||||
| seam (all layers) | comparisons | max abs error | max abs value |
|
||||
| --- | --- | --- | --- |
|
||||
| `model.input_embed` | 9 | 0.0e+00 | 3.763 |
|
||||
| `norm` | 126 | 1.1e-04 | 3.937 |
|
||||
| `attn_norm` | 36 | 1.7e-05 | 5.397 |
|
||||
| `conv_states` | 27 | 8.6e-06 | 3.773 |
|
||||
| `conv_states_reshaped` | 27 | 8.6e-06 | 3.773 |
|
||||
| `linear_attn_qkv_mixed` | 27 | 8.5e-06 | 4.543 |
|
||||
| `qkv_mixed_transposed` | 27 | 8.5e-06 | 4.543 |
|
||||
| `z` | 27 | 7.6e-06 | 4.58 |
|
||||
| `beta` | 27 | 5.9e-06 | 6.075 |
|
||||
| `beta_sigmoid` | 27 | 1.5e-06 | 0.9977 |
|
||||
| `alpha` | 27 | 9.2e-06 | 3.173 |
|
||||
| `a_softplus` | 27 | 2.4e-06 | 3.359 |
|
||||
| `gate` | 27 | 8.5e-06 | 38.85 |
|
||||
| `conv_input` | 27 | 8.6e-06 | 4.543 |
|
||||
| `conv_state_last` | 27 | 4.8e-06 | 3.944 |
|
||||
| `conv_output_raw` | 27 | 1.0e-05 | 9.484 |
|
||||
| `conv_output_silu` | 27 | 1.1e-05 | 9.483 |
|
||||
| `q_conv` | 27 | 1.1e-05 | 9.483 |
|
||||
| `k_conv` | 27 | 9.4e-06 | 7.217 |
|
||||
| `q_conv_predelta` | 27 | 2.3e-06 | 0.9935 |
|
||||
| `k_conv_predelta` | 27 | 2.9e-06 | 0.9874 |
|
||||
| `v_conv_predelta` | 27 | 1.1e-05 | 6.957 |
|
||||
| `state_predelta` | 27 | 4.6e-06 | 2.4 |
|
||||
| `new_state` | 27 | 3.9e-06 | 3.382 |
|
||||
| `attn_output` | 36 | 4.1e-06 | 1.878 |
|
||||
| `final_output` | 27 | 5.3e-05 | 8.531 |
|
||||
| `linear_attn_out` | 27 | 1.8e-05 | 3.891 |
|
||||
| `attn_residual` | 36 | 2.0e-05 | 9.001 |
|
||||
| `attn_post_norm` | 36 | 1.5e-05 | 5.079 |
|
||||
| `ffn_moe_logits` | 36 | 2.3e-05 | 12.4 |
|
||||
| `ffn_moe_probs` | 36 | 6.8e-06 | 0.9995 |
|
||||
| `ffn_moe_argsort` | 36 | identical | 0 |
|
||||
| `ffn_moe_topk` | 36 | identical | 0 |
|
||||
| `ffn_moe_weights` | 36 | 6.8e-06 | 0.9995 |
|
||||
| `ffn_moe_weights_sum` | 36 | 2.3e-06 | 0.9999 |
|
||||
| `ffn_moe_weights_sum_clamped` | 36 | 2.3e-06 | 0.9999 |
|
||||
| `ffn_moe_weights_norm` | 36 | 8.3e-06 | 0.9997 |
|
||||
| `ffn_moe_gate` | 36 | 1.4e-05 | 4.662 |
|
||||
| `ffn_moe_up` | 36 | 1.2e-05 | 4.383 |
|
||||
| `ffn_moe_swiglu` | 36 | 2.4e-05 | 10.1 |
|
||||
| `ffn_moe_down` | 36 | 1.3e-05 | 5.36 |
|
||||
| `ffn_moe_weighted` | 36 | 1.2e-05 | 3.552 |
|
||||
| `ffn_moe_out` | 36 | 1.4e-05 | 3.635 |
|
||||
| `ffn_up` | 36 | 1.5e-05 | 4.215 |
|
||||
| `ffn_gate` | 36 | 1.1e-05 | 4.541 |
|
||||
| `ffn_swiglu` | 36 | 2.9e-05 | 5.875 |
|
||||
| `ffn_shexp` | 36 | 1.6e-05 | 3.419 |
|
||||
| `shared_expert_gate` | 36 | 9.8e-06 | 5.545 |
|
||||
| `shared_expert_gate_sigmoid` | 36 | 2.2e-06 | 0.9961 |
|
||||
| `ffn_shexp_gated` | 36 | 6.8e-06 | 3.12 |
|
||||
| `ffn_out` | 36 | 1.2e-05 | 4.451 |
|
||||
| `l_out` | 36 | 2.3e-05 | 8.791 |
|
||||
| `Qcur_full` | 9 | 1.4e-05 | 4.189 |
|
||||
| `Kcur` | 18 | 1.1e-05 | 3.824 |
|
||||
| `Vcur` | 18 | 1.4e-05 | 4.189 |
|
||||
| `Qcur_reshaped` | 9 | 1.2e-05 | 3.753 |
|
||||
| `Qcur_normed` | 9 | 2.2e-05 | 5.186 |
|
||||
| `Kcur_normed` | 9 | 8.7e-06 | 3.824 |
|
||||
| `Qcur` | 9 | 2.2e-05 | 5.186 |
|
||||
| `kq` | 9 | 8.8e-05 | 22.06 |
|
||||
| `kq_soft_max` | 9 | 3.0e-06 | 1 |
|
||||
| `kqv` | 9 | 1.1e-05 | 3.075 |
|
||||
| `attn_pregate` | 9 | 1.1e-05 | 3.075 |
|
||||
| `gate_reshaped` | 9 | 1.4e-05 | 4.189 |
|
||||
| `gate_sigmoid` | 9 | 3.3e-06 | 0.9768 |
|
||||
| `attn_gated` | 9 | 8.2e-06 | 2.669 |
|
||||
| `h_nextn` | 9 | 1.7e-05 | 3.835 |
|
||||
| `result_norm` | 9 | 3.6e-06 | 3.259 |
|
||||
| `result_output` | 9 | 7.3e-06 | 7.799 |
|
||||
| `ffn_moe_gate_up` | 4 | 6.3e-06 | 3.595 |
|
||||
| `wqkv` | 1 | 6.7e-06 | 3.492 |
|
||||
|
||||
#### Nextn block (`graph_mtp`, 5 cases that carry a nextn block)
|
||||
|
||||
| seam (all layers) | comparisons | max abs error | max abs value |
|
||||
| --- | --- | --- | --- |
|
||||
| `mtp_tok_embd` | 5 | 0.0e+00 | 3.372 |
|
||||
| `norm` | 35 | 1.7e-05 | 3.956 |
|
||||
| `mtp_enorm` | 5 | 4.8e-07 | 3.57 |
|
||||
| `mtp_hnorm` | 5 | 1.5e-05 | 4.633 |
|
||||
| `mtp_concat` | 5 | 1.5e-05 | 4.633 |
|
||||
| `mtp_eh_proj` | 5 | 8.2e-06 | 3.742 |
|
||||
| `mtp_attn_norm` | 5 | 8.7e-06 | 4.298 |
|
||||
| `mtp_Qcur_full` | 5 | 8.8e-06 | 4.519 |
|
||||
| `mtp_Qcur_normed` | 5 | 1.1e-05 | 4.886 |
|
||||
| `mtp_gate` | 5 | 7.5e-06 | 4.387 |
|
||||
| `mtp_Kcur_normed` | 5 | 6.6e-06 | 3.528 |
|
||||
| `mtp_Vcur` | 5 | 8.6e-06 | 4 |
|
||||
| `kq` | 5 | 6.1e-05 | 23.47 |
|
||||
| `kq_soft_max` | 5 | 2.1e-06 | 1 |
|
||||
| `kqv` | 5 | 4.2e-06 | 3.701 |
|
||||
| `mtp_attn_pregate` | 5 | 4.2e-06 | 3.701 |
|
||||
| `mtp_attn_out` | 5 | 3.8e-06 | 1.818 |
|
||||
| `mtp_attn_residual` | 5 | 9.3e-06 | 4.383 |
|
||||
| `mtp_attn_post_norm` | 5 | 7.5e-06 | 4.184 |
|
||||
| `ffn_moe_logits` | 5 | 1.6e-05 | 11.01 |
|
||||
| `ffn_moe_probs` | 5 | 2.7e-06 | 0.9975 |
|
||||
| `ffn_moe_argsort` | 5 | identical | 0 |
|
||||
| `ffn_moe_topk` | 5 | identical | 0 |
|
||||
| `ffn_moe_weights` | 5 | 2.7e-06 | 0.9975 |
|
||||
| `ffn_moe_weights_sum` | 5 | 1.5e-06 | 0.9993 |
|
||||
| `ffn_moe_weights_sum_clamped` | 5 | 1.5e-06 | 0.9993 |
|
||||
| `ffn_moe_weights_norm` | 5 | 2.8e-06 | 0.9982 |
|
||||
| `ffn_moe_gate` | 5 | 7.7e-06 | 4.102 |
|
||||
| `ffn_moe_up` | 5 | 7.6e-06 | 3.967 |
|
||||
| `ffn_moe_swiglu` | 5 | 1.3e-05 | 6.547 |
|
||||
| `ffn_moe_down` | 5 | 1.2e-05 | 4.218 |
|
||||
| `ffn_moe_weighted` | 5 | 5.1e-06 | 2.526 |
|
||||
| `mtp_ffn_moe_out` | 5 | 5.9e-06 | 2.647 |
|
||||
| `ffn_up` | 5 | 8.7e-06 | 3.683 |
|
||||
| `ffn_gate` | 5 | 7.2e-06 | 4.162 |
|
||||
| `ffn_swiglu` | 5 | 1.5e-05 | 5.923 |
|
||||
| `mtp_ffn_shexp` | 5 | 8.3e-06 | 2.811 |
|
||||
| `mtp_shared_expert_gate_sigmoid` | 5 | 2.1e-06 | 0.9887 |
|
||||
| `mtp_ffn_shexp_gated` | 5 | 4.7e-06 | 2.501 |
|
||||
| `mtp_ffn_out` | 5 | 6.8e-06 | 3.119 |
|
||||
| `mtp_post_ffn` | 5 | 1.6e-05 | 4.947 |
|
||||
| `h_nextn` | 5 | 1.4e-05 | 3.562 |
|
||||
| `mtp_shared_head_norm` | 5 | 1.4e-05 | 3.562 |
|
||||
| `result_output` | 5 | 2.1e-05 | 7.916 |
|
||||
| `ffn_moe_gate_up` | 1 | 3.7e-06 | 3.81 |
|
||||
|
||||
The largest absolute error is 1.1e-4 on `norm-2#2`, the RMS norm of a GDN layer's recurrence output. Those values are small, so the norm amplifies the
|
||||
float32 summation-order difference of the recurrence by about 1 / rms; relative to the tensor's largest value it is 2.8e-5. The router's
|
||||
`ffn_moe_argsort` and `ffn_moe_topk` are bit-identical in every case.
|
||||
|
||||
### `llama-eval-callback` printed stats
|
||||
|
||||
`tools/qwen36_check_eval_callback.py` reconstructs which indices the tool prints (first and last 3 of every dimension, `%12.4f`) and its float32 `sum`:
|
||||
209 named nodes through `result_output`, 0 failed; worst printed value 6.2e-5 apart (that is the 4-decimal rounding, not a difference), worst `sum`
|
||||
3.9e-7 of the tensor's L1 mass. `kq` and `kq_soft_max` are skipped there because llama.cpp pads their KV axis to its cache size (256); the full-tensor
|
||||
comparison crops the padding and requires it to be exactly zero for `kq_soft_max`.
|
||||
|
||||
### Negative controls: the comparison fails when the oracle reads the graph wrongly
|
||||
|
||||
Each row runs the oracle with one `Model.opts` entry flipped to its rival (`ref/qwen36.py --opt KEY=VALUE`) against the same llama.cpp dump of `base_11`.
|
||||
All 8 fail, at the layer and seam that makes the mistake; `tools/test_qwen36_oracle.py` requires every one to move its seam by more than 5 % relative L1.
|
||||
|
||||
| rival reading | first failing seam | seams failing / 211 | change at that seam (relative L1) | change in logits |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| GDN output gate `sigmoid(z)` (the Flash-Next engine) instead of `SiLU(z)` | `final_output-0` | 179 | 1.07 | 0.92 |
|
||||
| v-head h paired with k-head `h // 2` instead of `h % 4` | `new_state-0` | 182 | 1.03 | 0.84 |
|
||||
| decay applied after the rank-1 update instead of before | `new_state-0` | 182 | 0.16 | 0.30 |
|
||||
| conv window applied in the opposite direction | `conv_output_raw-0` | 189 | 1.23 | 1.05 |
|
||||
| attention output gate skipped | `attn_gated-3` | 32 | 1.03 | 0.12 |
|
||||
| top-k weights not renormalized | `ffn_moe_weighted-0` | 152 | 0.14 | 0.12 |
|
||||
| query head h reads KV head `h % n_kv` instead of `h // (n_head/n_kv)` (on `gqa4_2`; invisible with one KV head) | `kq-3` | 36 | 0.74 (at `kqv-3`) | 0.13 |
|
||||
| RoPE on adjacent pairs (2p, 2p+1) instead of (p, p + n_rot/2) | `Qcur-3` | 37 | 0.20 (at `kqv-3`) | 0.04 |
|
||||
|
||||
## Formulas pinned (file:line in `third_party/llama.cpp`)
|
||||
|
||||
**Gated DeltaNet** (`qwen35moe.cpp:359-492`; `qwen35moe.cpp:20-26` decides which layers are recurrent). CPU always takes the fused op
|
||||
(`llama-context.cpp:232-233`), whose scalar loop is the reference; the chunked and autoregressive graphs in `delta-net-base.cpp:16-371` compute the same thing.
|
||||
|
||||
| step | formula | source |
|
||||
| --- | --- | --- |
|
||||
| beta | `sigmoid(ssm_beta x)` | `qwen35moe.cpp:382-387` |
|
||||
| log decay | `g = softplus(ssm_alpha x + ssm_dt.bias) * ssm_a`, `ssm_a < 0` in the file; softplus is `x > 20 ? x : log1p(exp(x))` | `qwen35moe.cpp:389-398`, `ggml-cpu/unary-ops.cpp:80-82` |
|
||||
| conv | per channel, `y[t] = sum_i w[c][i] * in[c][t+i]` over `[state (K-1) \| qkv]`, then `silu`; new state = last K-1 inputs | `qwen35moe.cpp:402-421`, `delta-net-base.cpp:449-525`, `ggml-cpu/ops.cpp:9703-9754` |
|
||||
| split | channels `[0,2048)` q, `[2048,4096)` k (16 heads of 128), `[4096,8192)` v (32 heads of 128); head h is a contiguous 128-run | `qwen35moe.cpp:424-444` |
|
||||
| q, k norm | `x / sqrt(sum(x^2) + eps)`, eps 1e-6, per head: `rms_norm(x, eps/n) * 1/sqrt(n)` | `models.h:14-18`, `qwen35moe.cpp:451-454` |
|
||||
| head pairing | v-head h uses k-head `h % 16` (tiling, not blocks) | `qwen35moe.cpp:462-466`, `ggml-cpu/ops.cpp:10971-10972` |
|
||||
| state | `S[j][i]`, j = v index, i = k index, per v-head, `ne [S_k, S_v, H_v]`, zero at sequence start | `ggml-cpu/ops.cpp:10999`, `qwen35moe.cpp:411-413` |
|
||||
| step | `S *= exp(g)`; `d = (v - S k) * beta`; `S += d (x) k`; `o = (S q) / sqrt(S_v)` | `ggml-cpu/ops.cpp:11012, 11016-11020, 11023-11025, 11028-11032` |
|
||||
| output | `rms_norm(o) * ssm_norm * SiLU(z)`, per head; then `ssm_out` | `qwen35moe.cpp:267-276, 475-486` |
|
||||
|
||||
**Full attention** (`qwen35moe.cpp:278-357`): `attn_q` is `[n_head, 2, head_dim]` per token, so query is the first `head_dim` of each head's `2*head_dim` slice and the gate the second
|
||||
(`:299-317`); RMS norm on q and k per head (`:305-311`); IMRoPE on the first 64 of 256 dims, pairs `(p, p+32)` (`ggml-cpu/ops.cpp:6205-6213`), theta per sector
|
||||
from `t,h,w,e` positions = `pos,pos,pos,0` for text (`llama-graph.cpp:131-141`, `ops.cpp:6026-6036`); scale `1/sqrt(256)` (`:340`); causal softmax; GQA groups are
|
||||
contiguous (`kv head = h / (n_head / n_head_kv)`); output `* sigmoid(gate)` then `attn_output` (`:347-354`).
|
||||
|
||||
**Router and experts** (`qwen35moe.cpp:494-548`, `llama-graph.cpp:1993-2355`): logits `ffn_gate_inp x`; `softmax` over all 256 (`:2043`); `argsort_top_k` of the probabilities, descending (`:2109`);
|
||||
weights are the unbiased probabilities of the chosen experts (`:2123`); **renormalized to sum 1** with the sum clamped at 6.1035e-5 (`:2134-2148`), because `qwen35moe.cpp:506`
|
||||
passes `norm_w = true`; `expert_weights_scale` is `0.0` (`llama-hparams.h:124`, never loaded for this architecture), so no scale (`:2149`). Experts: `silu(gate x) * (up x)` (`:2246`),
|
||||
`down`, times weight, summed in top-k order (`:2339-2345`). Shared expert: same SwiGLU with `ffn_{gate,up,down}_shexp`, times `sigmoid(ffn_gate_inp_shexp . x)` (a scalar per token), added to the routed sum
|
||||
(`qwen35moe.cpp:516-545`).
|
||||
|
||||
**Nextn / MTP** (`qwen35moe.cpp:550-741`, a real graph in this commit, run by llama.cpp's `LLAMA_CONTEXT_TYPE_MTP` context): `concat(rms_norm(embed(token)) * enorm, rms_norm(h) * hnorm)` (embedding first),
|
||||
`eh_proj`, then an attention block (`attn_norm`, joint q+gate, q/k norm, IMRoPE, causal over the MTP block's own KV, sigmoid gate, `attn_output`, residual), `post_attention_norm`, the same MoE
|
||||
plus gated shared expert, residual, `shared_head_norm` (else `output_norm`), and the main `output.weight` (there is no `nextn.shared_head_head` in shipped files). The pairing the speculative code builds
|
||||
(`common/speculative.cpp`, "shift the tgt embeddings to the right by one position"): token k with the trunk hidden state of position k-1, at position k; the cross-check does the same (`tokens[1:]`, `h[:-1]`, positions 1..).
|
||||
The trunk's `h_nextn` is the output-normed hidden state of every input token (`qwen35moe.cpp:230-233`).
|
||||
|
||||
## Quirks of the comparison that a later reader will trip over
|
||||
|
||||
- **Repeated names.** `cb()` renames the tensor, so `Kcur-3` and `Vcur-3` each exist twice (projection, then the reshaped or rope'd tensor), and every `build_norm` sets `norm-<layer>` on its unweighted result,
|
||||
so a layer has up to four. The dumps number repeats `#2`, `#3` in **execution order**, which is the graph's dependency order, not build order: in the nextn block `ggml_concat(e_norm, h_norm)` pulls
|
||||
`e_norm` first, so `norm-4` is the embedding norm. The oracle emits in that order. A later `cb` on the same tensor overwrites an earlier name (`v_conv` is only ever visible as `v_conv_predelta`, `post_moe` as `l_out`).
|
||||
- **Views read before their copy.** `conv_state_update-N` is a view of the cache that llama.cpp evaluates before the copy that writes it; it shows the old state. The new state is `conv_state_last-N`; the comparison ignores the former.
|
||||
- **`kq` is padded** to the KV cache size (256 here); `result_norm` and `result_output` hold the last token only because `llama_batch_get_one` requests logits for the last position; `h_nextn` holds all tokens.
|
||||
- **`llama-eval-callback` loses the end of its own output.** Its asynchronous logger drops its queue at exit, so the tail (sometimes through `result_output`) is cut off in a fraction of runs. The checker discards an unterminated block and
|
||||
`--require-tail` fails unless the printout reaches `result_output`; `qwen36_crosscheck.sh` retries up to 8 times. `tools/qwen36_dump_llama.cpp` writes files and is not affected.
|
||||
- **Tokenizer.** The fixture's vocabulary is the 128 ASCII byte tokens (GPT-2 byte-level BPE with a single dead merge), so `-p "text"` yields token id = ASCII code and `llama-eval-callback` can be driven by text.
|
||||
- **Stray metadata.** A `qwen35moe.expert_weights_scale` key changes nothing (case `stray_scl`); `expert_weights_norm` is not read either. `llama.cpp` warns about "unused tensor blk.4.*" when the nextn block is present and `--mtp` is not requested; harmless.
|
||||
|
||||
## ref/load.py dequantization against ggml (real file)
|
||||
|
||||
`tools/qwen36_check_dequant.py MODEL.gguf $B/qwen36-dequant` (the helper, `tools/qwen36_dequant_ggml.cpp`, calls ggml's own `to_float` on the raw bytes) on
|
||||
`Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf`: **max |difference| 0.0 (bit-identical)** for `token_embd.weight` rows (Q6_K), `output.weight` and a dense Q6_K block, whole experts of
|
||||
`blk.0.ffn_gate_exps` (IQ2_S), `blk.0.ffn_down_exps` (IQ3_XXS) and `blk.34.ffn_down_exps` (IQ4_XS), two experts each. Independently, `model.input_embed` from the real llama.cpp graph
|
||||
(a `get_rows` of the Q6_K table, exact dequantization) equals the oracle's rows with max error 0.0 over the 4 smoke-test tokens. So every real-file difference below comes from activation
|
||||
quantization and summation order, not from the weights.
|
||||
|
||||
## Tolerance policy for parity tests on the real file
|
||||
|
||||
The oracle is F32 weights x F32 activations. llama.cpp and the CUDA paths round activations to Q8 (`Q8_K` blocks of 256 for K-quant and IQ weights, `Q8_0` blocks of 32 for Q4_0/Q8_0/IQ4_NL)
|
||||
before each quantized matmul; F32 weights (router, `ssm_alpha`/`ssm_beta`, conv) are not affected. On the real file that moves seams by percents and flips near-tied expert picks
|
||||
(12 tokens: 1,895 of 3,840 top-k slots differ position-wise once errors have compounded). Therefore:
|
||||
|
||||
1. **Teacher-force expert selection** in any real-file parity test: `ref/qwen36.py --force-topk DIR` takes the choices from a dump's `ffn_moe_topk-<layer>.f32`
|
||||
(the CUDA test feeds the oracle's own, or the engine's). Exact top-k agreement is checked only on the F32 fixtures (`tools/qwen36_crosscheck.sh`, where it is bit-identical in every case).
|
||||
2. **Compare per layer, not accumulated**: `--force-inputs DIR` starts every layer from the reference's `l_out-(il-1)`, so each seam's error is that layer's own. Accumulated error over 40
|
||||
layers is 5-30x larger (table below, first block) and is not a usable tolerance.
|
||||
3. **Use these per-seam-class relative tolerances** (`||oracle - reference|| / ||reference||`, 12 tokens, 40 layers, topk and inputs forced). Column "F32 oracle" is the plain oracle; "Q8 oracle" is `--act-quant q8`:
|
||||
|
||||
| seam class | F32 oracle median / max over layers | Q8 oracle median / max |
|
||||
| --- | --- | --- |
|
||||
| `attn_norm` (input is the forced residual) | 5e-8 / 7e-8 | 5e-8 / 7e-8 |
|
||||
| `linear_attn_qkv_mixed` (GDN in-projection) | 1.4e-2 / 1.8e-2 | 6.9e-7 / 7.5e-7 |
|
||||
| `linear_attn_out` (GDN output) | 3.8e-2 / 6.6e-2 | 7.8e-5 / 3.7e-4 |
|
||||
| `attn_output` (full attention, 10 layers) | 4.2e-2 / 6.3e-2 | 1.1e-4 / 6.7e-4 |
|
||||
| `ffn_moe_out` | 2.9e-2 / 5.3e-2 | 2.3e-3 / 5.3e-3 |
|
||||
| `ffn_out` (routed + shared) | 3.0e-2 / 4.7e-2 | 2.1e-3 / 4.5e-3 |
|
||||
| `l_out` (layer output) | 6.9e-3 / 2.7e-2 | 1.8e-4 / 1.4e-3 |
|
||||
| `result_output` (logits, last token) | 1.9e-2 | 4.0e-7 |
|
||||
|
||||
Against an F32-activation engine path, use the F32 column with a 2x margin (for example `qkv_mixed` 4e-2, `gdn_out`/`attn_out` 1.3e-1, `moe_out` 1.1e-1, `l_out` 5e-2, logits 4e-2). Against a path that
|
||||
rounds activations to Q8 the way ggml does, use the Q8 column with a 4x margin.
|
||||
4. **Q8 mode is cheap and closes the gap**: `quantize_act` (about 25 lines) reproduces ggml's `quantize_row_q8_K_ref` / `quantize_row_q8_0_ref` and leaves 1e-6 to 1e-3 instead of 1e-2 to 1e-1; at layer 0
|
||||
the GDN in-projection goes from 7.6e-3 to 6e-7. What remains in `ffn_moe_out` (2e-3) is the IQ2_S / IQ3_XXS integer dot product against float summation. For the last three rows of that
|
||||
table the Q8 oracle is a better reference than the F32 one whenever the engine under test quantizes activations.
|
||||
5. The accumulated spread, for reference (`tools/qwen36_spread.py`, no forcing at all, medians over layers; F32 / Q8): `attn_norm` 1.3e-1 / 1.1e-1, `gdn_out` 1.9e-1 / 1.6e-1, `moe_out` 3.4e-1 / 2.8e-1,
|
||||
`l_out` 5.6e-2 / 4.5e-2, logits 9.8e-2 / 5.9e-2; with only the top-k forced: `l_out` 2.1e-2 / 1.3e-2, logits 3.1e-2 / 3.2e-2. Greedy next-token and the top-5 ids still agree. Q8 mode does not close this one: chaotic
|
||||
amplification through 40 layers, plus the attention layers (layer 3 alone takes `l_out-2` from 7e-3 to `attn_output-3` 2e-2), dominate, which is why the per-layer protocol above is the one to use.
|
||||
|
||||
## Not covered
|
||||
|
||||
- **Quantized numerics.** Everything above is F32 weights. On the real file (below) llama.cpp quantizes activations to Q8 for the matmuls, so seams agree to about 1e-2 relative, and near-tied router scores flip.
|
||||
- Real-file smoke, 4 token ids (`9707,11,1879,0`) through `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf`, oracle against `qwen36-dump` (8 threads): the seams computed from F32 weights
|
||||
(`beta`, `alpha`, `a_softplus`, `gate`) agree to 2e-5 abs and every projection with a quantized weight to about 1e-2 relative (layer 0 `linear_attn_qkv_mixed` 0.20 of 29.8); the last-token logits
|
||||
correlate 0.993, argmax (271) and the top 5 ids are identical, and the router picks different experts in 6 of 32 (token, slot) choices in layer 0, 5 in layer 3 and 12-23 in layers 30-39. That is a plausibility check that the
|
||||
oracle reads the real tensors in the real conventions (dequantization of IQ2_S / IQ3_XXS / IQ4_XS / Q6_K, 1-D `ffn_gate_inp_shexp`, negative `ssm_a`), not a parity claim.
|
||||
- YaRN / rope scaling (the file has none), sliding windows (none), multimodal position ids (text-only: `t = h = w = pos`, `e = 0`), batches of more than one sequence, GPU kernels, F16 KV.
|
||||
- Ties in the router: `argsort` here is stable descending; ggml's tie order is unspecified. Random fixtures have no ties; the engine's router kernel needs its own tie test (see `router_top10_parity.cpp`).
|
||||
@@ -1,198 +0,0 @@
|
||||
# The Pascal (sm_61) build of the engine on the GTX 1080 Ti
|
||||
|
||||
Phase 2 step 2, the one item that needed the GPU (2026-10-11, branch `qwen36-step2`, VM 211: GTX 1080 Ti sm_61,
|
||||
8 vCPU of a Ryzen 7 1700, 12 GiB, CUDA 12.4, Debian's gcc 14.2 as the default compiler and gcc-13 / g++-13 as the
|
||||
host compiler for nvcc). The configure line is the one in `step2-notes.md` section 4.
|
||||
|
||||
## 1. Where the tree uses what Pascal lacks (read before the build)
|
||||
|
||||
Pascal GP102 is compute capability 6.1: `__dp4a` is native; no tensor cores (`mma.sync`, `ldmatrix`, tf32), no
|
||||
`cp.async` (sm_80), no `__nanosleep` (sm_70), no thread-block clusters (sm_90), no `__match_any_sync` (sm_70),
|
||||
no `__reduce_*_sync` (sm_80), fp16 arithmetic at 1/64 rate. The tree was searched for every one of those before
|
||||
the build (`grep -rl` over `src/` and `include/`, `.cu` / `.cuh` / `.hpp` / `.cpp`):
|
||||
|
||||
| Feature | Files | Guard already in the file |
|
||||
| --- | --- | --- |
|
||||
| `mma.sync` f16 (m16n8k16 sm_80, m16n8k8 sm_75), `cp.async` | `src/kernels/cuda/qsa_prompt_attn.cu` | `STRATA_PA_SM80` (`__CUDA_ARCH__ >= 800`); `mma16816` is `__trap()` below sm_75 and `qsa_prompt_attn_batch` refuses `cc < 70` at run time, prefill takes `qsa_decode_attn_batch` instead. The Volta m8n8k4 kernel is under `STRATA_EXPERIMENTAL_SM60 && 700 <= arch < 750`, so it is not compiled for sm_61 |
|
||||
| `mma.sync` tf32, `ldmatrix` | `src/kernels/cuda/native_qsa_score.cu` | `__CUDA_ARCH__ >= 800` around `load_a` / `load_b` / `mma`; `score_kernel` has an FP32-FMA path under `__CUDA_ARCH__ < 800` |
|
||||
| `cvt.rna.tf32`, `mma.sync` tf32, `cp.async` | `src/kernels/cuda/qsa_select.cu` | `STRATA_SEL_SM80`; `qsa_block_scores_tc` refuses the device, the warp kernel runs |
|
||||
| thread-block clusters (`cudaLaunchKernelEx`, cluster barriers) | `src/kernels/cuda/qsa_select.cu`, `src/kernels/cuda/sampler.cu` | `STRATA_SEL_CLUSTER` / `STRATA_AM_CLUSTER` (`__CUDA_ARCH__ >= 900`): a trap that `qsa_block_topk_cluster` / `sample_greedy_cluster` never launch below sm_90 |
|
||||
| `__match_any_sync` | `src/kernels/cuda/qsa_select.cu` | inside the sm_80 region above (checked at the build) |
|
||||
| `cp.async` | `src/kernels/cuda/fused_gr.cu` | `__CUDA_ARCH__ >= 800 && !__HIPCC__` |
|
||||
| `cp.async` in the GDN recurrence | `src/prefill/kernels.cu`, `src/prefill/gdn_rec_parity.cu` | `STRATA_GDN_CP_ASYNC` (`__CUDA_ARCH__ < 800`: plain copies, and `gdn_keyhead_ok` never launches the key-head kernel there) |
|
||||
| `mma.sync` / `ldmatrix` / `cp.async` in the fused prompt MoE | `src/prefill/moe_fused.cu`, `src/prefill/moe_fused_iq.cu` | `__CUDA_ARCH__ >= 800` at the two sites of each; their tests exit 77 below sm_80 |
|
||||
| `__nanosleep` | `include/strata/kernels/dp4a.hpp` (`strata_spin_pause`), `src/prefill/gdn_rec_parity.cu` (`nap`) | `__CUDA_ARCH__ < 700`: the loop spins |
|
||||
| `__dp4a` | `include/strata/kernels/dp4a.hpp` | `STRATA_DP4A`: the byte-loop fallback only below 6.1; sm_61 uses the instruction |
|
||||
| half arithmetic (`__hfma2` and kin) | none found outside `qsa_prompt_attn.cu`'s mma path | conversions only elsewhere (the 1/64-rate risk of the design doc's section 7 item 2 is a throughput item, not a build item) |
|
||||
| bf16 intrinsics (`__nv_bfloat16`, `__float2bfloat16`), fp16 atomics, `__reduce_*_sync` | none | |
|
||||
| `STRATA_EXPERIMENTAL_SM60` itself | `src/core/device.cu` (the cc check), `src/kernels/cuda/qsa_decode_attn.cu` (the sm_60 decode kernel), `src/kernels/cuda/qsa_prompt_attn.cu` (the Volta kernel), `src/prefill/gemm.cu` (the FP32 GEMM default) | the flag the configure line passes |
|
||||
|
||||
So upstream's experimental build already guards every sm_75+ site this tree has; the question the build answers is
|
||||
whether any site was missed for sm_61 specifically (the guards were written for sm_60 and sm_70, and nobody has run
|
||||
the build at 61).
|
||||
|
||||
## 2. The build
|
||||
|
||||
Nothing needed a guard. The tree as it stood at `8b7525e` configured and built for sm_61 unchanged:
|
||||
|
||||
| Phase | Command | Result | Time (8 Zen 1 vCPU) |
|
||||
| --- | --- | --- | --- |
|
||||
| configure | the `cmake -S . -B build ...` line of `step2-notes.md` section 4 | `Strata: CUDA enabled, arch 61`; `NVIDIA 12.4.131 with host compiler GNU 13.3.0` | 4 s |
|
||||
| `unbiased-strata` | `cmake --build build -j 8 --target unbiased-strata` | 38,221,376 B; `cuobjdump --list-elf` shows `sm_61` only | 173 s |
|
||||
| every other target | `cmake --build build -j 8 -- -k` | 93 targets built, 0 errors (`logs/all.log`) | 43 s on top of the engine's libraries |
|
||||
|
||||
No compile error for sm_61 at all, so the table of section 1 stands: every `mma.sync` / `ldmatrix` / tf32 /
|
||||
`cp.async` / cluster / `__nanosleep` / `__match_any_sync` site is behind a `__CUDA_ARCH__` guard with a fallback or
|
||||
a trap that its host code never launches below the architecture. The 102 warnings of the engine build are the same
|
||||
on every target: 46 `-Wdeprecated-enum-enum-conversion` from ggml's `ggml_scale_mode | ggml_scale_flag`, nvcc's
|
||||
`#611-D` partially overridden `ExpertSource::prefetch` (twice each for `FileExpertSource` and `ArenaExpertSource`),
|
||||
`#177-D` the unused `MAGIC` of `strata::prefill::fused`, a handful of unused variables (`w`, `width`, `n_bid`) and
|
||||
unused functions in the vendored jinja. None is architecture-specific.
|
||||
|
||||
The VM has no `gguf` module for its system Python, but `tools/qwen36_synth_gguf.py` and `tools/iq_pack.py` run
|
||||
there with the vendored `third_party/llama.cpp/gguf-py` on `PYTHONPATH` (numpy 2.2.4 is installed).
|
||||
|
||||
## 3. The parity tests and ctest on the 1080 Ti
|
||||
|
||||
`ctest --output-on-failure --timeout 900` in `build/`: 75 tests, 52 s. First run: 7 failed, 2 skipped. Two of the
|
||||
failures were the branch's own tests that had never been run (both CUDA-gated in CMake, so the Mac had no binary),
|
||||
fixed on the branch; the final run (`logs/ctest-final.log`) is **69 passed, 4 failed, 2 skipped**.
|
||||
|
||||
| Test | 1080 Ti | First line of the failure | Pascal-specific? |
|
||||
| --- | --- | --- | --- |
|
||||
| `qwen36_synth_fixtures` then `model_geometry_test` | failed, then Not Run; **pass after the fix** | `CMake Error at cmake/qwen36_synth_fixtures.cmake:11 (list): list index: 1 out of range (-1, 0)` | no: cmake 3.31 drops the empty element of `"toy.gguf;"` with CMP0007 unset (cmake 4 on the Mac does not). Fix: `cmake_policy(SET CMP0007 NEW)` in the script (commit `cd2a73c`). `model_geometry_test --real` also passes on the VM against both real files |
|
||||
| `expert_layout_test` | 3 checks failed; **all pass after the fix** | `qwen36-q4_k_xl.txt: per-layer formats and blobs (... total 19636158464 B) FAIL` and twice `at Flash-Next's 2560 x 640 refused by its numbers: native experts: expert geometry is not whole blocks FAIL` | no: the test's Q4 total constant was 524,288 B above the pack's own header (19,635,634,176 B), and n_ff 640 is not whole 256-value blocks for Q4_K / IQ2_S rows, so `native_fmt` refuses before the blob message the test looked for (commit `5798a46`) |
|
||||
| `kv_hybrid_parity` | **FAIL** at `[5/5]` (steps 1 to 4 pass, max error 7.8e-08 / 4.4e-03 vs true fp32) | `[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)` | **yes**: `qsa_prompt_attn_batch` returns false for `cc < 70` (`qsa_prompt_attn.cu:1433`), by design (the prompt path takes the decode kernel on Pascal, design doc section 7 item 3). The test counts a refusal as PASS on HIP and FAIL on CUDA; it needs the same "refused below sm_70: the old kernel runs" branch. Step 3 item, with the dense attention work |
|
||||
| `platform_memory_test` | FAIL | `lock_resident: ok=0 locked=0 MiB (mlock failed (raise ulimit -l))` | no: the VM's `ulimit -l` hard limit is 8,192 KiB; every `file_cache_keeps` case before it passes |
|
||||
| `ple_parity` | FAIL | `ple_parity: required PLE table is missing or incompatible: ../../Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf (cannot open ...)` | no: the test hardcodes a Flash-Next shard path relative to the build directory; the VM has no Flash-Next file |
|
||||
| `expert_multi_test` | FAIL | `strata: this CPU cannot run the expert kernel: missing AVX512F AVX512BW AVX512VL AVX512-VNNI AVX512-VBMI.` | no: the canonical Q2_0 CPU expert kernel needs AVX-512; the Ryzen 7 1700 has AVX2 only (`STRATA_PORTABLE=ON`). Qwen3.6 rides the native pack path, which does not use this kernel |
|
||||
| `prefill_fused_moe_test`, `prefill_fused_iq_test` | Skipped (exit 77) | | expected: the fused prompt MoE needs sm_80 (`CMakeLists.txt`, SKIP_RETURN_CODE 77) |
|
||||
|
||||
**`expert_multi_test` and AVX-512, on both VMs.** VM 211's Ryzen 7 1700 (Zen 1) and VM 221's i9-9900K (Coffee Lake)
|
||||
both lack AVX-512, so `expert_multi_test` refuses on both with `this CPU cannot run the expert kernel`. The kernel it
|
||||
tests is the canonical Q2_0 pack's CPU expert kernel (`src/kernels/cpu/expert.cpp`, `s2_expert_vnni_q`: AVX-512 VNNI
|
||||
and VBMI, with a scalar fallback for tests only), which bakes Flash-Next's 2560 x 640. The engine calls
|
||||
`cpu_require_expert_support()` only when the pack is NOT native (`generate.cpp`, "the canonical Q2_0 pack's CPU
|
||||
kernels are AVX-512 only; a native pack runs on AVX2 CPUs as well"); for a native pack it logs instead that the
|
||||
expert kernels run on AVX-2 (or ggml-cpu `vec_dot` without AVX2 / with `STRATA_NO_IQ256`). What that means for
|
||||
step 5's RAM tier: the RAM tier (`FileExpertSource`'s pinned "cache complement", filled by profile rank) is read in
|
||||
two ways, both from the same bytes. The CPU lane computes experts from it: `ExpertPool`'s native modes 5 and 6
|
||||
(`src/kernels/cpu/pool.cpp`, `native_gu_rows` / `native_down_rows`, the AVX-2 i-quant kernels or ggml-cpu's
|
||||
`vec_dot`) take the blob pointer the source hands them, which is the complement's copy when the expert is held there
|
||||
and the mapped GGUF otherwise. And the VRAM staging path copies from it: `FileExpertSource::copy_blob` memcpys the
|
||||
complement's blob into the stage buffer bound for a VRAM slot (`prefetch` skips experts the complement holds; the
|
||||
`RAM-copy reads` counter of STATS). So the RAM tier is both a compute tier (the CPU lane, on AVX-2 for Qwen3.6
|
||||
on these hosts) and the source of VRAM refills; neither path touches the AVX-512 kernel, and the engine's own
|
||||
start-up refusal on these CPUs applies to the canonical pack only.
|
||||
|
||||
Everything else passed, including every kernel parity on the card: `iq_parity`, `iq_multi_parity`, `mmvq_multi_parity`,
|
||||
`s2_gemv_*`, `s_gemv_*`, `dequant_s2_parity`, `gdn_parity`, `gdn_rec_parity`, `gr_parity`, `qsa_parity`,
|
||||
`qsa_topk_parity`, `qsa_topk_active_parity`, `decode_cluster_parity`, `sampler_parity` (all three), `rope_parity`,
|
||||
`quantize_act_parity`, `route_window_parity`, `router_top10_parity`, `router_dot_parity` (and `_avx`),
|
||||
`elementwise_parity`, `bf16_gemv_parity`, `gemm_bf16_parity`, `kv_q4_parity`, `kv_q8_parity`, `kv_stream_parity`,
|
||||
`cvec_parity`, `native_grouped_parity`, `shared_expert_parity`, `s2_expert_grouped_parity`, the nine
|
||||
`native_expert_parity_*` cases (including `refuses_q6_K`), `cuda_device_selftest`, `ple_reader_selftest`, the
|
||||
expert cache / source / profile tests, `vram_plan_test`, `gguf_*`. So on the 1080 Ti the numerics of every kernel
|
||||
that has a parity test agree with their references; the one Pascal-specific result is a refusal, not a wrong number.
|
||||
|
||||
## 4. The pack and the gate
|
||||
|
||||
The pack is the layout half (`tools/iq_pack.py --layout-only`): one `native_experts.txt`, made on the Mac in 0.35 s
|
||||
and copied to `/home/rk/packs/qwen36-iq3/` (2,669 B). The Q4_K_XL layout was made on the VM itself
|
||||
(`PYTHONPATH=third_party/llama.cpp/gguf-py`, 0.6 s, 2,727 B, `/home/rk/packs/qwen36-q4/`), byte-identical in its
|
||||
layer lines to `tests/data/native_experts/qwen36-q4_k_xl.txt`.
|
||||
|
||||
**The first run did not reach the gate.** With the tree at `8b7525e` both files printed the geometry block and then
|
||||
exit 1 in 0.13 s from the expert format whitelist that `generate.cpp` ran right after the layout load:
|
||||
|
||||
strata generate: layer 0's experts are IQ2_S/IQ3_XXS (ggml types 22/18), which this engine has no GPU kernels for
|
||||
|
||||
(`Q4_K/Q5_K (ggml types 12/13)` for the Q4 file). `native_expert_supported()`'s *down* types (`STRATA_D_FMTS` in
|
||||
`src/kernels/cuda/iq_kernels.cu`) are IQ4_NL, IQ4_XS, Q5_0, Q5_1, Q8_0 and type 42; Q4_K / Q5_K / IQ2_S / IQ3_XXS
|
||||
are gate/up types only and Q6_K is in neither (`native_expert_parity_refuses_q6_K` pins that). The IQ3_XXS file's
|
||||
down projections are IQ3_XXS on 37 layers (IQ4_XS on 34/38/39, which the kernels have); the Q4_K_XL's are Q5_K on
|
||||
37 and Q6_K on 34/38/39. The study's section 3.7 checked the layout against these types, not the kernels. The down
|
||||
kernels are step 3's `qwen36-step3-experts` branch; commit `30e3add` moved the gate ahead of the whitelist, so a
|
||||
Qwen3.6 file now prints the plan and the missing pairs. The whitelist still runs, unchanged, for every other file.
|
||||
|
||||
**The gate as it stands** (`30e3add` and after, `logs/gate-IQ3_XXS-cap0.log`): exit 2 after 0.36 s, the IQ3_XXS
|
||||
file with its layout pack, the notes' command:
|
||||
|
||||
strata generate: model geometry (/home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf, from the file's metadata):
|
||||
arch qwen35moe
|
||||
n_embd 2048
|
||||
n_layers 40
|
||||
nextn_layers 0
|
||||
qsa_interval 4
|
||||
n_qsa_layers 10
|
||||
n_gdn_layers 30
|
||||
ssm_state_size 128
|
||||
ssm_k_heads 16
|
||||
ssm_v_heads 32
|
||||
ssm_d_conv 4
|
||||
ssm_conv_channels 8192
|
||||
ssm_value_dim 4096
|
||||
n_head 16
|
||||
n_head_kv 2
|
||||
head_dim 256
|
||||
n_rot 64
|
||||
rope_sections 11,11,10,0
|
||||
rope_base 10000000.000000
|
||||
rms_eps 0.000001
|
||||
idx_q_heads 0
|
||||
idx_key_dim 0
|
||||
hc 1
|
||||
hc_lr 0
|
||||
n_expert 256
|
||||
n_expert_used 8
|
||||
n_ff 512
|
||||
n_ff_shexp 512
|
||||
has_ple no
|
||||
has_indexer no
|
||||
strata generate: VRAM plan for /home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf on this card (kv q4_0, prefill borrows cache slots):
|
||||
VRAM budget 11001 MiB
|
||||
fixed set at 262144 tokens: 4019 MiB = weights 1596 + drafter 520 + KV 1440 + session 162 + CUDA context 0 + reserve 300 (prefill borrows cache slots)
|
||||
expert slots in VRAM: 6748 of 10240 (65%) at 6981 MiB, 1084825 B mean blob
|
||||
expert copies in RAM: 3492 (3612 MiB of 9409 MiB available minus 4096 headroom)
|
||||
experts mapped from the model file: 0
|
||||
strata generate: step 3 also needs GPU expert kernels for gate-up/down IQ2_S/IQ3_XXS (37 layers: 0, 1, 2, 3, 4, 5, 6, 7, ... (37 layers))
|
||||
strata generate: this is a Qwen3.6-35B-A3B file (qwen35moe, 40 layers, 2048 wide, 256 experts x top-8): Phase 2 step 2 (geometry, metadata, the VRAM plan above) is done, but the engine cannot run it yet. Not done: step 3 (kernels and the block: the GDN gate SiLU(z) instead of sigmoid(z), dense attention at 16 heads with no indexer, the block and the verify window without hyper-connections, prefill at this geometry), step 4 (the native pack and the MTP drafter from blk.40, the expert profile at 40 x 256). See docs/PLAN-qwen36-35b-a3b.md section 5 and docs/qwen36-port/step2-notes.md
|
||||
|
||||
The Q4_K_XL file (`logs/gate-Q4_K_XL-cap0.log`, exit 2): the same geometry block with `nextn_layers 1`, then
|
||||
|
||||
strata generate: VRAM plan for /home/rk/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf on this card (kv q4_0, prefill borrows cache slots):
|
||||
VRAM budget 11001 MiB
|
||||
fixed set at 262144 tokens: 4461 MiB = weights 2038 + drafter 520 + KV 1440 + session 162 + CUDA context 0 + reserve 300 (prefill borrows cache slots)
|
||||
expert slots in VRAM: 3575 of 10240 (34%) at 6539 MiB, 1917542 B mean blob
|
||||
expert copies in RAM: 2929 (5356 MiB of 9453 MiB available minus 4096 headroom)
|
||||
experts mapped from the model file: 3736 (read from disk on a miss)
|
||||
strata generate: step 3 also needs GPU expert kernels for gate-up/down Q4_K/Q5_K (37 layers: 0, 1, 2, 3, 4, 5, 6, 7, ... (37 layers))
|
||||
strata generate: step 3 also needs GPU expert kernels for gate-up/down Q4_K/Q6_K (2 layers: 34, 38)
|
||||
strata generate: step 3 also needs GPU expert kernels for gate-up/down Q5_K/Q6_K (1 layers: 39)
|
||||
strata generate: this is a Qwen3.6-35B-A3B file (qwen35moe, ...): [the same gate message]
|
||||
|
||||
(CUDA reports the card as 11,165 MiB total with 11,001 free at start, 164 MiB in use by the display and the
|
||||
driver; `nvidia-smi`'s 11,264 is the marketing figure.)
|
||||
|
||||
**`--vram-cap` on the 1080 Ti** (`logs/gate-*-cap*.log`, after commit `2b4fcf1`): the cap line and the plan at
|
||||
the study's caps that fit on an 11 GB card. "Free to this engine" is cap minus the 164 MiB in use before the
|
||||
start, within the driver's 1 MiB rounding of the blocker, at every cap; the start would refuse if it were more than
|
||||
64 MiB off.
|
||||
|
||||
| `--vram-cap` (MiB) | held back | free to this engine | expected (cap - 164) |
|
||||
| ---: | ---: | ---: | ---: |
|
||||
| 5722 (6 GB) | 5443 | 5557 | 5557 |
|
||||
| 7629 (8 GB) | 3536 | 7463 | 7464 |
|
||||
| 8192 | 2973 | 8027 | 8027 |
|
||||
| 10490 (11 GB decimal) | 675 | 10325 | 10325 |
|
||||
| 12288 | "is not below this card's 11165 MiB: no cap" | 11001 | |
|
||||
|
||||
The plan's tiers at each cap are in `step2-notes.md` section 5, next to the study's table 4.3.
|
||||
## 5. The Makefile's Pascal switch
|
||||
|
||||
`make build CUDA_ARCHS=61 BUILD_DIR=build-make` on the VM, with no compiler override at all (`logs/make-plain.log`):
|
||||
the llama.cpp patch applied (`git apply` works outside a repository, so the rsynced tree without `.git` is fine and
|
||||
the patch now sits in the VM copy of the submodule), CMake chose Debian's g++ 14.2 for the host code and nvcc 12.4
|
||||
took g++-13 as its host compiler by itself (`NVIDIA 12.4.131 with host compiler GNU 13.3.0`), `Strata: CUDA enabled,
|
||||
arch 61` with `STRATA_EXPERIMENTAL_SM60=ON` from the Makefile's switch, 0 errors, `built: build-make/unbiased-strata`
|
||||
(38,627,048 B) in 181 s from configure to link; `cuobjdump --list-elf build-make/unbiased-strata` shows `sm_61` only.
|
||||
@@ -1,166 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 2: geometry, metadata, the VRAM planner
|
||||
|
||||
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step2`, branched from `qwen36-oracle`).
|
||||
The design is `docs/QWEN36-35B-A3B.md` sections 3.7 to 3.9 and 4.2; the plan is `docs/PLAN-qwen36-35b-a3b.md`
|
||||
section 5 step 2. Every item below says what was decided, where it lives, and how it is checked.
|
||||
|
||||
## 1. What the engine does with a Qwen3.6 file at the end of this step
|
||||
|
||||
Started with `--native Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --pack <dir with native_experts.txt>` the engine:
|
||||
|
||||
1. reads every field of `ModelGeometry` from the file's `qwen35moe.*` keys and logs them;
|
||||
2. refuses the two fused tensor layouts by name if the file had them (no shipped file does);
|
||||
3. starts without `--ple-gguf` (the architecture has no PLE), with no PLE kernels selected;
|
||||
4. checks the pack's `native_experts.txt` against the model's 2048 x 512 (every layer's ggml formats must make
|
||||
the pack's blob size);
|
||||
5. makes the VRAM plan of section 4.2 from this card's free VRAM (clamped by `--vram-cap`) and the file's own
|
||||
census, prints the three tiers (VRAM slots, RAM copies, mapped experts), and
|
||||
6. **stops at the step 2 gate**, exit 2, with this message (from `strata::core::qwen35moe_not_yet`):
|
||||
|
||||
> this is a Qwen3.6-35B-A3B file (qwen35moe, 40 layers, 2048 wide, 256 experts x top-8): Phase 2 step 2
|
||||
> (geometry, metadata, the VRAM plan above) is done, but the engine cannot run it yet. Not done: step 3 (kernels
|
||||
> and the block: the GDN gate SiLU(z) instead of sigmoid(z), dense attention at 16 heads with no indexer, the
|
||||
> block and the verify window without hyper-connections, prefill at this geometry), step 4 (the native pack and
|
||||
> the MTP drafter from blk.40, the expert profile at 40 x 256).
|
||||
|
||||
Why a gate and not a run: `layer.cpp` and `verify.cpp` still wrap every layer in the hyper-connection read/write
|
||||
and require the `hc_*` and `indexer.*` tensors (`layout.cpp`'s `check_one`), the GDN kernels gate with sigmoid,
|
||||
prefill refuses any geometry but 2560/4/320/top-10. Each of those is step 3. Failing before the first weight
|
||||
moves, with the plan printed, is Maya's Phase 0 shape.
|
||||
|
||||
The real file's log on the Mac (`model_geometry_test --real`), both the IQ3_XXS and the Q4_K_XL file:
|
||||
|
||||
arch qwen35moe, n_embd 2048, n_layers 40 (nextn 0 / 1), qsa_interval 4 (10 attention, 30 GDN),
|
||||
ssm state 128 / 16 k-heads / 32 v-heads / conv 4, conv channels 8192, value dim 4096,
|
||||
n_head 16, n_head_kv 2, head_dim 256, n_rot 64, sections 11,11,10,0, base 1e7, eps 1e-6,
|
||||
hc 1, n_expert 256, k 8, n_ff 512, shexp 512, no PLE, no indexer
|
||||
|
||||
## 2. Decisions
|
||||
|
||||
| Decision | Where | Why |
|
||||
| --- | --- | --- |
|
||||
| `ModelGeometry` carries `arch` (an enum), `nextn_layers`, `n_rot`, `rope_sections`, `rope_base`, `rms_eps`, `n_ff_shexp`, `n_expert_used`, `n_vocab`, `has_ple`; `derive()` computes conv channels and value dim | `include/strata/core/layout.hpp` | the stored conv channels / value dim were the row-2 trap: changing `ssm_v_heads` alone left them at Flash-Next's. An enum, not a string, so the struct stays trivially copyable for the `.cu` files that take it by value |
|
||||
| The reader is header-only and CUDA-free | `include/strata/core/model_geometry.hpp` | the unit test links only the GGUF reader; the engine reads the geometry before any weight moves |
|
||||
| `hc = 1`, `has_ple = false`, no indexer come from the architecture string, not a key | same | the file has no key for any of them; llama.cpp decides the same way |
|
||||
| For `qwen4exp` the GDN, ff and interval keys are optional (defaults stay); for `qwen35moe` they are required | same | no Flash-Next file was on hand to confirm which of its keys are present; a required key that a shipped Flash-Next file lacks would have broken the working model. The six keys the guard always demanded stay required for both |
|
||||
| `check_architecture` accepts `qwen35moe` with presence-only checks of llama.cpp's required key set | `include/strata/artifact/gguf_reader.hpp` | the file is the authority on its sizes; the guard's job is "is this a file llama.cpp's own loader would accept" |
|
||||
| Fused forms refused by tensor name (`ffn_gate_up_exps`, `attn_qkv` in an attention layer) at the engine and in `iq_pack.py` | `model_geometry.hpp` (`check_model_tensor_forms`), `tools/iq_pack.py` (`expert_layout`) | `attn_qkv` is legitimate in a GDN layer (the conv input), so the check is per layer type |
|
||||
| `expert_layout_load` takes `n_embd`, `n_ff` | `include/strata/kernels/cpu/expert_layout.hpp`, `src/kernels/cpu/expert_layout.cpp` | the one leak (row 108). A pack with no `native_experts.txt` (canonical Q2_0, which bakes 2560 x 640) is now refused for any other geometry with a message naming the packer |
|
||||
| The geometry is read before the layout load in `generate.cpp`; `K` and the embedding dims come from it; the rope keys are read under the file's own prefix | `src/program/generate.cpp` (the block before `expert_layout_load`) | rows 7 to 11 |
|
||||
| The draft (nextn) block is left out of the trunk's `native_experts.txt` | `tools/iq_pack.py` | the Q4_K_XL file carries `blk.40`; a layout with 41 layers would make the engine route layer 40 of a 40-layer model. The drafter's pack (step 4) takes it |
|
||||
| `--ple-gguf` is not required when the architecture has no PLE; an explicit one is refused; the PLE kernels are not selected; the session carves no PLE history | `generate.cpp` (the `--native` block), `src/core/session.cpp` | 3.9: the kernels already ran without it, only the CLI insisted. The 360 KB `NG_HIST x NG_HC_DIM` buffer is skipped through `has_ple` |
|
||||
| The planner is a pure function at the mean blob | `include/strata/plan/vram_plan.hpp` | testable without a GPU; the engine's per-layer sizing prices the same bytes at each profile entry's own blob and lands within a few slots |
|
||||
| The context is lowered in steps of 4,096 toward 131,072, never below; below the floor the start refuses with every number and the IQ3 file's name | same | the plan's rule; KV streaming is not a lever for dense attention |
|
||||
| The reserve in the Qwen3.6 plan is 300 MiB (`kSmallReserveMib`) unless `--vram-reserve-mib` was given | `generate.cpp` (the gate) | table 4.3 was derived at the small reserve; the Flash-Next auto sizing starts at 700 and shrinks to 300 only when the cache would be too small |
|
||||
| The prompt buffers in the plan are the engine's own estimate (`160 + chunk * 680 / 1024` MiB: 1,520 at chunk 2048), not llama.cpp's 1,904 | same | it is this engine's prompt path that allocates them; the study's figure was the baseline's compute buffer. With a profile prefill borrows cache slots and the term is 0 |
|
||||
| `--vram-cap MIB`: every `cudaMemGetInfo` in `generate.cpp` goes through `vram_info`, which clamps the free figure to `cap - used`; a blocker of `total - cap` is allocated before the weight arena | `generate.cpp` (`vram_info`, the cap block) | 4.2 item 4. `used` counts every process, so the cap is the card's size, not this engine's share |
|
||||
| `--ram-cap GIB`: `host_available_memory` is clamped (so `pin_cache_complement` sizes the RAM tier as that machine would), the resident budget is clamped, the pinned arena's limit too | `src/core/expert_source.cpp` (`set_host_ram_cap`), `generate.cpp` | the page cache cannot be capped from inside the process (the 12 GiB VM does that physically) |
|
||||
| Tier counters: the serve loop's `STATS` command answers one JSON line; the same line is logged at start; `/health` carries it as `tiers` | `generate.cpp` (`tier_stats`), `frontend/main.cpp` | VRAM slots and how many hold an expert, RAM copies (`complement_count`), mapped experts, tokens served, VRAM hits of lookups, RAM-copy reads, file reads, warm hints, and the major page faults from `/proc/self/stat` since start as the disk-read proxy. During a request `/health` serves the last reading marked `tiers_stale` |
|
||||
| The Flash-Next path keeps its allocation order and auto sizing; it gains the cap and the counters | `generate.cpp` | its fixed set is allocated progressively with its own refusals; the lowering rule is for the dense-KV model, which is gated here anyway |
|
||||
|
||||
## 3. What a Qwen3.6 native pack contains (step 4 builds it; the layout half exists now)
|
||||
|
||||
`tools/iq_pack.py --gguf <file> --out <dir> --layout-only` writes `native_experts.txt` alone (v3: one line per
|
||||
trunk layer with the gate/up and down ggml types, the blob size, and the three tensors' absolute offsets) and
|
||||
prints the census. The two real files:
|
||||
|
||||
| File | Layers x experts | Expert bytes | Mean / largest blob | Per-layer formats |
|
||||
| --- | --- | ---: | ---: | --- |
|
||||
| `UD-IQ3_XXS` | 40 x 256 | 10,594 MiB (11,108,614,144 B) | 1.035 / 1.172 MiB | gate/up IQ2_S everywhere; down IQ3_XXS on 37 layers (blob 1,073,152 B), IQ4_XS on 34, 38, 39 (1,228,800 B) |
|
||||
| `UD-Q4_K_XL` (MTP repo) | 40 x 256 (+ `blk.40`, the drafter's, left out) | 18,726 MiB (19,635,634,176 B) | 1.829 / 2.195 MiB | gate/up Q4_K, down Q5_K on 37 layers (1,900,544 B); Q4_K / Q6_K on 34 and 38 (2,039,808 B); Q5_K / Q6_K on 39 (2,301,952 B) |
|
||||
|
||||
These two files are `tests/data/native_experts/qwen36-{iq3_xxs,q4_k_xl}.txt` and `expert_layout_test` loads them
|
||||
at 2048 x 512 (every layer's `NativeFmt` makes the blob) and sees them refused at 2560 x 640. The full pack
|
||||
(step 4) adds `index.txt` (the dense projections served natively from the GGUF: Q6_K / Q8_0 `attn_*`, `ssm_out`,
|
||||
`ffn_*_shexp`, `output`), `dense.bin` with the float tensors in the engine's forms (the norms F32 as stored;
|
||||
the F32 routers, `ssm_alpha`, `ssm_beta` and the 1-D shexp gate need `--compat-bf16` today, which step 4 decides),
|
||||
the tokenizer, and `expert-profile.bin` at 40 x 256 from the E0 trace.
|
||||
|
||||
## 4. Build and test commands
|
||||
|
||||
On the Mac (no CUDA; the artifact reader, the planner and the geometry test build and run):
|
||||
|
||||
cmake -S . -B build-mac -G Ninja -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_BUILD_TESTS=ON
|
||||
cmake --build build-mac --target model_geometry_test vram_plan_test gguf_split_test gguf_reader_test
|
||||
(cd build-mac && ctest -R 'qwen36_synth|model_geometry|vram_plan|gguf' --output-on-failure)
|
||||
./build-mac/model_geometry_test --real ~/models/qwen3.6/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf
|
||||
./build-mac/vram_plan_test --at q4 11264
|
||||
python3 tools/iq_pack.py --gguf ~/models/qwen3.6/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --out /tmp/p --layout-only
|
||||
python3 tools/test_iq_pack.py
|
||||
|
||||
Results on the Mac, 2026-10-11: `model_geometry_test` 32 checks pass on the synthetic files and the real-file
|
||||
mode passes on both files; `vram_plan_test` 43 checks pass; `test_iq_pack.py` 23 tests pass.
|
||||
|
||||
On VM 211 (the 1080 Ti, sm_61; `docs/qwen36-port/pascal-build.md` has the build's outcome):
|
||||
|
||||
rsync -a --delete --exclude build-mac --exclude .git --exclude build --exclude build-make --exclude logs \
|
||||
/Users/robertkarl/Code/UnbiasedStrata-step2/ rk@192.168.50.43:/home/rk/UnbiasedStrata-step2/
|
||||
# (--delete without the three VM-side excludes removed the VM's build/, build-make/ and logs/ once)
|
||||
cmake -S . -B build -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=ON \
|
||||
-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61 -DCMAKE_CUDA_HOST_COMPILER=g++-13 \
|
||||
-DCMAKE_C_COMPILER=gcc-13 -DCMAKE_CXX_COMPILER=g++-13
|
||||
cmake --build build -j 8 --target unbiased-strata
|
||||
cmake --build build -j 8 # every parity target the root CMakeLists declares
|
||||
(cd build && ctest --output-on-failure)
|
||||
./build/expert_layout_test tests/data/native_experts
|
||||
./build/model_geometry_test build/qwen36_synth
|
||||
./build/unbiased-strata --engine --native /home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --pack /home/rk/packs/qwen36-iq3 \
|
||||
--tokens 1 --max-context 262144 --kv q4_0 --spec 4 --prefill 2048 --expert-profile /dev/null # the gate
|
||||
|
||||
## 5. VM 211 results
|
||||
|
||||
Done 2026-10-11 after the sweep and its nvprof re-runs released the card (`docs/qwen36-port/pascal-build.md` has
|
||||
every log line; the VM keeps the tree at `/home/rk/UnbiasedStrata-step2/` with `build/`, `build-make/` and `logs/`).
|
||||
|
||||
| Item | Result |
|
||||
| --- | --- |
|
||||
| sm_61 build | no source change needed: configure 4 s, `unbiased-strata` 173 s, every other target 43 s more, 0 errors; `cuobjdump --list-elf` shows `sm_61` only. Every sm_75+ site was already behind `__CUDA_ARCH__` (pascal-build.md section 1) |
|
||||
| `make build CUDA_ARCHS=61` | end to end with no compiler override, 181 s, `sm_61` only; the Makefile's switch sets `STRATA_EXPERIMENTAL_SM60=ON` |
|
||||
| ctest on the 1080 Ti | 75 tests: 69 pass, 4 fail, 2 skip (sm_80 fused prompt MoE). Of the failures one is Pascal-specific, `kv_hybrid_parity` [5/5], where `qsa_prompt_attn_batch` refuses `cc < 70` by design and the test counts the refusal as a failure (step 3). The other three are the host: `platform_memory_test` (mlock limit 8 MiB), `ple_parity` (hardcoded Flash-Next path), `expert_multi_test` (AVX-512 on Zen 1). Two of the branch's own tests had never been built (CUDA-gated): `qwen36_synth_fixtures` failed under cmake 3.31 (CMP0007, commit `cd2a73c`) and `expert_layout_test` carried a wrong Q4 total and a refusal-message expectation (commit `5798a46`); both pass now, and `model_geometry_test --real` passes on the VM against both real files |
|
||||
| the pack | `native_experts.txt` only: 2,669 B in 0.35 s on the Mac for the IQ3_XXS file; 2,727 B in 0.6 s on the VM (vendored gguf-py) for the Q4_K_XL file |
|
||||
| the gate | **not reached.** Both real files print the geometry block and are then refused by the native expert kernel's format whitelist, before the plan: `layer 0's experts are IQ2_S/IQ3_XXS (ggml types 22/18), which this engine has no GPU kernels for` (exit 1, 0.13 s), and `Q4_K/Q5_K (12/13)` for the Q4 file. The grouped kernels' *down* types are IQ4_NL / IQ4_XS / Q5_0 / Q5_1 / Q8_0 only; the IQ3_XXS file's down is IQ3_XXS (37 layers), the Q4_K_XL's Q5_K and Q6_K. A step 3 kernel item (or a step 4 repack of the down projections) the plan did not list; the gate message itself is exercised by `model_geometry_test --real` |
|
||||
|
||||
Correction to section 3's table: the Q4_K_XL expert total is 19,635,634,176 B (the pack header's figure, and the sum
|
||||
of its blobs); the earlier 19,636,158,464 was 524,288 B high and was also in `expert_layout_test`.
|
||||
|
||||
### The planner on the 1080 Ti against the study's table 4.3 (2026-10-11, after `4a998ad`)
|
||||
|
||||
The engine's own plan (`--vram-cap`, prefill borrowing, `logs/gate-*-cap*.log` on the VM) at the caps an 11 GB card
|
||||
can emulate; the study's "derived, borrow" column beside each. The engine's figures run a few percent above the
|
||||
study's because the study's budgets carry a 300 MiB CUDA-context term that the engine's free figure already lacks,
|
||||
less the 164 MiB this VM's display and driver hold. The 12, 16, 24 and 32 GB rungs cannot be emulated on this card
|
||||
(`--vram-cap 12288` is "not below this card's 11165 MiB: no cap"); `vram_plan_test` covers them from the study's
|
||||
inputs.
|
||||
|
||||
| Budget | cap (MiB) | VRAM budget | Q4 slots (study) | Q4 RAM copies / mapped | IQ3 slots (study) | IQ3 RAM copies / mapped |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 6 GB | 5722 | 5557 | 598 (~525) | 2,894 / 6,748 | 1,486 (~1,350) | 5,172 / 3,582 |
|
||||
| 8 GB | 7629 | 7463 | 1,641 (~1,570) | 2,855 / 5,744 | 3,328 (~3,200) | 5,115 / 1,797 |
|
||||
| 8 GiB | 8192 | 8027 | 1,949 | 2,874 / 5,417 | 3,873 | 5,068 / 1,299 |
|
||||
| 11 GB (decimal) | 10490 | 10325 | 3,206 (~3,130) | 2,959 / 4,075 | 6,094 (~5,960) | 4,146 / 0 |
|
||||
| 1080 Ti, no cap | | 11001 | 3,575 (~3,550) | 2,929 / 3,736 | 6,748 (~6,700) | 3,492 / 0 |
|
||||
|
||||
The RAM tier is sized from this VM's ~9.4 GiB available minus the 4 GiB headroom (the `--resident-experts` rule),
|
||||
so the Q4 file keeps a disk tier at every cap on this host and the IQ3 file none from 11 GB up, as 4.3 said.
|
||||
|
||||
### What the review and the Pascal run changed afterwards (2026-10-11, the same branch)
|
||||
|
||||
| Finding | Commit | What changed |
|
||||
| --- | --- | --- |
|
||||
| the down-type whitelist, missed by the study's section 3.7 | `30e3add` | 3.7 said "the IQ3_XXS file's 37/3 down split and the Q4_K_XL's Q6_K layers need no format change" of the *layout*; it did not check `STRATA_D_FMTS`, the grouped kernels' down types (IQ4_NL, IQ4_XS, Q5_0, Q5_1, Q8_0), against the files' IQ3_XXS / Q5_K / Q6_K down projections. The gate now runs before that whitelist and names the missing pairs per layer; the kernels are step 3's `qwen36-step3-experts` branch |
|
||||
| `--vram-cap` subtracted the blocker twice | `2b4fcf1` | `vram_info` takes the blocker's own bytes out of `used`; the cap line prints what a card of the cap would show and refuses if the clamped figure is off by more than 64 MiB |
|
||||
| the planner's 300 MiB CUDA-context term on top of a free figure already net of it | `4a998ad` | the engine passes 0; the unit test keeps the study's 300 MiB with the cards' sizes as budgets |
|
||||
| `--ram-cap` set an explicit resident budget on the auto path | `76a437f` | only an explicit budget above the cap is clamped |
|
||||
| `/health`'s last reading raced | `84794ce` | its own mutex, copies under it |
|
||||
| the qwen4exp reader's optional keys untested | `afec2f1` | a fixture with the real Flash-Next key set equals the defaults field by field; the fixture writer gained f32 and u32-array values |
|
||||
| the trace bound literal 48; the refused-profile test | `db4da2f`, `d010040` | `Drive::n_layers` from the geometry; `expert_profile_save_test` sees a 48 x 512 profile refused for 40 x 256 |
|
||||
| `test_iq_pack.py` had no test of the step's additions | `b2ccff0` | `--layout-only`, the nextn exclusion, the fused refusal: 26 tests |
|
||||
| `tools/make_profile.py` `N_LAYER, N_EXPERT = 48, 512` | (step 4) | the profile from the E0 trace at 40 x 256 is step 4's, with the trace format |
|
||||
|
||||
`model_geometry_test --real` on the Mac's `~/models/dwarfstar/Qwen3.8-Flash-Next-Q2.gguf` (147 GB, the only Flash-Next
|
||||
file on the Mac or VM 211; the `ple_parity` shard path does not exist anywhere): the qwen4exp reader reads it
|
||||
(48 trunk layers, `nextn_layers 1`, every other field the struct's default, separate tensor forms), but the
|
||||
architecture guard refuses it with `qwen4exp.block_count = 49, expected 48`: the guard's qwen4exp branch wants the
|
||||
literal 48 (unchanged by this step, the reviewer's byte-for-byte check), and this file is an MTP build with a draft
|
||||
block. Whether that file ever ran under this engine is not this step's question; it is recorded here because the
|
||||
guard, not the reader, is what refuses it.
|
||||
@@ -1,214 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 3: dense attention replacing QSA
|
||||
|
||||
Working notes of the `attn` area (branch `qwen36-step3-attn`, from `qwen36-step2` at 8b7525e, 2026-10-11). The
|
||||
design is `docs/QWEN36-35B-A3B.md` section 3.3 (six items) and section 6 step 3, second bullet. Every item says
|
||||
what was decided, where it lives, how it is checked, and the numbers from both cards.
|
||||
|
||||
## 1. What changed, item by item
|
||||
|
||||
| 3.3 item | Decision | Where |
|
||||
| --- | --- | --- |
|
||||
| 1, the producer | A **null `ids` is the identity selection**: the decode and prompt kernels read cell `j = j` for `j < step[kStepWidth]`. The engine's dense paths pass `nullptr` and carve no ids buffer (prefill at 2,048 queries x 262,144 cells would carry 2 GiB of ids). The explicit form `qsa_identity_ids(ids, steps, n_q, cap, stream)` exists for a caller that must hand a buffer on (a dump, the streaming resolver) and for the test, which holds the two forms bit for bit equal | `src/kernels/cuda/qsa_decode_attn.cu`, `qsa_prompt_attn.cu`; `qsa_layer` and the verify window's attention step pass null |
|
||||
| 1, the indexer skipped | `g.has_indexer()` (step 2: false for `qwen35moe`) gates the raw key projection, the append, the indexer query, the block scores and the top-k in `qsa_layer` and in `Verifier`'s attention step; the four `indexer.*` tensors are required only with an indexer | `src/core/layer.cpp` (c4793cd), `src/core/verify.cpp` (bc2fb91), each one commit |
|
||||
| 2, G = 12 | `G` is a template parameter of every attention kernel, instantiated at **2, 8, 12**; `qsa_attn_group(s, why, n)` picks it from the geometry and returns 0 with a message naming the heads for any other ratio; `qsa_attn_group_check(s, G, why, n)` refuses a G that does not divide the geometry (G = 12 on 16 / 2 is a message, never a mis-indexed run); `qsa_prompt_attn_batch` returns false for an unknown ratio and the decode kernel then refuses by name | `qsa_decode_attn.cu`, `qsa_prompt_attn.cu`, `include/strata/kernels/qsa_decode_attn.hpp` |
|
||||
| 3, the selection width and the capacity | **One builder**, `strata::core::qsa_shapes(g)` (`include/strata/core/qsa_shapes.hpp`, header-only), used by `layer.cpp`, `verify.cpp`, `mtp.cpp`, `session.cpp` and `prefill.cpp` (the last two as `[shared]` commits): for a geometry without an indexer it zeroes `idx_n_head`, `idx_dim` **and** `idx_top_k`. The dense signal is `qsa_dense(s)` = the three zero together; `qsa_shapes_valid(s, why, n)` (what every kernel's guard checks, non-exiting for the test) refuses a half-set shape - two zeros with the 2,048 budget kept, which the first hand-written builders in verify and mtp made and the kernels' guard then exited on at the first append. `qsa_selection_width(n_kv, s)` returns `n_kv` when dense, so `qsa_step_fill` writes `width = n_kv`; **`qsa_selection_cap(max_cells, s)`** is the capacity every buffer is sized by: `max_cells` when dense, `qsa_selection_width(kTopkMaxCells, s)` = 2,051 otherwise. The indexer entry points refuse a dense shape by name (`validate_indexer`). Not converted: `generate.cpp:7469` (a snapshot-hash shape that sets only `n_head_kv`/`head_dim`/`idx_dim`; not edited on this branch) | `qsa_shapes.hpp`, `qsa.hpp`, `qsa.cu`, `layer.cpp`, `verify.cpp`, `mtp.cpp`, `session.cpp`, `prefill.cpp` |
|
||||
| 4, the state without the indexer | `kv_plan` gives a dense state `pooled_rows = 2` (the drafter's ring) and `idx_dim` is 0, so the three indexer regions are 0 bytes (section 3). The buffers carve no `cell_scores`, `ids`, `k_scratch`, `v_scratch` for the dense model: at 262,144 cells those are 1 + 1 + 512 + 512 MiB (the gather scratch was `cap x n_head_kv x 256 x 2 B` each) | `layer.cpp`: `kv_plan`, `qsa_state_bytes/init`, `qsa_buffers_bytes/init` |
|
||||
| 5, the split-K scratch | The grid is capped at **128 blocks per KV head**; a block walks its span of the selection in 64-cell sub-chunks with the running (m, l, acc) rescale. The span is computed **on the device from the token's width**, not from the capacity, so a selection up to 8,192 cells still spreads one block per 64 cells (decode at a short depth keeps its parallelism). **The bound applies to dense shapes only**: a sparse (Flash-Next) shape keeps `ceil(cap / 64)` blocks at any capacity, because the MTP drafter's ring runs this kernel at its `--mtp-window` (32,768 by default: 512 blocks, `mtp.cpp:249`) and keeps its previous grid, scratch (12 MiB at 24 heads) and summation order. On sm_75+ one looped kernel serves every capacity (the 4090 measures it equal to the old one at 2,051 cells). Below sm_75 (`STRATA_EXPERIMENTAL_SM60`, PR #540's kernel) the looped form costs 16-28 registers on sm_61 (80-92 at G 12 against 63-64; a register cap spilled and cost more), so every sparse shape, and a dense capacity under 8,192 cells, runs `attn_chunk_kernel_pre75_single`, PR #540's body as it was: every Flash-Next state (the QSA layers at cap 2,051, the drafter's ring at its window) is the old kernel to the instruction, and the looped `attn_chunk_kernel_pre75` runs only for the dense model's long-context states. `qsa_decode_attn_scratch_floats(cap, s) = min(ceil(cap / 64), 128) x n_head x 258 + 64`: **528,448 floats = 2.02 MiB per query row at 16 heads** for any cap >= 8,192 (was 64.5 MiB at 262,144); 16 MiB for the 8-row verify window, 64 MiB for prefill at `attn_batch` 32 | `qsa_decode_attn.cu` (`kMaxChunks`, `chunks_for`, both chunk kernels, `attn_merge_kernel<G>`) |
|
||||
| 6, KV streaming | `qsa_kv_streaming_applies(g, why)` (false for a no-indexer geometry, with the sentence that says why: every block resident every token is the whole KV over PCIe per token); `qsa_state_init` refuses a streamed dense state with that message as the backstop. The CLI check belongs in `generate.cpp`, which this branch does not edit (the step-2 branch owns it): the integrator wires `--kv-resident > 0 && !qsa_kv_streaming_applies(g, why)` into the start-up refusal | `include/strata/core/layer.hpp`, `layer.cpp` |
|
||||
|
||||
The formats carry over unchanged: the fp16 / INT8 / Q4_0 / K8V4 pools, the Hadamard rotation (`kv_rot`: q and the
|
||||
output rotated in `qsa_layer` and in verify exactly as before), the page table (shuffled in every test), the
|
||||
RoPE tables (the test builds them with `build_rope_table` at base 1e7 and holds `rope_neox_apply` to the oracle).
|
||||
|
||||
The prompt path on Pascal is the batched decode kernel (`qsa_prompt_attn_batch` returns false below cc 70), so
|
||||
G = 8 and the scratch bound above are the prefill attention there; on the 4090 the MMA kernels run at G = 8 (and
|
||||
2, 12). The MMA kernels pad the 16-row tile with zero rows for any G <= 16 exactly as 12 did; one real bug came
|
||||
out of G = 2: the two `mma` kernels wrote accumulator rows 0..7 unconditionally, which at G < 8 overwrote the next
|
||||
KV head's output (the 4 / 2 fixture read 0.99 relative L2). The writes are guarded by G now (856daa0).
|
||||
|
||||
## 2. The dense state's layout, exactly
|
||||
|
||||
`qsa_state_init` carves one 16-byte-aligned cursor (`layer.cpp`); for a no-indexer geometry (`pooled_rows = 2`,
|
||||
`idx_dim = 0`, `idx_block = 4`, mode 0, no ring) the regions are, in order:
|
||||
|
||||
| region | bytes | note |
|
||||
| --- | --- | --- |
|
||||
| K/V pools | `kv_pool_bytes(s, pages)` + 64: fp16 `pages x 2 x page_size x 256 x 2 x 2`; INT8 `pages x page_size x 1,056 + 64`; Q4_0 `pages x page_size x 576 + 64`; K8V4 `rows x 256 + rows x 8 + rows x 144 + 64` | `pages = ceil(max_cells / 4)`; 1,024 MiB fp16 / 528 INT8 / 288 Q4_0 / 408 K8V4 at 262,144 cells |
|
||||
| `page_table` | `pages x 4` | 256 KiB at 262,144 |
|
||||
| residency map | none | mode 1 is refused for the dense model |
|
||||
| `idx_tail` | `3 x idx_dim x 4` = **0** | pointer taken, nothing carved |
|
||||
| `idx_dead` | `idx_dim x 4` = **0** | |
|
||||
| `idx_pooled` | `pooled_rows x idx_dim x 4` = **2 x 0 x 4 = 0** | `idx_pooled_rows = 2` as the drafter's ring |
|
||||
| `idx_block_pos` | 16 (one int32, aligned) | kept: `QsaIndexerBuffers` is still a struct of four pointers |
|
||||
| `cos_tab`, `sin_tab` | `max_cells x 32 x 4` each, in the primary state only; the others borrow | 32 MiB each at 262,144 (`n_rot` 64) |
|
||||
| `step` | 16 | `kStepCount` int32 |
|
||||
| `attention_status` | 16 | |
|
||||
| `pos_dev` | `n_head x 4` -> 64 | |
|
||||
| trailer | +256 | `qsa_state_bytes` adds 256 after the alignment |
|
||||
|
||||
So the indexer's 32 MiB per attention layer at 262,144 cells (`65,538 x 128 x 4`) is gone; a dense state is the
|
||||
pools, the page table, the rope tables (primary only) and 112 bytes. `qsa_state_zero` memsets the 0-byte regions
|
||||
(a no-op). The buffers (`qsa_buffers_bytes`, one set per session): `x_q8k`, `x_q8_0`, `x_bf16`, `q_full`, `qcur`,
|
||||
`kcur`, `vcur`, `idx_raw` (0), `q_idx` (0), **no** `cell_scores` / `ids` / `k_scratch` / `v_scratch`, `attn`,
|
||||
`attn16`, `attn32`, `attn_q8k`, `attn_scratch` (2.02 MiB at 16 heads, any `max_cells` >= 8,192).
|
||||
|
||||
`conversation_state.cpp` / `conversation_snapshot.cpp` (the session save and restore) still address the indexer
|
||||
regions by `qsa_real_shapes().idx_block`; with `idx_dim = 0` their sizes are 0. Not exercised here (step 4's area).
|
||||
|
||||
## 3. How it is checked
|
||||
|
||||
`src/kernels/qsa_dense_parity.cpp` (CTest `qsa_dense_parity`, after the fixture test `qwen36_attn_fixtures`, which
|
||||
runs `cmake/qwen36_attn_fixtures.cmake`: `tools/qwen36_synth_gguf.py --heads 16,2|24,2|4,2 --head-dim 256
|
||||
--no-nextn` and `ref/qwen36.py --text "dense attention over sixteen heads, G=8!" --dump` on each; 40 tokens; about
|
||||
1 s). The `--head-dim` option is the one `[shared]` change (7368da2): the toy fixture is head_dim 32 and the
|
||||
engine's kernels are 256, so an engine-level comparison against the oracle needs a fixture at 256 (`n_rot` 64,
|
||||
the real IMRoPE sections in proportion, base 1e7).
|
||||
|
||||
1. **Host only.** The one builder on a `qwen35moe` geometry gives a dense shape the guard accepts, on Flash-Next's defaults the sparse real shape; the half-set shape (two zeros, budget 2,048) is neither dense nor valid (the negative). The chunk count by shape: dense 2,051 -> 33, 8,192 / 262,144 -> 128; sparse 32,768 -> 512 with the old scratch formula. The group from the geometry (16/2 -> 8, 24/2 -> 12, 4/2 -> 2, 26/2 refused naming 26 and 13);
|
||||
**G = 12 asked of 16 heads refused by name**; width and cap (sparse 3,000 -> 2,051 / 2,051; dense 3,000 ->
|
||||
3,000 / `max_cells`); `qsa_step_fill` width; `chunks` (2,051 -> 33, 8,192 and 262,144 -> 128); the scratch
|
||||
at 2,051 x 24 heads equals the old formula and at 262,144 x 16 heads is 528,448 floats.
|
||||
2. **The decode kernel against a host reference in double over the dequantized pools**, every KV format (fp16,
|
||||
INT8, Q4_0, K8V4; the pools filled through the engine's own append kernels behind a shuffled page table,
|
||||
read back and dequantized exactly as the kernel's loads do), at G = 8 (16 / 2) and G = 12 (24 / 2), widths
|
||||
300, 3,000 and 20,000 (the last one takes the multi-sub-chunk path: 313 sub-chunks over 128 blocks), three
|
||||
query rows per case with widths w, w - 1, w - 77 and their own steps; **null ids == explicit identity ids bit
|
||||
for bit**; the prompt kernel on the same rows where the host takes it (sm_70+). G = 2 fp16 at 3,000.
|
||||
**Negative:** the sparse width 2,051 handed to the kernel on the 3,000-cell context (what the old
|
||||
`qsa_selection_width` would have written for Qwen3.6) differs from the dense reference by 0.65-0.69 relative
|
||||
L1.
|
||||
3. **The oracle's fixtures.** For g8, g12, g2: `Qcur_reshaped-3` and `Kcur-3` through the engine's
|
||||
`rms_norm_weighted` and `rope_neox_apply` (table from `build_rope_table`) against `Qcur-3` and `Kcur-3#2`;
|
||||
the softmax of the engine's q/k (host, double) against `kq_soft_max-3`; the attention over the engine's fp32
|
||||
q/k/v (host, double) against `kqv-3`; then the **fp16 KV through `kv_append_step` and the batched decode kernel
|
||||
with null ids, 40 queries at widths 1..40**, against `kqv-3`; `qsa_gate_apply_f32` on `Qcur_full-3` against
|
||||
`attn_gated-3`. **Negatives, the oracle's controls:** the gate skipped (relative L1 0.995-0.998 at
|
||||
`attn_gated-3`; the oracle's table says 1.03 on its own fixture), RoPE on adjacent pairs from the oracle's
|
||||
normed q/k (0.17-0.20 at `kqv-3`; the oracle: 0.20), the GQA map `h % n_kv` (0.69-0.72; the oracle: 0.74).
|
||||
4. `src/kernels/qsa_attn_bench.cpp` (CTest `qsa_attn_bench`, 2,051 and 8,192 cells at 16 / 2): the kernel's
|
||||
time per call on random pools, explicit ids only, so it builds against the pre-step-3 kernel as well (the
|
||||
"before" column below is that build: `8b7525e`'s `qsa.hpp`, `qsa_decode_attn.{hpp,cu}`, `qsa_prompt_attn.cu`
|
||||
dropped into a copy of this tree).
|
||||
|
||||
Tolerances and what was measured (both cards):
|
||||
|
||||
| check | tolerance | 4090 (sm_89) | 1080 Ti (sm_61) |
|
||||
| --- | --- | --- | --- |
|
||||
| decode kernel vs host reference, dequantized pools, all formats, G 8 / 12 / 2 | 3e-5 rel L2 | 2.0e-7 .. 3.9e-7 | 2.0e-7 .. 3.9e-7 (the `pre75` kernel runs there) |
|
||||
| prompt kernel vs host reference (fp16 / INT8 / Q4_0 / K8V4), G 8 / 12 / 2 | 2e-3 | 4.1e-7 .. 6.3e-7; K8V4 1.6e-4 | the host keeps the decode kernel (cc < 70): skipped |
|
||||
| engine norm + RoPE vs `Qcur-3`, `Kcur-3#2` | 2e-6 | 8.1e-8 .. 9.8e-8 | 8.1e-8 .. 9.8e-8 |
|
||||
| host softmax of the engine's q/k vs `kq_soft_max-3` | 1e-5 | 1.6e-7 .. 1.7e-7 | 1.6e-7 .. 1.7e-7 |
|
||||
| host attention over the engine's fp32 q/k/v vs `kqv-3` | 1e-5 | 1.5e-7 .. 1.7e-7 | 1.5e-7 .. 1.7e-7 |
|
||||
| decode kernel over the **fp16** KV vs `kqv-3`; gated vs `attn_gated-3` | 1.5e-3 | 2.2e-4 .. 2.3e-4 | 2.2e-4 .. 2.3e-4 |
|
||||
|
||||
The 2.2e-4 is the fp16 KV pool (K and V rounded to 11 bits; the oracle's are F32): the same q/k/v in fp32 give
|
||||
1.5e-7, so the kernel's own arithmetic is at the 1e-7 level and the format is the whole gap. The policy's
|
||||
`attn_out` class (`oracle-crosscheck.md`: 1.1e-4 median, 6.7e-4 max for the Q8 oracle, 4x margin) is the right
|
||||
class for it and 1.5e-3 is inside that margin.
|
||||
|
||||
The rest of the attention suite on the branch: `qsa_parity`, `qsa_prompt_attn_parity`, `kv_hybrid_parity`,
|
||||
`kv_stream_parity`, `qsa_topk_parity`, `qsa_topk_active_parity` (the Flash-Next geometry, G = 12: the
|
||||
instantiation Flash-Next keeps). `kv_hybrid_parity`'s case [5/5] now skips below sm_70 instead of failing (the
|
||||
prompt kernel refuses cc < 70 by design and prefill takes the batched decode kernel, which case [4/4] holds to
|
||||
the same reference).
|
||||
|
||||
## 4. The numbers
|
||||
|
||||
`qsa_attn_bench`, one query row, identity selection of `cells` cells, median of the reps, microseconds per call
|
||||
(the chunk kernel plus the merge). "before" is the pre-step-3 kernel (G = 12 only: it refuses 16 heads).
|
||||
|
||||
**RTX 4090 (sm_89), VM 221**, `--reps 200` (24 / 2) and `100` (16 / 2):
|
||||
|
||||
| cells | 24/2 fp16 before -> after | 24/2 INT8 | 24/2 Q4_0 | 16/2 fp16 | 16/2 INT8 | 16/2 Q4_0 |
|
||||
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 2,051 | 32.8 -> 32.7 | 33.8 -> 34.5 | 34.6 -> 34.8 | 29.3 | 29.4 | 30.3 |
|
||||
| 8,192 | 57.2 -> 57.0 | 58.2 -> 57.3 | 59.2 -> 59.2 | 48.0 | 47.4 | 49.2 |
|
||||
| 32,768 | 215.7 -> 148.4 | 205.0 -> 143.2 | 212.6 -> 150.7 | 130.9 | 110.5 | 115.7 |
|
||||
|
||||
(A rerun of the final build: fp16 32.8 / 56.3 / 138.0, Q4_0 34.6 / 58.3 / 147.5 at 2,051 / 8,192 / 32,768; the
|
||||
sm_89 build runs the one looped kernel at every capacity.)
|
||||
| 131,072 | | | | 540.7 | 539.6 | 467.9 |
|
||||
| 262,144 | | | | 1,032 | 1,051 | 1,053 |
|
||||
|
||||
At 2,051 cells on Flash-Next's path the kernel is the same grid and the same arithmetic (33 blocks of one
|
||||
sub-chunk; the test holds the scratch formula equal there) and the time is the same within the run-to-run
|
||||
spread (32.7 vs 32.8 us; INT8 34.5 vs 33.8 is the spread of a 34 us launch, the Q4_0 pair is 34.8 vs 34.6). Above
|
||||
8,192 the bounded grid is faster (fewer, longer blocks: 148 vs 216 us at 32,768) and the scratch stays at 2.0 /
|
||||
3.0 MiB instead of 12. At 262,144 cells, 16 heads, one row costs 1.03 ms on the 4090 whatever the format: the
|
||||
fp16 pool streams at 520 GB/s and the quantized pools are bound by the dequantization in the value loop, not by
|
||||
bytes (INT8 263 GB/s, Q4_0 143 GB/s over fewer bytes, the same time). Ten attention layers at 256K are therefore
|
||||
about 10 ms of a token on this card.
|
||||
|
||||
**GTX 1080 Ti (sm_61), VM 211** (the `attn_chunk_kernel_pre75` path of `STRATA_EXPERIMENTAL_SM60`), `--reps 100`
|
||||
(24 / 2) and `50` (16 / 2):
|
||||
|
||||
| cells | 24/2 fp16 before -> after | 24/2 INT8 | 24/2 Q4_0 | 16/2 fp16 | 16/2 INT8 | 16/2 Q4_0 |
|
||||
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 2,051 | 41.0-42.0 -> 41.0-41.9 | 38.9 -> 38.9-39.9 | 41.0-42.0 -> 41.0 | 43.0 | 33.8 | 34.8 |
|
||||
| 8,192 | 141.3-142.3 -> 140.3-141.3 | 141.3 -> 140.3-141.3 | 146.4-147.5 -> 143.4-144.4 | 140.4 | 121.9 | 135.2 |
|
||||
| 32,768 | 493.6-494.6 -> 494.4-494.6 | 496.6 -> 496.6-497.4 | 505.9-506.9 -> 497.6-497.7 | 378.9 | 330.8 | 373.8 |
|
||||
| 131,072 | | | | 1,290 | 1,126 | 1,287 |
|
||||
| 262,144 | | | | 2,354 | 2,117 | 2,605 |
|
||||
|
||||
The before / after pairs are interleaved A/B runs (rounds 2 and 3 of three; round 1 is the warm-up). The 24/2
|
||||
shape is sparse, so after e7c9c8d both sides are the same grid (one block per 64 cells at every capacity, the
|
||||
same 12.09 MiB scratch at 32,768) and the same single-chunk kernel body: the pairs agree within the 1 us
|
||||
run-to-run spread at every capacity and format, which is the drafter's case (its ring at 32,768) as much as the
|
||||
QSA layers' (2,051). The 16/2 columns are the dense model's states (cap >= 131,072 in practice), which take the
|
||||
looped kernel on Pascal: on Q4_0 it is 10-15% slower than the single-chunk body would be at short depths (the
|
||||
looped body's extra registers cost the Q4_0 value loop a block per SM; a `__launch_bounds__(THREADS, 4)` cap
|
||||
spilled and made every format slower, 44.0 / 44.0 / 47.1 us at 2,051 in that build), about 0.15 ms of a token
|
||||
at 8K depth, which the A2 floor cannot see; at long depths it is ahead of the unbounded grid (465 vs 504 us at
|
||||
32,768 in the 24/2 trial that measured the looped kernel on a sparse shape).
|
||||
|
||||
At 262,144 cells, 16 heads, one row is 2.1 ms INT8 / 2.4 ms fp16 / 2.6 ms Q4_0 on the 1080 Ti: 21-26 ms of a
|
||||
token for the ten attention layers at the full context (the fp16 pool streams at 228 GB/s of the card's 484;
|
||||
Q4_0 is bound by the nibble decode in the value loop at 58 GB/s over a quarter of the bytes). At 8K depth the ten
|
||||
layers are 1.2-1.4 ms. The verify window multiplies the per-row figure by its rows (8), so the window's attention
|
||||
at 256K is about 17-21 ms on this card; A2's 10 tok/s at 32K depth leaves 100 ms per token, of which the
|
||||
attention is 3.3-3.8 ms.
|
||||
|
||||
## 5. Commands
|
||||
|
||||
4090 (`/models/work/qwen36-step3-attn`, `build-step3-attn.sh` = the configure of `step3-common.md` with
|
||||
`-DCMAKE_CUDA_ARCHITECTURES=89`, 162 s for the full tree):
|
||||
|
||||
export STRATA_GGUF_PY=/models/work/qwen36-step3-attn/third_party/llama.cpp/gguf-py
|
||||
cd build && ctest --output-on-failure -R "qwen36_attn_fixtures|qsa_dense_parity|qsa_parity|qsa_prompt_attn_parity|kv_hybrid_parity|kv_stream_parity|qsa_topk"
|
||||
./qsa_dense_parity --fixtures qwen36_attn
|
||||
for kv in fp16 int8 q4_0; do ./qsa_attn_bench --heads 24,2 --kv $kv --cells 2051,8192,32768 --reps 200; done
|
||||
for kv in fp16 int8 q4_0; do ./qsa_attn_bench --heads 16,2 --kv $kv --cells 2051,8192,32768,131072,262144 --reps 100; done
|
||||
# the "before" column: the same bench built in a copy of the tree with 8b7525e's four attention files
|
||||
/models/work/qwen36-step3-attn-base/build/qsa_attn_bench --heads 24,2 --kv fp16 --cells 2051,8192,32768 --reps 200
|
||||
|
||||
1080 Ti (`/home/rk/qwen36-step3-attn`, `-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`, under
|
||||
`/home/rk/VM-BUSY`): the same, by `/home/rk/pascal-run-attn.sh` (logs in `/home/rk/logs/qwen36-step3-attn-*.log`).
|
||||
|
||||
## 6. Not done, surprises, and where the study was off
|
||||
|
||||
- `generate.cpp` is not edited (the step-2 branch owns it): the `--kv-resident` refusal for a dense model is a
|
||||
predicate (`qsa_kv_streaming_applies`) plus the backstop in `qsa_state_init`; the integrator adds the one call.
|
||||
- `prefill.cpp` is not edited (the prefill agent's): its three sites take `qsa_selection_cap`, a null `sel_ids`
|
||||
for the dense model, and `attn_scratch` at the new bound (section 1).
|
||||
- The Volta (`launch70`, m8n8k4) and Turing prompt kernels are templated on G but no such card was on hand; the
|
||||
4090 runs `launch_i8` / `launch<>`, Pascal runs none of them. Flash-Next's G = 12 on those paths is unchanged
|
||||
code apart from the template parameter.
|
||||
- No test drives `Verifier` (the verify window) on a `qwen35moe` geometry yet; its attention step is checked by inspection and by the builder test above. That is step 4's streaming-runner test (the window against the oracle's `l_out-N` per position).
|
||||
- `layer_verify_compatible` still demands the native QSA indexer flag for the verify window; it is a global
|
||||
(on by default) and not a geometry question, so it is left for the block agent's verify rewrite.
|
||||
- Pascal's looped kernel is 10-15% slower than the single-chunk one on the Q4_0 pool at short depths (section 4);
|
||||
the single-chunk body is kept for capacities under 8,192 so Flash-Next's path is untouched, and the dense model
|
||||
pays it only below about 8K of depth, where the attention is a small part of the token.
|
||||
- The study's 3.3 item 5 sizes the scratch "(cap/64) x n_head x 258 + 64 ... 64.5 MiB per query row": right.
|
||||
Its proposed fixes were "a larger chunk per block, or an online-softmax merge that does not keep a partial per
|
||||
64-cell chunk": the kernel does the second inside the block (the running rescale) while keeping the 64-cell
|
||||
sub-chunk as the unit of work, so the short-context grid and arithmetic are untouched. The bound came out at
|
||||
2.02 MiB, not the 2 MiB-per-row-at-128-chunks guess rounded either way: 528,448 floats.
|
||||
- Item 4 says the drafter's ring passes "pooled_rows = 2"; what makes the dense state small is `idx_dim = 0`
|
||||
(the tail and the dead key are sized by it too), the 2 rows alone would still have carved `3 x 128 x 4 + 128 x 4
|
||||
+ 2 x 128 x 4` bytes. Both are in place.
|
||||
- Nothing in the study mentions `qsa.cu`'s geometry guard (`validate`: `idx_dim <= 0 || idx_n_head <= 0` is
|
||||
"geometry is not set up", and `n_rot > idx_dim` is refused): every KV append would have exited on the dense
|
||||
shape. The guard now distinguishes a dense shape (all three indexer widths 0) from a half-set-up one.
|
||||
- The oracle's negative controls reproduce on the head_dim-256 fixtures at the same order (gate 1.0, adjacent
|
||||
RoPE 0.17-0.20, GQA map 0.69-0.72); the oracle's own table was on its head_dim-32 fixture.
|
||||
@@ -1,202 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 3: the block without hyper-connections
|
||||
|
||||
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step3-block`, from `qwen36-step2` at 8b7525e).
|
||||
The design is `docs/QWEN36-35B-A3B.md` section 3.5 and section 6 (step 3, fourth bullet); the plan is
|
||||
`docs/PLAN-qwen36-35b-a3b.md` section 5 step 3. Every item says what was decided, where it lives, how it is
|
||||
checked, and the numbers from both cards.
|
||||
|
||||
## 1. What changed, in one paragraph
|
||||
|
||||
`ModelGeometry::hc == 1` (set by the `qwen35moe` architecture string in step 2) now selects a second block path:
|
||||
llama.cpp's plain pre-norm residual block, in the single-token functions (`block_layer_pre`, `block_layer_post`,
|
||||
`lm_head_mix`) and in the verify window (`Verifier::record_window`'s `pre`, `post` and head), through two row-count
|
||||
helpers that the single-token path calls with one row and the window with its T rows. The hyper-connection kernels
|
||||
are never entered for this model: the GR read on one stream is not a plain norm (its bottleneck gates the normed
|
||||
stream with a sigmoid and its norm weight is stored as `1 + w`), which the harness shows as a negative case. The
|
||||
Flash-Next path (`hc = 4`) is untouched: every `hc == 1` test is a branch in front of the existing code, no GR
|
||||
call site moved, and the no-geometry `layer_verify_compatible` keeps its Flash-Next meaning.
|
||||
|
||||
x = rms_norm(R) * attn_norm -> mixer (GDN | attention) -> R += out
|
||||
x = rms_norm(R) * post_attention_norm -> MoE (routed top-k, normalised, + shared expert) -> R += out
|
||||
head: rms_norm(R) * output_norm -> output.weight
|
||||
|
||||
## 2. Decisions
|
||||
|
||||
| Decision | Where | Why |
|
||||
| --- | --- | --- |
|
||||
| Two helpers, `plain_norm_rows(R, w, mixed, n_embd, eps, n_tok, stream)` and `plain_residual_rows(R, block_out, n_embd, n_tok, stream)`, take a ROW COUNT | `include/strata/core/layer.hpp` ("the plain block"), `src/core/layer.cpp` | the single-token path (1 row) and the verify window (T rows) call the same kernels, so the window's row arithmetic equals the single-token path by construction; the harness asserts it bitwise |
|
||||
| The norm is `native_qsa_rms_norm_weighted` (one block per row, fixed reduction order, `rsqrtf`, `(scale * x) * gamma`); the add is `add_inplace` | `layer.cpp` | the engine's pinned-arithmetic norm kernel, already used on q/k and in the drafter; ggml's `rms_norm` then `mul` in that order |
|
||||
| No pending write at hc = 1: `R += out` is applied where the reference adds it (stage 2 and `post`), never folded into the next read | `layer.cpp` (`plain_block_pre` / `plain_block_post`), `verify.cpp` | the fold exists to fuse the GR write into the GR read; with no GR there is nothing to fuse, and an in-place add keeps `R` materialised for the control vector, the hand-off and the head |
|
||||
| The stages and the `half` / `stage_prefix` selection are the GR path's (0 read, 1 mixer, 2 write, 3 read, 4 route) | `plain_block_pre` | `session_replay_stages`, the per-stage timing and the measurement splits apply unchanged; the harness drives stage 0 and half 2 separately |
|
||||
| The norm weights are read as `const float*` after a form check (F32, `n_embd` elements) | `plain_norm_weight` in `layer.cpp`, `plain_w` in `verify.cpp`, `lm_head_mix` | Qwen3.6's norms are F32 in the file and the pack keeps them F32; a BF16 row read as f32 walks 2x the tensor inside the arena and yields a finite wrong norm (the `layout.cpp` failure) |
|
||||
| `check_one` skips the `hc_*` rows at hc = 1 and requires `attn_norm` / `post_attention_norm` (F32, `n_embd`) instead; at hc > 1 the two plain names are skipped | `src/core/layout.cpp` | row 22 of the inventory; the indexer rows are the attention branch's |
|
||||
| `layer_verify_compatible(const ModelGeometry&, std::string&)`: at hc = 1 the fused GR read is not required; without an indexer the block selection and the native indexer are not required | `layer.cpp`, `layer.hpp` | the window's compatibility check named kernels this model has no use for; the no-argument form stays Flash-Next's |
|
||||
| `verify_geometry_supported(g, k, why)` replaces the window's `ss.k == 10` refusal: `k == g.n_expert_used` (8 from the file), the fused GR shape only at hc > 1, state 128 / conv 4 | `include/strata/core/verify.hpp`, `verify.cpp` | row 142; a free function so the negative case (top-10 on an 8-expert file) is a unit test and the message names both numbers |
|
||||
| The window's head at hc = 1: `output_norm` over the T rows in one launch when the native head is loaded; the canonical head goes through `lm_head`, which branches the same way | `verify.cpp` (`record_window`, the head block) | the per-row arithmetic is the single-token `lm_head_mix`'s |
|
||||
| A PLE run with hc = 1 is refused (`block_layer_pre`, `record_window`) | `layer.cpp`, `verify.cpp` | the model has no PLE (`has_ple = false`); a wired one would be a different model |
|
||||
| `session_zero`'s first token needs no change | `src/core/session.cpp:141-148` | the loop is over `g.hc` (row 26): one copy at hc = 1 |
|
||||
| `broadcast_streams` / `add_streams_broadcast` need no change | `src/kernels/cuda/verify_kernels.cu:256-291` | runtime `hc` (row 140): the identity copy at hc = 1 |
|
||||
|
||||
## 3. The harness: `tests/cuda/qwen36_block_test.cpp`
|
||||
|
||||
Maya's layer composition shape on the synthetic fixture (`tools/qwen36_synth_gguf.py`: hidden 64, layers 0-2 GDN,
|
||||
layer 3 attention, 8 experts top-2, F32 everywhere) against the oracle's dumps of 8 tokens
|
||||
(`cmake/qwen36_block_fixtures.cmake` runs `ref/qwen36.py --dump`; the fixture test `qwen36_block_fixtures` depends on
|
||||
step 2's `qwen36_synth_fixtures`). CTest: `qwen36_block_test` (exit 77: no CUDA device or no numpy).
|
||||
|
||||
**Through the engine's own functions.** The test writes a pack (index.txt + dense.bin) holding, per layer, the two
|
||||
norms (F32, index kind 2), the router `ffn_gate_inp` (BF16, kind 4, the engine's contract) and the shared expert's
|
||||
scalar gate, plus `output_norm`; `WeightTable::load` reads it like any pack. Then, per layer and token, with the
|
||||
mixer's output and the experts' outputs TEACHER-FORCED from the dumps:
|
||||
|
||||
| seam | engine call | tolerance (relative L2) |
|
||||
| --- | --- | --- |
|
||||
| `attn_norm-N` | `block_layer_pre(..., stage_prefix = 1)` on `R = l_out-(N-1)` (`model.input_embed` at N = 0) | 1e-6 |
|
||||
| `attn_residual-N` | `plain_residual_rows` with `block_out = linear_attn_out-N` (GDN) or `attn_output-N` (attention) | 1e-6 |
|
||||
| `attn_post_norm-N` | `block_layer_pre(..., half = 2)` on `R = attn_residual-N` (shared expert off: its weights are not in the pack) | 1e-6 |
|
||||
| `ffn_moe_topk-N`, `ffn_moe_weights_norm-N` | the same call's router (`moe_route`: BF16 weight, F32 activations, `router_top10` at 8 / 2) | picks identical; weights 1e-2 reported |
|
||||
| `ffn_out-N`, `l_out-N` | `block_layer_post` with `parts = ffn_moe_down-N`, `weights = ffn_moe_weights_norm-N`, `shared = ffn_shexp_gated-N` | 1e-6 |
|
||||
| `result_norm` | `lm_head_mix` on `R = l_out-3[last]` | 1e-6 |
|
||||
| `result_output` | the engine's `result_norm` through a host F32 projection of `output.weight` | 1e-5 |
|
||||
|
||||
**The window.** `plain_norm_rows` and `plain_residual_rows` over the 8 rows against the one-row calls per row
|
||||
(bitwise, `memcmp`), `native_moe_combine_multi` against `native_moe_combine` per row (bitwise), and the 8-token
|
||||
sequence carried through the four layers from the embeddings (`R` is never reloaded from the dumps) against
|
||||
`attn_norm-N`, `attn_residual-N`, `attn_post_norm-N`, `ffn_out-N`, `l_out-N` at every position, then `h_nextn`
|
||||
(every row) and `result_norm` (row 7), all at 1e-6.
|
||||
|
||||
**Negative cases** (each must differ from the oracle by more than 5 % relative L1): the GR read at hc = 1 with
|
||||
identity bottleneck weights (`GrShapes{64, 1, 64}`, `w_down = w_up = I`, `w_norm = attn_norm`) against
|
||||
`attn_norm-0`; the post-attention norm skipped (`attn_residual-0` as the MoE input) and unweighted; top-10 on the
|
||||
8-expert file refused by `verify_geometry_supported` with both numbers in the message; a layer whose `attn_norm`
|
||||
is not in the pack refused by name; `layer_verify_compatible` at hc = 1 passing without the fused GR read while
|
||||
the Flash-Next geometry still demands it.
|
||||
|
||||
**The mixers are reported, not asserted.** The fixture's projections are F32 and the engine has no F32 projection
|
||||
kernel (the mixers take quantized planes or native GGUF types), so `block_layer_pre(..., stage_prefix = 2)` is
|
||||
attempted and its own error printed (`blk.N.attn_qkv.weight is missing`; the attention layer's RoPE table of 0 rows).
|
||||
The mixer seams (`conv_output_silu-N`, `new_state-N`, `final_output-N`, `linear_attn_out-N`; `kq_soft_max-3`,
|
||||
`kqv-3`, `attn_gated-3`, `attn_output-3`) wait on the GDN and attention branches and on step 4's pack, which is
|
||||
where the engine first runs a Qwen3.6 mixer end to end.
|
||||
|
||||
**Why 1e-6 and not the policy's 5e-8.** `oracle-crosscheck.md`'s norm figure is numpy F32 against numpy F32 on a
|
||||
forced input; the CUDA norm uses `rsqrtf` (2 ulp, 2.4e-7) under `--use_fast_math`, so one CUDA ulp is above that
|
||||
figure. The measured numbers are below.
|
||||
|
||||
## 4. Build and test commands
|
||||
|
||||
On VM 221 (the 4090, sm_89; the working copy is synced with the worktree's empty `third_party/llama.cpp` excluded
|
||||
and the pinned submodule copied from the step-2 tree):
|
||||
|
||||
rsync -a --delete --exclude .git --exclude '/build/' --exclude '/build-mac/' --exclude '/logs/' \
|
||||
--exclude '/third_party/llama.cpp/' ~/Code/UnbiasedStrata-step3-block/ rk@192.168.50.151:/models/work/qwen36-step3-block/
|
||||
/models/work/build-step3-block.sh configure # the common file's configure line, logged
|
||||
/models/work/build-step3-block.sh target qwen36_block_test
|
||||
/models/work/build-step3-block.sh ctest 'qwen36'
|
||||
/models/work/build-step3-block.sh all # everything else still builds (the gate binary links the engine)
|
||||
|
||||
On VM 211 (the 1080 Ti, sm_61) under the `/home/rk/VM-BUSY` lock, the same with `-DSTRATA_EXPERIMENTAL_SM60=ON
|
||||
-DCMAKE_CUDA_ARCHITECTURES=61` and the working copy in `/home/rk/qwen36-step3-block/`.
|
||||
|
||||
## 5. Results
|
||||
|
||||
### VM 221, the RTX 4090 (sm_89), 2026-10-11
|
||||
|
||||
`./build/qwen36_block_test build/qwen36_synth build/qwen36_block/o8` (the fixtures written by hand, below), all 30
|
||||
checks pass:
|
||||
|
||||
| seam (single-token path through the engine) | measured, worst over 4 layers x 8 tokens | tolerance |
|
||||
| --- | ---: | ---: |
|
||||
| `attn_norm-N` (`block_layer_pre` stage 0) | 1.13e-7 | 1e-6 |
|
||||
| `attn_residual-N` | 0.0 | 1e-6 |
|
||||
| `attn_post_norm-N` (`block_layer_pre` half 2) | 1.23e-7 | 1e-6 |
|
||||
| `ffn_moe_topk-N` (the BF16 router) | 0 of 64 slots differ | identical |
|
||||
| `ffn_moe_weights_norm-N` (the BF16 router) | 9.82e-3 | 1e-2, reported |
|
||||
| `ffn_out-N` (`block_layer_post`) | 7.02e-8 | 1e-6 |
|
||||
| `l_out-N` (`block_layer_post`) | 4.82e-8 | 1e-6 |
|
||||
| `result_norm` (`lm_head_mix`) | 0.0 | 1e-6 |
|
||||
| `result_output` (host projection of the engine's `result_norm`) | 1.63e-7 | 1e-5 |
|
||||
|
||||
| the window (8 rows) | measured | tolerance |
|
||||
| --- | ---: | ---: |
|
||||
| `plain_norm_rows`, `plain_residual_rows`, `native_moe_combine_multi` against the one-row calls | bitwise | bitwise |
|
||||
| `attn_norm-N` / `attn_residual-N` / `attn_post_norm-N` / `ffn_out-N` | 6.98e-8 / 2.61e-8 / 7.78e-8 / 2.52e-8 | 1e-6 |
|
||||
| `l_out-N` per position, `R` carried from the embeddings (layers 0..3) | 1.99e-8 / 2.22e-8 / 2.65e-8 / 2.81e-8 | 1e-6 |
|
||||
| `h_nextn` (all rows) / `result_norm` (row 7) | 4.75e-8 / 3.25e-8 | 1e-6 |
|
||||
|
||||
| negative case | relative L1 against the oracle | required |
|
||||
| --- | ---: | ---: |
|
||||
| the GR read at hc = 1, identity bottleneck, against `attn_norm-0` | 0.423 | > 0.05 |
|
||||
| the post-attention norm skipped | 0.276 | > 0.05 |
|
||||
| the post-attention norm without its weight | 0.180 | > 0.05 |
|
||||
| top-10 on the 8-expert file | refused: "the session routes top-10 but the file routes top-2 of 8 experts" | refused by name |
|
||||
| the fixture's GDN state 16 | refused: "the T-token GDN kernels are built for state 128 and conv 4" | refused by name |
|
||||
| `blk.4.attn_norm.weight` absent | refused by name | refused by name |
|
||||
|
||||
The mixer seams, reported: layers 0-2 `blk.N.attn_qkv.weight is missing`, layer 3 `qsa_layer: position 0 is
|
||||
outside the RoPE table (0 rows)` (no attention state is built for a mixer that cannot run on F32 weights).
|
||||
|
||||
The 9.8e-3 on the router's renormalised weights is the BF16 contract on an F32 weight (2^-9 per element over a
|
||||
64-long dot product); the picks are identical on this fixture, whose logits are spread for that purpose. The
|
||||
real file's flip rate is the router branch's measurement (study 3.4).
|
||||
|
||||
**Two things found on the way.** (1) `cmake/qwen36_synth_fixtures.cmake` (step 2's) fails on this cmake 3.28
|
||||
under policy CMP0007 (`list(GET)` on `"toy.gguf;"` with its empty flag element), so `ctest -R qwen36` cannot
|
||||
reach `qwen36_block_test` until the step-2 branch fixes it; the fixtures were written by hand
|
||||
(`python3 -I tools/qwen36_synth_gguf.py build/qwen36_synth/toy.gguf`, then the block fixture script with `-P`)
|
||||
and the test run directly. (2) `read_model_geometry` leaves `n_vocab` at the Flash-Next default (248,320) on the
|
||||
synthetic file; the engine takes the vocabulary from `output.weight`'s `ne1` (verify.cpp, mtp.cpp), and so does
|
||||
the test, but a reader of `ModelGeometry::n_vocab` should know it is not the file's.
|
||||
|
||||
### VM 211, the GTX 1080 Ti (sm_61, Pascal), 2026-10-11, under `/home/rk/VM-BUSY`
|
||||
|
||||
The same tree (`/home/rk/qwen36-step3-block/`, the submodule copied from the step-2 tree), configured with
|
||||
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`, `cmake --build build -j 8 --target qwen36_block_test`
|
||||
(the engine library and the kernels compile for sm_61), the fixtures by hand as above, then
|
||||
`./build/qwen36_block_test build/qwen36_synth build/qwen36_block/o8`: all 30 checks pass with **the same numbers as
|
||||
the 4090 to the printed digit** (1.13e-7, 1.23e-7, 7.02e-8, 4.82e-8, 1.63e-7, 9.82e-3; the window's 1.99e-8 ..
|
||||
2.81e-8; the negatives 0.423 / 0.276 / 0.180; the router's 64 picks identical). The kernels the plain block adds
|
||||
to the path are a block-per-row reduction and an elementwise add: nothing Pascal lacks. The lock was held for
|
||||
the sync, the build, the run and released (about 12 minutes).
|
||||
|
||||
## 6. The hunks, for the integrator (against 8b7525e)
|
||||
|
||||
| file | hunks (old -> new line ranges) | what |
|
||||
| --- | --- | --- |
|
||||
| `include/strata/core/layer.hpp` | 479,8 -> 479,35 | `layer_verify_compatible(g, why)`, the plain-block section, `plain_norm_rows`, `plain_residual_rows` |
|
||||
| `src/core/layer.cpp` | 473,17 -> 473,22 | `layer_verify_compatible` with the geometry; the no-argument form calls it with the defaults |
|
||||
| | 1087,6 -> 1092,20 | `lm_head_mix`: the `hc == 1` branch (`output_norm`) in front of the GR mix |
|
||||
| | 1167,7 -> 1186,115 | the two helpers, `plain_norm_weight`, `plain_block_pre`, `plain_block_post`; `block_layer_pre` dispatches on `g.hc == 1` as its first statement |
|
||||
| | 1316,7 -> 1443,9 | `block_layer_post` dispatches on `g.hc == 1` as its first statement |
|
||||
| `src/core/layout.cpp` ([shared]) | 2,6 -> 2,7; 81,6 -> 82,9; 96,6 -> 100,10; 108,6 -> 116,10 | `<cstring>`; the `hc_*` 2-D rows skipped at hc = 1; the two plain norms in the 1-D table, skipped at hc > 1 |
|
||||
| `include/strata/core/verify.hpp` | 42,6 -> 42,13 | `verify_geometry_supported` |
|
||||
| `src/core/verify.cpp` | 125,6 -> 125,30 | `verify_geometry_supported` (after the first anonymous namespace) |
|
||||
| | 329,13 -> 353,12 | `init`: the two refusals |
|
||||
| | 557,7 -> 580,23 | `record_window`: the PLE refusal, `eps`, `plain_w` |
|
||||
| | 622,7 -> 661,14; 631,8 -> 677,8 | `pre`: the `hc_*` lookups only at hc > 1, `pending` only at hc > 1 |
|
||||
| | 693,9 -> 739,16 | `pre`: the first read (`attn_norm` or the GR read) |
|
||||
| | 899,7 -> 952,15 | `pre`: the residual add and `post_attention_norm`, or the second GR read |
|
||||
| | 998,7 -> 1059,7 | `fuse_head_gr` only at hc > 1 |
|
||||
| | 1091,7 -> 1152,15 | `post`: the plain write, else the last-layer materialisation |
|
||||
| | 1120,10 -> 1189,24 | the head: `output_hc_*` only at hc > 1; the plain head over the T rows |
|
||||
| `CMakeLists.txt` | 490,6 -> 490,22 | `qwen36_block_test`, `qwen36_block_fixtures` |
|
||||
| new | `tests/cuda/qwen36_block_test.cpp`, `cmake/qwen36_block_fixtures.cmake`, this file | |
|
||||
|
||||
The attention branch's regions (`qsa_layer` ~945-975 at the base, the window's attention step ~757-870, the state
|
||||
carve) and the GDN branch's (the decode GDN kernels, their launch sites) are not touched: the plain block calls
|
||||
`qsa_layer` / `gdn_layer` through their existing entry points, and the window's mixer steps are left as they are
|
||||
between my two hunks at 739 and 952.
|
||||
|
||||
## 7. What waits on the sibling branches and step 4
|
||||
|
||||
- The mixer seams (section 3) and `block_layer_pre` stage 1 on this model: the GDN gate (sigmoid today, SiLU on the
|
||||
GDN branch) and the dense attention (the indexer still runs in `qsa_layer`; the attention branch removes it).
|
||||
The window's attention step still builds the indexer's selection and `max_blocks_` from `idx_block` and demands
|
||||
the `indexer.*` tensors; that is the attention branch's hunk in `record_window` and in `layer_verify_compatible`'s
|
||||
`has_indexer()` conditions are already in place for it.
|
||||
- The real-file run of the window (the engine's first Qwen3.6 token) needs step 4's pack: the native projections,
|
||||
the F32 norms kept F32 (`attn_norm`, `post_attention_norm`, `output_norm` as index kind 2), the router and the
|
||||
shexp gate as BF16, and the `qwen35moe_not_yet` gate in `generate.cpp` lifted.
|
||||
- `check_one`'s indexer rows (`indexer.q_proj`, `indexer.k_proj`, `indexer.*_norm`) are still required on attention
|
||||
layers at hc = 1; the attention branch owns them.
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 3, experts: the native GPU expert kernels' format coverage
|
||||
|
||||
Working notes (2026-10-11, branch `qwen36-step3-experts`, from `qwen36-step2` at 8b7525e). The gap: the study's
|
||||
section 3.7 called the native pack path "otherwise runtime", but `native_expert_supported()` refused every layer of
|
||||
both real files because the DOWN-projection list `STRATA_D_FMTS` (`src/kernels/cuda/iq_kernels.cu`) held only the
|
||||
types Flash-Next's and the Coder's packs use (IQ4_NL, IQ4_XS, Q2_0, Q5_1, Q5_0, Q8_0). Qwen3.6's files put IQ3_XXS
|
||||
(37 layers) and IQ4_XS (34, 38, 39) on `ffn_down_exps` in UD-IQ3_XXS, and Q5_K (37) and Q6_K (34, 38, 39) in
|
||||
UD-Q4_K_XL, whose layer 39 gate/up is Q5_K (`tests/data/native_experts/qwen36-{iq3_xxs,q4_k_xl}.txt`, step2-notes.md
|
||||
section 3). The engine's refusal at `generate.cpp:2100` named the pair; it still does for anything not below.
|
||||
|
||||
## 1. What changed, and why it was small
|
||||
|
||||
| Decision | Where | Why |
|
||||
| --- | --- | --- |
|
||||
| IQ3_XXS (18) and Q5_K (13) join `STRATA_D_FMTS` | `iq_kernels.cu`, the three `STRATA_*_FMTS` lists | `native_down_kernel<TD>` and `native_down_multi_kernel<TD>` were already generic in `Fmt<TD>` (one row per warp, `row_dot<TD>` lane-strided over the row's dot calls); the list was the only restriction. The 256-value block types need `n_ff % 256 == 0`, which `native_expert_supported` already demanded: Qwen3.6's 512 passes, Flash-Next's 640 is refused as before (`native_grouped_parity.cpp` had noted "IQ4_XS: n_ff % 256") |
|
||||
| Q6_K (14): `vec_dot_q6_K_q8_1` and `dq_q6_k` transcribed from llama.cpp (`vecdotq.cuh`, `dequantize.cuh` at the pinned commit), `Fmt<14>` with `VDR_Q6_K = 1` (`ipb = QI6_K / 1 = 32`, `step = 1`), on all three lists, in `is_iq` and `iq_row_bytes` (210 B per block) | `iq_kernels.cu` (the K-quant section after Q5_K, the dequant section after `dq_q5_k`) | 16 int8 sub-scales per block, the value `(ql | qh << 4) - 32` by `__vsubss4`, no min term, `__dp4a` only: native on sm_61, nothing Pascal lacks. The HIP shim already defines `__vsubss4`. Q6_K takes the per-entry kernels (no `Split<14>`), as Q4_K / Q5_K do |
|
||||
| `native_expert_supported` unchanged | | its block-divisibility rule was right; only the type tables were short |
|
||||
| Q6_K in the MMQ prompt path under `STRATA_MMQ_KQUANTS` | `src/prefill/moe_mmq.cu`, the CMake instance list (`[shared]` commit 52b5dcd) | llama.cpp ships `mmq-instance-q6_k.cu`; the Q4_K_XL file's three Q6_K layers then take the int8 tiles rather than the fp16 GEMM over dequantized weights. The option defaults OFF: the step-5 build must turn it on for the Q4_K_XL file |
|
||||
|
||||
Not changed: `moe_fused_iq.cu` (the sm_80+ fused native prompt experts: gate/up IQ2_XXS..IQ4_XS, down Q2_0 / IQ4_NL
|
||||
only; the new types need a load stage of their own and its geometry is the prefill agent's), the CPU native path
|
||||
(`native_fmt` is ggml-generic and takes Q6_K through ggml-cpu's `vec_dot`; `kq256_supported` keeps its Q4_K / Q5_1 /
|
||||
Q8_0 AVX-2 kernels, Q5_K and Q6_K rows go to ggml's), `generate.cpp`.
|
||||
|
||||
## 2. Interface other agents consume
|
||||
|
||||
- `bool strata::kernels::native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff)`: true for
|
||||
every (gate/up, down) pair of both files at 2048 x 512: (22, 18), (22, 23), (12, 13), (12, 14), (13, 14). Gate/up
|
||||
types: 16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 14, 6, 8; down types: 20, 23, 42, 7, 6, 8, 18, 13, 14, the 256-value
|
||||
ones only where `n_ff % 256 == 0`.
|
||||
- `native_expert_grouped(...)`, `native_expert_layout(...)`, `native_expert_scratch_bytes(...)`,
|
||||
`iq_dequant_f16 / _f32 / _gu_f16`, `iq_embed_rows`, `iq_mmvq`: signatures unchanged; type 14 accepted everywhere
|
||||
`is_iq` gates.
|
||||
- `strata::prefill::mmq::supported(14)`: true when the build has `STRATA_MMQ_KQUANTS=ON`, as for 12, 13, 7.
|
||||
- `native_expert_parity [--geom HxFF] ...`: the geometry flag; `native_grouped_parity --bench-down`.
|
||||
|
||||
## 3. How it is checked
|
||||
|
||||
`src/kernels/native_expert_parity.cpp` (a CTest per pair): (a) the float reference is ggml's own `to_float` of the
|
||||
blob (the dequantization `oracle-crosscheck.md` cross-checked bit for bit against `ref/load.py` on the real file)
|
||||
times a double-precision SwiGLU expert on 3 random tokens; (b) the CPU path (ggml-cpu `vec_dot`, Q8_K activations);
|
||||
(c) the GPU path (`native_expert_grouped`, q8_1 activations), once per kernel family (decode-once vs per-entry, bitwise);
|
||||
(d) the GPU dequantizers against `to_float`; (e) the negative control. Tolerances (relative L1): GPU against (a)
|
||||
2e-2, the Q8-activation bound of `oracle-crosscheck.md` "Tolerance policy" (the Q8 oracle's `ffn_moe_out` max 5.3e-3
|
||||
with the 4x margin), 3e-2 only for a pair with a Q5_0 role (32-value blocks without a min: q4_K/q5_0 measures 2.7e-2
|
||||
at 2560 x 640, the pre-existing pair the CMake note describes); CPU against (a) 3e-2 (ggml-cpu rounds the activations
|
||||
to Q8_K, one scale per 256 values, against the GPU's q8_1 per 32: measured up to 2.2e-2); CPU against GPU 4e-2 (both
|
||||
roundings, measured up to 2.4e-2). Qwen3.6's five pairs measure 9.7e-3 to 1.3e-2 on the GPU (section 4).
|
||||
|
||||
The negative control (e), per the brief and `upstream-tooling.md` section 3: the high byte of one block's fp16 scale
|
||||
(its sign) flipped in down row 5 must move that row's GPU output by more than the gate and no other row by any bit
|
||||
(row locality: a flipped byte in row r's block reaches only row r); the same in gate row 3 must move the output by
|
||||
more than 1e-4 (one of n_ff SwiGLU terms). The gate is 1e-2 for a 256-value block of a 512-wide row (Qwen3.6's down
|
||||
types) and scales with the block's share of the row for the others (`1e-2 x qk/256 x 512/n_ff`: 1e-3 for a 32-value
|
||||
block at Flash-Next's 640, where one of 20 blocks moved the row by 8e-3 to 1.4e-2 on the 4090). The Q6_K scale sits
|
||||
at the block's last two bytes (`ggml_type_size(Q6_K) - 2`), the others at byte 0.
|
||||
|
||||
`src/kernels/native_grouped_parity.cpp`: every gate/up format with every down format at 512 x 256 (96 pairs, the
|
||||
grid-stride launches bitwise equal to v1's over 84 call shapes each), the five Qwen3.6 pairs at 2048 x 512, plus
|
||||
`--bench-down`. `src/kernels/iq_multi_parity.cpp`: the IQ3_XXS down pair at 1024 x 512 (decode-once vs per-column,
|
||||
bitwise). `tests/cuda/prefill_mmq_kquant_test.cpp`: Q5_K and Q6_K down products at 2048 x 512 through MMQ against a
|
||||
double-precision product of ggml's dequantized weights (its screen: rel L2 < 0.04).
|
||||
|
||||
Real file: `native_expert_parity --geom 2048x512 <file> 0 34 39` takes expert 7 of `blk.{0,34,39}` straight from the
|
||||
GGUF (the three tensor slices into one blob) through (a) to (e). Layers 0 and 39 are the brief's; 34 adds the third
|
||||
pair of each file.
|
||||
|
||||
## 4. Results, RTX 4090 (VM 221, sm_89, CUDA 12.4, gcc-13, `-DSTRATA_MMQ_KQUANTS=ON`)
|
||||
|
||||
Build: `/models/work/build-step3-experts.sh configure` then `targets` (116 s for the five test targets).
|
||||
|
||||
cd /models/work/qwen36-step3-experts/build
|
||||
ctest -R "native_expert_parity|native_grouped_parity|iq_multi_parity|prefill_mmq_kquant|^iq_parity"
|
||||
./native_expert_parity --geom 2048x512 /models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf 0 34 39
|
||||
./native_expert_parity --geom 2048x512 /models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf 0 34 39
|
||||
./native_grouped_parity --bench-down
|
||||
|
||||
ctest: 19 of 19 pass (15 `native_expert_parity_*` including the five `qwen36_*` pairs, `q6_K_q8_0` at 2560 x 640 and
|
||||
the `refuses_q6_K_down_at_640` WILL_FAIL; `native_grouped_parity`, `iq_multi_parity`, `iq_parity`,
|
||||
`prefill_mmq_kquant_test`).
|
||||
|
||||
Synthetic pairs at 2048 x 512 (relative L1 against the float reference; the negative control's down-row move, with
|
||||
0 other rows touched in every case, and the gate-row move):
|
||||
|
||||
| pair | cpu | gpu | cpu-gpu | GPU dequant vs `to_float` | down row flipped | gate row flipped |
|
||||
| --- | ---: | ---: | ---: | --- | ---: | ---: |
|
||||
| iq2_s / iq3_xxs | 1.7e-2 | 9.7e-3 | 1.8e-2 | bit-exact | 1.8e-1 | 3.5e-4 |
|
||||
| iq2_s / iq4_xs | 1.8e-2 | 1.2e-2 | 2.0e-2 | bit-exact | 5.8e-1 | 1.2e-3 |
|
||||
| q4_K / q5_K | 1.7e-2 | 1.0e-2 | 1.9e-2 | bit-exact | 1.5 | 2.5e-3 |
|
||||
| q4_K / q6_K | 2.2e-2 | 1.3e-2 | 2.4e-2 | bit-exact | 1.5e-1 | 1.3e-3 |
|
||||
| q5_K / q6_K | 2.2e-2 | 1.2e-2 | 2.3e-2 | bit-exact | 1.8e-1 | 3.3e-3 |
|
||||
|
||||
(The table's first three rows are the real-file layers 0 / 34 / 39 of UD-IQ3_XXS and the q4_K / q5_K row is layer 0 of
|
||||
UD-Q4_K_XL; the synthetic runs of the same pairs are within 1e-3 of them. The decode-once and per-entry kernels are
|
||||
bitwise equal on every pair; the CPU path's width invariance holds.)
|
||||
|
||||
Real files, both: 0 failures. UD-IQ3_XXS layers 0 (iq2_s/iq3_xxs), 34 and 39 (iq2_s/iq4_xs): gpu 9.7e-3, 1.2e-2,
|
||||
1.1e-2. UD-Q4_K_XL layers 0 (q4_K/q5_K), 34 and 39 (q4_K/q6_K): gpu 1.0e-2, 1.2e-2, 1.1e-2. Every layer's GPU
|
||||
dequantization of all three matrices equals ggml's `to_float` bit for bit.
|
||||
|
||||
The down kernel alone (`--bench-down`: phase 2, 48 calls in a graph, each layer its own 32 experts streamed from
|
||||
DRAM; medians of 40 launches), microseconds per expert at 2048 x 512:
|
||||
|
||||
| down type | MB / expert | 32 groups x 1 entry | 8 groups x 4 entries |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Q5_1 (the comparator) | 0.786 | 0.92 | 1.73 |
|
||||
| Q8_0 | 1.114 | 1.23 | 2.55 |
|
||||
| IQ4_XS | 0.557 | 0.98 | 1.97 |
|
||||
| IQ3_XXS | 0.401 | 0.96 | 1.88 |
|
||||
| Q5_K | 0.721 | 0.86 | 1.99 |
|
||||
| Q6_K | 0.860 | 0.96 | 2.53 |
|
||||
|
||||
On this card the 32 x 1 row is bandwidth-bound for every type (25 to 36 MB per 29 to 39 us call, 0.85 to 0.92 TB/s),
|
||||
so the new types cost what their bytes cost; the 8 x 4 row shows the per-entry kernels' cost (Q6_K, Q5_K: no
|
||||
`Split<>`, the dot redone per entry) against the decode-once ones (IQ3_XXS, IQ4_XS). The 1080 Ti numbers (section 5)
|
||||
set the step-5 budget.
|
||||
|
||||
## 5. Results, GTX 1080 Ti (VM 211, sm_61, CUDA 12.4, gcc-13)
|
||||
|
||||
`/home/rk/qwen36-step3-experts/run-vm211.sh` under the lock (2026-10-11, 20:02 UTC): configure with
|
||||
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61 -DSTRATA_MMQ_KQUANTS=ON` (5 s), the five test targets
|
||||
(149 s at `-j 8`), then the same three commands as section 4 with `/home/rk/models/` for the files; logs in its
|
||||
`logs/`. No guard was needed: the new kernels use `__dp4a`, `__vsubss4`, `__byte_perm` and fp16 conversions only.
|
||||
|
||||
- ctest: 20 of 20 pass (the 15 `native_expert_parity_*`, `native_grouped_parity`, `iq_multi_parity`, `iq_parity`
|
||||
with its fixture, `prefill_mmq_kquant_test` through llama.cpp's dp4a MMQ tiles on cc 61).
|
||||
- Real files, both 0 failures, the same numbers as the 4090 to the printed digits (the kernels are integer dp4a
|
||||
chains with one float expression per block; the q8_1 rounding is the same): UD-IQ3_XXS layers 0 / 34 / 39 gpu
|
||||
9.7e-3 / 1.2e-2 / 1.1e-2, UD-Q4_K_XL layers 0 / 34 / 39 (q4_K/q5_K, q4_K/q6_K, q5_K/q6_K) 1.1e-2 / 1.2e-2 /
|
||||
1.2e-2; GPU dequantization bit-exact for every matrix; the negative control's down-row move 1.8e-1 to 1.6 with no
|
||||
other row touched, the gate-row move 3.5e-4 to 3.4e-3.
|
||||
- `native_grouped_parity`: all 96 pairs at 512 x 256 and the seven model shapes bitwise equal to v1.
|
||||
|
||||
The down kernel alone per expert at 2048 x 512 (`--bench-down`, SM 1873 MHz, memory 5508 MHz, 46 C), the step-5
|
||||
budget:
|
||||
|
||||
| down type | MB / expert | 32 groups x 1 entry | 8 groups x 4 entries (per group) |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Q5_1 (the comparator) | 0.786 | 4.43 | 14.3 |
|
||||
| Q8_0 | 1.114 | 7.58 | 25.3 |
|
||||
| IQ4_XS | 0.557 | 6.58 | 12.1 |
|
||||
| IQ3_XXS | 0.401 | 6.78 | 10.8 |
|
||||
| Q5_K | 0.721 | 4.29 | 12.2 |
|
||||
| Q6_K | 0.860 | 5.32 | 15.6 |
|
||||
|
||||
Against Q5_1 at one entry per expert: Q5_K 0.97x, Q6_K 1.20x, IQ3_XXS 1.53x, IQ4_XS 1.49x. Pascal is not
|
||||
bandwidth-bound here (Q5_1: 25 MB per 142 us call, 178 GB/s of the card's 484): the i-quant down types pay their
|
||||
grid lookups and sign unpacking per call, so IQ3_XXS costs 1.5x Q5_1's time for half its bytes, while the K-quants'
|
||||
plain nibble chains run at Q5_1's speed. At four entries per expert the decode-once kernels (IQ3_XXS, IQ4_XS) amortise
|
||||
and come out ahead of the per-entry Q5_K / Q6_K. For a window of 4 tokens x top-8 routed to 32 distinct experts the
|
||||
down projection is 137 to 217 us per layer, 5.5 to 8.7 ms over 40 layers; the gate/up (twice the rows at the wider
|
||||
n_embd) is the larger half and was not re-timed here (the Flash-Next numbers in `native_grouped_parity --bench` stand).
|
||||
|
||||
## 6. Surprises
|
||||
|
||||
- `prefill_mmq_kquant_test` had a latent race: its sentinel memset on the legacy default stream was not ordered
|
||||
before the product on its non-blocking stream; the second product at 2048 x 512 read as entirely unwritten on the
|
||||
4090 and passed under `CUDA_LAUNCH_BLOCKING=1`. Fixed in the test (`[shared]` commit); not an MMQ fault.
|
||||
- The negative control's 1e-2 gate, stated for Qwen3.6's 256-value blocks, is above what a single 32-value block's
|
||||
sign flip moves a 640-wide Flash-Next row (8e-3 to 1.4e-2): hence the block-share scaling.
|
||||
- The study's 3.7 was right that the path is runtime per layer and that `native_experts.txt` carries the types; it
|
||||
missed that the GPU kernels' *type lists* did not include the files' down types, which is why "otherwise runtime"
|
||||
did not hold for either file.
|
||||
@@ -1,173 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 3, area `gdn`: the GDN output gate, the router and the shared expert
|
||||
|
||||
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step3-gdn`, from `qwen36-step2` at 8b7525e).
|
||||
The design is `docs/QWEN36-35B-A3B.md` sections 3.2 and 3.4 and step 3's first and third bullets in section 6; the
|
||||
plan is `docs/PLAN-qwen36-35b-a3b.md` section 5 step 3. Every item says what was decided, where it lives, and how
|
||||
it is checked, with the numbers from both cards.
|
||||
|
||||
## 1. What changed
|
||||
|
||||
| Decision | Where | Why |
|
||||
| --- | --- | --- |
|
||||
| `kernels::GdnGate { Sigmoid, Silu }` names the GDN output gate; every decode output kernel takes it as a required argument | `include/strata/kernels/gdn.hpp` | the one numerical difference between the two models (study 3.2, inventory row 39): `rms_norm(o) * ssm_norm * act(z)`, sigmoid for Flash-Next and SiLU for Qwen3.6. A required parameter, not a default, so a call site rewritten later cannot silently keep sigmoid |
|
||||
| `ModelGeometry::gdn_gate()` returns SiLU for `qwen35moe`, sigmoid for `qwen4exp` | `include/strata/core/layout.hpp` (`[shared]`) | from the architecture string, like `hc` and the indexer; no key says it. No global anywhere: one process can serve both models |
|
||||
| The four kernels: `gdn_out_norm` (legacy, `gdn.cu`), `fused_gdn_step_norm` (the default native decode, `fused_gdn.cu`), `native_gdn_out_norm` (pinned unfused, `native_gdn_preprocess.cu`), `gdn_step_norm_multi` (the verify window, `verify_kernels.cu`) | `src/kernels/cuda/` | SiLU is ggml's `op_silu` form `z / (1 + exp(-z))`; the sigmoid expression is untouched, so Flash-Next's arithmetic is bitwise what it was. `verify_kernels.cu` was not in the brief's list of three, but native packs decode only through the verify window (inventory row 114), so the gate had to reach it; it stays bitwise the fused kernel (checked) |
|
||||
| The seven call sites pass `g.gdn_gate()`: `layer.cpp` (3), `verify.cpp` (4) | `src/core/layer.cpp`, `src/core/verify.cpp` (`[shared]`, one commit, nothing else touched) | the smallest change the block agent's files needed |
|
||||
| No decode-path literal assumed 16/48 | (none) | `grep` of `src/kernels/cuda`, `src/core`, `src/program`, `include` for 48 / 6144 / 10240 / VPK finds only `ModelGeometry`'s defaults (step 2 reads them from the file), the PLE post-ops (Flash-Next only) and comments (`session.hpp:34`, `layer.hpp:10-16`, `gdn.hpp:11`). The kernels' only rule is `h_v % h_k == 0`; `fused_gdn_conv_l2` wants `channels % 128 == 0` (8192 is), `native_gdn_*` wants counts up to 65,535 (8192 is), `fused_gdn_ab` wants `n_embd % 8 == 0` (2048 is). The VPK 2 shape is run through every kernel in `gdn_parity` (16/32) and `qwen36_seam_parity` (2/4) |
|
||||
| The router and the shared expert: parameterisation and tests only | `src/kernels/router_top10_parity.cpp`, `src/kernels/shared_expert_parity.cpp` | generic already (study 3.1): `router_top10` takes `n_expert <= 512, k <= 32` at runtime; the native 512 x 10 router is guarded by `n_expert == 512 && k == 10` in `layer.cpp:370` and `verify.cpp:915`, so 256/8 takes the generic kernel. No literal of 10 or 512 in the decode router path needed changing; `verify.cpp`'s `HIP_GFX906` branch already carries a 256-expert window path |
|
||||
| The fixture tool grows `--gdn K,V,S`, `--experts E,K`, `--shexp-ff N`, `--quant-shexp q8_0`, `--bf16-exact` | `tools/qwen36_synth_gguf.py` (`[shared]`) | the CUDA GDN kernels are pinned to state 128 and the toy fixture has 16; the default fixture is byte-identical to before |
|
||||
|
||||
## 2. The harnesses
|
||||
|
||||
### `gdn_parity` (`src/kernels/gdn_parity.cpp`, `ctest -R gdn_parity`)
|
||||
|
||||
Both geometries, 16/48 (VPK 3, sigmoid) and 16/32 (VPK 2, SiLU), through all four implementations; the existing
|
||||
four traps (modulo versus interleaved pairing, decay order, conv direction, l2 epsilon) kept; the fifth trap is the
|
||||
gate, and it is run THROUGH the kernels: each kernel with the other model's gate must differ from the reference by
|
||||
more than 5%. The verify kernel is held bitwise to the fused one on the verify, commit and split-commit paths.
|
||||
|
||||
Note for a later reader: the first version of this rewrite reported the native and fused kernels 7.5x off at the
|
||||
32-head geometry and exact at 48. It was the harness: fixtures reset with pageable `cudaMemcpy` on a non-blocking
|
||||
stream race the DMA. The stream is blocking now, and the comment at its creation says why.
|
||||
|
||||
### `qwen36_seam_parity` (`src/kernels/qwen36_seam_parity.cpp`, `cmake/qwen36_oracle_dumps.cmake`)
|
||||
|
||||
`ctest -R 'qwen36_oracle_dumps|qwen36_seam_parity'`. The fixture `k.gguf`: hidden 64, GDN 2 k-heads / 4 v-heads of
|
||||
128 (VPK 2), conv 4, 256 experts top-8 of 32, shared expert 512 in Q8_0, the BF16-read weights BF16-exact; the oracle
|
||||
run twice on the 11-token "hello world" sequence (F32, and `--act-quant q8`). The engine's kernels then hold, by
|
||||
llama.cpp's `cb()` names, token by token with the state carried:
|
||||
|
||||
| seam | through | tolerance | basis |
|
||||
| --- | --- | --- | --- |
|
||||
| `conv_output_silu-0`, `q_conv_predelta-0`, `k_conv_predelta-0` | legacy, native, fused (`fused_gdn_conv_l2`), verify window (`gdn_conv_l2_multi`) | 1e-6 | one 4-tap F32 dot per channel |
|
||||
| `gate-0`, `beta_sigmoid-0` | fused (`fused_gdn_ab`), verify window (`gdn_ab_multi`) | 1e-6 | a 64-term dot against a BF16-exact weight |
|
||||
| `final_output-0` (every token) | all four | 8e-5 | oracle-crosscheck.md's `gdn_out` class |
|
||||
| `new_state-0` (after the 11th token; the verify window after two commits of 8 + 3) | all four | 2e-5 | the recurrence in F32 both sides |
|
||||
| `ffn_moe_topk-0` | `router_top10` at 256/8 from the oracle's `ffn_moe_logits-0` | identical | exact top-k on the F32 fixture only |
|
||||
| `ffn_moe_weights_norm-0` | same | 1e-5 | |
|
||||
| `ffn_shexp_gated-0` | `shared_expert`, native Q8_0 projections, the 1-D BF16 scalar gate | 1e-5 against the Q8 oracle | the engine rounds activations to Q8_1 as ggml does; the F32 oracle is 1.2e-2 away, which is the rounding itself and is printed, not gated |
|
||||
| `shared_expert_multi` | 8 + 3 tokens | bitwise the per-token call | verify.cpp's contract |
|
||||
|
||||
Negative cases through the kernels: the sigmoid gate at `final_output-0` (the oracle's control says 1.07), the
|
||||
un-normalised router weights at `ffn_moe_weights_norm-0`, the shared gate skipped at `ffn_shexp_gated-0`.
|
||||
|
||||
### `router_top10_parity` and `shared_expert_parity`
|
||||
|
||||
The router's five fixtures at both 512/10 and 256/8 (random, all-equal, a 12-way tie wider than k, a tie of exactly
|
||||
k scattered through the range, a dominant expert) and the clamp proved unreachable at both (8/256 is 512x the
|
||||
2^-14 clamp). The shared expert gains Qwen3.6's shape, 2048 x 512 with Q8_0 projections through `native_mmvq` and
|
||||
Q8_1 activations and the native BF16 scalar gate, against a host reference written from the block layouts; the
|
||||
silu-on-up reading and the skipped gate as negatives; `shared_expert_multi` bitwise the per-token call; and the
|
||||
output moved by rounding the F32 gate weight to BF16 reported (2.5e-4 on a random gate), not asserted.
|
||||
|
||||
## 3. The measured-not-asserted parity: the BF16 router (study 3.4)
|
||||
|
||||
`tools/qwen36_router_bf16_flips.py REAL.gguf DUMP` on the oracle's `--act-quant q8` dump of the first 8 tokens of
|
||||
`"Hello, world! How are you?"` (ids 9419, 11, 1814, 0, 2500, 513, 488, 30 by `llama-tokenize` on the IQ3_XXS file),
|
||||
VM 221, 2026-10-11 (`/models/work/logs/qwen36-step3-gdn-flips.log`):
|
||||
|
||||
| contract | top-8 slots differing (of 320) | experts in one set and not the other | tokens affected | rate |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| F32 x F32 (llama.cpp, the oracle) | 0 | 0 | 0 | 0 |
|
||||
| F32 x BF16(W) (the engine's native MMVF, `bf16_gemv_fp32_mmvf`) | **0** | **0** | **0** | **0** |
|
||||
| BF16(x) x BF16(W) (the legacy `bf16_gemv`, both rounded) | 34 | 6 | 6 | 0.23% (layers 4, 9, 12, 31, 32, 37; one slot each) |
|
||||
|
||||
**Why the native contract flips nothing: the F32 routers are already BF16.** A census of both shipped files
|
||||
(IQ3_XXS and Q4_K_XL): every element of `ffn_gate_inp`, `ffn_gate_inp_shexp`, `ssm_alpha`, `ssm_beta` and
|
||||
`ssm_conv1d` has its low 16 bits zero (20,971,520 of 20,971,520 router values per file); the checkpoint is BF16 and
|
||||
the converter stored these as F32. So `BF16(W) == W`, the engine's BF16 reading is lossless, and the pack's own rule
|
||||
("round exactly when the low 16 bits are zero", `upstream-tooling.md` section 4) already covers all four tensors
|
||||
`moe_shared`, `fused_gdn_ab` and the router read as BF16: **`--compat-bf16` is not needed for Qwen3.6**. The only
|
||||
rounding left is the activation's, in the legacy both-operands contract, which `native_bf16_projections` (step 2's
|
||||
default for native packs) does not use. `attn_norm` is not BF16-exact (17%) and is read as F32, which is fine.
|
||||
The study's "the router's flip rate is measured on the real file" (3.4, risk 6) stands, with the answer zero.
|
||||
|
||||
## 4. Results
|
||||
|
||||
### VM 221, the RTX 4090 (sm_89), 2026-10-11
|
||||
|
||||
rsync -rlpgoD --checksum --delete --exclude .git --exclude '/build/' --exclude '/build-mac/' --exclude '/logs/' \
|
||||
--exclude '/third_party/llama.cpp/' ~/Code/UnbiasedStrata-step3-gdn/ rk@192.168.50.151:/models/work/qwen36-step3-gdn/
|
||||
/models/work/build-step3-gdn.sh configure && /models/work/build-step3-gdn.sh all # 178 s clean, rc 0
|
||||
(cd build && ctest --output-on-failure -R 'qwen36_oracle_dumps|qwen36_seam_parity|gdn_parity|router_top10_parity|shared_expert_parity')
|
||||
|
||||
(`rsync -a` preserves the Mac's mtimes, and an object built seconds after an edit then looks newer than the edit:
|
||||
the first full build linked against a stale `verify.cpp.o`. `-rlpgoD --checksum` is `-a` without `-t`.)
|
||||
|
||||
5 of 5 pass. The numbers (relative L1 unless stated):
|
||||
|
||||
| harness | check | measured | tolerance |
|
||||
| --- | --- | ---: | ---: |
|
||||
| `gdn_parity` 16/48 | legacy / native / fused state vs reference | 4.0e-8 / 6.0e-8 / 6.0e-8 | 1e-5 |
|
||||
| | legacy / native / fused y (sigmoid) | 2.3e-7 / 1.4e-7 / 1.7e-7 | 1e-5 |
|
||||
| | the wrong gate (SiLU) through each kernel | 87% / 87% / 90% / 91% apart | > 5% |
|
||||
| `gdn_parity` 16/32 | legacy / native / fused state vs reference | 4.4e-8 / 6.0e-8 / 6.0e-8 | 1e-5 |
|
||||
| | legacy / native / fused y (SiLU) | 2.8e-7 / 1.4e-7 / 1.7e-7 | 1e-5 |
|
||||
| | the wrong gate (sigmoid) through each kernel | 110% / 125% / 116% / 110% apart | > 5% |
|
||||
| | verify kernel bitwise fused (y; commit; split commit) | yes / yes / yes | bitwise |
|
||||
| | pairing, decay, conv layout, l2 eps traps | 128% / 83% / 128% / 1031% apart | > 5% |
|
||||
| `qwen36_seam_parity` | `conv_output_silu-0`, worst path | 5.96e-8 | 1e-6 |
|
||||
| | `q/k_conv_predelta-0` (fused, verify) | 9.4e-8 | 1e-6 |
|
||||
| | `gate-0` / `beta_sigmoid-0` (fused_gdn_ab, gdn_ab_multi) | 2.3e-7 / 1.1e-7 | 1e-6 |
|
||||
| | `final_output-0`, worst token, legacy / native / fused / verify | 2.28e-7 / 1.91e-7 / 2.15e-7 / 2.15e-7 | 8e-5 |
|
||||
| | `new_state-0`, legacy / native / fused / verify (two commits) | 1.31e-7 / 1.49e-7 / 1.59e-7 / 1.59e-7 | 2e-5 |
|
||||
| | sigmoid gate at `final_output-0` (fused; verify window) | 125.8% / 125.8% apart | > 5% |
|
||||
| | `ffn_moe_topk-0` | 0 of 88 differ | identical |
|
||||
| | `ffn_moe_weights_norm-0`; the un-normalised reading | 6.1e-8; 23.5% apart | 1e-5; > 5% |
|
||||
| | `ffn_shexp_gated-0` vs the Q8 oracle; vs the F32 oracle | 3.5e-7; 1.2e-2 (reported) | 1e-5 |
|
||||
| | the shared gate skipped; `shared_expert_multi` vs per-token | 51.5% apart; bitwise | > 5%; bitwise |
|
||||
| `router_top10_parity` 512/10 and 256/8 | ids on 5 fixtures x 64 tokens; weights | exact; worst 1e-6-class | exact; 1e-5 |
|
||||
| `shared_expert_parity` 2048 x 512 | native Q8_0 + BF16 gate vs reference | 9.6e-8 | 1e-4 |
|
||||
| | silu-on-up; gate skipped; F32 vs BF16 gate weight | 83% / 272% apart; 2.5e-4 (reported) | > 5% |
|
||||
|
||||
### VM 211, the GTX 1080 Ti (sm_61), 2026-10-11
|
||||
|
||||
`/home/rk/qwen36-step3-gdn-run.sh` (kept on the VM), under the card lock for 5 minutes: the rsync above to
|
||||
`/home/rk/qwen36-step3-gdn/`, `set -o noclobber; echo qwen36-step3-gdn > /home/rk/VM-BUSY` after checking
|
||||
`pgrep -x llama-server` and `pgrep -f "[s]weep_ladder_1080ti.py"` are empty (the bracket keeps `pgrep -f` from
|
||||
matching its own shell, which it did on every earlier poll), then
|
||||
|
||||
cmake -S . -B build -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=ON \
|
||||
-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61 -DCMAKE_CUDA_HOST_COMPILER=g++-13 \
|
||||
-DCMAKE_C_COMPILER=gcc-13 -DCMAKE_CXX_COMPILER=g++-13 # 4 s
|
||||
cmake --build build -j 8 -- -k # 287 s, rc 0, everything
|
||||
(cd build && ctest --output-on-failure -R 'qwen36_oracle_dumps|qwen36_seam_parity|gdn_parity|router_top10_parity|shared_expert_parity')
|
||||
rm /home/rk/VM-BUSY # the script's EXIT trap
|
||||
|
||||
5 of 5 pass (`/home/rk/logs/qwen36-step3-gdn-1080ti.log`, the four binaries' printouts beside it). Every seam number
|
||||
of `qwen36_seam_parity` is the same digits as on the 4090 (the kernels are F32 and the summation orders do not
|
||||
depend on the card): `final_output-0` 2.28e-7 / 1.91e-7 / 2.15e-7 / 2.15e-7, `new_state-0` 1.31e-7 / 1.49e-7 /
|
||||
1.59e-7 / 1.59e-7, `conv_output_silu-0` 5.96e-8 worst, `gate-0` 2.27e-7, `ffn_moe_topk-0` identical,
|
||||
`ffn_moe_weights_norm-0` 6.1e-8, `ffn_shexp_gated-0` 3.5e-7 against the Q8 oracle, `shared_expert_multi` bitwise,
|
||||
the three negatives 125.8% / 23.5% / 51.5%. `gdn_parity`: states 5.3e-8 to 6.0e-8, y 1.4e-7 to 2.8e-7, the verify
|
||||
kernel bitwise the fused one on all three paths, the wrong gate 87% apart at 16/48 and 110% at 16/32 through every
|
||||
kernel. `shared_expert_parity` at 2048 x 512: 9.6e-8; `router_top10_parity`: ids exact at both shapes, weights
|
||||
worst 1.5e-7.
|
||||
|
||||
Nothing in the changed kernels is architecture-conditional: the SiLU is an `expf` and a divide in kernels that
|
||||
already ran on sm_61 in step 2's build, so no new guard was needed; the pass on the card is the proof.
|
||||
|
||||
## 5. The interface other agents consume
|
||||
|
||||
namespace strata::kernels {
|
||||
enum class GdnGate : int { Sigmoid = 0, Silu = 1 }; // strata/kernels/gdn.hpp
|
||||
inline const char* gdn_gate_name(GdnGate g);
|
||||
void gdn_out_norm(const float* o, const float* z, const float* ssm_norm, float* y, int64_t h_v, int64_t S,
|
||||
float eps, GdnGate act, void* stream); // gdn.hpp (legacy)
|
||||
void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate,
|
||||
const float* beta, const float* z, const float* gamma, float eps, GdnGate act,
|
||||
float* y, int h_k, int h_v, void* stream); // fused_gdn.hpp
|
||||
void native_gdn_out_norm(const float* output, const float* z, const float* gamma, float* destination,
|
||||
int64_t heads, int64_t cols, float epsilon, GdnGate act, void* stream); // native_gdn_preprocess.hpp
|
||||
void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
|
||||
const float* z, const float* gamma, float eps, GdnGate act, float* y, int h_k, int h_v,
|
||||
int n_tok, const int32_t* n_keep, void* stream, int t_out_begin = 0); // verify_kernels.hpp
|
||||
}
|
||||
kernels::GdnGate strata::core::ModelGeometry::gdn_gate() const; // strata/core/layout.hpp
|
||||
|
||||
Everything else is unchanged: `GdnShapes{S, h_k, h_v}` at runtime, the state `(S, h_v, S)` with j fastest, the conv
|
||||
history `[channel][3]`, `router_top10(logits, n_tokens, n_expert, k, ids, weights, stream)` at 256/8, `shared_expert`
|
||||
and `shared_expert_multi` with `NativeSharedWeights` (type ids per `native_mmvq.hpp`) at `n_ff` 512. The prompt-path
|
||||
GDN kernels (`src/prefill/kernels.cu:324, 612`) are the prefill agent's and still gate with sigmoid; they will want the
|
||||
same `GdnGate` argument. `layer.hpp:16`'s comment still says "SIGMOID for qwen4exp; qwen3.5 used SiLU" (the block
|
||||
agent's file; the code beneath it is right).
|
||||
@@ -1,63 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 3: the integration branch `qwen36-step3`
|
||||
|
||||
Branched from the step-2 head (0e40d4e) on 2026-10-11. Five areas were developed in parallel from 8b7525e, each on its
|
||||
own branch with its own notes, and cherry-picked here in this order with no conflicts: block (`step3-block.md`, 5
|
||||
commits), gdn (`step3-gdn.md`, 8), experts (`step3-experts.md`, 7), attn (`step3-attn.md`, 9), prefill
|
||||
(`step3-prefill.md`, 12 of 17: its five cherry-picks of attn and gdn commits were dropped here because the originals
|
||||
are present). One commit of the integrator's own, 7cfb7dc: `generate.cpp` calls `qsa_kv_streaming_applies` right after
|
||||
the geometry is read (the attention agent could not edit that file).
|
||||
|
||||
## Both cards, the whole branch
|
||||
|
||||
Configure for both: `-DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=ON
|
||||
-DSTRATA_MMQ_KQUANTS=ON` with gcc-13 as the host compiler; the 1080 Ti adds `-DSTRATA_EXPERIMENTAL_SM60=ON
|
||||
-DCMAKE_CUDA_ARCHITECTURES=61`, the 4090 `-DCMAKE_CUDA_ARCHITECTURES=89`. `STRATA_MMQ_KQUANTS` is needed for the
|
||||
Q4_K_XL file's prompt path (Q6_K down on layers 34, 38, 39) and defaults OFF; step 5 turns it on in the Makefile.
|
||||
|
||||
| Card | Build | ctest | Failures |
|
||||
| --- | --- | --- | --- |
|
||||
| RTX 4090 (VM 221, sm_89) | 0 errors, 420 s for every target | 89 of 92 pass | ple_parity (no Flash-Next shard on the host), platform_memory_test (mlock limit), expert_multi_test (no AVX-512) |
|
||||
| GTX 1080 Ti (VM 211, sm_61) | 0 errors, 302 s | 87 of 92 pass, 2 skipped (the sm_80 fused prompt MoE tests) | the same three |
|
||||
|
||||
Every step-3 test (qwen36_block_test, qwen36_seam_parity, gdn_parity, router_top10_parity, shared_expert_parity,
|
||||
qsa_dense_parity, the native_expert_parity pairs, prefill_mmq_kquant_test, gdn_rec_parity, prefill_qwen36_test) passes
|
||||
on both cards; the per-seam numbers are in each area's notes and are identical on both cards to the printed digits.
|
||||
|
||||
## The review (`step3-review`, read-only, on the 41-commit range) and what it changed
|
||||
|
||||
1. HIGH, attn x block seam: `shapes_of` in verify.cpp and mtp.cpp left `idx_top_k = 2048` on a no-indexer geometry, a
|
||||
"half set up" shape that `qsa.cu`'s validate refuses, so the verify window would have exited on the first Qwen3.6
|
||||
attention layer. Not covered by any test (no test drives `Verifier` on qwen35moe; that is step 4's runner test).
|
||||
Fix: one exported shape builder for all four sites and one dense predicate.
|
||||
2. MEDIUM, Flash-Next: the MTP drafter's attention (cap = the 32,768 draft window) took the new bounded split-K kernel,
|
||||
a different summation order; drafts are verified, so draft quality, not correctness. Fix: sparse-model shapes keep
|
||||
the previous grid.
|
||||
3. LOW: the prefill fixture failed instead of skipping without numpy (fixed, c4f599f); native_expert_parity's 3e-2
|
||||
bound tightened to the policy's 2e-2 with separate CPU rows (77983af); `qsa_attn_bench` registered as a test
|
||||
(removed from the suite).
|
||||
|
||||
All fixed on the attention branch and cherry-picked here (one builder `strata::core::qsa_shapes(g)` in
|
||||
`include/strata/core/qsa_shapes.hpp` used by layer, verify, mtp, session and prefill, the last by delegation from
|
||||
prefill's `shapes_of`; `qsa_dense()` and the kernels' guard test the same three-zero predicate; the split-K bound applies
|
||||
to dense shapes only, so Flash-Next's drafter keeps its 512-block grid and 12.09 MiB scratch, A/B equal within 1 us on
|
||||
the 1080 Ti). After the fixes: 4090 88 of 91 (the same three host failures); 1080 Ti incremental build 81 s, the 33
|
||||
attention / prefill / expert / verify tests 33 of 33.
|
||||
4. NOTE: the GDN head pairing is tiled (`h % 16`), as llama.cpp, the oracle and the engine all have it; the reviewer's
|
||||
brief had said interleaved, which is the oracle's negative control.
|
||||
|
||||
Not checked end to end until step 4's pack and runner exist: the verify window on qwen35moe, the decode mixers through
|
||||
`block_layer_pre` stage 1 on a real pack, `native_rope_apply` against the Qwen3.6 oracle, dense attention above 20,000
|
||||
cells against a reference, the drafter on qwen35moe.
|
||||
|
||||
## Findings that feed step 4 and 5
|
||||
|
||||
- The real files' F32 routers, `ffn_gate_inp_shexp`, `ssm_alpha`, `ssm_beta` and `ssm_conv1d` are BF16-exact
|
||||
(low 16 bits zero in every element of both files), so the engine's BF16 reading is lossless and `--compat-bf16` is
|
||||
not needed; the measured top-8 flip rate on the real file is 0 of 320 slots (`step3-gdn.md`).
|
||||
- The native expert kernels accept every layer of both files; on the 1080 Ti the down projection per expert is
|
||||
Q5_K 4.3 us, Q6_K 5.3, IQ3_XXS 6.8, IQ4_XS 6.6 against Q5_1's 4.4 (`step3-experts.md`).
|
||||
- Dense attention per query row at 262,144 cells: 1.0 ms on the 4090, 2.4 ms on the 1080 Ti (fp16 KV); the split-K
|
||||
scratch is 2.02 MiB per row (`step3-attn.md`).
|
||||
- `moe_fused_iq.cu` (sm_80+) still lacks the new down types; those layers take MMQ in the prompt path.
|
||||
- VM hygiene: sync with `rsync -rlpgoD --checksum` (`-a` keeps Mac mtimes and can leave a stale object linked);
|
||||
`pgrep -f "[s]weep_ladder_1080ti.py"` (the unbracketed pattern matches its own shell).
|
||||
@@ -1,217 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 3: the prompt path at Qwen3.6's geometry
|
||||
|
||||
Working notes of the prefill item of step 3 (2026-10-11, branch `qwen36-step3-prefill`, branched from `qwen36-step2` at
|
||||
8b7525e). The design is `docs/QWEN36-35B-A3B.md` section 3.6 (the table of literal sites) and section 6, step 3, the
|
||||
prefill bullet; the rules are `step3-common.md`. Every item says what was decided, where it lives, how it is checked,
|
||||
and the numbers from both cards.
|
||||
|
||||
## 1. What changed, site by site
|
||||
|
||||
`src/prefill/*` is the whole scope. The study's table (3.6) had eight literal sites; what each became:
|
||||
|
||||
| Study's site | What it was | What it is now |
|
||||
| --- | --- | --- |
|
||||
| `prefill.cpp` constants `N, HC, D, LR, K, NE, C, ZV, HV` | file-wide `constexpr` (2560 / 4 / 10240 / 320 / 10 / 512 / 10240 / 6144 / 48) | a `Geom` struct built from the `ModelGeometry` (`Geom::of`): n_embd, hc, hc*n_embd, hc_lr, k, n_expert, n_ff (and 2 n_ff, the shared width), conv channels, value dim, value heads, key heads, heads, KV heads, head dim, `attn_q`'s width, n_head*256, n_head_kv*256, `indexer`, `silu`. Every count (`gdn_set_bytes`, `qsa_set_bytes`, `moe_bufs`, `moe_set_bytes`, `bytes_needed`) and every launch in `carve` and `run_impl` reads it. The old names stay as local aliases inside each function so the arithmetic reads as before |
|
||||
| `Prefill::init`'s refusal (`n_embd == 2560 && hc == 4 && hc_lr == 320 && k == 10`) | one geometry | per architecture: `qwen4exp` keeps exactly that check; `qwen35moe` needs `hc == 1`; both need `ss.k == n_expert_used`, `k` in 1..32 and at most `n_expert`, a GDN geometry the kernels are built for (`gdn_geometry_supported`: 48/16/10240 or 32/16/8192, state 128, conv 4), head_dim 256, 2 KV heads, n_rot 64, n_embd a multiple of 256, n_ff of 64. Each refusal names what it saw |
|
||||
| `Qf` as `T * 12288`, `q` / `attn` as `T * ZV`, `idx_raw`, `q_idx` | 24 heads x 512; the indexer's two buffers always | `T * G.qf` (n_head * 512), `T * G.av` (n_head * 256); the indexer's buffers, the selection scores and the ids rows only with an indexer (`G.indexer`). Dense attention carries no ids: a null is the identity selection (below) |
|
||||
| MoE buffers `T*K*1280`, `T*K*640`, `1280 * 2560`, `2560 * 640`; `mmq::fits(gt, 1280)`, `matrix_bytes(dt, N, 640)` | 2 n_ff and n_ff as 1280 / 640 | `G.ff2`, `G.ff`, `G.ffs`; `mmq_plan()` takes each layer's widths from the native layout (`fmt[l].n_embd`, `fmt[l].n_ff`; the canonical Q2_0 pack's 2560 / 640 otherwise), so the plan is per pack, not per build. The peer paths (`set_peer`, `bind_stage_helper`, the peer products in `run_impl`) use the same members; `PeerPrefill`'s event ring and host bounds are sized once from `NE_MAX = 512` |
|
||||
| `grs`, `gated`, `inj`, `xq`, `ident` from `HC`, `D`, `LR` (`:854-856, :1000-1026, :1375-1380`) | the hyper-connection's buffers and the GR read / write around every half | carved only at `hc > 1`. At `hc == 1` the half is `x = rms_norm(R, attn_norm) -> mixer -> R += out; x = rms_norm(R, post_attention_norm) -> MoE -> R += out` through two new kernels, `rms_norm_images` (the FP32 norm with its BF16 and FP16 images, gr_norm_kernel's arithmetic on one stream) and `residual_add`. The GR path is untouched (`gr_*` kernels, the F-2 fusion, `STRATA_GR_UNFUSED`); the embedding broadcast becomes a copy. `draft_kv` (the MTP drafter's K/V through this path) is Flash-Next's graph and returns false for `qwen35moe` (step 4 brings the nextn block) |
|
||||
| GDN kernels on `HV`, `HK`, `C`, launched `<<<HV, ...>>>`; `VPK = 3` | file constants | templates on `<HV, HK, C>` (`gdn_gates_kernel<HV>`, the three conv kernels and the l2 norm on `<C>`, `gdn_rec_kernel<HV, HK, C, SILU>`, `gdn_rec_cols_kernel`, `gdn_rec_cols_pipe_kernel`, `gdn_rec_kh_kernel<HV, HK, C>` with `VPK = HV / HK` and a `static_assert(HV % HK == 0 && VPK <= RG)`, `gdn_out_norm_kernel<HV, SILU>`, `gdn_keyhead_ok<HV, HK, C>`), dispatched by `gdn_dispatch` from a `GdnGeom {hv, hk, c, silu}` at exactly the two geometries; any other stops the process (the kernels' convention) after `init` has refused it by name. The output gate is `gdn_gate<SILU>(z)`: `z * sigmoid(z)` for Qwen3.6, `sigmoid(z)` for Flash-Next, chosen from `g.arch` (`Geom::silu`) |
|
||||
| `route_kernel<REG>` with `rank < 10`, `ids[t*10 + rank]`, `lane < 10` | top-10 baked | `k` a kernel parameter (the warp kernel at 512 and 256 experts, `router_top10` for any other count); `moe_combine` takes the width and `k`; the SwiGLU kernels take n_ff; `swiglu_pair` runs over `n * n_ff` |
|
||||
| `split_q_kernel`, `gate_attn_kernel` over `T * 24 * 256` and `h * 512` | 24 heads | `n_head` a parameter (head_dim 256, `attn_q` as `[n_head, 2, 256]` per token in both models) |
|
||||
| `moe_fused_iq.cu:59` `GU_ROWS_K 2560 / D_ROWS_K 640`; the `1280 / 2560` weight-row counts; `dm[row * 2560]`; `out + row * (10 * AB)` | constants | `NativeGeom` carries `n_embd` and `n_ff`; the kernel's stage count, weight-row blocks per tile, activation row stride, H block count and output stride come from them (loop bounds, not unrolled constants); `experts_native` refuses a width that does not tile the work item (n_embd a multiple of 256, 2 n_ff and n_embd multiples of the item's 64 WW rows). `moe_fused.cu` is NOT touched: it is the Strata Q2_0 blob's kernel and the blob format itself is the Flash-Next shape (gate/up codes `[1280][640 B]`, down `[2560][160 B]`); the canonical pack is refused for any other geometry since step 2, so no Qwen3.6 chunk reaches it (`fused_l` needs `!lay.native`). The study's "likewise" for that file does not apply |
|
||||
| the layer loop at `:1724`, `RP = 48` at `:1303` | "check" | the loop runs `g.n_layers` (it always did); `RP = 48` is the peer-streaming ring's slot count (`STRATA_PF_PEER_RING`), not a head count: unchanged |
|
||||
|
||||
Also changed: `kv_append_kernel` keeps `t * 512 + kvh * 256 + d` and the grid `(T, 2, 8)`: 2 KV heads x 256 in both
|
||||
models (init refuses anything else); `rope()` keeps its 64 rotated dims and the pairs `(p, p + 32)` (n_rot 64, the
|
||||
IMRoPE sections and the 1e7 base are the same in both models; `rope_scaling()` is the process config). The
|
||||
`on_seam` hook on `Prefill` (null by default, nothing else changes) is how the harness reads the layer loop by
|
||||
llama.cpp's seam names and teacher-forces every layer's input. `STRATA_PREFILL_ALLOC_TRACE=1` names the allocation
|
||||
that did not fit (it found the harness's own bug below).
|
||||
|
||||
### The attention step
|
||||
|
||||
The study (3.3, risk 3) has the prompt attention through `qsa_prompt_attn_batch` on sm_80+ and the batched decode
|
||||
kernel below cc 70, both at `G = 12` with a split-K scratch that grows with the context. The attention branch
|
||||
(`qwen36-step3-attn`) templated `G` at 2 / 8 / 12, made a null `ids` the identity selection and bounded the scratch
|
||||
at 128 blocks per KV head; its three kernel commits are cherry-picked here (section 4). The prefill's dense path
|
||||
is then: the shapes zero the three indexer widths together (`shapes_of`: that is the kernels' `qsa_dense` signal;
|
||||
`qsa.cu`'s guard refuses a shape with only some of them zero), the capacity is `qsa_selection_cap` (every cell of
|
||||
the primary state), no ids are carved or passed, `qsa_attn_group` is asked before any launch and its refusal is
|
||||
`run`'s error string (a 16-head model asked for G = 12 is a message, not a mis-indexed run), the step records'
|
||||
width is `n_kv` (`qsa_step_fill` under the dense shape). The indexer tensors are not required of a dense layer.
|
||||
No kernel of the attention branch was rewritten here.
|
||||
|
||||
## 2. The harness
|
||||
|
||||
### 2.1 Fixtures (`tests/python/qwen36_prefill_fixture.py`)
|
||||
|
||||
The oracle's own fixture is 64 wide with heads of 16 and 32; the prompt kernels are built for the real widths
|
||||
(the GDN templates at 128-wide heads, the attention kernels at head_dim 256, the fused experts at 256-wide tiles),
|
||||
so the harness has its own: the synthetic model of `tools/qwen36_synth_gguf.py` (its weights, its 128-token
|
||||
vocabulary) at the real per-layer geometry, few layers, few experts:
|
||||
|
||||
| Case | Layers | Geometry | Forms |
|
||||
| --- | --- | --- | --- |
|
||||
| `gdn3` | 3, all Gated DeltaNet (interval 4: no layer satisfies `(il + 1) % 4 == 0`) | n_embd 2048, GDN 16 / 32 heads of 128 (conv 8192), attention 16 / 2 of 256, n_rot 64, sections 11/11/10/0, base 1e7, 16 experts top-8 of 512, shared 512 | projections, experts, shared expert and head Q8_0 (what the engine serves natively); `ffn_gate_inp`, `ssm_alpha`, `ssm_beta`, `ffn_gate_inp_shexp` F32 rounded to BF16-exact values (the engine's forms, exact); norms, conv, dt bias, ssm_a, `token_embd` F32 |
|
||||
| `full4` | 4: three DeltaNet, layer 3 full attention | the same | the same |
|
||||
|
||||
The router runs at half the toy's gain (`ffn_gate_inp * 0.5`): at the toy's spread the top-8 of 16 carry 99 % of
|
||||
the softmax mass and the renormalisation rival moves `ffn_out` by 1.3 %, invisible to a 5 % gate; at this gain it
|
||||
moves it by 5.7 %. For each case the script runs `ref/qwen36.py` on 40 tokens (the ASCII codes of
|
||||
`"the quick brown fox jumps over the lazy "`) three ways: the faithful reading (`o`), `--act-quant q8` (`o_q8`), and
|
||||
the rival readings `neg_gate` (`gdn_gate=sigmoid`), `neg_pair` (`head_pairing=interleaved`), `neg_norm`
|
||||
(`router_norm=False`) and, on `full4`, `neg_attngate` (`attn_gate=False`). The oracle dequantizes Q8_0 with
|
||||
gguf-py, bit-identical to ggml (oracle-crosscheck.md), so every difference the harness sees is the engine's
|
||||
arithmetic. `gdn3` is a file `read_model_geometry` refuses by design (block_count must be a multiple of the
|
||||
interval): the harness takes `full4`'s geometry with `gdn3`'s layer count, which is what the oracle ran it as.
|
||||
4m55s on VM 221 for both cases (the oracle in numpy); 269 and 351 MB.
|
||||
|
||||
### 2.2 The test (`tests/cuda/prefill_qwen36_test.cpp`; CTest `prefill_qwen36_fixtures`, `prefill_qwen36_test`, `prefill_qwen36_attn_test`)
|
||||
|
||||
The fixture's tensors go into a `WeightTable` row by row (`WeightTable::set`, the one `[shared]` change: Q8_0 as
|
||||
`native_data`, the BF16 set as `Bf16InF32`, the rest F32), the experts into an in-memory `ExpertSource` of
|
||||
`[gate | up | down]` blobs (unpinned: the prompt path's stager copies them) under a `native_experts.txt` the test
|
||||
writes, the session from `session_init` at 64 cells, the embedding rows through `embd_rows`. Then:
|
||||
|
||||
1. `Prefill::init` refusals: top-10 on the top-8 file ("top-10 routing over 16 experts (the file says top-8 ...)"),
|
||||
and 32 value heads / 8 key heads (VPK 4; "no GDN kernels for 32 value heads / 8 key heads / 6144 conv channels
|
||||
(built for 48/16/10240 and 32/16/8192 ...)"). Both must be refused with those words.
|
||||
2. One chunk of 40 and chunks of 7 (the oracle's `base_c7` case), every layer's input teacher-forced at the `l_in`
|
||||
seam to the oracle's `l_out` of the layer before (oracle-crosscheck.md, "Tolerance policy", item 2: per layer,
|
||||
not accumulated), each seam held to the faithful dumps as the relative L1 of the sums over the chunks:
|
||||
`attn_norm`, `linear_attn_out` / `attn_output`, `attn_post_norm`, `ffn_out`, `l_out`, and `ffn_moe_topk`.
|
||||
3. The router's top-k: a rank swap is allowed only where the oracle's own softmax puts the two experts within
|
||||
2e-3 of each other (the prompt path's router multiplies BF16-rounded activations, as the study notes under
|
||||
`STRATA_PREFILL_BF16X2`; the decode path's is FP32), any other disagreement fails.
|
||||
4. The negative controls: the engine, forced from the faithful dumps, against the rival readings' dumps at the seam
|
||||
that makes each, more than 5 % apart.
|
||||
5. For the record: the same seams against the Q8 oracle, and the accumulated error without forcing.
|
||||
|
||||
The gates (`gate_for`): `attn_norm` 1e-4 (FP32 norm), `attn_post_norm` 2e-3 (the mixer's error passes through
|
||||
the norm of R + out), `linear_attn_out` / `attn_output` 1e-2 (FP16 GEMMs over FP16-dequantized Q8_0 weights, BF16
|
||||
alpha / beta), `ffn_out` 2e-2 (the int8 MMQ products: q8_1 activations and H), `l_out` 1e-2. They are the measured
|
||||
numbers below with a 4x to 10x margin; the negatives sit at 0.06 to 0.92.
|
||||
|
||||
### 2.3 The GDN kernels alone (`src/prefill/gdn_rec_parity.cu`)
|
||||
|
||||
Kept its bit-for-bit check of the two recurrence variants, now at both geometries; added a double-precision host
|
||||
transcription of the recurrence (decay before the rank-1 update, v-head h with k-head h % HK, the gated RMS-normed
|
||||
output) that the engine's own `gdn_recurrence` and `gdn_conv` launches are held to (through their `GdnGeom`), the
|
||||
rival readings computed by the same reference (the other model's gate, the interleaved pairing h // VPK) required
|
||||
to sit more than 5 % away, and the geometry refusals. Links `strata_prefill`.
|
||||
|
||||
### 2.4 The fused native experts (`tests/cuda/prefill_fused_iq_test.cpp`)
|
||||
|
||||
The reference part runs at both geometries (the widths are variables set per pass); the timing part keeps the pack
|
||||
it was measured on. Exit 77 below sm_80 (the 1080 Ti: the prompt MoE takes MMQ or the FP16 path there, below).
|
||||
|
||||
## 3. Numbers
|
||||
|
||||
### 3.1 VM 221, RTX 4090 (sm_89), 2026-10-11
|
||||
|
||||
Build: `/models/work/build-step3-prefill.sh configure && ... all` (the common file's configure line at sm_89).
|
||||
|
||||
`./build/gdn_rec_parity`: 0 failures. Both geometries, T = 1 .. 4099: the two recurrence variants the same bits
|
||||
(output, state, FP16 output). Engine vs reference (T = 1, 7, 33, 257): y16 1.76e-4 to 1.79e-4, state 4e-8 to
|
||||
1.0e-7 relative L1 at both 48/16/10240 (sigmoid) and 32/16/8192 (SiLU). Rivals: the other gate 0.86 to 1.10 from
|
||||
the right reading (the engine 0.87 to 1.10 from the rival), the interleaved pairing 1.24 to 1.33. `gdn_conv`: h
|
||||
5.2e-8 to 5.4e-8, the history exact. Refused: 32/16/10240, 32/8/8192, 48/16/8192.
|
||||
|
||||
`./build/prefill_fused_iq_test --no-timing`: passed; every pair (IQ2_S / IQ2_XXS / IQ2_XS / IQ3_XXS / IQ3_S /
|
||||
IQ4_XS gate/up over Q2_0 / IQ4_NL down) within 1.45e-2 to 1.49e-2 rel RMS of the FP32 reference at 2560 / 640
|
||||
top-10 and 1.46e-2 to 1.49e-2 at 2048 / 512 top-8. `prefill_fused_moe_test`, `gemm_bf16_parity`: pass (the
|
||||
Flash-Next geometry unchanged).
|
||||
|
||||
`./build/prefill_qwen36_test /models/work/qwen36-step3-prefill-fx gdn3` and `full4`: pass, both chunkings.
|
||||
Relative L1 against the F32 oracle with forced layer inputs (one chunk of 40; chunks of 7 within 5 % of these):
|
||||
|
||||
| seam | layer 0 | layer 1 | layer 2 | layer 3 (attention) | gate |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| `attn_norm` | 2.4e-8 | 2.2e-8 | 3.1e-8 | 2.7e-8 | 1e-4 |
|
||||
| `linear_attn_out` / `attn_output` | 8.7e-4 | 8.5e-4 | 8.3e-4 | 5.9e-4 | 1e-2 |
|
||||
| `attn_post_norm` | 4.4e-4 | 3.6e-4 | 3.0e-4 | 8.2e-5 | 2e-3 |
|
||||
| `ffn_out` | 1.0e-2 | 8.2e-3 | 9.2e-3 | 7.9e-3 | 2e-2 |
|
||||
| `l_out` | 3.7e-3 | 2.6e-3 | 2.5e-3 | 2.1e-3 | 1e-2 |
|
||||
|
||||
The router: 7 rank swaps of 960 (40 x 8 x 3) slots on `gdn3` (one more in layer 3 on `full4`), every one a pair
|
||||
within 2e-5 to 1.3e-3 of each other in the oracle's softmax (an adjacent-rank swap); none elsewhere. Negatives:
|
||||
`neg_gate` 0.922, `neg_pair` 0.690, `neg_norm` 0.057 at the seams that make them, `neg_attngate` 0.541 at
|
||||
`attn_output-3`. Accumulated without forcing, `l_out` 3.7e-3 (layer 0) to 8.7e-3 (layer 3). Against the Q8
|
||||
oracle the GDN seams are worse (1.4e-2: the GDN projections run FP16 GEMMs, not Q8 products, so the Q8 oracle is
|
||||
the wrong reference for them) and `ffn_out` is not better (1.2e-2 to 2.4e-2): the MMQ products' q8_1 rounding of
|
||||
the activations and of H is not ggml's Q8_K rounding of the K-quant path the Q8 oracle models. The F32 column is
|
||||
the one the gates use.
|
||||
|
||||
Where the 1e-2 of `ffn_out` comes from: Q8_0 weights x q8_1 activations (a scale per 32) on int8 tensor cores,
|
||||
SwiGLU in FP32, H to q8_1 again, the down product the same. The fused test measures the same path at 1.45e-2 rel
|
||||
RMS against an FP32 reference over random weights; the oracle's own real-file numbers for `ffn_moe_out` are
|
||||
2.9e-2 (F32) / 2.3e-3 (Q8).
|
||||
|
||||
### 3.2 VM 211, GTX 1080 Ti (sm_61), 2026-10-11
|
||||
|
||||
Under the card's lock (taken 13:08 after the experts agent released it; held 182 s): `/home/rk/run211-prefill.sh`,
|
||||
the tree at `/home/rk/qwen36-step3-prefill/` (configure as the common file says at sm_61 with
|
||||
`STRATA_EXPERIMENTAL_SM60=ON`, the five test targets built in 168 s), the fixtures and dumps copied from VM 221 to
|
||||
`/home/rk/qwen36-step3-prefill-fx/`; the log is `/home/rk/logs/qwen36-step3-prefill-211.log`.
|
||||
|
||||
- `gdn_rec_parity`: 0 failures; the same bits for both variants at both geometries; engine vs reference y16
|
||||
1.76e-4 to 1.79e-4, state 4e-8 to 1.0e-7; the rivals 0.86 to 1.33 away; `gdn_conv` 5.2e-8 to 5.4e-8; the three
|
||||
geometry refusals. The numbers equal the 4090's to the printed digits.
|
||||
- `gemm_bf16_parity`: 0 failures (Pascal's fp32 widening path).
|
||||
- `prefill_fused_iq_test`, `prefill_fused_moe_test`: exit 77 ("the fused kernels need sm_80 or newer"), as expected.
|
||||
- `prefill_qwen36_test gdn3` and `full4`: pass, both chunkings. Against the F32 oracle with forced inputs:
|
||||
`attn_norm` 2.2e-8 to 3.1e-8, `linear_attn_out` 8.3e-4 to 8.6e-4, `attn_output-3` 5.9e-4, `attn_post_norm`
|
||||
8.2e-5 to 4.4e-4, `ffn_out` 7.9e-3 to 1.05e-2, `l_out` 2.1e-3 to 3.7e-3; the router 5 (gdn3) / 7 (full4)
|
||||
near-tie swaps, none elsewhere; negatives 0.922 / 0.690 / 0.057 / 0.541; accumulated `l_out` 3.7e-3 to 9.1e-3.
|
||||
The same as the 4090 to two digits: the prompt MoE took the same path on both cards.
|
||||
- Which prompt-MoE path runs on Pascal: MMQ. `STRATA_PREFILL_TIMING=1` shows the MMQ phases (gather, dequant =
|
||||
the gather marks, gemm gate/up 1 ms); and `STRATA_PREFILL_MMQ=0` (the FP16 GEMM over dequantized weights) gives
|
||||
different numbers (accumulated `l_out` 1.4e-3 / 3.0e-3 / 4.1e-3 instead of 3.7e-3 / 6.0e-3 / 8.2e-3; against the
|
||||
Q8 oracle `ffn_out-0` 2.25e-2 instead of 2.36e-2), so the default run was not that path. Q8_0 x q8_1 through
|
||||
llama.cpp's MMQ on sm_61 is dp4a, the study's risk 2 wants it enabled there, and it is. The FP16 path is the
|
||||
closer one to the F32 oracle (no int8 rounding of the activations), which is what the Q8 column says too.
|
||||
- 40 tokens through 3 GDN layers (and 4 with attention): a 60 to 100 ms GPU timeline per run, 36 to 40 ms of it
|
||||
host staging of the unpinned expert blobs; no throughput claim from a 40-token harness (step 5 measures).
|
||||
|
||||
## 4. Git
|
||||
|
||||
Commits on `qwen36-step3-prefill` past 8b7525e, in order: the kernels (templated GDN, runtime widths), the fused
|
||||
native experts' widths, the prefill geometry and plain block, `gdn_rec_parity` at both geometries, `[shared]
|
||||
WeightTable::set`, the fused test's second geometry, the three cherry-picks from `qwen36-step3-attn` (4a24760 and
|
||||
65a4f2b whole, 856daa0's three kernel files without its parity-test hunk, which belongs to that branch), the dense
|
||||
attention wiring with the harness and its fixtures, the harness's chunk accounting.
|
||||
|
||||
What the integrator should know:
|
||||
|
||||
- `src/kernels/cuda/qsa_decode_attn.cu`, `qsa_prompt_attn.cu`, `qsa.cu` and the two headers are the attention
|
||||
branch's versions at 856daa0; the decode GDN kernels and `gdn_parity.cpp` are the GDN branch's at 7954497;
|
||||
rebasing onto the integration branch makes those cherry-picks empty.
|
||||
- The GDN branch's 7954497 (`kernels::GdnGate`, the decode kernels' gate argument) and 4f9aeb9 (`[shared]`
|
||||
`ModelGeometry::gdn_gate()`) are cherry-picked here too: `GdnGeom::gate` is that enum, required with no default,
|
||||
and `Geom::of` takes it from `g.gdn_gate()`, so the prompt and decode paths agree by construction (drop the two
|
||||
at integration). The block branch's `layout.cpp` change (`[shared]` 69d52c9) is not needed by the prompt path:
|
||||
`Prefill::run` reads the two norms through `need()` and refuses a non-F32 one by name.
|
||||
- `WeightTable::set` is the only change outside `src/prefill`, `tests/cuda/prefill_*`, `tests/python`,
|
||||
`docs/qwen36-port` and the CMake lines that register the tests.
|
||||
|
||||
## 5. Not done, and surprises
|
||||
|
||||
- **The dense ids and scratch on the serve path** are the attention branch's bound (128 blocks per KV head, no ids
|
||||
buffer); `qsa_set_bytes` counts no ids rows for a dense model and the scratch at the bounded size. A 256K
|
||||
context on the serve path is step 5's measurement, not this harness's (64 cells).
|
||||
- **The prompt MoE on Pascal**: `moe_fused*.cu` need sm_80 (their tests exit 77 below it); the unfused path is MMQ
|
||||
where `mmq::fits` on sm_61 (dp4a) and the FP16 GEMM path otherwise, both at the new geometry (`mmq_plan` from the
|
||||
layout's widths, `dq_gu` / `dq_d` from `Geom`). Which one the 1080 Ti takes for Q8_0 is recorded in 3.2.
|
||||
- **The harness's own bug**: `ss.qsa_states[ss.qsa_primary()]` for a model with no attention layer at all (`gdn3`)
|
||||
reads past a zero-length array; the prefill now guards every read of the primary state with `ss.qsa_alloc`
|
||||
(`primary_cells`). Found by `STRATA_PREFILL_ALLOC_TRACE` as three multi-exabyte `cudaMalloc`s.
|
||||
- **Teacher forcing across a non-blocking stream**: a pageable `cudaMemcpy` into R returns before its DMA has
|
||||
landed, and the next kernel on the prompt stream read half-old rows (2.5e-3 at `attn_norm-1`); the harness waits
|
||||
for the device after the copy. Not an engine issue (the engine never copies host rows into R mid-layer).
|
||||
- **The study's table** is right about every site; two of its "check" items were not geometry (`RP = 48`, the
|
||||
peer ring; the layer loop already ran `g.n_layers`), and `moe_fused.cu` cannot take the new geometry because its
|
||||
blob format is the geometry (section 1).
|
||||
- **The study's harness line** ("chunked-prefill-then-decode against token-by-token decode") is met with the oracle
|
||||
standing in for the decode: the decode mixers are the other agents' and the oracle is the reference both are held
|
||||
to; the prefill is compared at every position of the chunked and the single-chunk run.
|
||||
@@ -1,266 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 4, area `drafter`: the MTP draft block from `blk.40`
|
||||
|
||||
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step4-drafter`, from the step-4 integration
|
||||
branch `qwen36-step4` at 1db8252). The design is `docs/QWEN36-35B-A3B.md` 3.10 and section 6 (step 4); what the
|
||||
block computes is `docs/qwen36-port/oracle-crosscheck.md` ("Nextn / MTP", 50 seams verified against llama.cpp) and
|
||||
`gguf-metadata.md` ("The nextn block"); the trunk pack this one sits beside is `step4-pack.md`. Section 2 is the
|
||||
pack's layout, section 5 the numbers from both cards, section 7 the interface the runner consumes.
|
||||
|
||||
## 1. The numbers first
|
||||
|
||||
**The real file, RTX 4090 (VM 221).** The draft pack cut from `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL-MTP.gguf`'s
|
||||
`blk.40`, loaded by the engine (506 MiB of VRAM: experts 464, dense 39, the K/V aside), fed the trunk's final residual
|
||||
of a 33-token prompt (llama.cpp's own `l_out-39` from `tools/qwen36_dump_llama.cpp` on that file), one row per
|
||||
position, token k with the hidden of k-1:
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| top-1 agreement with llama.cpp's MTP arm (its `graph_mtp` on the same pairs, `qwen36-dump ... mtp`) | **32 of 32** (the whole head); 31 of 32 with the shipped `data/draft_vocab.bin` subset (position 2's " fox", id 37550, is not in the subset) |
|
||||
| top-1 equal to the prompt's next token (teacher-forced acceptance over 31 positions) | **engine 24 of 31 (77.4 %)**, llama.cpp's MTP 24 of 31 (77.4 %): the same 24 |
|
||||
| seams vs llama.cpp's MTP graph (relative L2 per row, worst over 32 positions / relative L1 over all) | `mtp_eh_proj` 1.2e-3 / 5.6e-4, `mtp_attn_out` 1.2e-2 / 7.7e-3, `mtp_ffn_out` 2.5e-2 / 1.8e-2, `mtp_shared_head_norm` 2.2e-2 / 1.5e-2 |
|
||||
|
||||
llama.cpp's figures are its CPU graph with Q8_K / Q8_0 activation rounding; the engine's are q8_1 activations on
|
||||
the GPU. Those are the real-file numbers of the policy's Q8 class (`oracle-crosscheck.md`: `ffn_out` 4.5e-3 max per
|
||||
forced layer; here the block's products compound) and the drafts agree at every position. This is the B4 arm of
|
||||
the plan taken as a per-position reference rather than a generation: the 64-token greedy acceptance under the
|
||||
runner's verify window is the runner's measurement, after the gate is lifted.
|
||||
|
||||
**The synthetic fixture, both cards, all 37 checks** (section 5): every seam at every one of 75 positions within
|
||||
the gates against the Q8 oracle (the first product `mtp_eh_proj` at 2.3e-4), the router's top-8 identical at
|
||||
75 of 75 positions, the argmax identical at 74 and a near tie at the 75th, the three negatives 0.14 to 1.41 away.
|
||||
|
||||
## 2. The pack, exactly
|
||||
|
||||
`python3 -I tools/mtp_qwen36_pack.py --gguf <-MTP file>.gguf --out <dir> [--draft-vocab data/draft_vocab.bin | none]`
|
||||
(4 s on the Mac, 17 s on VM 221; reads 505 MB). Flash-Next's `tools/mtp_pack.py` / `mtp_rt.py` are untouched; the
|
||||
file names are theirs, so `--mtp DIR` is the one CLI and `MtpDrafter::load` picks the path by the trunk's
|
||||
architecture. Six files:
|
||||
|
||||
| File | Contents |
|
||||
| --- | --- |
|
||||
| `dense.txt` | 17 lines `name kind rows cols offset bytes`; the name without `blk.40.`; `kind` = `f32` (the 7 norms), `bf16` (`ffn_gate_inp` 256 x 2048, the 1-D `ffn_gate_inp_shexp`), or the projection's ggml type in lowercase (`q8_0` for all 8 in both shipped files); rows = ne1, cols = ne0 |
|
||||
| `dense.bin` | the tensors' bytes as stored, 256-aligned: **42,317,824 B** (Q4_K_XL-MTP: 7 x F32 norms 34 KiB, 2 x BF16 1.0 MiB, 8 x Q8_0 41.3 MiB) |
|
||||
| `experts.bin` | 256 blobs of `[gate rows \| up rows \| down rows]`, raw GGUF blocks, in id order: **486,539,264 B** (blob 1,900,544 = Q4_K 589,824 + 589,824 + Q5_K 720,896; `native_expert_layout(12, 13, 2048, 512)`) |
|
||||
| `native_experts.txt` | the v3 header and one line `0 12 13 0 1900544 0 589824 1179648` (the role offsets inside a blob; the header says so and names the source) |
|
||||
| `mtp.json` | `format`, `arch`, `source`, `source_bytes`, `trunk_layers` / `draft_block` 40, `n_embd` 2048, `n_head` 16, `n_head_kv` 2, `head_dim` 256, `n_rot` 64, `n_expert` 256, `n_expert_used` 8, `n_ff` 512, `n_ff_shexp` 512, the expert types and blob bytes, the dense types by name, `draft_vocab` |
|
||||
| `draft_vocab.bin` | copied from `--draft-vocab` (default `data/draft_vocab.bin`, 106,299 ids; `none` leaves it out: the whole head) |
|
||||
|
||||
Refused by name: a file without exactly one nextn block (the plain IQ3_XXS: "nextn_predict_layers is 0"), fused
|
||||
`ffn_gate_up_exps` / `attn_qkv`, a projection type outside `iq_pack.py`'s `NATIVE_PROJECTION_TYPES`, an F32 router
|
||||
that is not BF16-exact, and an expert pair the native kernels lack: **the IQ4_XS-MTP file's `blk.40` is Q3_K
|
||||
gate/up with Q4_K down, neither of which is in `iq_kernels.cu`'s lists (gate/up 16, 17, 18, 21, 22, 23, 29, 42,
|
||||
12, 13, 14, 6, 8; down 20, 23, 42, 7, 6, 8, 18, 13, 14)**, so only the Q4_K_XL-MTP file's draft block is served
|
||||
today, and it serves the IQ3_XXS trunk too (the study's 3.10: the drafter is separate from the trunk file; the
|
||||
float tensors are the same in every quant and the head and embedding come from the trunk's file).
|
||||
|
||||
The engine's view (`MtpDrafter::load`): `check_qwen36_pack` holds `mtp.json`'s nine geometry fields against the
|
||||
trunk's `ModelGeometry` and refuses a mismatch by name ("was cut for n_expert 256 but the trunk has 512"), requires
|
||||
the 17 names in the forms above (norms F32 of n_embd or head_dim elements, routers BF16, projections a type
|
||||
`native_mmvq_supported` takes, `eh_proj` n_embd x 2 n_embd); `load_qwen36_experts` requires one layer line, the
|
||||
header's `n_expert` equal to the trunk's, `native_expert_supported(gu, d, n_embd, n_ff)` and the blob and role
|
||||
offsets equal to `native_expert_layout`'s, then uploads `experts.bin` whole.
|
||||
|
||||
## 3. The drafter on the plain graph
|
||||
|
||||
`src/core/mtp.cpp`, `record_forward_qwen36` (dispatched from `record_forward` when `g.arch == Qwen35Moe`; the
|
||||
Flash-Next body is byte-for-byte what it was), T rows for the K/V-only pass, one row for the full layer, the same
|
||||
step / position records, graphs, staging, window, K/V formats, coupled sampling and draft chain as Flash-Next:
|
||||
|
||||
emb = token_embd[tok] (the native embedding table)
|
||||
e = rms_norm(emb) * nextn.enorm
|
||||
hn = rms_norm(R_in) * output_norm (the trunk's output norm: the caller hands the FINAL RESIDUAL, as
|
||||
h = rms_norm(hn) * nextn.hnorm for Flash-Next; llama.cpp's h_nextn is the normed state)
|
||||
R = eh_proj . concat(e, h) (embedding first; q8_1 x the pack's type through native_mmvq)
|
||||
x = rms_norm(R) * attn_norm
|
||||
K = rope(k_norm(attn_k . x)), V = attn_v . x -> the drafter's own K/V at the row's cell [the K/V-only pass stops here]
|
||||
q = rope(q_norm(attn_q . x)[:, :256]), gate = attn_q . x[:, 256:] per head
|
||||
a = dense attention over the cache (qsa_decode_attn_batch, the window's ids) * sigmoid(gate)
|
||||
R += attn_output . a
|
||||
x = rms_norm(R) * post_attention_norm
|
||||
ids, w = top-8 of softmax(ffn_gate_inp . x), renormalised (bf16_gemv_fp32_mmvf, router_top10 at 256 / 8)
|
||||
R += sum_j w_j expert_ids[j](x) + sigmoid(ffn_gate_inp_shexp . x) * shexp(x)
|
||||
(moe_group_resident over experts_ at blob stride -> native_expert_grouped on q8_1 x; shared_expert native)
|
||||
y = rms_norm(R) * nextn.shared_head_norm
|
||||
logits = head . y (the draft subset or the whole head), argmax / the coupled sampler, map_ids
|
||||
|
||||
What changed against Flash-Next's drafter, item by item of the study's 3.10: the two input projections
|
||||
(`fc_embedding`, `fc_hidden`) are the one `eh_proj` over the concatenation; the three hyper-connection groups are
|
||||
the three norms (`attn_norm`, `post_attention_norm`, `shared_head_norm`) with `add_inplace` residuals; the draft
|
||||
experts are 256 native blobs through `native_expert_grouped` (the kernels of step 3, `step3-experts.md`) instead of
|
||||
the Q2_0 grouped kernel; the geometry is the trunk's. What is the same: the dense attention over the drafter's own
|
||||
ring at `qsa_shapes(g)` (dense: null indexer, cap = max_cells or the `--mtp-window`), the main head over
|
||||
`draft_vocab.bin`'s subset, `token_embd` embeds, the pairing (cell i: the residual of position i with the token at
|
||||
i+1, RoPE at i).
|
||||
|
||||
**The RoPE position.** llama.cpp's MTP rotates the pair (token k, hidden k-1) at position k; the engine's drafter
|
||||
(both models) rotates at the cell, k-1. RoPE enters the scores only through position differences, so the two
|
||||
conventions give the same attention; the harness runs the engine's convention against the oracle's dumps and the
|
||||
seams agree to float rounding (`mtp_attn_pregate` 1.6e-3, the fp16 pool inside). Nothing in `prefill` / `draft` /
|
||||
`draft_kv` needed a Qwen branch for it.
|
||||
|
||||
**Buffers**: `cat_` (T x 2 n_embd) for the concatenation, `xq_` sized for the wider of `n_head x head_dim` and
|
||||
2 n_embd, `hit_scratch_` the larger of the grouped kernel's and `native_expert_scratch_bytes(T x k, n_ff)`; the
|
||||
rest of the carve is Flash-Next's at hc = 1. The K/V: without `--kv-resident` (KV streaming does not apply to the
|
||||
dense model, `step3-attn.md` item 6) `kv_plan` gives no ring, so the drafter's cache is `max_cells` whole: 2 KiB
|
||||
per cell fp16 (512 MiB at 262,144 cells), 576 B q4_0 (144 MiB); `--mtp-window` still bounds what a row attends to.
|
||||
|
||||
**The harness's entry point**: `MtpDrafter::debug_row(R_row, token, cell, pos, DebugOpts, seam, &top1, err)` runs
|
||||
the full layer for one row on the drafter's stream outside any graph and hands every seam to `seam` by llama.cpp's
|
||||
`cb()` name after a stream sync (the list is in `mtp.hpp`); `DebugOpts{hidden_first, skip_hnorm}` are the rival
|
||||
readings, set by nothing else.
|
||||
|
||||
**The prompt-side pass** (`src/prefill/prefill.cpp`, `Prefill::draft_kv`): the `qwen35moe` branch computes the
|
||||
nextn block's K/V for the prompt's cells through the prompt path's GEMMs in the drafter's order (embedding, the
|
||||
three norms, the concat, `eh_proj`, `attn_norm`, `attn_k` / `attn_v`, `k_norm`, RoPE at the cell, the append in the
|
||||
state's format), MMQ q8_1 x the pack's type where `mmq::supported` and `fits` say so (Q8_0: yes), else the FP16
|
||||
GEMM over dequantized weights; batches of 64 rows and up as for Flash-Next (`B < 64` declines and the drafter's own
|
||||
`prefill` runs). The harness checks it end to end: the positions after 64 `draft_kv` cells agree with the oracle
|
||||
to the same figures as the drafter's own pass and draft the same tokens.
|
||||
|
||||
## 4. The harness: `tests/cuda/qwen36_mtp_test.cpp`
|
||||
|
||||
The fixture (`tests/python/qwen36_mtp_fixture.py`; CTest `qwen36_mtp_fixtures`, 3 min on VM 221, 11 s on the Mac
|
||||
at 11 tokens) is the prompt-path harness's `full4` trunk (n_embd 2048, three DeltaNet layers, layer 3 attention
|
||||
16 / 2 x 256, 16 experts top-8 of 512, shared 512) plus the nextn block `blk.4` from `tools/qwen36_synth_gguf.py`,
|
||||
with every projection, `nextn.eh_proj`, the experts, the head and the embedding Q8_0 (the native paths' types) and
|
||||
the routers BF16-exact; 76 tokens, so 75 nextn positions and a 64-row `draft_kv` batch. The oracle runs twice
|
||||
(`--mtp`: faithful, and `--act-quant q8`) and `tools/mtp_qwen36_pack.py` cuts the pack from the fixture itself.
|
||||
`qwen36_mtp_test <dir>` (CTest `qwen36_mtp_test`, exit 77 without a device or the fixture):
|
||||
|
||||
1. Per position k = 1..75, `debug_row(l_out-3[k-1], tokens[k], cell k-1, pos k-1)`: 21 seams against the Q8
|
||||
oracle's row k-1 (relative L2 per row, the worst over positions; the F32 oracle's figure beside it from a
|
||||
second pass over its own trunk rows), `ffn_moe_topk` identical as a set, the draft equal to the oracle's argmax
|
||||
(a flip counts as a near tie when the oracle's gap is within 3x the row's largest logit error, and is printed).
|
||||
2. The negatives, each more than 5 % relative L1 from the oracle: the concat with the hidden state first
|
||||
(`mtp_eh_proj`, `result_output`), hnorm skipped (`mtp_hnorm`, `mtp_eh_proj`), the pairing with position k
|
||||
instead of k-1 (`mtp_hnorm`, `result_output`).
|
||||
3. `draft_first` (the captured round graph: the catch-up and the full layer at cell 0): draft 0 equals the
|
||||
uncaptured forward's draft at cell 0.
|
||||
4. `Prefill::draft_kv` for cells 0..63 (a `Prefill` on the fixture's trunk), then positions 65..75 through the
|
||||
forward again: the five seams within the same gates and the drafts equal to the drafter's own pass's.
|
||||
|
||||
`qwen36_mtp_test --real --gguf F --pack D --dump D1 --mtp-dump D2 --tokens ...` is the real-file arm of section 1:
|
||||
`D1` / `D2` from `qwen36-dump F D1 <tokens> 0 mtp` (CPU llama.cpp at the pinned commit, built under
|
||||
`/models/work/llama-cpu` on VM 221 with gcc-13; 52 s for 33 tokens at 4 threads, 871 MB of dumps).
|
||||
|
||||
The gates, relative L2 per row against the Q8 oracle, and why: `mtp_tok_embd` 1e-6 (exact dequantization),
|
||||
the norms of forced inputs 1e-5, `mtp_eh_proj` / `mtp_attn_norm` 1e-3 (one q8_1 x Q8_0 product: 2.3e-4 measured),
|
||||
then **every product after the first sees an input 2.3e-4 away from the oracle's, and the oracle's own q8 rounding
|
||||
of that input flips about 1 % of the int8 codes by a step (2e-4 x rms/amax x 127), which is 2e-3 of the output**:
|
||||
the Q/K/V projections 5e-3 (2.0-2.2e-3 measured), `mtp_attn_pregate` 5e-3 (1.6e-3), `mtp_attn_out` 1e-2 (5.4e-3),
|
||||
the residual / post norm / router logits 5e-3 (1.1-1.2e-3), the renormalised weights 1e-2 (1.7e-3), the shared
|
||||
expert and `mtp_ffn_out` 3e-2 (1.1-1.2e-2: the moe_out class), `mtp_post_ffn` / `mtp_shared_head_norm` 1.5e-2
|
||||
(5.3e-3: the l_out class), `result_output` 3e-2 (1.0e-2). The exact checks are the router's picks and the argmax.
|
||||
|
||||
## 5. Results
|
||||
|
||||
### VM 221, the RTX 4090 (sm_89), 2026-10-11
|
||||
|
||||
Build: `/models/work/build-step4-drafter.sh` (the common configure at sm_89 with `-DSTRATA_MMQ_KQUANTS=ON`;
|
||||
`qwen36_mtp_test` and `strata`, 2 min 34 s). `./build/qwen36_mtp_test /models/work/qwen36-drafter-fx`
|
||||
(`/models/work/logs/qwen36-drafter-synth.log`), 37 of 37:
|
||||
|
||||
| seam (75 positions) | vs Q8 oracle | gate | vs F32 oracle (reported) |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| `mtp_tok_embd` | 0.0 | 1e-6 | 0.0 |
|
||||
| `mtp_enorm` / `mtp_hnorm` / `mtp_concat` | 1.3e-7 / 1.3e-7 / 1.2e-7 | 1e-5 | 1.3e-7 / 1.3e-7 / 1.3e-7 |
|
||||
| `mtp_eh_proj` / `mtp_attn_norm` | 2.30e-4 / 2.31e-4 | 1e-3 | 6.2e-3 / 6.2e-3 |
|
||||
| `mtp_Vcur` / `mtp_Kcur_normed` / `mtp_Qcur_full` / `mtp_Qcur_normed` | 2.02e-3 / 2.08e-3 / 2.15e-3 / 2.22e-3 | 5e-3 | 9.0e-3 / 9.3e-3 / 8.6e-3 / 8.8e-3 |
|
||||
| `mtp_attn_pregate` / `mtp_attn_out` | 1.64e-3 / 5.41e-3 | 5e-3 / 1e-2 | 1.3e-2 / 1.5e-2 |
|
||||
| `mtp_attn_residual` / `mtp_attn_post_norm` / `ffn_moe_logits` | 1.09e-3 / 1.09e-3 / 1.19e-3 | 5e-3 | 7.4e-3 / 7.4e-3 / 1.2e-2 |
|
||||
| `ffn_moe_topk` | identical at 75 of 75 | identical | |
|
||||
| `ffn_moe_weights_norm` | 1.65e-3 | 1e-2 | 1.3e-2 |
|
||||
| `mtp_ffn_shexp_gated` / `mtp_ffn_out` | 1.18e-2 / 1.08e-2 | 3e-2 | 2.6e-2 / 1.9e-2 |
|
||||
| `mtp_post_ffn` / `mtp_shared_head_norm` | 5.32e-3 / 5.33e-3 | 1.5e-2 | 1.1e-2 / 1.1e-2 |
|
||||
| `result_output` | 1.09e-2 | 3e-2 | 1.4e-2 |
|
||||
| the draft = the oracle's argmax | 74 of 75; position 45 a near tie (oracle gap 1.2e-2, largest logit error 4.6e-2) | | 3 of 75 differ from the F32 argmax |
|
||||
|
||||
| negative case | relative L1 from the oracle | required |
|
||||
| --- | ---: | ---: |
|
||||
| concat(hnorm, enorm), the hidden state first, at `mtp_eh_proj` / `result_output` | 1.41 / 1.38 | > 0.05 |
|
||||
| hnorm skipped, at `mtp_hnorm` / `mtp_eh_proj` | 0.165 / 0.143 | > 0.05 |
|
||||
| paired with position k instead of k-1, at `mtp_hnorm` / `result_output` | 1.38 / 1.01 | > 0.05 |
|
||||
|
||||
`draft_first` at cell 0: drafts 65, 35, 16; the forward's draft at position 1: 65 (equal). `Prefill::draft_kv`
|
||||
took the 64 cells (batched, MMQ); positions 65..75 after it: `mtp_attn_pregate` 1.42e-3, `mtp_attn_out` 4.83e-3,
|
||||
`mtp_ffn_out` 1.11e-2, `mtp_shared_head_norm` 5.22e-3, `result_output` 1.14e-2, the drafts equal to the drafter's
|
||||
own pass's at 11 of 11. `ctest -R qwen36_mtp` (the fixture through CMake and the test): 2 of 2 (the fixture 132.5 s, the test 0.6 s).
|
||||
|
||||
The real file: section 1 (`/models/work/logs/qwen36-drafter-real-qwen36-mtp-draft{,-full}.log`;
|
||||
`/models/work/packs/qwen36-mtp-draft{,-full}`, the dumps in `/models/work/qwen36-drafter-real/`).
|
||||
|
||||
### VM 211, the GTX 1080 Ti (sm_61, Pascal), 2026-10-11, under `/home/rk/VM-BUSY`
|
||||
|
||||
The same tree (`/home/rk/qwen36-step4-drafter/`, the submodule copied from the step-4 pack tree), configured with
|
||||
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`, `qwen36_mtp_test` and `strata` built in 3 min 52 s;
|
||||
the fixture written there (`/home/rk/qwen36-drafter-fx`, 4 min 43 s) and the two packs cut from
|
||||
`/home/rk/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (the MTP repo's file, 22 s); the real-file dumps copied from VM 221
|
||||
(`l_out-39`, the MTP `result_output` and four seams). The lock was held from 21:28 to 21:34 UTC (the build and the
|
||||
fixture ran under it; the runs take seconds). Logs in `/home/rk/logs/qwen36-drafter-*.log`.
|
||||
|
||||
`./build/qwen36_mtp_test /home/rk/qwen36-drafter-fx`: **37 of 37**, the same numbers as the 4090 to the printed
|
||||
digits at every seam but four (`mtp_attn_out` 5.42e-3, `ffn_moe_logits` 1.23e-3, `ffn_moe_weights_norm` 1.61e-3,
|
||||
`mtp_ffn_shexp_gated` 1.14e-2, `mtp_post_ffn` / `mtp_shared_head_norm` 5.75e-3 / 5.70e-3: the per-entry expert
|
||||
kernels Pascal takes, `step3-experts.md`), the router's picks identical at 75 of 75, the argmax identical but the
|
||||
same near tie at position 45, the negatives 1.41 / 1.38, 0.165 / 0.143, 1.38 / 1.01, `draft_first` 65 35 16 = 65,
|
||||
`draft_kv` batched with the positions after it at 1.45e-3 / 4.75e-3 / 1.09e-2 / 5.34e-3 / 1.04e-2 and the drafts
|
||||
equal. The kernels the drafter adds to Pascal's path are the step-3 native expert kernels (dp4a), the MMVQ, the
|
||||
rms norm, the dense attention's `pre75` kernel: nothing new was guarded.
|
||||
|
||||
The real file, both packs: **top-1 agreement with llama.cpp's MTP arm 32 of 32 (the whole head), 31 of 32 (the
|
||||
subset: position 2 again); teacher-forced acceptance 24 of 31 = 77.4 % (23 with the subset), llama.cpp 24 of 31**;
|
||||
`mtp_eh_proj` 1.18e-3 / 5.6e-4, `mtp_attn_out` 1.22e-2 / 7.7e-3 as the 4090, but `mtp_ffn_out` 1.54e-1 / 2.6e-2 and
|
||||
`mtp_shared_head_norm` 1.42e-1 / 1.9e-2 (worst row / relative L1): **one position, 10, is 1.4e-1 from llama.cpp's
|
||||
head-normed state on the 1080 Ti and 1.6e-2 on the 4090**, every other position 1.0e-2 to 2.3e-2 on both. The
|
||||
only mechanism that moves one row by 14 % while its neighbours stay at 1 % is a routed-expert flip at a near tie
|
||||
(the real file's router sees percent-level differences, `oracle-crosscheck.md` "Tolerance policy"), from the
|
||||
cards' different dot-product orders in the attention and expert kernels; the draft at that position (411) is the
|
||||
same on both cards and equals llama.cpp's. Not confirmed by dumping both cards' `ffn_moe_topk` for that row (the
|
||||
lock was released); the runner's end-to-end parity on Pascal is where a flip rate per position is measured.
|
||||
|
||||
## 6. Not done, surprises, where the study was off
|
||||
|
||||
- **The 64-token greedy acceptance** (the brief's alternative to the llama.cpp arm) needs the trunk generating,
|
||||
which is the runner's (the step-2 gate, the verify window on qwen35moe); the per-position reference against
|
||||
llama.cpp's MTP arm is the stronger check and was cheap (the dumper exists since step 1). `draft()` and
|
||||
`draft_first()` run on the real pack (the captured graphs are the same code as Flash-Next's); only `draft_first`
|
||||
is held to the forward here.
|
||||
- **The VRAM plan's drafter line** (`generate.cpp`, `in.drafter_bytes = draft + 16 MiB` "its ring KV and 8 x n_vocab
|
||||
logits") undercounts: the weights are 506 MiB as planned, but the K/V is the whole context (no ring without
|
||||
`--kv-resident`: 512 MiB fp16 / 144 MiB q4_0 at 262,144 cells; `--mtp-window` does not shrink it), the draft head
|
||||
subset is `n_dvocab x row_bytes` (106,299 x 2,176 B = 221 MiB on the Q8_0 head of the Q4_K_XL file, 171 MiB on the
|
||||
IQ3_XXS file's Q6_K head), the logits 7.6 MiB, the identity ids T x max_cells x 4 (8 MiB at 256K). The runner's
|
||||
area (the plan is the gate block's); the numbers are here for it.
|
||||
- **The IQ4_XS-MTP file's draft block cannot be served** (Q3_K gate/up, Q4_K down: section 2). The study's 3.10
|
||||
counted it ("Q3_K/Q4_K, 364 MiB in the IQ4_XS file"); the step-3 expert kernels never gained those two roles.
|
||||
The Q4_K_XL-MTP pack serves every trunk, so nothing is lost today; adding Q3_K gate/up and Q4_K down to
|
||||
`iq_kernels.cu`'s lists is a step-5 item if that file is wanted.
|
||||
- **The data/draft_vocab.bin subset drops " fox"** (id 37550) and so one of 32 positions on the English prompt;
|
||||
the subset is Flash-Next's English-and-code selection over the same vocabulary and carries over as the study
|
||||
said, with that coverage.
|
||||
- **The study's 3.10 said "IMRoPE"** for the draft block's attention: the sections reduce to plain NEOX rope for
|
||||
text (section 1 of the study), and the engine's `native_rope_apply` / `rope_neox_apply` at n_rot 64 are what the
|
||||
oracle's dumps match.
|
||||
- The oracle's `mtp_ffn_moe_out` (the routed sum without the shared expert) is not a seam the engine materialises
|
||||
(`native_moe_combine` adds the shared expert in the same launch); `mtp_ffn_out` covers it.
|
||||
- `tests/python/qwen36_mtp_fixture.py` imports the prompt-path fixture module for its geometry and the BF16 rounding;
|
||||
a change there changes this fixture's trunk too (intended: one trunk shape for both harnesses).
|
||||
|
||||
## 7. The interface the runner consumes
|
||||
|
||||
- `MtpDrafter` is unchanged for the runner: `load(rt_dir, g, ss, max_t, err, window)` with `g` the trunk's geometry
|
||||
(`generate.cpp`: `draft_geometry = g.arch == Qwen35Moe ? g : ModelGeometry{}`, the one `[shared]` hunk, lines
|
||||
3267-3271), `bind(wt, &native_head, window_R, err)` (needs `output_norm.weight` F32 in `wt`, `output.weight`'s row
|
||||
for n_vocab, `token_embd.weight`'s row and the native embedding set, as the trunk pack provides), `prefill(R_rows,
|
||||
next_tokens, n, cell0)`, `draft(T, tokens, p, a, drafts, ...)`, `draft_first(...)`, `kv_state()`, `vram_bytes()`,
|
||||
`bind_bytes(row_bytes, n_vocab)`. `R_rows` / `window_R` are the trunk's FINAL RESIDUAL rows (hc = 1: n_embd each,
|
||||
`Verifier::final_R_all()`), not the normed state: the drafter applies `output_norm` itself.
|
||||
- `Prefill::draft_kv(mtp, R_rows, next_tokens, n, cell0, err)`: the same call; true for the Qwen3.6 drafter when
|
||||
the native embedding is set and the batch is at least 64 rows, false (err empty) otherwise.
|
||||
- New: `MtpDrafter::qwen36()`, `tensor_native(name, &type)`, `expert_gu_type()` / `expert_d_type()` /
|
||||
`expert_blob_bytes()`, `debug_row(...)` with `DebugOpts` and `SeamFn` (the harness's).
|
||||
- `tools/mtp_qwen36_pack.py`: `--gguf`, `--out`, `--draft-vocab`; the layout of section 2. The CLI's `--mtp DIR`
|
||||
takes the directory; `--draft-vocab en` style selection is whatever the pack holds as `draft_vocab.bin`.
|
||||
- The commits on `qwen36-step4-drafter` past 1db8252: ad70f3d the pack tool, 6ae03ea the drafter, f0e5362 the
|
||||
prompt-side pass, e21be6c `[shared] generate` (the one hunk, `src/program/generate.cpp:3267-3271`), 41c568d the
|
||||
harness and the fixture, then this file.
|
||||
@@ -1,58 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 4: the integration branch `qwen36-step4`
|
||||
|
||||
Branch `qwen36-step4` (worktree `~/Code/UnbiasedStrata-step4`), from the step-3 head 355ce3c. Unmerged, unpushed.
|
||||
|
||||
## What is on it, in order
|
||||
|
||||
| range | from | what |
|
||||
| --- | --- | --- |
|
||||
| 3ad2847..1db8252 (7) | `qwen36-step4-pack` | `iq_pack` FORM_QWEN35MOE, the regex-free tokenizer, `make_profile --n-layer`, the 40x256 expert profile, `pack_load_check`; notes step4-pack.md |
|
||||
| 02ff47e | integrator | step-3 notes |
|
||||
| ad70f3d..84b4756 (6) | `qwen36-step4-drafter` | `tools/mtp_qwen36_pack.py`, the qwen35moe drafter in `mtp.cpp`, prefill draft K/V, `[shared] generate.cpp` draft geometry, `qwen36_mtp_test`; notes step4-drafter.md |
|
||||
| 6d0d817..6042a32 (6, cherry-picked clean) | `qwen36-step4-runner` | the step-2 gate lifted, `[shared] verify.cpp` indexer tail, `qwen36_verify_test` + `qwen36_runner_check.py`, the llama.cpp teacher and the logits comparison, notes, the VRAM plan's drafter term |
|
||||
| 85d5d12 | `main` f07b81e | the front end's SSE keepalive and client-gone cancel (another session's patch, cherry-picked on request) |
|
||||
| e73adc6 | integrator | CMake applies the chat-parser patch at configure time (REGINA-104); `make build` turns `STRATA_MMQ_KQUANTS` on |
|
||||
|
||||
The expected `generate.cpp` conflict between the drafter's draft-geometry hunk (:3307) and the runner's gate region
|
||||
(:2184, :2557) did not occur; the three hunks sit apart.
|
||||
|
||||
## Builds and tests
|
||||
|
||||
- **VM 221, the RTX 4090**: the integrated tree at e73adc6 configures and builds with 0 errors (the common line,
|
||||
`-DSTRATA_MMQ_KQUANTS=ON`, sm_89; logs `/models/work/logs/qwen36-step4-*.log`, script `/models/work/build-step4.sh`).
|
||||
The full ctest of the integrated tree is **not** a result: 63 of 97 tests fail in under a second on
|
||||
`malloc x: out of memory`, because another session's Flash-Next service (`unbiased-strata.service`, active since
|
||||
2026-10-12 22:08 UTC) holds 23.9 of 24.5 GB. The 34 that pass are the CPU tests (`vram_plan_test`, the pack and
|
||||
planner tests, the tokenizer). Owed: the full run once the card has VRAM.
|
||||
- **VM 211, the GTX 1080 Ti**: the runner's own tree ran steps 2-4 at 21:38 UTC 2026-10-11 (step4-runner.md section
|
||||
4): verify test and runner check pass; the real-file llama.cpp comparison did not run (fixtures not synced). The
|
||||
integrated tree has not been built there: since 2026-10-12 22:04 UTC the card runs a Flash-Next coder service and
|
||||
the user has asked that it not be interrupted.
|
||||
- **The chat parser**: `make test-chat-parser MODEL=/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf BUILD_DIR=build` passes
|
||||
on VM 221 after the fix (all four argument orders).
|
||||
- **The Mac** (arm64, CUDA off): the upstream CPU expert kernel is compiled with `-mavx512*` flags unconditionally
|
||||
(CMakeLists.txt:1086), which clang rejects on arm64, so the CUDA-off Mac build has never linked past
|
||||
`strata_kernels_cpu`. Not the port's regression; the Mac configure step was used only to verify the patch logic.
|
||||
|
||||
## Numbers that carry forward
|
||||
|
||||
- Speculation with the real drafter on the 4090 (step4-runner.md, round 8): IQ3_XXS 0.77 accepted / 3.20 tokens per
|
||||
round with the full head, 0.72 / 3.05 with the subset head; Q4_K_XL (plain trunk, MTP-file draft) 0.53 / 2.54.
|
||||
- The VRAM plan's drafter share is now the whole context's K/V plus the head subset plus the ids (f2e70c8);
|
||||
`vram_plan_test` passes with the new cases.
|
||||
- Correctness held on both cards: 1080 Ti argmax 40/40 vs the Q8 oracle, 4090 teacher-forced IQ3 64/64 x3 prompts.
|
||||
|
||||
## Owed to step 5
|
||||
|
||||
1. ~~Full ctest of the integrated tree on a card with free VRAM.~~ Done 2026-10-13 once the 4090's service was
|
||||
stopped: 95 of 98 at 22d72e6 (the three host-environment failures), including the serve fixes and
|
||||
`pool_native_widths_test` of step5-serve.md.
|
||||
2. The 1080 Ti real-file comparison (sync `/models/work/qwen36-step4-teacher` to VM 211) and the Q4 fit at 11 GB.
|
||||
3. The ladder: serve and measure on 11 GB, then `--vram-cap` 8 and 6 GB; the three instruments; engine points on
|
||||
`ladder-baseline.png`; acceptance A1-A5.
|
||||
4. The step-6 fat binary, compile-checked on VM 221's CPU (`build-fat`, `/models/work/logs/qwen36-step4-fat-*.log`):
|
||||
`CUDA_ARCHS=61;70;75;86;89` with `STRATA_EXPERIMENTAL_SM60=ON` and `STRATA_MMQ_KQUANTS=ON` configures and builds
|
||||
`unbiased-strata` in 6 min 17 s at `-j 14`, 0 errors; `cuobjdump --list-elf` shows 62 ELF images per architecture
|
||||
for all five; 235 MiB. **sm_120 cannot come from this host**: CUDA 12.4's nvcc rejects `compute_120`
|
||||
("Unsupported gpu architecture"); Blackwell needs a 12.8+ toolkit, so the step-6 release build either uses a newer
|
||||
toolkit or ships 120 as PTX from 89. Nothing in this binary has run on a card yet.
|
||||
@@ -1,209 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 4, area `pack`: the native pack
|
||||
|
||||
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step4-pack`, from the step-3 integration
|
||||
branch `qwen36-step3` at c6fa016). The design is `docs/QWEN36-35B-A3B.md` 3.7, 3.8, 3.11 and section 6 (step 4);
|
||||
what the engine reads is `docs/qwen36-port/step3-block.md`, `step3-gdn.md`, `step3-attn.md`, `step3-prefill.md`;
|
||||
the census that decided the forms is `step3-gdn.md` section 3. This file is the contract the drafter and runner
|
||||
agents consume: section 2 is the pack's layout, exactly; section 5 is how the engine loads it and what was verified
|
||||
on both cards.
|
||||
|
||||
## 1. What changed
|
||||
|
||||
| Where | What | Why |
|
||||
| --- | --- | --- |
|
||||
| `tools/iq_pack.py` | `FORM_QWEN35MOE` beside Flash-Next's `FORM` (`FORMS[arch]`, `form_of(name, arch)`); `NATIVE_PROJECTIONS_QWEN35MOE` / `NATIVE_PROJECTION_TYPES` / `NATIVE_EMBED_TYPES` with `native_type_problem`; the draft block (`blk.<trunk>` and up) left out of `index.txt` and `dense.bin` (`n_trunk`); the inexact-BF16 refusal carries the count; `--expert-profile` (default `data/qwen36-expert-profile.bin` for qwen35moe) copied in as `expert-profile.bin` after a header check | the study's step 4 line; "a second entry, not a rewrite": a toy Flash-Next model with every FORM tensor kind packs byte-identically with the step-3 and the step-4 packer (all six files, checked) |
|
||||
| `tools/test_iq_pack.py` | `write_gguf(..., architecture=)`; `Qwen36PackTests`: the forms and `index.txt`'s contents, the count in the refusal and `--compat-bf16`'s rounding, the native types refused by name (projection, head, embedding each with its list), the nextn block left out, the profile checked and copied, the Flash-Next table untouched | the brief's fixtures |
|
||||
| `tools/make_profile.py`, `test_make_profile.py` | `--n-layer` (the base's header decides when given), `--text-trace` for llama.cpp eval-callback route traces (`<layer> <e0> ... <e7>` lines, `#` headers, `.gz`), `profile_header` | `N_LAYER = 48` was the study's row; the E0 trace is text |
|
||||
| `data/qwen36-expert-profile.bin` | the 40 x 256 ranking from the E0 trace (section 3) | shipped in every Qwen3.6 pack |
|
||||
| `tools/strata_tokenizer.py` | `regex` imported if present; `extract` needs no pattern, `encode` refuses by name without it | neither VM's system python has `regex`, and the packer runs the export as a subprocess |
|
||||
| `src/core/layout.cpp` (`[shared]`) | `check_one` skips the four `indexer.*` rows when `!g.has_indexer()` | they were still required of every attention layer at hc = 1 (step3-block.md section 7 said so): every Qwen3.6 pack would have been refused "missing blk.3.indexer.q_proj.weight" |
|
||||
| `src/program/generate.cpp` | `native_dense.load(..., 0, g.n_layers)` | a -MTP file's `blk.40` carries the projection names; it is not in the trunk's pack and `NativeDense::load` refuses a name absent from the table. A no-op for Flash-Next |
|
||||
| `tests/core/pack_load_check.cpp`, `CMakeLists.txt` | the pack loaded as `generate` loads it after the gate (section 5) | the gate fires before any of those loads |
|
||||
|
||||
Not needed, and why: `--compat-bf16` for the real files (section 2: 140 of 140 conversions exact, max error 0);
|
||||
any change to `weights.cpp` (index kinds 4 and 2 were already the raw-BF16 and F32 paths), `native_dense.cpp`
|
||||
(every projection type of both files is in `native_mmvq_supported`), `native_head.cpp` or the embedding (Q6_K /
|
||||
Q8_0 are in both lists), `expert_layout.cpp` (v3 at 2048 x 512 since step 2).
|
||||
|
||||
## 2. The pack, exactly
|
||||
|
||||
Built by `python3 -I tools/iq_pack.py --gguf <file>.gguf --out <dir>` from a single-shard qwen35moe GGUF
|
||||
(both shipped files are single shards; a split would name its shards in `native_experts.txt` as for Flash-Next).
|
||||
Six entries:
|
||||
|
||||
| File | Contents |
|
||||
| --- | --- |
|
||||
| `index.txt` | "strata pack index v3", `# align 64 pool <arena bytes> tensors 613`, then one row per non-expert trunk tensor: `name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias group_elems codebook has_offset codes_bytes scales_bytes offset_bytes scales_fp16 act_kind` (19 fields; `file` 0 = dense.bin). Kinds: **4** = raw BF16 in dense.bin (the loader's `Bf16InF32` form, copied), **2** = F32 copied, **0** with `code_bits 8 group_elems 32` and every byte count 0 = served natively from the GGUF (shape only; the loader refuses to read such a row, `NativeDense` / the head / the embedding attach it). `dst_off` is the running 64-aligned arena offset; a native row carries the current offset with 0 bytes. |
|
||||
| `dense.bin` | the kind-4 and kind-2 tensors at their `src_off`, each padded to 64 B: **54,610,432 B** for both files (byte-identical between IQ3_XXS, the plain Q4_K_XL and the MTP Q4_K_XL: md5 `096a0d6e140c3ac412b2f9542eb3c335`; the float tensors are the same in every quant, as they were for Flash-Next) |
|
||||
| `native_experts.txt` | v3, one line per trunk layer `layer gu_type d_type offset blob_bytes gate_off up_off down_off` (absolute byte offsets of the three expert tensors in the GGUF), header `(n_expert 256, total <bytes>; absolute offsets in <file>)`; 40 lines, the nextn block excluded. The IQ3_XXS table equals `tests/data/native_experts/qwen36-iq3_xxs.txt` byte for byte; the MTP Q4_K_XL table equals `qwen36-q4_k_xl.txt` up to the file name in the header. |
|
||||
| `conversions.json` | schema 1: the 140 F32 -> BF16 records (`exact: true`, `max_abs_err 0.0`, the source bytes' SHA-256), `compat_bf16: false` |
|
||||
| `expert-profile.bin` | `STRP`, version 1, 40 x 256, 10,240 ranked `(layer, expert)` u16 pairs then the 40 x 256 slot table: 81,944 B (section 3) |
|
||||
| `tokenizer/` | `vocab.json` (248,320), `merges.txt` (247,587), `token_type.json`, `tokenizer.json` (`pre: qwen35`, the shipped pattern, `add_bos_token false`, eos 248046 / pad 248055 / bos 248044), `chat_template.jinja` (8,057 B, the file's own) |
|
||||
|
||||
The 613 rows, per tensor (the suffix after `blk.N.`; shapes as GGUF `ne0 x ne1`, ne0 contiguous):
|
||||
|
||||
| Tensor | Layers | Index kind, form in the arena | Shape | Engine site that reads it (form it demands) |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `attn_norm.weight`, `post_attention_norm.weight` | all 40 | 2, F32 (8,192 B) | 2048 | `plain_block_pre` / verify `plain_w` / prefill `rms_norm_images`: `const float*`, `WeightKind::F32`, `n_embd` elements |
|
||||
| `ffn_gate_inp.weight` | all 40 | 4, BF16 (1,048,576 B) | 2048 x 256 | `moe_route` (`bf16_gemv_fp32_mmvf`), prefill `bf16_proj`: `Bf16InF32` |
|
||||
| `ffn_gate_inp_shexp.weight` | all 40 | 4, BF16 (4,096 B) | 2048 (1-D) | `moe_shared`, verify, prefill: `Bf16InF32`, `n_embd` elements (the one 1-D BF16 tensor) |
|
||||
| `ffn_gate_shexp`, `ffn_up_shexp`, `ffn_down_shexp` | all 40 | 0, native (Q6_K in IQ3_XXS, Q8_0 in Q4_K_XL) | 2048 x 512, 2048 x 512, 512 x 2048 | `moe_shared` through `NativeSharedWeights` (`native_data`, `native_type`) |
|
||||
| `attn_qkv.weight`, `attn_gate.weight`, `ssm_out.weight` | 30 GDN | 0, native (Q6_K / Q8_0) | 2048 x 8192, 2048 x 4096, 4096 x 2048 | `gdn_layer` (`native_mmvq` through `w.native_data`), verify, prefill |
|
||||
| `ssm_alpha.weight`, `ssm_beta.weight` | 30 GDN | 4, BF16 (131,072 B each) | 2048 x 32 | `gdn_layer` (`fused_gdn_ab`), prefill `bf16_proj`: `Bf16InF32` |
|
||||
| `ssm_conv1d.weight` | 30 GDN | 2, F32 (131,072 B) | 4 x 8192 | `gdn_layer`: `const float*` (`ssm_d_conv x ssm_conv_channels`) |
|
||||
| `ssm_a`, `ssm_dt.bias` | 30 GDN | 2, F32 (128 B each) | 32 | `gdn_layer`: `const float*` (`ssm_v_heads`) |
|
||||
| `ssm_norm.weight` | 30 GDN | 2, F32 (512 B) | 128 | `gdn_layer` / `gdn_out_norm`: `const float*` (`ssm_state_size`) |
|
||||
| `attn_q.weight`, `attn_k.weight`, `attn_v.weight`, `attn_output.weight` | 10 attention | 0, native (Q6_K / Q8_0) | 2048 x 8192, 2048 x 512, 2048 x 512, 4096 x 2048 | `qsa_layer` (`gemv_quantized` takes the native path), verify, prefill |
|
||||
| `attn_q_norm.weight`, `attn_k_norm.weight` | 10 attention | 2, F32 (1,024 B) | 256 | `qsa_layer` `normalize_rotate`: `const float*` (`head_dim`) |
|
||||
| `output_norm.weight` | once | 2, F32 (8,192 B) | 2048 | `lm_head_mix` / verify's head: `WeightKind::F32`, `n_embd` |
|
||||
| `output.weight` | once | 0, native (Q6_K / Q8_0) | 2048 x 248320 | `NativeHead::load` from the GGUF (`native_mmvq`); the index row gives `n_vocab = ne1` |
|
||||
| `token_embd.weight` | once | 0, native (Q6_K / Q8_0) | 2048 x 248320 | `NativeEmbed::load` from the GGUF into mapped host memory (`iq_embed_rows`) |
|
||||
|
||||
Counts: 252 native rows (30 x 3 + 10 x 4 + 40 x 3 + 2), 140 BF16 rows, 221 F32 rows; 613 in all. The arena
|
||||
(`dense.bin` as loaded, every tensor at its `dst_off`) is 54,610,432 B.
|
||||
|
||||
**The types the native paths accept** (`native_type_problem`): projections and the head, `native_mmvq_supported`:
|
||||
Q4_0, Q5_0, Q5_1, Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL, IQ4_XS, Q2_0, IQ2_XXS, IQ2_XS, IQ3_XXS, IQ3_S, IQ2_S,
|
||||
IQ1_M; the embedding, `embed_type_supported` (the `is_iq` set plus BF16): the same minus Q4_0, plus BF16. Any
|
||||
other type on one of those names (F32, F16, Q4_1, Q2_K, IQ1_S, ...) is refused before anything is written, naming
|
||||
the tensor, the type, the path and the list. The head also needs `n_embd % 256 == 0` (2048: yes).
|
||||
|
||||
**The BF16 rule.** The 140 F32 tensors read as BF16 (40 routers, 40 shexp gates, 30 `ssm_alpha`, 30 `ssm_beta`)
|
||||
have their low 16 bits zero in every element of both files, as `step3-gdn.md` found: written as BF16 exactly,
|
||||
`conversions.json` records 140 exact / 0 rounded / max error 0, no `compat-bf16.json`. A file where that fails is
|
||||
refused with "`<name>` is F32 with N of M values that are not BF16 (low 16 bits set), but the engine reads it as
|
||||
BF16; --compat-bf16 would round them to nearest-even (a lossy pack, recorded in compat-bf16.json)". `ssm_conv1d`
|
||||
is BF16-exact too but the engine reads it as F32, so it is copied. `attn_norm` is not BF16-exact (17%) and is
|
||||
F32.
|
||||
|
||||
**The nextn block.** A -MTP file (`nextn_predict_layers 1`, 41 blocks) has `blk.40.*`: an attention layer plus
|
||||
MoE (its routers BF16, not F32) and `blk.40.nextn.{eh_proj,enorm,hnorm,shared_head_norm}.weight`. 17 non-expert
|
||||
tensors; none of them, and none of its three expert tensors, is in the trunk's pack. The drafter's pack is the
|
||||
drafter agent's (`tools/mtp_qwen36_pack.py` per the study).
|
||||
|
||||
## 3. The expert profile
|
||||
|
||||
`python3 -I tools/make_profile.py --no-base --n-layer 40 --n-expert 256 --text-trace
|
||||
~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/routes/routes.txt --out data/qwen36-expert-profile.bin`
|
||||
(the Mac, 14.6 s). The raw `routes.txt` (269 MB, also as `.gz`) was present and used: the E0 trace of the IQ3_XXS
|
||||
file through llama.cpp 3cf0325 on the M3 Ultra, 214,940 routed tokens (143,091 prefill, 71,849 decode) over the
|
||||
110-prompt corpus (`README.md`, `summary.json` beside it). Every one of the 10,240 (layer, expert) pairs was routed
|
||||
at least once (mean entropy 7.37 of 8 bits), so the ranking is wholly from the trace: 10,240 from the trace, 0
|
||||
filled. The ranking is by count, ties broken by the smaller pair. `read_expert_profile` reads it back on both cards
|
||||
(section 5).
|
||||
|
||||
## 4. Build and test commands
|
||||
|
||||
Python (the Mac, `STRATA_GGUF_PY` at the main tree's gguf-py; VM 221 and VM 211 with their own):
|
||||
|
||||
python3 -m unittest tools.test_iq_pack tools.test_make_profile # 41 tests: 33 + 8 new, all three hosts
|
||||
python3 -I tools/iq_pack.py --gguf /models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --out /models/work/packs/qwen36-iq3
|
||||
|
||||
The engine (both cards, the common configure with `-DSTRATA_MMQ_KQUANTS=ON`, the 1080 Ti with
|
||||
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`):
|
||||
|
||||
cmake --build build -j 8 --target strata pack_load_check expert_layout_test model_geometry_test
|
||||
./build/pack_load_check --native <file>.gguf --pack <dir> # section 5
|
||||
./build/strata --native <file>.gguf --pack <dir> --tokens 1 --max-context 262144 --kv q4_0 --spec 4 \
|
||||
--prefill 2048 --expert-profile <dir>/expert-profile.bin # to the step-2 gate, exit 2
|
||||
|
||||
## 5. Results
|
||||
|
||||
### The packs (both VMs, 2026-10-11)
|
||||
|
||||
| Host, file | Pack | Time | `dense.bin` | rows / native / BF16 exact | expert table |
|
||||
| --- | --- | ---: | ---: | --- | --- |
|
||||
| VM 221, `/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` | `/models/work/packs/qwen36-iq3` | 1.9 s | 54,610,432 B | 613 / 252 / 140 of 140 | == `tests/data/native_experts/qwen36-iq3_xxs.txt`; 11,108,614,144 B of experts |
|
||||
| VM 221, `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (the plain 40-block file: VM 221's Q4_K_XL is NOT the MTP repo's, see 7) | `/models/work/packs/qwen36-q4` | 2.6 s | same bytes | 613 / 252 / 140 of 140 | 19,671,285,760 B; Q6_K down on layers 1, 34, 38, 39 (the plain file has one more Q6_K layer than the MTP file's 34, 38, 39) |
|
||||
| VM 221, `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL-MTP.gguf` (copied from the Mac, sha256 55983c5a..., 22,853,663,008 B, 41 blocks) | `/models/work/packs/qwen36-q4-mtp` | 2.4 s | same bytes | 613 / 252 / 140 of 140; 17 draft tensors left out | == `qwen36-q4_k_xl.txt` up to the file name; 19,635,634,176 B |
|
||||
| VM 211, `/home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` | `/home/rk/packs/qwen36-iq3` | 2.6 s | same bytes | 613 / 252 / 140 of 140 | == `qwen36-iq3_xxs.txt` |
|
||||
| VM 211, `/home/rk/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (the MTP repo's file, 41 blocks) | `/home/rk/packs/qwen36-q4` | 2.5 s | same bytes | 613 / 252 / 140 of 140; 17 draft tensors left out | == `qwen36-q4_k_xl.txt` |
|
||||
|
||||
The pack is 65 MB (dense 52.1 MiB, tokenizer 9.4 MiB, the rest under 200 KB); nothing of the experts or the
|
||||
projections is copied. `python3 -m unittest tools.test_iq_pack tools.test_make_profile`: 41 of 41 on the Mac,
|
||||
VM 221 (numpy 2.2.4) and VM 211.
|
||||
|
||||
### VM 221, the RTX 4090 (sm_89), 2026-10-11
|
||||
|
||||
Build (`/models/work/qwen36-step4-pack`, the four targets after a fresh configure): 2 min 14 s.
|
||||
`./build/pack_load_check --native FILE --pack DIR` (`/models/work/logs/qwen36-step4-check-*.log`):
|
||||
|
||||
| Pack | arena | native projections | head | embedding (mapped) | check_all | profile | exit |
|
||||
| --- | ---: | ---: | ---: | ---: | --- | --- | --- |
|
||||
| qwen36-iq3 | 54,610,432 B, read 11 ms + upload 7 ms | 250 matrices, 1,152,614,400 B (1,099 MiB), 1.8 s | Q6_K 417,177,600 B | Q6_K 417,177,600 B | 40 layers (10 + 30) ok | 10,240 pairs | 0 (3.1 s) |
|
||||
| qwen36-q4 | same | 250, 1,492,910,080 B (1,424 MiB), 3.2 s | Q8_0 540,344,320 B | Q8_0 540,344,320 B | ok | 10,240 | 0 (5.8 s) |
|
||||
| qwen36-q4-mtp | same; 259 names in the skip set (the 7 of `blk.40` are not in the index: harmless) | 250 (blk.40's not loaded: the trunk bound), 1,424 MiB | Q8_0 | Q8_0 | ok | 10,240 | 0 (2.4 s) |
|
||||
|
||||
Every weight of section 2's table resolves on every layer with the form its site demands (the log lists layers 0
|
||||
and 3 in full and reports any miss on the other 38: none). The gate run,
|
||||
`./build/strata --native FILE --pack DIR --tokens 1 --max-context 262144 --kv q4_0 --spec 4 --prefill 2048
|
||||
--expert-profile DIR/expert-profile.bin` (`qwen36-step4-gate-*.log`): the geometry (31 lines), the VRAM plan
|
||||
(IQ3_XXS: fixed set 4,019 MiB = weights 1,596 + drafter 520 + KV 1,440 + session 162 + reserve 300; 10,240 of 10,240
|
||||
slots resident at 19,729 MiB; 9,135 MiB spare), the step-2 gate message, exit 2, for both the IQ3_XXS and the MTP
|
||||
Q4_K_XL file; no "missing", "wrong form" or other refusal in the 42 lines. `ctest -R "pack_load_check|
|
||||
expert_layout_test"` with `STRATA_QWEN36_GGUF` / `STRATA_QWEN36_PACK` set: 2 of 2.
|
||||
|
||||
### VM 211, the GTX 1080 Ti (sm_61, Pascal), 2026-10-11, under `/home/rk/VM-BUSY`
|
||||
|
||||
The same tree (`/home/rk/qwen36-step4-pack`, the submodule copied from the step-3 tree), configured with
|
||||
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`; the four targets built in 3 min 22 s.
|
||||
`./build/pack_load_check` (`logs/check-*.log`):
|
||||
|
||||
| Pack | arena | native projections | head | embedding | check_all | profile | exit |
|
||||
| --- | ---: | ---: | ---: | ---: | --- | --- | --- |
|
||||
| `/home/rk/packs/qwen36-iq3` | 54,610,432 B, read 54 ms + upload 12 ms | 250, 1,099 MiB, 1.7 s | Q6_K 417,177,600 B, 0.5 s | Q6_K, 0.8 s | ok | 10,240 | 0 (3.5 s) |
|
||||
| `/home/rk/packs/qwen36-q4` (the MTP file) | same | 250, 1,424 MiB, 2.1 s | Q8_0 540,344,320 B, 0.9 s | Q8_0, 1.2 s | ok | 10,240 | 0 (4.7 s) |
|
||||
|
||||
The gate run (`logs/gate-*.log`), both packs: the geometry, the VRAM plan, the gate message, exit 2, no refusal.
|
||||
The plan on the 11 GB card: IQ3_XXS fixed set 4,019 MiB, 6,744 of 10,240 slots (65%) resident at 6,977 MiB;
|
||||
Q4_K_XL fixed set 4,461 MiB (weights 2,038), 3,573 slots (34%) at 6,535 MiB. `expert_layout_test` all passed;
|
||||
`ctest -R "pack_load_check|expert_layout_test"` 2 of 2. The lock was held from 20:50 to 20:58 UTC (sync and
|
||||
packs done beforehand without it: they touch neither the card nor the build cores for more than seconds).
|
||||
|
||||
## 7. Not done, surprises, what the brief and the study had differently
|
||||
|
||||
- **The gate is before the loads.** `generate.cpp`'s step-2 gate (line 2253) returns before the arena (2510),
|
||||
the native projections (2520), the head (3282) and the embedding (2424) are touched, so "load every dense weight
|
||||
... through to the gate" cannot be shown by the gate run alone: `pack_load_check` does those loads in the same
|
||||
order and is the evidence; the gate run shows the start reaches the gate with the pack in place. The
|
||||
gate-lifting agent gets section 6's order, including `check_all`, which `generate.cpp` has never called (the
|
||||
per-layer shape check exists since round 194 and only the parity binaries call it).
|
||||
- **VM 221's `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` is the plain 40-block file** (733 tensors, 22,360,456,160 B,
|
||||
no `nextn_predict_layers`), not the MTP repo's as the common file said; the MTP repo's Q4_K_XL (41 blocks, sha256
|
||||
`55983c5a...`, the file on VM 211 and the Mac, and the one `tests/data/native_experts/qwen36-q4_k_xl.txt` and the
|
||||
plan's "Q4 number" refer to) was copied to VM 221 as `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL-MTP.gguf` (rsync from the
|
||||
Mac, 3 min 40 s), so the drafter has `blk.40` on the development card. The two files are different quantization
|
||||
runs: the plain one has Q6_K down on layers 1, 34, 38, 39 and a 35.6 MB larger expert total.
|
||||
- **Neither VM's python has `regex`** (PEP 668 refuses `pip install` on VM 221; VM 211 has no pip), hence the lazy
|
||||
import in `strata_tokenizer.py`. The export is exact without it; `encode` needs it.
|
||||
- **`check_one` still demanded the indexer rows at hc = 1** (the attention agent's note said the four tensors "are
|
||||
required only with an indexer", which was true of `qsa_layer` and the window but not of `layout.cpp`). Fixed
|
||||
here, `[shared]`.
|
||||
- **The study's step-4 line** had the routers and the SSM gates "F32 to BF16 under `--compat-bf16` with
|
||||
`compat-bf16.json`"; the census (step3-gdn.md) made that moot and the packs carry no `compat-bf16.json`.
|
||||
`step2-notes.md` section 3 ("need `--compat-bf16` today, which step 4 decides") is superseded: decided, not needed.
|
||||
- **`ModelGeometry::n_vocab`** is the Flash-Next default (248,320, which happens to be Qwen3.6's too); the head and
|
||||
the embedding are sized from `output.weight`'s index row, as `generate.cpp` does.
|
||||
- Not mine, not done: lifting the gate, the verify window and the first token through this pack, the drafter's pack
|
||||
from `blk.40`, the chat template check, `generate.cpp` beyond the one-argument dense-load bound.
|
||||
|
||||
## 6. The interface other agents consume
|
||||
|
||||
- The pack layout of section 2, file by file and row by row. A consumer resolves a tensor by name through
|
||||
`WeightTable::find`; a native row has `data == nullptr`, `resident == false` after the skip-set load, and
|
||||
`native_data` / `native_type` after `NativeDense::load`; `output.weight`'s row is shape only and the head is
|
||||
`NativeHead`; `token_embd.weight` is `NativeEmbed`.
|
||||
- The load order the gate-lifting agent keeps (it is `generate.cpp`'s after the gate, and `pack_load_check.cpp`'s):
|
||||
`read_model_geometry` -> `check_model_tensor_forms` -> `expert_layout_load(pack, n_layers, n_expert, n_embd, n_ff)`
|
||||
-> `NativeDense::served_names(shards, false, skip)` + `output.weight` + `token_embd.weight` -> `pool_bytes(pack,
|
||||
&skip)` -> `WeightTable::load(pack, arena, pool, &skip)` -> `NativeDense::load(shards, wt, err, false, 0,
|
||||
n_layers)` -> `check_all(wt, g, err)` (generate.cpp does not call it today; it should, after the dense load) ->
|
||||
`NativeHead::load(shards, n_embd, wt.find("output.weight")->ne1)` -> `NativeEmbed::load(shards, n_embd, n_vocab)`
|
||||
-> `read_expert_profile(pack + "/expert-profile.bin", n_layers, n_expert, ...)`.
|
||||
- `tools/iq_pack.py`: `form_of(name, arch)`, `needs_bf16(name, type, arch)`, `native_type_problem(name, type, arch)`,
|
||||
`layer_of(name)`, `profile_problem(path, n_layers, n_expert)`, `index_standalone(src, out, model, compat_bf16,
|
||||
n_trunk)`, `model_arch(model)`; `main` takes `--expert-profile`.
|
||||
- `tools/make_profile.py`: `read_profile(path, n_expert, n_layer)`, `read_text_trace(path, n_expert, n_layer)`,
|
||||
`write_profile(path, ranked, n_expert, n_layer)`, `profile_header(path)`, `rank_profile(..., n_layer=)`.
|
||||
- `tests/core/pack_load_check.cpp`: `pack_load_check --native FILE --pack DIR` (or `STRATA_QWEN36_GGUF` /
|
||||
`STRATA_QWEN36_PACK`), exit 0 / 1 / 77.
|
||||
@@ -1,195 +0,0 @@
|
||||
# Qwen3.6 port, Phase 2 step 4, area `runner`: the gate lifted, the first token held to the oracle and llama.cpp
|
||||
|
||||
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step4-runner`, from the step-4 integration
|
||||
branch `qwen36-step4` = step 3 complete + the pack). The design is `docs/QWEN36-35B-A3B.md` sections 3.5 and 6
|
||||
(step 4) and 3.5; what the pack carries is `docs/qwen36-port/step4-pack.md` (section 2 the layout, section 6 the load
|
||||
order); the references are `docs/qwen36-port/oracle-crosscheck.md` (the cases, the tolerance policy, the quantized-mode
|
||||
gates). This file is the runner half; the drafter is `qwen36-step4-drafter` (mtp.cpp, blk.40), not touched here.
|
||||
|
||||
## 1. What this makes the engine do
|
||||
|
||||
With `--native <qwen35moe gguf> --pack <dir>` the start no longer stops at the step-2 gate
|
||||
(`qwen35moe_not_yet`). It makes and prints the VRAM plan as before, then proceeds through the native pack's load
|
||||
order, the session at hc = 1 with no PLE and no indexer, the expert tiers the plan sized, the prompt path, and the
|
||||
decode windows, and produces tokens. Measured on the real IQ3_XXS file (VM 221, the 4090), the first token of
|
||||
"Hello, world! How are you?" (ids 9419,11,1814,0,2500,513,488,30) is 271, and the 16 greedy tokens that follow are
|
||||
coherent English; the engine's own greedy continuation of the test20 prompt is byte-identical to llama.cpp's.
|
||||
|
||||
`--spec 0` / no drafter: the decode windows hold one token each (a window padded with token 0 would verify a draft
|
||||
nobody made). A native-pack start with `--spec` below 2 raises it to 2 (the verifier's smallest window) and says so;
|
||||
the drafter plugs in at `generate.cpp`'s `--mtp DIR` block (the `mtp.draft` / `mtp.draft_first` calls in the spec
|
||||
loop), which is the drafter agent's.
|
||||
|
||||
## 2. What changed, where (file:line against `qwen36-step4`)
|
||||
|
||||
`generate.cpp` is shared with the drafter agent; every hunk below is in the gate region, the load order, or the
|
||||
session/decode wiring, in its own commit.
|
||||
|
||||
| Site | What | file:line |
|
||||
| --- | --- | --- |
|
||||
| the gate | the step-2 gate removed: the qwen35moe block now prints the plan, refuses a plan that does not fit (exit 2), and for a drafter-off start raises `--spec` to 2; it no longer returns at `qwen35moe_not_yet` | `generate.cpp` the `if (g.arch == Qwen35Moe)` block at ~2175 and the drafter-off note at ~2246-2258 |
|
||||
| the load order | `check_all(wt, g)` after `NativeDense::load`, which `generate.cpp` had never called (step4-pack.md section 6): a pack missing a row or carrying it in the wrong form is refused by name before the first window | `generate.cpp:2532` (after the native projections) |
|
||||
| the runner | `--teacher-force` (with `--spec-oracle FILE`): every window row commits, the next window starts from the oracle's token, `--dump-logits` writes one row of head logits per position (the window path wrote none), and the run reports the top-1 agreement | `generate.cpp` option 495, flag 1462, usage 671, validation 1910, oracle-length clamp 8128, the window loop 8305-8480 |
|
||||
| the drafter-off path | one token per window when there is no drafter and no oracle; `--suffix-draft` skipped under teacher forcing | `generate.cpp:8326-8333` |
|
||||
| `[shared]` verify | the two commit captures skip the indexer key-tail restore when `!g.has_indexer()`: a dense model has no tail, and the first real-file window stopped at "blk.3.indexer.k_norm.weight is missing" after the window had already run | `verify.cpp` `capture_commit` ~1407, `capture_commit_batch` ~1957 |
|
||||
|
||||
The Flash-Next path is untouched: the generate.cpp hunks are guarded by `g.arch == Qwen35Moe` or by the native-pack
|
||||
/ teacher-force conditions, and the verify.cpp change is guarded by `!g.has_indexer()`. The step-3 parity suite is
|
||||
re-run below as the regression proof.
|
||||
|
||||
## 3. The tests (CMake targets)
|
||||
|
||||
`cmake/` nothing new; the fixtures are python, in `tests/python/`.
|
||||
|
||||
- **`qwen36_runner_fixture.py`** writes the synthetic model at the real per-layer geometry (the prefill harness's
|
||||
`full4`: 4 layers, three Gated DeltaNet and one full attention, n_embd 2048, GDN 16/32 heads of 128, attention
|
||||
16/2 of 256, 16 experts top-8 of 512) as a file a native pack can be built from (`token_embd.weight` Q8_0, a type
|
||||
`iq_embed_rows` serves), builds the pack with `tools/iq_pack.py` and a 4 x 16 expert profile ranking every pair,
|
||||
and dumps the oracle for the 8-, 11- and 40-token cases both faithfully (`oN`) and with `--act-quant q8`
|
||||
(`oN_q8`), each with `--all-logits`.
|
||||
- **`qwen36_verify_test.cpp`** (CTest `qwen36_verify_test`, fixture `qwen36_runner_fixtures`) drives `Verifier` on
|
||||
that pack as `generate` drives it (the load order, `check_all`, the decode config `layer_verify_compatible`
|
||||
requires, the cache holding every expert), the step-3 review's HIGH finding (no test drove the window on
|
||||
qwen35moe). Four parts: one 8-token window's residual after every layer and its head logits per row; the same
|
||||
rows from eight one-token windows, **bit for bit** equal to the 8-row window (verify.hpp's discipline); 8 + 3
|
||||
with a commit between; 40 tokens one per window (the oracle's `base_ar` shape).
|
||||
- **`qwen36_runner_check.py`** (CTest `qwen36_runner_check`) drives the `strata` binary end to end: the 40-token
|
||||
sequence teacher-forced to the oracle in three chunkings (the oracle's `base_c7`, one chunk, and `base_ar`),
|
||||
`--dump-logits` per position, and the **mutation-sensitivity gate** (4 KB of `blk.1.ffn_gate_inp.weight` flipped
|
||||
in a copy of dense.bin must move the logits by more than 1e-2 relative L1).
|
||||
- The real files: **`tools/qwen36_teacher_llama.cpp`** is llama.cpp's own greedy continuation with the head's
|
||||
logits per position and the routed experts at probed layers; **`tools/qwen36_compare_logits.py`** is top-1
|
||||
agreement, KL(ref || engine) per position, the drift gate (one-sided: only a KL that *rises* with position is a
|
||||
leaking state) and the routed-selection overlap. `ref/qwen36.py` grew `--all-logits` (dump
|
||||
`result_output_all`, the head at every position); `qwen36_prefill_fixture.py`'s `write` grew `q8_embd`.
|
||||
|
||||
### Tolerances
|
||||
|
||||
The oracle is F32 weights x F32 activations; the engine runs Q8_0 projections (FP16 GEMV with q8_1 activations) and
|
||||
Q8_0 experts on int8 dot products, so the reference for the window and runner tests is the **Q8 oracle**
|
||||
(`--act-quant q8`, oracle-crosscheck.md "Tolerance policy" items 3-4). Per-layer forced (the input forced from the
|
||||
Q8 oracle's `l_out` of the layer before): 1.5e-2 relative L2 (4x the real file's Q8 `l_out` class, the fixture's
|
||||
16-expert MoE spreads more). Accumulated over the 4 layers and the recurrence: 5e-2. Argmax must agree with the
|
||||
Q8 oracle at every position; positions where the F32 and Q8 oracles themselves disagree (near ties) are reported,
|
||||
not gated.
|
||||
|
||||
## 4. Results
|
||||
|
||||
### VM 221, the RTX 4090 (sm_89), 2026-10-11
|
||||
|
||||
Build: the common configure with `-DSTRATA_MMQ_KQUANTS=ON`, 25 min for the whole tree, 0 errors.
|
||||
|
||||
**`qwen36_verify_test`** (the synthetic native pack, 4 layers, 16 experts, every expert resident): PASS, 0 failures.
|
||||
|
||||
| check | measured | gate |
|
||||
| --- | --- | --- |
|
||||
| 8-token window, `l_out-N` per row accumulated vs the Q8 oracle | 1.9e-3 .. 2.4e-2 | 5e-2 |
|
||||
| each layer alone, input forced from the Q8 oracle, `l_out-N` | 1.1e-3 .. 3.1e-3 | 1.5e-2 |
|
||||
| eight one-token windows vs the 8-row window (R and logits) | 0.0 (bitwise) | bitwise |
|
||||
| 8 + 3 with a commit, `l_out-3` / logits per position (11) vs Q8 | 2.4e-2 / 2.7e-2 | 5e-2 |
|
||||
| 40 one-token windows, `l_out-3` / logits per position vs Q8 | 3.5e-2 / 3.5e-2 | 5e-2 |
|
||||
| argmax vs the Q8 oracle (8 / 11 / 40 positions) | 8/8, 11/11, 40/40 | equal |
|
||||
|
||||
(Against the F32 oracle the 40-token argmax differs at 3 near-tie positions where the F32 and Q8 oracles disagree.)
|
||||
|
||||
**`qwen36_runner_check`** (the `strata` binary, teacher-forced): PASS, 0 failures. Logits per position vs the Q8
|
||||
oracle: `c7` 2.7e-2, `c40` 2.3e-2, `ar` 4.4e-2 (all <= 5e-2); argmax equal at every unambiguous position (the `ar`
|
||||
run has 3 near-tie positions excluded, the same 1/4/23); the two prompt chunkings agree (1.4e-2), prompt vs decode
|
||||
agree (2.1e-2); **the 4 KB mutation moves the logits by 2.1e-1 relative L1** (> 1e-2).
|
||||
|
||||
**The real files, greedy, teacher-forced to llama.cpp's own greedy continuation** (3 prompts from the regina
|
||||
corpus x 64 tokens, context 8192, `--kv fp16`, the full profile-filled cache):
|
||||
|
||||
IQ3_XXS on the 4090:
|
||||
|
||||
| prompt | top-1 agreement | mean KL | max KL | drift (Spearman) |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| test20 | 64 / 64 | 1.1e-3 | 2.1e-2 | -0.63 (falls) |
|
||||
| task-prime-add-test | 64 / 64 | 6.6e-3 | 1.5e-1 (one near tie) | +0.12 (flat) |
|
||||
| task-psim-collide | 64 / 64 | 1.9e-3 | 1.8e-2 | -0.06 (flat) |
|
||||
|
||||
No monotone positional drift on any prompt (Maya's quantized-mode gate: the drift is one-sided; a falling or flat
|
||||
KL is not a leaking state). The engine's own greedy text for test20 is byte-identical to llama.cpp's (the
|
||||
qualitative check). Q4_K_XL on the 4090 (the plain 40-block file, pack `qwen36-q4`):
|
||||
|
||||
| prompt | top-1 agreement | mean KL | max KL | drift (Spearman) |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| test20 | 61 / 64 (3 near-tie quant flips) | 7.4e-3 | 1.5e-1 | -0.57 (falls) |
|
||||
| task-prime-add-test | 64 / 64 | 1.7e-3 | 3.5e-2 | -0.08 (flat) |
|
||||
| task-psim-collide | 64 / 64 | 4.2e-4 | 7.2e-3 | -0.20 (falls) |
|
||||
|
||||
The 1080 Ti was not used for the Q4 fit (the card was under a sibling's lock); the 4090 Q4 run is `--expert-cache
|
||||
auto`, the whole file resident.
|
||||
|
||||
The step-3 parity suite, re-run to prove the Flash-Next path and the kernels are unchanged by the gate lift and the
|
||||
`[shared]` verify edit (`ctest -R` over qsa_parity, qsa_prompt_attn_parity, kv_hybrid_parity, kv_stream_parity,
|
||||
qsa_topk_parity, qsa_dense_parity, gdn_parity, router_top10_parity, shared_expert_parity, qwen36_seam_parity,
|
||||
qwen36_block_test, prefill_qwen36, native_expert_parity): **100% of 33 tests passed, 0 failed** (pack_load_check
|
||||
skipped, it needs the real-file STRATA_QWEN36_GGUF / _PACK env). Every step-3 parity target and both new runner
|
||||
tests pass; the Flash-Next geometry's parity is unchanged.
|
||||
|
||||
### VM 211, the GTX 1080 Ti (sm_61), 2026-10-11 21:38-21:42 UTC
|
||||
|
||||
Run after the notes above were first written, once the card's lock freed (held by sibling agents with nothing
|
||||
running; released 21:34). Tree `/home/rk/qwen36-step4-runner`, logs `/home/rk/logs/step4-runner-*.log`.
|
||||
|
||||
- Configure (the common line, `-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`) and an incremental
|
||||
build from the pack tree's objects: 3 min 4 s, 0 errors.
|
||||
- `qwen36_verify_test`: PASS, 0 failures. `result_output_all` per position (40): worst rel L2 F32 5.65e-02, Q8
|
||||
3.46e-02 (gate Q8 <= 5e-02); argmax equals the Q8 oracle's at 40 of 40, the F32 oracle's at 37 of 40 (the same
|
||||
three near ties, positions 1, 4, 23, as on the 4090).
|
||||
- `qwen36_runner_check.py`: PASS, 0 failures. c7 worst rel L2 F32 2.05e-02 / Q8 2.55e-02; c40 2.32e-02 / 2.26e-02;
|
||||
ar (positions 1..39) 4.35e-02 / 4.37e-02, argmax 36 of 36 unambiguous; c7 vs c40 rows 35..39 rel L2 1.32e-02; c7
|
||||
vs ar 2.12e-02; the 4 KB mutation of `blk.1.ffn_gate_inp.weight` moves the logits by rel L1 2.05e-01.
|
||||
- The real-file comparison against llama.cpp (three prompts, IQ3_XXS) did **not** run: the teacher fixtures
|
||||
(`/home/rk/qwen36-step4-teacher/<prompt>/prompt_ids.txt`, `eng/*.f32`) were never synced to VM 211, so all three
|
||||
engine runs exit 2 on "invalid token id" and the comparisons on a missing file. Owed to step 5 along with the Q4
|
||||
fit at 11 GB; the card has since been taken by another service (section 5).
|
||||
|
||||
### VM 221, round 8 (2026-10-11 21:41 UTC): the drafter's VRAM term and the speculation rate
|
||||
|
||||
`vram_plan_test` with the drafter's whole share (its K/V over the context, the draft head subset, the ids): all
|
||||
passed. The real drafter (`--mtp`, 4-token windows, 64 greedy tokens on the `iq3-test20` prompt, `--prefill 2048
|
||||
--max-context 8192 --kv fp16 --expert-cache auto --suffix-draft 0`):
|
||||
|
||||
| file, draft pack | drafts accepted | tokens per round | drafting ms/round | drafter VRAM | decode tok/s |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| IQ3_XXS, `qwen36-mtp-draft-full` | 44 of 57 (0.772) | 3.20 | 2.30 | 524 MiB | 317 |
|
||||
| IQ3_XXS, `qwen36-mtp-draft` (subset head) | 43 of 60 (0.717) | 3.05 | 1.38 | 695 MiB | 326 |
|
||||
| Q4_K_XL (plain file), `qwen36-mtp-draft` | 40 of 75 (0.533) | 2.54 | 1.54 | 745 MiB | 246 |
|
||||
| IQ3_XXS, no `--mtp` (one-token windows) | - | 1.00 | - | 0 | 112 (1 token) |
|
||||
|
||||
The Q4 file's lower acceptance is expected: the draft pack comes from the Q4_K_XL-MTP file's `blk.40`, drafted
|
||||
against the plain Q4_K_XL trunk; the drafter notes (step4-drafter.md) measured 77% teacher-forced on the MTP file
|
||||
itself. Logs `/models/work/logs/spec-*.log`, `r8-vram-plan-test.log`.
|
||||
|
||||
## 5. Not done, surprises
|
||||
|
||||
- **The 1080 Ti pass** of steps 2-4 ran at 21:38 (section 4): build, verify test and runner check pass; the
|
||||
llama.cpp real-file comparison is owed (fixtures never synced). Since 2026-10-12 22:04 UTC the card runs another
|
||||
session's Flash-Next coder service (`unbiased-strata.service`, 10.9 GB, 100% busy) and is off limits.
|
||||
- **The Q4 fit at 11 GB** was not measured (the same lock, then the service); the Q4 run above is the 4090's. The pack notes
|
||||
(step4-pack.md section 5) record the plan on the 11 GB card (Q4_K_XL fixed set 4,461 MiB, 34% of slots resident),
|
||||
so a reduced-context Q4 run there is the remaining 1080 Ti item.
|
||||
- **The chat template** (`make test-chat-parser MODEL=<gguf>`): on Qwen3.6's template a tool call whose required
|
||||
parameter is not written first was silently dropped (0 tool calls). Filed REGINA-104. Resolved at integration
|
||||
(e73adc6): the template does route to the Qwen3-Coder parser the any-argument-order patch covers; the patch was
|
||||
simply never applied, because only `make build` applied it and every VM tree was configured with cmake directly on
|
||||
a copied submodule. CMake now applies it at configure time; with the rebuilt `libllama-common` the test passes on
|
||||
VM 221 for all four orders.
|
||||
- **The argmax near ties.** On the synthetic 40-token `base_ar` case the F32 and Q8 oracles disagree at 3 positions
|
||||
(1, 4, 23); the engine matches the Q8 oracle at all 40. A position where the two references disagree cannot
|
||||
discriminate the engine, so the tests gate against the Q8 oracle and report those positions.
|
||||
- **The real file's single-position KL spikes** (task-prime-add-test, 1.5e-1 at position 40) are near ties where
|
||||
top-1 still agrees; the mean KL is 1e-3 to 7e-3.
|
||||
|
||||
## 6. The interface other agents consume
|
||||
|
||||
- `strata --native FILE --pack DIR [--spec T] [--mtp DIR] --prefill CHUNK` now runs a Qwen3.6 pack to tokens.
|
||||
Drafter off: omit `--mtp`; the windows are one token each. `--spec-oracle FILE --teacher-force` holds the engine
|
||||
to a reference continuation and writes one logits row per position with `--dump-logits`.
|
||||
- `ref/qwen36.py --all-logits` dumps `result_output_all` (n_tok x n_vocab, the head at every position of the last
|
||||
chunk); `tools/qwen36_teacher_llama.cpp` is the llama.cpp reference (logits.f32, continuation.txt, routes.txt);
|
||||
`tools/qwen36_compare_logits.py` scores top-1, KL and the drift gate.
|
||||
- The runner tests: `qwen36_verify_test <fixture dir>`, `qwen36_runner_check.py --strata S --fixture DIR`, both from
|
||||
`qwen36_runner_fixture.py --out DIR`.
|
||||
@@ -1,521 +0,0 @@
|
||||
# Qwen3.6 port, step 5, first part: serving on the 4090, and what broke below full residency
|
||||
|
||||
Branch `qwen36-step4`, 2026-10-13, VM 221 (RTX 4090, 24 GB; the user handed the box to this work at 02:05 UTC and the
|
||||
Flash-Next service on it was stopped). Tree `/models/work/qwen36-step4`, binary `build/unbiased-strata`, logs under
|
||||
`/models/work/serve/`. The 1080 Ti (VM 211) is off limits: another session's service runs there.
|
||||
|
||||
## The serve command
|
||||
|
||||
```
|
||||
./build/unbiased-strata --model /models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --pack /models/work/packs/qwen36-q4 \
|
||||
--mtp /models/work/packs/qwen36-mtp-draft-full --ctx 262144 --threads 8 --host 127.0.0.1 --port 18090 -- --kv q4_0
|
||||
```
|
||||
|
||||
`--mtp` takes a Qwen3.6 draft pack (`tools/mtp_qwen36_pack.py`); `qwen36-mtp-draft` carries a `draft_vocab.bin`
|
||||
subset, `-full` has none. Everything after `--` goes to the engine: `--vram-cap MiB`, `--ram-cap GiB`, `--kv
|
||||
fp16|q4_0|int8`, `--expert-cache N|auto`, `--pcie-frac F`, `--prompt-cache N`, `--vram-reserve-mib`.
|
||||
|
||||
## Faults found in order, all fixed on the branch
|
||||
|
||||
| # | Symptom | Cause | Fix |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | `unbiased-strata: missing file: .../qwen36-mtp-draft-full/draft_vocab.bin` | the front end required the Flash-Next draft vocabulary subset | optional in the front end as it already was in the engine (3a806b5) |
|
||||
| 2 | first request: 220 tokens generated, then `saving a conversation checkpoint failed` (`conversation snapshot: invalid model geometry`, then `invalid indexer running-state target`) | the prompt-cache checkpoint and the snapshot rejected a geometry with no indexer (idx heads / key dim 0) and no hyper-connection rate, and demanded the indexer's tail / dead / block-position / pooled buffers | zeros allowed where `has_indexer()` is false and `hc` is 1, no indexer buffers or block positions for dense attention, pooled rows 0 (3a806b5). Two-turn conversation: 1 then 2 checkpoints, prefix reused |
|
||||
| 3 | Q4 at 262,144: `2, 3! 5, 7, 11, !!!!!!...` (token 0 forever); IQ3 under any `--vram-cap` the same; both files fine at 8K / 32K; IQ3 at 256K fine | **the pool's native-pack phases iterated the canonical Q2_0 widths (FF 640, H 2560) instead of the layer's (512, 2048)**: every expert miss computed on the CPU wrote 512 rows past its output row. The runner's and drafter's tests all ran with every expert resident, so the miss path had never executed on Qwen3.6 | `run_split_multi_native` at `NativeFmt::n_ff / n_embd`; `native_fmt` refuses wider layers; `pool_native_widths_test` (22d72e6) |
|
||||
|
||||
How fault 3 was isolated (each row one serve, the prime-numbers prompt, greedy, `bangs` = count of `!` in 120-200
|
||||
tokens):
|
||||
|
||||
| Run | file | ctx | KV | slots resident | misses on | result |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| e1 | Q4 | 8192 | fp16 | 10,240 / 10,240 | - | correct, 362 tok/s |
|
||||
| e3 | Q4 | 262,144 | q4_0 | 9,980 | CPU + DMA | `2, 3, 5, 7, !!!` |
|
||||
| e2 | Q4 | 262,144 | q4_0, `--vram-cap 20480` | 8,132 | CPU + DMA | `!!!` from the first token |
|
||||
| e4 | Q4 | 262,144 | fp16 | 8,120 | CPU + DMA | `!!!` |
|
||||
| e5 / e6 | Q4 | 8192 / 32,768 | q4_0 | 10,240 | - | correct, 354 / 356 tok/s |
|
||||
| t1 | IQ3 | 262,144 | q4_0, `--vram-cap 15360` | 10,212 | CPU + DMA | `!!!` |
|
||||
| t2 | Q4 | 262,144 | q4_0, `--vram-reserve-mib 1200` | 9,838 | CPU + DMA | `!!!` (so not VRAM pressure) |
|
||||
| t3 | Q4 | 8192 | fp16, `--expert-cache 8000` | 9,587 | CPU + DMA | `!!!` (the cheap reproduction) |
|
||||
| t4 | Q4 | 8192 | as t3, `--pcie-frac 1.0` | 9,587 | DMA only (GPU computes) | **correct**, 305 tok/s |
|
||||
| t5 | Q4 | 8192 | as t3, `--pcie-frac 0.0` | 9,587 | CPU only | `!!!` |
|
||||
| t6 / t7 / t8 | Q4 ggml dots only / IQ3 / one worker | 8192 | as t5 | 9,587 | CPU only | `!!!` all three: not the kernels |
|
||||
| fix | Q4 | 8192 | as t5 | 9,587 | CPU only | correct, 328 tok/s |
|
||||
| fix | Q4 | 262,144 | q4_0 | 9,980 | CPU + DMA | correct, 322 tok/s |
|
||||
| fix | IQ3 | 262,144 | q4_0, `--vram-cap 11264` | 5,762 (56%) | CPU + DMA | correct, 169 tok/s; 63,526 VRAM hits of 73,553 lookups |
|
||||
|
||||
| 4 | Pascal host (VM 211, step5-1080ti, REGINA-106): with CPU-computed misses iq3-test20 51/64 top-1, KL 0.84; Q4 52-54/64, KL 0.25; DMA misses correct; deterministic; `--spec 1` changes it | **the multi-token CPU dispatch addressed token t's activation at t x 2560 and its output row at i x 2560** (the canonical widths pulled in by `using namespace`), while the window publishes at the layer's 2048: every token after a group's first used another token's activation. Named by the Codex review of 22d72e6; the 4090's serve looked right because its text was checked, not its logits | the dispatch at the layer's width with refusals (the commit after 22d72e6); after it on VM 211 all three IQ3 prompts 64/64 (KL 1.4e-3 / 4.8e-3 / 2.0e-3), q4-test20 62/64 KL 6e-3, q4-prime 64/64 KL 8e-4, CPU misses forced. The ladder points taken with the old binary are rerun |
|
||||
| 5 | the 4090 sweep's `--ram-cap 12` points: "ArenaExpertSource: the expert arena needs 18.32 GiB ... memory limit is 12.00 GiB ... --mmap-experts" | the plan chose RAM copies but the arena source still pinned the whole file | the engine picks the mapped tier with profile-ranked RAM copies itself when the arena exceeds the limit or available RAM (same commit) |
|
||||
| 6 | planner (Codex review): a full-head draft pack charged 515 MiB the drafter never allocates; k8v4 undercounted the drafter's INT8 K/V by 60 MiB; a lowered context was printed but not applied | | all three in the same commit; multi-GPU helpers refused for this geometry |
|
||||
|
||||
| 7 | second Codex review of fa69e82: the front end kept validating and advertising the requested `--ctx` when the engine's plan lowered it; the automatic mapped tier ignored an explicit `--shared-expert-arena` and the multi-GPU residency rules; the plan's session term keeps the RoPE table at the requested context | | the front end takes the context from the engine's `READY <n>` line and bounds requests by it; the automatic choice is skipped with a shared arena or the helpers. The RoPE table at a lowered context is left as a conservative overcount (at most 32 MiB from 262,144 to 131,072), noted here rather than threaded through the plan |
|
||||
|
||||
## What the 4090 serves now
|
||||
|
||||
| file | ctx | fixed set | experts resident | VRAM free after load | short answer decode | drafts accepted |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| IQ3_XXS, `-full` draft | 262,144 | 4,331 MiB (weights 1,596, drafter 831, KV 1,440, session 162, reserve 300) | 10,240 / 10,240 (10.35 GiB) | 8,758 MiB | 319-359 tok/s | 157 / 181, 223 / 237 |
|
||||
| Q4_K_XL, subset draft | 262,144 | 4,823 MiB (weights 2,038, drafter 882, KV 1,440, session 162, reserve 300) | 9,980 / 10,240 | 434 MiB | 322 tok/s | 149 / 152 |
|
||||
|
||||
Also checked through the HTTP front end: streaming (SSE chunks, `reasoning_content` deltas), a two-turn
|
||||
conversation with checkpoint reuse, a tool call (`<tool_call><function=read>` emitted; the earlier "!!!" inside its
|
||||
arguments was fault 3). The response's `model` field is now the GGUF's base name (was the Flash-Next constant).
|
||||
|
||||
## Observations for the measurements
|
||||
|
||||
- The RAM tier reports `expert copies in RAM: 0` on this host: with 62 GB the whole expert arena is pinned host
|
||||
memory (`cudaHostRegister PORTABLE`, 18.3 GiB for Q4), and a miss is served from it by DMA or the CPU; `ram_reads`
|
||||
and `file_reads` on `/health` stay 0. On a 12 GiB host the arena cannot hold the file and the mapped-from-disk
|
||||
tier is what the ladder measures (`--ram-cap` emulates it here).
|
||||
- Checkpoint reuse: the second turn reused 27 of 278 prompt tokens. Cause and the opt-in that lifts it: the A5
|
||||
section below, check (d).
|
||||
- `expert cache ... policy is` prints an empty policy name for native packs (cosmetic).
|
||||
- At 262,144 the Q4 fixed set leaves 19.3 GiB for experts; 9,980 slots fit; the planner's "10240 of 10240 (100%)"
|
||||
line and the cache's "9980 slots" disagree by the 700 MiB runtime reserve the cache keeps; the plan line should
|
||||
say what the cache will actually hold.
|
||||
|
||||
## A5 on the 4090: the serving checks, after the streaming fix (REGINA-110)
|
||||
|
||||
**The fault.** With `"stream": true` the answer arrived as one `content` delta before the final chunk; only
|
||||
`reasoning_content` streamed. Not the parser: `run()` in `frontend/main.cpp` cleared the content of every partial
|
||||
parse together with its tool calls, a rule that came with 46c46ec so that partial tool-call JSON (closed and
|
||||
normalized by the parser on each token) could never change text already sent. That holds for a call's arguments,
|
||||
not for the answer. c3b41cc: reasoning and content are published as they arrive, tool calls once from the complete
|
||||
parse (`StreamParse`); a partial parse whose content does not extend what was sent publishes no content until it
|
||||
does; a non-streaming request is parsed once instead of after every token. **A tool call still arrives whole**, in
|
||||
one delta (name, id and full arguments) when the message ends; the text before a call streams.
|
||||
`make test-chat-parser` now feeds seven responses a character at a time (reasoning on and off, tools declared and
|
||||
not called, text before a call, one and two calls) and requires the pieces to add up to the whole parse, the answer
|
||||
to arrive in many deltas and each call in one; it passes on the IQ3_XXS and Q4_K_XL files. The ticket's request on
|
||||
the final binary: 200 content chunks of 203 (was 1 of 3).
|
||||
|
||||
**The checks.** VM 221, binary sha256 `46c5747f23dcbdeb` (c3b41cc), `--mtp qwen36-mtp-draft --ctx 262144 --threads
|
||||
8 ... -- --kv q4_0`, greedy, client and server on the VM (`/models/work/serve/a5-20261013/`: `a5.py`, `serve.sh`,
|
||||
one `.json` and `.log` per configuration). All nine checks pass in all three configurations.
|
||||
|
||||
| check | Q4_K_XL, no cap (9,980 slots) | Q4_K_XL, `--vram-cap 11264` (2,910 slots) | IQ3_XXS, `--vram-cap 6144` (809 slots) |
|
||||
| --- | --- | --- | --- |
|
||||
| (a) chat, not streamed, thinking off: "capital of France" | pass, 0.15 s | pass, 0.54 s | pass, 0.54 s |
|
||||
| (a) chat, not streamed, thinking on: 17 x 23 = 391 | pass, 314 tokens at 313 tok/s | pass, 314 at 76 | pass, 410 at 70 |
|
||||
| (b) stream, thinking on: reasoning deltas, first, largest gap | 1,087, 0.081 s, 14.1 ms | 467, 0.293 s, 92.8 ms | 418, 0.348 s, 78.6 ms |
|
||||
| (b) the same request: content deltas, first, largest gap | 89, 3.616 s, 13.8 ms | 82, 5.803 s, 61.6 ms | 53, 6.181 s, 82.3 ms |
|
||||
| (b) the same request: tokens, decode, largest gap between any two deltas | 1,179 at 303 tok/s, 14.1 ms | 552 at 83, 92.8 ms | 474 at 72, 82.3 ms |
|
||||
| (b) stream, thinking off (the ticket's request): content deltas, first, largest gap | 212 of 213 tokens, 0.076 s, 11.5 ms | 203 of 204, 0.330 s, 53.8 ms | 209 of 210, 0.345 s, 64.2 ms |
|
||||
| (c) tool round trip, not streamed: call, result, answer | pass: `get_weather {"city":"Paris"}`, `tool_calls`, then "17 C with light rain", `stop` | pass | pass |
|
||||
| (c) tool round trip, streamed | pass: reasoning 658 deltas, the call in 1 delta at 2.40 s; the answer in 14 content deltas | pass: 517 reasoning deltas, call in 1 at 5.40 s; 15 content deltas | pass: 173, call in 1 at 2.86 s; 18 content deltas |
|
||||
| (c) tools declared, not called, streamed, thinking on: content deltas, first, largest gap | 73, 2.597 s, 14.0 ms | 74, 10.318 s, 62.2 ms | 81, 12.442 s, 81.1 ms |
|
||||
| (c) the same, thinking off | 76, 0.032 s, 11.4 ms | 69, 0.067 s, 41.7 ms | 66, 0.093 s, 41.9 ms |
|
||||
| (d) three-turn chat, tokens reused of the prompt per turn | 0 / 23, 18 / 129, 124 / 172 | 0 / 23, 18 / 133, 128 / 176 | 0 / 23, 18 / 178, 173 / 246 |
|
||||
|
||||
"First" is from the request to that delta, so with thinking on the first content delta comes after the reasoning.
|
||||
Deltas come in bursts of an accepted draft window (median gap 0.05-0.1 ms); the largest gap is one verify round,
|
||||
longer under a cap where it waits on expert misses. No keepalive comment was needed in any run.
|
||||
|
||||
**(d) Why the reused prefix is short, and what lifts it.** The engine keeps a checkpoint at the last
|
||||
`<|im_start|>` of each prompt and one at the end of each reply. The next request reuses the second only if it
|
||||
renders the reply as it was generated, and in a plain chat Qwen3.6's template does not: a reply before the last
|
||||
user message is rendered without its `<think>` block (with thinking off, without the empty `<think>\n\n</think>`
|
||||
the generation prompt carried), whether or not the client sends `reasoning_content` back. The tokens leave the
|
||||
generated ones right after the assistant header, and the reuse is the previous prompt less its 5-token header: 18
|
||||
of 129, 124 of 172, and the 27 of 278 above. Each turn rereads the last reply and the new message, never the older
|
||||
history. Not an engine fault. Two cases reuse the reply too:
|
||||
|
||||
- a tool loop: a reply after the last user message keeps its reasoning in the template. pi's three requests (check
|
||||
e): 0 of 1,604, then 1,867 of 1,948 and 2,047 of 2,118;
|
||||
- `"chat_template_kwargs": {"preserve_thinking": true}` with `reasoning_content` sent back, which the front end now
|
||||
passes to the template (3aa9eed; binary `e4d8ec0c07473e13`): four turns reuse 0 / 22, 551 / 569, 1,010 / 1,027,
|
||||
1,365 / 1,382. Opt-in, because the earlier reasoning then stays in the context the model reads. Not every turn
|
||||
hits: in two of eight such turns the re-rendered reply did not match the generated tokens (578 of 1,330; 18 of
|
||||
1,138) and the request fell back to the header checkpoint; which replies re-tokenize differently was not traced.
|
||||
|
||||
**(e) pi.** pi 0.85.1 on the Mac, its own agent directory (`PI_CODING_AGENT_DIR`, the user's `~/.pi` untouched),
|
||||
provider `openai-completions` at the engine through an SSH tunnel, Q4_K_XL no cap, `pi -p --mode json`: it wrote
|
||||
`primes.py` with its `write` tool, ran it with `bash`, and reported `2 3 5 ... 71`. Three requests, two tool calls,
|
||||
80 thinking deltas and 82 text deltas seen by pi; nothing dropped by the parser.
|
||||
|
||||
**Tests.** The Qwen3.6 ctest subset on the free card (`ctest -R "qwen36|vram_plan_test|pool_native_widths_test"`):
|
||||
21 of 21. `make test-frontend` and `make test-chat-parser` pass. The engine is untouched by these two commits, so
|
||||
no logits comparison was owed.
|
||||
|
||||
**Seen, then chased.** The same greedy request does not always generate the same tokens on one server (check b,
|
||||
thinking on, Q4 no cap: 632 tokens in one pass, 1,179 in the next). Traced in the next section: not a fault.
|
||||
Images (mmproj) were out of scope.
|
||||
|
||||
## The same greedy request, different tokens: which paths differ, and by how much
|
||||
|
||||
2026-10-13, VM 221, binary `11da5388afdfabcb`. The engine was driven on its own stdin protocol (`unbiased-strata
|
||||
--engine --serve ...` with the front end's arguments, `GEN <max_new> <ids>`), so the record is token ids. Two
|
||||
prompts from A5, rendered by the front end: `think` (26 tokens, "What is 2+2? Answer, then write three sentences
|
||||
about addition.", thinking on) and `nothink` (25 tokens, the lighthouse request, thinking off), `max_new` 3,000.
|
||||
Material in `/models/work/serve/nd-20261013/` (`nd.py` the driver, `cmp.py`, `trdiff.py`, `acc.py`, one `.jsonl` of
|
||||
token ids and one engine log per run, 23 GB of logit dumps).
|
||||
|
||||
**Verdict: benign.** No state leaks between requests. The output is a pure function of the request and of which
|
||||
of three numerically different, individually correct paths each number went through; two things move a request
|
||||
between those paths from one pass to the next:
|
||||
|
||||
1. **Where an expert is computed.** A resident expert and one read over PCIe (DMA) run the GPU kernel (llama.cpp's
|
||||
CUDA arithmetic: activations as Q8_1); a miss computed on the CPU runs ggml's CPU kernel (activations as Q8_K).
|
||||
The two round differently, as llama.cpp's own CPU and CUDA back ends do. The adaptive tier (`--adapt-every`, 4
|
||||
rounds) swaps routed-but-missing experts into VRAM and keeps them across requests, so the second pass of a
|
||||
request finds experts on the card that the first computed on the CPU. It settles: once the cache stops
|
||||
changing the output stops changing.
|
||||
2. **How the prompt's state was built.** A part of at most `--short-read` (64) tokens and everything a checkpoint
|
||||
or the live session supplies went through the verify windows; a longer part read from token 0 goes through the
|
||||
batched prompt path, which is different arithmetic (step4-runner.md: the two agree to 2.1e-2 on the fixture).
|
||||
Restoring a checkpoint is exact; what differs is a state made by decode against the same state re-read in a batch.
|
||||
|
||||
With misses present a third input reaches the output through (1): the lookup drafter's policy picks window sizes
|
||||
from measured round times, the adaptive tier counts rounds, and the PCIe share of a layer's misses is a fraction
|
||||
of the misses in that window. With `--suffix-draft 0` a fresh engine gave the same tokens with and without the
|
||||
tracing below (which slows every window); with the default it gave 557, 554 and 555 tokens for `think`. With
|
||||
every expert resident the window shape does not reach the output (the window is bitwise independent of its shape).
|
||||
|
||||
**Which configurations repeat.** Ten requests of each prompt, alternating, on one engine unless noted:
|
||||
|
||||
| configuration | misses run on | distinct outputs, `think` / `nothink` | tokens generated |
|
||||
| --- | --- | --- | --- |
|
||||
| IQ3_XXS, 262,144, q4_0, no cap (10,240 resident) | - | 1 / 1 | 480 / 197 |
|
||||
| the same, `think` alone 10 times (21 of 26 reused) and with `--prompt-cache 0` | - | 1, the same tokens | 480 |
|
||||
| Q4_K_XL, 8,192, fp16 (10,240 resident) | - | 1 / 1 | 664 / 218 |
|
||||
| Q4, 8,192, `--expert-cache 8000 --pcie-frac 1.0`, adaptive tier on or off | GPU (DMA) | 1 / 1, **the all-resident tokens** | 664 / 218 |
|
||||
| Q4, 8,192, `--expert-cache 8000 --pcie-frac 0.0 --adapt-every 0` | CPU, fixed set | 1 / 1 | 632 / 191 |
|
||||
| the same with the adaptive tier | CPU, changing set | 7 / 6, the same from the 7th request | 511, 557, 639, 633, 1,451, 478, 479 x 4 |
|
||||
| Q4, 262,144, q4_0, no cap (9,980 slots): the A5 configuration | CPU (0.05% of lookups) | 3 / 3, the same from the 3rd | 557, 620, 553 x 8 / 221, 213, 214 x 8 |
|
||||
| the same, `--prompt-cache 0` | CPU | the tokens of the row above | |
|
||||
| the same, `--adapt-every 0` | CPU, fixed set | 1 / 1 | 558 / 211 |
|
||||
| the same, `--suffix-draft 0` | CPU | 2 / 3 | 550, 551 x 9 |
|
||||
| the same, `--mtp-max-t 1 --suffix-draft 0` (6 requests) | CPU | 4 / 2 | 561, 552, 1,014, 552 x 3 |
|
||||
| the same, a new engine for every request | CPU | 1 / 1 | 557 / 196 |
|
||||
|
||||
Every configuration with one path is bit-repeatable; the only ones that are not have CPU misses and a cache that
|
||||
is still changing. The checkpoint cache, the drafter and the lookup drafter are not sources. The second cause,
|
||||
with every expert resident (IQ3 no cap; Q4 at 8,192), one engine against a new engine reading from token 0:
|
||||
|
||||
| request | state from | tokens | first difference |
|
||||
| --- | --- | --- | --- |
|
||||
| 258-token prompt, three times | 0 reused, then 253 reused + 5 | identical, and identical to a new engine | - |
|
||||
| `think`, its 480 / 664 generated tokens and a second user turn (529 / 713) | the live session (505 / 690 reused) or the header checkpoint (524 / 708) | identical to each other | |
|
||||
| the same on a new engine | the batched prompt path, all of it | IQ3 554 against 495, Q4 437 against 401 | token 191 / 140 |
|
||||
| a 73-token second turn | 21 reused + 52 through the windows, or 68 reused | identical to each other | |
|
||||
| the same on a new engine | 73 read from 0 | IQ3 890 against 494, Q4 465 against 438 | token 61 / 61 |
|
||||
|
||||
**The margins where they part, and the accuracy of every state.** `STRATA_SERVE_LOGIT_TRACE=FILE` (new, off by
|
||||
default) writes the head's five largest logits, the window and its misses per emitted token, and
|
||||
`STRATA_SERVE_LOGIT_DUMP=PREFIX` the whole row (the last window's rows past the stop token included);
|
||||
`tools/qwen36_teacher_llama.cpp` grew `--prompt-ids` and `--force-ids`, so llama.cpp (F16 K/V, the 4090) is
|
||||
teacher-forced along each run's own tokens and every position of every run is scored, with the path that run took. Margins are logit differences between the two tokens chosen.
|
||||
|
||||
| first difference | this pass | the other pass | llama.cpp |
|
||||
| --- | --- | --- | --- |
|
||||
| Q4 no cap, `think`, request 1 against 2, token 249 | 0.03 for A | 0.23 for B | 0.16 for B |
|
||||
| request 1 against 3, token 245 | 0.10 for A | 0.78 for B | 0.09 for B |
|
||||
| request 3 against 4, token 531 | 0.007 for A | 0.20 for B | 0.31 for B (its own pick is a third token, 0.12 above B) |
|
||||
| IQ3 no cap, session state against a batched re-read, token 191 | 0.27 | 0.34 | 0.03 |
|
||||
| Q4 8,192, the same, token 140 | 0.08 | 0.03 | 0.012 |
|
||||
| IQ3 / Q4 second turn, windows against batched, token 61 | 0.09 / 0.11 | 0.37 / 0.08 | 0.32 / 0.03 |
|
||||
|
||||
Over the common prefix two passes differ by a mean of 0.12-0.13 logits on the reference's 20 largest (KL 1.4e-3
|
||||
to 2.1e-3 between them), the size of each pass's distance from llama.cpp. Every state against llama.cpp, the
|
||||
whole run and its first 64 positions (the rule: 62 of 64, mean KL below 1e-2):
|
||||
|
||||
| run, path | positions | top-1 | mean KL | max KL | first 64: top-1, mean KL |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Q4 8,192 fp16, all resident (serve) | 664 | 660 (99.4%) | 8.3e-4 | 0.077 | 64, 5.6e-4 |
|
||||
| Q4 8,192, CPU misses, `--expert-cache 8000`, fixed (0.7% of lookups) | 632 | 624 (98.7%) | 8.9e-4 | 0.053 | 64, 5.5e-4 |
|
||||
| Q4 8,192, CPU misses, `--expert-cache 4000`, fixed (33% of lookups) | 547 | 542 (99.1%) | 8.9e-4 | 0.046 | 64, 1.3e-3 |
|
||||
| Q4 no cap 262,144 q4_0, requests 1 / 2 / 3 / 4 of `think` | 555 / 630 / 557 / 553 | 98.4 / 98.4 / 98.7 / 98.6% | 3.4e-3 / 3.3e-3 / 4.0e-3 / 3.8e-3 | 0.08 / 0.30 / 0.16 / 0.13 | 63, 1.8e-3 to 2.1e-3 |
|
||||
| IQ3 no cap 262,144 q4_0, second turn: session state / batched re-read | 495 / 554 | 98.8 / 99.3% | 3.4e-3 / 4.7e-3 | 0.11 / 0.10 | 64, 1.4e-3 / 64, 1.0e-3 |
|
||||
| IQ3, 73-token second turn: windows / batched | 494 / 890 | 98.2 / 98.5% | 4.1e-3 / 4.0e-3 | 0.15 / 0.14 | 62, 3.5e-3 / 63, 1.4e-3 |
|
||||
| Q4 8,192, second turn: session state / batched re-read | 401 / 437 | 99.8 / 99.3% | 9.4e-4 / 8.1e-4 | 0.023 / 0.033 | 64, 2.5e-4 / 64, 2.0e-4 |
|
||||
| Q4 8,192, 73-token second turn: windows / batched | 438 / 465 | 99.3 / 99.4% | 9.0e-4 / 1.5e-3 | 0.021 / 0.12 | 64, 8.3e-4 / 63, 6.2e-4 |
|
||||
| `strata --teacher-force`, 400 tokens of the all-resident run: resident / DMA / CPU 8000 / CPU 4000 / CPU 4000 fixed | 400 | 393 / 393 / 396 / 396 / 395 | 9.2e-4 / 9.2e-4 / 9.6e-4 / 7.9e-4 / 8.8e-4 | 0.028 to 0.036 | 63 or 64, 3.6e-4 to 5.9e-4 |
|
||||
|
||||
Every top-1 disagreement with llama.cpp in these runs (113 in 9,912 positions) sits where llama.cpp's own margin is
|
||||
under 0.75 logits; one position in 20 to 25 has a top-2 gap under 0.5, so a greedy run of 500 tokens meets some
|
||||
twenty places where a pass can turn. The teacher-forced resident and DMA dumps are the same bytes (`cmp`). No
|
||||
rising drift: Spearman(position, KL) is between 0.00 and +0.13 in every run but the IQ3 batched re-read (+0.20, KL
|
||||
3.2e-3 in its first half and 6.1e-3 in its second).
|
||||
The 262,144 rows carry the q4_0 K/V against llama.cpp's F16 (mean KL 3-5e-3 where the fp16 rows have 8e-4 to
|
||||
1.5e-3); the K/V format is the likely reason (not isolated here), and it is in every pass alike.
|
||||
|
||||
**For a run that must repeat.** `--pcie-frac 1.0` (every miss on the GPU: the all-resident tokens whatever the
|
||||
cache holds, at the DMA path's cost; only while no layer of a window has more than 16 distinct misses, past which the
|
||||
rest run on the CPU, see the REGINA-111 section at the end), or `--adapt-every 0 --suffix-draft 0` (the miss set fixed, no timed policy).
|
||||
A conversation that continues on one engine still differs from the same prompt read from token 0 on another.
|
||||
|
||||
**Not checked.** The 1080 Ti (VM 211, off limits); a capped Q4 or IQ3 with thousands of misses per request beyond
|
||||
the `--expert-cache 4000` rows; sampled (temperature above 0) requests; requests cancelled mid-generation followed
|
||||
by the same prompt; the q4_0 K/V's own share of the 262,144 rows' KL. `--teacher-force` with `--mtp` committed
|
||||
the drafter's guesses as if they were the oracle's tokens (70 of 400 top-1 on a run that scores 394 without it): it
|
||||
is now refused.
|
||||
|
||||
## A5 on the 1080 Ti: the serving checks at the branch head
|
||||
|
||||
2026-10-13, VM 211 (GTX 1080 Ti 11,264 MiB, sm_61, 14 vCPU, 52 GB; the box was free), tree at 542b53b (the streaming
|
||||
fix c3b41cc, `preserve_thinking` 3aa9eed, the logit diagnostics c7825b4), built by `/home/rk/build-step4.sh`:
|
||||
`unbiased-strata` sha256 `4e161358c8fd20c1`, `strata` `a44d896ccb25ff98`. The ladder on this card was measured with
|
||||
7ebc9e5 (`e6c8bbf4cfb16e09`); the engine source differs from it by the diagnostics and the `--teacher-force --mtp`
|
||||
refusal only (`generate.cpp`, 52 lines). Material: `/home/rk/bench/a5-1080ti-20261013/` (`logits/`, one `.json`,
|
||||
`.log`, `.summ.txt` per configuration, `speed/`), drivers `/home/rk/bench/a5-1080ti-job1a.sh` and `job1b.sh` there.
|
||||
|
||||
**Tests.** `ctest -R "qwen36|vram_plan_test|pool_native_widths_test"` on the free card: 21 of 21 (668 s).
|
||||
|
||||
**The accuracy rule on this binary** (teacher-forced logits against llama.cpp's, `tools/qwen36_compare_logits.py`,
|
||||
fixtures `/home/rk/qwen36-step4-teacher`, the command of the REGINA-108 check: context 8,192, `--kv fp16`, `--spec 4
|
||||
--suffix-draft 0`, 64 positions; pass = top-1 at least 62 and mean KL below 1e-2). Every miss forced onto one path:
|
||||
`--pcie-frac 0.0` the CPU pool, `1.0` DMA with the GPU computing. `auto` holds 8,061 of 10,240 slots for IQ3 and
|
||||
4,240 for Q4 on this card; `--expert-cache 2000` holds 2,263 and 2,399. Cells are top-1 of 64, mean KL; **bold**
|
||||
misses the rule.
|
||||
|
||||
| fixture | auto, CPU misses | auto, DMA | 2000, CPU misses | 2000, DMA | the 4090, all resident |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| iq3-test20 | 64, 1.3e-3 | 63, 9.1e-4 | 64, 1.4e-3 | 64, 8.0e-4 | 64, 1.1e-3 |
|
||||
| iq3-task-prime-add-test | 64, 4.5e-3 | **64, 1.26e-2** | 64, 4.8e-3 | **63, 1.18e-2** | 64, 6.6e-3 |
|
||||
| iq3-task-psim-collide | 64, 2.3e-3 | 64, 2.1e-3 | 64, 2.0e-3 | 64, 2.0e-3 | 64, 1.9e-3 |
|
||||
| q4-test20 | 62, 6.0e-3 | **61**, 8.5e-3 | **61**, 8.3e-3 | **62, 1.17e-2** | 61, 7.4e-3 |
|
||||
| q4-task-prime-add-test | 64, 8.1e-4 | 64, 1.2e-3 | 64, 1.1e-3 | 64, 7.2e-4 | 64, 1.7e-3 |
|
||||
| q4-task-psim-collide | 64, 1.3e-3 | 64, 7.0e-4 | 64, 1.3e-3 | 64, 7.7e-4 | 64, 4.2e-4 |
|
||||
|
||||
**19 of 24 runs pass; 5 do not, all on two fixtures** (REGINA-111). Not a regression of this binary, and not broad:
|
||||
|
||||
- the CPU column at `auto` is the REGINA-108 post-fix table again (1.4e-3 / 4.8e-3 / 2.0e-3, q4-test20 62 at 6e-3,
|
||||
q4-prime-add 8e-4), and q4-test20 `auto` DMA has the pre-fix binary's figures to the last printed digit (61, 0.00845,
|
||||
0.13765 at position 8): neither path moved;
|
||||
- each miss is one position. q4-test20: positions 8, 9, 13, the near ties where the 4090 with every expert resident
|
||||
also reads 61 of 64 (KL 0.147 at position 8; here 0.086 to 0.323 in the three runs that miss). iq3-prime-add: position 40, 0.152 on the 4090,
|
||||
0.416 / 0.467 on this card's GPU path, under 0.05 with CPU misses at `auto`; the median KL of those runs is 3e-5;
|
||||
- this card against the 4090's all-resident dumps (`eng/*.f32`): mean KL 5.2e-3 to 1.2e-2 on these two fixtures, 5e-4
|
||||
to 2.7e-3 on the other four, the size of either engine's distance from llama.cpp;
|
||||
- the four DMA runs repeated: byte-identical dumps.
|
||||
|
||||
Open in the ticket: on the 4090 the resident and DMA dumps were the same bytes; here `auto` DMA and `2000` DMA differ
|
||||
from each other although the GPU computes every miss (the adaptive tier was on: 139 to 384 experts swapped in during the 64
|
||||
tokens), and no all-resident run fits this card at fp16 to compare against. Closed in the REGINA-111 section at the end: the
|
||||
`2000, DMA` column is not a GPU-only path (its logs read `CPU experts` 0.22 to 0.73 per layer), and the five misses are
|
||||
the reference's own spread.
|
||||
|
||||
**The checks.** `a5.py` of the 4090 section unchanged, the measured ladder's launch (`--mtp qwen36-mtp-draft-full
|
||||
--ctx 262144 --threads 8 ... -- --kv q4_0`; the 4090 table used the subset head), greedy, client and server on the VM.
|
||||
All nine checks pass in all three configurations.
|
||||
|
||||
| check | Q4_K_XL, no cap (3,141 slots) | Q4_K_XL, `--vram-cap 6144` (397 slots) | IQ3_XXS, `--vram-cap 6144` (1,258 slots) |
|
||||
| --- | --- | --- | --- |
|
||||
| (a) chat, not streamed, thinking off: "capital of France" | pass, 0.61 s | pass, 0.74 s | pass, 0.77 s |
|
||||
| (a) chat, not streamed, thinking on: 17 x 23 = 391 | pass, 314 tokens at 63 tok/s | pass, 321 at 43 | pass, 412 at 53 |
|
||||
| (b) stream, thinking on: reasoning deltas, first, largest gap | 520, 0.345 s, 108.6 ms | 466, 0.528 s, 131.9 ms | 420, 0.491 s, 105.1 ms |
|
||||
| (b) the same request: content deltas, first, largest gap | 89, 8.328 s, 82.6 ms | 89, 11.604 s, 142.8 ms | 55, 8.323 s, 108.1 ms |
|
||||
| (b) the same request: tokens, decode, largest gap between any two deltas | 612 at 63 tok/s, 108.6 ms | 558 at 41, 142.8 ms | 478 at 54, 108.1 ms |
|
||||
| (b) stream, thinking off (the ticket's request): content deltas, first, largest gap | 207 of 208 tokens, 0.364 s, 73.0 ms | 213 of 214, 0.515 s, 83.2 ms | 204 of 205, 0.471 s, 84.1 ms |
|
||||
| (c) tool round trip, not streamed: call, result, answer | pass: `get_weather {"city":"Paris"}`, `tool_calls`, then "17°C with light rain", `stop` | pass | pass |
|
||||
| (c) tool round trip, streamed | pass: reasoning 585 deltas, the call in 1 delta at 9.28 s; the answer in 14 content deltas | pass: 546 reasoning deltas, call in 1 at 13.72 s; 14 content deltas | pass: 169, call in 1 at 3.73 s; 18 content deltas |
|
||||
| (c) tools declared, not called, streamed, thinking on: content deltas, first, largest gap | 73, 11.704 s, 101.4 ms | 83, 23.747 s, 135.1 ms | 80, 14.626 s, 71.4 ms |
|
||||
| (c) the same, thinking off | 71, 0.102 s, 68.4 ms | 76, 0.164 s, 85.5 ms | 69, 0.140 s, 79.2 ms |
|
||||
| (d) three-turn chat, tokens reused of the prompt per turn | 0 / 23, 18 / 111, 106 / 154 | 0 / 23, 18 / 143, 138 / 184 | 0 / 23, 18 / 165, 160 / 221 |
|
||||
|
||||
The largest gap between any two deltas in any stream is 142.8 ms, a hundredth of the 15 s keepalive; no keepalive
|
||||
comment was sent in any run. The longest silence a client sees is the wait for the first content delta with thinking
|
||||
on, during which reasoning deltas arrive: 23.7 s at Q4 `--vram-cap 6144` (974 tokens at 43 tok/s). A streamed tool
|
||||
call still arrives whole, 9.3 to 13.7 s after the request for Q4, with reasoning deltas before it. `/health` after
|
||||
each run: `ram_reads` and `file_reads` 0 (the arena is pinned), VRAM hits per lookup 78% / 29% / 51%. VRAM after
|
||||
load 10,615 / 10,617 / 10,603 MiB (the cap holds the rest of the card back itself), 10,747 / 10,749 / 10,735 at the end.
|
||||
|
||||
(d) as on the 4090: the previous prompt less its 5-token header. `reuse.py` on Q4 no cap: with
|
||||
`preserve_thinking` and `reasoning_content` sent back, 942 of 961 and 1,267 of 1,285; without it 18 of 127 and 122 of
|
||||
170; thinking off 18 of 236 and 229 of 294.
|
||||
|
||||
**Decode speed with this binary** (`sweep_engine_ladder.py --host vm211 --threads 8 --no-depth --no-stability`, the
|
||||
ladder's method: cache dropped, fresh launch, regina twice and the short request; `speed/`):
|
||||
|
||||
| | regina rep 0 / rep 1, decode tok/s | short, decode tok/s | prefill 3.1K / 203 tokens, tok/s | drafts accepted (regina rep 1) | the ladder with 7ebc9e5: regina rep 1 / short |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Q4_K_XL, full card | 66.2 / **66.4** | 66.3 | 942 / 132 | 802 / 967 | 66.3 / 65.3 |
|
||||
| IQ3_XXS, full card | 83.3 / **81.2** | 77.8 | 911 / 193 | 792 / 958 | 81.0 / 77.4 |
|
||||
|
||||
No regression.
|
||||
|
||||
**Not checked.** pi against this card (check e); images; `--vram-cap 8192`; IQ3 at the full card through `a5.py`
|
||||
(its decode is in the speed row); the nondeterminism section's ten-request repeats on this card.
|
||||
|
||||
## REGINA-111: the five misses on the 1080 Ti
|
||||
|
||||
2026-10-13. **Verdict: no fault in the engine, on either card.** Two findings: the `2000, DMA` column above was not a
|
||||
forced path, and the two fixtures that miss are ones llama.cpp fails against itself. No engine source changed; the
|
||||
binaries are the ones above (`a44d896ccb25ff98` on VM 211, `b1575740af995a78` on VM 221). Material:
|
||||
`rk@192.168.50.43:/home/rk/bench/r111/` and `rk@192.168.50.151:/models/work/r111/` (`r111-*.sh` the drivers, `pos.py`
|
||||
and `dist.py` the per-position tables, `oracle_rows.py`, `SHA256.txt`).
|
||||
|
||||
**Why two "all GPU" configurations differed.** They were not both all GPU. The window's PCIe share is staged in 16
|
||||
VRAM blobs (`kStagingBlobs`, `verify.hpp:358`; 8 per group when a window runs as two groups, `verify.cpp:1705`), and
|
||||
the pool sends a miss to DMA only while `fetches < P.staging_cap` (`expert_source.cpp:2100`). A layer of a window with
|
||||
more than 16 distinct misses computes the rest on the CPU, whatever `--pcie-frac` says. A 4-token window routes 32
|
||||
experts; with 2,399 of 10,240 slots resident that limit is reached, with 4,240 or 8,061 it is not.
|
||||
|
||||
- `STRATA_POOL_TRACE=1` on q4-test20, `--expert-cache 2000 --pcie-frac 1.0`: 46 of 680 layer calls publish 16 fetches
|
||||
and then run 1 to 16 CPU jobs; no call with fewer than 16 fetches runs any. The first is window 1 (positions 1 to
|
||||
4), layer 0: 16 by DMA, 12 on the CPU. The first logits row that differs from the `auto` run is position 3.
|
||||
- With `--spec 2` (at most 16 routed experts a window) the log reads `CPU experts 0.00`, and the `2000` and `auto`
|
||||
dumps are the same bytes, for both fixtures; for q4-test20 they are also the bytes of the `auto` run at `--spec 4`
|
||||
(`790e501683ea6af6`). The GPU path on sm_61 does not depend on what is resident or on the window's shape.
|
||||
- The 4090 does the same: `--expert-cache 2000 --pcie-frac 1.0` at `--spec 4` reads `CPU experts` 0.33 (Q4) and 0.68
|
||||
(IQ3) per layer and its dumps differ from the all-resident ones; at `--spec 2` they are the all-resident bytes
|
||||
(`e4e5fdc81b4bc604`, `de2fd0e08c2e6679`). The earlier resident-against-DMA identity there was measured at
|
||||
`--expert-cache 8000`, which never reaches 16 misses. Nothing here is specific to Pascal.
|
||||
|
||||
So in the A5 table the `auto, DMA` column is the GPU path (`CPU experts 0.00` in all six logs) and the `2000, DMA`
|
||||
column is the GPU path with 0.22 to 0.73 CPU-computed experts per layer mixed in. A run meant to force the GPU path
|
||||
has to show `CPU experts 0.00`; `--spec 2` guarantees it.
|
||||
|
||||
**The soft positions.** The fixtures' reference is llama.cpp on the 4090, every layer offloaded. The same pinned
|
||||
llama.cpp was teacher-forced along the same ids on VM 211, once with no layer offloaded (`--ngl 0`, "CPU" below) and once on the 1080 Ti with
|
||||
what fits (28 of 41 layers for IQ3, 15 of 42 for Q4), and `ref/qwen36.py` (the numpy oracle: F32 weights as
|
||||
dequantized, F32 activations, its own routing) was run over prompt and continuation in one pass, plain and with
|
||||
`--act-quant q8`. Each run against the fixture's reference, and against the F32 oracle (top-1 of 64, mean KL, the
|
||||
largest KL and its position; **bold** misses the rule's thresholds):
|
||||
|
||||
| run | q4-test20 vs llama.cpp 4090 | q4-test20 vs F32 oracle | iq3-prime-add vs llama.cpp 4090 | iq3-prime-add vs F32 oracle |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| llama.cpp, the 4090 (the reference) | - | **61**, 6.1e-3, 0.141 (8) | - | 64, 7.6e-3, 0.316 (40) |
|
||||
| llama.cpp, CPU | **60**, 9.2e-3, 0.174 (8) | 63, 5.5e-3, 0.079 (8) | 62, **2.72e-2**, 1.400 (40) | 62, **1.48e-2**, 0.626 (40) |
|
||||
| llama.cpp, the 1080 Ti, partly offloaded | **60**, 9.9e-3, 0.199 (8) | 63, 5.7e-3, 0.087 (8) | 62, **2.70e-2**, 1.368 (40) | 62, **1.31e-2**, 0.570 (40) |
|
||||
| engine, 1080 Ti, GPU only (`auto`, DMA) | **61**, 8.5e-3, 0.138 (8) | 64, 4.3e-3, 0.050 (10) | 64, **1.26e-2**, 0.416 (40) | 64, 4.5e-3, 0.066 (48) |
|
||||
| engine, 1080 Ti, `auto`, CPU misses | 62, 6.0e-3, 0.049 (10) | 62, 7.0e-3, 0.161 (8) | 64, 4.5e-3, 0.062 (54) | 64, 5.9e-3, 0.244 (40) |
|
||||
| engine, 1080 Ti, `2000`, GPU with the CPU overflow | 62, **1.17e-2**, 0.323 (8) | 63, 6.5e-3, 0.122 (8) | 63, **1.18e-2**, 0.467 (40) | 63, 7.4e-3, 0.141 (40) |
|
||||
| engine, 1080 Ti, `2000`, CPU misses | **61**, 8.3e-3, 0.086 (8) | 62, 5.7e-3, 0.083 (8) | 64, 4.8e-3, 0.073 (45) | 64, **1.22e-2**, 0.612 (40) |
|
||||
| engine, 4090, all resident | **61**, 7.4e-3, 0.147 (8) | 64, 3.8e-3, 0.040 (8) | 64, 6.6e-3, 0.152 (40) | 64, 3.5e-3, 0.082 (40) |
|
||||
| Q8 oracle | | 63, 7.5e-3, 0.109 (8) | | 64, 7.6e-3, 0.186 (45) |
|
||||
|
||||
llama.cpp on another back end misses the rule against its own 4090 run on both fixtures, by more than any engine run
|
||||
does. Against the F32 oracle the engine's GPU path is inside the thresholds on both cards (1080 Ti 64 of 64 at 4.3e-3
|
||||
and 4.5e-3; 4090 64 of 64 at 3.8e-3 and 3.5e-3) and nearer the oracle than the reference is (61 at 6.1e-3; 64 at
|
||||
7.6e-3). The 1080 Ti is 0.5e-3 and 1.0e-3 farther from the oracle than the 4090, 64 of 64 on both.
|
||||
|
||||
The positions themselves (margins are logits, first candidate minus second; KL against the reference / the F32 oracle):
|
||||
|
||||
| position | llama.cpp 4090 | llama.cpp CPU | llama.cpp 1080 Ti | engine 1080 Ti, GPU only | engine 4090, resident | F32 oracle |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| q4-test20, 8: " operation" / " expression" / " list"; entropy 4.2 nats | " operation" by 0.21 (p 0.21 / 0.17); - / 0.141 | " list"; 0.174 / 0.079 | " list"; 0.199 / 0.087 | " list"; 0.138 / 0.029 | " list"; 0.147 / 0.040 | " list" (p 0.15) |
|
||||
| q4-test20, 9: ":" / "?" | ":" by 0.15 | "?" by 0.14 | "?" by 0.18 | "?" by 0.27 | "?" by 0.30 | "?" by 0.13 |
|
||||
| q4-test20, 13: " Extract" / " Take" | " Extract" by 0.13 | " Take" by 0.08 | " Take" by 0.12 | " Take" by 0.28 | " Take" by 0.20 | " Take" by 0.07 |
|
||||
| iq3-prime-add, 40: "user" / `<\|im_start\|>` | "user" by 2.70 (p 0.86); - / 0.316 | `<\|im_start\|>` by 1.57; 1.400 / 0.626 | `<\|im_start\|>` by 1.26; 1.368 / 0.570 | "user" by 0.30; 0.416 / 0.053 | "user" by 0.96; 0.152 / 0.082 | "user" by 0.77 (p 0.55) |
|
||||
|
||||
At q4-test20 positions 8, 9 and 13 every other source, the F32 oracle included, picks what the engine picks: the three
|
||||
"misses" are the 4090 llama.cpp run standing alone at near ties. iq3-prime-add position 40 is the fifth token after
|
||||
the reply's `<|im_end|>` (position 35), in `<|im_end|>\n<|endoftext|><|im_start|><|im_start|>user`: text no request
|
||||
is ever served, where llama.cpp's own back ends differ by 4.3 logits on the margin (+2.70 to -1.57) and the engine sits
|
||||
between them, next to the oracle. On that fixture positions 0 to 35 read mean KL 2.7e-3 (largest 0.025) for the 1080
|
||||
Ti's GPU path and 3.4e-3 (0.071) for the 4090; positions 36 to 63 read 2.5e-2 and 1.1e-2, and llama.cpp's CPU run
|
||||
5.5e-2.
|
||||
|
||||
**Is 0.4 at one position acceptable.** Per-position KL against the reference, the 24 runs of the table above and
|
||||
the 4090's six: the median is 1e-6 to 2.5e-3 in every run and the 90th percentile at most 2.4e-2. 17 of 30 runs
|
||||
have no position above 0.05. Positions above 0.1 exist only on these two fixtures: position 8 of q4-test20 (0.138 to
|
||||
0.323 in three of five runs) and positions 40, 42 and 48 of iq3-prime-add (0.416, 0.128, 0.119 in the GPU-only run;
|
||||
0.467 with the overflow; 0.152 on the 4090). With its largest position left out no run's mean is above 7.1e-3. A KL
|
||||
of 0.4 at a position where two llama.cpp back ends are 1.4 apart measures the reference, not the engine; the same
|
||||
0.4 at a position where they agree to 1e-2 would be a fault; no position of the other four fixtures is above 0.1.
|
||||
|
||||
**Proposed for the rule, not adopted** (the thresholds 62 of 64 and 1e-2 stand as written until decided):
|
||||
|
||||
1. Score positions up to and including the reference's first stop token only (36 of 64 on iq3-prime-add; the other five
|
||||
fixtures do not stop), or regenerate that fixture to hold 64 positions before the stop.
|
||||
2. Keep a second llama.cpp run per fixture (`--ngl 0`, forced along the same ids; under half a minute each) and
|
||||
report, not gate, the positions where the two llama.cpp runs disagree on top-1 or differ by more than 0.05 KL, as
|
||||
the runner tests already do where the F32 and Q8 oracles disagree. q4-test20 loses positions 6, 8, 9, 13, 15;
|
||||
iq3-prime-add loses 0, 2, 8, 40. The thresholds become shares of what is left (96.9% and 1e-2).
|
||||
3. A forced-GPU run counts only with `CPU experts 0.00` in its log.
|
||||
|
||||
With 1 and 2 all eight 1080 Ti runs of the two fixtures pass: q4-test20 59 of 59 in each, mean KL 5.2e-3 to 5.8e-3;
|
||||
iq3-prime-add 33 of 33 in each, 8.9e-4 to 2.1e-3.
|
||||
|
||||
**Left as it is, for a decision.** `--pcie-frac 1.0` does not force the GPU past 16 distinct misses per layer and
|
||||
window (8 per group). README line 232 and the paragraph "For a run that must repeat" above promise repeats from that
|
||||
flag; with a small cache (the 1080 Ti at `--expert-cache 2000`, or a `--vram-cap` configuration) the overflow runs
|
||||
on the CPU and the adaptive tier can then move a request between passes as in the CPU rows of that section. Sizing the
|
||||
staging to the window (8 blobs per token: 16 more at 4 tokens, under 58 MiB at Q4) would make the flag exact; it also moves
|
||||
the default share's ceiling, so it changes what the ladder measured and was not done here.
|
||||
|
||||
**Not checked.** A Pascal-against-Ada bisect by layer: the two cards run different kernels from the prompt on (the
|
||||
BF16 GEMM through fp32 and no tensor-core MoE on sm_61), so they are not expected to agree in bytes, and each agrees
|
||||
with the F32 oracle to 4e-3; the other four fixtures against the oracle or a second llama.cpp run; llama.cpp fully
|
||||
offloaded on a second card (neither file fits the 1080 Ti); whether the overflow makes a served request differ between
|
||||
passes (inferred from the CPU rows above, not run); the 262,144 q4_0 configuration.
|
||||
|
||||
## Flash-Next regression check
|
||||
|
||||
2026-10-13, VM 221 (RTX 4090, 62 GB RAM), card otherwise idle. Does the branch still serve Qwen3.8-Flash-Next as the
|
||||
production binary does? Production: `/tank/nvme/strata/unbiased-strata`, sha256 `abbe990f4e3c658e` (main's lineage
|
||||
with 121d23a). Branch: `/models/work/qwen36-step4/build/unbiased-strata`, `11da5388afdfabcb` at d00d383 and
|
||||
`5428c8d791f7a697` at 0513d5b. Both started by hand with the command line of `unbiased-strata.service` on
|
||||
127.0.0.1:18091 (`--ctx 196608 --mmproj ... --threads 8 -- --kv-resident 32768 --ple-io mmap --kv int8`,
|
||||
`CUDA_MODULE_LOADING=EAGER`, memlock unlimited; the unit's first-prompt capture variable left out so the captured file
|
||||
was not overwritten). Scripts and logs: `/models/work/flashcheck/`.
|
||||
|
||||
**One fault, fixed (REGINA-112).** The branch took f07b81e from main but not 121d23a, so its front end sized
|
||||
`max_new` as context - prompt and the engine (prompt + max_new + 8 <= context) refused every request that sent no
|
||||
`max_tokens`, and any with `max_tokens` at or above context - prompt - 7, with a 500. The serving checks below did
|
||||
not see it because each sets `max_tokens`. 0513d5b carries main's hunk and `tests/python/serve_max_tokens_check.py`
|
||||
(`make test-serve PORT=...`): 0 of 5 on `11da5388`, 5 of 5 on production and on `5428c8d7`, the latter on Flash-Next
|
||||
at 196,608 and on Qwen3.6 Q4_K_XL at 262,144.
|
||||
|
||||
**Serving**, `a5.py` of the A5 section and one image request, on both branch binaries:
|
||||
|
||||
| check | d00d383 | 0513d5b |
|
||||
| --- | --- | --- |
|
||||
| start, plan | 10,368 expert slots (production 10,373), 430 MiB free, KV 32,768 of 196,608 cells resident | the same |
|
||||
| `/health`, `/v1/models` | ok, tiers; `input_modalities` text, image | ok |
|
||||
| chat, not streamed, thinking off / on | pass / pass (391) | pass / pass |
|
||||
| stream, thinking on: reasoning deltas, content deltas | 84, 41 of 128 tokens, largest gap 77 ms | 90, 50 of 143 |
|
||||
| stream, thinking off: content deltas | 193 of 194 tokens | 200 of 201 |
|
||||
| tool round trip, not streamed / streamed | pass / pass (the call in 1 delta, the answer in 14) | pass / pass (16) |
|
||||
| tools declared, not called, streamed, thinking on / off | 79 / 90 content deltas | pass / pass |
|
||||
| three turns, tokens reused of the prompt | 0 / 65, 60 / 138, 133 / 169 | 0 / 65, 60 / 145, 140 / 176 |
|
||||
| image (96 x 96 PNG, red left, blue right) | pass, 1.0 s, 41 prompt tokens | pass |
|
||||
|
||||
**Speed**, greedy, reasoning off: 4 prompts of 400 tokens and 2 prompts of 19,593 and 20,820 tokens, five passes per
|
||||
start, production, branch (d00d383), production, branch. The host holds 62 GB against 76 GB of model files, so
|
||||
14,208 of the 24,576 experts and the n-gram table are read through the file cache and the first two passes of a start
|
||||
measure the cache (60 tokens/s and 700 prompt tokens/s on both binaries on the first pass). The table is passes 3 to
|
||||
5, tokens over time, per start:
|
||||
|
||||
| | Generation, tokens/s | Prompt, tokens/s |
|
||||
| --- | --- | --- |
|
||||
| Production | 89.5, 92.1 (74 to 109 per prompt) | 2,093, 2,098 |
|
||||
| Branch | 89.0, 89.2 (74 to 107) | 2,092, 2,094 |
|
||||
| Branch / production | 0.98 | 1.00 |
|
||||
|
||||
Drafts accepted 0.61 to 0.62 of those offered on both. The 2% in generation is inside the spread between the two
|
||||
production starts.
|
||||
|
||||
**ctest**, the branch build at d00d383 on the free card: 94 of 98 pass, `pack_load_check` skipped, and the three
|
||||
host failures (`ple_parity`, `platform_memory_test`, `expert_multi_test`).
|
||||
|
||||
**On main.** main at e7ae2c8 builds the same binary as 0513d5b (`5428c8d791f7a697`). One more start of each, same
|
||||
requests, passes 3 to 5: production 90.6 tokens/s and 2,097 prompt tokens/s, main 90.4 and 2,091 (1.00, 1.00).
|
||||
|
||||
### Both models on the one 4090, two processes
|
||||
|
||||
One process serves one model: the front end loads one `--model`, starts one engine child, and answers every request
|
||||
with it whatever the request's `model` field says. Two models are two processes on two ports. Tried once, main's
|
||||
binary, Flash-Next on 18091 and Qwen3.6 IQ3_XXS at 262,144 on 18092, `--threads 8` each on 16 vCPUs:
|
||||
|
||||
- **`--vram-cap` does not partition a card.** It allocates a blocker of total - cap, so one capped engine holds the
|
||||
whole card. What works: start Flash-Next first with a fixed `--expert-cache N`, then Qwen3.6 uncapped, whose plan
|
||||
takes what is free. `--expert-cache 4000` gave Flash-Next 5,357 slots and 15.4 GB of the card, with 8.8 GB free;
|
||||
Qwen3.6 then planned a 4,331 MiB fixed set and 3,187 of 10,240 expert slots (8.1 GB), 447 MiB left. At
|
||||
`--expert-cache 6000` (8,053 slots) 4.3 GB stayed free, below Qwen3.6's fixed set.
|
||||
- **RAM binds first on this host.** Flash-Next alone uses 47 of 62 GB (its 40 GiB expert arena is pinned). With
|
||||
Qwen3.6 beside it 60 GB were used and 2 GB available; Qwen3.6 found too little to pin its 7,053 off-card experts
|
||||
and mapped them from the file, and took 239 s to start. No swap, no OOM kill in this run.
|
||||
- **Idle costs nothing, concurrency costs most of both.** An idle engine shows 0% GPU. 4 prompts of 400 tokens,
|
||||
greedy, reasoning off, tokens/s:
|
||||
|
||||
| | Flash-Next | Qwen3.6 IQ3_XXS |
|
||||
| --- | --- | --- |
|
||||
| Alone on the card, service configuration (10,368 slots) | 90 | |
|
||||
| Alone, `--expert-cache 4000` (5,357 slots) | 54 | |
|
||||
| The other engine loaded and idle | 45 | 133 |
|
||||
| Both generating | 12 | 27 |
|
||||
|
||||
Requests to both at once complete without error; each engine runs at about a quarter of its speed with the other
|
||||
idle. Two CUDA contexts time-slice the card, each engine's verify graph spins on the GPU while it waits for its
|
||||
host, and 16 pool workers plus two host threads share 16 vCPUs. Not separated which of the three costs what.
|
||||
@@ -1,106 +0,0 @@
|
||||
# Upstream Strata tooling the Qwen3.6 port needs back
|
||||
|
||||
Surveyed 2026-10-11. Read-only references:
|
||||
|
||||
- `/Users/robertkarl/Code/strata-upstream-6f32ec0`: exact snapshot, exported with `git archive 12a7825` from this repository's first commit ("Import Strata at 6f32ec0, unmodified"). Use this one.
|
||||
- `/Users/robertkarl/Code/strata-upstream`: a clone of `Niko1221/Strata` main (1859 commits). **Commit `6f32ec0` is not in the public history**: `git checkout` fails with "unable to read tree", so the pinned commit was force-rewritten or never public. Main still carries the same tooling and adds `bench/bench_vs_llama.py`.
|
||||
|
||||
Nothing was built. UnbiasedStrata was not modified.
|
||||
|
||||
## 1. The finding that changes the plan
|
||||
|
||||
Upstream's Python oracle is **not** published. `ref/` contains only `ref/load.py`, in the snapshot and in main, in every commit. The engine source cites `ref/gdn.py` (22 times), `ref/qsa.py` (26), `ref/moe.py` (12), `ref/gr.py` (11), `ref/ngram.py` (10), `ref/model.py` (9) and `ref/quant.py` (7), and `docs/semantics.md` and `docs/activation-contract.md` do not exist in any commit. The same holds for `bench/micro/` (the ggml-oracle tests), `tests/python/gen_ple_oracle.py`, `scripts/_gen_f16_oracle.py` and `tests/CMakeLists.txt`. The published CMake says so: "the test suite and the micro benchmarks live in tests/ and bench/micro/, which the published source leaves out".
|
||||
|
||||
So the Maya recipe (`ref/glm.py` plus a synthetic GGUF and dumps) has no upstream Strata counterpart to restore for the mixers or the MoE. What is restorable is `ref/load.py`, the pack tools, the in-C++ parity tests, and the discipline. The Qwen3.6 oracle is new code. It is specified from the pinned llama.cpp graph `third_party/llama.cpp/src/models/qwen35moe.cpp`, as Maya specified `ref/glm.py` from `glm5-next.cpp`.
|
||||
|
||||
## 2. Inventory
|
||||
|
||||
### `ref/`
|
||||
|
||||
- `ref/load.py` (212 lines). `Gguf(path)`: a demand-paged view of a possibly sharded GGUF (shard discovery from the `-0000N-of-0000M` suffix, a directory, or a list). `tensor(name)` returns FP32 shaped (out, in[, experts]). `expert(name, e)` decodes one expert of a fused `[in, out, experts]` tensor without touching the others. `rows(name, idx)` gathers rows of a 2-D tensor (built for the 27 GB PLE table; Qwen3.6 has no PLE). One dequant dispatch `_dequant_flat`: F32, F16, BF16 by hand; Q2_0 through `tools/gguf_writer.dequantize_q2_0`; everything else through gguf-py `quants.dequantize` (the table GEOM holds 13 entries: F32 F16 BF16 Q4_0 Q5_0 Q8_0 IQ4_NL Q3_K Q4_K Q5_K Q6_K IQ4_XS Q2_0). It lacks Q4_1, Q5_1, Q2_K and the IQ1/IQ2/IQ3 types the engine itself serves; a Q4_K_M or UD-Q4_K_XL Qwen3.6 file needs only Q4_K, Q5_K, Q6_K, Q8_0, F32, BF16 or F16, all present. It imports `gguf` without adding it to `sys.path`, so `PYTHONPATH` or `STRATA_GGUF_PY` must point at gguf-py (see section 5).
|
||||
|
||||
### `tools/` (the ones a port uses)
|
||||
|
||||
- `tools/iq_pack.py` (602 lines). The native-pack builder, described in section 4. Hardcodes Flash-Next assumptions listed in section 6.
|
||||
- `tools/gguf_reader.py` (142). A GGUF v3 header reader with no gguf-py dependency; knows ggml type ids to 42 (Q2_0). Used by `iq_pack`, the tokenizer exporter and `ref/load.py`. It is the Python twin of `src/artifact/gguf_reader.cpp`.
|
||||
- `tools/gguf_writer.py` (234). A minimal GGUF v3 writer with a Q2_0 quantizer. Its self-test writes a synthetic file with `general.architecture = qwen4exp`. Not a model generator.
|
||||
- `tools/iq_fixture.py` (137). Writes deterministic i-quant blocks plus gguf-py's dequantized reference for `iq_parity` (see section 3). It is the one fixture generator upstream ships.
|
||||
- `tools/test_iq_pack.py` (528). The closest thing to a synthetic-GGUF generator upstream ships: `write_gguf()` builds tiny sharded GGUFs with gguf-py's `GGUFWriter` and `quants.quantize`, then asserts pack behaviour (BF16 rounding to even, refused inexact F32 routers, split shards, a layer split across shards, interrupted packs, stale `experts.bin`). Arch string is `qwen4exp`.
|
||||
- `tools/make_profile.py` (119). Writes `expert-profile.bin`, a ranking of every (layer, expert) pair, from the base profile plus routing traces from `generate --dump-routing FILE`. Has `--n-expert` but `N_LAYER = 48` is hardcoded (line 26) and the output header carries layer and expert counts that the engine checks. Test: `tools/test_make_profile.py`. The shipped `data/expert-profile.bin` is for Flash-Next and is useless for Qwen3.6 (40 layers, 256 experts).
|
||||
- `tools/mtp_fetch.py` (308). Range-reads the 31 `mtp.*` tensors out of the 131-shard BF16 checkpoint over HTTP and verifies SHA256s (`inventory`, `fetch`, `verify`). Pinned to Qwen3.8-Flash-Next.
|
||||
- `tools/mtp_pack.py` (193). Quantizes those tensors into an MTP GGUF (`--experts q2_0|q4_0|q8_0`). Hardcodes the Flash-Next tensor names and the 512-expert fused shapes.
|
||||
- `tools/mtp_rt.py` (111). Turns the MTP GGUF into the engine's runtime files: `experts.bin`, `dense.bin`, `dense.txt`. Applies Gemma-style `+1` to RMSNorm weights.
|
||||
- `tools/draft_vocab.py` (+ `test_draft_vocab.py`). Extends `draft_vocab.bin`, the token subset the draft head may propose, by script (`--add han|kana|...`) or corpus (`--corpus`, `--coverage`). Data files `data/draft_vocab*.bin` are tied to the Flash-Next vocabulary of 248,320 tokens.
|
||||
- `tools/strata_tokenizer.py` (331). Exports `tokenizer/` (vocab, merges, chat template) from GGUF metadata. Refuses pre-tokenizer schemes it has not transcribed; Qwen3.6 uses `qwen35`, same family as Flash-Next. Called by `iq_pack` when `<out>/tokenizer/` is missing. Needs `regex`.
|
||||
- `tools/strata_pack.py`, `pack_layer.py`, `pack_index.py`, `canonical_xcheck.py`. The canonical Q2_0 pack (bakes in the 1,382,400-byte Flash-Next blob). The plan says Qwen3.6 rides the native pack instead, so these are reference only. `canonical_xcheck.py` shows the "bit-exact against gguf-py over every block" style.
|
||||
- `tools/calibrate.py`, `needle_bench.py`, `batch_test.py`, `test_conversation_cache_*.py`. Server-level measurement and regression harnesses. `calibrate.py` tunes `--pcie-frac`, `--spec-min-p`, `--pool-workers` through an engine's per-request keys. `needle_bench.py` is recall at 32K to 262K through the HTTP API. `batch_test.py` checks batched against solo greedy tokens.
|
||||
- `tools/_paths.py`. Finds gguf-py: `$STRATA_GGUF_PY`, then `<repo>/third_party/llama.cpp/gguf-py`. That second path exists in this fork's submodule, so the tools work unmodified.
|
||||
- Not needed: `setup.py`/`test_setup_*.py` (the installer), `strata_mcp.py`, `embd_bf16_pack.py`, `ple_fp8_pack.py` (Flash-Next PLE), `hip/`, `vision/`.
|
||||
|
||||
### `tests/` and the parity sources
|
||||
|
||||
- `tests/` in the snapshot has 30 files and no `CMakeLists.txt`: `tests/core/*.cpp` (loader and cache tests, `gguf_fixture.hpp` is a C++ synthetic-GGUF writer with pattern-filled tensors), `tests/cuda/prefill_*_test.cpp`, `tests/hip/*`, `tests/data/native_experts/*.txt` (golden `native_experts.txt` files for q2_0, iq2_xs, iq3_s, iq3_xxs, coder-iq1_m, swift-iq2_xs).
|
||||
- The root `CMakeLists.txt` references 23 `tests/` sources that are **absent in UnbiasedStrata** (the snapshot has 30 files there), and four `bench/micro/*` sources that upstream never published. Configuring this fork with `-DSTRATA_BUILD_TESTS=ON` would fail at `tests/core/gguf_split_test.cpp` (line 231). Restoring `tests/` fixes all but the `bench/micro` ones, which sit under the oracle option.
|
||||
- The 36 `src/kernels/*_parity.cpp` files, `src/prefill/gdn_rec_parity.cu`, `src/prefill/gemm_bf16_parity.cu` and `src/kernels/cpu/*_parity.cpp` are **still in UnbiasedStrata**. Relevant to the port: `gdn_parity.cpp`, `router_top10_parity.cpp`, `shared_expert_parity.cpp`, `gr_parity.cpp` (the Flash-Next hyper-connection residual, which Qwen3.6 lacks), `rope_parity.cpp`, `qsa_parity.cpp` (indexer path, bypassed for dense attention), `native_expert_parity.cpp`, `native_grouped_parity.cpp`, `sampler_parity.cpp`, `kv_*_parity.cpp`, `iq_parity.cpp`, `gdn_rec_parity.cu`.
|
||||
|
||||
### Docs
|
||||
|
||||
- `docs/semantics.md`, `docs/activation-contract.md`: **do not exist upstream** (no commit). The semantics live in comments in the parity files and in the unpublished `ref/*.py`.
|
||||
- `docs/ORCA.md` (95 lines) and `ORCA_Q4_K_S.md` (36). These are the precedent for a **different quantization of the same geometry** (512 experts), not for a different expert count: `iq_pack.py --compat-bf16` rounds the small projections the engine reads as BF16, records each in `compat-bf16.json`, and the pack carries its own tokenizer and `dense.bin`. The precedent for a **different expert count** is the Coder (256 of 512 experts): `iq_pack` reads `n_expert` from the router's shape, `make_profile.py --n-expert 256`, and `tests/data/native_experts/coder-iq1_m.txt`. `docs/MODELS.md` describes it.
|
||||
- `docs/DETAILS.md` (1127 lines; this fork keeps it as `docs/upstream/DETAILS.md`), `docs/HOW_IT_WORKS.md`, `docs/OLDER_GPUS.md`, `docs/NVIDIA_V100.md`, `docs/paper/`.
|
||||
|
||||
### `bench/`
|
||||
|
||||
- Snapshot: results only (`bench/results/<date>-<topic>/` with `README.md`, `matrix.md`, `matrix.json`). Useful as the format for reporting. The speed matrix of `2026-09-28-speed-0114` records the flags the setup writes (`--prefill auto`, `--expert-cache auto`, `--kv-resident`, `--spec 4 --spec-min-p 0.5`).
|
||||
- Main only: `bench/bench_vs_llama.py` drives Strata's and llama.cpp's OpenAI-compatible servers with the same prompts and GGUF, takes server-side prompt and decode tokens per second, peak VRAM from `nvidia-smi` polling, RSS from `psutil`, interleaves engines across rounds, and has `prompts`, `run`, `quality`, `summary` subcommands. Needs `psutil`. This is the closest match for the plan's baseline-versus-engine comparison, and it is not in the pinned snapshot.
|
||||
- The engine itself prints a `strata decode GPU stages (ms/window)` line and takes `--dump-routing` (`src/program/generate.cpp:1310`).
|
||||
|
||||
## 3. How upstream produces oracle dumps for a parity test today
|
||||
|
||||
1. There is no dump pipeline for the model. No script in the published tree runs a forward pass of the model and writes per-seam tensors. Everything below is what exists.
|
||||
2. Most parity tests are self-contained: the oracle is a **host C++ transcription of the spec**, inside the test file. `gdn_parity.cpp` has `ref_step()` and `ref_conv()` "a transcription of `ref/gdn.py`", in double precision, with boolean switches for the rival readings. `router_top10_parity.cpp` has `reference()` (softmax, stable sort, renormalise). Random inputs come from `std::mt19937(2024)`. Nothing is read from `data/`.
|
||||
3. Registration: `add_test(NAME gdn_parity COMMAND gdn_parity --selftest)` in the root `CMakeLists.txt` under `if(STRATA_BUILD_TESTS)` and a CUDA or HIP backend. `STRATA_BUILD_TESTS` defaults ON only when `tests/CMakeLists.txt` and `bench/micro` both exist, so a published checkout builds none of it unless `-DSTRATA_BUILD_TESTS=ON` is given. Run with `ctest` or the binary with `--selftest`. Exit 0 pass, 1 fail, 77 or 3 skip (`SKIP_RETURN_CODE`).
|
||||
4. Vector tests embed the oracle as a generated header: `ple_oracle_vectors.inc` ("GENERATED by tests/python/gen_ple_oracle.py") holds token windows and expected hash rows; `qsa_oracle_vectors.inc` holds float32-to-float16 bit pairs from `np.float16(np.float32(x))`. Both generators are unpublished. Regenerating means rewriting them.
|
||||
5. Fixture tests generate files into the build directory at test time: `iq_parity_fixtures` runs `tools/iq_fixture.py --out <build>/iq_fixture`, which writes `<name>.bin` (int32 header: kernel type id, rows, cols, then raw block bytes) and `<name>.f32` (reference values from gguf-py). `iq_parity <dir>` reads them. CMake probes interpreters for numpy (`-DIQ_FIXTURE_PYTHON` overrides) and uses `FIXTURES_SETUP`/`FIXTURES_REQUIRED` for ordering. This is the only dump-like flow in the published tree, and only for dequantization.
|
||||
6. Real-GGUF tests take a path from an environment variable or argument: `STRATA_PLE_GGUF` (default `../../Q2_0/...-00002-of-00002.gguf`) and `--pack`, plus binary captures `bench/micro/ple_in.bin` and `ple_out.bin` recorded from ggml's graph by an unpublished `ple_layer_xcheck.cpp`, which "records EVERY intermediate" so a failure is attributable to a stage.
|
||||
7. The independent-oracle tests (`bench/micro/native_{mmvq,bf16,shared,gr_norm,moe,gdn,gr_postops,router,gdn_preprocess,gdn_pipeline,qsa,rope,ple_postops,flash_attn,qsa_indexer,qsa_score}_parity.cpp`) link a pinned llama.cpp CUDA build as the oracle: `-DSTRATA_ORACLE_SOURCE_DIR=<llama.cpp>` and `-DSTRATA_ORACLE_BUILD_DIR=<build>` (CMake lines 387 to 408; libraries `ggml`, `ggml-base`, `ggml-cpu`, `ggml-cuda` located with `find_library`). These sources are unpublished, so the 16 names are a list of what to rewrite, and the CMake foreach is the wiring to restore.
|
||||
8. No dump file naming convention exists upstream. Maya's convention (llama.cpp `cb()` names, files under `data/glm5-synth-dumps/`) is the one to adopt.
|
||||
|
||||
**Negative-test discipline, from `gdn_parity.cpp`.** Before the kernel is judged, each wrong reading of the spec is computed with the same reference and must differ from the right one by more than 5 % (relative L1). Four traps are pinned: modulo versus interleaved head pairing, decay before versus after the rank-1 update, conv slide direction (state rows labelled so every position is identifiable), and `l2_norm`'s epsilon on the squared norm versus the mean. It prints `yes` or `*** NO ***` for "is the rival observable" and counts a failure when it is not. The first fixture for the decay trap showed only 3.25 % apart, so the gate and the input range were changed (decay in (0.0025, 0.135], beta in [0, 1)) until the trap was clearly visible. The state layout test fills the state with `0.001*(i + 2j + 3h) - 1` so a layout mix-up yields a different number, not a plausible one. `router_top10_parity.cpp` shows the same idea for selection: all-equal logits, a 12-way tie, a dominant expert, and an assertion that the 2^-14 renormalisation clamp is unreachable (top-k sum at least k/n). Comparisons are NaN-safe (`le`/`gt` demand finite values first) after a NaN fixture once printed a perfect score.
|
||||
|
||||
## 4. How a native pack is built from a GGUF
|
||||
|
||||
Entry point: `python tools/iq_pack.py --gguf <first-shard>.gguf --out <dir> [--compat-bf16] [--experts-bin] [--skip-experts] [--base <pack>]`. All sibling shards must exist (`Model.__init__` reads `-0000N-of-0000M`, a missing one is an error). `main()` runs `expert_layout()` first so a model that cannot be packed is refused before any file changes, then `index_standalone()`, then the tokenizer export, then writes `native_experts.txt` last.
|
||||
|
||||
- **`native_experts.txt`** is the completion marker and the expert map. One line per layer: `layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard]`. `gu_type` and `d_type` are ggml type ids (gate and up must match; down may differ, e.g. IQ3_XXS gate/up with Q2_0 down). `offset` is the layer's start in the virtual `experts.bin`. `blob_bytes` is the per-expert size of gate + up + down. The last three are absolute byte offsets of the three role tensors in their GGUF shard. Header `v3`; `v4` only if one layer's roles sit in different shards (column becomes `gate,up,down`). The engine reads the experts straight from the GGUF unless `experts.bin` exists. Golden examples: `tests/data/native_experts/*.txt`.
|
||||
- **`index.txt`**: "strata pack index v3", one row per non-expert tensor: `name, ?, kind, offset, bytes, arena_offset, arena_bytes, ne0, ne1, ...`. Kind 4 = BF16, 5 = F16, 2 = F32, 3 = F32 narrowed to F16 by the loader. A quantized tensor the engine serves natively from the GGUF has zero offsets and only its shape. The arena is 64-byte aligned.
|
||||
- **`dense.bin`**: the float tensors the engine reads from the pack, in the form it reads them (table `FORM`: routers, hyper-connection and indexer projections, SSM gates BF16; norms, `ssm_a`, `ssm_conv1d`, `ssm_dt.bias`, `ssm_norm` F32; PLE conv F16). Exact conversions are the default (F32 whose low 16 bits are zero to BF16; F16 or BF16 widened to F32). Rounding conversions need `--compat-bf16`. Anything the engine requires in a form the GGUF does not hold, without the flag, is a hard error.
|
||||
- **`conversions.json`** (schema 1): every converted tensor: shard, source and destination types, method, exact or not, max absolute error, SHA-256 of the source bytes, plus the source shard names and sizes.
|
||||
- Also: `experts.bin` plus `experts.bin.src.json` (optional, only with `--experts-bin`, reuse is checked by shard sizes, the hash of `native_experts.txt` and six sampled blobs), `tokenizer/`, and `compat-bf16.json` with the flag. All files are written under `.tmp` names and renamed, so an interrupted run leaves no completion marker.
|
||||
|
||||
## 5. Dependencies and GPU
|
||||
|
||||
- Pack tools and `ref/load.py`: Python 3.10+, `numpy`, gguf-py from llama.cpp (the submodule's `third_party/llama.cpp/gguf-py` works through `_paths.py`; `ref/load.py` needs `PYTHONPATH` set to it). `regex` for the tokenizer export. `requirements.txt` pins numpy, jinja2, regex, pyyaml, tqdm. `psutil` for `bench_vs_llama.py`. `mtp_fetch.py` uses the standard library's HTTP client.
|
||||
- **No torch, no safetensors library, no GPU** anywhere in `tools/` or `ref/`. The oracle is NumPy on the CPU. Maya's `ref/glm.py` is also NumPy; the full-attention and GDN loops are slow but small models are fine, and the synthetic GGUF keeps them fast.
|
||||
- GPU is needed only to run the C++ parity binaries and the engine.
|
||||
- For cross-checking, the submodule has `examples/eval-callback`, `src/models/qwen35moe.cpp`, `src/models/delta-net-base.cpp` and `convert_hf_to_gguf.py`. llama.cpp's `cb()` names in `qwen35moe.cpp` include `conv_output_silu`, `gate_sigmoid`, `beta_sigmoid` and `shared_expert_gate_sigmoid`.
|
||||
|
||||
## 6. Hardcoded Flash-Next assumptions found while reading (each must be generalized or bypassed)
|
||||
|
||||
- `iq_pack.py`: `FORM`/`ROUTERS` name Flash-Next tensors (`hc_*`, `indexer.*`, `ple_*`); `is_expert()` matches any `*_exps.weight`; `expert_layout()` takes `n_expert` from `blk.0.ffn_gate_inp.weight` and demands every layer to have all three expert tensors (true for qwen35moe, which has no dense-lead layers); tensors with more than two dimensions outside experts are refused; the `FORM` table has no qwen35moe entries, so SSM and attention tensors are served natively from the GGUF where quantized and copied as stored where float. Whether the engine needs `ssm_alpha`/`ssm_beta`, the router and the shared-expert gate as BF16 for the GDN and router kernels is a step 3 and 4 question; the `FORM` table is where that gets decided. `ffn_gate_inp_shexp.weight` is already in `ROUTERS`.
|
||||
- `make_profile.py`: `N_LAYER = 48`, `N_EXPERT = 512`.
|
||||
- `mtp_fetch.py`, `mtp_pack.py`, `mtp_rt.py`: Flash-Next tensor names, the 512-expert fused shapes, the revision pin. The Qwen3.6 MTP head comes from the MTP GGUF's `nextn` tensors per the plan.
|
||||
- `gdn_parity.cpp` and `src/kernels/cuda/gdn.cu`: the out-norm is `rms_norm(o) * ssm_norm * sigmoid(z)` (`gdn.cu:148`), and the parity test's negative case asserts SiLU is the wrong reading. llama.cpp's `qwen35moe` `build_norm_gated` uses `ggml_silu(gate)`. The test's geometry is fixed at S = 128, h_k = 16, h_v = 48 against Qwen3.6's 32 v-heads. Re-pin both before reusing either.
|
||||
- `tests/data/native_experts/` and `data/*.bin`: Flash-Next only.
|
||||
|
||||
## 7. What to restore and what to write
|
||||
|
||||
Restore into a dev checkout (copy from `/Users/robertkarl/Code/strata-upstream-6f32ec0`; a dev branch, or keep out of the fork's release tree):
|
||||
|
||||
1. `ref/load.py`.
|
||||
2. `tools/`: `_paths.py`, `gguf_reader.py`, `gguf_writer.py`, `iq_pack.py`, `test_iq_pack.py`, `make_profile.py`, `test_make_profile.py`, `strata_tokenizer.py`, `mtp_pack.py`, `mtp_rt.py`, `mtp_fetch.py` (for reference), `draft_vocab.py`, `iq_fixture.py`, `needle_bench.py`, `calibrate.py`, `batch_test.py`.
|
||||
3. `tests/` whole (30 files), so that `-DSTRATA_BUILD_TESTS=ON` configures. `bench/micro/` cannot be restored; the CMake foreach for the llama.cpp-oracle parity tests stays dormant.
|
||||
4. `requirements.txt` (numpy, regex, jinja2).
|
||||
5. From upstream main only: `bench/bench_vs_llama.py`.
|
||||
|
||||
Write new (nothing upstream to copy): `ref/qwen36.py`, `tools/qwen36_synth_gguf.py`, the oracle invariant tests, qwen35moe parity binaries (GDN at 32 v-heads with SiLU gating, the top-8 over 256 router with shared-expert gate, the gated full-attention layer), the layer composition test, and the streaming runner test.
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
@@ -1,132 +0,0 @@
|
||||
// Exercise request preparation and final tool parsing with the actual GGUF.
|
||||
// No inference engine or CUDA context is created.
|
||||
#define main unused_serving_main
|
||||
#include "main.cpp"
|
||||
#undef main
|
||||
#include <cassert>
|
||||
#include <sstream>
|
||||
|
||||
int strata_engine_main(int, char**) { return 99; }
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 2) return 2;
|
||||
llama_log_set(quiet_log, nullptr);
|
||||
llama_backend_init();
|
||||
Server server;
|
||||
server.opt.ctx = 196608;
|
||||
auto params = llama_model_default_params(); params.vocab_only = true;
|
||||
server.model = llama_model_load_from_file(argv[1], params);
|
||||
assert(server.model);
|
||||
server.vocab = llama_model_get_vocab(server.model);
|
||||
server.tmpls = common_chat_templates_init(server.model, "");
|
||||
assert(common_chat_templates_get_caps(server.tmpls.get()).at("supports_parallel_tool_calls"));
|
||||
auto request = common_json::parse_no_throw(R"({
|
||||
"messages":[{"role":"user","content":"Check the files and the date."}],
|
||||
"tools":[{"type":"function","function":{"name":"bash","parameters":{
|
||||
"type":"object","properties":{"command":{"type":"string"}},"required":["command"]
|
||||
}}}]
|
||||
})");
|
||||
const std::string output = "Reasoning.\n</think>\n\n"
|
||||
"<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n</function>\n</tool_call>\n"
|
||||
"<tool_call>\n<function=bash>\n<parameter=command>\ndate\n</parameter>\n</function>\n</tool_call>";
|
||||
Prepared default_request, explicit_request;
|
||||
std::string error;
|
||||
assert(server.prepare(request, default_request, error));
|
||||
auto message = common_chat_parse(output, false, default_request.parser);
|
||||
assert(message.tool_calls.size() == 2);
|
||||
assert(message.tool_calls[0].arguments == "{\"command\":\"ls\"}");
|
||||
assert(message.tool_calls[1].arguments == "{\"command\":\"date\"}");
|
||||
request["parallel_tool_calls"] = true;
|
||||
assert(server.prepare(request, explicit_request, error));
|
||||
assert(explicit_request.ids == default_request.ids);
|
||||
assert(common_chat_parse(output, false, explicit_request.parser).tool_calls.size() == 2);
|
||||
request["parallel_tool_calls"] = false;
|
||||
assert(server.prepare(request, explicit_request, error));
|
||||
assert(explicit_request.ids == default_request.ids);
|
||||
assert(common_chat_parse(output, false, explicit_request.parser).tool_calls.size() == 1);
|
||||
// Arguments in any order: the model writes optional parameters before required ones, and upstream's
|
||||
// required-first rule dropped such calls without an error (patches/llama.cpp-qwen3-coder-any-argument-order.patch).
|
||||
auto read_request = common_json::parse_no_throw(R"({
|
||||
"messages":[{"role":"user","content":"Read the file."}],
|
||||
"tools":[{"type":"function","function":{"name":"read","parameters":{
|
||||
"type":"object","required":["path"],"properties":{"path":{"type":"string"},
|
||||
"offset":{"type":"number"},"limit":{"type":"number"}}
|
||||
}}}]
|
||||
})");
|
||||
Prepared read_prepared;
|
||||
assert(server.prepare(read_request, read_prepared, error));
|
||||
for (const char* order : {"limit offset path", "offset path limit", "path limit offset", "path"}) {
|
||||
std::string text = "Reasoning.\n</think>\n\n<tool_call>\n<function=read>\n";
|
||||
std::istringstream names(order);
|
||||
for (std::string name; names >> name;)
|
||||
text += "<parameter=" + name + ">\n" + (name == "path" ? "/tmp/a.txt" : "40") + "\n</parameter>\n";
|
||||
text += "</function>\n</tool_call>";
|
||||
auto parsed = common_chat_parse(text, false, read_prepared.parser);
|
||||
assert(parsed.tool_calls.size() == 1);
|
||||
assert(parsed.tool_calls[0].name == "read");
|
||||
assert(parsed.tool_calls[0].arguments.find("\"path\":\"/tmp/a.txt\"") != std::string::npos);
|
||||
}
|
||||
// Streaming (REGINA-110): the response's text grows a UTF-8 character at a time, as it does token by token
|
||||
// in run(); the answer must be published as it grows, not in one piece at the end, and the pieces must add
|
||||
// up to the parse of the whole message. Tool calls are published once, complete.
|
||||
struct StreamCase { const char* name; bool thinking; bool tools; std::string output; size_t calls; };
|
||||
const std::string call_ls = "<tool_call>\n<function=bash>\n<parameter=command>\nls -l \"a b\" | head -n 3\n"
|
||||
"</parameter>\n</function>\n</tool_call>";
|
||||
const std::string answer = "A lighthouse stands on the cape: caf\xC3\xA9 lights, 2 < 3 and <b>bold</b>.\n\n"
|
||||
"```json\n{\"a\": [1, 2], \"s\": \"x\\ny\"}\n```\nIt writes <tool and <function= as text.";
|
||||
const StreamCase cases[] = {
|
||||
{"reasoning then answer", true, false, "The user asks.\nTwo steps.\n</think>\n\n" + answer, 0},
|
||||
{"answer, thinking off", false, false, answer, 0},
|
||||
{"answer, tools declared", true, true, "No tool is needed.\n</think>\n\n" + answer, 0},
|
||||
{"answer, tools declared, thinking off", false, true, answer, 0},
|
||||
{"text then a tool call", true, true, "List first.\n</think>\n\nI will list the files.\n\n" + call_ls, 1},
|
||||
{"a tool call alone", false, true, call_ls, 1},
|
||||
{"two tool calls", true, true, "Both.\n</think>\n\n" + call_ls + "\n" + call_ls, 2},
|
||||
};
|
||||
for (const StreamCase& c : cases) {
|
||||
auto body = common_json::parse_no_throw(R"({"messages":[{"role":"user","content":"Describe a lighthouse."}],
|
||||
"stream":true})");
|
||||
if (c.tools) body["tools"] = request.at("tools");
|
||||
body["chat_template_kwargs"] = common_json::object();
|
||||
body["chat_template_kwargs"]["enable_thinking"] = c.thinking;
|
||||
Prepared prepared;
|
||||
assert(server.prepare(body, prepared, error));
|
||||
const common_chat_msg whole = common_chat_parse(c.output, false, prepared.parser);
|
||||
StreamParse parse;
|
||||
std::string content, reasoning;
|
||||
size_t content_deltas = 0, reasoning_deltas = 0, call_deltas = 0, steps = 0;
|
||||
bool calls_only_at_end = true;
|
||||
auto take = [&](const std::vector<common_chat_msg_diff>& diffs, bool partial) {
|
||||
for (const auto& d : diffs) {
|
||||
if (!d.content_delta.empty()) { content += d.content_delta; ++content_deltas; }
|
||||
if (!d.reasoning_content_delta.empty()) { reasoning += d.reasoning_content_delta; ++reasoning_deltas; }
|
||||
if (d.tool_call_index != std::string::npos) { ++call_deltas; if (partial) calls_only_at_end = false; }
|
||||
}
|
||||
};
|
||||
for (size_t n = 1; n < c.output.size(); ++n) {
|
||||
if (utf8_complete_prefix(c.output.substr(0, n)) != n) continue;
|
||||
take(parse.step(c.output.substr(0, n), true, prepared.parser), true);
|
||||
++steps;
|
||||
}
|
||||
take(parse.step(c.output, false, prepared.parser), false);
|
||||
std::printf("stream case '%s': %zu steps, %zu reasoning deltas, %zu content deltas, %zu tool-call deltas\n",
|
||||
c.name, steps, reasoning_deltas, content_deltas, call_deltas);
|
||||
if (std::getenv("STREAM_TEST_VERBOSE"))
|
||||
std::printf(" whole content [%s]\n streamed [%s]\n", whole.content.c_str(), content.c_str());
|
||||
assert(reasoning == whole.reasoning_content);
|
||||
// the streamed answer is the whole one; before a tool call it may keep the white space the parser trims
|
||||
assert(content.compare(0, whole.content.size(), whole.content) == 0);
|
||||
assert(content.find_first_not_of(" \n", whole.content.size()) == std::string::npos);
|
||||
assert(whole.content.size() < 20 || content_deltas * 2 >= whole.content.size());
|
||||
assert(whole.reasoning_content.size() < 10 || reasoning_deltas * 2 >= whole.reasoning_content.size());
|
||||
assert(whole.tool_calls.size() == c.calls && parse.msg.tool_calls.size() == c.calls);
|
||||
assert(calls_only_at_end && call_deltas == c.calls);
|
||||
for (size_t i = 0; i < c.calls; ++i) {
|
||||
assert(parse.msg.tool_calls[i].arguments == "{\"command\":\"ls -l \\\"a b\\\" | head -n 3\"}");
|
||||
assert(!parse.msg.tool_calls[i].id.empty());
|
||||
}
|
||||
}
|
||||
llama_model_free(server.model);
|
||||
std::puts("PASS: omitted parallel_tool_calls uses the model capability; explicit false remains honored; "
|
||||
"tool arguments parse in any order; the answer streams as it grows and tool calls arrive whole");
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <sys/wait.h>
|
||||
|
||||
namespace strata_frontend {
|
||||
// Called only by the supervisor, which is joined before Engine::quit().
|
||||
// Reap dead children: kill(pid, 0) would report a zombie as still alive.
|
||||
inline bool child_running(pid_t& pid, std::string& why) {
|
||||
int status = 0;
|
||||
const pid_t result = ::waitpid(pid, &status, WNOHANG);
|
||||
if (result == 0 || (result < 0 && errno == EINTR)) return true;
|
||||
if (result < 0) why = std::string("waitpid: ") + std::strerror(errno);
|
||||
else if (WIFSIGNALED(status)) why = "engine killed by signal " + std::to_string(WTERMSIG(status));
|
||||
else if (WIFEXITED(status)) why = "engine exited with code " + std::to_string(WEXITSTATUS(status));
|
||||
else why = "engine exited unexpectedly";
|
||||
pid = -1;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
#include "child_watch.hpp"
|
||||
#include <cassert>
|
||||
#include <csignal>
|
||||
#include <cstdio>
|
||||
#include <sys/resource.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main() {
|
||||
for (bool crash : {false, true}) {
|
||||
pid_t pid = ::fork();
|
||||
assert(pid >= 0);
|
||||
if (pid == 0) {
|
||||
const struct rlimit no_core{0, 0};
|
||||
::setrlimit(RLIMIT_CORE, &no_core);
|
||||
::usleep(30000);
|
||||
if (crash) ::raise(SIGABRT);
|
||||
::_exit(17);
|
||||
}
|
||||
std::string why;
|
||||
assert(strata_frontend::child_running(pid, why));
|
||||
bool exited = false;
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
if (!strata_frontend::child_running(pid, why)) { exited = true; break; }
|
||||
::usleep(10000);
|
||||
}
|
||||
assert(exited && pid == -1);
|
||||
assert(why == (crash ? "engine killed by signal " + std::to_string(SIGABRT) : "engine exited with code 17"));
|
||||
std::puts(why.c_str());
|
||||
}
|
||||
std::puts("PASS: normal exit and watchdog-style abort reaped and diagnosed");
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
#pragma once
|
||||
#include "child_watch.hpp"
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <csignal>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace strata_frontend {
|
||||
struct GenResult {
|
||||
bool ok = false;
|
||||
std::string error;
|
||||
std::string finish = "length";
|
||||
long long produced = 0, prompt_n = 0, draft_accepted = 0, draft_offered = 0;
|
||||
double prompt_ms = 0, decode_ms = 0;
|
||||
};
|
||||
|
||||
class Engine {
|
||||
public:
|
||||
bool start(const std::vector<std::string>& args, std::string& err, const char* executable = "/proc/self/exe") {
|
||||
int to_child[2], from_child[2];
|
||||
if (::pipe(to_child) != 0 || ::pipe(from_child) != 0) { err = "pipe failed"; return false; }
|
||||
pid_ = ::fork();
|
||||
if (pid_ < 0) { err = "fork failed"; return false; }
|
||||
if (pid_ == 0) {
|
||||
::dup2(to_child[0], STDIN_FILENO);
|
||||
::dup2(from_child[1], STDOUT_FILENO);
|
||||
::close(to_child[0]); ::close(to_child[1]); ::close(from_child[0]); ::close(from_child[1]);
|
||||
std::vector<char*> argv;
|
||||
for (const std::string& a : args) argv.push_back(const_cast<char*>(a.c_str()));
|
||||
argv.push_back(nullptr);
|
||||
::execv(executable, argv.data());
|
||||
std::fprintf(stderr, "unbiased-strata: could not start the engine: %s\n", std::strerror(errno));
|
||||
::_exit(127);
|
||||
}
|
||||
::close(to_child[0]);
|
||||
::close(from_child[1]);
|
||||
in_fd_ = to_child[1];
|
||||
out_ = ::fdopen(from_child[0], "r");
|
||||
return out_ != nullptr;
|
||||
}
|
||||
|
||||
/// Reads the engine's start-up lines until it says READY. Loading the model takes minutes. The READY line
|
||||
/// carries the context the engine actually allocated (`READY <max_context> stop`): its VRAM plan may have
|
||||
/// lowered the request, and the front end's request limit and /v1/models follow that figure, not --ctx.
|
||||
bool wait_ready(std::string& err, long long* context = nullptr) {
|
||||
std::string line;
|
||||
while (read_line(line)) {
|
||||
if (line.rfind("READY", 0) == 0) {
|
||||
if (context != nullptr) {
|
||||
const long long n = std::atoll(line.c_str() + 5);
|
||||
if (n > 0) *context = n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (line.rfind("ERR", 0) == 0) { err = line; return false; }
|
||||
}
|
||||
err = "the engine exited before it was ready (its messages are above)";
|
||||
return false;
|
||||
}
|
||||
|
||||
/// One request. `on_token` returns false when the client has gone: the engine is told to stop and the rest of
|
||||
/// its output for this request is read and dropped, so the next request starts clean.
|
||||
GenResult generate(const std::string& header, const std::vector<int32_t>& ids,
|
||||
const std::function<bool(int32_t)>& on_token) {
|
||||
GenResult r;
|
||||
if (!alive_) { r.error = "the engine is not running"; return r; }
|
||||
std::string req = header;
|
||||
req.reserve(header.size() + ids.size() * 7 + 2);
|
||||
for (size_t i = 0; i < ids.size(); ++i) {
|
||||
if (i) req += ',';
|
||||
req += std::to_string(ids[i]);
|
||||
}
|
||||
req += '\n';
|
||||
if (!send(req)) { r.error = "the engine is not running"; return r; }
|
||||
bool stopped = false;
|
||||
std::string callback_error;
|
||||
std::string line;
|
||||
while (read_line(line)) {
|
||||
if (line.size() > 2 && line[0] == 'T' && line[1] == ' ') {
|
||||
if (!stopped) {
|
||||
bool keep_going = false;
|
||||
try {
|
||||
keep_going = on_token((int32_t) std::atoi(line.c_str() + 2));
|
||||
} catch (const std::exception& ex) {
|
||||
callback_error = ex.what();
|
||||
std::fprintf(stderr, "unbiased-strata: response formatter failed; stopping and draining request: %s\n", ex.what());
|
||||
}
|
||||
if (!keep_going) {
|
||||
stopped = true;
|
||||
send("STOP\n");
|
||||
}
|
||||
}
|
||||
} else if (line.rfind("DONE ", 0) == 0) {
|
||||
char finish[32] = {0};
|
||||
std::sscanf(line.c_str(), "DONE %lld %lld %lf %lf %31s %lld %lld", &r.produced, &r.prompt_n, &r.prompt_ms,
|
||||
&r.decode_ms, finish, &r.draft_accepted, &r.draft_offered);
|
||||
r.finish = finish;
|
||||
if (r.prompt_n != (long long) ids.size()) {
|
||||
r.error = "engine response prompt size mismatch: submitted " + std::to_string(ids.size()) +
|
||||
", returned " + std::to_string(r.prompt_n);
|
||||
std::fprintf(stderr, "unbiased-strata: %s; refusing this response\n", r.error.c_str());
|
||||
alive_ = false;
|
||||
return r;
|
||||
}
|
||||
r.ok = callback_error.empty();
|
||||
if (!r.ok) r.error = "response formatter failed: " + callback_error;
|
||||
return r;
|
||||
} else if (line.rfind("ERR", 0) == 0) {
|
||||
r.error = line.size() > 4 ? line.substr(4) : "the engine reported an error";
|
||||
return r;
|
||||
}
|
||||
// PP (prompt progress), RESUME, REUSED and INFO lines need no action here
|
||||
}
|
||||
alive_ = false;
|
||||
r.error = "the engine exited during the request";
|
||||
return r;
|
||||
}
|
||||
|
||||
/// One command line between requests (the caller holds `mu`): the engine's one-line reply whose first word is
|
||||
/// `reply_prefix` lands in `reply`; an ERR line is the error. `STATS` is the one in use (the server's /health).
|
||||
bool command(const std::string& line, const char* reply_prefix, std::string& reply, std::string& err) {
|
||||
if (!alive_) { err = "the engine is not running"; return false; }
|
||||
if (!send(line + "\n")) { err = "the engine is not running"; return false; }
|
||||
std::string got;
|
||||
while (read_line(got)) {
|
||||
if (got.rfind(reply_prefix, 0) == 0) { reply = got; return true; }
|
||||
if (got.rfind("ERR", 0) == 0) { err = got.size() > 4 ? got.substr(4) : "the engine reported an error"; return false; }
|
||||
}
|
||||
alive_ = false;
|
||||
err = "the engine exited";
|
||||
return false;
|
||||
}
|
||||
|
||||
void quit() {
|
||||
if (pid_ > 0) {
|
||||
send("QUIT\n");
|
||||
int status = 0;
|
||||
for (int i = 0; i < 100 && ::waitpid(pid_, &status, WNOHANG) == 0; ++i) ::usleep(100 * 1000);
|
||||
::kill(pid_, SIGKILL);
|
||||
::waitpid(pid_, &status, 0);
|
||||
pid_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
bool reap_exit(std::string& why) {
|
||||
if (strata_frontend::child_running(pid_, why)) return false;
|
||||
alive_ = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool alive() const { return alive_; }
|
||||
std::mutex mu; // one request at a time: the engine holds one conversation
|
||||
|
||||
private:
|
||||
bool send(const std::string& s) {
|
||||
size_t off = 0;
|
||||
while (off < s.size()) {
|
||||
const ssize_t n = ::write(in_fd_, s.data() + off, s.size() - off);
|
||||
if (n <= 0) { alive_ = false; return false; }
|
||||
off += (size_t) n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read_line(std::string& line) {
|
||||
char* buf = nullptr;
|
||||
size_t cap = 0;
|
||||
const ssize_t n = ::getline(&buf, &cap, out_);
|
||||
if (n < 0) { std::free(buf); alive_ = false; return false; }
|
||||
line.assign(buf, (size_t) n);
|
||||
std::free(buf);
|
||||
while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) line.pop_back();
|
||||
return true;
|
||||
}
|
||||
|
||||
pid_t pid_ = -1;
|
||||
int in_fd_ = -1;
|
||||
FILE* out_ = nullptr;
|
||||
std::atomic<bool> alive_{true};
|
||||
};
|
||||
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
#include "engine.hpp"
|
||||
#include <cassert>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
// Enough output to fill a Linux pipe, with the same independent stdin reader
|
||||
// and per-token STOP check as the backend. This requires no model or CUDA.
|
||||
int fake_backend() {
|
||||
std::setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
std::mutex mutex;
|
||||
std::condition_variable ready;
|
||||
std::deque<std::string> commands;
|
||||
std::atomic<bool> stop{false};
|
||||
auto reader = std::thread([&] {
|
||||
std::string input;
|
||||
char byte;
|
||||
while (::read(0, &byte, 1) == 1) {
|
||||
if (byte != '\n') { input += byte; continue; }
|
||||
if (input == "STOP") { stop.store(true); input.clear(); continue; }
|
||||
const bool quit = input == "QUIT";
|
||||
{ std::lock_guard<std::mutex> lock(mutex); commands.push_back(input); }
|
||||
input.clear(); ready.notify_one();
|
||||
if (quit) return;
|
||||
}
|
||||
});
|
||||
std::puts("READY");
|
||||
for (;;) {
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
ready.wait(lock, [&] { return !commands.empty(); });
|
||||
auto command = commands.front(); commands.pop_front(); lock.unlock();
|
||||
if (command == "QUIT") break;
|
||||
stop.store(false);
|
||||
const int token = command.find("99") != std::string::npos ? 99 : 11;
|
||||
int count = 0;
|
||||
while (count < 100000) {
|
||||
std::printf("T %d\n", token); ++count;
|
||||
if (stop.load()) break;
|
||||
}
|
||||
std::printf("DONE %d 1 1 1 stop 0 0\n", count);
|
||||
}
|
||||
reader.join();
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc > 1) return fake_backend();
|
||||
strata_frontend::Engine engine;
|
||||
std::string error;
|
||||
assert(engine.start({argv[0], "--fake-backend"}, error, argv[0]));
|
||||
assert(engine.wait_ready(error));
|
||||
auto failed = engine.generate("GEN 100000 ", {11}, [](int32_t) -> bool {
|
||||
throw std::runtime_error("partial tool JSON formatter failure");
|
||||
});
|
||||
assert(!failed.ok);
|
||||
int count = 0;
|
||||
auto next = engine.generate("GEN 100000 ", {99}, [&](int32_t token) {
|
||||
assert(token == 99); ++count; return true;
|
||||
});
|
||||
assert(next.ok && count == 100000);
|
||||
auto cancel = engine.generate("GEN 100000 ", {11}, [](int32_t) { return false; });
|
||||
assert(cancel.ok);
|
||||
count = 0;
|
||||
next = engine.generate("GEN 100000 ", {99}, [&](int32_t token) {
|
||||
assert(token == 99); ++count; return true;
|
||||
});
|
||||
assert(next.ok && count == 100000);
|
||||
engine.quit();
|
||||
std::puts("PASS: large responses cannot fill an abandoned pipe or leak into the next request");
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// frontend/engine_entry.cpp - the unmodified Strata engine program, compiled into this binary under another name.
|
||||
//
|
||||
// The engine's own source file is included as it is; only its entry point is renamed, so frontend/main.cpp can
|
||||
// decide whether this process is the HTTP front end or the engine it starts as a child (`--engine`).
|
||||
#define main strata_engine_main
|
||||
#include "../src/program/generate.cpp"
|
||||
@@ -1,62 +0,0 @@
|
||||
#include "engine.hpp"
|
||||
#include <cassert>
|
||||
#include <stdexcept>
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc > 1 && std::string(argv[1]) == "--fake-engine") {
|
||||
std::puts("READY"); std::fflush(stdout);
|
||||
char* line = nullptr; size_t capacity = 0;
|
||||
while (::getline(&line, &capacity, stdin) > 0) {
|
||||
const std::string request(line);
|
||||
if (request == "QUIT\n") break;
|
||||
if (request == "STOP\n") continue;
|
||||
if (request == "STATS\n") { // the tier census and counters, one line (the server's /health)
|
||||
std::printf("STATS {\"experts\":10240,\"vram_slots\":3555,\"ram_copies\":4954,\"mapped\":1731}\n");
|
||||
std::fflush(stdout);
|
||||
continue;
|
||||
}
|
||||
if (request == "STATS BAD\n") { std::printf("ERR STATS: no such form\n"); std::fflush(stdout); continue; }
|
||||
if (request.rfind("GEN ", 0) != 0) continue;
|
||||
if (request.find("88") != std::string::npos) {
|
||||
std::printf("T 88\nDONE 1 2 1 1 stop 0 0\n");
|
||||
std::fflush(stdout);
|
||||
continue;
|
||||
}
|
||||
const int base = request.find("99") != std::string::npos ? 99 : 11;
|
||||
std::printf("T %d\nT %d\nDONE 2 1 1 1 stop 0 0\n", base, base+1);
|
||||
std::fflush(stdout);
|
||||
}
|
||||
std::free(line);
|
||||
return 0;
|
||||
}
|
||||
strata_frontend::Engine engine;
|
||||
std::string error;
|
||||
assert(engine.start({argv[0], "--fake-engine"}, error, argv[0]));
|
||||
assert(engine.wait_ready(error));
|
||||
auto failed = engine.generate("GEN 2 ", {11}, [](int32_t) -> bool {
|
||||
throw std::runtime_error("synthetic partial tool JSON diff error");
|
||||
});
|
||||
assert(!failed.ok && failed.error.find("synthetic") != std::string::npos);
|
||||
std::vector<int32_t> tokens;
|
||||
auto next = engine.generate("GEN 2 ", {99}, [&](int32_t token) { tokens.push_back(token); return true; });
|
||||
assert(next.ok && (tokens == std::vector<int32_t>{99,100}));
|
||||
auto cancelled = engine.generate("GEN 2 ", {11}, [](int32_t) { return false; });
|
||||
assert(cancelled.ok);
|
||||
tokens.clear();
|
||||
next = engine.generate("GEN 2 ", {99}, [&](int32_t token) { tokens.push_back(token); return true; });
|
||||
assert(next.ok && (tokens == std::vector<int32_t>{99,100}));
|
||||
// STATS between requests: the one-line reply by its prefix, an ERR as the error, and the next request unharmed
|
||||
std::string reply;
|
||||
assert(engine.command("STATS", "STATS ", reply, error) && reply.find("\"vram_slots\":3555") != std::string::npos);
|
||||
assert(!engine.command("STATS BAD", "STATS ", reply, error) && error.find("no such form") != std::string::npos && engine.alive());
|
||||
tokens.clear();
|
||||
next = engine.generate("GEN 2 ", {99}, [&](int32_t token) { tokens.push_back(token); return true; });
|
||||
assert(next.ok && (tokens == std::vector<int32_t>{99,100}));
|
||||
auto mismatched = engine.generate("GEN 2 ", {88}, [](int32_t) { return true; });
|
||||
assert(!mismatched.ok && !engine.alive());
|
||||
assert(mismatched.error.find("prompt size mismatch") != std::string::npos);
|
||||
auto rejected = engine.generate("GEN 2 ", {99}, [](int32_t) { return true; });
|
||||
assert(!rejected.ok && rejected.produced == 0);
|
||||
engine.quit();
|
||||
std::puts("PASS: formatter exceptions and client cancellation drain the old request before the next request");
|
||||
}
|
||||
@@ -1,829 +0,0 @@
|
||||
// frontend/main.cpp - UnbiasedStrata's front end: tokenizer, chat template and an OpenAI-style HTTP endpoint in
|
||||
// front of the unmodified Strata engine.
|
||||
//
|
||||
// One binary, two roles. Started normally it is the front end: it starts a copy of itself with `--engine`, which
|
||||
// runs the engine's own program (frontend/engine_entry.cpp) in serve mode, and talks to it over a pipe in the
|
||||
// engine's line protocol (token ids in, token ids out). That is the process model upstream's Python server uses,
|
||||
// so the engine runs exactly as upstream tested it.
|
||||
//
|
||||
// The tokenizer and the chat template come from llama.cpp (the pinned submodule): the GGUF's own vocabulary and
|
||||
// its own Jinja template. Nothing here opens an outgoing connection.
|
||||
#include "engine.hpp"
|
||||
#include "vision.hpp"
|
||||
#include "chat.h"
|
||||
#include "common.h"
|
||||
#include "llama.h"
|
||||
|
||||
#include <cpp-httplib/httplib.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int strata_engine_main(int argc, char** argv);
|
||||
|
||||
namespace {
|
||||
|
||||
// the model id reported on /v1/models and in every completion: the GGUF's base name (`Qwen3.6-35B-A3B-UD-IQ3_XXS`,
|
||||
// `Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS` for shard 1 without its `-00001-of-00002`), set once the options are parsed
|
||||
std::string g_model_name = "unbiased-strata";
|
||||
std::string model_name_of(const std::string& path) {
|
||||
std::string b = path.substr(path.find_last_of('/') == std::string::npos ? 0 : path.find_last_of('/') + 1);
|
||||
if (b.size() > 5 && b.compare(b.size() - 5, 5, ".gguf") == 0) b.resize(b.size() - 5);
|
||||
const size_t at = b.rfind("-00001-of-");
|
||||
if (at != std::string::npos) b.resize(at);
|
||||
return b.empty() ? std::string("unbiased-strata") : b;
|
||||
}
|
||||
|
||||
struct Options {
|
||||
std::string model; // shard 1 of the GGUF
|
||||
std::string pack; // the prepared pack directory
|
||||
std::string mtp; // the prepared draft-head directory
|
||||
std::string mmproj;
|
||||
int vision_tokens = 1024;
|
||||
std::string host = "127.0.0.1";
|
||||
int port = 8080;
|
||||
long long ctx = 32768;
|
||||
int threads = 0; // CPU expert workers; 0 = the engine's default (every physical core)
|
||||
long long vram_cap_mib = 0; // --vram-cap: the engine limits itself to a smaller card's VRAM
|
||||
double ram_cap_gib = 0.0; // --ram-cap: bounds the engine's RAM expert tier and pinned arena
|
||||
std::vector<std::string> extra; // after `--`: passed to the engine as they are
|
||||
};
|
||||
|
||||
void usage() {
|
||||
std::fprintf(stderr,
|
||||
"usage: unbiased-strata --model SHARD1.gguf --pack DIR --mtp DIR [options] [-- engine options]\n\n"
|
||||
" --model PATH the model's first GGUF shard (...-00001-of-00002.gguf); the second must be beside it\n"
|
||||
" --pack DIR the prepared pack for that model\n"
|
||||
" --mtp DIR the prepared draft head\n"
|
||||
" --mmproj PATH enable image input using this vision encoder (CPU)\n"
|
||||
" --vision-tokens N maximum tokens per image (default 1024)\n"
|
||||
" --ctx N context length in tokens (default 32768)\n"
|
||||
" --threads N CPU threads for the experts the GPU does not hold (default: every physical core,\n"
|
||||
" or half the CPU quota inside a container that has one)\n"
|
||||
" --host ADDR address to listen on (default 127.0.0.1)\n"
|
||||
" --port N port to listen on (default 8080)\n"
|
||||
" --vram-cap MIB emulate a smaller card: the engine uses at most MIB of VRAM (a 1080 Ti as 6 GB: 5722)\n"
|
||||
" --ram-cap GIB bound the engine's RAM expert tier and pinned arena to GIB\n\n"
|
||||
"Serves POST /v1/chat/completions (OpenAI style, with streaming), GET /v1/models and GET /health (with the\n"
|
||||
"engine's expert tiers and per-token counters: VRAM slots, RAM copies, mapped experts, hits, warm hints,\n"
|
||||
"major page faults).\n");
|
||||
}
|
||||
|
||||
bool file_exists(const std::string& p) {
|
||||
struct stat st;
|
||||
return ::stat(p.c_str(), &st) == 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------- the engine
|
||||
|
||||
using strata_frontend::Engine;
|
||||
using strata_frontend::GenResult;
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ text handling
|
||||
|
||||
/// The length of the longest prefix of `s` that does not end inside a UTF-8 character.
|
||||
size_t utf8_complete_prefix(const std::string& s) {
|
||||
size_t i = s.size();
|
||||
int back = 0;
|
||||
while (i > 0 && back < 4) {
|
||||
const unsigned char c = (unsigned char) s[i - 1];
|
||||
++back;
|
||||
if ((c & 0xC0) == 0x80) { --i; continue; } // a continuation byte: keep looking for its lead
|
||||
const int need = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : c >= 0xC0 ? 2 : 1;
|
||||
return need > back ? i - 1 : s.size();
|
||||
}
|
||||
return s.size();
|
||||
}
|
||||
|
||||
std::string make_id() {
|
||||
static std::mt19937_64 rng{std::random_device{}()};
|
||||
static std::mutex mu;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
char b[40];
|
||||
std::snprintf(b, sizeof b, "chatcmpl-%016llx", (unsigned long long) rng());
|
||||
return b;
|
||||
}
|
||||
|
||||
long long now_s() {
|
||||
return (long long) std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
void json_error(httplib::Response& res, int status, const std::string& message, const char* type) {
|
||||
common_json e = common_json::object();
|
||||
e["error"] = common_json::object();
|
||||
e["error"]["message"] = message;
|
||||
e["error"]["type"] = type;
|
||||
res.status = status;
|
||||
res.set_content(e.dump_safe(), "application/json");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- the request
|
||||
|
||||
struct Prepared {
|
||||
std::shared_ptr<strata_frontend::ImageFile> images;
|
||||
std::vector<llama_token> ids;
|
||||
std::string header; // "GEN <max_new> key=value ... " - the ids follow
|
||||
std::string request_id;
|
||||
common_chat_parser_params parser; // how to split the output into reasoning, answer and tool calls
|
||||
bool stream = false;
|
||||
long long max_new = 0;
|
||||
};
|
||||
|
||||
/// The parse of one response as its text grows: what has been published, and what to publish next.
|
||||
///
|
||||
/// Reasoning and answer text are published as they arrive. Tool calls are published once, from the parse of the
|
||||
/// complete message: while a call is being written its arguments are partial JSON that the parser closes and
|
||||
/// normalizes on every token, so text already parsed can change (an escape, a number still being written), and
|
||||
/// an OpenAI stream cannot take back what it sent. The same rule keeps the answer text sound: a partial parse
|
||||
/// whose content does not extend what was published (the parser reread the tail as the start of a tool call)
|
||||
/// publishes nothing for the content until it does. This changes delivery, never generated tokens.
|
||||
struct StreamParse {
|
||||
common_chat_msg msg; // what has been published
|
||||
std::vector<std::string> call_ids;
|
||||
|
||||
std::vector<common_chat_msg_diff> step(const std::string& text, bool partial, const common_chat_parser_params& parser) {
|
||||
common_chat_msg now;
|
||||
try {
|
||||
now = common_chat_parse(text, partial, parser);
|
||||
} catch (const std::exception&) {
|
||||
if (partial) return {}; // not parseable yet: wait for more text
|
||||
now = common_chat_msg();
|
||||
now.role = "assistant";
|
||||
now.content = text;
|
||||
}
|
||||
now.content_parts.clear();
|
||||
if (partial) {
|
||||
now.tool_calls.clear();
|
||||
if (now.content.compare(0, msg.content.size(), msg.content) != 0) now.content = msg.content;
|
||||
if (now.reasoning_content.compare(0, msg.reasoning_content.size(), msg.reasoning_content) != 0)
|
||||
now.reasoning_content = msg.reasoning_content;
|
||||
} else {
|
||||
// the complete parse decides; text it no longer holds was already sent and stays sent (the parser
|
||||
// trims the white space before a tool call, which the partial parses still carried)
|
||||
for (auto field : {&common_chat_msg::content, &common_chat_msg::reasoning_content}) {
|
||||
const std::string& sent = msg.*field;
|
||||
std::string& whole = now.*field;
|
||||
if (whole.compare(0, sent.size(), sent) == 0) continue;
|
||||
if (sent.compare(0, whole.size(), whole) != 0)
|
||||
std::fprintf(stderr, "unbiased-strata: the complete message's %s differs from the %zu bytes "
|
||||
"already streamed; the stream keeps what it sent\n",
|
||||
field == &common_chat_msg::content ? "content" : "reasoning", sent.size());
|
||||
whole = sent;
|
||||
}
|
||||
}
|
||||
if (now.empty()) return {};
|
||||
now.set_tool_call_ids(call_ids, [] { return "call_" + make_id().substr(9); });
|
||||
std::vector<common_chat_msg_diff> diffs = common_chat_msg_diff::compute_diffs(msg, now);
|
||||
msg = now;
|
||||
return diffs;
|
||||
}
|
||||
};
|
||||
|
||||
struct Server {
|
||||
Options opt;
|
||||
Engine engine;
|
||||
strata_frontend::Vision vision;
|
||||
llama_model* model = nullptr;
|
||||
const llama_vocab* vocab = nullptr;
|
||||
common_chat_templates_ptr tmpls;
|
||||
|
||||
/// Parses an OpenAI chat request, renders the model's chat template and tokenizes the result.
|
||||
bool prepare(const common_json& body, Prepared& p, std::string& err) {
|
||||
if (!body.is_object() || !body.contains("messages")) { err = "the request needs a \"messages\" array"; return false; }
|
||||
common_chat_templates_inputs in;
|
||||
common_json messages = body.at("messages");
|
||||
std::vector<std::string> markers;
|
||||
std::vector<std::shared_ptr<strata_frontend::EncodedImage>> images;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(engine.mu);
|
||||
for (auto& message : messages) {
|
||||
if (!message.contains("content") || !message.at("content").is_array()) continue;
|
||||
for (auto& part : message["content"]) {
|
||||
if (part.value("type", "") != "image_url") continue;
|
||||
if (images.size() >= 32) throw std::invalid_argument("at most 32 images per request");
|
||||
const std::string url = part.at("image_url").at("url").get<std::string>();
|
||||
images.push_back(vision.encode(url));
|
||||
markers.push_back("UNBIASED_IMAGE_" + make_id() + "_" + std::to_string(markers.size()));
|
||||
part = common_json::object();
|
||||
part["type"] = "media_marker"; part["text"] = markers.back();
|
||||
}
|
||||
}
|
||||
}
|
||||
in.messages = common_chat_msgs_parse_oaicompat(messages);
|
||||
if (body.contains("tools") && body.at("tools").is_array() && body.at("tools").size() > 0) {
|
||||
in.tools = common_chat_tools_parse_oaicompat(body.at("tools"));
|
||||
if (body.contains("tool_choice") && body.at("tool_choice").is_string())
|
||||
in.tool_choice = common_chat_tool_choice_parse_oaicompat(body.at("tool_choice").get<std::string>());
|
||||
const auto caps = common_chat_templates_get_caps(tmpls.get());
|
||||
in.parallel_tool_calls = body.value("parallel_tool_calls", caps.at("supports_parallel_tool_calls"));
|
||||
}
|
||||
in.add_generation_prompt = true;
|
||||
in.use_jinja = true;
|
||||
in.reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK; // reasoning goes to "reasoning_content"
|
||||
in.enable_thinking = true;
|
||||
// thinking: OpenAI's reasoning_effort, or the llama.cpp / vLLM convention chat_template_kwargs.enable_thinking
|
||||
if (body.contains("reasoning_effort") && body.at("reasoning_effort").is_string()) {
|
||||
const std::string effort = body.at("reasoning_effort").get<std::string>();
|
||||
if (effort == "none") in.enable_thinking = false;
|
||||
else in.chat_template_kwargs["reasoning_effort"] = common_json(effort).dump();
|
||||
}
|
||||
if (body.contains("chat_template_kwargs") && body.at("chat_template_kwargs").is_object()) {
|
||||
const common_json& kw = body.at("chat_template_kwargs");
|
||||
if (kw.contains("enable_thinking") && kw.at("enable_thinking").is_boolean())
|
||||
in.enable_thinking = kw.at("enable_thinking").get<bool>();
|
||||
if (kw.contains("reasoning_effort") && kw.at("reasoning_effort").is_string())
|
||||
in.chat_template_kwargs["reasoning_effort"] = kw.at("reasoning_effort").dump();
|
||||
// Qwen3.6's template drops the reasoning of every reply before the last user message unless this is
|
||||
// set; with it (and the client sending reasoning_content back) the history renders as it was
|
||||
// generated, so the next turn reuses the checkpoint at the end of the reply, not only the one at
|
||||
// its header
|
||||
if (kw.contains("preserve_thinking") && kw.at("preserve_thinking").is_boolean())
|
||||
in.chat_template_kwargs["preserve_thinking"] = kw.at("preserve_thinking").dump();
|
||||
}
|
||||
const common_chat_params cp = common_chat_templates_apply(tmpls.get(), in);
|
||||
std::string rendered = cp.prompt;
|
||||
if (images.empty()) {
|
||||
p.ids = common_tokenize(vocab, rendered, false, true);
|
||||
} else {
|
||||
const auto pad = common_tokenize(vocab, "<|image_pad|>", false, true);
|
||||
const auto literal_pad = common_tokenize(vocab, "<|image_pad|>", false, false);
|
||||
const auto start = common_tokenize(vocab, "<|vision_start|>", false, true);
|
||||
const auto end = common_tokenize(vocab, "<|vision_end|>", false, true);
|
||||
if (pad.size() != 1 || start.size() != 1 || end.size() != 1)
|
||||
throw std::runtime_error("model does not have the expected image special tokens");
|
||||
auto text_ids = [&](const std::string& text) {
|
||||
for (auto id : common_tokenize(vocab, text, false, true)) {
|
||||
if (id == pad[0]) p.ids.insert(p.ids.end(), literal_pad.begin(), literal_pad.end());
|
||||
else p.ids.push_back(id);
|
||||
}
|
||||
};
|
||||
size_t offset = 0; rendered.clear();
|
||||
for (size_t i = 0; i < images.size(); ++i) {
|
||||
auto at = cp.prompt.find(markers[i], offset);
|
||||
if (at == std::string::npos || cp.prompt.find(markers[i], at+markers[i].size()) != std::string::npos)
|
||||
throw std::invalid_argument("chat template did not preserve each image exactly once");
|
||||
auto text = cp.prompt.substr(offset, at-offset);
|
||||
text_ids(text); rendered += text + "<|vision_start|>";
|
||||
p.ids.push_back(start[0]);
|
||||
p.ids.insert(p.ids.end(), images[i]->tokens, pad[0]);
|
||||
for (int j = 0; j < images[i]->tokens; ++j) rendered += "<|image_pad|>";
|
||||
p.ids.push_back(end[0]); rendered += "<|vision_end|>";
|
||||
offset = at + markers[i].size();
|
||||
}
|
||||
auto tail = cp.prompt.substr(offset); text_ids(tail); rendered += tail;
|
||||
p.images = std::make_shared<strata_frontend::ImageFile>();
|
||||
strata_frontend::write_images(*p.images, images);
|
||||
}
|
||||
if (p.ids.empty()) { err = "the prompt is empty"; return false; }
|
||||
|
||||
p.parser = common_chat_parser_params(cp);
|
||||
p.parser.reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK;
|
||||
p.parser.parse_tool_calls = true;
|
||||
if (!cp.parser.empty()) p.parser.parser.load(cp.parser);
|
||||
|
||||
// The engine refuses a request unless prompt + max_new + 8 <= context (generate.cpp, the GEN handler), so
|
||||
// the slots it keeps back are not ours to promise. Without this a client that asks for "as much as fits"
|
||||
// (pi sends max_tokens 32768 on a 64K card) was refused on every prompt longer than ctx - max_tokens.
|
||||
constexpr long long kEngineReserve = 8;
|
||||
const long long n = (long long) p.ids.size();
|
||||
if (n + 1 + kEngineReserve > opt.ctx) {
|
||||
err = "the prompt is " + std::to_string(n) + " tokens, which does not fit the context of " +
|
||||
std::to_string(opt.ctx);
|
||||
return false;
|
||||
}
|
||||
long long max_new = opt.ctx - n - kEngineReserve;
|
||||
for (const char* key : {"max_completion_tokens", "max_tokens"})
|
||||
if (body.contains(key) && body.at(key).is_number()) {
|
||||
const long long want = body.at(key).get<long long>();
|
||||
if (want >= 1) max_new = std::min(max_new, want);
|
||||
break;
|
||||
}
|
||||
p.max_new = max_new;
|
||||
p.stream = body.value("stream", false);
|
||||
|
||||
// sampling: greedy unless the request sets a temperature above zero
|
||||
std::string keys;
|
||||
const double temperature = body.contains("temperature") && body.at("temperature").is_number()
|
||||
? body.at("temperature").get<double>() : 0.0;
|
||||
if (temperature > 0.0) {
|
||||
const double top_p = body.contains("top_p") && body.at("top_p").is_number() ? body.at("top_p").get<double>() : 0.95;
|
||||
long long top_k = body.contains("top_k") && body.at("top_k").is_number() ? body.at("top_k").get<long long>() : 20;
|
||||
top_k = std::max(1LL, std::min(64LL, top_k)); // the engine's sampler takes 1..64
|
||||
unsigned long long seed;
|
||||
if (body.contains("seed") && body.at("seed").is_number()) seed = (unsigned long long) body.at("seed").get<long long>();
|
||||
else seed = std::random_device{}();
|
||||
char b[160];
|
||||
std::snprintf(b, sizeof b, " temperature=%g top_p=%g top_k=%lld seed=%llu", temperature, top_p, top_k, seed);
|
||||
keys += b;
|
||||
if (body.contains("min_p") && body.at("min_p").is_number()) {
|
||||
std::snprintf(b, sizeof b, " min_p=%g", body.at("min_p").get<double>());
|
||||
keys += b;
|
||||
}
|
||||
}
|
||||
for (const auto& kv : {std::pair<const char*, const char*>{"presence_penalty", "penalty_present"},
|
||||
std::pair<const char*, const char*>{"frequency_penalty", "penalty_freq"},
|
||||
std::pair<const char*, const char*>{"repeat_penalty", "penalty_repeat"}})
|
||||
if (body.contains(kv.first) && body.at(kv.first).is_number()) {
|
||||
char b[64];
|
||||
std::snprintf(b, sizeof b, " %s=%g", kv.second, body.at(kv.first).get<double>());
|
||||
keys += b;
|
||||
if (keys.find("penalty_last_n") == std::string::npos) keys += " penalty_last_n=64";
|
||||
}
|
||||
p.header = (p.images ? "GENI " : "GEN ") + std::to_string(max_new) + keys + " " +
|
||||
(p.images ? p.images->path + " " : "");
|
||||
// Opt-in provenance capture: the exact first rendered request this
|
||||
// process serves, including token IDs and the engine sampling header.
|
||||
if (const char* path = std::getenv("SUGMEOFF_CAPTURE_FIRST_PROMPT")) {
|
||||
if (FILE* f = std::fopen(path, "wx")) {
|
||||
common_json capture = common_json::object();
|
||||
capture["request"] = body;
|
||||
capture["rendered_prompt"] = rendered;
|
||||
capture["token_ids"] = p.ids;
|
||||
capture["engine_header"] = p.header;
|
||||
const std::string text = capture.dump_safe();
|
||||
if (std::fwrite(text.data(), 1, text.size(), f) != text.size())
|
||||
std::fprintf(stderr, "unbiased-strata: prompt capture write failed: %s\n", path);
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
common_json usage_json(const GenResult& r) const {
|
||||
common_json u = common_json::object();
|
||||
u["prompt_tokens"] = r.prompt_n;
|
||||
u["completion_tokens"] = r.produced;
|
||||
u["total_tokens"] = r.prompt_n + r.produced;
|
||||
return u;
|
||||
}
|
||||
|
||||
common_json timings_json(const GenResult& r) const {
|
||||
common_json t = common_json::object();
|
||||
t["prompt_n"] = r.prompt_n;
|
||||
t["prompt_ms"] = r.prompt_ms;
|
||||
t["prompt_per_second"] = r.prompt_ms > 0 ? 1000.0 * (double) r.prompt_n / r.prompt_ms : 0.0;
|
||||
t["predicted_n"] = r.produced;
|
||||
t["predicted_ms"] = r.decode_ms;
|
||||
t["predicted_per_second"] = r.decode_ms > 0 ? 1000.0 * (double) r.produced / r.decode_ms : 0.0;
|
||||
t["draft_n"] = r.draft_offered;
|
||||
t["draft_n_accepted"] = r.draft_accepted;
|
||||
return t;
|
||||
}
|
||||
|
||||
/// Runs one request. The text produced so far is parsed by llama.cpp's chat parser after every token, and
|
||||
/// `emit` gets what changed (reasoning and answer text as they grow, tool calls once the message is complete:
|
||||
/// see StreamParse); it returns false when the client has gone. `final_msg` is the whole parsed message.
|
||||
/// `keepalive`, when given, is called whenever 15 s pass without an emit (a long tool call is silent while
|
||||
/// its arguments are written): the stream writes an SSE comment, which keeps clients with an idle timeout
|
||||
/// (pi: 5 minutes) attached and notices a client that has gone, so the generation is cancelled instead of
|
||||
/// running to the end for nobody.
|
||||
GenResult run(const Prepared& p, common_chat_msg& final_msg,
|
||||
const std::function<bool(const std::vector<common_chat_msg_diff>&)>& emit,
|
||||
const std::function<bool()>& keepalive = {}) {
|
||||
std::lock_guard<std::mutex> lk(engine.mu);
|
||||
std::fprintf(stderr, "unbiased-strata: request %s start: prompt=%zu header=%s\n",
|
||||
p.request_id.c_str(), p.ids.size(), p.header.c_str());
|
||||
std::string text, pending;
|
||||
StreamParse parse;
|
||||
common_chat_msg& msg = parse.msg;
|
||||
bool client_ok = true;
|
||||
auto last_write = std::chrono::steady_clock::now();
|
||||
auto update = [&](bool partial) {
|
||||
const std::vector<common_chat_msg_diff> diffs = parse.step(text, partial, p.parser);
|
||||
if (client_ok && !diffs.empty()) {
|
||||
client_ok = emit(diffs);
|
||||
last_write = std::chrono::steady_clock::now();
|
||||
}
|
||||
};
|
||||
GenResult r = engine.generate(p.header, p.ids, [&](llama_token id) {
|
||||
if (llama_vocab_is_eog(vocab, id)) return client_ok;
|
||||
pending += common_token_to_piece(vocab, id, /*special=*/true);
|
||||
const size_t n = utf8_complete_prefix(pending);
|
||||
if (n > 0) {
|
||||
text.append(pending, 0, n);
|
||||
pending.erase(0, n);
|
||||
if (p.stream) update(true); // a whole response is parsed once, at the end
|
||||
}
|
||||
if (client_ok && keepalive) {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now - last_write >= std::chrono::seconds(15)) {
|
||||
client_ok = keepalive();
|
||||
last_write = now;
|
||||
}
|
||||
}
|
||||
return client_ok;
|
||||
});
|
||||
text += pending;
|
||||
try {
|
||||
update(false);
|
||||
} catch (const std::exception& ex) {
|
||||
r.ok = false;
|
||||
r.error = std::string("response formatter failed: ") + ex.what();
|
||||
std::fprintf(stderr, "unbiased-strata: final response formatter failed: %s\n", ex.what());
|
||||
}
|
||||
final_msg = msg;
|
||||
if (final_msg.role.empty()) final_msg.role = "assistant";
|
||||
if (final_msg.tool_calls.empty() && text.find("<tool_call>") != std::string::npos) {
|
||||
// The parser accepts a message with no tool call even when the text holds one it could not
|
||||
// match (see third_party/llama.cpp/common/parsers/qwen3-coder.cpp); say so, with the text.
|
||||
std::fprintf(stderr, "unbiased-strata: request %s: the output contains <tool_call> but no tool call was "
|
||||
"parsed; the client sees finish=stop. raw-output-begin\n%s\n"
|
||||
"unbiased-strata: request %s raw-output-end\n",
|
||||
p.request_id.c_str(), text.c_str(), p.request_id.c_str());
|
||||
}
|
||||
if (r.error.find("response formatter failed") == 0) {
|
||||
std::fprintf(stderr, "unbiased-strata: request %s formatter-input-begin\n%s\n"
|
||||
"unbiased-strata: request %s formatter-input-end\n",
|
||||
p.request_id.c_str(), text.c_str(), p.request_id.c_str());
|
||||
}
|
||||
std::fprintf(stderr, "unbiased-strata: request %s end: ok=%d prompt=%lld generated=%lld finish=%s error=%s\n",
|
||||
p.request_id.c_str(), r.ok ? 1 : 0, r.prompt_n, r.produced, r.finish.c_str(), r.error.c_str());
|
||||
return r;
|
||||
}
|
||||
|
||||
static const char* finish_reason(const GenResult& r, const common_chat_msg& msg) {
|
||||
if (!msg.tool_calls.empty()) return "tool_calls";
|
||||
return r.finish == "stop" ? "stop" : "length";
|
||||
}
|
||||
|
||||
void handle_chat(const httplib::Request& req, httplib::Response& res) {
|
||||
if (!engine.alive()) return json_error(res, 503, "the engine is not running", "server_error");
|
||||
const common_json body = common_json::parse_no_throw(req.body);
|
||||
if (body.is_discarded()) return json_error(res, 400, "the request body is not valid JSON", "invalid_request_error");
|
||||
auto prep = std::make_shared<Prepared>();
|
||||
std::string err;
|
||||
try {
|
||||
if (!prepare(body, *prep, err)) return json_error(res, 400, err, "invalid_request_error");
|
||||
} catch (const std::exception& ex) {
|
||||
return json_error(res, 400, ex.what(), "invalid_request_error");
|
||||
}
|
||||
const std::string id = make_id();
|
||||
prep->request_id = id;
|
||||
const long long created = now_s();
|
||||
|
||||
if (!prep->stream) {
|
||||
common_chat_msg msg;
|
||||
const GenResult r = run(*prep, msg, [](const std::vector<common_chat_msg_diff>&) { return true; });
|
||||
if (!r.ok) return json_error(res, 500, r.error, "server_error");
|
||||
common_json choice = common_json::object();
|
||||
choice["index"] = 0;
|
||||
choice["message"] = msg.to_json_oaicompat();
|
||||
choice["finish_reason"] = finish_reason(r, msg);
|
||||
common_json out = common_json::object();
|
||||
out["id"] = id;
|
||||
out["object"] = "chat.completion";
|
||||
out["created"] = created;
|
||||
out["model"] = g_model_name;
|
||||
out["choices"] = common_json::array();
|
||||
out["choices"].push_back(choice);
|
||||
out["usage"] = usage_json(r);
|
||||
out["timings"] = timings_json(r);
|
||||
res.set_content(out.dump_safe(), "application/json");
|
||||
return;
|
||||
}
|
||||
|
||||
res.set_header("Cache-Control", "no-cache");
|
||||
res.set_header("X-Accel-Buffering", "no");
|
||||
res.set_chunked_content_provider("text/event-stream", [this, prep, id, created](size_t, httplib::DataSink& sink) {
|
||||
auto chunk = [&](const common_json& delta, const char* finish, const GenResult* done) {
|
||||
common_json choice = common_json::object();
|
||||
choice["index"] = 0;
|
||||
choice["delta"] = delta;
|
||||
if (finish) choice["finish_reason"] = finish; else choice["finish_reason"] = nullptr;
|
||||
common_json out = common_json::object();
|
||||
out["id"] = id;
|
||||
out["object"] = "chat.completion.chunk";
|
||||
out["created"] = created;
|
||||
out["model"] = g_model_name;
|
||||
out["choices"] = common_json::array();
|
||||
out["choices"].push_back(choice);
|
||||
if (done) { out["usage"] = usage_json(*done); out["timings"] = timings_json(*done); }
|
||||
const std::string s = "data: " + out.dump_safe() + "\n\n";
|
||||
return sink.write(s.data(), s.size());
|
||||
};
|
||||
common_json first = common_json::object();
|
||||
first["role"] = "assistant";
|
||||
first["content"] = "";
|
||||
bool ok = chunk(first, nullptr, nullptr);
|
||||
common_chat_msg msg;
|
||||
const GenResult r = run(*prep, msg, [&](const std::vector<common_chat_msg_diff>& diffs) {
|
||||
for (const common_chat_msg_diff& df : diffs) {
|
||||
common_json d = common_json::object();
|
||||
if (!df.reasoning_content_delta.empty()) d["reasoning_content"] = df.reasoning_content_delta;
|
||||
if (!df.content_delta.empty()) d["content"] = df.content_delta;
|
||||
if (df.tool_call_index != std::string::npos) {
|
||||
common_json fn = common_json::object();
|
||||
if (!df.tool_call_delta.name.empty()) fn["name"] = df.tool_call_delta.name;
|
||||
fn["arguments"] = df.tool_call_delta.arguments;
|
||||
common_json tc = common_json::object();
|
||||
tc["index"] = (long long) df.tool_call_index;
|
||||
if (!df.tool_call_delta.id.empty()) { tc["id"] = df.tool_call_delta.id; tc["type"] = "function"; }
|
||||
tc["function"] = fn;
|
||||
d["tool_calls"] = common_json::array();
|
||||
d["tool_calls"].push_back(tc);
|
||||
}
|
||||
if (d.size() == 0) continue;
|
||||
ok = ok && chunk(d, nullptr, nullptr);
|
||||
}
|
||||
return ok;
|
||||
}, [&]() {
|
||||
static const std::string ka = ": keepalive\n\n"; // an SSE comment: every client ignores it
|
||||
ok = ok && sink.write(ka.data(), ka.size());
|
||||
return ok;
|
||||
});
|
||||
if (ok) {
|
||||
if (r.ok) {
|
||||
chunk(common_json::object(), finish_reason(r, msg), &r);
|
||||
} else {
|
||||
common_json e = common_json::object();
|
||||
e["error"] = common_json::object();
|
||||
e["error"]["message"] = r.error;
|
||||
e["error"]["type"] = "server_error";
|
||||
const std::string s = "data: " + e.dump_safe() + "\n\n";
|
||||
sink.write(s.data(), s.size());
|
||||
}
|
||||
static const std::string end = "data: [DONE]\n\n";
|
||||
sink.write(end.data(), end.size());
|
||||
}
|
||||
sink.done();
|
||||
return true;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Server* g_server = nullptr;
|
||||
httplib::Server* g_http = nullptr;
|
||||
|
||||
void on_signal(int) {
|
||||
if (g_http) g_http->stop();
|
||||
}
|
||||
|
||||
void quiet_log(ggml_log_level level, const char* text, void*) {
|
||||
if (level == GGML_LOG_LEVEL_ERROR || level == GGML_LOG_LEVEL_WARN) std::fputs(text, stderr);
|
||||
}
|
||||
|
||||
// The CPU expert workers to ask the engine for when --threads is not given: 0 lets the engine use every physical
|
||||
// core it sees. Inside a container it sees the host's cores, not its own share, and that many workers on a small
|
||||
// quota throttle one another; so with a cgroup CPU quota below the visible CPUs the quota decides. The quota
|
||||
// counts hardware threads and the engine wants cores, hence the halving when SMT is on.
|
||||
int default_threads() {
|
||||
long long quota = 0, period = 0;
|
||||
char q[32] = "";
|
||||
if (FILE* f = std::fopen("/sys/fs/cgroup/cpu.max", "r")) { // cgroup v2
|
||||
if (std::fscanf(f, "%31s %lld", q, &period) == 2 && std::strcmp(q, "max") != 0) quota = std::atoll(q);
|
||||
std::fclose(f);
|
||||
} else if (FILE* f1 = std::fopen("/sys/fs/cgroup/cpu/cpu.cfs_quota_us", "r")) { // cgroup v1
|
||||
if (std::fscanf(f1, "%lld", "a) != 1) quota = 0;
|
||||
std::fclose(f1);
|
||||
if (FILE* f2 = std::fopen("/sys/fs/cgroup/cpu/cpu.cfs_period_us", "r")) {
|
||||
if (std::fscanf(f2, "%lld", &period) != 1) period = 0;
|
||||
std::fclose(f2);
|
||||
}
|
||||
}
|
||||
if (quota <= 0 || period <= 0) return 0;
|
||||
const long long cpus = (quota + period / 2) / period;
|
||||
if (cpus < 1 || cpus >= sysconf(_SC_NPROCESSORS_ONLN)) return 0;
|
||||
int smt = 0;
|
||||
if (FILE* f = std::fopen("/sys/devices/system/cpu/smt/active", "r")) {
|
||||
if (std::fscanf(f, "%d", &smt) != 1) smt = 0;
|
||||
std::fclose(f);
|
||||
}
|
||||
return (int) std::max<long long>(smt ? cpus / 2 : cpus, 1);
|
||||
}
|
||||
|
||||
bool parse_args(int argc, char** argv, Options& o) {
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string a = argv[i];
|
||||
auto next = [&](const char* name) -> std::string {
|
||||
if (i + 1 >= argc) { std::fprintf(stderr, "unbiased-strata: %s needs a value\n", name); std::exit(2); }
|
||||
return argv[++i];
|
||||
};
|
||||
if (a == "--model") o.model = next("--model");
|
||||
else if (a == "--mmproj") o.mmproj = next("--mmproj");
|
||||
else if (a == "--vision-tokens") o.vision_tokens = std::atoi(next("--vision-tokens").c_str());
|
||||
else if (a == "--pack") o.pack = next("--pack");
|
||||
else if (a == "--mtp") o.mtp = next("--mtp");
|
||||
else if (a == "--host") o.host = next("--host");
|
||||
else if (a == "--port") o.port = std::atoi(next("--port").c_str());
|
||||
else if (a == "--ctx") o.ctx = std::atoll(next("--ctx").c_str());
|
||||
else if (a == "--threads") o.threads = std::atoi(next("--threads").c_str());
|
||||
else if (a == "--vram-cap") o.vram_cap_mib = std::atoll(next("--vram-cap").c_str());
|
||||
else if (a == "--ram-cap") o.ram_cap_gib = std::atof(next("--ram-cap").c_str());
|
||||
else if (a == "--") {
|
||||
for (++i; i < argc; ++i) {
|
||||
const std::string e = argv[i];
|
||||
// one GPU only: the engine's multi-GPU and remote-expert modes are not part of this fork
|
||||
for (const char* no : {"--gpus", "--layer-split", "--split-device", "--peer-device", "--peer-slots",
|
||||
"--remote-expert", "--vision", "--batch"})
|
||||
if (e.rfind(no, 0) == 0) {
|
||||
std::fprintf(stderr, "unbiased-strata: %s is not supported here (use --mmproj for image input)\n", e.c_str());
|
||||
std::exit(2);
|
||||
}
|
||||
o.extra.push_back(e);
|
||||
}
|
||||
}
|
||||
else if (a == "-h" || a == "--help") return false;
|
||||
else { std::fprintf(stderr, "unbiased-strata: unknown option %s\n\n", a.c_str()); return false; }
|
||||
}
|
||||
return !o.model.empty() && !o.pack.empty() && !o.mtp.empty();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc > 1 && std::strcmp(argv[1], "--engine") == 0) return strata_engine_main(argc - 1, argv + 1);
|
||||
|
||||
Server srv;
|
||||
Options& o = srv.opt;
|
||||
if (!parse_args(argc, argv, o)) { usage(); return 2; }
|
||||
g_model_name = model_name_of(o.model);
|
||||
|
||||
// every file the engine needs must already be here: nothing is fetched
|
||||
// Flash-Next ships as two shards and the second holds the PLE table, so it is the engine's --ple-gguf; a one-file
|
||||
// model (Qwen3.6-35B-A3B) has no PLE and no second shard, and the engine decides from the file's architecture
|
||||
std::string shard2 = o.model;
|
||||
const size_t at = shard2.rfind("-00001-of-00002");
|
||||
if (at != std::string::npos) shard2.replace(at, 15, "-00002-of-00002");
|
||||
else shard2.clear();
|
||||
const std::string profile = o.pack + "/expert-profile.bin";
|
||||
// draft_vocab.bin is the draft head's vocabulary subset; a Qwen3.6 draft pack built with the full head
|
||||
// (tools/mtp_qwen36_pack.py --full-head) has none and the engine then drafts over the whole vocabulary
|
||||
for (const std::string& f : {o.model, shard2, o.pack + "/index.txt", profile, o.mtp + "/experts.bin"})
|
||||
if (!f.empty() && !file_exists(f)) { std::fprintf(stderr, "unbiased-strata: missing file: %s\n", f.c_str()); return 2; }
|
||||
if (o.ctx < 1024) { std::fprintf(stderr, "unbiased-strata: --ctx must be at least 1024\n"); return 2; }
|
||||
|
||||
if (!o.mmproj.empty() && (!file_exists(o.mmproj) || o.vision_tokens < 16 || o.vision_tokens > 4096)) {
|
||||
std::fprintf(stderr, "unbiased-strata: --mmproj must exist and --vision-tokens must be 16..4096\n"); return 2;
|
||||
}
|
||||
// the engine, started first: loading takes minutes, and it must be forked before any thread exists
|
||||
std::vector<std::string> eargs = {
|
||||
"unbiased-strata", "--engine", "--serve", "--pack", o.pack, "--native", o.model,
|
||||
"--expert-profile", profile, "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5",
|
||||
"--mtp", o.mtp, "--max-context", std::to_string(o.ctx)};
|
||||
if (!shard2.empty()) { eargs.push_back("--ple-gguf"); eargs.push_back(shard2); eargs.push_back("--ple-io"); eargs.push_back("ram"); }
|
||||
if (o.vram_cap_mib > 0) { eargs.push_back("--vram-cap"); eargs.push_back(std::to_string(o.vram_cap_mib)); }
|
||||
if (o.ram_cap_gib > 0.0) { eargs.push_back("--ram-cap"); eargs.push_back(std::to_string(o.ram_cap_gib)); }
|
||||
if (!o.mmproj.empty()) eargs.push_back("--vision");
|
||||
if (o.ctx > 8192) { eargs.push_back("--kv"); eargs.push_back("int8"); }
|
||||
if (o.threads <= 0) {
|
||||
o.threads = default_threads();
|
||||
if (o.threads > 0)
|
||||
std::fprintf(stderr, "unbiased-strata: this container's CPU quota gives %d expert threads (--threads N overrides)\n",
|
||||
o.threads);
|
||||
}
|
||||
if (o.threads > 0) { eargs.push_back("--pool-workers"); eargs.push_back(std::to_string(o.threads)); }
|
||||
for (const std::string& e : o.extra) eargs.push_back(e);
|
||||
std::signal(SIGPIPE, SIG_IGN);
|
||||
std::string err;
|
||||
if (!srv.engine.start(eargs, err)) { std::fprintf(stderr, "unbiased-strata: %s\n", err.c_str()); return 1; }
|
||||
|
||||
// the tokenizer and the chat template, from the GGUF itself
|
||||
llama_log_set(quiet_log, nullptr);
|
||||
llama_backend_init();
|
||||
llama_model_params mp = llama_model_default_params();
|
||||
mp.vocab_only = true;
|
||||
srv.model = llama_model_load_from_file(o.model.c_str(), mp);
|
||||
if (srv.model == nullptr) {
|
||||
std::fprintf(stderr, "unbiased-strata: could not read the tokenizer from %s\n", o.model.c_str());
|
||||
srv.engine.quit();
|
||||
return 1;
|
||||
}
|
||||
srv.vocab = llama_model_get_vocab(srv.model);
|
||||
srv.tmpls = common_chat_templates_init(srv.model, "");
|
||||
if (!o.mmproj.empty()) {
|
||||
try { srv.vision.init(o.mmproj, srv.model, o.threads, o.vision_tokens); }
|
||||
catch (const std::exception& ex) {
|
||||
std::fprintf(stderr, "unbiased-strata: %s\n", ex.what()); srv.engine.quit(); return 1;
|
||||
}
|
||||
}
|
||||
|
||||
std::fprintf(stderr, "unbiased-strata: loading the model (this takes a few minutes)...\n");
|
||||
long long engine_ctx = 0;
|
||||
if (!srv.engine.wait_ready(err, &engine_ctx)) {
|
||||
std::fprintf(stderr, "unbiased-strata: %s\n", err.c_str());
|
||||
srv.engine.quit();
|
||||
return 1;
|
||||
}
|
||||
if (engine_ctx > 0 && engine_ctx != o.ctx) { // the engine's VRAM plan lowered the context: serve that one
|
||||
std::fprintf(stderr, "unbiased-strata: the engine allocated a context of %lld tokens, not the %lld requested; "
|
||||
"requests are bounded by %lld\n", engine_ctx, o.ctx, engine_ctx);
|
||||
o.ctx = engine_ctx;
|
||||
}
|
||||
|
||||
httplib::Server http;
|
||||
g_server = &srv;
|
||||
g_http = &http;
|
||||
// /health: ok or error, plus the engine's expert tiers and counters when it is between requests (STATS: VRAM
|
||||
// slots and how many hold an expert, RAM copies, mapped experts, tokens served, VRAM hits of lookups, RAM-copy
|
||||
// and file reads, warm hints, major page faults). During a request the last reading is served, marked stale.
|
||||
// httplib serves /health from several threads: the last reading has its own lock (engine.mu is the engine's,
|
||||
// taken only to ask), and every read of it is a copy under that lock.
|
||||
static std::mutex stats_mu;
|
||||
static std::string last_stats;
|
||||
http.Get("/health", [&](const httplib::Request&, httplib::Response& res) {
|
||||
res.status = srv.engine.alive() ? 200 : 503;
|
||||
std::string body = srv.engine.alive() ? "{\"status\":\"ok\"" : "{\"status\":\"error\"";
|
||||
if (srv.engine.alive()) {
|
||||
std::unique_lock<std::mutex> lk(srv.engine.mu, std::try_to_lock);
|
||||
if (lk.owns_lock()) {
|
||||
std::string reply, err;
|
||||
const bool got = srv.engine.command("STATS", "STATS ", reply, err);
|
||||
lk.unlock();
|
||||
std::string stats;
|
||||
{
|
||||
std::lock_guard<std::mutex> sl(stats_mu);
|
||||
if (got) last_stats = reply.substr(6);
|
||||
stats = last_stats;
|
||||
}
|
||||
if (!got && stats.empty()) body += ",\"tiers_error\":\"" + err + "\"";
|
||||
if (!stats.empty()) body += ",\"tiers\":" + stats;
|
||||
} else {
|
||||
std::string stats;
|
||||
{
|
||||
std::lock_guard<std::mutex> sl(stats_mu);
|
||||
stats = last_stats;
|
||||
}
|
||||
if (!stats.empty()) body += ",\"tiers\":" + stats + ",\"tiers_stale\":true";
|
||||
else body += ",\"busy\":true";
|
||||
}
|
||||
}
|
||||
body += "}";
|
||||
res.set_content(body, "application/json");
|
||||
});
|
||||
http.Get("/v1/models", [&](const httplib::Request&, httplib::Response& res) {
|
||||
if (!srv.engine.alive()) return json_error(res, 503, "the engine is not running", "server_error");
|
||||
common_json m = common_json::object();
|
||||
m["id"] = g_model_name;
|
||||
m["object"] = "model";
|
||||
m["owned_by"] = "local";
|
||||
m["context_length"] = srv.opt.ctx;
|
||||
m["input_modalities"] = common_json::array();
|
||||
m["input_modalities"].push_back("text");
|
||||
if (srv.vision.enabled()) m["input_modalities"].push_back("image");
|
||||
common_json out = common_json::object();
|
||||
out["object"] = "list";
|
||||
out["data"] = common_json::array();
|
||||
out["data"].push_back(m);
|
||||
res.set_content(out.dump_safe(), "application/json");
|
||||
});
|
||||
http.Post("/v1/chat/completions", [&](const httplib::Request& req, httplib::Response& res) {
|
||||
srv.handle_chat(req, res);
|
||||
});
|
||||
http.set_payload_max_length(64 * 1024 * 1024);
|
||||
http.set_read_timeout(600, 0);
|
||||
http.set_write_timeout(600, 0);
|
||||
std::signal(SIGINT, on_signal);
|
||||
std::signal(SIGTERM, on_signal);
|
||||
|
||||
if (!http.bind_to_port(o.host, o.port)) {
|
||||
std::fprintf(stderr, "unbiased-strata: could not listen on %s:%d\n", o.host.c_str(), o.port);
|
||||
srv.engine.quit();
|
||||
return 1;
|
||||
}
|
||||
std::fprintf(stderr, "unbiased-strata: ready on http://%s:%d (context %lld tokens)\n", o.host.c_str(), o.port, o.ctx);
|
||||
// The engine watchdog intentionally aborts a stuck child. Exit the HTTP
|
||||
// parent too so systemd's Restart=on-failure reloads the complete service.
|
||||
// Do not fork a replacement from this multithreaded HTTP process.
|
||||
std::atomic<bool> shutting_down{false};
|
||||
std::thread supervisor([&] {
|
||||
while (!shutting_down.load()) {
|
||||
std::string why;
|
||||
if (srv.engine.reap_exit(why)) {
|
||||
std::fprintf(stderr, "unbiased-strata: %s; exiting frontend for service restart\n", why.c_str());
|
||||
std::fflush(stderr);
|
||||
std::_Exit(1);
|
||||
}
|
||||
if (!srv.engine.alive()) {
|
||||
std::fprintf(stderr, "unbiased-strata: engine protocol failed; exiting frontend for service restart\n");
|
||||
std::fflush(stderr);
|
||||
std::_Exit(1);
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
});
|
||||
http.listen_after_bind();
|
||||
shutting_down.store(true);
|
||||
supervisor.join();
|
||||
|
||||
std::fprintf(stderr, "unbiased-strata: stopping\n");
|
||||
srv.engine.quit();
|
||||
llama_model_free(srv.model);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
#pragma once
|
||||
#include "common.h"
|
||||
#include "gguf.h"
|
||||
#include "mtmd.h"
|
||||
#include "mtmd-helper.h"
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace strata_frontend {
|
||||
// Private per-request file, retained through streaming completion/cancellation.
|
||||
struct ImageFile {
|
||||
std::string path;
|
||||
ImageFile() {
|
||||
char name[] = "/tmp/unbiased-strata-image-XXXXXX";
|
||||
int fd = mkstemp(name);
|
||||
if (fd < 0) throw std::runtime_error("cannot create image embedding file");
|
||||
close(fd); path = name;
|
||||
}
|
||||
~ImageFile() { if (!path.empty()) unlink(path.c_str()); }
|
||||
ImageFile(const ImageFile&) = delete;
|
||||
ImageFile& operator=(const ImageFile&) = delete;
|
||||
};
|
||||
|
||||
inline std::vector<unsigned char> image_data(const std::string& url) {
|
||||
const size_t comma = url.find(',');
|
||||
if (url.rfind("data:image/", 0) != 0 || comma == std::string::npos ||
|
||||
comma < 7 || url.substr(comma - 7, 7) != ";base64")
|
||||
throw std::invalid_argument("image_url must contain a base64 data:image URL (PNG, JPEG, BMP or GIF)");
|
||||
const std::string data = url.substr(comma + 1);
|
||||
if (data.empty() || data.size() > 32 * 1024 * 1024 || data.size() % 4)
|
||||
throw std::invalid_argument("empty, oversized or malformed base64 image");
|
||||
const std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
std::array<int, 256> table; table.fill(-1);
|
||||
for (size_t i = 0; i < alphabet.size(); ++i) table[(unsigned char) alphabet[i]] = (int) i;
|
||||
std::vector<unsigned char> out; out.reserve(data.size() / 4 * 3);
|
||||
for (size_t i = 0; i < data.size(); i += 4) {
|
||||
int a = table[(unsigned char)data[i]], b = table[(unsigned char)data[i+1]];
|
||||
bool p2 = data[i+2] == '=', p3 = data[i+3] == '=';
|
||||
int c = p2 ? 0 : table[(unsigned char)data[i+2]], d = p3 ? 0 : table[(unsigned char)data[i+3]];
|
||||
if (a < 0 || b < 0 || c < 0 || d < 0 || (p2 && !p3) ||
|
||||
((p2 || p3) && i + 4 != data.size()) || (p2 && (b & 15)) || (!p2 && p3 && (c & 3)))
|
||||
throw std::invalid_argument("malformed base64 image");
|
||||
out.push_back((a << 2) | (b >> 4));
|
||||
if (!p2) out.push_back((b << 4) | (c >> 2));
|
||||
if (!p3) out.push_back((c << 6) | d);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
struct EncodedImage {
|
||||
int32_t tokens, nx, ny, width;
|
||||
std::vector<float> values;
|
||||
};
|
||||
|
||||
// CPU encoder leaves the engine's full VRAM expert cache available. Its callers
|
||||
// take engine.mu, serializing image encoding and generation just like upstream.
|
||||
class Vision {
|
||||
mtmd_context* ctx_ = nullptr;
|
||||
int width_ = 0;
|
||||
int max_tokens_ = 1024;
|
||||
size_t cache_bytes_ = 0;
|
||||
std::map<std::string, std::shared_ptr<EncodedImage>> cache_;
|
||||
public:
|
||||
~Vision() { if (ctx_) mtmd_free(ctx_); }
|
||||
bool enabled() const { return ctx_ != nullptr; }
|
||||
void init(const std::string& path, const llama_model* model, int threads, int max_tokens) {
|
||||
gguf_init_params gp{true, nullptr};
|
||||
auto gg = std::unique_ptr<gguf_context, decltype(&gguf_free)>(gguf_init_from_file(path.c_str(), gp), gguf_free);
|
||||
auto key = gg ? gguf_find_key(gg.get(), "clip.vision.projection_dim") : -1;
|
||||
if (key < 0) throw std::runtime_error("vision encoder has no projection_dim");
|
||||
width_ = (int) gguf_get_val_u32(gg.get(), key);
|
||||
// the projector must produce rows of the model's own width (2560 for Flash-Next, 2048 for Qwen3.6-35B-A3B);
|
||||
// the tokenizer-only model the front end holds has no hparams, so the width is read from its metadata
|
||||
char arch[64] = {0}, val[32] = {0};
|
||||
int want = 0;
|
||||
if (llama_model_meta_val_str(model, "general.architecture", arch, sizeof arch) > 0 &&
|
||||
llama_model_meta_val_str(model, (std::string(arch) + ".embedding_length").c_str(), val, sizeof val) > 0)
|
||||
want = std::atoi(val);
|
||||
if (want <= 0) throw std::runtime_error("cannot read the model's embedding width");
|
||||
if (width_ != want)
|
||||
throw std::runtime_error("vision projector width " + std::to_string(width_) +
|
||||
" does not match the model's embedding width " + std::to_string(want));
|
||||
max_tokens_ = max_tokens;
|
||||
auto cp = mtmd_context_params_default();
|
||||
cp.use_gpu = false; cp.print_timings = false; cp.warmup = false;
|
||||
cp.n_threads = threads > 0 ? threads : 8;
|
||||
cp.image_max_tokens = max_tokens;
|
||||
ctx_ = mtmd_init_from_file(path.c_str(), model, cp);
|
||||
if (!ctx_ || !mtmd_support_vision(ctx_)) throw std::runtime_error("cannot load vision encoder: " + path);
|
||||
}
|
||||
std::shared_ptr<EncodedImage> encode(const std::string& url) {
|
||||
if (!ctx_) throw std::invalid_argument("image input requires starting UnbiasedStrata with --mmproj PATH");
|
||||
auto bytes = image_data(url);
|
||||
auto t0 = std::chrono::steady_clock::now();
|
||||
auto bw = mtmd_helper_bitmap_init_from_buf(ctx_, bytes.data(), bytes.size(), false, mtmd_helper_init_opt_default());
|
||||
std::unique_ptr<mtmd_bitmap, decltype(&mtmd_bitmap_free)> bitmap(bw.bitmap, mtmd_bitmap_free);
|
||||
if (bw.video_ctx) mtmd_helper_video_free(bw.video_ctx);
|
||||
if (!bitmap || mtmd_bitmap_is_audio(bitmap.get())) throw std::invalid_argument("cannot decode image; use PNG, JPEG, BMP or GIF");
|
||||
const char* hash = mtmd_bitmap_get_id(bitmap.get());
|
||||
if (!hash || !*hash) throw std::runtime_error("image decoder did not supply a content hash");
|
||||
std::string id(hash);
|
||||
auto cached = cache_.find(id);
|
||||
if (cached != cache_.end()) return cached->second;
|
||||
auto chunks = std::unique_ptr<mtmd_input_chunks, decltype(&mtmd_input_chunks_free)>(mtmd_input_chunks_init(), mtmd_input_chunks_free);
|
||||
std::string marker = mtmd_default_marker();
|
||||
mtmd_input_text txt{marker.c_str(), marker.size(), false, true};
|
||||
const mtmd_bitmap* bm[] = {bitmap.get()};
|
||||
if (mtmd_tokenize(ctx_, chunks.get(), &txt, bm, 1)) throw std::invalid_argument("image preprocessing failed");
|
||||
const mtmd_input_chunk* image = nullptr;
|
||||
for (size_t i = 0; i < mtmd_input_chunks_size(chunks.get()); ++i) {
|
||||
auto ch = mtmd_input_chunks_get(chunks.get(), i);
|
||||
if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
|
||||
if (image) throw std::invalid_argument("multiple image chunks are unsupported for this model");
|
||||
image = ch;
|
||||
}
|
||||
}
|
||||
if (!image) throw std::invalid_argument("no image tokens produced");
|
||||
size_t n = mtmd_input_chunk_get_n_tokens(image);
|
||||
if (!n || n > (size_t)max_tokens_) throw std::invalid_argument("image token count exceeds configured limit");
|
||||
if (mtmd_encode_chunk(ctx_, image)) throw std::runtime_error("vision encoding failed");
|
||||
auto last = mtmd_image_tokens_get_decoder_pos(mtmd_input_chunk_get_tokens_image(image), 0, n-1);
|
||||
int nx = (int)last.x + 1, ny = (int)last.y + 1;
|
||||
if ((size_t)nx * ny != n) throw std::runtime_error("image grid is not rectangular");
|
||||
auto result = std::make_shared<EncodedImage>();
|
||||
result->tokens = (int32_t)n; result->nx = nx; result->ny = ny; result->width = width_;
|
||||
auto values = mtmd_get_output_embd(ctx_);
|
||||
if (!values) throw std::runtime_error("encoder returned no image embeddings");
|
||||
result->values.assign(values, values+n*width_);
|
||||
size_t size = result->values.size()*sizeof(float);
|
||||
if (cache_bytes_ + size > 128*1024*1024) { cache_.clear(); cache_bytes_ = 0; }
|
||||
cache_[id] = result; cache_bytes_ += size;
|
||||
auto ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now()-t0).count();
|
||||
std::fprintf(stderr, "unbiased-strata: encoded image %.0f ms, %d tokens (%dx%d), CPU\n", ms, result->tokens, nx, ny);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
inline void write_images(const ImageFile& file, const std::vector<std::shared_ptr<EncodedImage>>& images) {
|
||||
auto f = std::unique_ptr<FILE, decltype(&std::fclose)>(std::fopen(file.path.c_str(), "wb"), std::fclose);
|
||||
if (!f) throw std::runtime_error("cannot open image embedding file");
|
||||
for (auto& im : images) {
|
||||
int32_t hdr[] = {0x31455653, im->tokens, im->nx, im->ny, im->width};
|
||||
if (std::fwrite(hdr, sizeof(hdr), 1, f.get()) != 1 ||
|
||||
std::fwrite(im->values.data(), sizeof(float), im->values.size(), f.get()) != im->values.size())
|
||||
throw std::runtime_error("short write to image embedding file");
|
||||
}
|
||||
if (std::fflush(f.get())) throw std::runtime_error("cannot flush image embedding file");
|
||||
}
|
||||
} // namespace strata_frontend
|
||||
@@ -1,292 +0,0 @@
|
||||
#pragma once
|
||||
// src/artifact/dequant.cpp - P1.S3: scalar reference dequantizers, transcribed from ggml.
|
||||
//
|
||||
// P1.S3 asks for every encoding present in the Q2_0 file. This starts with the ones on the critical
|
||||
// path (the routed experts are all Q2_0) plus the trivial element types, and is structured so the
|
||||
// rest drop in. Source of truth per encoding is quoted in each function.
|
||||
//
|
||||
// Q2_0 is the one that matters, and its contract is settled from source in docs/q2_0-contract.md:
|
||||
// block = { fp16 d; uint8 qs[16] } = 64 elements, 18 bytes
|
||||
// code {0,1,2,3} -> symbol {-1,0,+1,+2}; v = (code - 1) * d
|
||||
// 4 codes per byte, LSB-first: byte j/4, bits (j%4)*2
|
||||
// QK2_0 = 64 is PROVEN from the artifact's own offset brackets, not assumed (the llama.cpp PR that
|
||||
// introduced the type used 128; this artifact is 64).
|
||||
//
|
||||
// Validation: `--check <file.gguf>` dequantizes real blocks and asserts the STRUCTURAL invariant that
|
||||
// every output value is one of {-d, 0, +d, +2d} for that block's own scale. That catches bit-order,
|
||||
// sign and stride bugs, which are the failure modes a dequantizer actually has. It is deliberately
|
||||
// not a correctness-vs-ggml test - that needs ggml linked, which is P1.S3's next step.
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#define STRATA_GGUF_MAIN_DISABLED 1
|
||||
#include "strata/artifact/gguf_reader.hpp"
|
||||
|
||||
namespace strata {
|
||||
|
||||
// ---- fp16/bf16 -> fp32. Both handle subnormals and infinities; naive shifts do not.
|
||||
inline float fp16_to_fp32(uint16_t h) {
|
||||
const uint32_t sign = (uint32_t)(h >> 15) & 1u;
|
||||
uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f;
|
||||
if (exp == 0) {
|
||||
if (man == 0)
|
||||
f = sign << 31;
|
||||
else {
|
||||
exp = 127 - 15 + 1;
|
||||
while (!(man & 0x400u)) {
|
||||
man <<= 1;
|
||||
--exp;
|
||||
}
|
||||
man &= 0x3FFu;
|
||||
f = (sign << 31) | (exp << 23) | (man << 13);
|
||||
}
|
||||
} else if (exp == 31)
|
||||
f = (sign << 31) | 0x7F800000u | (man << 13);
|
||||
else
|
||||
f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13);
|
||||
float out;
|
||||
std::memcpy(&out, &f, 4);
|
||||
return out;
|
||||
}
|
||||
|
||||
inline float bf16_to_fp32(uint16_t h) {
|
||||
const uint32_t f = (uint32_t)h << 16;
|
||||
float out;
|
||||
std::memcpy(&out, &f, 4);
|
||||
return out;
|
||||
}
|
||||
|
||||
inline uint16_t read_u16(const uint8_t* p) {
|
||||
return (uint16_t)(p[0] | (p[1] << 8));
|
||||
}
|
||||
|
||||
// ---- Q2_0: 64 elements from an 18-byte block. Mirrors dequantize_row_q2_0 (ggml master 3cf03257).
|
||||
inline void dequantize_q2_0(const uint8_t* block, float* out) {
|
||||
const float d = fp16_to_fp32(read_u16(block));
|
||||
const uint8_t* qs = block + 2;
|
||||
for (int j = 0; j < 64; ++j) {
|
||||
const int byte_index = j / 4;
|
||||
const int bit_offset = (j % 4) * 2;
|
||||
const int code = (qs[byte_index] >> bit_offset) & 0x03;
|
||||
out[j] = (float)(code - 1) * d; // code {0,1,2,3} -> symbol {-1,0,+1,+2}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Q8_0: 32 elements from a 34-byte block.
|
||||
inline void dequantize_q8_0(const uint8_t* block, float* out) {
|
||||
const float d = fp16_to_fp32(read_u16(block));
|
||||
const int8_t* qs = (const int8_t*)(block + 2);
|
||||
for (int j = 0; j < 32; ++j) out[j] = (float)qs[j] * d;
|
||||
}
|
||||
|
||||
// ---- Q4_0: 32 elements from an 18-byte block. Low nibble is element j, high nibble is j+16.
|
||||
inline void dequantize_q4_0(const uint8_t* block, float* out) {
|
||||
const float d = fp16_to_fp32(read_u16(block));
|
||||
const uint8_t* qs = block + 2;
|
||||
for (int j = 0; j < 16; ++j) {
|
||||
out[j] = (float)((int)(qs[j] & 0x0F) - 8) * d;
|
||||
out[j + 16] = (float)((int)(qs[j] >> 4) - 8) * d;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Q5_0: 32 elements from a 22-byte block. Same nibble layout as Q4_0 plus a 5th bit per element
|
||||
// packed in qh[4]; the 32 bits of qh are the high bits of elements 0..31 in order.
|
||||
inline void dequantize_q5_0(const uint8_t* block, float* out) {
|
||||
const float d = fp16_to_fp32(read_u16(block));
|
||||
const uint8_t* qh = block + 2;
|
||||
const uint8_t* qs = block + 6;
|
||||
const uint32_t h =
|
||||
(uint32_t)qh[0] | ((uint32_t)qh[1] << 8) | ((uint32_t)qh[2] << 16) | ((uint32_t)qh[3] << 24);
|
||||
for (int j = 0; j < 16; ++j) {
|
||||
const int x0 = (int)(qs[j] & 0x0F) | (int)(((h >> j) & 1u) << 4);
|
||||
const int x1 = (int)(qs[j] >> 4) | (int)(((h >> (j + 16)) & 1u) << 4);
|
||||
out[j] = (float)(x0 - 16) * d;
|
||||
out[j + 16] = (float)(x1 - 16) * d;
|
||||
}
|
||||
}
|
||||
// ---- IQ4_NL: 32 elements from an 18-byte block. Non-linear 4-bit codebook, NOT a linear grid, so
|
||||
// the table must be exact. Copied verbatim from ggml-common.h `kvalues_iq4nl` at 3cf03257:
|
||||
// -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113
|
||||
// Layout matches dequantize_row_iq4_nl (ggml-quants.c): low nibble is element j, high nibble j+16.
|
||||
static const int8_t kvalues_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10,
|
||||
1, 13, 25, 38, 53, 69, 89, 113};
|
||||
|
||||
inline void dequantize_iq4_nl(const uint8_t* block, float* out) {
|
||||
const float d = fp16_to_fp32(read_u16(block));
|
||||
const uint8_t* qs = block + 2;
|
||||
for (int j = 0; j < 16; ++j) {
|
||||
out[j] = d * (float)kvalues_iq4nl[qs[j] & 0x0F];
|
||||
out[j + 16] = d * (float)kvalues_iq4nl[qs[j] >> 4];
|
||||
}
|
||||
}
|
||||
// ---- Q6_K: 256 elements from a 210-byte super-block, transcribed from dequantize_row_q6_K
|
||||
// (ggml-quants.c at 3cf03257). Layout: ql[128] low nibbles, qh[64] high 2 bits, scales[16] int8,
|
||||
// fp16 d LAST. Processed in two 128-element halves, each advancing ql by 64, qh by 32, sc by 8.
|
||||
// The `sc` indices are is+{0,2,4,6} with is = l/16 - so each 32-element group draws from 8 of the 16
|
||||
// scales, and the four output positions within a 32-group use different scales. Easy to get subtly
|
||||
// wrong, which is why it is transcribed rather than recalled.
|
||||
inline void dequantize_q6_K(const uint8_t* block, float* out) {
|
||||
const uint8_t* ql = block; // 128 bytes
|
||||
const uint8_t* qh = block + 128; // 64
|
||||
const int8_t* sc = (const int8_t*)(block + 192); // 16
|
||||
const float d = fp16_to_fp32(read_u16(block + 208));
|
||||
float* y = out;
|
||||
for (int n = 0; n < 256; n += 128) {
|
||||
for (int l = 0; l < 32; ++l) {
|
||||
const int is = l / 16;
|
||||
const int q1 = (int)((ql[l + 0] & 0x0F) | (((qh[l] >> 0) & 3) << 4)) - 32;
|
||||
const int q2 = (int)((ql[l + 32] & 0x0F) | (((qh[l] >> 2) & 3) << 4)) - 32;
|
||||
const int q3 = (int)((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32;
|
||||
const int q4 = (int)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32;
|
||||
y[l + 0] = d * (float)sc[is + 0] * (float)q1;
|
||||
y[l + 32] = d * (float)sc[is + 2] * (float)q2;
|
||||
y[l + 64] = d * (float)sc[is + 4] * (float)q3;
|
||||
y[l + 96] = d * (float)sc[is + 6] * (float)q4;
|
||||
}
|
||||
y += 128;
|
||||
ql += 64;
|
||||
qh += 32;
|
||||
sc += 8;
|
||||
}
|
||||
}
|
||||
// ---- Q4_K: 256 elements from a 144-byte super-block. Layout is `fp16 d`, `fp16 dmin` (so the FIRST
|
||||
// four bytes are the scale pair, unlike Q6_K where d is last), `scales[12]`, `qs[128]`.
|
||||
// Both functions transcribed from ggml-quants.c at 3cf03257. The 6-bit scale/min unpacking in
|
||||
// get_scale_min_k4 is the part that is impossible to recall reliably: the low 4 bits of the second
|
||||
// half come from q[j+4], and the high 2 bits from the low halves' top bits (q[j-4] and q[j]).
|
||||
static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) {
|
||||
if (j < 4) {
|
||||
d = q[j] & 63;
|
||||
m = q[j + 4] & 63;
|
||||
} else {
|
||||
d = (q[j + 4] & 0x0F) | ((q[j - 4] >> 6) << 4);
|
||||
m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
|
||||
}
|
||||
}
|
||||
|
||||
inline void dequantize_q4_K(const uint8_t* block, float* out) {
|
||||
const float d = fp16_to_fp32(read_u16(block)); // d
|
||||
const float mn = fp16_to_fp32(read_u16(block + 2)); // dmin
|
||||
const uint8_t* scales = block + 4; // 12 bytes
|
||||
const uint8_t* q = block + 16; // 128 bytes
|
||||
float* y = out;
|
||||
int is = 0;
|
||||
for (int j = 0; j < 256; j += 64) {
|
||||
uint8_t sc, m;
|
||||
get_scale_min_k4(is + 0, scales, sc, m);
|
||||
const float d1 = d * (float)sc, m1 = mn * (float)m;
|
||||
get_scale_min_k4(is + 1, scales, sc, m);
|
||||
const float d2 = d * (float)sc, m2 = mn * (float)m;
|
||||
for (int l = 0; l < 32; ++l) *y++ = d1 * (float)(q[l] & 0x0F) - m1;
|
||||
for (int l = 0; l < 32; ++l) *y++ = d2 * (float)(q[l] >> 4) - m2;
|
||||
q += 32;
|
||||
is += 2;
|
||||
}
|
||||
}
|
||||
// ---- Q5_K: 256 elements from a 176-byte super-block: `fp16 d`, `fp16 dmin`, `scales[12]`,
|
||||
// `qh[32]`, `qs[128]`. Same shape as Q4_K plus the 5th bit plane. Transcribed from
|
||||
// dequantize_row_q5_K (ggml-quants.c, 3cf03257). The 5th bits are selected by a mask that SHIFTS LEFT
|
||||
// BY 2 each 64-element group (u1 = 1,4,16,64; u2 = 2,8,32,128) - a recalled version would very likely
|
||||
// have used a fixed mask or a shift by 1.
|
||||
inline void dequantize_q5_K(const uint8_t* block, float* out) {
|
||||
const float d = fp16_to_fp32(read_u16(block));
|
||||
const float mn = fp16_to_fp32(read_u16(block + 2));
|
||||
const uint8_t* scales = block + 4; // 12
|
||||
const uint8_t* qh = block + 16; // 32
|
||||
const uint8_t* ql = block + 48; // 128
|
||||
float* y = out;
|
||||
int is = 0;
|
||||
uint8_t u1 = 1, u2 = 2;
|
||||
for (int j = 0; j < 256; j += 64) {
|
||||
uint8_t sc, m;
|
||||
get_scale_min_k4(is + 0, scales, sc, m);
|
||||
const float d1 = d * (float)sc, m1 = mn * (float)m;
|
||||
get_scale_min_k4(is + 1, scales, sc, m);
|
||||
const float d2 = d * (float)sc, m2 = mn * (float)m;
|
||||
for (int l = 0; l < 32; ++l) *y++ = d1 * (float)((ql[l] & 0x0F) + ((qh[l] & u1) ? 16 : 0)) - m1;
|
||||
for (int l = 0; l < 32; ++l) *y++ = d2 * (float)((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - m2;
|
||||
ql += 32;
|
||||
is += 2;
|
||||
u1 = (uint8_t)(u1 << 2);
|
||||
u2 = (uint8_t)(u2 << 2);
|
||||
}
|
||||
}
|
||||
// ---- Q3_K: 256 elements from a 110-byte super-block: `hmask[32]`, `qs[64]`, `scales[12]`, `fp16 d`
|
||||
// LAST. Transcribed from dequantize_row_q3_K (ggml-quants.c, 3cf03257). This type has NO `dmin` - its
|
||||
// scales are SIGNED 6-bit with a `- 32` bias - so it does not follow the Q4_K/Q5_K pattern at all.
|
||||
// Two details that cannot be recalled:
|
||||
// * the 12 scale bytes are bit-repacked through three 32-bit masks before use (kmask1/2 below),
|
||||
// because 16 six-bit scales do not fit in 12 bytes linearly;
|
||||
// * the low 2 bits are offset by -4 when the high bit is CLEAR, i.e. the correction is NEGATIVE.
|
||||
inline void dequantize_q3_K(const uint8_t* block, float* out) {
|
||||
const uint8_t* hm = block; // 32
|
||||
const uint8_t* q = block + 32; // 64
|
||||
const float d_all = fp16_to_fp32(read_u16(block + 108));
|
||||
|
||||
const uint32_t kmask1 = 0x03030303u, kmask2 = 0x0f0f0f0fu;
|
||||
uint32_t aux[4] = {0, 0, 0, 0};
|
||||
std::memcpy(aux, block + 96, 12);
|
||||
const uint32_t tmp = aux[2];
|
||||
aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4);
|
||||
aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4);
|
||||
aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4);
|
||||
aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4);
|
||||
const int8_t* scales = (const int8_t*)aux;
|
||||
|
||||
float* y = out;
|
||||
int is = 0;
|
||||
uint8_t m = 1; // hoisted: ggml declares this BEFORE the n loop, so it does not reset between halves
|
||||
for (int n = 0; n < 256; n += 128) {
|
||||
int shift = 0;
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
float dl = d_all * (float)(scales[is++] - 32);
|
||||
for (int l = 0; l < 16; ++l)
|
||||
*y++ = dl * (float)((int8_t)((q[l + 0] >> shift) & 3) - ((hm[l + 0] & m) ? 0 : 4));
|
||||
dl = d_all * (float)(scales[is++] - 32);
|
||||
for (int l = 0; l < 16; ++l)
|
||||
*y++ = dl * (float)((int8_t)((q[l + 16] >> shift) & 3) - ((hm[l + 16] & m) ? 0 : 4));
|
||||
shift += 2;
|
||||
m = (uint8_t)(m << 1);
|
||||
}
|
||||
q += 32;
|
||||
}
|
||||
}
|
||||
// ---- IQ4_XS: 256 elements from a 136-byte super-block: `fp16 d`, `uint16 scales_h`, `scales_l[4]`,
|
||||
// `qs[128]`. Transcribed from dequantize_row_iq4_xs (ggml-quants.c, 3cf03257). Reuses the IQ4_NL
|
||||
// codebook. Eight 32-element groups; each group's scale is 6 bits assembled from the LOW nibble of
|
||||
// `scales_l[ib/2]` (selected by ib%2) and TWO bits of `scales_h` at shift 2*ib - so the high bits come
|
||||
// from a 16-bit field indexed by group, not from a byte array. Then `- 32`, as in Q3_K.
|
||||
inline void dequantize_iq4_xs(const uint8_t* block, float* out) {
|
||||
const float d = fp16_to_fp32(read_u16(block));
|
||||
const uint16_t scales_h = read_u16(block + 2);
|
||||
const uint8_t* scales_l = block + 4; // 4
|
||||
const uint8_t* qs = block + 8; // 128
|
||||
float* y = out;
|
||||
for (int ib = 0; ib < 8; ++ib) {
|
||||
const int ls = ((scales_l[ib / 2] >> (4 * (ib % 2))) & 0x0F) | (((scales_h >> (2 * ib)) & 3) << 4);
|
||||
const float dl = d * (float)(ls - 32);
|
||||
for (int j = 0; j < 16; ++j) {
|
||||
y[j + 0] = dl * (float)kvalues_iq4nl[qs[j] & 0x0F];
|
||||
y[j + 16] = dl * (float)kvalues_iq4nl[qs[j] >> 4];
|
||||
}
|
||||
y += 32;
|
||||
qs += 16;
|
||||
}
|
||||
}
|
||||
// ---- element types
|
||||
inline void dequantize_f32(const uint8_t* p, float* out, int n) {
|
||||
std::memcpy(out, p, (size_t)n * 4);
|
||||
}
|
||||
inline void dequantize_f16(const uint8_t* p, float* out, int n) {
|
||||
for (int i = 0; i < n; ++i) out[i] = fp16_to_fp32(read_u16(p + 2 * i));
|
||||
}
|
||||
inline void dequantize_bf16(const uint8_t* p, float* out, int n) {
|
||||
for (int i = 0; i < n; ++i) out[i] = bf16_to_fp32(read_u16(p + 2 * i));
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -1,627 +0,0 @@
|
||||
// include/strata/artifact/gguf_reader.hpp - generated from src/artifact/gguf_reader.cpp by
|
||||
// scripts/split_artifact.py. Header-only on purpose: the reader is one translation unit's worth of
|
||||
// code with no state to hide, and a header-only split cannot introduce a duplicate-symbol or
|
||||
// missing-declaration bug in code that is already validated.
|
||||
#pragma once
|
||||
// src/artifact/gguf_reader.cpp - P1.S2: GGUF v3 reader, mmap, no ggml dependency.
|
||||
//
|
||||
// The C++ counterpart of tools/gguf_reader.py, which has been the reference since P0.S6 (written
|
||||
// because gguf-py cannot represent type 42 / Q2_0). Per P1.S2 it must:
|
||||
// * mmap the file and parse header, metadata KV (ALL value types incl. arrays), tensor directory
|
||||
// * be multi-shard aware (split.* keys)
|
||||
// * carry an architecture guard: general.architecture == "qwen4exp" and the compiled-in constants
|
||||
// must match, refusing with a precise error otherwise
|
||||
// * have no ggml dependency
|
||||
//
|
||||
// This file is the reader plus a `--check` mode that validates it the way the Python one is
|
||||
// validated: parse the tiny model AND both real shards, and report counts that other harnesses have
|
||||
// already established independently (1,223 / 1 tensors; 202 Q2_0 in shard 1). Agreement with those
|
||||
// numbers is the test.
|
||||
//
|
||||
// Build: scripts/build_artifact.bat Run: gguf_reader.exe <file.gguf> [--check]
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
|
||||
#include "strata/artifact/gguf_split.hpp"
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX // windows.h's min/max macros would break std::min/std::max in every file that includes this one
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace strata {
|
||||
|
||||
// ---- ggml type ids we care about. 42 = Q2_0, the PrismML ternary 2-bit encoding this engine targets.
|
||||
inline const char* ggml_type_name(uint32_t t) {
|
||||
switch (t) {
|
||||
case 0:
|
||||
return "F32";
|
||||
case 1:
|
||||
return "F16";
|
||||
case 2:
|
||||
return "Q4_0";
|
||||
case 3:
|
||||
return "Q4_1";
|
||||
case 6:
|
||||
return "Q5_0";
|
||||
case 7:
|
||||
return "Q5_1";
|
||||
case 8:
|
||||
return "Q8_0";
|
||||
case 9:
|
||||
return "Q8_1";
|
||||
case 10:
|
||||
return "Q2_K";
|
||||
case 11:
|
||||
return "Q3_K";
|
||||
case 12:
|
||||
return "Q4_K";
|
||||
case 13:
|
||||
return "Q5_K";
|
||||
case 14:
|
||||
return "Q6_K";
|
||||
case 15:
|
||||
return "Q8_K";
|
||||
case 16:
|
||||
return "IQ2_XXS";
|
||||
case 17:
|
||||
return "IQ2_XS";
|
||||
case 18:
|
||||
return "IQ3_XXS";
|
||||
case 19:
|
||||
return "IQ1_S";
|
||||
case 20:
|
||||
return "IQ4_NL";
|
||||
case 21:
|
||||
return "IQ3_S";
|
||||
case 22:
|
||||
return "IQ2_S";
|
||||
case 23:
|
||||
return "IQ4_XS";
|
||||
case 24:
|
||||
return "I8";
|
||||
case 30:
|
||||
return "BF16";
|
||||
case 34:
|
||||
return "TQ1_0";
|
||||
case 35:
|
||||
return "TQ2_0";
|
||||
case 39:
|
||||
return "MXFP4";
|
||||
case 40:
|
||||
return "NVFP4";
|
||||
case 41:
|
||||
return "Q1_0";
|
||||
case 42:
|
||||
return "Q2_0";
|
||||
default:
|
||||
return "?";
|
||||
}
|
||||
}
|
||||
|
||||
// Block geometry: (elements per block, bytes per block). Q2_0 is 64/18 - proven from this artifact's
|
||||
// own offset brackets in P0.S6 and recorded in docs/q2_0-contract.md.
|
||||
inline bool block_geometry(uint32_t t, int& elems, int& bytes) {
|
||||
switch (t) {
|
||||
case 0:
|
||||
elems = 1;
|
||||
bytes = 4;
|
||||
return true;
|
||||
case 1:
|
||||
case 30:
|
||||
elems = 1;
|
||||
bytes = 2;
|
||||
return true;
|
||||
case 2:
|
||||
elems = 32;
|
||||
bytes = 18;
|
||||
return true;
|
||||
case 3:
|
||||
elems = 32;
|
||||
bytes = 20;
|
||||
return true;
|
||||
case 6:
|
||||
elems = 32;
|
||||
bytes = 22;
|
||||
return true;
|
||||
case 7:
|
||||
elems = 32;
|
||||
bytes = 24;
|
||||
return true;
|
||||
case 8:
|
||||
elems = 32;
|
||||
bytes = 34;
|
||||
return true;
|
||||
case 9:
|
||||
elems = 32;
|
||||
bytes = 36;
|
||||
return true;
|
||||
case 10:
|
||||
elems = 256;
|
||||
bytes = 84;
|
||||
return true;
|
||||
case 11:
|
||||
elems = 256;
|
||||
bytes = 110;
|
||||
return true;
|
||||
case 12:
|
||||
elems = 256;
|
||||
bytes = 144;
|
||||
return true;
|
||||
case 13:
|
||||
elems = 256;
|
||||
bytes = 176;
|
||||
return true;
|
||||
case 14:
|
||||
elems = 256;
|
||||
bytes = 210;
|
||||
return true;
|
||||
case 16:
|
||||
elems = 256;
|
||||
bytes = 66;
|
||||
return true;
|
||||
case 17:
|
||||
elems = 256;
|
||||
bytes = 74;
|
||||
return true;
|
||||
case 18:
|
||||
elems = 256;
|
||||
bytes = 98;
|
||||
return true;
|
||||
case 20:
|
||||
elems = 32;
|
||||
bytes = 18;
|
||||
return true;
|
||||
case 21: // IQ3_S
|
||||
elems = 256;
|
||||
bytes = 110;
|
||||
return true;
|
||||
case 22: // IQ2_S
|
||||
elems = 256;
|
||||
bytes = 82;
|
||||
return true;
|
||||
case 23:
|
||||
elems = 256;
|
||||
bytes = 136;
|
||||
return true;
|
||||
case 29: // IQ1_M
|
||||
elems = 256;
|
||||
bytes = 56;
|
||||
return true;
|
||||
case 24: // I8: raw bytes (the FP8 PLE table of tools/ple_fp8_pack.py)
|
||||
elems = 1;
|
||||
bytes = 1;
|
||||
return true;
|
||||
case 42:
|
||||
elems = 64;
|
||||
bytes = 18;
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
struct TensorInfo {
|
||||
std::string name;
|
||||
std::vector<uint64_t> shape; // GGUF order: dim 0 varies fastest
|
||||
uint32_t type = 0;
|
||||
uint64_t offset = 0;
|
||||
uint64_t elements() const {
|
||||
uint64_t n = 1;
|
||||
for (auto d : shape) n *= d;
|
||||
return n;
|
||||
}
|
||||
const char* type_name() const { return ggml_type_name(type); }
|
||||
};
|
||||
|
||||
// A bounds-checked cursor over the mmapped header region. Every read is checked, so a truncated or
|
||||
// corrupt file produces a precise error rather than a segfault.
|
||||
class Cursor {
|
||||
public:
|
||||
Cursor(const uint8_t* base, size_t size) : base_(base), size_(size) {}
|
||||
void need(size_t n) const {
|
||||
if (pos_ + n > size_) throw std::runtime_error("GGUF: unexpected end of file in header");
|
||||
}
|
||||
template <class T> T read() {
|
||||
need(sizeof(T));
|
||||
T v;
|
||||
std::memcpy(&v, base_ + pos_, sizeof(T));
|
||||
pos_ += sizeof(T);
|
||||
return v;
|
||||
}
|
||||
std::string str() {
|
||||
const uint64_t n = read<uint64_t>();
|
||||
need((size_t)n);
|
||||
std::string s(reinterpret_cast<const char*>(base_ + pos_), (size_t)n);
|
||||
pos_ += (size_t)n;
|
||||
return s;
|
||||
}
|
||||
size_t pos() const { return pos_; }
|
||||
|
||||
private:
|
||||
const uint8_t* base_;
|
||||
size_t size_;
|
||||
size_t pos_ = 0;
|
||||
};
|
||||
|
||||
enum class MetaType : uint32_t { U8 = 0, I8, U16, I16, U32, I32, F32, BOOL, STRING, ARRAY, U64, I64, F64 };
|
||||
|
||||
struct MetaValue {
|
||||
MetaType type = MetaType::U32;
|
||||
uint64_t u = 0; // integer payloads
|
||||
double f = 0; // float payloads
|
||||
std::string s; // string payloads
|
||||
MetaType elem = MetaType::U32; // arrays
|
||||
uint64_t count = 0;
|
||||
std::vector<MetaValue> items;
|
||||
bool is_num() const { return type != MetaType::STRING && type != MetaType::ARRAY; }
|
||||
double num() const { return (type == MetaType::F32 || type == MetaType::F64) ? f : (double)u; }
|
||||
};
|
||||
|
||||
inline MetaValue read_value(Cursor& c, MetaType t, int depth = 0) {
|
||||
if (depth > 2) throw std::runtime_error("GGUF: array nesting too deep");
|
||||
MetaValue v;
|
||||
v.type = t;
|
||||
switch (t) {
|
||||
case MetaType::U8:
|
||||
v.u = c.read<uint8_t>();
|
||||
break;
|
||||
case MetaType::I8:
|
||||
v.u = (uint64_t)(int64_t)c.read<int8_t>();
|
||||
break;
|
||||
case MetaType::U16:
|
||||
v.u = c.read<uint16_t>();
|
||||
break;
|
||||
case MetaType::I16:
|
||||
v.u = (uint64_t)(int64_t)c.read<int16_t>();
|
||||
break;
|
||||
case MetaType::U32:
|
||||
v.u = c.read<uint32_t>();
|
||||
break;
|
||||
case MetaType::I32:
|
||||
v.u = (uint64_t)(int64_t)c.read<int32_t>();
|
||||
break;
|
||||
case MetaType::F32: {
|
||||
float x = c.read<float>();
|
||||
v.f = x;
|
||||
v.u = 0;
|
||||
break;
|
||||
}
|
||||
case MetaType::BOOL:
|
||||
v.u = c.read<uint8_t>() ? 1 : 0;
|
||||
break;
|
||||
case MetaType::STRING:
|
||||
v.s = c.str();
|
||||
break;
|
||||
case MetaType::U64:
|
||||
v.u = c.read<uint64_t>();
|
||||
break;
|
||||
case MetaType::I64:
|
||||
v.u = (uint64_t)c.read<int64_t>();
|
||||
break;
|
||||
case MetaType::F64:
|
||||
v.f = c.read<double>();
|
||||
break;
|
||||
case MetaType::ARRAY: {
|
||||
v.elem = (MetaType)c.read<uint32_t>();
|
||||
v.count = c.read<uint64_t>();
|
||||
if (v.count > (1u << 24)) throw std::runtime_error("GGUF: implausible array length");
|
||||
v.items.reserve((size_t)std::min<uint64_t>(v.count, 64));
|
||||
for (uint64_t i = 0; i < v.count; ++i) {
|
||||
MetaValue e = read_value(c, v.elem, depth + 1);
|
||||
if (i < 64) v.items.push_back(std::move(e)); // keep a sample; the count is what matters
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw std::runtime_error("GGUF: unknown metadata value type");
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
class GgufFile {
|
||||
public:
|
||||
explicit GgufFile(const std::string& path) : path_(path) {
|
||||
try { open(); }
|
||||
catch (...) { close(); throw; }
|
||||
}
|
||||
~GgufFile() { close(); }
|
||||
GgufFile(const GgufFile&) = delete;
|
||||
GgufFile& operator=(const GgufFile&) = delete;
|
||||
|
||||
const std::vector<TensorInfo>& tensors() const { return tensors_; }
|
||||
const std::map<std::string, MetaValue>& metadata() const { return meta_; }
|
||||
uint32_t version() const { return version_; }
|
||||
uint64_t data_start() const { return data_start_; }
|
||||
uint64_t file_size() const { return size_; }
|
||||
uint64_t alignment() const { return alignment_; }
|
||||
const std::string& path() const { return path_; }
|
||||
|
||||
const TensorInfo* find(const std::string& name) const {
|
||||
for (const auto& t : tensors_)
|
||||
if (t.name == name) return &t;
|
||||
return nullptr;
|
||||
}
|
||||
uint64_t count_type(const char* tn) const {
|
||||
uint64_t n = 0;
|
||||
for (const auto& t : tensors_)
|
||||
if (std::strcmp(t.type_name(), tn) == 0) ++n;
|
||||
return n;
|
||||
}
|
||||
const MetaValue* get(const std::string& key) const {
|
||||
auto it = meta_.find(key);
|
||||
return it == meta_.end() ? nullptr : &it->second;
|
||||
}
|
||||
const uint8_t* tensor_data(const TensorInfo& t) const { return base_ + data_start_ + t.offset; }
|
||||
|
||||
private:
|
||||
void open() {
|
||||
#ifdef _WIN32
|
||||
HANDLE h = CreateFileA(path_.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (h == INVALID_HANDLE_VALUE) throw std::runtime_error("cannot open " + path_);
|
||||
LARGE_INTEGER li{};
|
||||
GetFileSizeEx(h, &li);
|
||||
size_ = (uint64_t)li.QuadPart;
|
||||
HANDLE m = CreateFileMappingA(h, nullptr, PAGE_READONLY, 0, 0, nullptr);
|
||||
if (!m) {
|
||||
CloseHandle(h);
|
||||
throw std::runtime_error("CreateFileMapping failed");
|
||||
}
|
||||
base_ = (const uint8_t*)MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0);
|
||||
if (!base_) {
|
||||
CloseHandle(m);
|
||||
CloseHandle(h);
|
||||
throw std::runtime_error("MapViewOfFile failed");
|
||||
}
|
||||
map_ = m;
|
||||
file_ = h;
|
||||
#else
|
||||
int fd = ::open(path_.c_str(), O_RDONLY);
|
||||
if (fd < 0) throw std::runtime_error("cannot open " + path_);
|
||||
fd_ = fd;
|
||||
struct stat st{};
|
||||
if (fstat(fd, &st) != 0) throw std::runtime_error("fstat failed");
|
||||
size_ = (uint64_t)st.st_size;
|
||||
void* p = mmap(nullptr, size_, PROT_READ, MAP_PRIVATE, fd, 0);
|
||||
if (p == MAP_FAILED) throw std::runtime_error("mmap failed");
|
||||
base_ = (const uint8_t*)p;
|
||||
#endif
|
||||
parse();
|
||||
}
|
||||
void close() {
|
||||
#ifdef _WIN32
|
||||
if (base_) UnmapViewOfFile(base_);
|
||||
if (map_) CloseHandle((HANDLE)map_);
|
||||
if (file_) CloseHandle((HANDLE)file_);
|
||||
#else
|
||||
if (base_) munmap((void*)base_, size_);
|
||||
if (fd_ >= 0) ::close(fd_);
|
||||
#endif
|
||||
}
|
||||
|
||||
void parse() {
|
||||
Cursor c(base_, size_);
|
||||
const uint32_t magic = c.read<uint32_t>();
|
||||
if (magic != 0x46554747u) throw std::runtime_error("not a GGUF file (bad magic)");
|
||||
version_ = c.read<uint32_t>();
|
||||
if (version_ != 3)
|
||||
throw std::runtime_error("GGUF v" + std::to_string(version_) + ", this reader handles v3");
|
||||
const uint64_t n_tensors = c.read<uint64_t>();
|
||||
const uint64_t n_kv = c.read<uint64_t>();
|
||||
|
||||
for (uint64_t i = 0; i < n_kv; ++i) {
|
||||
std::string key = c.str();
|
||||
MetaType t = (MetaType)c.read<uint32_t>();
|
||||
meta_.emplace(std::move(key), read_value(c, t));
|
||||
}
|
||||
tensors_.reserve((size_t)n_tensors);
|
||||
// GGUF has no index to arbitrate between two tensors of one name: find() is first-match, so a
|
||||
// duplicate would silently win by position. Refuse the file at open instead, naming both.
|
||||
std::set<std::string> names;
|
||||
for (uint64_t i = 0; i < n_tensors; ++i) {
|
||||
TensorInfo t;
|
||||
t.name = c.str();
|
||||
if (!names.insert(t.name).second)
|
||||
throw std::runtime_error("GGUF: duplicate tensor name '" + t.name + "' in " + path_);
|
||||
const uint32_t nd = c.read<uint32_t>();
|
||||
if (nd == 0 || nd > 4) throw std::runtime_error("GGUF: bad n_dims for " + t.name);
|
||||
t.shape.resize(nd);
|
||||
for (uint32_t d = 0; d < nd; ++d) t.shape[d] = c.read<uint64_t>();
|
||||
t.type = c.read<uint32_t>();
|
||||
t.offset = c.read<uint64_t>();
|
||||
tensors_.push_back(std::move(t));
|
||||
}
|
||||
uint64_t align = 32;
|
||||
if (const MetaValue* a = get("general.alignment"))
|
||||
if (a->u) align = a->u;
|
||||
alignment_ = align;
|
||||
data_start_ = (c.pos() + align - 1) / align * align;
|
||||
if (data_start_ > size_) throw std::runtime_error("GGUF: data section starts past EOF");
|
||||
}
|
||||
|
||||
std::string path_;
|
||||
const uint8_t* base_ = nullptr;
|
||||
uint64_t size_ = 0, data_start_ = 0, alignment_ = 32;
|
||||
uint32_t version_ = 0;
|
||||
#ifdef _WIN32
|
||||
void* file_ = nullptr;
|
||||
void* map_ = nullptr;
|
||||
#else
|
||||
int fd_ = -1;
|
||||
#endif
|
||||
std::vector<TensorInfo> tensors_;
|
||||
std::map<std::string, MetaValue> meta_;
|
||||
};
|
||||
|
||||
// Bytes of a tensor's payload from its shape and block geometry; 0 when the type is unknown, a row is not whole
|
||||
// blocks, or the count overflows.
|
||||
inline uint64_t tensor_payload_bytes(const TensorInfo& t) {
|
||||
int be = 0, bb = 0;
|
||||
if (t.shape.empty() || !block_geometry(t.type, be, bb) || t.shape[0] % (uint64_t) be) return 0;
|
||||
uint64_t elements = 1;
|
||||
for (uint64_t d : t.shape) {
|
||||
if (d == 0 || elements > (std::numeric_limits<uint64_t>::max)() / d) return 0;
|
||||
elements *= d;
|
||||
}
|
||||
const uint64_t blocks = elements / (uint64_t) be;
|
||||
if (blocks > (std::numeric_limits<uint64_t>::max)() / (uint64_t) bb) return 0;
|
||||
return blocks * (uint64_t) bb;
|
||||
}
|
||||
|
||||
// The shards of one model (strata::gguf_split_paths), opened together; tensors are looked up across all of them.
|
||||
// From eddoursul/Strata 8029fa9, with the split-key validation of #255 (gopinath87607) made a property of the
|
||||
// model rather than of one loader: a split GGUF carries the model's metadata (general.architecture and the
|
||||
// qwen4exp keys) in its FIRST shard only, and the later shards just declare split.count / split.no /
|
||||
// split.tensors.count. Unsloth's UD-Q4_K_XL is the extreme case: shard 1 holds the metadata and no tensor at
|
||||
// all, and output.weight, token_embd.weight and the PLE table live in shard 2. So the architecture is checked
|
||||
// on `meta()` and a tensor is read from the shard that holds it.
|
||||
//
|
||||
// Refused at construction: a later shard whose split keys disagree with shard 1's (another model's shard, or a
|
||||
// shard renamed into the family), a split model whose tensor directories do not add up to split.tensors.count,
|
||||
// and a tensor name present in two shards (GGUF has no index to say which one is meant).
|
||||
class GgufModel {
|
||||
public:
|
||||
explicit GgufModel(const std::vector<std::string>& paths) {
|
||||
if (paths.empty()) throw std::runtime_error("GGUF: a model needs at least one shard");
|
||||
for (const auto& p : paths) shards_.push_back(std::make_unique<GgufFile>(p));
|
||||
validate_split();
|
||||
for (size_t i = 0; i < shards_.size(); ++i)
|
||||
for (const auto& t : shards_[i]->tensors()) {
|
||||
const auto ins = index_.emplace(t.name, std::make_pair(i, &t));
|
||||
if (!ins.second)
|
||||
throw std::runtime_error("GGUF: tensor " + t.name + " is in two shards (" +
|
||||
shards_[ins.first->second.first]->path() + " and " +
|
||||
shards_[i]->path() + ")");
|
||||
}
|
||||
}
|
||||
/// Opens every shard of the model that `any_shard` belongs to (throws when one is missing).
|
||||
static GgufModel open(const std::string& any_shard) { return GgufModel(gguf_split_paths(any_shard)); }
|
||||
|
||||
size_t size() const { return shards_.size(); }
|
||||
const GgufFile& shard(size_t i) const { return *shards_[i]; }
|
||||
/// The metadata shard: general.architecture and the model's keys.
|
||||
const GgufFile& meta() const { return *shards_[0]; }
|
||||
/// The tensor named `name` (its shard index in `*shard`), or nullptr.
|
||||
const TensorInfo* find(const std::string& name, size_t* shard = nullptr) const {
|
||||
const auto it = index_.find(name);
|
||||
if (it == index_.end()) return nullptr;
|
||||
if (shard) *shard = it->second.first;
|
||||
return it->second.second;
|
||||
}
|
||||
/// Whether `t` (a tensor of shard `s`) has a known byte count that lies inside its file.
|
||||
bool in_bounds(const TensorInfo& t, size_t s) const {
|
||||
const GgufFile& g = *shards_[s];
|
||||
const uint64_t bytes = tensor_payload_bytes(t);
|
||||
const uint64_t payload = g.file_size() - g.data_start();
|
||||
return bytes != 0 && t.offset <= payload && bytes <= payload - t.offset;
|
||||
}
|
||||
|
||||
private:
|
||||
void validate_split() const {
|
||||
const size_t n = shards_.size();
|
||||
const MetaValue* count0 = shards_[0]->get("split.count");
|
||||
if (n == 1) {
|
||||
if (count0 && count0->u > 1)
|
||||
throw std::runtime_error("GGUF: " + shards_[0]->path() + " is shard 1 of " + std::to_string(count0->u) +
|
||||
", but it was opened as a whole model");
|
||||
return;
|
||||
}
|
||||
if (!shards_[0]->get("general.architecture"))
|
||||
throw std::runtime_error("GGUF: " + shards_[0]->path() + " has no general.architecture; the first shard "
|
||||
"of a split model carries the metadata");
|
||||
const MetaValue* total = shards_[0]->get("split.tensors.count");
|
||||
uint64_t tensors = 0;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const GgufFile& g = *shards_[i];
|
||||
const MetaValue* count = g.get("split.count");
|
||||
const MetaValue* no = g.get("split.no");
|
||||
const MetaValue* tc = g.get("split.tensors.count");
|
||||
if (!count || !no || count->u != n || no->u != i || (total && (!tc || tc->u != total->u)))
|
||||
throw std::runtime_error("GGUF: " + g.path() + " does not declare itself shard " + std::to_string(i + 1) +
|
||||
" of " + std::to_string(n) + " of this model (split.count / split.no / "
|
||||
"split.tensors.count)");
|
||||
tensors += g.tensors().size();
|
||||
}
|
||||
if (total && tensors != total->u)
|
||||
throw std::runtime_error("GGUF: the " + std::to_string(n) + " shards hold " + std::to_string(tensors) +
|
||||
" tensors, but split.tensors.count is " + std::to_string(total->u));
|
||||
}
|
||||
|
||||
std::vector<std::unique_ptr<GgufFile>> shards_;
|
||||
std::map<std::string, std::pair<size_t, const TensorInfo*>> index_;
|
||||
};
|
||||
|
||||
// ---- architecture guard (P1.S2). The engine is specialised to ONE family; anything else must be refused
|
||||
// with a precise error rather than silently mis-run. Two architecture strings pass: `qwen4exp` (Qwen3.8-Flash-Next,
|
||||
// the model the kernels were written for: its six keys are checked against the compiled-in values) and `qwen35moe`
|
||||
// (Qwen3.6-35B-A3B, Phase 2 of docs/PLAN-qwen36-35b-a3b.md: the file is the authority on every size, so its keys
|
||||
// are checked for PRESENCE only, and `strata::core::read_model_geometry` reads them). Passing this guard says the
|
||||
// metadata is readable, not that the engine runs the model: the Qwen3.6 start stops at its own gate afterwards.
|
||||
struct Qwen4ExpGuard {
|
||||
uint32_t block_count = 48, hidden = 2560, experts = 0, experts_used = 0, head_count = 24,
|
||||
head_count_kv = 2; // 0 = presence-only: pruned variants (GSQ-RCO Coder) legitimately ship
|
||||
// fewer experts than the canonical 512; the graph reads the true value
|
||||
};
|
||||
|
||||
inline std::string check_architecture(const GgufFile& g, const Qwen4ExpGuard& want = {}) {
|
||||
const MetaValue* arch = g.get("general.architecture");
|
||||
if (!arch) return "missing general.architecture";
|
||||
struct Req {
|
||||
const char* key;
|
||||
uint64_t want;
|
||||
};
|
||||
if (arch->s == "qwen4exp") {
|
||||
const Req reqs[] = {
|
||||
{"qwen4exp.block_count", want.block_count},
|
||||
{"qwen4exp.embedding_length", want.hidden},
|
||||
{"qwen4exp.expert_count", want.experts},
|
||||
{"qwen4exp.expert_used_count", want.experts_used},
|
||||
{"qwen4exp.attention.head_count", want.head_count},
|
||||
{"qwen4exp.attention.head_count_kv", want.head_count_kv},
|
||||
};
|
||||
for (const auto& r : reqs) {
|
||||
const MetaValue* v = g.get(r.key);
|
||||
if (!v) return std::string("missing ") + r.key;
|
||||
if (r.want && v->u != r.want)
|
||||
return std::string(r.key) + " = " + std::to_string(v->u) + ", expected " + std::to_string(r.want);
|
||||
}
|
||||
return {}; // empty == ok
|
||||
}
|
||||
if (arch->s == "qwen35moe") {
|
||||
// llama.cpp's qwen35moe loader requires these (src/models/qwen35moe.cpp:4-34, llama-model.cpp:1254-1380);
|
||||
// the engine's geometry reader derives everything else from them
|
||||
static const char* const keys[] = {
|
||||
"qwen35moe.block_count", "qwen35moe.embedding_length", "qwen35moe.expert_count",
|
||||
"qwen35moe.expert_used_count", "qwen35moe.attention.head_count", "qwen35moe.attention.head_count_kv",
|
||||
"qwen35moe.attention.key_length", "qwen35moe.full_attention_interval", "qwen35moe.ssm.conv_kernel",
|
||||
"qwen35moe.ssm.state_size", "qwen35moe.ssm.group_count", "qwen35moe.ssm.time_step_rank",
|
||||
"qwen35moe.ssm.inner_size", "qwen35moe.expert_feed_forward_length",
|
||||
};
|
||||
for (const char* k : keys)
|
||||
if (!g.get(k)) return std::string("missing ") + k + " (a qwen35moe file llama.cpp's own loader would refuse)";
|
||||
return {};
|
||||
}
|
||||
return "architecture is '" + arch->s + "', this engine requires 'qwen4exp' (Qwen3.8-Flash-Next) or 'qwen35moe' "
|
||||
"(Qwen3.6-35B-A3B)";
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -1,52 +0,0 @@
|
||||
// include/strata/artifact/gguf_split.hpp - the shards of a split model. Separate from gguf_reader.hpp, which
|
||||
// includes <windows.h>, so any translation unit can resolve a model's shards.
|
||||
//
|
||||
// From eddoursul/Strata 8029fa9 (gguf_split_paths), with one change of contract: upstream's model_shards()
|
||||
// skipped a shard it could not open and returned the rest, so a download that was still running (or a shard
|
||||
// deleted by hand) produced a model with some layers missing and an error much later, or none. A missing shard
|
||||
// is now an error that names it.
|
||||
#pragma once
|
||||
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata {
|
||||
|
||||
// Split models: `<name>-00001-of-0000N.gguf` ... `<name>-0000N-of-0000N.gguf`, as llama.cpp's gguf-split names
|
||||
// them. Given ANY shard's path, the shards in split order (the metadata shard, 00001, first); a file without that
|
||||
// suffix is a model of one shard. Only the five digits of the shard number are rewritten, so the directory and
|
||||
// the stem are the caller's own spelling (a symlinked Hugging Face snapshot keeps its split names). Throws when
|
||||
// a shard is missing.
|
||||
inline std::vector<std::string> gguf_split_paths(const std::string& any) {
|
||||
static const char tag[] = "-of-";
|
||||
const size_t at = any.rfind(tag);
|
||||
// "...-NNNNN-of-MMMMM.gguf": five digits before the tag, five after it, then the extension
|
||||
if (at == std::string::npos || at < 6 || any[at - 6] != '-' || any.size() != at + 4 + 5 + 5 ||
|
||||
any.compare(at + 9, 5, ".gguf") != 0)
|
||||
return {any};
|
||||
int no = 0, n = 0;
|
||||
for (size_t i = 0; i < 5; ++i) {
|
||||
const char a = any[at - 5 + i], b = any[at + 4 + i];
|
||||
if (a < '0' || a > '9' || b < '0' || b > '9') return {any};
|
||||
no = no * 10 + (a - '0');
|
||||
n = n * 10 + (b - '0');
|
||||
}
|
||||
if (n < 1 || no < 1 || no > n) return {any};
|
||||
std::vector<std::string> out;
|
||||
for (int i = 1; i <= n; ++i) {
|
||||
char num[8];
|
||||
std::snprintf(num, sizeof num, "%05d", i);
|
||||
std::string p = any;
|
||||
p.replace(at - 5, 5, num);
|
||||
if (!std::ifstream(p, std::ios::binary))
|
||||
throw std::runtime_error("missing model shard " + p + " (shard " + std::to_string(i) + " of " +
|
||||
std::to_string(n) + "; is the download complete?)");
|
||||
out.push_back(std::move(p));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -1,154 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
// Snapshot-owned host storage. Appending never relocates existing payloads;
|
||||
// only the small segment directory can move. No sharing or copy-on-write is
|
||||
// needed because a parked image and its retained active buffers have one owner.
|
||||
class ConversationBuffer {
|
||||
public:
|
||||
static constexpr size_t segment_bytes = 16 * 1024 * 1024;
|
||||
ConversationBuffer() = default;
|
||||
ConversationBuffer(std::initializer_list<uint8_t> values) {
|
||||
resize(values.size());
|
||||
visit(0, size(), [&](uint8_t* p, size_t n, size_t at) {
|
||||
std::memcpy(p, values.begin() + at, n);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
ConversationBuffer(const ConversationBuffer&) = default;
|
||||
ConversationBuffer& operator=(const ConversationBuffer&) = default;
|
||||
ConversationBuffer(ConversationBuffer&& other) noexcept
|
||||
: segments_(std::move(other.segments_)), size_(std::exchange(other.size_, 0)) {}
|
||||
ConversationBuffer& operator=(ConversationBuffer&& other) noexcept {
|
||||
if (this == &other) return *this;
|
||||
segments_ = std::move(other.segments_);
|
||||
size_ = std::exchange(other.size_, 0);
|
||||
return *this;
|
||||
}
|
||||
|
||||
size_t size() const { return size_; }
|
||||
bool empty() const { return size_ == 0; }
|
||||
size_t bytes() const {
|
||||
size_t n = segments_.capacity() * sizeof(Segment);
|
||||
for (const auto& segment : segments_) n += segment.capacity();
|
||||
return n;
|
||||
}
|
||||
// Includes the old directory while reserve allocates its replacement.
|
||||
// Saturation makes an overflowing estimate fail admission before resize.
|
||||
size_t allocation_peak(size_t n) const {
|
||||
size_t total = bytes();
|
||||
if (n <= size_) return total;
|
||||
const size_t spare = segments_.empty() ? 0 : segments_.back().capacity() - segments_.back().size();
|
||||
const size_t extra = n - size_ - std::min(n - size_, spare);
|
||||
const size_t full = extra / segment_bytes, tail = extra % segment_bytes;
|
||||
if (!add(total, full * segment_bytes)) return SIZE_MAX;
|
||||
if (tail && !add(total, segment_capacity(tail, full ? segment_bytes :
|
||||
segments_.empty() ? 0 : segments_.back().capacity(), size_ != 0))) return SIZE_MAX;
|
||||
size_t count = segments_.size();
|
||||
if (!add(count, full + (tail != 0))) return SIZE_MAX;
|
||||
if (count > segments_.capacity() &&
|
||||
(count > SIZE_MAX / sizeof(Segment) || !add(total, count * sizeof(Segment)))) return SIZE_MAX;
|
||||
return total;
|
||||
}
|
||||
void resize(size_t n, uint8_t value = 0) {
|
||||
if (n > size_) {
|
||||
const bool growing = size_ != 0;
|
||||
const size_t spare = segments_.empty() ? 0 : segments_.back().capacity() - segments_.back().size();
|
||||
const size_t extend = std::min(n - size_, spare);
|
||||
const size_t extra = n - size_ - extend;
|
||||
segments_.reserve(segments_.size() + extra / segment_bytes + (extra % segment_bytes != 0));
|
||||
if (extend) {
|
||||
segments_.back().resize(segments_.back().size() + extend, value);
|
||||
size_ += extend;
|
||||
}
|
||||
while (size_ < n) {
|
||||
const size_t count = std::min(segment_bytes, n - size_);
|
||||
const size_t previous = segments_.empty() ? 0 : segments_.back().capacity();
|
||||
Segment segment;
|
||||
segment.reserve(segment_capacity(count, previous, growing));
|
||||
segment.resize(count, value);
|
||||
segments_.push_back(std::move(segment));
|
||||
size_ += count;
|
||||
}
|
||||
} else {
|
||||
while (!segments_.empty() && size_ - segments_.back().size() >= n) {
|
||||
size_ -= segments_.back().size();
|
||||
segments_.pop_back();
|
||||
}
|
||||
if (size_ > n) segments_.back().resize(segments_.back().size() - (size_ - n));
|
||||
size_ = n;
|
||||
}
|
||||
}
|
||||
void pop_back() { resize(size_ - 1); }
|
||||
|
||||
// fn(pointer, count, absolute_offset); false aborts a transfer immediately.
|
||||
template<class Fn> bool visit(size_t offset, size_t count, Fn fn) {
|
||||
return visit_impl(*this, offset, count, fn);
|
||||
}
|
||||
template<class Fn> bool visit(size_t offset, size_t count, Fn fn) const {
|
||||
return visit_impl(*this, offset, count, fn);
|
||||
}
|
||||
bool read(void* target, size_t offset, size_t count) const {
|
||||
return visit(offset, count, [&](const uint8_t* p, size_t n, size_t at) {
|
||||
std::memcpy(static_cast<uint8_t*>(target) + at - offset, p, n);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
bool operator==(const ConversationBuffer& other) const {
|
||||
if (size_ != other.size_) return false;
|
||||
size_t a = 0, b = 0, x = 0, y = 0;
|
||||
while (a < segments_.size() && b < other.segments_.size()) {
|
||||
const auto& left = segments_[a];
|
||||
const auto& right = other.segments_[b];
|
||||
const size_t n = std::min(left.size() - x, right.size() - y);
|
||||
if (std::memcmp(left.data() + x, right.data() + y, n)) return false;
|
||||
x += n; y += n;
|
||||
if (x == left.size()) { ++a; x = 0; }
|
||||
if (y == right.size()) { ++b; y = 0; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
using Segment = std::vector<uint8_t>;
|
||||
// A fresh capture allocates exactly its payload. Later appends reserve
|
||||
// geometrically growing segments, bounded by 16 MiB. Small chat turns then
|
||||
// extend the final allocation instead of adding one transfer per turn.
|
||||
static size_t segment_capacity(size_t count, size_t previous, bool growing) {
|
||||
if (!growing) return count;
|
||||
return std::max(count, std::min(segment_bytes, std::max<size_t>(65536, std::min(previous, segment_bytes/2)*2)));
|
||||
}
|
||||
static bool add(size_t& n, size_t extra) {
|
||||
if (extra > SIZE_MAX - n) return false;
|
||||
n += extra;
|
||||
return true;
|
||||
}
|
||||
template<class Self, class Fn> static bool visit_impl(Self& self, size_t offset, size_t count, Fn fn) {
|
||||
if (offset > self.size_ || count > self.size_ - offset) return false;
|
||||
size_t begin = 0;
|
||||
for (auto& segment : self.segments_) {
|
||||
if (!count) break;
|
||||
const size_t end = begin + segment.size();
|
||||
if (offset < end) {
|
||||
const size_t n = std::min(count, end - offset);
|
||||
if (!fn(segment.data() + offset - begin, n, offset)) return false;
|
||||
offset += n; count -= n;
|
||||
}
|
||||
begin = end;
|
||||
}
|
||||
return count == 0;
|
||||
}
|
||||
std::vector<Segment> segments_;
|
||||
size_t size_ = 0;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,283 +0,0 @@
|
||||
// CPU-only ownership and matching policy for --serve's parked conversations.
|
||||
// Token equality, image identity, and steering mode are all required for reuse.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/conversation_buffer.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
struct ConversationImageKey {
|
||||
int64_t start = 0;
|
||||
uint64_t hash = 0;
|
||||
bool operator==(const ConversationImageKey&) const = default;
|
||||
};
|
||||
|
||||
struct ConversationCheckpoint {
|
||||
std::vector<int32_t> ids;
|
||||
std::vector<ConversationImageKey> imgs;
|
||||
std::vector<uint8_t> gdn, ple, tails, dead, block_pos;
|
||||
uint64_t used = 0; // upstream root-pinned/LRU checkpoint retention
|
||||
// Ordinary layer-split checkpoints retain each device's running state.
|
||||
// Whole-session parking is currently single-GPU and rejects these parts.
|
||||
std::vector<ConversationCheckpoint> stage_parts;
|
||||
|
||||
size_t bytes() const {
|
||||
size_t n = ids.capacity() * sizeof(int32_t) + imgs.capacity() * sizeof(ConversationImageKey) +
|
||||
gdn.capacity() + ple.capacity() + tails.capacity() + dead.capacity() + block_pos.capacity() +
|
||||
stage_parts.capacity() * sizeof(ConversationCheckpoint);
|
||||
for (const auto& part : stage_parts) n += part.bytes();
|
||||
return n;
|
||||
}
|
||||
};
|
||||
|
||||
// Identity-layout K/V pages and completed indexer rows. For streamed layers the
|
||||
// source is the authoritative host pool, NOT the replaceable VRAM slots.
|
||||
struct ConversationKv {
|
||||
int format = 0;
|
||||
int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0;
|
||||
ConversationBuffer k, v, k_scale, v_scale, pooled;
|
||||
size_t bytes() const {
|
||||
return k.bytes() + v.bytes() + k_scale.bytes() + v_scale.bytes() + pooled.bytes();
|
||||
}
|
||||
};
|
||||
|
||||
struct ConversationKvReuse {
|
||||
std::vector<ConversationKv> kv;
|
||||
// Original image extent for validation, and the earliest subsequent rewrite.
|
||||
int64_t captured_tokens = 0, unchanged_tokens = 0;
|
||||
// With a layer split: the later stages' own retained K/V, one per stage, same extents (empty: none)
|
||||
std::vector<ConversationKvReuse> stages;
|
||||
size_t bytes() const {
|
||||
size_t n = kv.capacity() * sizeof(ConversationKv) + stages.capacity() * sizeof(ConversationKvReuse);
|
||||
for (const auto& layer : kv) n += layer.bytes();
|
||||
for (const auto& s : stages) n += s.bytes();
|
||||
return n;
|
||||
}
|
||||
};
|
||||
|
||||
/// Layer-split parking: each running checkpoint holds the first stage's state and, in `stage_parts`, one part per
|
||||
/// later stage; a parked conversation keeps them in one image per stage. `split` MOVES the checkpoints apart (no
|
||||
/// running state is copied): the complete ones (a part for each of `stages` stages) into `stage0` and `parts[k]`,
|
||||
/// every part carrying the checkpoint's ids / images / LRU stamp, the others aside; `merge` puts them back in their
|
||||
/// original order. merge(split(x)) == x.
|
||||
struct ConversationCheckpointSplit {
|
||||
std::vector<ConversationCheckpoint> stage0;
|
||||
std::vector<std::vector<ConversationCheckpoint>> parts; ///< [stage][checkpoint]
|
||||
std::vector<ConversationCheckpoint> rest; ///< not split (no complete set of stage parts)
|
||||
std::vector<bool> complete; ///< per original position: in stage0/parts or in rest
|
||||
};
|
||||
|
||||
inline ConversationCheckpointSplit conversation_checkpoints_split(std::vector<ConversationCheckpoint>&& checks,
|
||||
size_t stages) {
|
||||
ConversationCheckpointSplit out;
|
||||
out.parts.resize(stages);
|
||||
for (auto& c : checks) {
|
||||
const bool whole = c.stage_parts.size() == stages;
|
||||
out.complete.push_back(whole);
|
||||
if (!whole) { out.rest.push_back(std::move(c)); continue; }
|
||||
for (size_t k = 0; k < stages; ++k) {
|
||||
ConversationCheckpoint part = std::move(c.stage_parts[k]);
|
||||
part.ids = c.ids; part.imgs = c.imgs; part.used = c.used; part.stage_parts.clear();
|
||||
out.parts[k].push_back(std::move(part));
|
||||
}
|
||||
c.stage_parts.clear();
|
||||
out.stage0.push_back(std::move(c));
|
||||
}
|
||||
checks.clear();
|
||||
return out;
|
||||
}
|
||||
|
||||
/// false (and `out` empty) when the parts do not line up: a stage with another number of checkpoints, or a part
|
||||
/// whose ids differ from its checkpoint's.
|
||||
inline bool conversation_checkpoints_merge(ConversationCheckpointSplit&& split, std::vector<ConversationCheckpoint>& out) {
|
||||
out.clear();
|
||||
for (const auto& p : split.parts)
|
||||
if (p.size() != split.stage0.size()) return false;
|
||||
size_t whole = 0, other = 0;
|
||||
for (bool c : split.complete) (c ? whole : other) += 1;
|
||||
if (!split.complete.empty() && (whole != split.stage0.size() || other != split.rest.size())) return false;
|
||||
if (split.complete.empty()) split.complete.assign(split.stage0.size(), true); // a restored image: all whole
|
||||
for (size_t j = 0; j < split.stage0.size(); ++j)
|
||||
for (const auto& p : split.parts)
|
||||
if (p[j].ids != split.stage0[j].ids) return false;
|
||||
size_t w = 0, r = 0;
|
||||
for (bool c : split.complete) {
|
||||
if (!c) { out.push_back(std::move(split.rest[r++])); continue; }
|
||||
ConversationCheckpoint cp = std::move(split.stage0[w]);
|
||||
for (auto& p : split.parts) cp.stage_parts.push_back(std::move(p[w]));
|
||||
++w;
|
||||
out.push_back(std::move(cp));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
struct SavedConversation {
|
||||
// Runtime compatibility only; NOT a model/weights identity or disk schema.
|
||||
std::array<int64_t, 18> geometry{};
|
||||
// The session's layer carve the image was captured from ([0, n_layers) on one GPU); restore requires the same.
|
||||
int64_t layer_lo = 0, layer_hi = 0;
|
||||
ConversationCheckpoint live;
|
||||
std::vector<ConversationCheckpoint> checkpoints;
|
||||
std::vector<ConversationKv> kv; // main layers followed by the draft layer
|
||||
bool cvec = true;
|
||||
// with a layer split, the later stages' own images, one per stage, in stage order
|
||||
std::vector<SavedConversation> stage_images;
|
||||
|
||||
size_t bytes() const {
|
||||
size_t n = live.bytes() + checkpoints.capacity() * sizeof(ConversationCheckpoint) +
|
||||
kv.capacity() * sizeof(ConversationKv);
|
||||
for (const auto& s : stage_images) n += s.bytes();
|
||||
for (const auto& c : checkpoints) n += c.bytes();
|
||||
for (const auto& k : kv) n += k.bytes();
|
||||
return n;
|
||||
}
|
||||
};
|
||||
|
||||
template<class Token>
|
||||
int64_t conversation_prefix(const ConversationCheckpoint& c, const std::vector<Token>& prompt,
|
||||
const std::vector<ConversationImageKey>& images) {
|
||||
const size_t n = c.ids.size();
|
||||
// The last prompt token always starts the next verify window.
|
||||
if (n == 0 || n >= prompt.size() || !std::equal(c.ids.begin(), c.ids.end(), prompt.begin())) return 0;
|
||||
size_t j = 0;
|
||||
for (const auto& image : images) {
|
||||
if (image.start >= (int64_t) n) continue;
|
||||
if (j == c.imgs.size() || !(c.imgs[j++] == image)) return 0;
|
||||
}
|
||||
if (j != c.imgs.size()) return 0;
|
||||
return (int64_t) n;
|
||||
}
|
||||
|
||||
class ConversationCache {
|
||||
public:
|
||||
struct Match {
|
||||
size_t index = 0;
|
||||
int64_t tokens = 0;
|
||||
bool live = false;
|
||||
};
|
||||
|
||||
ConversationCache(size_t budget, size_t slots) : budget_(budget), slots_(slots) {}
|
||||
bool enabled() const { return budget_ != 0 && slots_ != 0; }
|
||||
size_t bytes() const { return bytes_ + reuse_.bytes(); }
|
||||
size_t size() const { return entries_.size(); }
|
||||
size_t evictions() const { return evictions_; }
|
||||
|
||||
// Retain only the restored K/V buffers, not duplicate running checkpoints.
|
||||
// This optimization never evicts a parked conversation to make itself fit.
|
||||
// `stage_kv`: with a layer split, the later stages' restored K/V (one per stage), retained with the first's.
|
||||
void retain(std::vector<ConversationKv>&& kv, int64_t tokens,
|
||||
std::vector<std::vector<ConversationKv>>&& stage_kv = {}) {
|
||||
reuse_ = {};
|
||||
ConversationKvReuse candidate{std::move(kv), tokens, tokens, {}};
|
||||
for (auto& k : stage_kv) candidate.stages.push_back(ConversationKvReuse{std::move(k), tokens, tokens, {}});
|
||||
if (enabled() && candidate.bytes() <= budget_ - bytes_) reuse_ = std::move(candidate);
|
||||
}
|
||||
void limit_reuse(int64_t first_dirty) {
|
||||
reuse_.unchanged_tokens = std::min(reuse_.unchanged_tokens, first_dirty);
|
||||
for (auto& s : reuse_.stages) s.unchanged_tokens = std::min(s.unchanged_tokens, first_dirty);
|
||||
if (reuse_.unchanged_tokens <= 0) reuse_ = {};
|
||||
}
|
||||
ConversationKvReuse take_reuse() { return std::exchange(reuse_, {}); }
|
||||
size_t retained_bytes() const { return reuse_.bytes(); }
|
||||
bool can_fit(size_t incoming, size_t held = 0) const {
|
||||
return enabled() && held <= budget_ && incoming <= budget_ - held &&
|
||||
entries_.size() < slots_ && bytes() <= budget_ - held - incoming;
|
||||
}
|
||||
|
||||
template<class Token>
|
||||
Match best(const std::vector<Token>& prompt, const std::vector<ConversationImageKey>& images, bool cvec) const {
|
||||
Match best;
|
||||
// Ties prefer the most recently parked branch. The caller prefers its
|
||||
// already-active state when that offers the same prefix length.
|
||||
for (size_t i = entries_.size(); i-- > 0;) {
|
||||
const auto& e = entries_[i];
|
||||
if (e.cvec != cvec) continue;
|
||||
auto consider = [&](const ConversationCheckpoint& c, bool live) {
|
||||
const int64_t n = conversation_prefix(c, prompt, images);
|
||||
if (n > best.tokens) best = {i, n, live};
|
||||
};
|
||||
consider(e.live, true);
|
||||
for (const auto& c : e.checkpoints) consider(c, false);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
SavedConversation take(size_t index) {
|
||||
SavedConversation out = std::move(entries_.at(index));
|
||||
bytes_ -= out.bytes();
|
||||
entries_.erase(entries_.begin() + (std::ptrdiff_t) index);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Reserve before allocating a snapshot. held is an incoming image removed
|
||||
// with take() but still alive during the exchange; count it against RAM too.
|
||||
bool make_room(size_t incoming, size_t held = 0) {
|
||||
if (!enabled() || held > budget_ || incoming > budget_ - held) return false;
|
||||
if (bytes() > budget_ - held - incoming) reuse_ = {};
|
||||
while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) {
|
||||
bytes_ -= entries_.front().bytes();
|
||||
entries_.pop_front();
|
||||
++evictions_;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// #342: drop the parked entries an outgoing conversation (its live tokens and checkpoint chain) supersedes:
|
||||
// the same conversation a turn back, whose DEEPEST checkpoint the outgoing chain still holds, so all it adds
|
||||
// is the tail the client rewrote (the reply as it was generated, before the next request re-rendered it) and
|
||||
// checkpoints older than that one. A subagent's successive turns parked one such copy each, and make_room's
|
||||
// oldest-first eviction then pushed the parent conversation out after `slots` turns. An entry without
|
||||
// checkpoints, or whose deepest checkpoint the outgoing chain does not hold (another conversation that only
|
||||
// shares the system prompt's root with it), is kept. Returns how many were dropped.
|
||||
size_t drop_superseded(const std::vector<int32_t>& ids, const std::vector<ConversationImageKey>& images,
|
||||
const std::vector<ConversationCheckpoint>& checkpoints, bool cvec) {
|
||||
auto held = [&](const ConversationCheckpoint& c) {
|
||||
if (c.ids == ids && c.imgs == images) return true;
|
||||
for (const auto& k : checkpoints)
|
||||
if (k.ids == c.ids && k.imgs == c.imgs) return true;
|
||||
return false;
|
||||
};
|
||||
size_t dropped = 0;
|
||||
for (size_t i = 0; i < entries_.size();) {
|
||||
const auto& e = entries_[i];
|
||||
const ConversationCheckpoint* deepest = nullptr;
|
||||
for (const auto& c : e.checkpoints)
|
||||
if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c;
|
||||
if (e.cvec == cvec && deepest && !deepest->ids.empty() && held(*deepest)) {
|
||||
bytes_ -= e.bytes();
|
||||
entries_.erase(entries_.begin() + (std::ptrdiff_t) i);
|
||||
++dropped;
|
||||
continue;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
superseded_ += dropped;
|
||||
return dropped;
|
||||
}
|
||||
size_t superseded() const { return superseded_; }
|
||||
|
||||
bool put(SavedConversation&& image, size_t held = 0) {
|
||||
const size_t n = image.bytes();
|
||||
if (!enabled() || held > budget_ || n > budget_ - held) return false; // make_room's refusal, first
|
||||
drop_superseded(image.live.ids, image.live.imgs, image.checkpoints, image.cvec);
|
||||
if (!make_room(n, held)) return false;
|
||||
entries_.push_back(std::move(image));
|
||||
bytes_ += n;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0, superseded_ = 0;
|
||||
std::deque<SavedConversation> entries_; // least recently active first
|
||||
ConversationKvReuse reuse_;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,19 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <istream>
|
||||
#include <optional>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
// Host physical memory, not swap/commit or a container/job memory reservation.
|
||||
// Unknown telemetry is deliberately distinct from a measured zero.
|
||||
std::optional<uint64_t> conversation_available_memory();
|
||||
std::optional<uint64_t> conversation_mem_available(std::istream& meminfo);
|
||||
|
||||
inline bool conversation_memory_admit(std::optional<uint64_t> available,
|
||||
uint64_t allocation, uint64_t floor) {
|
||||
return available && *available >= floor && allocation <= *available - floor;
|
||||
}
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,96 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/conversation_cache.hpp"
|
||||
#include "strata/core/layer.hpp"
|
||||
#include "strata/core/session.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
// Caller synchronizes the device before saving, and after restoring all layers.
|
||||
// include_index is false for the draft layer (its attention has no indexer).
|
||||
size_t conversation_kv_bytes(const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index);
|
||||
// A nonzero unchanged_tokens is valid only for storage retained from an image
|
||||
// actually restored into this session, bounded by every subsequent rewrite.
|
||||
// Equal token IDs alone do not establish that its K/V bytes are unchanged.
|
||||
bool conversation_kv_save(ConversationKv& image, const QsaState& state, const ModelGeometry& g,
|
||||
int64_t upto, bool include_index, std::string& error,
|
||||
int64_t unchanged_tokens = 0, size_t* reused_bytes = nullptr);
|
||||
bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& state, const ModelGeometry& g,
|
||||
int64_t upto, bool include_index, size_t& bytes, std::string& error);
|
||||
// No CUDA calls or destination writes. Used for whole-session prevalidation.
|
||||
bool conversation_kv_validate(const ConversationKv& image, const QsaState& state, const ModelGeometry& g,
|
||||
int64_t upto, bool include_index, std::string& error);
|
||||
bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, const ModelGeometry& g,
|
||||
int64_t upto, bool include_index, std::string& error);
|
||||
// Diagnostic read-back after a synchronized restore. Uses 64 KiB of stack
|
||||
// workspace, compares authoritative bytes and resident draft-ring pages, and
|
||||
// fingerprints the authoritative payload only. Never changes model state.
|
||||
bool conversation_kv_verify(const ConversationKv& image, const QsaState& state, const ModelGeometry& g,
|
||||
int64_t upto, bool include_index, uint64_t& fingerprint, std::string& error);
|
||||
|
||||
struct ConversationStateSizes {
|
||||
size_t gdn = 0, ple = 0, tail = 0, dead = 0, block_pos = 0;
|
||||
};
|
||||
/// Whole-model sizes: `gdn` covers every GDN layer, the indexer sizes are per QSA layer.
|
||||
bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& sizes, std::string& error);
|
||||
/// The same for one session's layer carve (#216): `gdn` covers its `gdn_alloc` rows; the per-QSA-layer sizes
|
||||
/// apply to each owned state [qsa_ord0, qsa_ord0 + qsa_alloc). Rejects an inconsistent carve. Checkpoints,
|
||||
/// snapshots and their validation all use this: a session saves and restores only the state it owns.
|
||||
bool conversation_session_sizes(const ModelGeometry& g, const SessionState& session, ConversationStateSizes& sizes,
|
||||
std::string& error);
|
||||
bool conversation_checkpoint_validate(const ConversationCheckpoint& checkpoint, const SessionState& session,
|
||||
const ModelGeometry& g, std::string& error);
|
||||
bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const SessionState& session,
|
||||
const ModelGeometry& g, std::string& error);
|
||||
bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session,
|
||||
const ModelGeometry& g, std::string& error);
|
||||
|
||||
struct ConversationView {
|
||||
const std::vector<int32_t>& ids;
|
||||
const std::vector<ConversationImageKey>& images;
|
||||
const std::vector<ConversationCheckpoint>& checkpoints;
|
||||
bool cvec;
|
||||
};
|
||||
bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session,
|
||||
const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error);
|
||||
bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,
|
||||
const SessionState& session, const ModelGeometry& g,
|
||||
const QsaState& draft, size_t& bytes, std::string& error);
|
||||
// The capture estimate includes retained capacity and transient segment directories;
|
||||
// only estimate - reuse.bytes() requires additional physical RAM. Capture consumes
|
||||
// the uniquely owned reusable buffers, including on failure.
|
||||
// Caller admits the estimate before invoking capture. Allocation failures propagate
|
||||
// to the RAM policy; the active session is never modified by capture.
|
||||
bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view,
|
||||
const SessionState& session, const ModelGeometry& g,
|
||||
const QsaState& draft, std::string& error,
|
||||
ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr);
|
||||
bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session,
|
||||
const ModelGeometry& g, const QsaState& draft, std::string& error);
|
||||
enum class ConversationRestore { restored, invalid, transfer_failed };
|
||||
// Invalid images are rejected before any CUDA call/write. Transfer failure may
|
||||
// leave partial state: caller MUST NOT continue inference from that session.
|
||||
ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session,
|
||||
const ModelGeometry& g, const QsaState& draft,
|
||||
std::string& error);
|
||||
|
||||
// The same with `draft == nullptr`: an image WITHOUT the draft layer's K/V (kv holds the session's own QSA layers
|
||||
// only). A layer split's later stages park this way; the draft ring is saved once, with the first stage's image.
|
||||
// An image is validated and restored with the same kind of call it was saved with (a K/V layer count mismatch is
|
||||
// rejected as invalid).
|
||||
bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session, const ModelGeometry& g,
|
||||
const QsaState* draft, size_t& bytes, std::string& error);
|
||||
bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,
|
||||
const SessionState& session, const ModelGeometry& g, const QsaState* draft,
|
||||
size_t& bytes, std::string& error);
|
||||
bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& session,
|
||||
const ModelGeometry& g, const QsaState* draft, std::string& error,
|
||||
ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr);
|
||||
bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session,
|
||||
const ModelGeometry& g, const QsaState* draft, std::string& error);
|
||||
ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session,
|
||||
const ModelGeometry& g, const QsaState* draft, std::string& error);
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,90 +0,0 @@
|
||||
// include/strata/core/coupled_draft.hpp - COUPLED DRAFT SAMPLING (STRATA_SPEC_COUPLED=1, off by default).
|
||||
//
|
||||
// Under sampling the verify window samples row t of a window at position pos0 as Philox(seed, pos0 + t) over the
|
||||
// sampler chain (penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick; verify.cpp run(),
|
||||
// sampler.cu), and a draft is kept only when it EQUALS that row's pick. The output is therefore a function of the
|
||||
// seed alone, whatever the drafts are: drafts only decide how many tokens a window yields.
|
||||
//
|
||||
// The MTP draft layer used to propose its ARGMAX. In coupled mode it SAMPLES instead, with the target's own chain
|
||||
// (the request's top_k / top_p / min_p / temperature and penalties over the same history) and the SAME uniform the
|
||||
// target will draw for the row that verifies the draft. When the draft's distribution is close to the target's,
|
||||
// the two inverse-CDF picks from one uniform agree far more often than an argmax agrees with a sample; the target's
|
||||
// pick - and so the text - does not change, because verification is still exact-match against the target's sample.
|
||||
//
|
||||
// THE COUNTER ARITHMETIC (all positions are sequence indices; a window's row t holds the token at pos0 + t and its
|
||||
// pick is the token at pos0 + t + 1, drawn with counter pos0 + t):
|
||||
// * MTP cell c pairs the main model's residual at position c with the token at c + 1 and predicts the token at
|
||||
// c + 2 (mtp.hpp).
|
||||
// * After a window at p with a drafts accepted, the next window starts at p' = p + a + 1 (its row 0 is the token
|
||||
// the window picked at row a). Chain step j (j = 0 ..) runs at cell p + a + j and predicts the token at
|
||||
// p + a + j + 2 = p' + j + 1: row j + 1 of the next window, VERIFIED BY ROW j's pick, counter p' + j.
|
||||
// * So a draft made at cell c is verified with counter c + 1 - whatever the window size T, the accepted count, a
|
||||
// suffix-drafter window in between (its drafts are then simply not used), or `draft_first` (cell p - 1, a = 0 for
|
||||
// a window at p). The kernel reads c from the step record the host already stages for the cell (device memory,
|
||||
// so the captured graphs replay with each round's own counter), and the seed and chain from a device copy of the
|
||||
// request's SamplerParams, refreshed at the start of every round graph.
|
||||
//
|
||||
// THE PENALTY HISTORY. The verify row j of the next window counts penalties over penalty_rows(consumed', window')
|
||||
// row j: the last h of (consumed', x', drafts 0 .. j-1), where consumed' is what the session holds after the commit
|
||||
// and x' the window's pick at row a. The drafter keeps a device RING of kCoupledHistCap + max_t slots: the host
|
||||
// stages the base (the last h of consumed' + x', -1 padded in front) in [cap - h, cap) before the round, and draft j
|
||||
// writes its token to cap + j - so draft j's window is [cap + j - h, cap + j), exactly the row the target will use.
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/sampler.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#if defined(__CUDACC__) || defined(__HIPCC__)
|
||||
#define STRATA_COUPLED_HD __host__ __device__
|
||||
#else
|
||||
#define STRATA_COUPLED_HD
|
||||
#endif
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// The longest penalty window the coupled drafter mirrors (serve's kPenaltyWindowCap).
|
||||
inline constexpr int kCoupledHistCap = 4096;
|
||||
|
||||
inline bool& coupled_draft_state() {
|
||||
static bool on = [] {
|
||||
const char* e = std::getenv("STRATA_SPEC_COUPLED");
|
||||
return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
/// Whether coupled draft sampling is enabled (via STRATA_SPEC_COUPLED=1 or --coupled-draft CLI flag).
|
||||
inline bool coupled_draft_env() {
|
||||
return coupled_draft_state();
|
||||
}
|
||||
|
||||
inline void set_coupled_draft(bool on) {
|
||||
coupled_draft_state() = on;
|
||||
}
|
||||
|
||||
/// The MTP cell of chain step j after a window at `p` with `a` drafts accepted (draft() runs step j there).
|
||||
STRATA_COUPLED_HD inline int64_t coupled_draft_cell(int64_t p, int a, int j) { return p + a + j; }
|
||||
|
||||
/// The Philox counter the verify window will draw for the row that checks the draft made at MTP cell `cell`.
|
||||
STRATA_COUPLED_HD inline uint64_t coupled_draft_counter(int64_t cell) { return (uint64_t) (cell + 1); }
|
||||
|
||||
/// The penalty window the draft layer and the target use: min(penalty_last_n, cap), 0 when penalties are off.
|
||||
STRATA_COUPLED_HD inline int coupled_hist_len(int penalty_last_n, int cap) {
|
||||
return penalty_last_n <= 0 ? 0 : (penalty_last_n < cap ? penalty_last_n : cap);
|
||||
}
|
||||
|
||||
/// Where draft j's penalty window starts in the ring (base in [cap - h, cap), draft i at cap + i).
|
||||
STRATA_COUPLED_HD inline int coupled_hist_start(int cap, int j, int h) { return cap + j - h; }
|
||||
|
||||
/// The ring's base on the host: the last `h` tokens of (tail[0..n_tail), next), -1 padded in front, into
|
||||
/// out[0..h) - row 0 of `penalty_rows` for the one-token window [next].
|
||||
inline void coupled_hist_base(const int32_t* tail, int64_t n_tail, int32_t next, int h, int32_t* out) {
|
||||
if (h <= 0) return;
|
||||
strata::kernels::penalty_rows(tail, n_tail, &next, 1, h, out);
|
||||
}
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,95 +0,0 @@
|
||||
// include/strata/core/device.hpp - P2.S1: the device arena and the runtime's device facts.
|
||||
//
|
||||
// `DeviceArena` is ONE cudaMalloc per planner region with bump sub-allocation below it and no frees. That is
|
||||
// not a simplification for the first version: the memory plan from P1.S9 is fixed at startup, so the set of
|
||||
// regions and their sizes is known before anything is allocated, and an allocator that can free would be
|
||||
// solving a problem the engine does not have while adding fragmentation and failure modes it does.
|
||||
//
|
||||
// The reason to get this in early is that the VRAM budget is the binding constraint of the whole design
|
||||
// (5.95 GB pooled between KV and the expert cache, 33.97 GB of experts in DRAM). A runtime that discovers at
|
||||
// token 4000 that it has overcommitted has already lost; the plan is printed against `cudaMemGetInfo` at
|
||||
// startup so the discrepancy is visible immediately.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
struct DeviceInfo {
|
||||
int ordinal = -1;
|
||||
std::string name;
|
||||
int cc_major = 0, cc_minor = 0;
|
||||
uint64_t total_bytes = 0; // as reported by cudaMemGetInfo at query time
|
||||
uint64_t free_bytes = 0;
|
||||
int driver_version = 0, runtime_version = 0;
|
||||
int multi_processor_count = 0;
|
||||
std::string arch; // HIP: gcnArchName without its feature suffix ("gfx1201"); empty on CUDA
|
||||
};
|
||||
|
||||
// HIP builds: whether GPU `ordinal` can run this binary - its architecture must be one the binary was COMPILED
|
||||
// for (STRATA_HIP_ARCHS, set by cmake/hip_backend.cmake) and it must run wave32. "" when it can (or when there
|
||||
// is no such device: the caller's own device errors apply), else the reason in a sentence. A binary carried to
|
||||
// another card would otherwise fail later with "invalid device function". CUDA builds: always "".
|
||||
std::string gpu_arch_problem(int ordinal);
|
||||
|
||||
// The GPU architectures this binary was compiled for ("gfx1100,gfx1201"); "" on CUDA builds.
|
||||
const char* compiled_gpu_archs();
|
||||
|
||||
// How many devices the runtime enumerates, numbered as HIP_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES number them; 0 when
|
||||
// there is none (or no usable runtime). `device_info` throws on a card this binary cannot run, so a caller that LISTS
|
||||
// every card - the ones it has no code for included (`strata-device --list-devices`) - counts them with this first.
|
||||
int device_count();
|
||||
|
||||
// One line per device for `strata-device --list-devices`, without the arch check that `device_info` applies:
|
||||
// "arch gfx1201, 15.9 GiB" (HIP) or "compute capability 12.0, 11.9 GiB" (CUDA), plus the device's name. false when
|
||||
// the runtime cannot describe it.
|
||||
bool device_summary(int ordinal, std::string& name, std::string& detail);
|
||||
|
||||
// Throws when there is no CUDA device. The engine targets sm_120 specifically and must say so rather than
|
||||
// run slowly on something else: `CMakeLists.txt` already refuses to COMPILE for another architecture, and
|
||||
// this is the matching check at run time (a binary can be carried to a different machine).
|
||||
DeviceInfo device_info(int ordinal = 0);
|
||||
|
||||
/// "" when this build has device code for the current device, else CUDA's error: a build for other GPUs would
|
||||
/// otherwise fail at its first kernel launch, with nothing that names the cause.
|
||||
std::string device_code_error();
|
||||
|
||||
class CudaError : public std::runtime_error {
|
||||
public:
|
||||
CudaError(const std::string& what, int code) : std::runtime_error(what), code_(code) {}
|
||||
int code() const { return code_; }
|
||||
|
||||
private:
|
||||
int code_;
|
||||
};
|
||||
|
||||
// One cudaMalloc, bump-allocated below. `poison` fills new allocations with a NaN-ish pattern in a debug
|
||||
// build so that reading uninitialised VRAM gives a NaN rather than a plausible number - the same reasoning as
|
||||
// the harness work in Phase 1: a wrong value that looks right is the expensive kind.
|
||||
class DeviceArena {
|
||||
public:
|
||||
explicit DeviceArena(uint64_t bytes, int ordinal = 0, bool poison = false);
|
||||
~DeviceArena();
|
||||
DeviceArena(const DeviceArena&) = delete;
|
||||
DeviceArena& operator=(const DeviceArena&) = delete;
|
||||
|
||||
// `align` must be a power of two; 256 keeps every sub-allocation at a sector boundary.
|
||||
void* alloc(uint64_t bytes, uint64_t align = 256);
|
||||
|
||||
uint64_t capacity() const { return capacity_; }
|
||||
uint64_t used() const { return used_; }
|
||||
uint64_t peak() const { return used_; } // no frees, so used IS the peak
|
||||
int ordinal() const { return ordinal_; }
|
||||
void* base() const { return base_; }
|
||||
|
||||
private:
|
||||
void* base_ = nullptr;
|
||||
uint64_t capacity_ = 0, used_ = 0;
|
||||
int ordinal_ = 0;
|
||||
bool poison_ = false;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,36 +0,0 @@
|
||||
// strata/core/emulate.hpp - STRATA_EMULATE_CC: another GPU generation's code paths, run on this card (tests only).
|
||||
//
|
||||
// A build whose device code is PTX for an older architecture (CMAKE_CUDA_ARCHITECTURES=86-virtual) runs on a newer
|
||||
// card through the driver's JIT, and every kernel then sees __CUDA_ARCH__ = 860. What the host decides from the
|
||||
// device must agree with that, or it picks paths and shared-memory sizes the device code was not built for:
|
||||
// STRATA_EMULATE_CC=75|80|86|89 makes each such query (compute capability, shared memory per block) answer as that
|
||||
// card would. Speed under it says nothing about the real card; results do - the kernels are the real card's.
|
||||
#pragma once
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace strata {
|
||||
|
||||
/// the emulated compute capability as 10 * major + minor, or 0 (off)
|
||||
inline int emulated_cc() {
|
||||
static const int cc = [] {
|
||||
const char* e = std::getenv("STRATA_EMULATE_CC");
|
||||
const int v = e ? std::atoi(e) : 0;
|
||||
return v >= 75 && v < 120 ? v : 0;
|
||||
}();
|
||||
return cc;
|
||||
}
|
||||
inline int cc_major_of(int real_major) { return emulated_cc() ? emulated_cc() / 10 : real_major; }
|
||||
inline int cc_minor_of(int real_minor) { return emulated_cc() ? emulated_cc() % 10 : real_minor; }
|
||||
/// cudaDevAttrMaxSharedMemoryPerBlockOptin as the emulated card reports it: 64 KB on Turing, 163 KB on the A100,
|
||||
/// 99 KB on the other Ampere and Ada cards
|
||||
inline int smem_optin_of(int real) {
|
||||
switch (emulated_cc()) {
|
||||
case 0: return real;
|
||||
case 75: return 65536;
|
||||
case 80: return 166912;
|
||||
default: return real < 101376 ? real : 101376;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -1,227 +0,0 @@
|
||||
// include/strata/core/expert_cache.hpp - R4: the VRAM-resident expert tier.
|
||||
//
|
||||
// **WHY THIS EXISTS, IN ONE PARAGRAPH.** The CPU expert pool is the engine's largest single cost: measured,
|
||||
// **663.6 MB of expert bytes per token at ~40 GB/s = 16.2 ms**, on a token of ~53 ms, and `test_expert_pool`
|
||||
// says the pipeline hides **1.055 ms of 19.035** - the CPU work is 96% exposed because the residual chain is
|
||||
// strictly serial. The only way past it is to stop reading those bytes: put some of the 48 x 512 experts in
|
||||
// VRAM and let the GPU compute them, so the CPU reads only the misses.
|
||||
//
|
||||
// **THE DESIGN IS SIZED AGAINST MEASUREMENTS, NOT AGAINST THE PLAN'S ASSUMPTIONS.**
|
||||
//
|
||||
// * `h_expert` at 4,105 slots, **ten-fold leave-one-out: 0.6447 [0.6110, 0.6750]** (`tools/routing_kfold.py`).
|
||||
// The 0.6573 the README published is in-sample and 0.4720 measured a single-prompt CORPUS, not the metric.
|
||||
// * VRAM, measured on a live run rather than at startup: **6414 MiB free** with the engine at steady state,
|
||||
// against **5413 MiB** for 4,105 slots. It fits, with ~1 GB spare. `strata-device`'s planner agrees and says
|
||||
// FITS, but the planner runs before the dense arena exists, so the live figure is the one that counts.
|
||||
// * `h_layer` held-out is **0.0456** - only 4.6% of (layer, token) pairs have all ten experts resident - so
|
||||
// this cannot be a per-layer grouped kernel and the three-way split is not an optimisation.
|
||||
//
|
||||
// **WHAT THIS FILE IS.** The SLOT STORAGE and the RESIDENCY TABLE: it allocates the VRAM, fills it from the host
|
||||
// arena, and answers `(layer, expert) -> slot or -1`. It computes nothing itself: the GPU computes the experts it
|
||||
// holds in the verify window's grouped kernels and the prompt path (the hit/miss split), and the CPU pool the rest.
|
||||
// (Written when nothing consumed the slots yet and `--expert-cache` defaulted to 0; setup's configs use `auto`.)
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// Where one expert's VRAM lives, or -1. `int32_t` and not a bool because the slot index is what the kernel
|
||||
/// needs, and a table that has to be re-derived from a bitmask is a table that will be re-derived differently
|
||||
/// in the two places that use it.
|
||||
inline constexpr int32_t kNotResident = -1;
|
||||
|
||||
/// **THE STATIC RESIDENCY PLAN, READ BACK FROM THE FILE `tools/make_profile.py` WROTE.**
|
||||
///
|
||||
/// `profile.bin` is `STRP`, then `version, n_layers, n_expert, slots, n_ranked`, then `n_ranked` `(layer,
|
||||
/// expert)` pairs ranked by descending routing frequency, then a `n_layers x n_expert` frequency table.
|
||||
///
|
||||
/// **WHY A PROFILE AND NOT THE COMPULSORY-MISS POLICY THIS ENGINE ALREADY HAD.** Compulsory-miss fills with
|
||||
/// the first `S` DISTINCT experts the run happens to route, which on this workload is whatever the prompt
|
||||
/// touched first - it measured `h = 0.4864`. A profile ranked by frequency over a whole trace is what the
|
||||
/// plan's `0.6447` refers to, and the CPU's half of the drain is linear in `h`, so the gap is worth about
|
||||
/// 4 ms of drain. The point of reading it from a file is that a profile built on ONE prompt can be scored on
|
||||
/// ANOTHER, which is the only way to know whether it transfers.
|
||||
///
|
||||
/// The frequency table is not returned: it is the profile's own working, and the engine measures `h` by
|
||||
/// running rather than by re-deriving what the file claims.
|
||||
bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert,
|
||||
std::vector<std::pair<int32_t, int32_t>>& ranked, int64_t& slots, std::string& err);
|
||||
|
||||
/// #477 (--expert-profile-save): what the adaptive tier learned, as a profile ranking EVERY (layer, expert) pair -
|
||||
/// the experts resident in VRAM now first (where the swaps left the cache), then the rest; within each, by `heat`
|
||||
/// (the routing the adaptive tier counted since the start, descending), then by `prior` (the profile the engine
|
||||
/// started from: an expert this run never routed keeps its old place), then by index. A start from it begins
|
||||
/// where this one ended; one with more slots adds the hottest of the rest, one with fewer keeps the hottest.
|
||||
/// `resident` and `heat`: n_layers x n_expert entries (`heat` may be empty: no counts, the prior decides).
|
||||
std::vector<std::pair<int32_t, int32_t>> rank_learned_profile(int64_t n_layers, int64_t n_expert,
|
||||
const std::vector<uint8_t>& resident,
|
||||
const std::vector<double>& heat,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& prior);
|
||||
|
||||
/// #477: writes `ranked` in tools/make_profile.py's format, byte for byte: `STRP`, `1, n_layers, n_expert,
|
||||
/// n_ranked, n_ranked` (uint32), the pairs (uint16 layer, uint16 expert), then the n_layers x n_expert int32 table
|
||||
/// of each pair's rank (-1: not ranked). Atomically: a `<path>.tmp` beside it, renamed over `path` once complete,
|
||||
/// so a reader (the next start) never sees half a file. False with `err` when it could not be written.
|
||||
bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& ranked, std::string& err);
|
||||
|
||||
class ExpertCache {
|
||||
public:
|
||||
ExpertCache() = default;
|
||||
~ExpertCache();
|
||||
ExpertCache(const ExpertCache&) = delete;
|
||||
ExpertCache& operator=(const ExpertCache&) = delete;
|
||||
|
||||
/// Allocates `n_slots * blob_bytes` of DEVICE memory and a `n_layers * n_expert` residency table, and
|
||||
/// **CHECKS THE ALLOCATION AGAINST WHAT THE CARD ACTUALLY HAS** rather than assuming the planner was right.
|
||||
/// A cache that silently allocates less than it was asked for would report a hit rate for slots it does
|
||||
/// not have, which is the shape of error this project keeps paying for.
|
||||
bool open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int64_t blob_bytes, std::string& err);
|
||||
/// Plan v0.3 P6: slots of the given sizes, back to back (a native pack's blobs differ per layer, and a
|
||||
/// profile-filled tier never moves an expert to another layer's slot, so each slot keeps its first size).
|
||||
bool open_sized(const std::vector<int64_t>& slot_bytes, int64_t n_layers, int64_t n_expert, std::string& err);
|
||||
/// Byte offset of each slot in the arena (null for uniform slots).
|
||||
const uint64_t* slot_offsets() const { return off_.empty() ? nullptr : off_.data(); }
|
||||
void close();
|
||||
|
||||
bool valid() const { return base_ != nullptr; }
|
||||
/// The slots usable now: all of them, unless `shrink` gave the tail's VRAM back (#533) - then the ones wholly
|
||||
/// inside the VRAM still backed, always a prefix. The prompt path's loan (the last slots) and every report
|
||||
/// follow this; `full_slots()` is what `open` allocated.
|
||||
int64_t slots() const { return live_slots_; }
|
||||
int64_t full_slots() const { return slots_; }
|
||||
/// Slots actually claimed. Not the same as `slots()` - the cache does not evict, so a run that routes
|
||||
/// fewer distinct experts than there are slots leaves the rest empty.
|
||||
int64_t resident() const { return per_layer_ ? admitted_ : next_free_; }
|
||||
/// The bytes of `slots()` (all of the arena unless shrunk); `full_bytes()`: of every slot.
|
||||
int64_t bytes() const { return slot_end(live_slots_); }
|
||||
int64_t full_bytes() const { return slot_end(slots_); }
|
||||
double gib() const { return (double) bytes() / 1073741824.0; }
|
||||
|
||||
/// **#533: HOT VRAM RESIZE, OPT-IN (--vram-elastic).** With a segment size set before `open`/`open_sized`, the
|
||||
/// arena is one reserved address range backed by physical segments of that size (CUDA virtual memory
|
||||
/// management) instead of one cudaMalloc, so `shrink` can give the tail's VRAM back to the driver - for another
|
||||
/// program - and `grow` can take it again, while every slot keeps its address (the captured graphs, the verify
|
||||
/// plan's pointers and the prompt path's loan all hold addresses into it). 0 (the default): one cudaMalloc, as
|
||||
/// always. CUDA only: a HIP build refuses it at open. The slots past `slots()` after a shrink must hold no
|
||||
/// resident expert and no loan: the CALLER evicts them first (they become CPU misses).
|
||||
void set_segment_bytes(int64_t seg_bytes) { seg_req_ = seg_bytes > 0 ? seg_bytes : 0; }
|
||||
bool segmented() const { return !segs_.empty(); }
|
||||
int64_t segment_bytes() const { return seg_; }
|
||||
/// Bytes of the arena backed by VRAM now (a whole number of segments; the arena when not segmented).
|
||||
int64_t mapped_bytes() const;
|
||||
/// Unmaps every segment past the first `keep_bytes` (rounded UP to a segment boundary): `slots()` becomes the
|
||||
/// slots wholly inside what stays. Waits for the device first. False with `err` when not segmented or a driver
|
||||
/// call failed.
|
||||
bool shrink(int64_t keep_bytes, std::string& err);
|
||||
/// Maps segments again up to `want_bytes` (rounded DOWN to a segment, at most the arena; the last, shorter
|
||||
/// segment only when `want_bytes` covers the arena). Stops at the first segment the driver cannot back (false,
|
||||
/// `err`: what was mapped by then stays). The new slots are empty until the caller fills them.
|
||||
bool grow(int64_t want_bytes, std::string& err);
|
||||
/// The number of leading slots that fit wholly inside the first `bytes` bytes.
|
||||
int64_t slots_within(int64_t bytes) const;
|
||||
/// The bytes the first `n` slots span.
|
||||
int64_t bytes_of(int64_t n) const { return slot_end(n < 0 ? 0 : n > slots_ ? slots_ : n); }
|
||||
|
||||
/// `(layer, expert)` -> slot index, or `kNotResident`. Bounds-checked: a bad layer or expert returns
|
||||
/// `kNotResident` rather than reading whatever is adjacent in the table.
|
||||
int32_t slot_of(int64_t layer, int64_t expert) const;
|
||||
/// Claims the next free slot for `(layer, expert)`. Returns the slot, or `kNotResident` when the cache is
|
||||
/// full - **it never evicts**, because eviction policy is a measured question (`R4.1`'s LFU-decay vs LRU
|
||||
/// sweep) and a placeholder policy would set the hit rate that everything downstream is then sized against.
|
||||
int32_t admit(int64_t layer, int64_t expert);
|
||||
|
||||
/// Publish a same-layer replacement after its slot copy has completed.
|
||||
void replace(int64_t layer, int32_t old_expert, int32_t new_expert) {
|
||||
auto& old = residency_[(size_t) layer * n_expert_ + old_expert];
|
||||
residency_[(size_t) layer * n_expert_ + new_expert] = old;
|
||||
old = kNotResident;
|
||||
}
|
||||
|
||||
/// **R4.2g: GIVE EACH LAYER ITS OWN SLOTS. ROUND 328 MEASURED WHY THE GLOBAL FORM CANNOT WORK.**
|
||||
///
|
||||
/// `admit`'s original policy hands out slots in ARRIVAL ORDER from one counter shared by every layer
|
||||
/// (`if (next_free_ >= slots_) return kNotResident;`). A position looks at 10 experts in each of 48
|
||||
/// layers, so the first `n_slots` distinct (layer, expert) pairs are **about 26 layers of POSITION 0** -
|
||||
/// the cache fills entirely inside the first position it ever sees and never changes again, so hits are
|
||||
/// confined to those few layers for the rest of the run.
|
||||
///
|
||||
/// Measured, `--expert-cache 256`: **1781 of 60000 = 2.97%**. `Memory/cache_allocation.py` scores the
|
||||
/// same run's routing and says **8 slots per layer is worth 21.4%** and 64 is worth **70.4%**. The cache
|
||||
/// was never short of capacity - it was handing all of it to two layers.
|
||||
///
|
||||
/// With this on, layer `l` may only use slots `[l*q, (l+1)*q)` where `q = slots()/n_layers`, the last
|
||||
/// layer taking the remainder. **EVICTION IS STILL ABSENT** - the property the comment above calls
|
||||
/// deliberate is preserved exactly; only WHICH slot a layer may take changes. Default off, so every
|
||||
/// caller that predates this flag is bit-for-bit unaffected.
|
||||
void set_per_layer_admission(bool on) { per_layer_ = on; }
|
||||
bool per_layer_admission() const { return per_layer_; }
|
||||
/// The slot range layer `l` may admit into under per-layer admission. Exposed so a test can check it.
|
||||
void layer_slot_range(int64_t layer, int64_t& lo, int64_t& hi) const;
|
||||
|
||||
/// The device address of one slot.
|
||||
uint8_t* device_slot(int32_t slot);
|
||||
const uint8_t* device_slot(int32_t slot) const;
|
||||
|
||||
/// Copies `(layer, expert)`'s blob from `host_blob` into `slot` on `stream`. Asynchronous: the caller
|
||||
/// orders it. Returns false if the indices are out of range rather than reading past the arena.
|
||||
/// `bytes` (plan v0.3 P6): the blob's own size when it is smaller than the slot (a native pack); 0 = the slot.
|
||||
bool fill_slot(int32_t slot, const uint8_t* host_blob, void* stream, std::string& err, int64_t bytes = 0);
|
||||
|
||||
/// **THE SAME COPY, BUT BLOCKING, AND THE PROFILE FILL NEEDS IT.** `fill_slot` is asynchronous because on
|
||||
/// the token path the fill and the kernel that reads it are ordered by one stream and waiting would be a
|
||||
/// synchronisation per layer. At STARTUP there is no such ordering to lean on: the source is pageable host
|
||||
/// memory, `verify_slot` reads the slot back on the LEGACY stream, and a legacy-stream copy is not ordered
|
||||
/// against a `cudaStreamNonBlocking` one. The first version used the async form and `verify_slot` refused
|
||||
/// the whole run with "slot 0 differs from the arena at byte 0" - which is the check doing its job.
|
||||
bool fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0);
|
||||
/// perf-review D-4: `fill_slot_blocking`'s copy on the same (legacy) stream, but queued: many slots are refilled
|
||||
/// with one `sync_queued` at the end instead of a wait per slot. Same ordering against earlier work, same bytes.
|
||||
bool fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0);
|
||||
bool sync_queued(std::string& err);
|
||||
|
||||
/// Reads `slot` back to the host and compares it to `host_blob`, byte for byte. **THE ONLY THING THAT SAYS
|
||||
/// THE CACHE HOLDS THE EXPERT IT CLAIMS TO.** A slot table that is right about indices and wrong about
|
||||
/// bytes produces a plausible token, which is exactly the failure this project has paid for most often.
|
||||
bool verify_slot(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0);
|
||||
|
||||
/// Slots filled so far, for the startup report.
|
||||
int64_t fills() const { return fills_; }
|
||||
|
||||
private:
|
||||
#if defined(STRATA_USE_HIP)
|
||||
bool ensure_blocking_staging(std::size_t bytes, std::string& err);
|
||||
uint8_t* blocking_staging_ = nullptr;
|
||||
std::size_t blocking_staging_bytes_ = 0;
|
||||
#endif
|
||||
int64_t slot_end(int64_t n) const { return off_.empty() ? n * blob_ : (int64_t) off_[(size_t) n]; }
|
||||
bool open_segmented(uint64_t want, std::string& err);
|
||||
void release_segmented();
|
||||
uint8_t* base_ = nullptr;
|
||||
int64_t live_slots_ = 0; ///< #533: slots() - all of them unless shrunk
|
||||
int64_t seg_req_ = 0; ///< #533: the segment size asked for (0: one cudaMalloc)
|
||||
int64_t seg_ = 0; ///< #533: the segment size used (a multiple of the driver's granularity)
|
||||
uint64_t reserved_ = 0; ///< #533: the reserved address range's size
|
||||
std::vector<unsigned long long> segs_; ///< #533: each segment's physical handle (0: unmapped)
|
||||
std::vector<int64_t> seg_size_; ///< #533: each segment's size (the last one may be shorter)
|
||||
int64_t mapped_segs_ = 0; ///< #533: segments [0, mapped_segs_) are backed
|
||||
std::vector<int32_t> residency_; ///< [n_layers * n_expert] -> slot or kNotResident
|
||||
int64_t slots_ = 0;
|
||||
int64_t n_layers_ = 0;
|
||||
int64_t n_expert_ = 0;
|
||||
int64_t blob_ = 0;
|
||||
int64_t next_free_ = 0;
|
||||
int64_t fills_ = 0;
|
||||
/// R4.2g. `per_layer_` off (the default) leaves `next_free_` as the only admission counter, so the
|
||||
/// pre-existing path is untouched.
|
||||
bool per_layer_ = false;
|
||||
std::vector<int32_t> layer_next_; ///< [n_layers] -> that layer's next free slot
|
||||
std::vector<uint64_t> off_; ///< plan v0.3 P6: slot offsets (slots + 1 entries) when sized
|
||||
int64_t admitted_ = 0;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,727 +0,0 @@
|
||||
// include/strata/core/expert_source.hpp - P2.S3/P2.S5: the expert pool's adapter to the host loop.
|
||||
//
|
||||
// `session_loop` publishes, per layer, the NORMED activation `x_f`, the ten routed expert ids and their router
|
||||
// weights, and expects `k x n_embd` floats back. This is the piece that turns those four things into an
|
||||
// `ExpertPool::run` call. Nothing here is clever, and that is the point: the pool, the kernel and the loop are
|
||||
// each already verified, so this file has exactly one job - get the CONTRACT between them right.
|
||||
//
|
||||
// THE CONTRACT, and each clause is a way to be wrong:
|
||||
//
|
||||
// 1. **`x_f` IS THE SAME PINNED BUFFER EVERY LAYER.** Its ADDRESS never changes, so the `ActQ` cannot be
|
||||
// cached by pointer - a cache keyed on `x_f` would quantize layer 0 and reuse it for all 47 remaining
|
||||
// layers, which is a finite, plausible, completely wrong token. There is no cache here at all: the
|
||||
// conversion is one 2560-element pass against a 0.3 ms/layer budget, and a correct answer is worth more
|
||||
// than the microseconds.
|
||||
// 2. **THE POOL DOES NOT APPLY THE ROUTER WEIGHT.** `moe_combine` (`src/core/layer.cpp:479`) sums
|
||||
// `w[i] * parts[i]` on the device. `ExpertJob::weight` is a diagnostic field; setting it here would
|
||||
// apply the weight twice, which is invisible in a single layer and compounds over 48.
|
||||
// 3. **THE KERNEL'S GEOMETRY IS FIXED BY THE ARTIFACT** (`H = 2560`, `FF = 640`, `BLOB = 1,382,400`). A
|
||||
// different `n_embd` or a different expert width is REFUSED rather than mis-indexed, because the blob's
|
||||
// internal offsets are compile-time constants and reading a 640-wide expert as a 2560-wide one walks off
|
||||
// the end into the next expert's bytes without faulting.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/expert_cache.hpp"
|
||||
#include "strata/core/hit_hook.hpp"
|
||||
#include "strata/kernels/cpu/pool.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <condition_variable>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
struct ExpertLayout;
|
||||
}
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
class PeerExperts; // multi-GPU: the second GPU's expert tier (peer_experts.hpp)
|
||||
class RemoteExperts;
|
||||
struct LoadStats;
|
||||
|
||||
namespace detail {
|
||||
|
||||
/// Sentinel used by the pure complement planner for a blob that remains in the mmap fallback.
|
||||
inline constexpr uint64_t kNoCacheComplement = ~uint64_t{0};
|
||||
|
||||
/// Required cgroup-v2 usage counters for the conservative cache-reclaim allowance.
|
||||
struct CgroupMemoryStat {
|
||||
uint64_t current = 0;
|
||||
uint64_t inactive_file = 0;
|
||||
uint64_t file_dirty = 0;
|
||||
uint64_t file_writeback = 0;
|
||||
bool valid = false;
|
||||
};
|
||||
|
||||
/// Calculate additional bytes under a finite cgroup limit after reclaiming only clean inactive file cache.
|
||||
/// Returns false when the required memory.stat counters were unavailable.
|
||||
bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes);
|
||||
|
||||
/// #633: the RAM this process can get. `available`: MemAvailable (Windows: the available physical memory), lowered
|
||||
/// to the room under the tightest cgroup limit; `cgroup_limit`: that tightest limit itself (v2 memory.max of the group
|
||||
/// and its ancestors, or v1 memory.limit_in_bytes), ~0 when there is none - what a container can never exceed.
|
||||
struct HostMemory {
|
||||
uint64_t available = 0;
|
||||
uint64_t cgroup_limit = ~uint64_t{0};
|
||||
};
|
||||
|
||||
/// Linux reads `meminfo`, `self_cgroup` and the cgroup tree under `cgroup_root` (the parameters are for tests; the
|
||||
/// defaults are the real files). cgroup v2 as before (an unreadable limit of a group that has one fails); cgroup v1's
|
||||
/// memory controller (`<root>/memory/<path>`: memory.limit_in_bytes - memory.usage_in_bytes); no cgroup line at all is
|
||||
/// MemAvailable alone. False when the RAM cannot be determined.
|
||||
bool host_available_memory(HostMemory& m, const std::string& meminfo = "/proc/meminfo",
|
||||
const std::string& self_cgroup = "/proc/self/cgroup",
|
||||
const std::string& cgroup_root = "/sys/fs/cgroup");
|
||||
/// --ram-cap (Qwen3.6 port, step 2): every `host_available_memory` answer is clamped to this many bytes, so the RAM
|
||||
/// tier is sized as a machine of that much RAM would size it. 0 = no cap.
|
||||
void set_host_ram_cap(uint64_t bytes);
|
||||
uint64_t host_ram_cap();
|
||||
|
||||
/// Build compact offsets for experts absent from both the primary GPU cache and an optional second GPU tier.
|
||||
/// Kept CPU-only so selection and byte accounting can be tested without initializing a GPU.
|
||||
bool make_cache_complement_plan(
|
||||
int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& primary_gpu_pairs,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs,
|
||||
std::vector<uint64_t>& offsets, uint64_t& bytes, std::string& err);
|
||||
|
||||
/// Resolve one blob through the compact copy when present, otherwise preserve its exact mapped-file fallback.
|
||||
const uint8_t* cache_complement_blob_or_fallback(
|
||||
size_t index, const std::vector<uint64_t>& offsets, const uint8_t* complement_host,
|
||||
const uint8_t* mapped_fallback);
|
||||
|
||||
/// The resident RAM mode: which GPU-cache slots' experts are kept in RAM too. The prompt path lends the cache's
|
||||
/// LAST slots (from `lend_from` on; a short prompt lends only the last few), and a lent slot's expert is streamed
|
||||
/// from RAM during the prompt and copied back into its slot after it. `base_bytes` (every expert no slot holds)
|
||||
/// must fit `budget`; slots are then added from the end down to `lend_from` while they still fit. Returns the
|
||||
/// first slot kept in RAM (`slot_bytes.size()` = none), or -1 when `base_bytes` alone exceeds `budget`.
|
||||
int64_t choose_resident_keep_from(const std::vector<uint64_t>& slot_bytes, uint64_t base_bytes, uint64_t budget,
|
||||
int64_t lend_from);
|
||||
|
||||
/// The adaptive tier swapped `in` into a GPU slot and `out` out of it: `out` takes `in`'s place in the compact copy
|
||||
/// (the caller copies out's bytes there). False, and nothing changed, unless `in` is in the copy and `out` is not.
|
||||
bool exchange_cache_complement(std::vector<uint64_t>& offsets, size_t in, size_t out);
|
||||
|
||||
} // namespace detail
|
||||
|
||||
|
||||
|
||||
/// Where one routed expert's bytes come from.
|
||||
///
|
||||
/// Phase 2 has NO cache (`phase-2-correct-engine.md`: hit rate `h = 0`), so the only implementation is a
|
||||
/// file-backed reader. The interface exists anyway because Phase 3 replaces exactly this object with the VRAM
|
||||
/// cache, and because a test can supply an in-memory source without a 34 GB artifact.
|
||||
class ExpertSource {
|
||||
public:
|
||||
virtual ~ExpertSource() = default;
|
||||
|
||||
/// The expert-layout blob for `(layer, expert)`, or nullptr if it cannot be produced.
|
||||
///
|
||||
/// The pointer only has to stay valid until the next `blob()` call: with `h = 0` every expert is computed
|
||||
/// immediately and nothing is retained. A CACHING source must return pointers into the cache, not into a
|
||||
/// reused staging buffer - otherwise the pool would read the next expert's bytes while computing this one.
|
||||
virtual const uint8_t* blob(int64_t layer, int64_t expert) = 0;
|
||||
|
||||
/// Blobs touched, for the driver to report. A source that does not count returns 0.
|
||||
virtual int64_t reads() const { return 0; }
|
||||
|
||||
/// Plan v0.3 P5: whether `blob(layer, expert)` lies in page-locked, CUDA-registered memory, so an
|
||||
/// asynchronous host-to-device copy can DMA it directly (no staging copy on the CPU).
|
||||
virtual bool pinned(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; }
|
||||
|
||||
/// Called once before the first expert of a layer. A source that reads from disk wants to start the read
|
||||
/// here so it overlaps the quantisation, and a prefetching source in Phase 3 wants the ids.
|
||||
virtual void begin_layer(int64_t layer, const int32_t* ids, int64_t k) { (void) layer; (void) ids; (void) k; }
|
||||
/// Plan v0.3 P6: the DEVICE address of a pinned, mapped blob (the GPU can read it over PCIe), or null.
|
||||
virtual const uint8_t* device_alias(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return nullptr; }
|
||||
/// A file-backed source: start reading this expert's pages now (it will be needed by the CPU); no-op elsewhere.
|
||||
virtual void prefetch(int64_t layer, int64_t expert) { (void) layer; (void) expert; }
|
||||
/// A file-backed source: this expert lives in VRAM, so its pages need not stay in RAM - hand them back to the
|
||||
/// kernel (a later read re-reads the file; no result depends on it). Returns the bytes released; 0 elsewhere.
|
||||
virtual uint64_t release(int64_t layer, int64_t expert) { (void) layer; (void) expert; return 0; }
|
||||
/// Whether the verify window may give the GPU a PCIe share of this layer's misses at all (each expert is still
|
||||
/// checked with `pinned`). The arena answers per layer through its expert 0; the resident RAM mode's compact
|
||||
/// copy has no expert 0 when the GPU cache holds it, so it answers for the whole copy.
|
||||
virtual bool pcie_layer(int64_t layer) const { return device_alias(layer, 0) != nullptr; }
|
||||
|
||||
/// CS-T: whether `blob(layer, expert)` would be assembled into a short-lived buffer (a native pack read from its
|
||||
/// GGUF shards in place, where an expert's gate, up and down rows are three separate slices). Such a pointer
|
||||
/// stays valid for the layer it was asked in and the next one or two; a consumer that keeps a blob longer (the
|
||||
/// prompt path's stager queues a whole chunk) copies it with `copy_blob` instead.
|
||||
virtual bool transient(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; }
|
||||
/// The blob's bytes into `dst` (blob_bytes(layer) of them). Safe from several threads for a source whose
|
||||
/// `transient` can be true.
|
||||
virtual bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst);
|
||||
/// The `n` experts of `layer` the CPU is about to ask `blob` for, all at once: a source that reads a file may
|
||||
/// fetch them in parallel. The bytes `blob` then returns are the same. Default: nothing.
|
||||
virtual void prefetch(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; }
|
||||
/// CS-T: the experts of `layer` a predictor expects next - a source that reads a file may start reading their
|
||||
/// pages now, in the background. Only warms: what `blob` returns is unchanged. Default: nothing.
|
||||
virtual void warm(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; }
|
||||
/// Whether `warm` does anything (the predictor is not run otherwise).
|
||||
virtual bool warms() const { return false; }
|
||||
};
|
||||
|
||||
/// CS-T, routing-aware prefetch of the file tier: when the CPU pool starts layer `l`, a worker thread applies layer
|
||||
/// l+1's router (BF16, host copy) to layer l's MoE input - the residual stream changes little from one layer to the
|
||||
/// next - takes each token's top `k` experts, drops the ones the GPU cache or the RAM copy holds, and asks the
|
||||
/// source to `warm` the rest, so their pages are on the way while layer l computes. A prediction only warms pages:
|
||||
/// it never changes which experts are computed or how.
|
||||
class RouterLookahead {
|
||||
public:
|
||||
RouterLookahead() = default;
|
||||
~RouterLookahead();
|
||||
RouterLookahead(const RouterLookahead&) = delete;
|
||||
RouterLookahead& operator=(const RouterLookahead&) = delete;
|
||||
/// `routers[l]`: layer l's ffn_gate_inp as BF16 bits, n_expert rows of n_embd.
|
||||
bool start(std::vector<std::vector<uint16_t>> routers, int64_t n_embd, int64_t n_expert, int k, ExpertSource* src,
|
||||
std::string& err);
|
||||
/// Layer `layer`'s MoE input for `n_tok` tokens (host floats): predict and warm layer + 1. Never waits: a
|
||||
/// prediction still running for an earlier layer makes this one skip.
|
||||
void submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res);
|
||||
int64_t predicted() const { return predicted_.load(std::memory_order_relaxed); }
|
||||
int64_t skipped() const { return skipped_.load(std::memory_order_relaxed); }
|
||||
double busy_ms() const { return (double) busy_us_.load(std::memory_order_relaxed) / 1000.0; }
|
||||
|
||||
private:
|
||||
void run();
|
||||
std::vector<std::vector<uint16_t>> routers_;
|
||||
int64_t n_embd_ = 0, n_expert_ = 0;
|
||||
int k_ = 10;
|
||||
ExpertSource* src_ = nullptr;
|
||||
std::thread thread_;
|
||||
std::mutex mu_;
|
||||
std::condition_variable cv_;
|
||||
bool quit_ = false, pending_ = false, busy_ = false;
|
||||
int64_t layer_ = -1, n_tok_ = 0;
|
||||
const int32_t* host_res_ = nullptr;
|
||||
std::vector<float> x_;
|
||||
std::atomic<int64_t> predicted_{0}, skipped_{0};
|
||||
std::atomic<uint64_t> busy_us_{0};
|
||||
};
|
||||
|
||||
/// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right
|
||||
/// after the ring and published before the CPU starts its own share. Groups of entries that share a blob; the
|
||||
/// blob is a VRAM slot or a pinned host blob read over PCIe.
|
||||
struct GpuPlanSink {
|
||||
int32_t* counts = nullptr; ///< [0] groups, [1] entries
|
||||
int32_t* start = nullptr; ///< cap + 1
|
||||
int32_t* dst = nullptr; ///< cap: the entry's row of parts (token * k + j)
|
||||
int32_t* tok = nullptr; ///< cap: the entry's token
|
||||
unsigned long long* ptr = nullptr; ///< cap: the group's blob, device address
|
||||
/// Plan v0.3 P6 (DMA): the PCIe share is a second list of groups - `ptr2[q]` is staging slot q, `start2` indexes
|
||||
/// the same dst/tok entries - computed by the GPU after `fetch` has copied their blobs into staging with the
|
||||
/// copy engine. counts[0] = VRAM groups, counts[1] = all entries, counts[2] = PCIe groups.
|
||||
unsigned long long* ptr2 = nullptr;
|
||||
int32_t* start2 = nullptr;
|
||||
unsigned long long staging = 0;
|
||||
int64_t staging_cap = 0;
|
||||
int64_t cap = 0;
|
||||
void (*publish)(void* ctx) = nullptr;
|
||||
/// Starts the DMA copies of `n` host blobs (pinned) into staging slots 0..n-1 and signals the GPU when they land.
|
||||
void (*fetch)(void* ctx, const uint8_t* const* src, int n, size_t bytes) = nullptr;
|
||||
void* ctx = nullptr;
|
||||
/// Plan v0.3 P6: how a PCIe group reaches the GPU. 0 = the copy engine stages it (DMA, `fetch`); 1 = the grouped
|
||||
/// kernel reads the mapped arena directly; 2 = a copy kernel stages it inside the graph. For 1 and 2 `ptr2`
|
||||
/// holds the arena's device alias.
|
||||
int pcie_mode = 0;
|
||||
};
|
||||
|
||||
/// The adapter's own state. One per session, reused every layer so the token path allocates nothing (P2.T10).
|
||||
struct ExpertDispatch {
|
||||
strata::kernels::cpu::ExpertPool* pool = nullptr;
|
||||
ExpertSource* src = nullptr;
|
||||
RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts
|
||||
RemoteExperts* remote[3] = {}; ///< optional CUDA1..3 tiers for otherwise CPU-served rows
|
||||
int remote_count = 0;
|
||||
int64_t n_expert = strata::kernels::cpu::NE;
|
||||
|
||||
/// Counters, for the driver to report rather than for control flow.
|
||||
int64_t layers = 0;
|
||||
int64_t experts = 0;
|
||||
int64_t missing = 0;
|
||||
|
||||
// ================================ R4: THE VRAM TIER, MEASURED BEFORE IT IS USED ================================
|
||||
//
|
||||
// **THE CACHE IS CONSULTED AND FILLED HERE, AND NOTHING IS COMPUTED FROM IT YET.** That is deliberate and
|
||||
// it is `R4-design-note.md` §7 step 2: the *dispatch* is measured on its own before any kernel is written,
|
||||
// because a hit rate measured after the kernel exists cannot say whether a disappointing result was the
|
||||
// policy, the split or the kernel.
|
||||
//
|
||||
// So every expert is still computed by the CPU, exactly as before, and the run is numerically identical
|
||||
// with the cache on or off. What changes is that the engine now reports **h on its own routing, on a real
|
||||
// workload** - which is the number `R4.1` asks for and which until now existed only from offline traces.
|
||||
//
|
||||
// The policy is compulsory-miss: the first time `(layer, expert)` is routed, if a slot is free it is
|
||||
// admitted and filled from the arena. No eviction, because eviction policy is the measured question
|
||||
// (`R4.1`'s LFU-decay vs LRU sweep) and a placeholder would set the hit rate everything is sized against.
|
||||
ExpertCache* cache = nullptr;
|
||||
int64_t cache_hits = 0; ///< lookups already resident
|
||||
int64_t cache_admitted = 0; ///< lookups that took a slot
|
||||
int64_t cache_refused = 0; ///< lookups with no slot free (the cache is full)
|
||||
void* cache_stream = nullptr;
|
||||
const char* cache_fail = nullptr;
|
||||
|
||||
// ================================ R4.2c: THE HITS GO TO THE GPU ================================
|
||||
//
|
||||
// **THE SPLIT IS BY ROUTER INDEX, AND THAT IS THE WHOLE TRICK.** A layer routes ten experts; the resident
|
||||
// ones are computed on the GPU and the rest on the CPU, and both answers have to end up in `parts` at the
|
||||
// index the ROUTER gave them, because that is the order `moe_combine` weights against. So the CPU's `out`
|
||||
// rows are zeroed for the hits, and each hit carries its routed index to the kernel as `dst`.
|
||||
//
|
||||
// Everything below is per-session state rather than per-call, so the token path allocates nothing (P2.T10).
|
||||
const uint8_t* cache_base = nullptr; ///< the slot arena on the DEVICE
|
||||
int64_t cache_blob = 0; ///< bytes per slot
|
||||
const uint64_t* cache_slot_off = nullptr; ///< plan v0.3 P6: per-slot offsets when the slots differ in size
|
||||
void* hit_scratch = nullptr; ///< `moe_hit_grouped_scratch_bytes(K, ...)`
|
||||
float* parts_out = nullptr; ///< the graph's `parts` buffer, on the device
|
||||
/// Where the GPU's hits land, `K x n_embd`, DEVICE and separate from `parts_out` on purpose: see
|
||||
/// `HitPhase`. Zeroed by the hit path each layer before the kernel writes it.
|
||||
float* hit_out = nullptr;
|
||||
int64_t parts_elems = 0; ///< `K * n_embd`, the length of both buffers
|
||||
const float* mixed = nullptr; ///< the layer's normed activation, for the hit kernel's Q8_0
|
||||
uint8_t* x_q8_0_hit = nullptr; ///< `(n_embd/32) * 34` bytes, its own buffer
|
||||
/// **R4.2h: THE CPU's fp32 ACTIVATION SCALES, `(n_embd/32)` FLOATS.** Without them the GPU's hits are
|
||||
/// computed with the `block_q8_0`'s fp16 `d` while the CPU's misses use the fp32 `ActQ::scale`
|
||||
/// (`cpu/expert.cpp:92`) - **4.761e-04 relative on 80 of 80 chunks**, measured with both real
|
||||
/// implementations linked in `bench/micro/act_quant_parity.cu`. That disagreement is why turning the
|
||||
/// cache on changed the generated tokens. Required whenever the hit path runs.
|
||||
float* x_q8_0_hit_scale = nullptr;
|
||||
int32_t* d_slot = nullptr; ///< device, K entries
|
||||
int32_t* d_dst = nullptr; ///< device, K entries
|
||||
std::vector<int32_t> h_slot, h_dst; ///< host staging, sized at session setup
|
||||
/// **PER ROUTER INDEX, DECIDED IN `Launch` AND CONSUMED BY THE POOL.** The two callbacks share it
|
||||
/// so the decision is made exactly once, on this layer's ids, and neither side can re-decide it.
|
||||
std::vector<uint8_t> is_hit;
|
||||
bool decided = false;
|
||||
/// Plan v0.3 P4 token graph: the STATIC residency table (`n_layers x n_expert`, slot or -1), the host's copy
|
||||
/// of what the device hit path reads. When set, the pool leaves a resident expert's row at zero (the GPU
|
||||
/// computes it) without any `Launch` callback.
|
||||
const int32_t* host_res = nullptr;
|
||||
/// Plan v0.3 P4: split every expert by rows across the pool's threads (default on; A/B `--no-split-rows`).
|
||||
bool split_rows = true;
|
||||
|
||||
// ================================ R4.2d: DID THE GPU ACTUALLY START? ================================
|
||||
//
|
||||
// **THE HIT PATH IS 0.91 ms SLOWER AND THE ONLY EXPLANATION LEFT IS THAT IT NEVER OVERLAPS.** The kernel
|
||||
// is 159 GB/s against the CPU's 35, the CPU's half of the drain falls 6 ms, and none of it reaches the
|
||||
// token - which is what it would look like if the enqueued hit kernels did not BEGIN until the host next
|
||||
// entered the driver, i.e. after `pool()` returned. That is the third sighting of this driver behaving
|
||||
// that way (rounds 195/287 on the doorbell, round 36 on the head and sampler) and it decides whether R4 can
|
||||
// pay at all, so it gets measured rather than argued.
|
||||
//
|
||||
// `hit_done` is recorded on the stream straight after the hit kernel. `Combine` - which runs after the
|
||||
// pool - queries it: SUCCESS means the GPU finished while the CPU was working, NOT-READY means it had not.
|
||||
// Same shape as the doorbell's `rings_mid_graph`, and for the same reason.
|
||||
void* hit_done = nullptr; ///< cudaEvent_t, created at session setup
|
||||
int64_t hit_ready = 0; ///< layers where the hit work was DONE by the time the pool returned
|
||||
int64_t hit_late = 0; ///< layers where it was not
|
||||
/// The candidate fix, as an A/B arm: enter the driver once right after the hit launch. If submission is
|
||||
/// lazy, this starts the GPU work before the pool instead of after it.
|
||||
bool hit_poke = false;
|
||||
bool hit_cpu_order = false; ///< experimental CPU-order GPU expert arithmetic; opt-in only
|
||||
int64_t n_hits = 0; ///< this layer's hits
|
||||
/// Set by `Launch` and consumed by `Combine`, so a `Combine` with no `Launch` in front of it cannot
|
||||
/// add a stale buffer into `parts`.
|
||||
bool hit_pending = false;
|
||||
const char* hit_fail = nullptr;
|
||||
|
||||
/// Whether the hit path is wired up. All of it or none of it: a half-configured hit path would compute
|
||||
/// some experts twice and others not at all, which is a wrong token rather than an error.
|
||||
bool hits_ready() const {
|
||||
return cache != nullptr && cache_base != nullptr && parts_out != nullptr && hit_out != nullptr &&
|
||||
mixed != nullptr &&
|
||||
hit_scratch != nullptr && x_q8_0_hit != nullptr && x_q8_0_hit_scale != nullptr && d_slot != nullptr && d_dst != nullptr;
|
||||
}
|
||||
|
||||
std::vector<strata::kernels::cpu::ExpertJob> jobs;
|
||||
strata::kernels::cpu::ActQ act;
|
||||
/// Plan v0.3 P6 verify window: one quantized activation per token, the multi-token jobs, and the expert ->
|
||||
/// job map (reset after every layer).
|
||||
std::vector<strata::kernels::cpu::ActQ> act_multi;
|
||||
/// Plan v0.3 P6: a native pack's per-token activations (MAXT x kNativeActBytes).
|
||||
std::vector<uint8_t> nact_multi;
|
||||
std::vector<strata::kernels::cpu::ExpertJobMulti> jobs_multi;
|
||||
std::vector<int16_t> job_of;
|
||||
/// Plan v0.3 P6: the verify window's GPU plan (VRAM hits + the PCIe share of the misses); `pcie_num`/256 of
|
||||
/// each layer's distinct missed experts (the last ones in routing order) are read by the GPU over PCIe.
|
||||
GpuPlanSink* plan = nullptr;
|
||||
int pcie_num = 0;
|
||||
int64_t pcie_experts = 0; ///< distinct experts the GPU read over PCIe in verify windows
|
||||
/// #588: routed (token, expert) entries the GPU computed from outside its cache in verify windows: read over PCIe
|
||||
/// (--pcie-frac, kind 1) or on another GPU (kind 2). In neither cache_hits nor cache_refused.
|
||||
int64_t offload_entries = 0;
|
||||
double ms_plan = 0, ms_actq = 0, ms_jobs = 0, ms_run = 0; ///< verify-window dispatch sections
|
||||
/// Plan v0.3 P6: decayed routing counts per (layer, expert) during decode (sized by the caller; empty = off),
|
||||
/// which the driver uses to swap the most-routed missing experts into the VRAM tier between rounds.
|
||||
std::vector<float> usage;
|
||||
int64_t multi_misses = 0; ///< distinct (layer, expert) pairs the CPU computed in verify windows
|
||||
int64_t multi_entries = 0; ///< routed (token, expert) entries the CPU served in verify windows
|
||||
/// Multi-GPU: the second GPU's tier. Its experts are computed there instead of on the CPU (kind 2).
|
||||
PeerExperts* peer = nullptr;
|
||||
int64_t peer_entries = 0; ///< routed entries the peer served in verify windows
|
||||
/// Set when `dispatch` could not produce an answer. The loop itself has no error channel, so this is
|
||||
/// where a source failure surfaces: the driver checks it after `session_loop` returns rather than the
|
||||
/// engine computing from a half-filled `parts`.
|
||||
///
|
||||
/// **`failed` LATCHES AND `fail` IS ONLY THE MESSAGE.** Clearing the message must not re-arm the adapter:
|
||||
/// a session that failed at layer 5 has already fed `moe_combine` whatever `parts` held, so every layer
|
||||
/// after it is built on a hole - and resuming into a plausible-looking token is the exact outcome this
|
||||
/// whole mechanism exists to prevent. `failed` is what the short-circuit reads.
|
||||
bool failed = false;
|
||||
const char* fail = nullptr;
|
||||
int64_t fail_layer = -1;
|
||||
int64_t fail_expert = -1;
|
||||
};
|
||||
|
||||
/// `strata::core::PoolFn`, exactly. Silent on failure BY SIGNATURE - see `ExpertDispatch::fail`.
|
||||
void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd,
|
||||
int64_t k, float* out);
|
||||
|
||||
/// Plan v0.3 P6: the pool for a verify window of `n_tok` tokens. `x_f` is (n_tok, n_embd), `ids` (n_tok, k) and
|
||||
/// `out` (n_tok * k, n_embd). Each distinct missed expert is computed once for all the tokens routed to it;
|
||||
/// resident experts' rows are zeroed (the GPU adds them). Requires `host_res` (the token-graph residency).
|
||||
void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k,
|
||||
float* out);
|
||||
|
||||
/// **THE HITS, LAUNCHED AFTER THE MISSES ARE STAGED AND BEFORE `post[l]`.** Same shape as `PoolFn` and for the
|
||||
/// same reason: `session_loop` owns the ORDER and this owns the work, so the loop needs to know nothing about
|
||||
/// expert caches. Returns immediately when there are no hits, which is every layer until the cache is warm.
|
||||
///
|
||||
/// It must run AFTER the host has copied the misses into `parts_dev` (it writes into the same buffer, on rows
|
||||
/// the CPU zeroed) and BEFORE `post[l]` (which reads it). Both are stream-ordered on the loop's own stream.
|
||||
void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k);
|
||||
/// The pool half of the same decision; see `ExpertDispatch::is_hit`.
|
||||
|
||||
/// **PHASE 2'S ONLY SOURCE: `experts.bin`, memory-mapped, no cache.**
|
||||
///
|
||||
/// `experts.bin` is 33,973,862,400 B and `BLOB` is 1,382,400, so it holds exactly `48 x 512 = 24,576` blobs and
|
||||
/// the index is `layer * 512 + expert` with NO padding. A mapping is therefore the whole implementation: the
|
||||
/// blob pointer is base plus a multiply, and the page fault that follows is the read.
|
||||
///
|
||||
/// **AND THAT IS NOT AS SLOW AS IT SOUNDS, WHICH IS THE POINT.** The expert set is 34 GB and this machine has
|
||||
/// 64 GB of DDR5, so a warm OS page cache holds ALL of it - the second token onward is a DRAM read at the
|
||||
/// measured 44.14 GB/s, not a disk read. The first token's 663.6 MB comes off the disk and is the cold-path
|
||||
/// number; `benches` should report the two separately rather than blending them.
|
||||
///
|
||||
/// IT IS NOT AN LRU, AN LFU OR A PREFETCHER. Phase 3 replaces this object with those. Phase 2 is hit rate
|
||||
/// `h = 0` on purpose, so that the CPU path and the host round trip are exercised on every layer of every
|
||||
/// token - which is the only way they get debugged before speed matters.
|
||||
class FileExpertSource : public ExpertSource {
|
||||
public:
|
||||
FileExpertSource() = default;
|
||||
~FileExpertSource() override;
|
||||
FileExpertSource(const FileExpertSource&) = delete;
|
||||
FileExpertSource& operator=(const FileExpertSource&) = delete;
|
||||
|
||||
/// Maps `<pack_dir>/experts.bin` and checks its size against the loaded expert layout. Canonical packs use
|
||||
/// `n_layers * n_expert * BLOB`; native packs use their variable per-layer blob sizes and offsets.
|
||||
///
|
||||
/// The size check is not a formality: a short file would fault at the END of a long sequence, and an
|
||||
/// over-long one means the pack is not the one the geometry came from. Refuses with the two numbers.
|
||||
///
|
||||
/// CS-T: a native pack WITHOUT experts.bin, after `set_gguf`, maps the model's GGUF shards instead (every file
|
||||
/// native_experts.txt names, after `check_experts_gguf`), and assembles a blob from its three role slices when
|
||||
/// it is asked for: the SSD tier, read in place through the OS file cache, with no 30-77 GB experts.bin copy.
|
||||
/// With experts.bin present nothing changes.
|
||||
bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err);
|
||||
/// CS-T: the --native shard (native_experts.txt names the other files beside it); see `open`.
|
||||
void set_gguf(const std::string& native) { gguf_ = native; }
|
||||
/// Whether the experts are read from the GGUF shards in place (no experts.bin).
|
||||
bool gguf_mode() const { return !role_ptr_.empty(); }
|
||||
/// Pin a compact host mirror of experts absent from a fully filled static GPU cache. The mmap remains open
|
||||
/// as a fallback for later cache reloads. This is opt-in because the complement may still be a large allocation.
|
||||
///
|
||||
/// The resident RAM mode (`--resident-experts`, `--resident-cpu-experts`):
|
||||
/// - `pin`: page-locked and mapped (`cudaHostAlloc`), so the prompt path copies it by DMA and the verify
|
||||
/// window may read a share of the misses over PCIe; when the driver refuses, ordinary memory locked in the
|
||||
/// working set instead. `pin = false` is ordinary pageable memory (the ROCm arm: large pinned allocations
|
||||
/// can fail there, and it is what the HIP measurements used).
|
||||
/// - `lend_from_slot` >= 0: the GPU-cache slots from there to the end are the prompt path's lend region; their
|
||||
/// experts are kept in RAM too, from the last slot down, as far as `available RAM - headroom_bytes` allows
|
||||
/// (a lent slot's expert is streamed during the prompt and copied back after it).
|
||||
/// - the rest (the experts no slot holds) must fit that budget, or nothing is allocated and this returns false.
|
||||
///
|
||||
/// CS-T, `budget_bytes` > 0 (`--resident-budget-gib`): only as many of those experts as fit `budget_bytes`, taken
|
||||
/// in `rank` order (the expert profile: the hottest after the GPU cache's), are copied; the rest stay on the
|
||||
/// mapped files (the SSD tier). No lend region then (a lent slot's expert is read from the files).
|
||||
/// #467: `budget_bytes` = `kResidentWhatFits` is that path sized by the RAM alone (available minus the headroom
|
||||
/// and the #403 margin) - the soft --resident-experts mode's second try when the whole complement does not fit;
|
||||
/// false when not even one expert fits. On Windows the mapped experts leave the working set before any reading.
|
||||
static constexpr uint64_t kResidentWhatFits = ~0ull;
|
||||
bool pin_cache_complement(
|
||||
const ExpertCache& cache, std::string& err, bool pin = true,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs = {}, int64_t lend_from_slot = -1,
|
||||
uint64_t headroom_bytes = 8ull << 30, uint64_t budget_bytes = 0,
|
||||
const std::vector<std::pair<int32_t, int32_t>>* rank = nullptr);
|
||||
void close();
|
||||
|
||||
bool mapped() const { return base_ != nullptr; }
|
||||
int64_t blobs() const { return blobs_; }
|
||||
uint64_t pinned_bytes() const { return complement_pinned_ ? complement_pin_limit_ : 0; }
|
||||
uint64_t resident_bytes() const { return complement_bytes_; }
|
||||
bool complement_pinned() const { return complement_pinned_; }
|
||||
bool complement_ready() const { return complement_ready_; }
|
||||
/// How many experts the RAM copy holds (the RAM tier's count for the start-up log and /health; 0 before it is built).
|
||||
int64_t complement_count() const;
|
||||
uint64_t locked_bytes() const { return complement_locked_; }
|
||||
/// Lend-region slots whose experts the compact copy holds (the last ones of the cache).
|
||||
int64_t resident_lent_slots() const { return complement_lent_slots_; }
|
||||
|
||||
// ---- the resident RAM mode and the adaptive tier. A swap puts `in` (held here) into a GPU slot and evicts
|
||||
// `out` (held only by that slot). Before the slot is overwritten the caller copies it back into an exchange
|
||||
// buffer and calls `stage_exchange`: `out` is then read from that buffer, and `in` still from here (the CPU
|
||||
// computes both until the swap lands). Once the slot copy has landed, `commit_exchanges` moves `out` into
|
||||
// `in`'s place, so the copy keeps holding exactly the experts the GPU does not - with no read of the file.
|
||||
/// Whether the compact copy holds `(layer, expert)`.
|
||||
bool has_resident(int64_t layer, int64_t expert) const;
|
||||
/// Host room for `n` evicted blobs (page-locked when possible). Idempotent for the same or a smaller `n`.
|
||||
bool reserve_exchanges(int64_t n, std::string& err);
|
||||
int64_t exchange_capacity() const { return xstage_cap_; }
|
||||
uint8_t* exchange_buffer(int64_t q) const;
|
||||
/// Requires `has_resident(layer, in)`, `!has_resident(layer, out)` and `exchange_buffer(q)` holding out's blob.
|
||||
bool stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q);
|
||||
/// After the GPU copies of every staged swap have landed. Returns how many exchanges were applied.
|
||||
int64_t commit_exchanges();
|
||||
int64_t exchanges() const { return exchanges_; }
|
||||
/// With the compact copy ready: blobs read from the mapped file since (what the plain mmap mode may read from
|
||||
/// the SSD). 0 in a steady resident mode; lend-region experts that did not fit the RAM count here.
|
||||
int64_t file_reads() const { return file_reads_.load(std::memory_order_relaxed); }
|
||||
/// CS-T per-tier counters: blobs served from the RAM copy, and the bytes read from the mapped files (the blobs
|
||||
/// `file_reads` counts, plus the prompt path's copies of them).
|
||||
int64_t ram_reads() const { return ram_reads_.load(std::memory_order_relaxed); }
|
||||
uint64_t file_read_bytes() const { return file_read_bytes_.load(std::memory_order_relaxed); }
|
||||
/// Of those, the bytes `blob` read (decode windows, adaptive swaps; the rest are the prompt path's copies), and
|
||||
/// the time spent reading the files, summed over threads.
|
||||
uint64_t file_blob_bytes() const { return file_blob_bytes_.load(std::memory_order_relaxed); }
|
||||
double file_ms() const { return (double) file_us_.load(std::memory_order_relaxed) / 1000.0; }
|
||||
/// Threads `prefetch` reads the GGUF with (STRATA_FETCH_THREADS, default 8).
|
||||
void set_fetch_threads(int n) { fetch_threads_ = n < 1 ? 1 : n; }
|
||||
/// #286 (Windows): read the experts straight from the drive (FILE_FLAG_NO_BUFFERING, overlapped) instead of
|
||||
/// through the mapped files - the GGUF in place, or a pack's experts.bin - when the file cache could not keep them
|
||||
/// beside `ram_bytes` (the RAM budget), cached now or not (their mapped pages would land in the working set); see
|
||||
/// experts_unbuffered. The mapped reads' page faults are one small request each, and the pages they bring in
|
||||
/// take the RAM the budget was sized for. `why` says what decided.
|
||||
/// #577: `ram_bytes` counts up to every expert, and only the experts outside it are what the cache must keep.
|
||||
bool set_unbuffered(uint64_t ram_bytes, std::string& why);
|
||||
/// #577: the same decision once the RAM copy is built (pin_cache_complement), from the RAM it really holds and the
|
||||
/// expert bytes outside it; switches either way (startup only, nothing reading). Returns whether unbuffered.
|
||||
bool recheck_unbuffered(std::string& why);
|
||||
bool unbuffered() const { return !direct_.empty(); }
|
||||
/// Every expert's bytes (n_layers x n_expert blobs).
|
||||
uint64_t expert_bytes() const;
|
||||
/// #286, unbuffered: assembles the blobs of these pairs ahead of the `blob` calls that will ask for them (the
|
||||
/// GPU cache's fill from the profile) - one batch of reads instead of one blob at a time. At most 64 pairs.
|
||||
void prefetch_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n);
|
||||
|
||||
const uint8_t* blob(int64_t layer, int64_t expert) override;
|
||||
bool pinned(int64_t layer, int64_t expert) const override;
|
||||
const uint8_t* device_alias(int64_t layer, int64_t expert) const override;
|
||||
bool pcie_layer(int64_t layer) const override;
|
||||
bool transient(int64_t layer, int64_t expert) const override;
|
||||
bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override;
|
||||
/// CS-T: advances the assembled blobs' age (see staged_blob).
|
||||
void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override;
|
||||
/// CS-T: the GGUF in place assembles the missed experts on `fetch_threads_` threads.
|
||||
void prefetch(int64_t layer, const int64_t* experts, int64_t n) override;
|
||||
/// CS-T: the GGUF in place asks the OS for the predicted experts' pages (PrefetchVirtualMemory on Windows,
|
||||
/// madvise(WILLNEED) elsewhere), skipping the RAM copy's.
|
||||
void warm(int64_t layer, const int64_t* experts, int64_t n) override;
|
||||
/// Not when the reads are unbuffered: the warmed pages would be read through the file cache, a second time.
|
||||
bool warms() const override { return !role_ptr_.empty() && direct_.empty(); }
|
||||
/// Of the blobs the file tier read for the decode, how many had been warmed for their layer beforehand.
|
||||
int64_t warmed_hits() const { return warm_hits_.load(std::memory_order_relaxed); }
|
||||
int64_t warmed() const { return warm_count_.load(std::memory_order_relaxed); }
|
||||
|
||||
/// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only
|
||||
/// interesting once Phase 3 makes it not so.
|
||||
int64_t reads() const override { return reads_; }
|
||||
|
||||
private:
|
||||
const uint8_t* mapped_blob(int64_t layer, int64_t expert) const;
|
||||
/// The blob's bytes from the mapped file(s) - experts.bin, or the three GGUF role slices - into `dst`.
|
||||
bool copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const;
|
||||
bool open_gguf(std::string& err);
|
||||
const uint8_t* staged_blob(int64_t layer, int64_t expert);
|
||||
bool claim_stage(int64_t key, size_t& v, bool& fill);
|
||||
bool fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst);
|
||||
void publish_stage(size_t v, int64_t layer, bool ok, double us);
|
||||
struct Fill { size_t v; int64_t layer, e; uint8_t* dst; };
|
||||
/// The claimed buffers' blobs: one overlapped batch when unbuffered, else the fetch threads' mapped copies.
|
||||
void fill_many(const std::vector<Fill>& todo);
|
||||
/// #286: the blobs from the drive, unbuffered: every role's 4 KiB-aligned window is read at once (overlapped)
|
||||
/// into this thread's aligned buffer, then copied into place. False when a read fails.
|
||||
bool read_direct(const Fill* fills, size_t n) const;
|
||||
bool open_direct(std::string& why);
|
||||
std::vector<std::string> paths_; ///< the mapped files, as maps_
|
||||
std::vector<void*> direct_; ///< #286: per file, an unbuffered overlapped handle (Windows)
|
||||
std::vector<int> role_file_; ///< 3 x n_layers: index into maps_ / direct_
|
||||
/// blobs assembled in the stage buffers (`blob` hands those out): the GGUF in place, or any unbuffered source
|
||||
bool staged() const { return !role_ptr_.empty() || !direct_.empty(); }
|
||||
static constexpr uint64_t kNoComplement = detail::kNoCacheComplement;
|
||||
// ---- CS-T: the GGUF shards in place
|
||||
std::string gguf_;
|
||||
struct Map {
|
||||
const uint8_t* base = nullptr;
|
||||
uint64_t bytes = 0;
|
||||
#if defined(_WIN32)
|
||||
void* file = nullptr;
|
||||
void* mapping = nullptr;
|
||||
#else
|
||||
int fd = -1;
|
||||
#endif
|
||||
};
|
||||
std::vector<Map> maps_;
|
||||
std::vector<const uint8_t*> role_ptr_; ///< 3 x n_layers: gate / up / down of the layer's expert 0
|
||||
std::vector<uint64_t> role_bytes_; ///< 3 x n_layers: bytes per expert of that role
|
||||
// the blobs assembled for `blob()`: a small pool of buffers, one per recent (layer, expert). A buffer is
|
||||
// reused only once `kStageAge` layer changes have passed since its blob was last asked for, so a pointer holds
|
||||
// through the layer it was asked in and the next ones (the pool computes a layer's misses before the next).
|
||||
static constexpr uint64_t kStageAge = 3;
|
||||
std::mutex stage_mu_;
|
||||
std::vector<std::unique_ptr<uint8_t[]>> stage_buf_;
|
||||
std::vector<int64_t> stage_key_;
|
||||
std::vector<uint64_t> stage_epoch_, stage_used_;
|
||||
std::vector<char> stage_busy_; ///< being filled (outside stage_mu_): never a victim
|
||||
std::condition_variable stage_cv_;
|
||||
int fetch_threads_ = 8;
|
||||
std::atomic<uint64_t> file_blob_bytes_{0}, file_us_{0};
|
||||
std::unique_ptr<std::atomic<uint32_t>[]> warm_stamp_; ///< per (layer, expert): epoch_ + 1 when warmed
|
||||
std::atomic<int64_t> warm_hits_{0}, warm_count_{0};
|
||||
std::unordered_map<int64_t, size_t> stage_of_;
|
||||
uint64_t stage_blob_ = 0;
|
||||
uint64_t stage_seq_ = 0;
|
||||
uint64_t epoch_ = 0;
|
||||
int64_t last_layer_ = -1;
|
||||
bool stage_grew_ = false;
|
||||
std::atomic<int64_t> ram_reads_{0};
|
||||
std::atomic<uint64_t> file_read_bytes_{0};
|
||||
const uint8_t* base_ = nullptr;
|
||||
int64_t blobs_ = 0;
|
||||
int64_t n_layers_ = 0;
|
||||
int64_t n_expert_ = 0;
|
||||
uint64_t mapped_bytes_ = 0;
|
||||
std::vector<uint64_t> layer_offsets_, layer_blob_bytes_;
|
||||
void* complement_arena_ = nullptr;
|
||||
const uint8_t* complement_host_ = nullptr;
|
||||
const uint8_t* complement_device_ = nullptr;
|
||||
uint64_t complement_bytes_ = 0;
|
||||
std::vector<uint64_t> complement_offsets_;
|
||||
int64_t complement_count_ = 0; ///< experts in the RAM copy (counted when it is built)
|
||||
bool complement_pinned_ = false;
|
||||
bool complement_partial_ = false; ///< CS-T: only the first complement_pin_limit_ bytes are registered
|
||||
uint64_t complement_pin_limit_ = 0;
|
||||
uint64_t complement_lock_off_ = 0; ///< the working-set lock covers [lock_off, lock_off + locked)
|
||||
bool complement_ready_ = false;
|
||||
uint64_t complement_locked_ = 0; ///< bytes held in the working set (pin refused)
|
||||
int64_t complement_lent_slots_ = 0;
|
||||
std::vector<const uint8_t*> override_; ///< staged exchanges: an evicted expert read from its exchange buffer
|
||||
struct Exchange { size_t in, out; int64_t q; uint64_t bytes; };
|
||||
std::vector<Exchange> staged_;
|
||||
uint8_t* xstage_ = nullptr; ///< exchange buffers, `xstage_cap_ x xstage_blob_`
|
||||
bool xstage_pinned_ = false;
|
||||
int64_t xstage_cap_ = 0;
|
||||
uint64_t xstage_blob_ = 0;
|
||||
int64_t exchanges_ = 0;
|
||||
std::atomic<int64_t> file_reads_{0};
|
||||
int64_t reads_ = 0;
|
||||
#if defined(_WIN32)
|
||||
void* file_ = nullptr;
|
||||
void* mapping_ = nullptr;
|
||||
#else
|
||||
int fd_ = -1;
|
||||
#endif
|
||||
};
|
||||
|
||||
// ================================ THE RESIDENT ARENA (R2.1) ================================
|
||||
//
|
||||
// **THE MMAP ABOVE IS THE REVIEW'S FINDING C1 AND IT IS WORTH 2.2x.** Read the comment on `FileExpertSource`
|
||||
// about the page cache holding all 34 GB: that is true of the expert file ALONE, and it is not what this engine
|
||||
// does. The PLE/n-gram shard is a 26.8 GB file that the engine also maps, so 34 GB of experts plus 26.8 GB of
|
||||
// n-gram is 60.8 GB of mapped, file-backed pages on a 63 GB machine - and file-backed pages are exactly the ones
|
||||
// the OS drops from the standby list when it wants memory. The expert stream then re-faults from disk.
|
||||
//
|
||||
// Measured, this round: the pool runs at **~19 GB/s in the engine against 42.8 GB/s in `bench/micro/cpu_s2.cpp`
|
||||
// on the same machine, reading the same 34 GB**. The micro does `std::fread` into a heap arena and reads
|
||||
// ordinary (anonymous, resident) memory; the engine reads `MapViewOfFile`. That is the whole difference, and it
|
||||
// is why this class exists.
|
||||
//
|
||||
// It reads `experts.bin` into a `PinnedArena` once at startup, so the expert stream comes from anonymous memory
|
||||
// the OS has no cheaper reason to evict. `PinnedArena` also tries `cudaHostRegister`, which the GPU needs for
|
||||
// Phase 3's cache fills and the CPU/PCIe miss split - but registration is best-effort and reported, not assumed.
|
||||
class ArenaExpertSource : public ExpertSource {
|
||||
public:
|
||||
ArenaExpertSource() = default;
|
||||
~ArenaExpertSource() override;
|
||||
ArenaExpertSource(const ArenaExpertSource&) = delete;
|
||||
ArenaExpertSource& operator=(const ArenaExpertSource&) = delete;
|
||||
|
||||
/// Allocates and loads `<pack_dir>/experts.bin`. Prints nothing; the caller reports `note()` and the load
|
||||
/// rate, because those are the two numbers that say whether the arena is the one that was asked for.
|
||||
bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err,
|
||||
uint64_t max_pinned_bytes = 0, const std::string& shared_arena_file = {});
|
||||
/// Plan v0.3 P6: a native pack without experts.bin takes its experts from the model's GGUF: `native` is the
|
||||
/// --native shard, and native_experts.txt names the other shards beside it (per layer, or per role in v4).
|
||||
void set_gguf(const std::string& native) { gguf_ = native; }
|
||||
void close();
|
||||
|
||||
bool mapped() const { return base_ != nullptr; }
|
||||
int64_t blobs() const { return blobs_; }
|
||||
const uint8_t* blob(int64_t layer, int64_t expert) override;
|
||||
int64_t reads() const { return reads_; }
|
||||
bool pinned(int64_t layer, int64_t expert) const override;
|
||||
const uint8_t* device_alias(int64_t layer, int64_t expert) const override;
|
||||
void prefetch(int64_t layer, int64_t expert) override;
|
||||
uint64_t release(int64_t layer, int64_t expert) override;
|
||||
|
||||
/// What backing was obtained and why, for the startup print. "The engine adapts to the machine it is on" is
|
||||
/// only true if the engine says what it got.
|
||||
const std::string& note() const { return note_; }
|
||||
/// #633: set by `open` when the RAM available is less than the arena needs (a recommendation; it still loads)
|
||||
const std::string& ram_warning() const { return ram_warning_; }
|
||||
double load_gib_per_second() const { return gib_per_s_; }
|
||||
// Loader fix: the load, split. `load_seconds()` is the wall clock of the load loop; the other two are
|
||||
// sums over the reader threads (see LoadStats), so on their own they say how much of that wall was spent
|
||||
// waiting for the disk and how much in memcpy + FNV-1a.
|
||||
double load_seconds() const { return load_seconds_; }
|
||||
double load_read_seconds() const { return load_read_s_; }
|
||||
double load_copy_seconds() const { return load_copy_s_; }
|
||||
|
||||
private:
|
||||
void* arena_ = nullptr; ///< the PinnedArena, owned
|
||||
void* map_ = nullptr; ///< STRATA_ARENA_MMAP: the arena file, mapped read-only (not the PinnedArena)
|
||||
uint64_t map_bytes_ = 0;
|
||||
std::vector<const uint8_t*> dev_slice_; ///< device alias of each registered slice (or of the whole range)
|
||||
uint64_t slice_bytes_ = 0;
|
||||
const uint8_t* base_ = nullptr;
|
||||
int64_t blobs_ = 0;
|
||||
int64_t n_expert_ = 0;
|
||||
int64_t reads_ = 0;
|
||||
std::string note_;
|
||||
std::string ram_warning_;
|
||||
double gib_per_s_ = 0.0;
|
||||
double load_seconds_ = 0.0;
|
||||
double load_read_s_ = 0.0;
|
||||
double load_copy_s_ = 0.0;
|
||||
uint64_t pinned_bytes_ = 0;
|
||||
std::string gguf_;
|
||||
};
|
||||
|
||||
/// Plan v0.3 P6: checks native_experts.txt's GGUF spans against the files, before anything is read: each layer's
|
||||
/// gate/up/down at its recorded (file, offset) must be that tensor (`blk.L.ffn_<role>_exps.weight`), of the
|
||||
/// layout's type and dimensions, and inside the file. `native` is the --native shard (see set_gguf).
|
||||
bool check_experts_gguf(const std::string& native, const strata::kernels::cpu::ExpertLayout& lay, std::string& err);
|
||||
/// Fills `dst` (lay.total bytes, the experts.bin layout) from the GGUF files, one role at a time.
|
||||
/// `unbuffered`: each chunk read past the file cache (Windows).
|
||||
LoadStats load_experts_gguf(const std::string& native, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay,
|
||||
int threads, bool unbuffered = false);
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,117 +0,0 @@
|
||||
// include/strata/core/graph.hpp - P2.S5: the GraphRegistry.
|
||||
//
|
||||
// `GraphRegistry`: capture/replay wrappers keyed by `(layer_type, n_tokens)`, with static input/output
|
||||
// buffers at fixed addresses.
|
||||
//
|
||||
// THREE THINGS ARE BAKED INTO THIS INTERFACE, and each one is a measurement rather than a preference. All
|
||||
// three come from `bench/micro/graph_capture.cu`, which was written to answer the phase's own instruction -
|
||||
// "verify on the installed CUDA version with a minimal test before building on it".
|
||||
//
|
||||
// 1. **THE WAIT MUST POLL THE DRIVER, NOT MEMORY.** The phase's host loop says "spin on
|
||||
// doorbell_seq == expected ... no cudaStreamSynchronize anywhere". A spin that only reads memory NEVER
|
||||
// RUNS THE KERNEL: 5,907,703 spins over 500 ms, and the datum flips to 1 the instant anything calls into
|
||||
// the driver and never before. On Windows the display driver model BATCHES command submission, and a
|
||||
// thread that only reads memory gives it no reason to flush. Hence `wait_ms`, which polls an event -
|
||||
// a QUERY and not a blocking sync, so P2.X3's "zero synchronization calls in the layer loop" still holds,
|
||||
// and it costs 0.021 ms.
|
||||
//
|
||||
// 2. **A GRAPH RE-READS ITS INPUT BUFFERS AT REPLAY, BUT NOT ITS KERNEL ARGUMENTS.** Verified: eight
|
||||
// replays with a different pinned input each time all tracked correctly, so the data path is live; but a
|
||||
// kernel argument is copied into the node at capture and is never re-read. **Anything that changes per
|
||||
// step - a position, a page-table base, a token id - must be DATA in a device buffer, never an argument.**
|
||||
// This is the phase's "graph capture with pointers that change between steps silently replays stale
|
||||
// addresses" hazard, and it now has a measurement behind it.
|
||||
//
|
||||
// 3. **FIXED ADDRESSES ARE THE CALLER'S OBLIGATION.** The registry cannot check them. Every buffer a
|
||||
// captured body touches must be allocated before `record` and never reallocated; the registry holds the
|
||||
// graph, not the memory.
|
||||
//
|
||||
// What the registry is FOR: a layer's ops are the same every token, so recording them once and replaying
|
||||
// removes the per-call host cost of submitting them individually. Measured, that cost is 10-22 us PER CALL
|
||||
// into the driver on this machine, and a layer with 8 submissions is ~0.1 ms of round trip.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// The two attention families. `docs/semantics.md`: 36 GDN layers and 12 QSA, at indices 3, 7, ... 47.
|
||||
enum class LayerType : int { GDN = 0, QSA = 1 };
|
||||
inline const char* to_string(LayerType t) { return t == LayerType::GDN ? "GDN" : "QSA"; }
|
||||
|
||||
/// One recorded graph. Move-only: it owns a `cudaGraphExec_t` and an event, and two owners would
|
||||
/// double-destroy.
|
||||
class CapturedGraph {
|
||||
public:
|
||||
CapturedGraph() = default;
|
||||
~CapturedGraph() { reset(); }
|
||||
CapturedGraph(const CapturedGraph&) = delete;
|
||||
CapturedGraph& operator=(const CapturedGraph&) = delete;
|
||||
CapturedGraph(CapturedGraph&& o) noexcept { *this = std::move(o); }
|
||||
CapturedGraph& operator=(CapturedGraph&& o) noexcept;
|
||||
|
||||
/// Start recording everything the caller launches into `stream`.
|
||||
bool begin(void* stream, std::string& err);
|
||||
|
||||
/// Stop recording, instantiate, and record the completion event. A capture that produced ZERO nodes is
|
||||
/// reported as an error: it means the body did nothing, which is a wiring mistake and NOT an empty graph
|
||||
/// to be replayed happily forever.
|
||||
bool end(void* stream, std::string& err);
|
||||
|
||||
/// Replay. Does not synchronise.
|
||||
bool launch(void* stream, std::string& err) const;
|
||||
|
||||
/// The host loop's wait: poll `done_` until it completes or `timeout_ms` elapses. Returns false on
|
||||
/// timeout, which the caller must treat as a hang and not as "probably fine". See NOTE 1 above for why
|
||||
/// this exists instead of a memory spin.
|
||||
bool wait_ms(int timeout_ms) const;
|
||||
|
||||
size_t nodes() const { return nodes_; }
|
||||
bool valid() const { return exec_ != nullptr; }
|
||||
|
||||
private:
|
||||
void reset();
|
||||
cudaGraph_t graph_ = nullptr;
|
||||
cudaGraphExec_t exec_ = nullptr;
|
||||
cudaEvent_t done_ = nullptr;
|
||||
size_t nodes_ = 0;
|
||||
};
|
||||
|
||||
/// Capture-once, replay-many, keyed by `(layer_type, n_tokens)`.
|
||||
///
|
||||
/// `record` is given a CALLABLE that launches the layer's ops. On the first call for a key it captures;
|
||||
/// afterwards it returns the cached graph and does NOT run the callable - so a caller that mutates state
|
||||
/// inside the body will be surprised, which is why the body must only launch.
|
||||
class GraphRegistry {
|
||||
public:
|
||||
explicit GraphRegistry(void* stream) : stream_(stream) {}
|
||||
|
||||
/// Capture `body` for `key` if it is not already recorded. Returns false and fills `err` on failure.
|
||||
/// Recording the same key twice is a no-op and is NOT an error - that is the point of a registry, and a
|
||||
/// regression test asserts that the body runs exactly once across many calls.
|
||||
bool record(LayerType type, int n_tokens, const std::function<void()>& body, std::string& err);
|
||||
|
||||
const CapturedGraph* find(LayerType type, int n_tokens) const;
|
||||
|
||||
/// Launch and wait, in that order, the two things the host loop does per layer.
|
||||
bool launch(LayerType type, int n_tokens, int timeout_ms, std::string& err) const;
|
||||
|
||||
size_t size() const { return graphs_.size(); }
|
||||
/// How many times a BODY was actually captured. With a working cache this equals `size()`.
|
||||
size_t captures() const { return captures_; }
|
||||
|
||||
private:
|
||||
using Key = std::pair<int, int>;
|
||||
void* stream_ = nullptr;
|
||||
std::map<Key, CapturedGraph> graphs_;
|
||||
size_t captures_ = 0;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,41 +0,0 @@
|
||||
// include/strata/core/hit_hook.hpp - R4.2c: the seam between the host loop and the VRAM expert tier.
|
||||
//
|
||||
// **IT IS ITS OWN HEADER BECAUSE BOTH SIDES NEED IT AND NEITHER SHOULD OWN IT.** `session.hpp` declares the
|
||||
// loop that calls the hook; `expert_source.hpp` declares the implementation that answers it. Putting the type
|
||||
// in either one makes the other include a header it has no other use for, and the loop knowing what an expert
|
||||
// cache is (or the adapter knowing what a graph is) is exactly the coupling this seam exists to avoid.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// **TWO PHASES, AND THE SPLIT IS THE WHOLE POINT.** `Launch` runs BEFORE the CPU pool and `Combine` runs
|
||||
/// AFTER the misses have been copied into `parts`. That ordering is what lets the GPU's resident experts run
|
||||
/// at the same time as the CPU's misses instead of after them:
|
||||
///
|
||||
/// ring -> hits(Launch) [GPU: quantize + grouped experts into `hit_out`]
|
||||
/// -> pool() [CPU: the misses, CONCURRENT with the GPU]
|
||||
/// -> H2D misses into `parts`
|
||||
/// -> hits(Combine) [GPU: parts += hit_out]
|
||||
/// -> post[l]
|
||||
///
|
||||
/// **MEASURED, AND WHY IT IS NOT THE OBVIOUS ORDER.** The first version called the hit path once, after the
|
||||
/// pool, writing straight into `parts`. The drain duly fell **18.2 -> 10.2 ms** - the CPU really was doing
|
||||
/// half the experts - and **the token did not move at all**, because the GPU's half had simply been moved onto
|
||||
/// the critical path behind the CPU's instead of beside it. A second buffer and one `add_inplace` buy the
|
||||
/// overlap back.
|
||||
enum class HitPhase { Launch, Combine };
|
||||
|
||||
/// `ids` AND `k` ARE THE ROUTER'S OWN OUTPUT, AND THEY ARE WHY THIS HOOK TAKES ARGUMENTS AT ALL.
|
||||
///
|
||||
/// The first version took only `(user, stream, phase)` and left the hit/miss decision inside the pool
|
||||
/// callback - which runs AFTER `Launch`. So `Launch` read the hit list from the PREVIOUS layer and computed
|
||||
/// the previous layer's experts into the current layer's rows. It produced a token, the timings looked
|
||||
/// plausible, and **C1 moved from mean KL 9.69e-02 to 1.03e+00 and top-1 from 0.867 to 0.333.** The decision
|
||||
/// has to happen in `Launch`, on the ids the doorbell published for THIS layer, and the pool then consumes it.
|
||||
///
|
||||
/// A null `HitFn` means "no VRAM tier" - the default, and what every caller had before R4.
|
||||
using HitFn = void (*)(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k);
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,658 +0,0 @@
|
||||
// include/strata/core/layer.hpp - one GDN LAYER, composed. P2.S5's mixer.
|
||||
//
|
||||
// This is the first place in the engine where the kernels are COMPOSED rather than tested individually, so
|
||||
// the thing it has to get right is the ORDER and the buffers, not the arithmetic. Every kernel it calls is
|
||||
// parity-tested on its own; what can go wrong here is a buffer sized for the wrong shape, a step done in the
|
||||
// wrong order, or a value that should have been converted and was not.
|
||||
//
|
||||
// `ref/gdn.py::gdn_decode` is the specification, and the order below is its docstring verbatim:
|
||||
//
|
||||
// qkv = wqkv @ x (10240 = q|k|v, each a contiguous run of 128-wide heads)
|
||||
// conv -> SiLU (SiLU is applied to the WHOLE conv output before the split)
|
||||
// q,k = l2_norm (v is NOT normalised)
|
||||
// beta = sigmoid(wbeta @ x)
|
||||
// gate = softplus(walpha @ x + dt) * ssm_a
|
||||
// recurrent step
|
||||
// y = rms_norm(o, ssm_norm) * sigmoid(z) <- SIGMOID for qwen4exp; qwen3.5 used SiLU
|
||||
// out = ssm_out @ y
|
||||
//
|
||||
// FOUR THINGS IN THAT ORDER ARE EASY TO READ PAST, and each produces a plausible number:
|
||||
//
|
||||
// * **SiLU is applied BEFORE the split**, to the whole 10240-wide conv output. Applying it only to q and
|
||||
// k, or after the reshape, is the same arithmetic on different data.
|
||||
// * **v is NOT normalised.** `l2_norm` applies to q and k only - two rows of 16 heads, not the 48 of v.
|
||||
// * **the `/hc`-style scale on q is `1/sqrt(S)`**, applied by the CALLER because `ref/gdn.py` says the two
|
||||
// llama.cpp paths apply it in different places. It goes on AFTER the norm.
|
||||
// * **the state is transposed** relative to the reference: (S, h_v, S) here, (S, S, h_v) there. That is
|
||||
// `gdn.hpp`'s choice and it is the reason `gdn_step`'s arguments are laid out as they are.
|
||||
//
|
||||
// THE ACTIVATIONS FOLLOW THE CONTRACT, which is why three different GEMVs appear below: `attn_qkv`,
|
||||
// `attn_gate` and `ssm_out` are K-quants (Q8_K), while `ssm_alpha` and `ssm_beta` are BF16 (bf16). Using one
|
||||
// activation format for all five would be a 0.66-1.41% error on the three that matter - measured, in
|
||||
// `s_gemv_q8k_parity` and `bf16_gemv_parity`.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/layout.hpp"
|
||||
#include "strata/core/weights.hpp"
|
||||
|
||||
#include "strata/kernels/gr.hpp"
|
||||
#include "strata/kernels/kv_stream.hpp"
|
||||
#include "strata/kernels/ngram.hpp"
|
||||
#include "strata/kernels/ple.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// Select pinned CUDA BF16/F32 projections for SSM gates, routing and the sparse indexer.
|
||||
/// Configure before session capture; captured graphs retain the selected implementation.
|
||||
/// Does not change GR, PLE or the shared expert's scalar gate.
|
||||
void layer_set_native_bf16(bool enabled);
|
||||
// Diagnostic vector-attention adapter; configure before capture, context <=256.
|
||||
void layer_set_native_flash_attn_short(bool enabled);
|
||||
|
||||
/// Every buffer one GDN layer needs, carved from an arena ONCE. Sizes are functions of `ModelGeometry`, and
|
||||
/// `gdn_buffers_bytes` returns the total so a caller can size the arena before committing.
|
||||
struct GdnBuffers {
|
||||
// the activation, in the formats the contract asks for. BOTH quantized images are produced for every
|
||||
// layer, because WHICH ONE A WEIGHT WANTS IS A PROPERTY OF THE WEIGHT and the pack mixes them by layer -
|
||||
// `attn_qkv` alone is IQ4_XS on 13 layers, Q3_K on 18, Q4_K on 4 and S2 on 1.
|
||||
uint8_t* x_q8k = nullptr; ///< n_embd, block_q8_K
|
||||
uint8_t* x_q8_0 = nullptr; ///< n_embd, block_q8_0
|
||||
uint16_t* x_bf16 = nullptr; ///< n_embd, bf16 bits
|
||||
|
||||
// the qkv path
|
||||
float* qkv = nullptr; ///< conv_channels
|
||||
float* conv_out = nullptr; ///< conv_channels
|
||||
float* h = nullptr; ///< conv_channels = silu(conv_out), and it IS q|k|v in place
|
||||
|
||||
// the per-head scalars and the recurrence
|
||||
float* alpha = nullptr; ///< h_v
|
||||
float* beta = nullptr; ///< h_v
|
||||
float* gate = nullptr; ///< h_v
|
||||
float* o = nullptr; ///< h_v * S
|
||||
float* z = nullptr; ///< value_dim
|
||||
float* y = nullptr; ///< value_dim
|
||||
uint8_t* y_q8k = nullptr; ///< value_dim, block_q8_K
|
||||
uint8_t* y_q8_0 = nullptr; ///< value_dim, block_q8_0
|
||||
|
||||
// the recurrent state, which outlives the call
|
||||
float* state = nullptr; ///< S * h_v * S
|
||||
float* conv_state = nullptr; ///< conv_channels * (d_conv-1)
|
||||
};
|
||||
|
||||
/// Bytes needed for `b`, 16-byte aligned between regions.
|
||||
uint64_t gdn_buffers_bytes(const ModelGeometry& g);
|
||||
/// Carves `base` (which must be DEVICE memory) into `b`. Returns the bytes used.
|
||||
uint64_t gdn_buffers_init(const ModelGeometry& g, void* base, GdnBuffers& b);
|
||||
/// Zeroes the recurrent and conv state, so a fresh sequence starts from the reference's own `zeros()`.
|
||||
void gdn_buffers_zero_state(const GdnBuffers& b, const ModelGeometry& g, void* stream);
|
||||
|
||||
/// `Mixed` (n_embd f32) through one GDN layer to `out` (n_embd f32). `state` and `conv_state` are updated.
|
||||
///
|
||||
/// `layer` selects the weights; `tables` must outlive the call. Returns false and fills `err` if a tensor is
|
||||
/// missing - which is a wiring mistake here rather than a shape problem, because `check_layer` already
|
||||
/// asserted the shapes at load time.
|
||||
bool gdn_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const GdnBuffers& b,
|
||||
const float* mixed, float* out, void* stream, std::string& err);
|
||||
|
||||
// ================================ the MoE block ================================
|
||||
|
||||
struct Doorbell; // defined with the rest of the handoff, below; only a pointer is needed here
|
||||
|
||||
/// Buffers for the MoE block, on EVERY layer.
|
||||
struct MoEBuffers {
|
||||
uint16_t* x_bf16 = nullptr; ///< n_embd, for the ROUTER's weight, which is BF16
|
||||
uint16_t* x_f16 = nullptr; ///< n_embd, for the SHARED EXPERT's weights (see the note in `moe_layer`)
|
||||
float* logits = nullptr; ///< n_expert
|
||||
int* ids = nullptr; ///< k
|
||||
float* weights = nullptr; ///< k
|
||||
float* shared = nullptr; ///< n_embd
|
||||
float* sh_scratch = nullptr; ///< shared_expert_scratch_bytes(n_ff): the shared expert's own scratch
|
||||
uint8_t* x_q8_0 = nullptr; ///< n_embd, block_q8_0 - the shared expert's weights want Q8_0 on the layers
|
||||
///< whose types are Q2_0/Q4_0/Q5_0/Q8_0/IQ4_NL, which is most of them
|
||||
uint8_t* x_q8k = nullptr; ///< n_embd, block_q8_K - and Q8_K on the K-quant ones
|
||||
};
|
||||
|
||||
uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k);
|
||||
uint64_t moe_buffers_init(const ModelGeometry& g, int64_t k, void* base, MoEBuffers& b);
|
||||
|
||||
/// The MoE block: router -> (the caller's expert outputs) -> combine.
|
||||
///
|
||||
/// `parts` is (k, n_embd) device f32 and is **filled by the CALLER** - by the CPU pool and the VRAM-resident
|
||||
/// experts. That split is the architecture's, not a shortcut: the routed experts are the only part of the
|
||||
/// model that does not fit in VRAM, and every design decision in this engine exists to keep them out of the
|
||||
/// graph. This function therefore owns the two ends - which experts, and how their outputs are combined -
|
||||
/// and deliberately not the middle.
|
||||
///
|
||||
/// TWO ACTIVATION FORMATS AGAIN, and the router's is the one that matters most:
|
||||
///
|
||||
/// * `ffn_gate_inp.weight` is BF16, so the router sees a BF16 activation. `ref/moe.py` L88-92 calls this
|
||||
/// "the highest-consequence rounding in the model": the logits were measured **8.100e-03** off without it,
|
||||
/// which is enough to FLIP a top-10 selection - and a flipped selection is not a small numeric error, it
|
||||
/// is a different expert reading a different weight.
|
||||
/// * the shared expert's weights are Q3_K/IQ4_XS/Q5_0 IQ-quants whose contract is Q8_K, which
|
||||
/// `shared_expert` does not implement; it takes fp16. That is the known gap its own header documents and
|
||||
/// `docs/activation-contract.md` names as outstanding.
|
||||
bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
|
||||
const float* x, const float* parts, float* out, void* stream, std::string& err,
|
||||
const Doorbell* db = nullptr);
|
||||
|
||||
// ================================ THE MOE, SPLIT AT THE ROUTER ================================
|
||||
//
|
||||
// **THE SPLIT EXISTS BECAUSE THE ONE-LAYER DELAY WAS NOT A TIMING CHANGE.** `moe_layer` is
|
||||
// `route -> publish -> shared expert -> combine`, and `combine` multiplies `parts` by THIS layer's
|
||||
// `b.weights`. So `parts` must be THIS layer's expert outputs. A host loop that hands layer `l`'s pool
|
||||
// result to layer `l+1` computes `sum_j w_{l+1}[j] * expert_{ids_l,j}(x_l)` while the model is
|
||||
// `sum_j w_l[j] * expert_{ids_l,j}(x_l)` - **both the expert selection and the input one layer stale while the
|
||||
// weights are current** - and `session.hpp` states the contract it violates: the doorbell is "a change to WHEN
|
||||
// the host runs, not to what this function computes".
|
||||
//
|
||||
// The one-layer delay was introduced for a real reason - it is the only way to overlap a CPU pool with a GPU
|
||||
// that has already queued the combine - and the fix is to split the GRAPH, not to delay the answer:
|
||||
//
|
||||
// block_layer_pre[l] attn -> mixer -> gr_write -> ffn gr_read -> moe_route [rings the doorbell]
|
||||
// ... the host runs the pool here, on the ids `moe_route` just published ...
|
||||
// block_layer_post[l] moe_finish -> gr_write
|
||||
//
|
||||
// `post[l]` is launched AFTER the pool returns, so it sees layer `l`'s experts with layer `l`'s weights, and it
|
||||
// is still a captured graph. What it costs is the overlap: the window is now whatever GPU work follows the
|
||||
// ring inside `pre[l]` - the shared expert and nothing else, because everything after the combine depends on
|
||||
// `parts`. **A per-layer CPU pool cannot be hidden behind a strictly serial residual chain**, which is why
|
||||
// Phase 3's VRAM expert cache is the answer to the CPU term and the doorbell is not.
|
||||
|
||||
/// The routing half: bf16 activation, the router GEMV, top-k, and the doorbell publish. Ends with the ring
|
||||
/// rung, so a host that sees it knows `h_x_f`/`h_ids`/`h_weights` are in place.
|
||||
bool moe_route(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
|
||||
const float* x, void* stream, std::string& err, const Doorbell* db = nullptr);
|
||||
/// The verify window's n tokens routed at once (see layer.cpp); bitwise per token what `moe_route` gives.
|
||||
bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
|
||||
const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err);
|
||||
|
||||
/// The finishing half: the shared expert and the combination.
|
||||
///
|
||||
/// **`parts` MUST BE THE EXPERTS THIS LAYER'S OWN ROUTER SELECTED.** It is combined with `b.weights`, which
|
||||
/// `moe_route` wrote for THIS layer. Passing the previous layer's vectors is the L100 bug: it produces a
|
||||
/// finite, fluent, deterministic token that is not the model's.
|
||||
bool moe_finish(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
|
||||
const float* x, const float* parts, float* out, void* stream, std::string& err);
|
||||
|
||||
/// Plan v0.3 P3: the two parts of `moe_finish` separately. `moe_shared` computes the shared expert into
|
||||
/// `b.shared` and needs only `x`; `moe_combine_parts` combines `parts` with `b.weights` and `b.shared`.
|
||||
/// `moe_finish` is exactly `moe_shared` followed by `moe_combine_parts`.
|
||||
bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b,
|
||||
const float* x, void* stream, std::string& err);
|
||||
bool moe_combine_parts(const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* parts,
|
||||
float* out, void* stream, std::string& err);
|
||||
|
||||
/// Plan v0.3 P3 (default ON): the shared expert runs at the END OF `pre[l]`, after the doorbell has rung, so
|
||||
/// the GPU computes it while the host runs the CPU pool; `post[l]` then only combines. Same kernels on the
|
||||
/// same inputs in the same stream order relative to their consumers, so the result is bitwise unchanged.
|
||||
/// Must be set before capture. `false` restores the shared expert inside `post[l]` (A/B arm).
|
||||
void layer_set_shared_early(bool enabled);
|
||||
bool layer_shared_early();
|
||||
|
||||
// ================================ the QSA mixer ================================
|
||||
|
||||
/// THE PERSISTENT STATE OF ONE QSA LAYER FOR ONE SEQUENCE: the KV cache, the indexer's pooled keys, the rope
|
||||
/// tables, and the per-token step buffer. None of it is scratch - it survives every token.
|
||||
///
|
||||
/// `max_cells` is the sequence capacity the arena was sized for, and it fixes the rope table's length: a table
|
||||
/// shorter than the sequence would have `rope_neox_apply` read past it, which is a wrong rotation rather than a
|
||||
/// fault.
|
||||
struct QsaState {
|
||||
uint16_t* k_pool = nullptr; ///< [page][kv_head][page_size][head_dim] fp16 (null in INT8 mode)
|
||||
uint16_t* v_pool = nullptr;
|
||||
/// Plan v0.3 P7: INT8 KV (qsa_set_kv_int8). Codes [page][kv_head][page_size][head_dim], one FP16 scale per 64.
|
||||
bool kv_int8 = false;
|
||||
int8_t* k_q = nullptr;
|
||||
int8_t* v_q = nullptr;
|
||||
uint16_t* k_scale = nullptr;
|
||||
uint16_t* v_scale = nullptr;
|
||||
/// PR #21: Q4_0 KV with Walsh-Hadamard rotation (qsa_set_kv_q4, kv_q4.hpp): 144 B per cell and head
|
||||
bool kv_q4 = false;
|
||||
uint8_t* k_q4 = nullptr;
|
||||
uint8_t* v_q4 = nullptr;
|
||||
/// Hybrid K8V4: K in INT8 (unrotated - the scores stay exact), V in rotated Q4_0 (kv_q4.hpp): 816 B per cell.
|
||||
/// Uses k_q/k_scale + v_q4. Mode 0 only (no KV streaming, no ring); under this setting the MTP drafter's
|
||||
/// ring state stays plain INT8, so the block movers never see the hybrid layout.
|
||||
bool kv_hybrid = false;
|
||||
/// K and V go through kv_q4.hpp's Walsh-Hadamard rotation before they are stored, the queries too, the output
|
||||
/// back: always for Q4_0, for INT8 by qsa_set_kv_int8_rotate (spreads outlier channels over the scale groups)
|
||||
bool kv_rot = false;
|
||||
int32_t* page_table = nullptr; ///< (n_pages,) logical page -> physical page (-1: not resident, streamed)
|
||||
int64_t n_pages = 0;
|
||||
int64_t max_cells = 0;
|
||||
|
||||
/// KV STREAMING (docs/kv-streaming-design.md, `kv_stream.hpp`). `kv_mode` 0: every page in VRAM, identity
|
||||
/// table (n_slots == n_pages, no host copy). 1: streamed - the authoritative K/V in `host`, `n_slots` pages
|
||||
/// in VRAM, `map` resolves the selection's blocks on device. 2: a ring (the MTP drafter's window) - `n_slots`
|
||||
/// pages at `block % n_slots`, with the host copy for a resume. The pool pointers above point at the slots.
|
||||
int kv_mode = 0;
|
||||
int64_t n_slots = 0;
|
||||
strata::kernels::KvHostPools host;
|
||||
strata::kernels::KvStreamMap map;
|
||||
int64_t idx_pooled_rows = 0; ///< rows of `idx_pooled` (a ring, which has no indexer, keeps 2)
|
||||
|
||||
float* idx_tail = nullptr; ///< (idx_block - 1, idx_dim): the raw tail of the block being filled
|
||||
float* idx_dead = nullptr; ///< (idx_dim,): the spare slot's key, CONSTANT for the sequence
|
||||
float* idx_pooled = nullptr; ///< (max_cells/idx_block + 2, idx_dim)
|
||||
int32_t* idx_block_pos = nullptr;
|
||||
|
||||
float* cos_tab = nullptr; ///< (max_cells, n_rot/2), built on the HOST in float64
|
||||
bool owns_rope = false; ///< built the table above (not borrowed with share_rope): it releases it
|
||||
float* sin_tab = nullptr;
|
||||
|
||||
/// THE PER-TOKEN COUNTS, IN DEVICE MEMORY - the whole reason this layer can be a graph. `qsa_step_fill`
|
||||
/// computes all four from the position, so one H2D per token updates every count every kernel needs.
|
||||
int32_t* step = nullptr;
|
||||
int32_t* attention_status = nullptr; ///< per-layer device status, captured D2H to host_step[kStepCount]
|
||||
/// The rope positions, (n_head,) int32, all equal to the current position. `rope_neox_apply` reads its
|
||||
/// positions from the DEVICE, so a host scalar here would be an illegal access (and uncapturable).
|
||||
int32_t* pos_dev = nullptr;
|
||||
|
||||
/// PINNED HOST STAGING AT FIXED ADDRESSES, and they are not an optimisation. The uploads in `qsa_layer`
|
||||
/// copy FROM these, so a CUDA graph captures the SOURCE POINTER - and the first version of the layer filled
|
||||
/// a stack array and a local `std::vector` instead. Those addresses are dead by the time the graph is
|
||||
/// replayed, which is this project's own recorded pitfall ("graph inputs live at fixed addresses") walked
|
||||
/// straight into: the replay would read whatever the stack held, and the step counts would be wrong in a way
|
||||
/// that looks like a working token.
|
||||
///
|
||||
/// Pinned as well as fixed, because a pageable source would make `cudaMemcpyAsync` a synchronous staged
|
||||
/// copy and give back the overlap the doorbell protocol exists for.
|
||||
int32_t* host_step = nullptr; ///< (kStepCount + 1,) pinned; final element is attention status
|
||||
int32_t* host_pos = nullptr; ///< (n_head,) pinned
|
||||
};
|
||||
|
||||
/// Plan v0.3 P7: the RoPE cos/sin table (max_cells x n_rot/2 x 2 floats, 64 MiB at 262K) is identical in every
|
||||
/// QSA layer. `with_rope = false` sizes a state that borrows it; `share_rope` points `st` at another state's table
|
||||
/// instead of building a copy (the session builds it once, in the first QSA layer).
|
||||
uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_rope = true, int64_t ring_cells = 0);
|
||||
/// KV streaming: keep `cells` cells of each QSA layer in VRAM and the rest in pinned host memory (0: all in VRAM,
|
||||
/// the default). Set before sizing and initializing the session; a context that fits in `cells` is not streamed.
|
||||
/// Also puts the MTP drafter's K/V in a ring of its window (`ring_cells` of qsa_state_bytes/init; -1 forces a fully
|
||||
/// resident state).
|
||||
void qsa_set_kv_resident(int64_t cells);
|
||||
int64_t qsa_kv_resident();
|
||||
/// Whether KV streaming applies to this geometry. Dense attention (Qwen3.6, no indexer) reads every cell every
|
||||
/// token, so streaming would copy the whole KV over PCIe per token: false, with `why` for the CLI's refusal.
|
||||
/// `qsa_state_init` refuses the same way as a backstop.
|
||||
bool qsa_kv_streaming_applies(const ModelGeometry& g, std::string& why);
|
||||
/// The fewest resident cells a streamed layer may have: one verify window's selections (8 queries x 2,051 cells
|
||||
/// in whole blocks) must fit at once, with room to spare.
|
||||
int64_t qsa_kv_resident_min();
|
||||
/// Pinned host bytes the streamed states hold (their host copies).
|
||||
uint64_t qsa_kv_host_bytes();
|
||||
/// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and
|
||||
/// initializing the session; default off until gate G-C accepts it.
|
||||
void qsa_set_kv_int8(bool enabled);
|
||||
/// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1)
|
||||
void qsa_set_kv_int8_rotate(bool enabled);
|
||||
bool qsa_kv_int8();
|
||||
/// PR #21: store K/V as Q4_0 after a Hadamard rotation (`--kv q4_0`): 576 B per cell, vs 1,056 in INT8.
|
||||
void qsa_set_kv_q4(bool enabled);
|
||||
bool qsa_kv_q4();
|
||||
/// Hybrid K8V4 (`--kv k8v4`): K in INT8, V in rotated Q4_0 - 816 B per cell. Not with --kv-resident.
|
||||
void qsa_set_kv_hybrid(bool enabled);
|
||||
bool qsa_kv_hybrid();
|
||||
/// The state's KV format for the block-moving functions of kv_stream.hpp (kKvF16 / kKvInt8 / kKvQ4).
|
||||
inline int qsa_kv_format(const QsaState& st) {
|
||||
// A hybrid K8V4 state is mode 0 only and never reaches the block movers; refuse rather than let it
|
||||
// fall through to kKvF16 - a wrong layout silently applied is worse than a hard stop (PR review).
|
||||
if (st.kv_hybrid) {
|
||||
std::fprintf(stderr, "strata: qsa_kv_format: a hybrid K8V4 state must never reach the block movers\n");
|
||||
std::exit(1); // the kernels' own "unsupported geometry" convention (kv_q8.cu, qsa_decode_attn.cu)
|
||||
}
|
||||
return st.kv_q4 ? strata::kernels::kKvQ4 : st.kv_int8 ? strata::kernels::kKvInt8 : strata::kernels::kKvF16;
|
||||
}
|
||||
uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st,
|
||||
const QsaState* share_rope = nullptr, int64_t ring_cells = 0);
|
||||
/// KV streaming: the pools a reader sees (the VRAM slots) and, when streamed, make the selection's blocks resident.
|
||||
strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st);
|
||||
void qsa_kv_resolve(const QsaState& st, const ModelGeometry& g, const int32_t* ids, const int32_t* steps, int64_t n_q,
|
||||
int64_t cap, void* stream);
|
||||
/// Zeroes the pools AND the indexer, so a fresh sequence matches the reference's own `zeros()`. The KV pool
|
||||
/// matters even for cells that are never attended, because `kv_gather` reads whatever the selection names.
|
||||
void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream);
|
||||
|
||||
// ================================ PER-STAGE TIMING, DEBUG ONLY ================================
|
||||
//
|
||||
// Event pairs around the pieces of `block_layer_pre`/`_post`, recorded per (layer, stage) and read once at the
|
||||
// end so that **NOTHING IS SYNCHRONISED DURING THE RUN** - a per-stage sync would serialise the pipeline and
|
||||
// report the serialised time. **CAPTURED GRAPHS CANNOT USE IT**: an event record inside a stream capture is
|
||||
// silently dropped, so this is for the `--no-capture` path only.
|
||||
//
|
||||
// It exists because the engine spends ~1.047 ms per layer with the experts off while every cost model in
|
||||
// `bench/` predicts less than half that, and the gap has to be attributed before it can be attacked.
|
||||
// slot 0 gr_read(attn) 1 the attention block 2 gr_write(attn) 3 gr_read(ffn) 4 router
|
||||
// slot 5 moe_finish 6 gr_write(ffn)
|
||||
bool stage_timing_enable();
|
||||
void stage_timing_name(int slot, const char* name);
|
||||
void stage_timing_report(int64_t n_layers);
|
||||
/// The same event pairs, reachable from `session.cpp`, for marks that sit OUTSIDE the captured graphs - the
|
||||
/// two `cudaGraphLaunch` calls per layer. Those are ordinary stream operations, so an event around them is
|
||||
/// legal and is not captured, which is what lets the captured path's 1.047 ms/layer be split into the two
|
||||
/// graphs' execution and the gap the host spends between them. Slots 16 and 17 are reserved for it; slots
|
||||
/// 0-15 are the in-layer marks and are only meaningful with `--no-capture`.
|
||||
void stage_mark_begin(int64_t layer, int slot, void* stream);
|
||||
void stage_mark_end(int64_t layer, int slot, void* stream);
|
||||
|
||||
/// Scratch for one QSA layer. Every buffer here is overwritten by every token.
|
||||
struct QsaBuffers {
|
||||
uint8_t* x_q8_0 = nullptr; ///< n_embd, block_q8_0 - `attn_q` is Q2_0, whose vec_dot_type is Q8_0
|
||||
uint8_t* x_q8k = nullptr; ///< n_embd, block_q8_K - the three K-quant projections
|
||||
uint16_t* x_bf16 = nullptr; ///< n_embd - the two BF16 indexer projections
|
||||
float* q_full = nullptr; ///< n_head * 2 * head_dim: the raw `attn_q` output, q | gate per head
|
||||
float* qcur = nullptr; ///< n_head * head_dim: the FIRST half of each head, contiguously
|
||||
float* kcur = nullptr; ///< n_head_kv * head_dim
|
||||
float* vcur = nullptr; ///< n_head_kv * head_dim
|
||||
float* idx_raw = nullptr; ///< idx_key_dim: NEVER normed and NEVER rotated
|
||||
float* q_idx = nullptr; ///< idx_q_heads * idx_key_dim
|
||||
float* cell_scores = nullptr; ///< max_cells
|
||||
int32_t* ids = nullptr; ///< cap = qsa_selection_width(kTopkMaxCells, s)
|
||||
uint16_t* k_scratch = nullptr; ///< cap * n_head_kv * head_dim
|
||||
uint16_t* v_scratch = nullptr;
|
||||
float* attn = nullptr; ///< n_head * head_dim
|
||||
uint16_t* attn16 = nullptr; ///< n_head * head_dim, for a fp16-activation consumer
|
||||
/// `attn * sigmoid(gate)` in f32 and then in Q8_K - what `attn_output` ACTUALLY wants. Its weights are
|
||||
/// Q4_K/Q5_K/Q6_K, whose `vec_dot_type` is Q8_K, and the fp16 path is worth 0.66-1.41% against the
|
||||
/// reference. `docs/activation-contract.md`.
|
||||
float* attn32 = nullptr;
|
||||
uint8_t* attn_q8k = nullptr;
|
||||
float* attn_scratch = nullptr; ///< plan v0.3 P3: split-K decode attention partials
|
||||
};
|
||||
|
||||
uint64_t qsa_buffers_bytes(const ModelGeometry& g, int64_t max_cells);
|
||||
uint64_t qsa_buffers_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaBuffers& b);
|
||||
|
||||
/// `x` (n_embd f32) through one QSA layer to `out` (n_embd f32) at sequence position `pos`.
|
||||
///
|
||||
/// `pos_base` is the sequence's FIRST cell's position, which the indexer needs and cannot derive - equating a
|
||||
/// cell's position with its index is only right for a sequence starting at 0.
|
||||
///
|
||||
/// THE OP ORDER IS `ref/model.py::_qsa`, and two things in it are easy to read past:
|
||||
///
|
||||
/// * the indexer's raw key is appended BEFORE any norm or rotation, and it is the raw `indexer.k_proj`
|
||||
/// output that is pooled and rotated LATER, once per block and at the block's FIRST cell;
|
||||
/// * `q_full` is split into q and gate by HALVES of each head's 2*head_dim block, contiguous, not
|
||||
/// interleaved - `qsa_gate_apply` reads the second half and `qcur` is copied out of the first.
|
||||
///
|
||||
/// THE THREE ACTIVATION FORMATS FOLLOW `docs/activation-contract.md`, and they are not interchangeable:
|
||||
/// `attn_q` is Q2_0 (Q8_0 activation), `attn_k`/`attn_v`/`attn_output` are K-quants (Q8_K), and the two
|
||||
/// indexer projections are BF16 (bf16).
|
||||
bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base,
|
||||
const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream,
|
||||
std::string& err, float* dump = nullptr);
|
||||
|
||||
// ================================ THE DOORBELL ================================
|
||||
|
||||
/// THE HANDOFF: `x_f` and the miss list reach the CPU WHILE THE LAYER IS STILL RUNNING.
|
||||
///
|
||||
/// Everything about the shape of this struct comes from two measurements, and neither was a guess:
|
||||
///
|
||||
/// * **THE WAIT MUST POLL THE DRIVER.** Round 195: a host spin that only reads a memory location never runs
|
||||
/// the kernel - 5,907,703 spins over 500 ms and the datum flips the instant `cudaStreamSynchronize` is
|
||||
/// called and never before, because on Windows the driver BATCHES command submission and a memory-only
|
||||
/// spin gives it no reason to flush. So `h_seq` is read AND `cudaEventQuery` is called, which is a query
|
||||
/// and not a blocking sync - P2.X3's "zero synchronization calls in the layer loop" still holds.
|
||||
/// * **THE WRITE MUST BE CAPTURABLE, AND A KERNEL IS.** Round 199: `cudaEventRecord` inside a capture is
|
||||
/// SILENTLY DROPPED - 2 nodes for two kernels plus an event record, and the event never completed across a
|
||||
/// 41 ms graph. A mid-graph doorbell KERNEL is captured normally, and round 209 measured the host seeing a
|
||||
/// pinned handoff **0.050 ms** into a 39.8 ms graph.
|
||||
///
|
||||
/// The memory is MAPPED PINNED, so it has one address for the device and another for the host and both refer
|
||||
/// to the same bytes. Pinned as well as mapped, because a pageable destination would turn the device's write
|
||||
/// into a staged copy and give back the overlap this exists for.
|
||||
struct Doorbell {
|
||||
int64_t n_embd = 0;
|
||||
int64_t k = 0;
|
||||
// the HOST's view
|
||||
float* h_x_f = nullptr; ///< n_embd
|
||||
int32_t* h_ids = nullptr; ///< k
|
||||
float* h_weights = nullptr; ///< k
|
||||
uint32_t* h_seq = nullptr; ///< 1
|
||||
/// Plan v0.3 P3 token graph: the HOST's answer. The host writes the ring value it has served (after the
|
||||
/// pool's output is in place); the device's `doorbell_wait` spins until the flag equals the ring.
|
||||
uint32_t* h_flag = nullptr; ///< 1
|
||||
// the DEVICE's view of the same bytes
|
||||
float* d_x_f = nullptr;
|
||||
int32_t* d_ids = nullptr;
|
||||
float* d_weights = nullptr;
|
||||
uint32_t* d_seq = nullptr;
|
||||
uint32_t* d_flag = nullptr;
|
||||
};
|
||||
|
||||
/// Allocates the four mapped-pinned regions. Returns the bytes, or 0 on failure.
|
||||
uint64_t doorbell_init(const ModelGeometry& g, int64_t k, Doorbell& db);
|
||||
void doorbell_free(Doorbell& db);
|
||||
/// Zeroes `h_seq` (and `h_flag`), so a caller can wait for it to become `expected` from a known state.
|
||||
void doorbell_reset(const Doorbell& db);
|
||||
|
||||
// ================================ ONE WHOLE BLOCK ================================
|
||||
|
||||
/// The gated-residual stack plus the two buffers the halves hand to each other.
|
||||
///
|
||||
/// `R` is (hc, n_embd) and is BOTH the input and the output: `hc` residual streams, each n_embd wide, which is
|
||||
/// what `gr_read`/`gr_write` exist for. It is not one vector with a gate.
|
||||
struct BlockBuffers {
|
||||
float* R = nullptr; ///< (hc, n_embd)
|
||||
float* mixed = nullptr; ///< n_embd: what the mixer consumes
|
||||
float* block_out = nullptr; ///< n_embd: what a half produces
|
||||
float* inject = nullptr; ///< hc: `gr_read`'s per-stream injection, reused per half
|
||||
/// Plan v0.3 P3 fused GR: the FFN half's injection lives here (the attention half's stays in `inject`),
|
||||
/// because the fused read of one half reads the other half's injection while writing its own.
|
||||
float* inject2 = nullptr; ///< hc
|
||||
float* gr_rs = nullptr; ///< hc: the fused read's per-stream 1/rms
|
||||
uint8_t* head_q8k = nullptr; ///< `q8k_bytes(n_embd)`: the head's Q8_K activation image
|
||||
strata::kernels::GrWorkspace gr; ///< `gr_read`'s scratch
|
||||
|
||||
/// THE HALF-LEVEL C1 ORACLE, and it is a HOST buffer of `(2 * n_embd + 2 * hc + n_head * head_dim)` floats
|
||||
/// PER LAYER: `[0, n_embd)` the attention half's `block_out`, `[n_embd, 2*n_embd)` the MoE half's, the two
|
||||
/// `hc`-vectors of `inject`, and finally the QSA layers' PRE-GATE attention (`n_head * head_dim`, unused by
|
||||
/// GDN). The residual ladder (`session_loop`'s `dump_layers`) says WHICH LAYER diverges; this says which
|
||||
/// stage, and it is the only way to separate the reference's `linear_attn_out-<l>` from its `ffn_out-<l>`
|
||||
/// without re-deriving one of them. The copies are issued from inside `block_layer_pre`/`_post`, so they
|
||||
/// are recorded as nodes of the per-layer captured graph and replay with the layer they belong to. Null
|
||||
/// means no dumping, which is the default and costs nothing.
|
||||
float* dump = nullptr;
|
||||
};
|
||||
|
||||
uint64_t block_buffers_bytes(const ModelGeometry& g);
|
||||
|
||||
/// Plan v0.3 P3: the hyper-connection read as two fused kernels with the previous half's write folded in
|
||||
/// (`strata/kernels/fused_gr.hpp`). Requires the native MMVF contract (FP32 activations). The residual `R`
|
||||
/// then lags by one pending write between halves; it is materialised before the layer-1 PLE and after the last
|
||||
/// layer. Set before capture; not for the per-stage or dump measurements.
|
||||
void layer_set_fused_gr(bool enabled);
|
||||
bool layer_fused_gr();
|
||||
|
||||
/// Plan v0.3 P3/P7: QSA attention by the split-K kernel reading the KV pools directly (default ON; `false` keeps
|
||||
/// the gather + one-block-per-head kernel). Set before capture.
|
||||
void layer_set_fast_attn(bool enabled);
|
||||
/// Plan v0.3 P3: doorbell payload + ring as one kernel, QSA step staging read by a kernel from mapped memory
|
||||
/// (default ON; `false` keeps the memcpy nodes). Set before capture.
|
||||
void layer_set_publish_kernel(bool enabled);
|
||||
/// Plan v0.3 P3: GDN step + output norm as one coalesced kernel under the native contract (default ON).
|
||||
void layer_set_fused_gdn(bool enabled);
|
||||
/// Plan v0.3 P7: QSA block scores in FP32 and a radix top-k over blocks (default ON; `false` = the FP64 row scores
|
||||
/// and the bit-serial cell top-k). Set before capture.
|
||||
void layer_set_fast_select(bool enabled);
|
||||
/// Plan v0.3 P6: whether the current decode configuration is the one the speculative verify window reproduces
|
||||
/// bit for bit (native projections, fused GR and GDN, split-K attention, block selection, native indexer).
|
||||
bool layer_verify_compatible(std::string& why);
|
||||
/// The same for a model's geometry: at `hc = 1` (Qwen3.6) there is no hyper-connection read to fuse and, without an
|
||||
/// indexer, no block selection and no native indexer to require. The no-geometry form above is Flash-Next's.
|
||||
bool layer_verify_compatible(const ModelGeometry& g, std::string& why);
|
||||
uint64_t block_buffers_init(const ModelGeometry& g, void* base, BlockBuffers& b);
|
||||
|
||||
// ================================ THE PLAIN BLOCK (hc = 1, Qwen3.6) ================================
|
||||
//
|
||||
// `hc = 1` (`ModelGeometry::hc`, set by the architecture string: docs/QWEN36-35B-A3B.md section 3.5) means NO
|
||||
// hyper-connections: `R` is one n_embd stream and the block is llama.cpp's `qwen35moe` pre-norm residual block
|
||||
//
|
||||
// x = rms_norm(R) * attn_norm -> mixer -> R += out
|
||||
// x = rms_norm(R) * post_attention_norm -> MoE -> R += out head: rms_norm(R) * output_norm -> output
|
||||
//
|
||||
// **IT IS A SECOND PATH CHOSEN BY `hc`, NOT THE GR PATH AT hc = 1.** `gr_read` on one stream is not a plain norm
|
||||
// (its bottleneck gates the normed stream with a sigmoid and its norm weight is stored as `1 + w`), so the GR
|
||||
// kernels are never entered for this model; `block_layer_pre`, `block_layer_post`, `lm_head_mix` and the verify
|
||||
// window each branch on `g.hc == 1` to the two helpers below. There is no pending write either: the residual is
|
||||
// added where the reference adds it, so `R` never lags between halves.
|
||||
//
|
||||
// The two helpers take a ROW COUNT so the verify window (T rows) and the single-token path (1 row) call the same
|
||||
// kernels: row t of the T-row call is bitwise the one-row call (the norm has independent per-row statistics in a
|
||||
// fixed reduction order; the add is elementwise). tests/cuda/qwen36_block_test.cpp asserts that.
|
||||
|
||||
/// `mixed[t] = rms_norm(R[t], eps) * w` over n_embd, for `n_tok` rows at stride n_embd (`w` is the F32 norm weight,
|
||||
/// n_embd long; ggml's `rms_norm` then `mul`). `mixed` may equal `R` (in place) or must be disjoint.
|
||||
void plain_norm_rows(const float* R, const float* w, float* mixed, int64_t n_embd, float eps, int n_tok, void* stream);
|
||||
/// `R[t] += block_out[t]` over n_embd, for `n_tok` rows at stride n_embd.
|
||||
void plain_residual_rows(float* R, const float* block_out, int64_t n_embd, int n_tok, void* stream);
|
||||
|
||||
// ================================ THE TWO ENDS OF A TOKEN ================================
|
||||
|
||||
/// THE EMBEDDING LOOKUP, done as a COLUMN DEQUANT rather than a GEMV.
|
||||
///
|
||||
/// `token_embd.weight` is `[n_embd, n_vocab]`, so `out[i] = W[i][token]` - one column, `n_embd` values. Running
|
||||
/// `output`-style arithmetic on a one-hot activation would produce the same numbers with 248320x the work.
|
||||
///
|
||||
/// **THE DECODE IS TRANSCRIBED FROM `s_gemv_q8k_split` AND MUST STAY BIT-IDENTICAL TO IT**: the code is the
|
||||
/// `CODE_BITS`-wide field, least-significant first, at bit `(i % PER_BYTE) * CODE_BITS` of byte `i / PER_BYTE`;
|
||||
/// the value is `(code + code_bias) * scales[i / group_elems] + offsets[i / group_elems]`; and the column's
|
||||
/// planes start at `token * n_in / PER_BYTE` and `token * n_in / group_elems`. A second decoder that drifts
|
||||
/// from the kernel's would make the prompt embed differently from the tokens generated after it.
|
||||
bool embed_row(const WeightTable& tables, const ModelGeometry& g, int64_t token, float* out_dev, void* stream,
|
||||
std::string& err);
|
||||
|
||||
/// `ref/model.py` L520: `fin = GR.gr_read(R, output_hc_*..., inject=None, rms_eps); logits = output @ fin`.
|
||||
///
|
||||
/// `R` is read from `bb.R` and the result goes to `logits`, which the caller sizes at `output.weight`'s `ne1`
|
||||
/// (the vocabulary). `bb.head_q8k` and `bb.mixed` are scratch.
|
||||
bool lm_head(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb, float* logits,
|
||||
void* stream, std::string& err);
|
||||
|
||||
/// Compute the final residual mix in bb.mixed, before the output projection. This is shared by the
|
||||
/// canonical and experimental native head so only the projection's arithmetic changes in their A/B test.
|
||||
bool lm_head_mix(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb,
|
||||
void* stream, std::string& err);
|
||||
|
||||
/// THE PER-LAYER OP ORDER of `phases/phase-2-correct-engine.md` P2.S5, architecture Ă„ĂË€šĂËÂĂ˂¬ĹˇÄ‚ĂË€šĂ‚§6.1, for ONE layer:
|
||||
///
|
||||
/// gr_read (attn) -> mixer -> gr_write (attn)
|
||||
/// gr_read (ffn) -> MoE -> gr_write (ffn)
|
||||
///
|
||||
/// `layer` picks the mixer: `is_qsa_layer` selects `qsa_layer`, otherwise `gdn_layer`. `pos`/`pos_base` reach
|
||||
/// the QSA layer and are ignored by GDN, which has no position argument at all - its whole per-token input is
|
||||
/// `x` and what advances between tokens is its recurrent state.
|
||||
///
|
||||
/// **`parts` IS THE CALLER'S**, and that is the architecture's split rather than an omission: the routed experts
|
||||
/// are the only part of the model that does not fit in VRAM, so the CPU pool and the VRAM-resident experts fill
|
||||
/// `parts` and this function owns the two ends. In P2.S5 everything is a miss, so a caller passes whatever the
|
||||
/// pool produced; the doorbell protocol is what lets it be produced DURING this layer rather than before it.
|
||||
// ================================ THE PLE (LAYER 1'S PER-LAYER EMBEDDING) ================================
|
||||
//
|
||||
// **THIS MODULE EXISTED, WAS PARITY-TESTED, AND WAS NEVER CALLED - WHICH IS WHY GATE C1 FAILED.** Layer 1 is
|
||||
// the only layer with `blk.1.ple_*` tensors (six of them) and `block_layer` ran GDN/QSA + GR + MoE without it,
|
||||
// so the engine computed a different model. `ple_parity` verifies all three pieces against things that are
|
||||
// not this project's code - the hash against `ref/ngram.py` with the artifact's own constants, the IQ4_NL row
|
||||
// read against numpy over the original GGUF, and the block against ggml's own graph - and none of that helps
|
||||
// if nothing calls it.
|
||||
//
|
||||
// THE TABLE IS NOT IN THE PACK. `per_layer_token_embd.weight` is 51.2e9 elements (28.8 GB) of IQ4_NL in the
|
||||
// ORIGINAL second GGUF shard, and it is the only tensor this engine reads from the GGUF rather than from the
|
||||
// canonical pack. It is also why the PLE is cheap: sixteen 90-byte rows per token is 1440 bytes of traffic,
|
||||
// against the experts' 664 MB.
|
||||
struct PleRun {
|
||||
/// Null when the PLE is not wired (no table, or a pack without `blk.1.ple_*`). Then `block_layer_pre`
|
||||
/// SKIPS the module entirely, which is what every measurement before this change did.
|
||||
strata::kernels::PleTable* table = nullptr;
|
||||
strata::kernels::PleWeights w;
|
||||
/// The session's PLE state, by pointer so `block_layer_pre` needs no `SessionState`.
|
||||
const int32_t* token = nullptr; ///< the token being decoded
|
||||
const int32_t* prev = nullptr; ///< (2,) predecessors, OLDEST FIRST, `-1` where there is none
|
||||
float* hist = nullptr; ///< NG_HIST x hc_dim NORMALIZED history, row-fastest
|
||||
/// The gathered 2560-wide row vector on the DEVICE, and the host staging it is copied from: `gather`
|
||||
/// writes HOST memory (the table is a host mapping) and the block wants the device.
|
||||
float* emb_dev = nullptr;
|
||||
float* emb_host = nullptr;
|
||||
/// Internal workspace plus a disjoint normalized export for the next history row.
|
||||
/// Allocate ple_run_scratch_bytes(), not merely the lower-level ple_block_scratch_bytes().
|
||||
float* scratch = nullptr;
|
||||
strata::kernels::PleConsts consts;
|
||||
bool ready() const {
|
||||
return table != nullptr && table->is_open() && hist != nullptr && emb_dev != nullptr &&
|
||||
emb_host != nullptr && scratch != nullptr && token != nullptr && prev != nullptr &&
|
||||
((w.key_codes != nullptr && w.key_scales != nullptr) || w.key_bf16 != nullptr ||
|
||||
w.key_native_data != nullptr) &&
|
||||
w.value_bf16 != nullptr &&
|
||||
w.norm_key != nullptr && w.norm_query != nullptr && w.norm_conv != nullptr &&
|
||||
w.conv1d_f16 != nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
/// **CALLED ONCE PER TOKEN, FROM THE DRIVER, *OUTSIDE* ANY CAPTURE.** The n-gram hash and the table gather
|
||||
/// are host operations, and `block_layer_pre` is captured - so doing them there would run them once, at capture
|
||||
/// time, and replay the same rows for every token forever. This is the doorbell's cloned-literal bug in a
|
||||
/// different coat: silent, finite, and stable.
|
||||
bool ple_stage_token(const PleRun& p, void* stream, std::string& err);
|
||||
|
||||
/// Plan v0.3 P2: `ple_stage_token` in two halves, so the SSD reads overlap other host work.
|
||||
/// `ple_issue_token` hashes the token and starts its 16 row reads; `ple_finish_token` waits for them,
|
||||
/// dequantizes and queues the upload. Both are driver-side, outside any capture, like `ple_stage_token`.
|
||||
bool ple_issue_token(const PleRun& p, std::string& err);
|
||||
bool ple_finish_token(const PleRun& p, void* stream, std::string& err);
|
||||
|
||||
/// Internal PLE workspace plus one separate hc_dim normalized row for advancing history.
|
||||
uint64_t ple_run_scratch_bytes();
|
||||
|
||||
/// `ple` is the layer-1 PLE, or null to skip it (which is what every measurement before LEDGER L123 did).
|
||||
/// It is applied INSIDE `pre[1]`, before layer 1's own `gr_read`, because the block's output is
|
||||
/// `hidden + gated + silu(conv)` on the residual itself - it is a residual UPDATE, and the architecture puts
|
||||
/// the gathered rows in place "before layer 2".
|
||||
bool block_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base,
|
||||
const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb, const MoEBuffers& mb,
|
||||
int64_t k, const BlockBuffers& bb, const float* parts, void* stream, std::string& err,
|
||||
const Doorbell* db = nullptr, const PleRun* ple = nullptr);
|
||||
|
||||
/// **THE BLOCK, SPLIT AT THE ROUTER, SO A HOST LOOP CAN PUT THE CPU POOL IN THE MIDDLE.**
|
||||
///
|
||||
/// pre[l] gr_read(attn) -> mixer -> gr_write(attn) -> gr_read(ffn) -> moe_route [rings the doorbell]
|
||||
/// post[l] moe_finish -> gr_write(ffn)
|
||||
///
|
||||
/// `parts` reaches only `post`, and it must be THIS layer's experts. The two calls are NOT independent: `post`
|
||||
/// reads `bb.mixed` and `bb.inject` exactly as `pre` left them, so nothing may run between them that touches the
|
||||
/// block buffers - and in particular `pre[l+1]` may NOT be launched between them, because its own `gr_read`
|
||||
/// overwrites both. That constraint is why the doorbell's window is the shared expert and nothing more, and
|
||||
/// why the CPU expert term is answered by Phase 3's VRAM cache rather than by this pipeline.
|
||||
///
|
||||
/// **`half` EXISTS SO THE CAPTURED GRAPH CAN BE SPLIT FOR MEASUREMENT, AND IT IS THE ONLY REASON.**
|
||||
///
|
||||
/// The plan's R3 items - GR, GDN, the router - are each worth several milliseconds and there has never been a
|
||||
/// per-stage breakdown of the CAPTURED graph to choose between them. The `--no-capture` table cannot supply
|
||||
/// one: round 312 showed its `moe_finish` figure was a host-gap artefact, four times the captured cost of the
|
||||
/// same work. An event recorded BETWEEN two `cudaGraphLaunch` calls IS valid, so the answer is to capture the
|
||||
/// layer as more than one graph and time them from outside.
|
||||
///
|
||||
/// `half` selects a prefix of the stages, and the seam is the one this file already documents:
|
||||
///
|
||||
/// 1 = stages 0..2 gr_read -> attention -> gr_write the MIXER
|
||||
/// 2 = stages 3..4 gr_read -> moe_route the FFN front and the ROUTER
|
||||
/// 0 = both, which is what every caller before this used and what `session_loop` still uses
|
||||
///
|
||||
/// **A half is not a free-standing call.** `2` reads what `1` left in `bb.mixed`/`bb.inject`, exactly as
|
||||
/// `block_layer_post` does; the two are only meaningful replayed in order on one stream, which is what
|
||||
/// `session_replay_stages` does.
|
||||
bool block_layer_pre(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos,
|
||||
int32_t pos_base, const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb,
|
||||
const MoEBuffers& mb, int64_t k, const BlockBuffers& bb, void* stream, std::string& err,
|
||||
const Doorbell* db = nullptr, const PleRun* ple = nullptr, int half = 0,
|
||||
int stage_prefix = 0);
|
||||
|
||||
bool block_layer_post(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k,
|
||||
const MoEBuffers& mb, const BlockBuffers& bb, const float* parts, void* stream,
|
||||
std::string& err);
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,139 +0,0 @@
|
||||
// include/strata/core/layout.hpp - the pack's LAYOUT, resolved by name and checked against the kernels.
|
||||
//
|
||||
// `WeightTable` answers "where are the bytes". This answers "is this the tensor I think it is", and it is
|
||||
// the layer where a pack and a kernel disagree - which is the failure this project keeps paying for. Two
|
||||
// examples, both real:
|
||||
//
|
||||
// * round 194 sized the indexer key store from `indexer.head_count = 4`, which counts QUERY heads. The
|
||||
// cached key is ONE shared head of 128 (`indexer.k_proj` is [2560, 128]), so the term was 4x too big and
|
||||
// the error survived a round because it moved in the direction that TIGHTENS the budget.
|
||||
// * `docs/semantics.md` and the tensor manifest agree on every dimension here, but nothing CHECKED that a
|
||||
// named tensor had the shape the kernel reading it assumes.
|
||||
//
|
||||
// So this header does two things: it names the tensors per layer type, and it asserts every shape the
|
||||
// kernels depend on. A mismatch is reported with the tensor name, the shape found and the shape required,
|
||||
// at LOAD time - not as a wrong number inside a GEMV at token 4000.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/weights.hpp"
|
||||
#include "strata/kernels/gdn.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// Which architecture the model file declares. The engine was written for ONE model (Qwen3.8-Flash-Next,
|
||||
/// `qwen4exp`); Qwen3.6-35B-A3B (`qwen35moe`) is the same family one generation earlier with the hyper-connection
|
||||
/// residual, the sparse-attention indexer and the PLE table removed. The string decides what the file cannot say:
|
||||
/// `hc`, the indexer and the PLE (docs/QWEN36-35B-A3B.md section 3.8).
|
||||
enum class ModelArch { Qwen4Exp, Qwen35Moe };
|
||||
|
||||
inline const char* model_arch_name(ModelArch a) { return a == ModelArch::Qwen4Exp ? "qwen4exp" : "qwen35moe"; }
|
||||
|
||||
/// The model's geometry. Every field here is a number a kernel depends on, so a change is a change to a kernel
|
||||
/// contract and not a tuning knob. The defaults are Qwen3.8-Flash-Next's (`docs/semantics.md`); a model file
|
||||
/// overrides every one of them through `read_model_geometry` (strata/core/model_geometry.hpp), which reads the
|
||||
/// `<arch>.*` keys of the GGUF and derives the dependent members below with `derive()`.
|
||||
struct ModelGeometry {
|
||||
ModelArch arch = ModelArch::Qwen4Exp;
|
||||
|
||||
int64_t n_embd = 2560;
|
||||
int64_t n_layers = 48; ///< trunk layers: `block_count` minus the draft (`nextn_predict_layers`) blocks
|
||||
int64_t nextn_layers = 0; ///< MTP draft blocks at the end of the file (0 when the key is absent)
|
||||
int64_t qsa_interval = 4; ///< every 4th layer is full attention: layers 3, 7, ... (`full_attention_interval`)
|
||||
int64_t n_vocab = 248320; ///< rows of `token_embd.weight` (both models share the tokenizer)
|
||||
|
||||
// GDN (36 of 48 layers; 30 of 40 for Qwen3.6)
|
||||
int64_t ssm_state_size = 128; ///< `ssm.state_size`: the head dim of k and v
|
||||
int64_t ssm_k_heads = 16; ///< `ssm.group_count`
|
||||
int64_t ssm_v_heads = 48; ///< `ssm.time_step_rank` (32 for Qwen3.6)
|
||||
int64_t ssm_d_conv = 4; ///< `ssm.conv_kernel`
|
||||
int64_t ssm_conv_channels = 10240; ///< DERIVED: 2*S*k_heads + S*v_heads (`derive()`); 8192 for Qwen3.6
|
||||
int64_t ssm_value_dim = 6144; ///< DERIVED: S*v_heads (`ssm.inner_size` in the file); 4096 for Qwen3.6
|
||||
|
||||
// full attention (QSA for Flash-Next: with an indexer; dense for Qwen3.6: no indexer)
|
||||
int64_t n_head = 24; ///< `attention.head_count` (16 for Qwen3.6)
|
||||
int64_t n_head_kv = 2; ///< `attention.head_count_kv`
|
||||
int64_t head_dim = 256; ///< `attention.key_length`
|
||||
int64_t n_rot = 64; ///< `rope.dimension_count`: the partial rotary width (0.25 * head_dim)
|
||||
int64_t rope_sections[4] = {11, 11, 10, 0}; ///< `rope.dimension_sections` (IMRoPE), sum == n_rot / 2
|
||||
double rope_base = 1e7; ///< `rope.freq_base`
|
||||
double rms_eps = 1e-6; ///< `attention.layer_norm_rms_epsilon`
|
||||
int64_t idx_q_heads = 4; ///< the QSA indexer's query heads (Flash-Next only; meaningless at hc 1)
|
||||
int64_t idx_key_dim = 128; ///< the QSA indexer's key width (Flash-Next only)
|
||||
|
||||
// gated residual, on every layer. `hc = 1` means NO hyper-connections: a plain residual with `attn_norm`,
|
||||
// `post_attention_norm` and `output_norm` (Qwen3.6). No key says this; the architecture string does.
|
||||
int64_t hc = 4;
|
||||
int64_t hc_lr = 320;
|
||||
|
||||
// MoE, on every layer
|
||||
int64_t n_expert = 512; ///< `expert_count` (256 for Qwen3.6)
|
||||
int64_t n_expert_used = 10; ///< `expert_used_count`, the router's k (8 for Qwen3.6)
|
||||
int64_t n_ff = 640; ///< `expert_feed_forward_length` (512 for Qwen3.6)
|
||||
int64_t n_ff_shexp = 640; ///< `expert_shared_feed_forward_length` (512 for Qwen3.6)
|
||||
|
||||
/// The per-layer token embedding (PLE) and its n-gram table: Flash-Next has one, Qwen3.6 has none. Decides
|
||||
/// whether `--ple-gguf` is required and whether the session carves the PLE history (strata/core/session.hpp).
|
||||
bool has_ple = true;
|
||||
|
||||
int64_t hc_dim() const { return hc * n_embd; }
|
||||
/// `layer % qsa_interval == qsa_interval - 1` is full attention. Derived, not a second list.
|
||||
int64_t n_qsa_layers() const { return n_layers / qsa_interval; }
|
||||
int64_t n_gdn_layers() const { return n_layers - n_qsa_layers(); }
|
||||
/// Whether the full-attention layers carry the sparse indexer (QSA). Qwen3.6's attention is dense.
|
||||
bool has_indexer() const { return arch == ModelArch::Qwen4Exp; }
|
||||
/// The GDN output gate: `rms_norm(o) * ssm_norm * act(z)` with act = sigmoid for Flash-Next and SiLU for Qwen3.6
|
||||
/// (geometry-inventory.md row 39; `kernels::GdnGate`). From the architecture, like `hc` and the indexer: no key
|
||||
/// says it. Every GDN output kernel takes this value from the layer; none reads a global.
|
||||
kernels::GdnGate gdn_gate() const {
|
||||
return arch == ModelArch::Qwen35Moe ? kernels::GdnGate::Silu : kernels::GdnGate::Sigmoid;
|
||||
}
|
||||
|
||||
/// The members that follow from others: conv channels `2*S*k_heads + S*v_heads` and the value dim
|
||||
/// `S*v_heads`. They are stored (the kernels read them as plain members) and derived here, so a file that
|
||||
/// changes `ssm_v_heads` cannot leave them at the defaults (geometry-inventory.md row 2).
|
||||
void derive() {
|
||||
ssm_value_dim = ssm_state_size * ssm_v_heads;
|
||||
ssm_conv_channels = 2 * ssm_state_size * ssm_k_heads + ssm_value_dim;
|
||||
}
|
||||
};
|
||||
|
||||
/// True for the full-attention layers. `docs/semantics.md` gives this twice over - `full_attention_interval
|
||||
/// = 4` and an explicit `attention.compress_ratios` array - and this is the first of the two.
|
||||
inline bool is_qsa_layer(const ModelGeometry& g, int64_t layer) {
|
||||
return layer % g.qsa_interval == g.qsa_interval - 1;
|
||||
}
|
||||
|
||||
/// One layer's tensors, resolved by NAME. `get("attn_qkv.weight")` looks up `blk.<layer>.attn_qkv.weight`
|
||||
/// and returns null if the pack does not have it - a null is information, because a GDN layer has no
|
||||
/// `attn_q` and a QSA layer has no `attn_qkv`.
|
||||
///
|
||||
/// Holds a reference to the table; the table must outlive it.
|
||||
class LayerView {
|
||||
public:
|
||||
LayerView(const WeightTable& table, int64_t layer) : table_(&table), layer_(layer) {}
|
||||
|
||||
int64_t layer() const { return layer_; }
|
||||
std::string name(const char* suffix) const;
|
||||
const WeightRef* get(const char* suffix) const { return table_->find(name(suffix)); }
|
||||
|
||||
private:
|
||||
const WeightTable* table_;
|
||||
int64_t layer_;
|
||||
};
|
||||
|
||||
/// Every shape the kernels depend on, asserted for ONE layer. Returns false and fills `err` with the first
|
||||
/// mismatch, naming the tensor, what it has and what is required.
|
||||
///
|
||||
/// This is deliberately a separate function from `LayerView`: a caller that only wants the pointers should
|
||||
/// not pay for the checks, and a caller that wants the checks should get ALL of them rather than the ones
|
||||
/// its own call site happens to touch.
|
||||
bool check_layer(const WeightTable& table, const ModelGeometry& g, int64_t layer, std::string& err);
|
||||
|
||||
/// `check_layer` over every layer, plus the cross-layer properties: exactly 12 QSA layers at the right
|
||||
/// indices, every GDN layer having the GDN set and no QSA tensor, and vice versa. Returns the first failure.
|
||||
bool check_all(const WeightTable& table, const ModelGeometry& g, std::string& err);
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,262 +0,0 @@
|
||||
// include/strata/core/model_geometry.hpp - `ModelGeometry` from the model file's own metadata.
|
||||
//
|
||||
// Until Phase 2 step 2 of docs/PLAN-qwen36-35b-a3b.md the geometry was a struct of Flash-Next defaults and only
|
||||
// `expert_count`, `expert_used_count` and the rope keys were read, under the `qwen4exp.` prefix and only with
|
||||
// `--native` (docs/qwen36-port/geometry-inventory.md rows 7 to 10). This header reads every field from the
|
||||
// `<arch>.*` keys llama.cpp's own loader reads (`src/llama-model.cpp:1231-1424`, `src/models/qwen35moe.cpp:4-34`
|
||||
// in the pinned submodule; the key set is docs/QWEN36-35B-A3B.md section 3.8), for both architectures, and names
|
||||
// the tensor forms this engine refuses rather than mis-reads.
|
||||
//
|
||||
// Header-only and CUDA-free on purpose: the unit test (tests/core/model_geometry_test.cpp) links nothing but the
|
||||
// GGUF reader, and the engine's start-up reads the geometry BEFORE any weight moves.
|
||||
#pragma once
|
||||
|
||||
#include "strata/artifact/gguf_reader.hpp"
|
||||
#include "strata/core/layout.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
namespace detail {
|
||||
|
||||
/// One integer key: `<arch>.<suffix>`. `required`: absent is an error; otherwise the default stays.
|
||||
inline bool geometry_int(const strata::GgufFile& meta, const std::string& prefix, const char* suffix, int64_t& out,
|
||||
bool required, std::string& err) {
|
||||
const strata::MetaValue* v = meta.get(prefix + suffix);
|
||||
if (v == nullptr) {
|
||||
if (required) err = "missing " + prefix + suffix;
|
||||
return !required;
|
||||
}
|
||||
if (!v->is_num()) {
|
||||
err = prefix + suffix + " is not a number";
|
||||
return false;
|
||||
}
|
||||
out = (int64_t) v->num();
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool geometry_num(const strata::GgufFile& meta, const std::string& prefix, const char* suffix, double& out,
|
||||
bool required, std::string& err) {
|
||||
const strata::MetaValue* v = meta.get(prefix + suffix);
|
||||
if (v == nullptr) {
|
||||
if (required) err = "missing " + prefix + suffix;
|
||||
return !required;
|
||||
}
|
||||
if (!v->is_num()) {
|
||||
err = prefix + suffix + " is not a number";
|
||||
return false;
|
||||
}
|
||||
out = v->num();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
/// Fills `g` from the metadata shard. Every field of `ModelGeometry` comes from the file where the file has a
|
||||
/// key for it; the two models' keys differ only in the prefix. What the file cannot say is decided by the
|
||||
/// architecture string: `hc` (4 with hyper-connections, 1 without), the indexer, the PLE. `n_layers` is
|
||||
/// `block_count` minus the draft blocks (`nextn_predict_layers`, 0 when absent). A missing key the kernels
|
||||
/// depend on, a value that is not a number, or a derived quantity the file states differently (`ssm.inner_size`
|
||||
/// against `state_size * time_step_rank`) is an error that names the key.
|
||||
inline bool read_model_geometry(const strata::GgufFile& meta, ModelGeometry& g, std::string& err) {
|
||||
const strata::MetaValue* arch = meta.get("general.architecture");
|
||||
if (arch == nullptr) { err = "missing general.architecture"; return false; }
|
||||
if (arch->s == "qwen4exp") {
|
||||
g = ModelGeometry{}; // Flash-Next's defaults, every one of them overridable below
|
||||
g.arch = ModelArch::Qwen4Exp;
|
||||
} else if (arch->s == "qwen35moe") {
|
||||
g = ModelGeometry{};
|
||||
g.arch = ModelArch::Qwen35Moe;
|
||||
g.hc = 1; // plain residual: attn_norm / post_attention_norm / output_norm
|
||||
g.hc_lr = 0;
|
||||
g.has_ple = false; // no per-layer token embedding, no n-gram table
|
||||
g.idx_q_heads = 0; // no sparse indexer: the attention is dense
|
||||
g.idx_key_dim = 0;
|
||||
} else {
|
||||
err = "architecture is '" + arch->s + "', this engine reads 'qwen4exp' (Qwen3.8-Flash-Next) and 'qwen35moe' "
|
||||
"(Qwen3.6-35B-A3B)";
|
||||
return false;
|
||||
}
|
||||
const std::string p = arch->s + ".";
|
||||
const bool q36 = g.arch == ModelArch::Qwen35Moe;
|
||||
// the keys both loaders require (the architecture guard already demands the first six)
|
||||
int64_t block_count = 0;
|
||||
if (!detail::geometry_int(meta, p, "block_count", block_count, true, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "nextn_predict_layers", g.nextn_layers, false, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "embedding_length", g.n_embd, true, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "attention.head_count", g.n_head, true, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "attention.head_count_kv", g.n_head_kv, true, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "expert_count", g.n_expert, true, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "expert_used_count", g.n_expert_used, true, err)) return false;
|
||||
// the keys Flash-Next's files may leave to the defaults (its loader has them hard-coded in places) and Qwen3.6's
|
||||
// must carry: the GDN shape, the expert widths, the layer pattern, the attention widths
|
||||
if (!detail::geometry_int(meta, p, "attention.key_length", g.head_dim, q36, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "full_attention_interval", g.qsa_interval, q36, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "ssm.conv_kernel", g.ssm_d_conv, q36, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "ssm.state_size", g.ssm_state_size, q36, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "ssm.group_count", g.ssm_k_heads, q36, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "ssm.time_step_rank", g.ssm_v_heads, q36, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "expert_feed_forward_length", g.n_ff, q36, err)) return false;
|
||||
g.n_ff_shexp = g.n_ff;
|
||||
if (!detail::geometry_int(meta, p, "expert_shared_feed_forward_length", g.n_ff_shexp, false, err)) return false;
|
||||
if (!detail::geometry_int(meta, p, "rope.dimension_count", g.n_rot, false, err)) return false;
|
||||
if (!detail::geometry_num(meta, p, "rope.freq_base", g.rope_base, false, err)) return false;
|
||||
if (!detail::geometry_num(meta, p, "attention.layer_norm_rms_epsilon", g.rms_eps, false, err)) return false;
|
||||
if (const strata::MetaValue* v = meta.get(p + "rope.dimension_sections")) {
|
||||
if (v->type != strata::MetaType::ARRAY || v->items.size() != 4) {
|
||||
err = p + "rope.dimension_sections is not an array of 4";
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < 4; ++i) g.rope_sections[i] = (int64_t) v->items[i].num();
|
||||
}
|
||||
// derived, then checked against what the file says of the same quantity
|
||||
g.n_layers = block_count - g.nextn_layers;
|
||||
g.derive();
|
||||
int64_t inner = g.ssm_value_dim;
|
||||
if (!detail::geometry_int(meta, p, "ssm.inner_size", inner, false, err)) return false;
|
||||
auto bad = [&](const std::string& what) { err = p.substr(0, p.size() - 1) + ": " + what; return false; };
|
||||
if (g.n_layers <= 0 || g.nextn_layers < 0)
|
||||
return bad("block_count " + std::to_string(block_count) + " minus nextn_predict_layers " +
|
||||
std::to_string(g.nextn_layers) + " leaves no trunk layer");
|
||||
if (inner != g.ssm_value_dim)
|
||||
return bad("ssm.inner_size is " + std::to_string(inner) + ", but ssm.state_size * ssm.time_step_rank is " +
|
||||
std::to_string(g.ssm_value_dim));
|
||||
if (g.qsa_interval <= 0 || g.n_layers % g.qsa_interval != 0)
|
||||
return bad("block_count " + std::to_string(g.n_layers) + " is not a multiple of full_attention_interval " +
|
||||
std::to_string(g.qsa_interval));
|
||||
if (g.ssm_k_heads <= 0 || g.ssm_v_heads % g.ssm_k_heads != 0)
|
||||
return bad("ssm.time_step_rank " + std::to_string(g.ssm_v_heads) + " is not a multiple of ssm.group_count " +
|
||||
std::to_string(g.ssm_k_heads) + " (the recurrence pairs v-heads to k-heads by h % h_k)");
|
||||
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv != 0)
|
||||
return bad("attention.head_count " + std::to_string(g.n_head) + " is not a multiple of head_count_kv " +
|
||||
std::to_string(g.n_head_kv));
|
||||
if (g.n_expert_used <= 0 || g.n_expert_used > g.n_expert)
|
||||
return bad("expert_used_count " + std::to_string(g.n_expert_used) + " over expert_count " +
|
||||
std::to_string(g.n_expert));
|
||||
if (g.n_rot <= 0 || g.n_rot > g.head_dim || g.n_rot % 2 != 0)
|
||||
return bad("rope.dimension_count " + std::to_string(g.n_rot) + " does not fit attention.key_length " +
|
||||
std::to_string(g.head_dim));
|
||||
if (g.rope_sections[0] + g.rope_sections[1] + g.rope_sections[2] + g.rope_sections[3] != g.n_rot / 2)
|
||||
return bad("rope.dimension_sections do not sum to rope.dimension_count / 2 = " + std::to_string(g.n_rot / 2));
|
||||
// the vocabulary: `output.weight`'s rows are what the engine samples over (generate.cpp takes n_vocab from that
|
||||
// tensor), `token_embd.weight`'s rows are what the native embedding loads with g.n_vocab, and the tokenizer's
|
||||
// token list is the third statement of the same number. Whichever of the three the metadata shard carries must
|
||||
// agree; the default (248,320, the shipped files') stands only when none is present (a metadata-only fixture).
|
||||
{
|
||||
int64_t seen[3] = {-1, -1, -1};
|
||||
const char* names[3] = {"output.weight", "token_embd.weight", "tokenizer.ggml.tokens"};
|
||||
if (const strata::TensorInfo* t = meta.find(names[0])) seen[0] = t->shape.size() >= 2 ? (int64_t) t->shape[1] : 0;
|
||||
if (const strata::TensorInfo* t = meta.find(names[1])) seen[1] = t->shape.size() >= 2 ? (int64_t) t->shape[1] : 0;
|
||||
if (const strata::MetaValue* v = meta.get(names[2]))
|
||||
seen[2] = v->type == strata::MetaType::ARRAY ? (int64_t) v->count : 0; // `count` is the full length; `items` is capped
|
||||
int64_t vocab = -1;
|
||||
const char* from = nullptr;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
if (seen[i] < 0) continue;
|
||||
if (seen[i] <= 0) return bad(std::string(names[i]) + " gives no vocabulary size");
|
||||
if (vocab < 0) { vocab = seen[i]; from = names[i]; continue; }
|
||||
if (seen[i] != vocab)
|
||||
return bad(std::string(from) + " says " + std::to_string(vocab) + " tokens but " + names[i] + " says " +
|
||||
std::to_string(seen[i]));
|
||||
}
|
||||
if (vocab > 0) g.n_vocab = vocab;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Reads the geometry from `any_shard`'s model (every shard found beside it; the metadata shard decides).
|
||||
inline bool read_model_geometry(const std::string& any_shard, ModelGeometry& g, std::string& err) {
|
||||
try {
|
||||
const strata::GgufModel model = strata::GgufModel::open(any_shard);
|
||||
return read_model_geometry(model.meta(), g, err);
|
||||
} catch (const std::exception& e) {
|
||||
err = e.what();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// The tensor FORMS this engine refuses by name. llama.cpp accepts two fused layouts that no shipped Qwen3.6 file
|
||||
/// uses (`gguf-metadata.md`, "What was unexpected"): experts fused as `ffn_gate_up_exps` (gate rows then up rows)
|
||||
/// and an attention layer's projections fused as `attn_qkv` (Q | K | V rows). The engine reads three separate
|
||||
/// expert tensors (`expert_source.cpp`, check_experts_gguf) and separate `attn_q` / `attn_k` / `attn_v`; `attn_qkv`
|
||||
/// is legitimate ONLY in a GDN layer, where it is the conv input. A file in a fused form is refused here, naming
|
||||
/// the tensor, instead of failing later on a shape or being split silently. Returns true when nothing is fused.
|
||||
inline bool check_model_tensor_forms(const strata::GgufModel& model, const ModelGeometry& g, std::string& err) {
|
||||
for (int64_t l = 0; l < g.n_layers + g.nextn_layers; ++l) {
|
||||
const std::string blk = "blk." + std::to_string(l) + ".";
|
||||
if (model.find(blk + "ffn_gate_up_exps.weight") != nullptr) {
|
||||
err = blk + "ffn_gate_up_exps.weight: the experts are fused (llama.cpp's gate-then-up form); this engine "
|
||||
"reads separate ffn_gate_exps / ffn_up_exps / ffn_down_exps tensors. No shipped Qwen3.6 file is "
|
||||
"fused; re-convert the model without the fused experts";
|
||||
return false;
|
||||
}
|
||||
const bool attention = l >= g.n_layers || is_qsa_layer(g, l);
|
||||
if (attention && model.find(blk + "attn_qkv.weight") != nullptr && model.find(blk + "attn_q.weight") == nullptr) {
|
||||
err = blk + "attn_qkv.weight: the attention projections are fused (llama.cpp's Q|K|V form); this engine "
|
||||
"reads separate attn_q / attn_k / attn_v tensors in an attention layer (attn_qkv is the conv "
|
||||
"input of a GDN layer only). No shipped Qwen3.6 file is fused; re-convert the model without it";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// One line per field, for the start-up log and the test's --real mode.
|
||||
inline std::string model_geometry_text(const ModelGeometry& g) {
|
||||
std::string s;
|
||||
auto add = [&](const char* k, int64_t v) { s += std::string(" ") + k + " " + std::to_string(v) + "\n"; };
|
||||
s += std::string(" arch ") + model_arch_name(g.arch) + "\n";
|
||||
add("n_embd", g.n_embd);
|
||||
add("n_vocab", g.n_vocab);
|
||||
add("n_layers", g.n_layers);
|
||||
add("nextn_layers", g.nextn_layers);
|
||||
add("qsa_interval", g.qsa_interval);
|
||||
add("n_qsa_layers", g.n_qsa_layers());
|
||||
add("n_gdn_layers", g.n_gdn_layers());
|
||||
add("ssm_state_size", g.ssm_state_size);
|
||||
add("ssm_k_heads", g.ssm_k_heads);
|
||||
add("ssm_v_heads", g.ssm_v_heads);
|
||||
add("ssm_d_conv", g.ssm_d_conv);
|
||||
add("ssm_conv_channels", g.ssm_conv_channels);
|
||||
add("ssm_value_dim", g.ssm_value_dim);
|
||||
add("n_head", g.n_head);
|
||||
add("n_head_kv", g.n_head_kv);
|
||||
add("head_dim", g.head_dim);
|
||||
add("n_rot", g.n_rot);
|
||||
s += " rope_sections " + std::to_string(g.rope_sections[0]) + "," + std::to_string(g.rope_sections[1]) + "," +
|
||||
std::to_string(g.rope_sections[2]) + "," + std::to_string(g.rope_sections[3]) + "\n";
|
||||
s += " rope_base " + std::to_string(g.rope_base) + "\n";
|
||||
s += " rms_eps " + std::to_string(g.rms_eps) + "\n";
|
||||
add("idx_q_heads", g.idx_q_heads);
|
||||
add("idx_key_dim", g.idx_key_dim);
|
||||
add("hc", g.hc);
|
||||
add("hc_lr", g.hc_lr);
|
||||
add("n_expert", g.n_expert);
|
||||
add("n_expert_used", g.n_expert_used);
|
||||
add("n_ff", g.n_ff);
|
||||
add("n_ff_shexp", g.n_ff_shexp);
|
||||
s += std::string(" has_ple ") + (g.has_ple ? "yes" : "no") + "\n";
|
||||
s += std::string(" has_indexer ") + (g.has_indexer() ? "yes" : "no") + "\n";
|
||||
return s;
|
||||
}
|
||||
|
||||
/// Phase 2 step 2's gate (docs/PLAN-qwen36-35b-a3b.md section 5): what this engine can and cannot yet do with a
|
||||
/// `qwen35moe` file, said once and precisely, so a start fails here and not inside a kernel. Empty when the
|
||||
/// architecture needs no gate.
|
||||
inline std::string qwen35moe_not_yet(const ModelGeometry& g) {
|
||||
if (g.arch != ModelArch::Qwen35Moe) return {};
|
||||
return "this is a Qwen3.6-35B-A3B file (qwen35moe, " + std::to_string(g.n_layers) + " layers, " +
|
||||
std::to_string(g.n_embd) + " wide, " + std::to_string(g.n_expert) + " experts x top-" +
|
||||
std::to_string(g.n_expert_used) + "): Phase 2 step 2 (geometry, metadata, the VRAM plan above) is done, "
|
||||
"but the engine cannot run it yet. Not done: step 3 (kernels and the block: the GDN gate SiLU(z) "
|
||||
"instead of sigmoid(z), dense attention at " + std::to_string(g.n_head) + " heads with no indexer, the "
|
||||
"block and the verify window without hyper-connections, prefill at this geometry), step 4 (the native "
|
||||
"pack and the MTP drafter from blk." + std::to_string(g.n_layers) + ", the expert profile at " +
|
||||
std::to_string(g.n_layers) + " x " + std::to_string(g.n_expert) + "). See docs/PLAN-qwen36-35b-a3b.md "
|
||||
"section 5 and docs/qwen36-port/step2-notes.md";
|
||||
}
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,228 +0,0 @@
|
||||
// include/strata/core/mtp.hpp - plan v0.3 P6: the MTP draft layer on the GPU.
|
||||
//
|
||||
// The model ships one multi-token-prediction layer (vLLM 0.30.0 `qwen4_exp` MTP; transcribed and validated in
|
||||
// `tools/mtp_probe.py`, where it accepts 0.89 / 0.86 / 0.85 of greedy drafts at steps 1-3). Cell i of its
|
||||
// sequence pairs the main model's final multi-stream residual at position i with the token at position i+1, at
|
||||
// rope position i (vLLM's convention); its output predicts the token at position i+2, and its own residual feeds
|
||||
// the next draft step.
|
||||
//
|
||||
// e = fc_embedding(rms(embed(tok)) * (1+w)) h = fc_hidden per stream(rms_10240(R) * (1+w))
|
||||
// R = h + e -> attention hyper-connection -> QSA attention (own K/V) -> MLP hyper-connection ->
|
||||
// MoE (512 experts, top-10, shared expert) -> R += y * 2 sigmoid(inject / hc) -> final mixer -> head
|
||||
//
|
||||
// Runtime choices, each a trade of exactness for simplicity that only affects DRAFT quality, never the output
|
||||
// (the verify window decides every emitted token):
|
||||
// * the large projections run as Q8_0 through the multi-column MMVQ (`tools/mtp_rt.py` quantizes them);
|
||||
// * the attention is DENSE over every cell the layer has seen - identical to the model's sparse selection
|
||||
// below 2,051 cells - so speculative cells (draft steps, rejected window rows) never touch indexer state and
|
||||
// are simply overwritten when their positions are processed again;
|
||||
// * all 512 routed experts live in VRAM (708 MB) and run through the grouped hit kernels.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/layer.hpp"
|
||||
#include "strata/core/session.hpp"
|
||||
#include "strata/kernels/sampler.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
class NativeHead;
|
||||
|
||||
class MtpDrafter {
|
||||
public:
|
||||
MtpDrafter() = default;
|
||||
~MtpDrafter();
|
||||
MtpDrafter(const MtpDrafter&) = delete;
|
||||
MtpDrafter& operator=(const MtpDrafter&) = delete;
|
||||
|
||||
/// Loads `rt_dir` (from tools/mtp_rt.py) and allocates the layer's K/V and buffers for up to `max_t` rows.
|
||||
/// Call before the VRAM expert tier is sized: this takes ~0.9 GB.
|
||||
bool load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,
|
||||
int64_t window = 32768);
|
||||
/// The prompt's length: prefill() skips the cells the attention window can never reach again.
|
||||
void set_prompt_len(int64_t n) { prompt_len_ = n; }
|
||||
/// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere.
|
||||
void set_max_drafts(int k) { max_drafts_ = k; }
|
||||
uint64_t vram_bytes() const { return vram_; }
|
||||
/// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it)
|
||||
const QsaState& kv_state() const { return st_; }
|
||||
/// KV streaming: refill the ring of the drafter's window from its host copy for a sequence that continues at
|
||||
/// `upto` (a conversation-cache resume). No-op unless the drafter's K/V is a ring.
|
||||
void kv_restore(int64_t upto);
|
||||
/// The VRAM bind() will allocate for a native head of `head_row_bytes` per vocabulary row: the draft logits and
|
||||
/// the draft head over rt/draft_vocab.bin's subset. The expert cache is sized before bind(), so it reserves this.
|
||||
uint64_t bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const;
|
||||
/// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each).
|
||||
bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err);
|
||||
|
||||
/// Prompt cells [cell0, cell0 + n): residual rows `R_rows` (device, hc*n_embd each) and `next_tokens` (host,
|
||||
/// the token at position cell+1). Runs in batches of up to max_t rows.
|
||||
bool prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err);
|
||||
|
||||
/// One round: catch-up over T cells from `p` (rows = the window's final residuals, `tokens` = the window's
|
||||
/// argmaxes: row t pairs R_{p+t} with the token at p+t+1), then the draft chain from row `a` (the last
|
||||
/// accepted row) for T-1 drafts at cells p+a+1 ... `drafts` gets T-1 tokens.
|
||||
bool draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err,
|
||||
float* probs = nullptr, float min_p = 0.0f, int* n_drafts = nullptr);
|
||||
|
||||
/// The first round: one cell (`cell`) from `R_row` (device) and `token` -> T-1 drafts.
|
||||
bool draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err,
|
||||
float* probs = nullptr, float min_p = 0.0f, int* n_drafts = nullptr);
|
||||
|
||||
/// COUPLED DRAFT SAMPLING (core/coupled_draft.hpp; STRATA_SPEC_COUPLED=1, set up by bind()): the request's
|
||||
/// sampling. A sampled request (temperature > 0, not greedy) then drafts by SAMPLING with the target's chain and
|
||||
/// the target's Philox draw for the verifying row, and `probs` is the draft's probability under that chain; a
|
||||
/// greedy one keeps the argmax drafts and their graphs. A no-op when the switch is off.
|
||||
void set_draft_sampling(const strata::kernels::SamplerParams& sp);
|
||||
/// Coupled mode with penalties: the history the next draft() chain starts from - what the session holds after the
|
||||
/// window's commit (`tail`) and the window's pick at its last accepted row (`next`, the next window's row 0).
|
||||
void set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next);
|
||||
void set_ple_session(SessionState* s) { ple_ss_ = s; }
|
||||
bool coupled() const { return coupled_active_; }
|
||||
|
||||
double ms_draft = 0, ms_prefill = 0;
|
||||
int64_t rounds = 0;
|
||||
|
||||
/// E-9: the prompt path computes this layer's prompt K/V in batches (Prefill::draft_kv): its tensors, its K/V
|
||||
/// state, the first cell a round can still read, its device, and a wait for its own stream.
|
||||
const float* tensor_f32(const char* name) const { return f32(name); }
|
||||
const uint16_t* tensor_bf16(const char* name) const { return bf16(name); }
|
||||
const void* tensor_q8(const char* name) const { return q8(name); }
|
||||
/// A projection of the pack in its GGUF form (Qwen3.6's pack keeps every projection as stored: `nextn.eh_proj.weight`,
|
||||
/// `attn_k.weight`, ...): its blocks and ggml type (`*type`), null when the name is not a native projection.
|
||||
const void* tensor_native(const char* name, int* type) const;
|
||||
|
||||
// ---- QWEN3.6 (qwen35moe; docs/qwen36-port/step4-drafter.md). The drafter is the -MTP file's nextn block through
|
||||
// the plain graph: concat(rms_norm(embed(tok)) * enorm, rms_norm(h) * hnorm) (embedding first), eh_proj, one plain
|
||||
// attention + MoE block over the drafter's own dense KV, shared_head_norm, the main head. `h` is the trunk's
|
||||
// OUTPUT-NORMED hidden state (llama.cpp's h_nextn): the drafter applies `output_norm` to the residual rows it is
|
||||
// handed, so the caller passes the same final residual it passes for Flash-Next. Pairing: token k with the hidden
|
||||
// state of position k-1 (common/speculative.cpp), the cell convention `prefill` / `draft` already use. The second
|
||||
// path is chosen by the geometry's architecture; the Flash-Next path is unchanged.
|
||||
bool qwen36() const;
|
||||
/// The harness's one-row forward, outside any graph: the row's seams by llama.cpp's cb() names (`mtp_tok_embd`,
|
||||
/// `mtp_enorm`, `mtp_hnorm`, `mtp_concat`, `mtp_eh_proj`, `mtp_attn_norm`, `mtp_Vcur`, `mtp_Kcur_normed` (before
|
||||
/// RoPE), `mtp_Qcur_full`, `mtp_Qcur_normed` (before RoPE), `mtp_attn_pregate`, `mtp_attn_out`, `mtp_attn_residual`,
|
||||
/// `mtp_attn_post_norm`, `ffn_moe_logits`, `ffn_moe_topk` (int32 ids behind the float pointer), `ffn_moe_weights_norm`,
|
||||
/// `mtp_ffn_shexp_gated`, `mtp_ffn_out`, `mtp_post_ffn`, `mtp_shared_head_norm`, `result_output`), each handed to
|
||||
/// `seam` after a stream sync with the device pointer and the element count; `top1` gets the draft (a vocabulary
|
||||
/// id). `R_row` is the trunk's final residual (device), the K/V is written at `cell`, RoPE at `pos`. The rival
|
||||
/// readings of `DebugOpts` are the harness's negative controls and nothing else sets them.
|
||||
struct DebugOpts {
|
||||
bool hidden_first = false; ///< concat(hnorm, enorm): the wrong order
|
||||
bool skip_hnorm = false; ///< the hidden state's second norm (hnorm) left out
|
||||
};
|
||||
using SeamFn = std::function<void(const char* seam, const float* dev, int64_t n)>;
|
||||
bool debug_row(const float* R_row, int32_t token, int64_t cell, int32_t pos, const DebugOpts& o, const SeamFn& seam,
|
||||
int32_t* top1, std::string& err);
|
||||
/// The draft block's expert blob (Qwen3.6): the native layout's types and bytes, for a reader of `experts.bin`.
|
||||
int expert_gu_type() const { return exp_gu_type_; }
|
||||
int expert_d_type() const { return exp_d_type_; }
|
||||
int64_t expert_blob_bytes() const { return exp_blob_; }
|
||||
QsaState& kv_state_rw() { return st_; }
|
||||
int64_t first_needed() const { return (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0; }
|
||||
int device() const { return device_; }
|
||||
bool idle(std::string& err) {
|
||||
if (cs_ && cudaStreamSynchronize(cs_) != cudaSuccess) { err = "mtp: its stream failed"; return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
bool record_forward(int T, int step_row0, cudaStream_t cs, std::string& err);
|
||||
bool record_forward_qwen36(int T, int step_row0, cudaStream_t cs, std::string& err);
|
||||
bool load_qwen36_experts(const std::string& rt_dir, const ModelGeometry& g, uint64_t& bytes, std::string& err);
|
||||
bool check_qwen36_pack(const std::string& rt_dir, const ModelGeometry& g, std::string& err);
|
||||
int exp_gu_type_ = -1, exp_d_type_ = -1; ///< Qwen3.6: the draft experts' GGUF types (native_expert_layout)
|
||||
int64_t exp_blob_ = 0; ///< Qwen3.6: bytes per expert blob in experts_
|
||||
float* cat_ = nullptr; ///< Qwen3.6: concat(enorm, hnorm), T x 2 n_embd
|
||||
const DebugOpts* dbg_ = nullptr; ///< set by debug_row only
|
||||
const SeamFn* seam_ = nullptr; ///< set by debug_row only
|
||||
bool capture_prefill(int T, std::string& err);
|
||||
bool capture_prefill_dev(int T, std::string& err); ///< E-4: without the mapped staging (inputs copied on device)
|
||||
bool capture_round(int T, bool coupled, std::string& err);
|
||||
bool capture_step(int j, bool coupled, std::string& err);
|
||||
cudaGraphExec_t step_exec_[9] = {};
|
||||
// coupled draft sampling: its own round/step graphs (the argmax ones stay as they were), the request's
|
||||
// parameters and the penalty ring (mapped staging + device copies), the split scratch, token id -> subset index
|
||||
bool setup_coupled(std::string& err);
|
||||
cudaGraphExec_t round_exec_c_[9] = {};
|
||||
cudaGraphExec_t step_exec_c_[9] = {};
|
||||
bool coupled_ok_ = false, coupled_active_ = false;
|
||||
bool coupled_rec_ = false; ///< record_forward: the full layer ends in the coupled sampler (draft coupled_j_)
|
||||
int coupled_j_ = 0;
|
||||
strata::kernels::SamplerParams *h_cparams_ = nullptr, *m_cparams_ = nullptr, *cparams_ = nullptr;
|
||||
int32_t *h_chist_ = nullptr, *m_chist_ = nullptr, *cring_ = nullptr, *dinv_ = nullptr;
|
||||
void* cscratch_ = nullptr;
|
||||
const float* f32(const char* name) const;
|
||||
const uint16_t* bf16(const char* name) const;
|
||||
const void* q8(const char* name) const;
|
||||
|
||||
const ModelGeometry* g_ = nullptr;
|
||||
SessionState* ss_ = nullptr;
|
||||
SessionState* ple_ss_ = nullptr;
|
||||
const WeightTable* wt_ = nullptr;
|
||||
const NativeHead* head_ = nullptr;
|
||||
const float* window_R_ = nullptr;
|
||||
int max_t_ = 0;
|
||||
int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split)
|
||||
int max_drafts_ = 1 << 30;
|
||||
int64_t n_vocab_ = 0;
|
||||
uint64_t vram_ = 0;
|
||||
cudaStream_t cs_ = nullptr;
|
||||
cudaGraphExec_t prefill_exec_[9] = {};
|
||||
cudaGraphExec_t prefill_dev_exec_[9] = {};
|
||||
int32_t* pf_dev_ = nullptr; ///< E-4: a prompt's rows' token / step / position records, uploaded at once
|
||||
int64_t pf_cap_ = 0; ///< its capacity in ints
|
||||
cudaGraphExec_t round_exec_[9] = {};
|
||||
|
||||
struct Tensor { std::string name, kind; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; int type = -1; };
|
||||
std::vector<Tensor> tensors_;
|
||||
uint8_t* dense_ = nullptr;
|
||||
uint8_t* experts_ = nullptr;
|
||||
void* state_arena_ = nullptr;
|
||||
QsaState st_;
|
||||
void* arena_ = nullptr;
|
||||
|
||||
// mapped staging: tokens, step records (2*max_t rows), positions per head (2*max_t rows), the selected row,
|
||||
// the drafts out
|
||||
int32_t *h_tok_ = nullptr, *m_tok_ = nullptr, *h_step_ = nullptr, *m_step_ = nullptr;
|
||||
int32_t *h_pos_ = nullptr, *m_pos_ = nullptr, *h_row_ = nullptr, *m_row_ = nullptr;
|
||||
int32_t *h_out_ = nullptr, *m_out_ = nullptr;
|
||||
float *h_prob_ = nullptr, *m_prob_ = nullptr; // each draft's probability under the draft layer
|
||||
// the draft head: the main head's rows for a token subset (rt/draft_vocab.bin), or the whole head
|
||||
uint8_t* dhead_ = nullptr;
|
||||
int32_t* dvocab_ = nullptr;
|
||||
int64_t n_dvocab_ = 0;
|
||||
std::string rt_dir_;
|
||||
int64_t window_ = 0; // attention over the last window_ cells (0 = every cell)
|
||||
int64_t prompt_len_ = 0;
|
||||
float* probs_ = nullptr;
|
||||
// device
|
||||
int32_t *tok_ = nullptr, *step_ = nullptr, *pos_ = nullptr, *row_ = nullptr, *ident_ = nullptr;
|
||||
float *Rin_ = nullptr, *R_ = nullptr, *emb_ = nullptr, *en_ = nullptr, *e2_ = nullptr, *hn_ = nullptr, *h2_ = nullptr;
|
||||
float *mixed_ = nullptr, *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *bo_ = nullptr;
|
||||
float* xn_ = nullptr;
|
||||
uint8_t* xq_ = nullptr;
|
||||
float *qfull_ = nullptr, *qcur_ = nullptr, *kcur_ = nullptr, *vcur_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr;
|
||||
float* attn_scratch_ = nullptr;
|
||||
float *logits_ = nullptr, *w_ = nullptr, *shared_ = nullptr, *parts_ = nullptr, *y_ = nullptr, *sample_ = nullptr;
|
||||
int32_t *ids_ = nullptr, *hit_slot_ = nullptr, *hit_dst_ = nullptr, *hit_count_ = nullptr, *out_ids_ = nullptr;
|
||||
uint8_t* hit_xq_ = nullptr;
|
||||
unsigned long long* grp_ptr_ = nullptr;
|
||||
int32_t *grp_start_ = nullptr, *grp_counts_ = nullptr;
|
||||
float* hit_xs_ = nullptr;
|
||||
void* hit_scratch_ = nullptr;
|
||||
float* sh_scratch_ = nullptr;
|
||||
uint16_t* x_bf16_ = nullptr;
|
||||
float* head_logits_ = nullptr;
|
||||
float* dummy_inj_ = nullptr;
|
||||
int64_t cap_ = 0, attn_scratch_floats_ = 0;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,45 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
class WeightTable;
|
||||
|
||||
// Experimental GDN/QSA/shared-expert projection overrides. Upload unchanged native GGUF
|
||||
// blocks once, then attach them to the matching canonical WeightRef. Unsupported
|
||||
// types retain their canonical paths. Owns one Q8_1 scratch vector shared by all
|
||||
// these projections, so use one ordered session stream and keep this object
|
||||
// alive until all graphs that reference it have been destroyed and synchronized.
|
||||
class NativeDense {
|
||||
public:
|
||||
NativeDense() = default;
|
||||
~NativeDense();
|
||||
NativeDense(const NativeDense&) = delete;
|
||||
NativeDense& operator=(const NativeDense&) = delete;
|
||||
/// With layer_hi >= 0, only the `blk.<l>.` matrices with layer_lo <= l < layer_hi are uploaded (a layer
|
||||
/// split's stage holds its own layers' projections, not the whole model's); the others keep data == nullptr.
|
||||
bool load(const std::vector<std::string>& shards, WeightTable& table, std::string& err,
|
||||
bool include_ple_key = false, int64_t layer_lo = 0, int64_t layer_hi = -1);
|
||||
/// Plan v0.3 P1: the canonical tensor names `load` would serve natively from these shards (eligible name,
|
||||
/// supported type, 2-D), read from the GGUF headers only - so the canonical arena can skip them.
|
||||
static bool served_names(const std::vector<std::string>& shards, bool include_ple_key,
|
||||
std::set<std::string>& out, std::string& err);
|
||||
/// Layer split: load only blocks [lb, le) (every other `blk.N.` projection belongs to another GPU's stage; the
|
||||
/// PLE tensors are loaded everywhere). Process-wide, read by the next `load`; (-1, -1) = all layers.
|
||||
static void set_layer_range(int lb, int le);
|
||||
/// #326: a native pack whose `blk.1.ple_key.weight` row is unquantized (iq_pack --compat-bf16 of a GGUF key
|
||||
/// the native kernel also reads, e.g. OrcaRouter's IQ3_XXS) serves the PLE from that row, so it is taken out
|
||||
/// of `skip` and `load` does not upload the GGUF key over it. A quantized row leaves `skip` unchanged.
|
||||
static bool keep_unquantized_ple_key(const std::string& pack_dir, std::set<std::string>& skip, std::string& err);
|
||||
uint64_t weight_bytes() const { return bytes_; }
|
||||
size_t tensor_count() const { return weights_.size(); }
|
||||
|
||||
private:
|
||||
std::vector<void*> weights_;
|
||||
void* scratch_ = nullptr;
|
||||
uint64_t bytes_ = 0;
|
||||
};
|
||||
} // namespace strata::core
|
||||
@@ -1,68 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// Opt-in native output projection. Uploads unchanged GGUF blocks once at startup and owns its
|
||||
/// activation scratch. The normal canonical head remains available for numerical A/B comparisons.
|
||||
/// Plan v0.3 P6: any type the native MMVQ takes (Q5_K in the Q2_0 / IQ3_XXS files, IQ4_XS in IQ2_XS).
|
||||
/// `load` takes the model's shards (strata::gguf_split_paths): the architecture is checked on the first, the
|
||||
/// tensor is read from the shard that holds it.
|
||||
class NativeHead {
|
||||
public:
|
||||
NativeHead() = default;
|
||||
~NativeHead();
|
||||
NativeHead(const NativeHead&) = delete;
|
||||
NativeHead& operator=(const NativeHead&) = delete;
|
||||
|
||||
bool load(const std::vector<std::string>& shards, int64_t n_in, int64_t n_out, std::string& err);
|
||||
bool run(const float* mixed, float* logits, void* stream, std::string& err) const;
|
||||
uint64_t weight_bytes() const { return bytes_; }
|
||||
bool loaded() const { return weights_ != nullptr; }
|
||||
/// Plan v0.3 P6: the GGUF blocks, for the verify window's multi-column head.
|
||||
const void* weights() const { return weights_; }
|
||||
int type() const { return type_; }
|
||||
/// Bytes of one vocabulary row.
|
||||
size_t row_bytes() const { return n_out_ > 0 ? (size_t) (bytes_ / (uint64_t) n_out_) : 0; }
|
||||
|
||||
private:
|
||||
void* weights_ = nullptr;
|
||||
void* scratch_ = nullptr;
|
||||
uint64_t bytes_ = 0;
|
||||
int n_in_ = 0, n_out_ = 0;
|
||||
int type_ = -1;
|
||||
};
|
||||
|
||||
/// Plan v0.3 P6: `token_embd.weight` in its GGUF form (the IQ model files), in mapped pinned host memory: a row
|
||||
/// is read over PCIe per token, so the table costs no VRAM. `embed_row`, the verify window and the MTP drafter
|
||||
/// use it instead of the canonical table when it is set (`set_native_embed`).
|
||||
class NativeEmbed {
|
||||
public:
|
||||
NativeEmbed() = default;
|
||||
~NativeEmbed();
|
||||
NativeEmbed(const NativeEmbed&) = delete;
|
||||
NativeEmbed& operator=(const NativeEmbed&) = delete;
|
||||
bool load(const std::vector<std::string>& shards, int64_t n_embd, int64_t n_vocab, std::string& err);
|
||||
/// Rows for device token ids.
|
||||
void gather_dev(const int32_t* tokens, int64_t n_tok, float* out, void* stream) const;
|
||||
/// One row for a host token id.
|
||||
void gather_one(int64_t token, float* out, void* stream) const;
|
||||
uint64_t bytes() const { return bytes_; }
|
||||
int type() const { return type_; }
|
||||
|
||||
private:
|
||||
void* host_ = nullptr;
|
||||
const void* dev_ = nullptr;
|
||||
uint64_t bytes_ = 0;
|
||||
size_t row_ = 0;
|
||||
int64_t n_embd_ = 0, n_vocab_ = 0;
|
||||
int type_ = -1;
|
||||
};
|
||||
void set_native_embed(const NativeEmbed* e);
|
||||
const NativeEmbed* native_embed();
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,22 +0,0 @@
|
||||
#pragma once
|
||||
// Multi-GPU: make `device` current for a scope and restore the caller's device after it. An object that owns CUDA
|
||||
// streams, graphs and buffers on one device (a verify stage, the drafter) wraps its public calls in this, so the
|
||||
// caller's thread may be on any device. A negative device, or the device already current, does nothing.
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
struct OnDevice {
|
||||
int previous = -1;
|
||||
explicit OnDevice(int device) {
|
||||
int cur = 0;
|
||||
if (device >= 0 && cudaGetDevice(&cur) == cudaSuccess && cur != device && cudaSetDevice(device) == cudaSuccess)
|
||||
previous = cur;
|
||||
}
|
||||
~OnDevice() { if (previous >= 0) cudaSetDevice(previous); }
|
||||
OnDevice(const OnDevice&) = delete;
|
||||
OnDevice& operator=(const OnDevice&) = delete;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,106 +0,0 @@
|
||||
// include/strata/core/peer_experts.hpp - multi-GPU: a second expert tier on another GPU.
|
||||
//
|
||||
// The primary GPU (device 0) keeps everything it had: the dense weights, the KV cache, the MTP layer, its own
|
||||
// adaptive expert tier and the captured verify graph. This class adds an expert tier on a SECOND card. From
|
||||
// the verify graph's point of view nothing changes: for each layer the pool thread decides which routed experts
|
||||
// the primary computes (its VRAM tier, the PCIe share), and every remaining expert is a "CPU row" the graph reads
|
||||
// from mapped host memory after the pool raises its flag. The peer takes the rows whose experts it holds: the
|
||||
// pool thread launches them on the peer right after publishing the primary's plan, the CPU computes the rest at
|
||||
// the same time, and the peer's rows are written into the same mapped rows before the pool returns.
|
||||
//
|
||||
// The peer computes with the SAME kernels as the primary's hit path (q8_1 activations + native_expert_grouped),
|
||||
// from the same activation values, so an expert gives bit-identical rows on either card.
|
||||
//
|
||||
// The tier follows the conversation like the primary's: `adapt` swaps the most-routed experts that neither card
|
||||
// holds into the peer's least-used slots (per layer, so a slot keeps its layer's blob size).
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/expert_cache.hpp"
|
||||
#include "strata/core/expert_source.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// multi-GPU: set once at startup when a peer device is configured (--peer-device N). The mapped host buffers
|
||||
/// the peer card writes into are then allocated with cudaHostAllocPortable; without a peer the flag stays off.
|
||||
void set_peer_portable(bool on);
|
||||
bool peer_portable();
|
||||
|
||||
class PeerExperts {
|
||||
public:
|
||||
PeerExperts() = default;
|
||||
~PeerExperts();
|
||||
PeerExperts(const PeerExperts&) = delete;
|
||||
PeerExperts& operator=(const PeerExperts&) = delete;
|
||||
|
||||
/// Opens the tier on `device`: fills it with the first pairs of `ranked` that `primary` does not hold, as many
|
||||
/// as fit in the card's free memory minus `reserve_mib` (`max_slots` > 0 caps the count).
|
||||
bool open(int device, const std::vector<std::pair<int32_t, int32_t>>& ranked, const ExpertCache& primary,
|
||||
ExpertSource& src, int64_t n_layers, int64_t n_expert, int reserve_mib, int64_t max_slots,
|
||||
std::string& err);
|
||||
void close();
|
||||
bool valid() const { return device_ >= 0; }
|
||||
int device() const { return device_; }
|
||||
|
||||
/// Whether the peer holds (layer, expert) right now.
|
||||
bool has(int64_t layer, int64_t expert) const { return res_[(size_t) (layer * n_expert_ + expert)] >= 0; }
|
||||
|
||||
/// The device address of (layer, expert)'s blob on the peer, or null when it is not resident.
|
||||
const uint8_t* slot_ptr(int64_t layer, int64_t expert) {
|
||||
const int32_t sl = res_[(size_t) (layer * n_expert_ + expert)];
|
||||
return sl >= 0 ? cache_.device_slot(sl) : nullptr;
|
||||
}
|
||||
/// Whether the primary (device 0) and the peer can read each other's memory directly (NVLink / PCIe P2P).
|
||||
bool p2p() const { return p2p_; }
|
||||
|
||||
/// Starts the peer's share of one layer: the entries i with kind[i] == 2 (x: n_tok rows of n_embd floats).
|
||||
/// multi-GPU: with `out` (pinned, portable host rows) the peer writes its rows straight into
|
||||
/// out[entry] with a scatter kernel (no D2H copy + host memcpy in finish); STRATA_PEER_DIRECT=0: the old way.
|
||||
bool launch(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, int64_t k, const int32_t* kind,
|
||||
std::string& err, float* out = nullptr);
|
||||
/// Waits for the launched share and writes its rows into `out` (row i = entry i, n_embd floats).
|
||||
bool finish(float* out, std::string& err);
|
||||
|
||||
/// Adaptive tier: swap up to `max_swaps` experts routed at least twice that neither the primary (`res0`, slot
|
||||
/// or -1) nor the peer holds into the peer's least-used slots. Copies run on the peer's refill stream; a
|
||||
/// swapped-in expert becomes resident at `apply_pending`. Call only between verify windows.
|
||||
bool adapt(const float* usage, const int32_t* res0, int max_swaps, std::string& err);
|
||||
void apply_pending(bool wait);
|
||||
|
||||
int64_t resident() const { return resident_; }
|
||||
/// the last launch writes its rows into the host rows itself (the caller must not touch them)
|
||||
bool launched_direct() const { return launched_direct_; }
|
||||
double gib() const { return cache_.gib(); }
|
||||
int64_t entries() const { return entries_; } ///< routed entries the peer computed
|
||||
int64_t experts() const { return experts_; } ///< distinct (layer, expert) the peer computed
|
||||
int64_t swaps() const { return swaps_; }
|
||||
double ms_wait = 0; ///< host time spent in finish() waiting for the peer
|
||||
|
||||
private:
|
||||
int device_ = -1;
|
||||
bool p2p_ = false;
|
||||
int64_t n_layers_ = 0, n_expert_ = 0;
|
||||
ExpertCache cache_;
|
||||
ExpertSource* src_ = nullptr;
|
||||
std::vector<int32_t> res_; ///< [n_layers * n_expert] -> peer slot or -1
|
||||
std::vector<std::pair<int32_t, int32_t>> pending_; ///< (residency index, slot) once the copies land
|
||||
int64_t resident_ = 0, entries_ = 0, experts_ = 0, swaps_ = 0;
|
||||
cudaStream_t stream_ = nullptr, refill_ = nullptr;
|
||||
cudaEvent_t refill_ev_ = nullptr;
|
||||
float* h_x_ = nullptr; float* d_x_ = nullptr; // n_tok x n_embd
|
||||
float* h_out_ = nullptr; float* d_out_ = nullptr; // compact rows
|
||||
void* h_meta_ = nullptr; void* d_meta_ = nullptr; // groups: ptr | start | dst | tok | count
|
||||
uint8_t* d_q8_ = nullptr;
|
||||
void* d_scratch_ = nullptr;
|
||||
std::vector<int32_t> row_of_; ///< compact row -> original entry
|
||||
int64_t launched_rows_ = 0;
|
||||
bool launched_direct_ = false;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,152 +0,0 @@
|
||||
// include/strata/core/pinned.hpp - P2.S1: the host arena the expert weights live in.
|
||||
//
|
||||
// 33.97 GB of expert weights cannot fit in a 12 GB card, so they stay in host memory and are streamed. That
|
||||
// makes this arena the engine's real working set: it must be PAGE-LOCKED for the copy engine to reach full
|
||||
// bandwidth, and it must say which backing it got, because the two options differ by more than twice in TLB
|
||||
// reach:
|
||||
//
|
||||
// * LARGE PAGES (2 MB) - `mmap(MAP_HUGETLB)` / hugetlbfs on Linux, `VirtualAlloc(MEM_LARGE_PAGES)` on
|
||||
// Windows. 33.97 GB at 4 KB pages is 8.3 million TLB entries, which does not fit in any TLB, so every
|
||||
// block of every expert matvec takes TLB misses.
|
||||
// * NORMAL PAGES - the fallback. Correct, slower, and it must be REPORTED rather than silently accepted:
|
||||
// "the engine adapts to the machine it is on" is only true if the engine says what it got. On Windows
|
||||
// large pages additionally need SeLockMemoryPrivilege, which a normal user account does not have, so this
|
||||
// fallback is the common case and not an error path.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
enum class PageBacking { LargePages, NormalPages, PinnedByCuda };
|
||||
|
||||
/// #243: STRATA_ARENA_PIN_GIB, the cap on the expert arena's CUDA registration in GiB. -1 when unset (the engine
|
||||
/// decides, as in 0.1.30), 0 = no cap (the whole arena, or as many slices as the driver takes), N > 0 = at most N GiB,
|
||||
/// -2 for "auto" (Windows: the sliced pin stays below the GPU's shared-memory budget).
|
||||
int arena_pin_cap_gib();
|
||||
|
||||
struct PinnedArena {
|
||||
void* base = nullptr;
|
||||
uint64_t capacity = 0;
|
||||
PageBacking backing = PageBacking::NormalPages;
|
||||
std::string note; // why the backing is what it is, for the startup print
|
||||
uint64_t locked_bytes = 0; // resident via the working-set lock when CUDA could not pin it
|
||||
/// Plan v0.3 P5: when the whole arena cannot be registered, it is registered in `slice`-byte pieces from the
|
||||
/// start; this is the pinned prefix (a copy that stays inside one slice can then DMA straight from the arena).
|
||||
uint64_t registered_bytes = 0;
|
||||
uint64_t slice_bytes = 0;
|
||||
int registered_slices = 0;
|
||||
|
||||
PinnedArena() = default;
|
||||
/// `slice`: the piece size for the per-slice registration fallback (0 = none).
|
||||
explicit PinnedArena(uint64_t bytes, uint64_t slice = 0);
|
||||
/// Plan v0.3 P6: slices of different sizes (one per layer of a native pack), given as their start offsets
|
||||
/// followed by the end of the last one. `slice_starts` holds the registered ones.
|
||||
/// `max_pinned_bytes`: optional cap on CUDA registration. 0 preserves the normal unrestricted path.
|
||||
/// `shared_file`: on Linux, use a file-backed MAP_SHARED mapping instead of anonymous memory.
|
||||
/// `shared_pack_hash` identifies the pack that is allowed to populate that backing. The file carries a
|
||||
/// small header and is refused when its stored hash does not match. Empty `shared_file` preserves the
|
||||
/// existing allocation path. Population/coordination and backing-file lifetime remain the caller's job.
|
||||
PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds, uint64_t max_pinned_bytes = 0,
|
||||
const std::string& shared_file = {}, uint64_t shared_pack_hash = 0);
|
||||
std::vector<uint64_t> slice_starts;
|
||||
void* mapping_base = nullptr; ///< actual mapping start; differs from base when a shared-file header exists
|
||||
uint64_t mapping_bytes = 0; ///< bytes to release from mapping_base
|
||||
~PinnedArena();
|
||||
PinnedArena(const PinnedArena&) = delete;
|
||||
PinnedArena& operator=(const PinnedArena&) = delete;
|
||||
|
||||
bool valid() const { return base != nullptr; }
|
||||
uint8_t* data() const { return (uint8_t*) base; }
|
||||
};
|
||||
|
||||
struct LoadStats {
|
||||
double seconds = 0.0;
|
||||
// Loader fix: the two halves of `seconds`, both SUMMED OVER THE READER THREADS rather than wall clock, so
|
||||
// either can exceed `seconds` when the threads overlap. They exist to separate the read from the copy and
|
||||
// the hash: an 8 MiB chunk that reaches the disk as ~2048 4 KiB reads spends its time in the first one.
|
||||
double read_seconds = 0.0; // inside the read call only: no seek, no copy, no hash
|
||||
double copy_seconds = 0.0; // memcpy + FNV-1a
|
||||
// A short read is not a slow load, it is a WRONG one: the caller must refuse the pack rather than run
|
||||
// on an arena whose tail was never written. `seconds` alone cannot say that (it is -1.0 on failure, but
|
||||
// the caller's own check is on the REQUESTED byte count, which a refused read does not change).
|
||||
bool ok = true; // false: the load failed, see `error`
|
||||
std::string error; // why it failed, for the caller's message
|
||||
uint64_t bytes = 0;
|
||||
uint64_t layers = 0;
|
||||
std::vector<uint64_t> layer_checksums; // one FNV-1a per layer
|
||||
double gib_per_second() const { return seconds > 0 ? (double) bytes / (1024.0 * 1024 * 1024) / seconds : 0.0; }
|
||||
// Aggregate rate of the readers WHILE THEY WERE INSIDE THE READ CALL: `bytes` over the mean per-thread
|
||||
// read time. `gib_per_second()` above divides the same bytes by the wall clock of the whole loop, which
|
||||
// also contains the copy and the hash, so the two differ by how much of the loop was not I/O.
|
||||
double read_gib_per_second(int threads) const {
|
||||
if (read_seconds <= 0.0 || threads < 1) return 0.0;
|
||||
return (double) bytes / (1024.0 * 1024 * 1024) / (read_seconds / (double) threads);
|
||||
}
|
||||
};
|
||||
|
||||
// Load `layers` layers of the expert arena into `dst` with `threads` readers, `chunk` bytes at a time.
|
||||
// Each thread opens its OWN handle and seeks, which is the portable form of parallel pread: a shared handle
|
||||
// needs a lock around the seek and defeats the parallelism on Windows.
|
||||
//
|
||||
// The reads go through `fread()` on a per-thread `FILE*`, NOT through `std::ifstream`. MSVC's
|
||||
// `basic_filebuf::xsgetn` splits every request larger than `_INTERNAL_BUFSIZ - 1` into 4095-byte `fread()`
|
||||
// calls, so an 8 MiB `chunk` reached the disk as ~2048 4 KiB operations and the chunking did nothing at all
|
||||
// (measured on a 42.9 GB pack: 1222 s, 4096 bytes per operation, 0.03 GiB/s). `fread()` hands a request
|
||||
// larger than the stream buffer straight to `_read()`/`ReadFile()`, which is what `chunk` is for. The
|
||||
// control flow, the copy, the per-layer FNV-1a and therefore the checksums are unchanged, so a pack loaded
|
||||
// by the old and the new reader must produce identical `layer_checksums`.
|
||||
LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_bytes, uint64_t blobs_per_layer,
|
||||
uint64_t layers, int threads, uint64_t chunk);
|
||||
/// Plan v0.3 P6: the same with one byte range per layer (`layer_off[L]`, `layer_bytes[L]`).
|
||||
LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,
|
||||
const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk);
|
||||
|
||||
/// The same ranges read UNBUFFERED straight into `dst` (Windows): no staging buffer and no file-cache copy - the
|
||||
/// drive's DMA lands where the experts live. Every range, `dst` and `chunk` must be 4 KiB aligned; returns ok =
|
||||
/// false with an empty `error` when they are not (or off Windows), and the caller falls back to load_experts_ranges.
|
||||
LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,
|
||||
const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk);
|
||||
|
||||
/// Whether the expert files are better read unbuffered (Windows; false elsewhere): a timed probe of random 64 KiB
|
||||
/// reads says they are not in the OS file cache (a cached read takes ~10 us, the drive ~80), and the RAM left
|
||||
/// beside the arena (`arena_bytes`) could not keep them cached for the next start either - so a warm restart after
|
||||
/// an idle unload never gets slower, and only a start that reads the drive anyway skips the cache's copy.
|
||||
/// STRATA_UNBUFFERED_LOAD=1 / 0 forces it. `why` says what decided.
|
||||
/// `cache_counts` false (the file tier with a RAM budget): only whether the files could be kept decides - their mapped
|
||||
/// pages land in the process's working set, so a partly cached file would still take the RAM the budget was sized for.
|
||||
/// `read_bytes` (#577): the bytes the files are read for, when that is less than the files (the file tier reads only
|
||||
/// the experts outside its RAM copy); `kAllFileBytes` = every byte of `files`. See platform::file_cache_keeps.
|
||||
constexpr uint64_t kAllFileBytes = ~0ull;
|
||||
bool experts_unbuffered(const std::vector<std::string>& files, uint64_t arena_bytes, std::string& why,
|
||||
bool cache_counts = true, uint64_t read_bytes = kAllFileBytes);
|
||||
|
||||
// FNV-1a 64. Per layer, so a corrupt or short read names WHICH layer rather than just failing a whole-file
|
||||
// comparison - the same reason the Phase 1 tools report the first differing element.
|
||||
uint64_t fnv1a64(const uint8_t* p, uint64_t n, uint64_t seed = 1469598103934665603ull);
|
||||
|
||||
// ---- the expert stream -----------------------------------------------------
|
||||
//
|
||||
// THIS IS THE NUMBER THE OBJECTIVE DEPENDS ON. With one expert per stream, the design's own arithmetic is:
|
||||
//
|
||||
// per token: E = 663.6 MB of expert weights, of which only the MISSES cross the bus
|
||||
// miss fraction (1 - h) x 663.6 MB / measured bandwidth = milliseconds per token
|
||||
//
|
||||
// So `h` (the VRAM hit rate, ~0.167 by design) is only worth anything if a per-expert transfer can actually
|
||||
// reach the bus's bandwidth. A 1,382,400-byte copy is SMALL, and if small copies run at a fraction of large
|
||||
// ones then the architecture's central constant is wrong and no kernel optimisation can fix it. That is what
|
||||
// this measures: the same total bytes at several granularities, so the difference is visible.
|
||||
struct StreamStats {
|
||||
double seconds = 0.0;
|
||||
uint64_t bytes = 0;
|
||||
uint64_t chunk = 0;
|
||||
double gib_per_second() const { return seconds > 0 ? (double) bytes / (1024.0 * 1024 * 1024) / seconds : 0.0; }
|
||||
};
|
||||
|
||||
// Copy `bytes` from pinned host memory at `src` to a device buffer of `chunk` bytes, in `chunk`-sized
|
||||
// transfers, `iters` times. The destination is REUSED, so this measures the bus and not allocation.
|
||||
StreamStats stream_bandwidth(const uint8_t* src, uint64_t bytes, uint64_t chunk, int iters);
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,59 +0,0 @@
|
||||
// include/strata/core/progress.hpp - issue #29: whether a request is still moving, and where it is.
|
||||
//
|
||||
// The engine's host loop and the GPU wait on each other through flags; a protocol bug there does not crash, it
|
||||
// spins forever (the GPU "100%", one CPU core busy, no tokens). `--serve` runs a watchdog thread over this: a
|
||||
// request whose heartbeat stops for `STRATA_WATCHDOG_S` seconds (default 60; 0 = off) ends the engine with the
|
||||
// stage it was stuck in, and the server starts it again instead of hanging. Tokens, prompt chunks and verify
|
||||
// windows beat; the stage is two relaxed stores per layer, which the token path does not notice.
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
struct Progress {
|
||||
std::atomic<uint64_t> beats{0};
|
||||
std::atomic<bool> busy{false};
|
||||
std::atomic<const char*> where{"idle"};
|
||||
std::atomic<int64_t> detail{-1};
|
||||
std::atomic<int64_t> chunk{-1}; ///< #251: the prompt chunk (its first position) a batched-read stage is in
|
||||
std::atomic<int64_t> since_ms{0}; ///< when `where` was set (steady clock): how long a stage has lasted
|
||||
std::atomic<uint64_t> ticks{0}; ///< layers served: a window that still moves, slowly, against one that stopped
|
||||
};
|
||||
|
||||
inline int64_t progress_now_ms() {
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
/// What the watchdog prints about a part of the engine when it fires (the expert pool, the verify window).
|
||||
using DiagFn = void (*)(std::FILE*);
|
||||
inline std::atomic<DiagFn>& diag_pool_fn() { static std::atomic<DiagFn> f{nullptr}; return f; }
|
||||
inline std::atomic<DiagFn>& diag_verify_fn() { static std::atomic<DiagFn> f{nullptr}; return f; }
|
||||
/// #267: what a path that ends the engine runs first - it releases the GPU's spin waits on host flags (the verify
|
||||
/// window's), so no kernel stays resident while the process goes away (on Windows that left the GPU "lost").
|
||||
inline std::atomic<DiagFn>& release_gpu_fn() { static std::atomic<DiagFn> f{nullptr}; return f; }
|
||||
inline void release_gpu_waits(std::FILE* f) {
|
||||
if (auto fn = release_gpu_fn().load()) fn(f);
|
||||
}
|
||||
|
||||
inline Progress& progress() {
|
||||
static Progress p;
|
||||
return p;
|
||||
}
|
||||
|
||||
inline void progress_at(const char* where, int64_t detail = -1, int64_t chunk = -1) {
|
||||
Progress& p = progress();
|
||||
p.where.store(where, std::memory_order_relaxed);
|
||||
p.detail.store(detail, std::memory_order_relaxed);
|
||||
p.chunk.store(chunk, std::memory_order_relaxed);
|
||||
p.since_ms.store(progress_now_ms(), std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
inline void progress_beat() { progress().beats.fetch_add(1, std::memory_order_relaxed); }
|
||||
inline void progress_tick() { progress().ticks.fetch_add(1, std::memory_order_relaxed); }
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,30 +0,0 @@
|
||||
// include/strata/core/qsa_shapes.hpp - THE ONE builder of a `QsaShapes` from a `ModelGeometry`.
|
||||
//
|
||||
// Five sites used to transcribe the same six assignments by hand (layer.cpp, verify.cpp, mtp.cpp, session.cpp and
|
||||
// prefill.cpp), and the Qwen3.6 port showed what that costs: the geometry says "no indexer" with two zeros
|
||||
// (`idx_q_heads`, `idx_key_dim`) while the kernels' dense predicate (`qsa_dense`) wants the selection budget
|
||||
// `idx_top_k` zero as well - a builder that copies the two and keeps `qsa_real_shapes()`'s 2,048 makes a shape
|
||||
// that is neither sparse nor dense, which `qsa.cu`'s guard refuses as "not set up" at the first KV append.
|
||||
// Header-only so the parity test can build the shape without linking the engine.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/layout.hpp"
|
||||
#include "strata/kernels/qsa.hpp"
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// The kernels' geometry for this model: the attention widths from the file, `n_rot`, `idx_block`, `page_size` and
|
||||
/// (with an indexer) `idx_top_k` from the kernel contracts in `qsa_real_shapes()`; without an indexer the three
|
||||
/// indexer widths are zero together, which is what `qsa_dense()` and the kernels' guard test.
|
||||
inline strata::kernels::QsaShapes qsa_shapes(const ModelGeometry& g) {
|
||||
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
|
||||
s.n_head = g.n_head;
|
||||
s.n_head_kv = g.n_head_kv;
|
||||
s.head_dim = g.head_dim;
|
||||
s.idx_n_head = g.idx_q_heads;
|
||||
s.idx_dim = g.idx_key_dim;
|
||||
if (!g.has_indexer()) { s.idx_n_head = 0; s.idx_dim = 0; s.idx_top_k = 0; }
|
||||
return s;
|
||||
}
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,53 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
class RemoteExperts;
|
||||
class ExpertSource;
|
||||
|
||||
// Remote Expert Decode Optimization v1 on existing helper caches. One instance per serial engine.
|
||||
class RemoteExpertOpt {
|
||||
public:
|
||||
RemoteExpertOpt() = default;
|
||||
~RemoteExpertOpt();
|
||||
RemoteExpertOpt(const RemoteExpertOpt&) = delete;
|
||||
RemoteExpertOpt& operator=(const RemoteExpertOpt&) = delete;
|
||||
|
||||
void attach(RemoteExperts& remote); // before RemoteExperts::open
|
||||
bool init(std::string& err); // after all helper caches are open
|
||||
bool owns(int64_t layer, int32_t expert) const;
|
||||
bool adapt(const std::vector<float>& usage, const std::vector<int32_t>& primary,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& pending, int max_swaps,
|
||||
ExpertSource& source);
|
||||
|
||||
// Bracket the existing pool callback; its signature and dispatch remain unchanged.
|
||||
void begin(const float* weights, int token_begin, int tokens);
|
||||
void end() { weights_ = nullptr; }
|
||||
void copy_rows(float* dst, const float* src, int token_begin, int tokens,
|
||||
const int32_t* hit_rows, const int32_t* count, void* stream) const;
|
||||
void combine(float* dst, float* scratch, int token_begin, int tokens,
|
||||
const uint32_t* skip, uint32_t ring, void* stream) const;
|
||||
|
||||
private:
|
||||
friend class RemoteExperts;
|
||||
static size_t metadata_bytes();
|
||||
bool active() const { return weights_ != nullptr; }
|
||||
void prepare(const RemoteExperts& remote, void* metadata) const;
|
||||
bool reduce(RemoteExperts& remote, const void* metadata, std::string& err);
|
||||
void accumulate(const RemoteExperts& remote);
|
||||
|
||||
struct Peer { RemoteExperts* remote; float* sum = nullptr; };
|
||||
std::vector<Peer> peers_;
|
||||
float* h_sum_ = nullptr;
|
||||
float* m_sum_ = nullptr;
|
||||
int32_t* h_mask_ = nullptr;
|
||||
int32_t* m_mask_ = nullptr;
|
||||
const float* weights_ = nullptr;
|
||||
int token_begin_ = 0, tokens_ = 0;
|
||||
};
|
||||
} // namespace strata::core
|
||||
@@ -1,89 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/expert_cache.hpp"
|
||||
#include "strata/core/expert_source.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
class RemoteExpertOpt;
|
||||
|
||||
/// A static, profile-filled expert tier on another CUDA device. CUDA0 keeps all
|
||||
/// dense weights and state; results return through the existing pinned CPU rows.
|
||||
class RemoteExperts {
|
||||
public:
|
||||
RemoteExperts() = default;
|
||||
~RemoteExperts();
|
||||
RemoteExperts(const RemoteExperts&) = delete;
|
||||
RemoteExperts& operator=(const RemoteExperts&) = delete;
|
||||
|
||||
/// Initialise the device before the host expert arena registers
|
||||
/// tens of GiB of portable mapped memory with CUDA.
|
||||
static bool preflight(int device, double& free_gib, std::string& err);
|
||||
bool open(int device, int slots, int64_t layers, int64_t experts,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& ranked,
|
||||
const ExpertCache& primary, ExpertSource& source,
|
||||
std::vector<uint8_t>& claimed, std::string& err, bool auto_size = false);
|
||||
void close();
|
||||
|
||||
/// `kind` is the primary verifier's classification (-1 = CPU candidate),
|
||||
/// or null on the one-token path. Entries already served on CUDA0 are excluded.
|
||||
bool begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok,
|
||||
int64_t k, const int32_t* kind, const int32_t* primary_res,
|
||||
std::string& err);
|
||||
bool owns(int64_t index) const { return owned_[(size_t) index] != 0; }
|
||||
bool optimized_decode() const { return remote_opt_ != nullptr; }
|
||||
bool finish(float* out, std::string& err);
|
||||
int64_t resident() const { return cache_.resident(); }
|
||||
int64_t computed() const { return computed_; }
|
||||
int64_t launched_layers() const { return launched_layers_; }
|
||||
double gib() const { return cache_.gib(); }
|
||||
uint64_t returned_bytes() const { return returned_bytes_; }
|
||||
uint64_t full_row_bytes() const { return full_row_bytes_; }
|
||||
/// host time spent in begin() (staging + launches) and in finish() (waiting for this GPU), cumulative
|
||||
double ms_begin() const { return ms_begin_; }
|
||||
double ms_wait() const { return ms_wait_; }
|
||||
|
||||
private:
|
||||
friend class RemoteExpertOpt;
|
||||
RemoteExpertOpt* remote_opt_ = nullptr;
|
||||
int device_ = -1;
|
||||
int64_t n_expert_ = 0;
|
||||
int32_t groups_ = 0;
|
||||
int64_t computed_ = 0;
|
||||
int64_t launched_layers_ = 0;
|
||||
uint64_t returned_bytes_ = 0;
|
||||
uint64_t full_row_bytes_ = 0;
|
||||
double ms_begin_ = 0, ms_wait_ = 0;
|
||||
ExpertCache cache_;
|
||||
cudaStream_t stream_ = nullptr;
|
||||
float* h_x_ = nullptr;
|
||||
float* h_out_ = nullptr;
|
||||
void* h_meta_ = nullptr;
|
||||
float* d_x_ = nullptr;
|
||||
float* z_x_ = nullptr; ///< h_x_ as the helper GPU sees it (zero-copy: no input copy per layer)
|
||||
float* z_out_ = nullptr; ///< h_out_ as the helper GPU sees it (zero-copy: no result copy)
|
||||
bool zero_copy_ = false;
|
||||
float* d_out_ = nullptr;
|
||||
uint8_t* d_q8_ = nullptr;
|
||||
float* d_scales_ = nullptr;
|
||||
void* d_scratch_ = nullptr;
|
||||
void* d_meta_ = nullptr; ///< one contiguous upload of grouped indices, instead of five small copies
|
||||
int32_t* d_start_ = nullptr;
|
||||
int32_t* d_dst_ = nullptr;
|
||||
int32_t* d_tok_ = nullptr;
|
||||
int32_t* d_count_ = nullptr;
|
||||
unsigned long long* d_ptr_ = nullptr;
|
||||
std::vector<uint8_t> owned_;
|
||||
std::vector<uint8_t> layers_present_;
|
||||
std::vector<int32_t> group_of_, group_id_;
|
||||
std::vector<int32_t> start_, dst_, tok_, original_row_;
|
||||
std::vector<unsigned long long> ptr_;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,436 +0,0 @@
|
||||
// include/strata/core/session.hpp - ONE TOKEN through all 48 layers, and the doorbell protocol between them.
|
||||
//
|
||||
// P2.S5's host loop, and the first place the engine runs a whole forward pass rather than one block. What it
|
||||
// owns is the ORDER across layers and the state that outlives a layer:
|
||||
//
|
||||
// * the gated residual stack `R` - (hc, n_embd), which every block reads and writes;
|
||||
// * 12 QSA states (KV cache + indexer) and 36 GDN states (recurrence + conv history), because `is_qsa_layer`
|
||||
// splits the 48 layers 12/36 and the two kinds of state have nothing in common;
|
||||
// * the per-token expert handoff, which is where the CPU pool meets the GPU.
|
||||
//
|
||||
// WHY THE LAYER GRAPHS ARE CAPTURED AND THE LOOP IS NOT. A graph bakes in its arguments, so the graph unit is
|
||||
// ONE LAYER: everything per-token (the position, the step counts) arrives through fixed-address device buffers
|
||||
// (rounds 211-214), and the HOST decides when each layer runs. That decision is the whole point - it is what
|
||||
// lets the CPU expert pool start while the GPU is still working on the next layer.
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/hit_hook.hpp"
|
||||
#include "strata/core/layer.hpp"
|
||||
#include "strata/kernels/cpu/pool.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// Everything a sequence needs that is NOT a weight: the per-layer state, the block scratch, and the pinned
|
||||
/// handoff between the GPU and the CPU expert pool.
|
||||
struct SessionState {
|
||||
int64_t max_cells = 0;
|
||||
|
||||
GdnBuffers gdn; ///< the 36 GDN layers share one set of scratch; their STATE is per layer
|
||||
float* gdn_state = nullptr; ///< (n_gdn_layers, gdn_state_floats)
|
||||
|
||||
QsaState* qsa_states = nullptr; ///< one per QSA layer
|
||||
void* qsa_state_arena = nullptr;
|
||||
QsaBuffers qsa_bufs; ///< scratch, shared across the 12 (they never run concurrently)
|
||||
void* qsa_buf_arena = nullptr;
|
||||
|
||||
MoEBuffers moe;
|
||||
void* moe_arena = nullptr;
|
||||
BlockBuffers block;
|
||||
void* block_arena = nullptr;
|
||||
|
||||
float* R = nullptr; ///< alias of `block.R`, named for what it means at this level
|
||||
int64_t k = 10; ///< experts per token
|
||||
|
||||
// **THE LAYER-RANGE CARVE (multi-GPU).** A split stage's session used to carve state for ALL 48 layers
|
||||
// (every QSA KV pool at max_cells, every GDN recurrence) while running only its slice - the same
|
||||
// whole-model-sized-buffer disease the QSA chunked-prefill PR cured upstream. A session now owns
|
||||
// [layer_lo, layer_hi): `qsa_states`/`gdn_state` keep GLOBAL ordinal indexing, the arrays simply hold
|
||||
// fewer rows, so per-layer consumers subtract `gdn_ord0`, and every old model-level `qsa_states[0]` use
|
||||
// (the shared RoPE table, the prefill staging identity, the MTP rope borrow) reads `qsa_states[primary]`.
|
||||
// A range with no QSA layer still carves ONE primary state so those model-level uses stay valid.
|
||||
int64_t layer_lo = 0, layer_hi = 0; ///< resolved by `session_init` (hi = n_layers for the full range)
|
||||
int64_t qsa_ord0 = 0; ///< global QSA ordinal of the first allocated state
|
||||
int64_t qsa_alloc = 0; ///< allocated QSA states (>= 1 whenever the model has any)
|
||||
int64_t gdn_ord0 = 0; ///< global GDN ordinal of `gdn_state` row 0
|
||||
int64_t gdn_alloc = 0; ///< allocated GDN rows
|
||||
int qsa_primary() const { return (int) qsa_ord0; }
|
||||
/// The doorbell the host loop polls. Null until a caller provides one - the engine runs without it, and
|
||||
/// neither `session_token` nor `session_replay` looks at it.
|
||||
const Doorbell* db = nullptr;
|
||||
|
||||
// ================================ THE PLE, AND IT IS SEQUENCE STATE ================================
|
||||
//
|
||||
// **THE PLE IS A LAYER-1 MODULE AND THIS ENGINE DID NOT RUN IT, WHICH IS WHY C1 FAILED** (LEDGER L123).
|
||||
// Every part of it was already built and parity-tested - the hash against `ref/ngram.py` with the
|
||||
// artifact's own constants, the IQ4_NL row read against numpy over the original GGUF, and the block
|
||||
// against ggml's own graph - and none of it was ever called from the model path. These fields are what
|
||||
// was missing on the state side.
|
||||
//
|
||||
// `ple_prev` is the last two tokens OLDEST FIRST with `-1` where there is none, which is exactly
|
||||
// `ngram_rows`' `prev` argument; `ple_token` is the token being decoded. **They are advanced by the
|
||||
// DRIVER, once per token**, because the hash is a function of the sequence and not of a layer.
|
||||
int32_t ple_prev[2] = {-1, -1};
|
||||
int32_t ple_token = -1;
|
||||
/// `NG_HIST` rows of `hc_dim` NORMALIZED history, **ROW-FASTEST**: `ple_hist[row + NG_HIST*channel]`.
|
||||
/// That is `ggml_reshape_3d(state, d_conv-1, conv_channels, n_seqs)`, not a layout choice - the transposed
|
||||
/// reading fails ggml's own assert (`ple_layer_xcheck.cpp` L79-83).
|
||||
float* ple_hist = nullptr;
|
||||
/// **THE WHOLE PLE RUN LIVES HERE, AND THAT IS NOT A CONVENIENCE.** Its history and its token window are
|
||||
/// sequence state, so the session is where they belong - and putting the rest of it here too means
|
||||
/// `session_capture`/`session_loop`/`session_token` need no new parameter to reach it. A `PleRun` whose
|
||||
/// `ready()` is false is skipped, which is what every caller had before LEDGER L123.
|
||||
PleRun ple;
|
||||
};
|
||||
|
||||
/// Bytes for a whole session at `max_cells` of context. Every layer's state is sized at once, because P2.T10
|
||||
/// requires ZERO token-path allocations - a `cudaMalloc` that happened on the first token of a longer sequence
|
||||
/// would satisfy every test here and fail that one.
|
||||
///
|
||||
/// [layer_lo, layer_hi) carves only that range's per-layer state (a split stage runs a slice of the model);
|
||||
/// the default full range is byte-identical to the old whole-model carve. Pure arithmetic - safe to call for
|
||||
/// a candidate range before anything is allocated, which is how the layer-split search prices a placement.
|
||||
uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo = 0,
|
||||
int64_t layer_hi = -1);
|
||||
/// Carves `base` (DEVICE memory) into `s`. Returns the bytes used. Same range convention as `session_bytes`.
|
||||
uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s,
|
||||
int64_t layer_lo = 0, int64_t layer_hi = -1);
|
||||
/// Before the memory `session_init` carved is freed: forgets what points into it from outside the session (the
|
||||
/// rope kernels' registered angle table, #280), so a later session never rotates by freed memory.
|
||||
void session_release(SessionState& s);
|
||||
/// Zeroes every layer's state - the residual to `R_init`, everything else to zero, so a fresh sequence starts
|
||||
/// from the reference's own `zeros()`.
|
||||
void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream);
|
||||
|
||||
/// One token: layers 0..47 in order, each a `block_layer`, and the residual is updated in place.
|
||||
///
|
||||
/// `parts` is (k, n_embd) DEVICE memory, filled by the caller - by the CPU expert pool and the VRAM-resident
|
||||
/// experts. In this phase `moe_layer` consumes it directly; the doorbell protocol's job is to let it be
|
||||
/// produced DURING the layer rather than before it, which is a change to *when* the host runs, not to what this
|
||||
/// function computes.
|
||||
///
|
||||
/// `sync_every_layer` inserts a device synchronisation and an error check after EVERY layer. That is the
|
||||
/// `--sync-every-layer` debug mode, and it is deliberately a parameter rather than a compile-time choice: the
|
||||
/// errors it catches (a kernel reading a buffer that a later layer writes) are invisible otherwise, and the
|
||||
/// synchronisation it costs is exactly what P2.X3 forbids in the fast path.
|
||||
bool session_token(const WeightTable& tables, const ModelGeometry& g, int64_t pos, int32_t pos_base,
|
||||
SessionState& s, const float* parts, void* stream, bool sync_every_layer,
|
||||
std::string& err);
|
||||
|
||||
// ================================ the captured form ================================
|
||||
|
||||
/// ONE GRAPH PER LAYER, because a graph bakes in its POINTERS and every layer has different weights AND
|
||||
/// different state. That is not a limitation to work around - it is what makes the per-layer graph the right
|
||||
/// unit: the host decides when each layer runs, which is what lets the CPU expert pool start while the GPU is
|
||||
/// still working on the next one.
|
||||
///
|
||||
/// WHY THIS IS WORTH DOING, MEASURED: **the engine is launch-bound, not bandwidth-bound.** Every kernel in
|
||||
/// `gdn_layer` measured ~0.028 ms - including `gdn_gate`, which processes FORTY-EIGHT elements, and a kernel
|
||||
/// cannot execute for 28 us. That is what a null-stream launch costs on this driver, and `gdn_layer` makes ~19
|
||||
/// of them while a block makes ~45. Replaying the 43-node block graph measured **1.585 ms against 2.393 ms**
|
||||
/// for the same work as direct launches - a 1.51x that is pure launch overhead.
|
||||
struct SessionGraphs {
|
||||
cudaGraphExec_t* execs = nullptr; ///< one per layer, in layer order
|
||||
int64_t n = 0;
|
||||
/// **THE SECOND GRAPH PER LAYER: `moe_finish` + `gr_write`, launched AFTER the host has run the pool.**
|
||||
///
|
||||
/// Without it the loop has to hand layer `l`'s expert vectors to layer `l+1`, which multiplies them by
|
||||
/// layer `l+1`'s router weights - see `layer.hpp`'s note on `moe_route`. With it, `post[l]` is launched
|
||||
/// after the pool returns, so layer `l`'s experts are combined with layer `l`'s weights.
|
||||
///
|
||||
/// The cost is the overlap, and it is worth stating: the window is now whatever GPU work follows the ring
|
||||
/// inside `pre[l]` - the shared expert, and nothing else, because everything after the combine depends on
|
||||
/// `parts`. **A per-layer CPU pool cannot be hidden behind a strictly serial residual chain**, which is
|
||||
/// why the CPU term is answered by Phase 3's VRAM cache and not by this pipeline.
|
||||
cudaGraphExec_t* posts = nullptr;
|
||||
bool captured = false;
|
||||
/// THE DEVICE ADDRESS THE GRAPHS WERE CAPTURED WITH. The host loop copies each layer's expert outputs
|
||||
/// here before launching the next layer, and a graph bakes the POINTER, so it has to be this one.
|
||||
float* parts_dev = nullptr;
|
||||
|
||||
/// **DIAGNOSTIC, AND IT IS THE ONE THAT SAYS WHETHER THE DOORBELL IS DECORATIVE.**
|
||||
///
|
||||
/// Counts the layers where the ring was observed while the graph was STILL RUNNING - i.e. the layers where
|
||||
/// the pool actually had a window to work in. A nonzero `h_seq` read at the same moment
|
||||
/// `cudaEventQuery` returns `cudaSuccess` means the layer was already over, and the pool then runs with the
|
||||
/// GPU IDLE, which makes the whole pipeline equivalent to a serialised one.
|
||||
///
|
||||
/// That distinction is invisible in the loop's RETURN VALUE - both paths produce a correct token - and it
|
||||
/// is invisible in a per-layer timing, because the layer still takes the same time either way. It shows up
|
||||
/// only as "the overlap hides nothing", which is why it is counted here.
|
||||
int64_t rings_mid_graph = 0;
|
||||
|
||||
/// **THE WINDOW, MEASURED RATHER THAN ASSUMED.** Milliseconds from `cudaGraphLaunch` to the moment the
|
||||
/// ring was observed, summed over the loop. The pool's window is `layer period - this`, and that is the
|
||||
/// entire budget the overlap has: if the CPU's per-layer work exceeds it, the GPU goes idle for the
|
||||
/// difference on every layer and a "pipelined" loop measures the same as a serialised one.
|
||||
///
|
||||
/// It is NOT the same as the doorbell's position inside the graph. It includes the launch itself, the
|
||||
/// driver's submission, and however long the host took to notice - all of which are real and none of which
|
||||
/// the pool gets to use.
|
||||
double ms_to_ring = 0;
|
||||
|
||||
// ================================ R0.9: THE LAYER AS THREE GRAPHS ================================
|
||||
//
|
||||
// **THE CAPTURED PER-STAGE TABLE THE PROTOCOL HAS DEMANDED SINCE R0 AND NOBODY HAS HAD.** Round 309's
|
||||
// came from `--no-capture`, and round 312 showed its `moe_finish` figure was a host-gap artefact four
|
||||
// times the captured cost of the same work - so the plan has been choosing between R3.3, R3.4 and R3.5
|
||||
// without knowing what any of them is worth.
|
||||
//
|
||||
// An event recorded BETWEEN two `cudaGraphLaunch` calls is not inside a capture and is therefore valid,
|
||||
// so the layer is captured at its own documented seam (`block_layer_pre`'s `half`) and timed from outside.
|
||||
/// **R0.11: FIVE PREFIX GRAPHS, ADDED BESIDE `preA`/`preB` RATHER THAN REPLACING THEM.**
|
||||
/// `preP[k]` (k = 1..5) runs stages `0..k-1`. Consecutive differences are the per-stage times, which is
|
||||
/// what prices the two `gr_read`s and the `gr_write` (R3.3) against GDN's interior (R3.4). A prefix and not
|
||||
/// a range, because the stages are a chain: stage 1 reads what stage 0 wrote and stage 2 mutates the
|
||||
/// residual in place.
|
||||
///
|
||||
/// **THE FIFTH PREFIX USED TO BE `execs[l]`, AND THAT WAS THE BUG ROUND 324 COULD NOT FIND.** Prefix 5
|
||||
/// has ~7 more nodes than prefix 4, so the two differ in launch setup as well as in execution - and the
|
||||
/// difference attributed ALL of it to stage 4, the router. Capturing prefix 5 the same way as the others
|
||||
/// makes the two comparable and the difference purely stage 4's.
|
||||
cudaGraphExec_t* preP[5] = {nullptr, nullptr, nullptr, nullptr, nullptr};
|
||||
cudaGraphExec_t* preA = nullptr; ///< `half == 1`: gr_read -> attention -> gr_write (the MIXER)
|
||||
cudaGraphExec_t* preB = nullptr; ///< `half == 2`: gr_read -> moe_route (FFN front + ROUTER)
|
||||
bool split_captured = false;
|
||||
|
||||
/// How many times `session_loop` has run. `rings_mid_graph` and `ms_to_ring` are CUMULATIVE and the loop
|
||||
/// is called once per token, so anything reporting a ratio needs this - and prefill runs the loop too, so
|
||||
/// "per generated token" is the wrong denominator.
|
||||
int64_t calls_total = 0;
|
||||
|
||||
/// **WHERE THE PER-LAYER ROUND TRIP GOES, AND `ms_to_ring` ALONE CANNOT SAY.**
|
||||
///
|
||||
/// `--no-pool` measures **38.73 ms/token against a 26.32 ms pure-GPU floor**, so ~12.4 ms/token - a quarter
|
||||
/// of the token - is spent in the loop with no expert work at all: 0.258 ms per layer. `ms_to_ring` covers
|
||||
/// only the first half of that; it stops when the ring is seen, and everything the host then does before
|
||||
/// the next `pre` is launched is invisible to it.
|
||||
///
|
||||
/// So the round trip is split at the ring, and **`ms_to_ring` above IS the first half** - do not add a
|
||||
/// second counter for it:
|
||||
///
|
||||
/// * `ms_to_ring` - launch -> ring observed. The GPU is working (or already finished) here.
|
||||
/// * `ms_host` - ring observed -> `pre[l+1]` launched. **The GPU has nothing queued and is IDLE for
|
||||
/// all of this unless `pre[l]`'s tail still covers it.** This is
|
||||
/// `cudaMemcpyAsync(parts)` + `cudaGraphLaunch(post[l])` + `cudaGraphLaunch(pre[l+1])` +
|
||||
/// `cudaEventRecord`, and if it is the large half then the fix is fewer driver calls
|
||||
/// (R2.4), not a faster kernel.
|
||||
///
|
||||
/// Cumulative, like `ms_to_ring`; divide by `calls_total * n_layers`.
|
||||
double ms_host = 0;
|
||||
};
|
||||
|
||||
/// Captures all 48 layer graphs. Idempotent: a second call is a no-op.
|
||||
///
|
||||
/// `pos`/`pos_base` are baked in ONLY through the fixed-address pinned staging in each `QsaState`, which the
|
||||
/// replay re-reads every token - so the position is data, not an argument. That is the whole reason rounds
|
||||
/// 211-214 moved the per-token counts into device buffers.
|
||||
bool session_capture(const WeightTable& tables, const ModelGeometry& g, SessionState& s, const float* parts,
|
||||
SessionGraphs& gr, std::string& err, bool split = false, int64_t layer_lo = 0,
|
||||
int64_t layer_hi = -1);
|
||||
|
||||
/// One token by REPLAYING the captured graphs. Identical arithmetic to `session_token`; the only difference is
|
||||
/// that ~2,000 kernel launches become 48 graph launches.
|
||||
bool session_replay(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr,
|
||||
void* stream, std::string& err);
|
||||
|
||||
/// One token by replaying BOTH halves of every layer - `pre[l]` and `post[l]` - with no pool running.
|
||||
///
|
||||
/// **THIS IS THE TRUE PER-TOKEN GPU FLOOR, AND `session_replay` IS NOT.** `session_replay` launches only
|
||||
/// `gr.execs[l]`, the `pre` graphs, so it omits the 48 `post` graphs (shared expert, combine, second `gr_write`)
|
||||
/// entirely - and everything published as "39.8 ms pure GPU" came from it while being described as the whole
|
||||
/// GPU. See `Memory/ERRORS.md` A4.
|
||||
///
|
||||
/// `parts` is left at whatever the buffer holds, because no pool writes it; that is deliberate and makes the
|
||||
/// measurement pure GPU work. The LM head is NOT included here - the caller times it separately, since it runs
|
||||
/// on the host-side path rather than inside a captured graph.
|
||||
bool session_replay_full(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
|
||||
SessionGraphs& gr, void* stream, std::string& err);
|
||||
|
||||
/// **ONE TOKEN THROUGH THE SPLIT GRAPHS, WITH EVERY STAGE TIMED FROM OUTSIDE THE CAPTURE.** Requires
|
||||
/// `session_capture(..., split = true)`. Replays `preA[l]`, `preB[l]`, `post[l]` in order on one stream -
|
||||
/// the same order `session_loop` uses - and reports the three totals in milliseconds for the whole token.
|
||||
///
|
||||
/// The stages are ordered by the stream, so an event pair around each launch measures that launch's GPU work
|
||||
/// plus the gap the driver left before it. That gap is real and is why the three totals sum slightly above
|
||||
/// `session_replay_full`; the comparison is printed by the caller rather than hidden here.
|
||||
/// **R0.11: THE FIVE STAGES SEPARATELY, BY DIFFERENCING PREFIXES.** `stage_ms` is resized to 5 and holds
|
||||
/// stages 0..4 in milliseconds for a whole token; `mixer_per_layer` holds prefix 3's time for each layer, which
|
||||
/// is what R0.10's GDN-versus-QSA split needs. Requires `session_capture(..., split = true)`.
|
||||
///
|
||||
/// **THE RESIDUAL IS SAVED AND RESTORED BETWEEN PREFIXES.** Stage 2 is `gr_write`, which mutates `R` in
|
||||
/// place, so without the restore every prefix after the first reads a residual the earlier ones already
|
||||
/// advanced - and every number after the first would be measuring a different tensor while looking correct.
|
||||
bool session_replay_stage_prefixes(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
|
||||
SessionGraphs& gr, void* stream, std::vector<double>& stage_ms,
|
||||
std::vector<double>& mixer_per_layer, std::string& err);
|
||||
|
||||
/// **R3.5c: ONE PREFIX, ALL 48 LAYERS, BACK TO BACK.** `k` in 1..5 replays `preP[k-1][l]` (or `execs[l]` for
|
||||
/// k = 5) for every layer with no other graph in between, and reports the whole sweep in milliseconds.
|
||||
///
|
||||
/// **WHY THIS EXISTS: TO RULE OUT THE PREFIX TABLE'S OWN BIAS.** The five-stage table differences prefix
|
||||
/// times measured with FIVE DIFFERENT GRAPHS LAUNCHED PER LAYER. Stage 4's interval therefore contains the
|
||||
/// launch of `execs[l]` - the full five-stage graph - while stage 3's contains `preP[3][l]`, a four-stage one.
|
||||
/// A launch cost that scales with graph size would inflate stage 4 specifically, and stage 4 is the router,
|
||||
/// which is the thing under investigation. This sweep launches ONE graph type per layer, so there is nothing
|
||||
/// to switch between and nothing to attribute wrongly.
|
||||
///
|
||||
/// Five separate sweeps give five totals; their consecutive differences are the stage times on the same
|
||||
/// arithmetic as before, and **if the two methods disagree the difference is the bias and the sweep is right.**
|
||||
bool session_replay_stage_sweep(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
|
||||
SessionGraphs& gr, void* stream, int k, double& ms, std::string& err);
|
||||
|
||||
bool session_replay_stages(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
|
||||
SessionGraphs& gr, void* stream, double& ms_mixer, double& ms_ffn, double& ms_post,
|
||||
std::string& err);
|
||||
|
||||
/// **THE SAME REPLAY, KEEPING EVERY LAYER INSTEAD OF SUMMING THEM.**
|
||||
///
|
||||
/// The 48 layers are not 48 of the same thing: 36 are GDN and 12 are QSA, and the mixer - 55.8% of the GPU
|
||||
/// floor - contains both. A total cannot separate them; a per-layer vector can, and it is already being
|
||||
/// measured. `out` is resized to `n_layers` and holds each layer's mixer time in milliseconds.
|
||||
///
|
||||
/// **THIS IS THE CHEAPEST HALF OF R0.10 AND IT NEEDS NO NEW SPLIT.** Round 309's uncaptured table put GDN at
|
||||
/// 10.88 ms for 36 layers and QSA at 4.56 for 12, which would make the recurrence the largest single R3
|
||||
/// target; that table also had `moe_finish` wrong by 4x, so the ratio is worth re-deriving from the captured
|
||||
/// graph rather than inherited.
|
||||
bool session_replay_stages_per_layer(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
|
||||
SessionGraphs& gr, void* stream, std::vector<double>& mixer_per_layer,
|
||||
double& ms_ffn, double& ms_post, std::string& err);
|
||||
|
||||
/// Releases the graph execs. The `SessionGraphs` struct holds no device memory of its own.
|
||||
void session_graphs_free(SessionGraphs& gr);
|
||||
|
||||
// ================================ THE HOST LOOP ================================
|
||||
|
||||
/// WHAT THE POOL HAS TO DO, as the loop sees it: given the `x_f` a layer published and the miss list it
|
||||
/// selected, produce the `k` expert outputs into `out` (k x n_embd, HOST memory). A function pointer rather
|
||||
/// than a virtual class because the loop is the thing under test and the pool is the thing being faked.
|
||||
using PoolFn = void (*)(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd,
|
||||
int64_t k, float* out);
|
||||
|
||||
/// **R4.2c: THE VRAM-RESIDENT HALF OF THE LAYER'S EXPERTS.** Called by the loop after the misses have been
|
||||
/// staged into `parts` and before `post[l]` is launched, so its kernels are stream-ordered between them: the
|
||||
/// misses are already in `parts`, the hits overwrite the rows the CPU zeroed, and `post[l]`'s `moe_combine`
|
||||
/// reads the sum and cannot tell which engine produced which row.
|
||||
///
|
||||
/// **WHY IT IS A CALLBACK RATHER THAN MORE PARAMETERS.** `session_loop` owns the ORDER across layers and has
|
||||
/// no business knowing what an expert cache is. Everything the hit path needs lives on the caller's `user`,
|
||||
/// and this has the same shape as `PoolFn` for the same reason.
|
||||
///
|
||||
/// A null pointer means "no VRAM tier" - the default, and what every caller had before R4.
|
||||
// The hit hook's type lives in its own header - see `hit_hook.hpp` for why and for the ordering it wants.
|
||||
|
||||
/// `phases/phase-2-correct-engine.md` P2.S5's host loop, which is the point of everything above it:
|
||||
///
|
||||
/// launch G[l] -> poll the doorbell -> read the miss list -> dispatch the pool -> wait for it ->
|
||||
/// write y_miss -> launch G[l+1]
|
||||
///
|
||||
/// **NO `cudaStreamSynchronize` IN THE LOOP**, which is P2.X3. Waiting is `cudaEventQuery` on an event recorded
|
||||
/// right after the launch - a QUERY, and it is not optional: round 195 measured a host spin that only read
|
||||
/// memory never running the kernel at all, 5,907,703 spins over 500 ms with the datum flipping only when
|
||||
/// `cudaStreamSynchronize` was called.
|
||||
///
|
||||
/// **THE OVERLAP IS THE ONE-LAYER DELAY.** A layer publishes `x_f` at ~71% of its own duration, so the pool has
|
||||
/// the remaining 29% of that layer to work in; its result is consumed by the NEXT layer, which is why the
|
||||
/// combine is not waiting on it. `overlap = false` runs the same sequence with a synchronisation after every
|
||||
/// layer, which is the comparison that says whether the pipeline is worth its complexity - and it is a
|
||||
/// parameter rather than a second function so that the two cannot drift.
|
||||
///
|
||||
/// **`dump_layers`, WHEN NOT NULL, IS THE C1 ORACLE AND IT IS A HOST BUFFER OF `(n_layers + 1) * hc * n_embd`
|
||||
/// FLOATS.** Slot 0 is the residual the function was ENTERED with - the token's embedding broadcast to every
|
||||
/// stream, which is the reference's `hc_init` node - and slot `l + 1` is `s.R` after layer `l`, which is the
|
||||
/// reference's `l_last-<l>`. Each is enqueued as a device-to-host copy, and the final `cudaStreamSynchronize`
|
||||
/// at the end of the loop is what makes every one of them complete. **NO EXTRA SYNCHRONISATION IS INSERTED**,
|
||||
/// which is the whole reason this is written as an enqueue rather than a read: `pre[l+1]` does not write `R` and
|
||||
/// `post[l+1]` is launched after the copy on the same stream, so FIFO order alone makes slot `l + 1` a true
|
||||
/// snapshot. It costs 40 KB per layer per token, and it is the only way to bisect the engine against the
|
||||
/// reference layer by layer instead of against one end-to-end perplexity.
|
||||
/// Per-token scratch that MUST NOT be reallocated per token (P2.T10, review finding H3).
|
||||
///
|
||||
/// **`session_loop` IS CALLED ONCE PER TOKEN, SO ANYTHING IT ALLOCATES IS A PER-TOKEN ALLOCATION.** It used to
|
||||
/// allocate three things on every token of every run:
|
||||
///
|
||||
/// * `cudaHostAlloc` for the pool's pinned staging, freed by an RAII destructor at the end of the call - and
|
||||
/// `cudaFreeHost` IMPLICITLY SYNCHRONISES THE DEVICE, so every token ended with a device sync;
|
||||
/// * `cudaEventCreate` / `cudaEventDestroy` for the doorbell probe;
|
||||
/// * a host-affinity change (`physical_cores` + pin + restore).
|
||||
///
|
||||
/// A comment in the old code said "allocated once", but once per token is not once.
|
||||
///
|
||||
/// Own one of these at session setup and pass it in. **Passing `nullptr` keeps the old behaviour** - the loop
|
||||
/// allocates and frees locally - so every existing caller and test is unaffected, but the allocation is then
|
||||
/// visible at the call site instead of hidden inside a hot function.
|
||||
struct SessionLoopScratch {
|
||||
float* y_miss = nullptr; ///< pinned host staging for the pool's answer, `parts_bytes` long
|
||||
size_t parts_bytes = 0;
|
||||
cudaEvent_t probe = nullptr;
|
||||
strata::kernels::cpu::ThreadAffinity pinned_core{}; ///< affinity to restore, or invalid if the host was not pinned
|
||||
bool pinned = false;
|
||||
|
||||
/// Allocates the buffers and pins the host thread. Call ONCE, at session setup.
|
||||
bool init(size_t parts_bytes_in, std::string& err);
|
||||
/// Frees everything and restores the affinity. Safe to call twice, or on a default-constructed object.
|
||||
void free();
|
||||
};
|
||||
|
||||
bool session_loop(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr,
|
||||
PoolFn pool, HitFn hits, void* user, bool overlap, void* stream, std::string& err,
|
||||
float* dump_layers = nullptr, SessionLoopScratch* scratch = nullptr);
|
||||
|
||||
// ================================ plan v0.3 P3: THE WHOLE TOKEN AS ONE GRAPH ================================
|
||||
//
|
||||
// Under WDDM every graph launch costs ~0.3-0.4 ms of submission latency, and the per-layer loop above makes 96
|
||||
// of them per token: measured 48.6 ms/token for 12 ms of GPU kernels and 27 ms of pool. The token graph holds
|
||||
// all 48 layers. Between `pre[l]` (which rings the doorbell) and the parts copy, a one-thread kernel waits ON
|
||||
// THE DEVICE until the host writes the ring value into `db.h_flag`; the host only polls rings, runs the pool
|
||||
// and writes flags, with no driver call in the loop (bench/micro/device_wait.cu: 5.2 us per handoff).
|
||||
//
|
||||
// for l: pre[l] (.. router, doorbell ring, shared expert) -> doorbell_wait -> parts <- y_miss (H2D)
|
||||
// -> post[l] (combine, gr_write)
|
||||
//
|
||||
// Same kernels, same order per layer as `session_loop`, so the token is bitwise the same. No VRAM expert tier
|
||||
// yet (the hit decision is a host step between ring and post); the caller falls back to `session_loop` then.
|
||||
struct TokenGraph {
|
||||
cudaGraphExec_t exec = nullptr;
|
||||
bool captured = false;
|
||||
int64_t n_layers = 0;
|
||||
const float* y_src = nullptr; ///< the pinned host staging the graph's H2D copies read (baked in)
|
||||
size_t parts_bytes = 0;
|
||||
int64_t calls = 0;
|
||||
double ms_wait = 0; ///< host waiting for rings (the GPU is running)
|
||||
double ms_pool = 0; ///< host inside the pool
|
||||
int64_t flushes = 0; ///< cudaStreamQuery calls made because a ring was slow to appear
|
||||
};
|
||||
|
||||
/// Plan v0.3 P4: the VRAM expert tier inside the token graph. Residency is STATIC during a token (a
|
||||
/// `n_layers x n_expert` table, slot or -1, on the device; the host pool reads its own copy), so the hit list
|
||||
/// is built on the device right after the ring and the hits run while the CPU computes the misses.
|
||||
struct TokenHits {
|
||||
const int32_t* d_res = nullptr; ///< device [n_layers * n_expert]
|
||||
int64_t n_expert = 0;
|
||||
const uint8_t* cache_base = nullptr; ///< slot 0 of the VRAM expert arena
|
||||
int64_t blob = 0; ///< bytes per slot
|
||||
int32_t* d_slot = nullptr; ///< device, k entries
|
||||
int32_t* d_dst = nullptr; ///< device, k entries
|
||||
int32_t* d_count = nullptr; ///< device, 1
|
||||
uint8_t* x_q8 = nullptr; ///< the activation's q8_0 blocks, (n_embd/32)*34 B
|
||||
float* x_scale = nullptr; ///< and its fp32 scales (the CPU pool's contract)
|
||||
void* scratch = nullptr; ///< moe_hit_grouped_scratch_bytes(k, ...)
|
||||
float* hit_out = nullptr; ///< device, k * n_embd
|
||||
bool on() const { return d_res && cache_base && d_slot && d_dst && d_count && x_q8 && x_scale && scratch && hit_out; }
|
||||
};
|
||||
|
||||
bool session_capture_token(const WeightTable& tables, const ModelGeometry& g, SessionState& s, float* parts_dev,
|
||||
const float* y_miss_host, size_t parts_bytes, TokenGraph& tg, std::string& err,
|
||||
const TokenHits* hits = nullptr);
|
||||
bool session_run_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, TokenGraph& tg,
|
||||
PoolFn pool, void* user, float* y_miss_host, void* stream, std::string& err);
|
||||
void token_graph_free(TokenGraph& tg);
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,371 +0,0 @@
|
||||
// include/strata/core/verify.hpp - plan v0.3 P6: the speculative VERIFY window.
|
||||
//
|
||||
// T tokens at consecutive positions p0 .. p0+T-1 - the last accepted token and T-1 drafts - go through all 48
|
||||
// layers in ONE captured graph, and the head's argmax is produced for every one of them. Token t's argmax is
|
||||
// what plain greedy decode would produce after token t, BIT FOR BIT: every kernel here is either the single-token
|
||||
// kernel applied per token, or a multi-token kernel whose per-token arithmetic is the single-token kernel's
|
||||
// (multi-column MMVQ in exact mode, the T-token GDN kernels, the per-token hit activation, the multi-token CPU
|
||||
// expert rows). So a draft is accepted exactly when greedy decode would have produced it.
|
||||
//
|
||||
// What the window costs is the dense weights read ONCE for T tokens and the union of the T tokens' missed
|
||||
// experts on the CPU (measured on decode traces: 1.75x one token's misses for T=2, 2.4x for 3, 3.05x for 4).
|
||||
//
|
||||
// STATE. The window appends K/V and indexer keys for all T positions and leaves the GDN state untouched.
|
||||
// `commit(n_keep)` then makes the first `n_keep` tokens permanent: the GDN conv history and recurrent state are
|
||||
// advanced by replaying those tokens from inputs the window stored, the indexer's key tail is restored from a
|
||||
// snapshot and the accepted keys re-appended (a rejected key can land in a slot the current block still needs),
|
||||
// and the PLE history is set to its snapshot after token n_keep-1. K/V cells past the accepted prefix are simply
|
||||
// overwritten when those positions are processed again, before any query can read them.
|
||||
//
|
||||
// Requires the default native decode configuration (native projections, fused GR, fused GDN, fast attention and
|
||||
// selection, native indexer) and a profile-filled VRAM expert tier with its residency table on the device.
|
||||
#pragma once
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#include "strata/core/expert_source.hpp"
|
||||
#include "strata/core/layer.hpp"
|
||||
#include "strata/core/session.hpp"
|
||||
#include "strata/kernels/sampler.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
class NativeHead;
|
||||
class RemoteExpertOpt;
|
||||
|
||||
/// The geometry a verify window reproduces: at hc > 1 the fused hyper-connection read's shape (Flash-Next's
|
||||
/// 2560 / 4 / 320), at hc = 1 the plain block (any width: layer.hpp, "the plain block"); `k` equal to the file's
|
||||
/// `expert_used_count` (the window routes and combines with the session's k, and top-10 on a file that routes
|
||||
/// top-8 is a different model, finite and fluent); GDN state 128 and conv 4 (the T-token GDN kernels' shapes).
|
||||
/// False with `why` naming the number that differs. `Verifier::init` refuses on it; tests call it directly.
|
||||
bool verify_geometry_supported(const ModelGeometry& g, int64_t k, std::string& why);
|
||||
|
||||
/// The CPU pool for a window: x_f (n_tok, n_embd), ids (n_tok, k) -> out (n_tok * k, n_embd), hit rows zeroed.
|
||||
using PoolMultiFn = void (*)(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out,
|
||||
int64_t layer);
|
||||
|
||||
struct VerifyHits {
|
||||
const int32_t* d_res = nullptr; ///< device [n_layers * n_expert] slot or -1
|
||||
const int32_t* h_res = nullptr; ///< host [n_layers * n_expert] slot or -1 (when all >= 0 in stage: zero-doorbell)
|
||||
const uint8_t* cache_base = nullptr; ///< slot 0 of the VRAM expert arena
|
||||
const uint64_t* slot_off = nullptr; ///< E-6: host per-slot offsets when slots differ in size (null: slot * blob)
|
||||
int64_t n_slots = 0; ///< E-6: how many (for the device copy)
|
||||
int64_t blob = 0;
|
||||
};
|
||||
|
||||
class Verifier {
|
||||
public:
|
||||
Verifier() = default;
|
||||
~Verifier();
|
||||
Verifier(const Verifier&) = delete;
|
||||
Verifier& operator=(const Verifier&) = delete;
|
||||
void set_remote_expert_opt(RemoteExpertOpt* opt) { remote_opt_ = opt; } // before init/capture
|
||||
|
||||
/// The watchdog's view of the window in flight (issue #31): the layer, the GPU's sequence, the flags.
|
||||
void diag(std::FILE* f) const;
|
||||
/// #649 (STRATA_VERIFY_TRACE=1, opt-in): the last windows' host-side handshake events and the GPU's breadcrumbs
|
||||
/// (in mapped memory, so they read while the GPU hangs). Nothing when the trace is off.
|
||||
void trace_dump(std::FILE* f) const;
|
||||
|
||||
/// #267: raise every flag the window's spin kernels wait on past any ring (UINT32_MAX), so a window the GPU
|
||||
/// cannot finish drains instead of staying resident, then wait up to `timeout_ms` for its streams. For the
|
||||
/// paths that give up on the engine (a timed-out window, the serve watchdog): the window then ran on whatever
|
||||
/// the flags guarded, so this verifier refuses every later window. True when the streams finished.
|
||||
bool release_gpu_waits(int timeout_ms);
|
||||
|
||||
/// `max_t` <= kVerifyMaxT. `head` may be null (the canonical head is then run per token).
|
||||
bool init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits,
|
||||
const NativeHead* head, int max_t, std::string& err);
|
||||
|
||||
/// One window: `tokens[0..T)` at positions pos0.., the pool served per layer; `out[t]` = argmax after token t.
|
||||
/// The PLE rows are gathered here from `ss.ple_prev` and the tokens. Captures the T-token graph on first use.
|
||||
bool run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err);
|
||||
/// Diagnostics: row `t` of the last window's head logits (n_vocab floats) to the host. Valid after run().
|
||||
bool copy_logits(int t, float* host) const;
|
||||
int64_t vocab() const { return next_ ? next_->vocab() : n_vocab_; }
|
||||
/// The sampling the verify window's head applies (temperature / top_p / top_k / seed). Set per
|
||||
/// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its
|
||||
/// parameters would otherwise be baked forever - so this can change between requests freely.
|
||||
void set_sampling(const strata::kernels::SamplerParams& sp) {
|
||||
sampling_ = sp; // row t of a window at pos0 draws Philox(seed, pos0 + t): see run()
|
||||
if (next_) next_->set_sampling(sp);
|
||||
}
|
||||
|
||||
/// The penalty histories for `sampling_.penalty_last_n`: ONE ROW PER WINDOW ROW, T rows of `history_len`
|
||||
/// int32 slots at that stride (`strata::kernels::penalty_rows` builds them), most recent token LAST, unused
|
||||
/// front slots -1 (the kernel reads only the tail window). Row t follows the window's drafts 1..t - staging
|
||||
/// row 0 alone (before 0.1.19) left the drafted rows with unwritten histories. Null disables the penalties
|
||||
/// entirely - the neutral run's sampling call is byte-for-byte what it was. The engine re-uploads the rows
|
||||
/// before every window; the buffer must hold kVerifyMaxT rows and stay alive across the request.
|
||||
void set_history(const int32_t* history, int history_len) {
|
||||
hist_d_ = history;
|
||||
hist_len_ = history_len;
|
||||
if (next_) next_->set_history(history, history_len);
|
||||
}
|
||||
/// Off: `run` skips the request's head sampling and `out` is the recorded greedy pick. For windows whose
|
||||
/// picks are discarded - a prompt read through windows commits every token - so they cost no sampler launch
|
||||
/// or sync and never read a history staged for another position.
|
||||
void set_head_sampling(bool on) { head_sampling_ = on; if (next_) next_->set_head_sampling(on); }
|
||||
|
||||
/// LAYER SPLIT (multi-GPU): this verifier runs layers [layer_begin, layer_end) of every window. A stage that
|
||||
/// does not start at layer 0 takes its residual from `handoff_in` instead of embedding the tokens; a stage that
|
||||
/// does not end at the last layer writes its residual to `handoff_out` and has no head. The hand-off holds,
|
||||
/// per token, the residual R (hc x n_embd), the last layer's pending write bo (n_embd) and inject (hc): the next
|
||||
/// stage folds that write into its first read exactly as the unsplit window does, so the split is bit-exact.
|
||||
/// Both pointers must be device-visible (mapped pinned memory, portable when the stages are on two devices).
|
||||
/// Set before `init`. Default: the whole model, no hand-off.
|
||||
void set_stage(int64_t layer_begin, int64_t layer_end, const float* handoff_in, float* handoff_out) {
|
||||
lb_ = layer_begin; le_ = layer_end; hand_in_ = handoff_in; hand_out_ = handoff_out;
|
||||
}
|
||||
/// The next stage: `run` and `commit` continue into it (its pool calls get `next_user`); sampling settings
|
||||
/// and `final_R` are the last stage's.
|
||||
void set_next(Verifier* next, void* next_user) { next_ = next; next_user_ = next_user; }
|
||||
/// floats per token in a hand-off buffer
|
||||
static int64_t handoff_floats(const ModelGeometry& g) { return (int64_t) g.hc * g.n_embd + g.n_embd + g.hc; }
|
||||
|
||||
/// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them.
|
||||
bool commit(int n_keep, std::string& err);
|
||||
|
||||
// ================================ SEVERAL SEQUENCES IN ONE WINDOW ================================
|
||||
//
|
||||
// A batch window holds S INDEPENDENT sequences, one token each: row s is slot s, at slot s's own position,
|
||||
// reading and writing slot s's own state (GDN recurrence and conv history, QSA K/V and indexer, PLE history),
|
||||
// which lives in `slots[s]` - a session carved like this verifier's own (same layer range, same max_cells).
|
||||
// Everything that is per row already (hyper-connections, dense projections, router, shared expert, the
|
||||
// routed experts on the GPU and the CPU, the head) runs once over the S rows, so the weights are read once
|
||||
// per window for all the sequences. Row s's arithmetic is the single-token window's, so a slot's greedy
|
||||
// tokens are its solo greedy tokens (modulo the multi-token CPU kernel choice: STRATA_IQ_MT_MIN=1).
|
||||
//
|
||||
// Greedy only, no drafts (MTP) in a batch window. `init_slots` once after `init` (S <= max_t); a layer
|
||||
// split's stages each get their own sessions, and run_slots/commit_slots continue into the next stage.
|
||||
bool init_slots(const std::vector<SessionState*>& slots, std::string& err);
|
||||
int n_slots() const { return (int) slots_.size(); }
|
||||
/// One batch window over slots [0, S): tokens[s] at positions pos[s]; out[s] = the greedy pick after it.
|
||||
bool run_slots(int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user, int32_t* out,
|
||||
std::string& err);
|
||||
/// The same over the S slots `rows` (row t is slot rows[t], any distinct slots in any order): the slots not
|
||||
/// listed are not touched, so an idle slot keeps its state (a finished conversation it may continue later).
|
||||
bool run_slot_rows(const int* rows, int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user,
|
||||
int32_t* out, std::string& err);
|
||||
/// Keep every row of the last batch window: each slot's state advances by its one token.
|
||||
bool commit_slots(std::string& err);
|
||||
|
||||
// ---- The stages of a layer split as a PIPELINE. A batch window over the slot GROUP
|
||||
// [base, base + S) is launched on ONE stage with its commit right behind it on the stage's stream (a batch window
|
||||
// keeps every row, so the commit needs no host decision), and the host serves the rings of every stage that has
|
||||
// a window in flight from one thread (batch_poll does not block). Stage k can then run group g while stage k+1
|
||||
// runs group g-1. Rows of group `base` use hand-off rows [base, base + S), so groups never share a hand-off row.
|
||||
bool batch_launch(int base, int S, const int32_t* tokens, const int64_t* pos, std::string& err);
|
||||
/// 1 = this stage's window and commit are done (the last stage's picks are in batch_out), 0 = still running,
|
||||
/// -1 = an error (err). Serves every layer that has rung so far.
|
||||
int batch_poll(PoolMultiFn pool, void* user, std::string& err);
|
||||
bool batch_busy() const { return b_running_; }
|
||||
/// A slot's sampling (temperature / top_p / top_k / min_p / seed; penalties are not applied in batch windows):
|
||||
/// its row is drawn again on the last stage with Philox(seed, position), as a solo window draws it. Greedy by
|
||||
/// default. Set on the first stage, it reaches the last.
|
||||
void set_slot_sampling(int slot, const strata::kernels::SamplerParams& sp) {
|
||||
if (slot >= 0 && slot < (int) slot_sp_.size()) slot_sp_[(size_t) slot] = sp;
|
||||
if (next_) next_->set_slot_sampling(slot, sp);
|
||||
}
|
||||
const int32_t* batch_out() const { return b_out_; }
|
||||
bool last_stage() const { return g_ != nullptr && le_ == g_->n_layers; }
|
||||
/// commit() returns without waiting for its graph (a single-GPU session sets it): the next window follows it on
|
||||
/// the same stream and the drafter reads nothing it writes, so it overlaps the draft. Whoever reads or writes
|
||||
/// the session from another stream or the host afterwards (a new request, a checkpoint, a snapshot, the prompt
|
||||
/// path, the end of a run) calls wait_commit() first. STRATA_COMMIT_SYNC=1 keeps the wait.
|
||||
static void set_commit_async(bool on);
|
||||
/// Waits for the last commit graph when commit() did not (an event recorded after it, not the whole device);
|
||||
/// false with `err` when it failed. Free when nothing is pending.
|
||||
bool wait_commit(std::string& err);
|
||||
|
||||
/// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head -
|
||||
/// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the
|
||||
/// distribution at pos0 + t, targets[t] is the token at pos0 + t + 1, extra_logprob is the log-probability of
|
||||
/// `extra_id` in the same row, and the last column is the target's log-probability in that row renormalized
|
||||
/// over every token but `extra_id` (both nan when they do not apply). A layer split's earlier stage forwards
|
||||
/// to the stage that holds the head.
|
||||
bool window_logprobs(const int32_t* targets, int T, int64_t pos0, int32_t extra_id, std::FILE* out,
|
||||
std::string& err);
|
||||
|
||||
/// Token t's residual after the last layer, (hc, n_embd) on the device, valid until the next `run`.
|
||||
const float* final_R(int t) const;
|
||||
const float* final_R_all() const { return next_ ? next_->final_R_all() : R_; }
|
||||
|
||||
/// The GPU plan the pool writes each layer (VRAM hits + the PCIe share of the misses); give it to the
|
||||
/// dispatch (`ExpertDispatch::plan`) before the first `run`.
|
||||
GpuPlanSink* plan_sink() { return &sink_; }
|
||||
/// Plan v0.3 P6: split the window into two token groups and pipeline the CPU experts of one with the GPU work
|
||||
/// of the other (default on). Set before the first `run`.
|
||||
void set_split(bool on) { split_ = on; }
|
||||
/// Plan v0.3 P6: how the PCIe share of the misses reaches the GPU: 0 = DMA into staging (the copy engine works
|
||||
/// beside the CPU; best when the CPU is compute-bound, the i-quants), 1 = the grouped kernel reads the mapped
|
||||
/// arena directly, 2 = a copy kernel stages it inside the graph (no API calls on the pool's thread; best when
|
||||
/// the CPU is RAM-bound, Q2_0). Set before the first `run`.
|
||||
void set_pcie_mode(int mode) { sink_.pcie_mode = mode; }
|
||||
/// the pool never plans a PCIe share (--pcie-frac 0): the window skips that path. Before the first run.
|
||||
|
||||
double ms_wait = 0, ms_pool = 0, ms_host = 0, ms_commit = 0;
|
||||
int64_t windows = 0;
|
||||
/// STRATA_VERIFY_PROFILE=1 - GPU stage times of the windows since the last call (ms per
|
||||
/// window), as one line; empty when off.
|
||||
std::string profile_report();
|
||||
|
||||
private:
|
||||
RemoteExpertOpt* remote_opt_ = nullptr;
|
||||
bool capture(int T, std::string& err);
|
||||
// batch windows (see init_slots)
|
||||
std::vector<SessionState*> slots_;
|
||||
bool batch_rec_ = false; ///< record_window is capturing a batch window
|
||||
int row_base_ = 0; ///< ... its hand-off rows start here (a pipeline group's own rows)
|
||||
int brow_[8] = {}; ///< ... and row t is slot brow_[t]
|
||||
bool last_batch_ = false; ///< the last run was a batch window (set_plan_slot: one group)
|
||||
std::map<uint64_t, cudaGraphExec_t> exec_bm_, commit_bm_; ///< key: batch_key(rows, S, hand-off base)
|
||||
int last_rows_[8] = {}; ///< the slots of the last batch window's rows
|
||||
static uint64_t batch_key(const int* rows, int S, int hbase) {
|
||||
uint64_t k = (uint64_t) hbase << 40 | (uint64_t) S << 32;
|
||||
for (int t = 0; t < S; ++t) k |= (uint64_t) (rows[t] & 15) << (4 * t);
|
||||
return k;
|
||||
}
|
||||
// batch_launch / batch_poll
|
||||
bool b_running_ = false;
|
||||
int64_t b_k_ = 0, b_steps_ = 0;
|
||||
std::chrono::steady_clock::time_point b_last_;
|
||||
int32_t b_out_[8] = {};
|
||||
std::vector<strata::kernels::SamplerParams> slot_sp_;
|
||||
bool sample_rows(int S, std::string& err); ///< the sampled slots' rows of the last batch window
|
||||
int32_t* h_commitb_ = nullptr; int32_t* m_commitb_ = nullptr; // per slot [1, 0, pos, -1 ..], stride 2 + max_t
|
||||
int32_t* commitb_ = nullptr;
|
||||
float* tail_snap_b_ = nullptr; ///< per (slot, QSA layer) indexer tail snapshot
|
||||
void* arena_b_ = nullptr;
|
||||
int64_t last_pos_b_[8] = {};
|
||||
bool capture_batch(const int* rows, int S, int hbase, std::string& err);
|
||||
void collect_profile(); ///< STRATA_VERIFY_PROFILE: add the last window's stamps to prof_sum_
|
||||
bool capture_commit_batch(const int* rows, int S, int hbase, std::string& err);
|
||||
bool stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos, std::string& err);
|
||||
strata::kernels::SamplerParams sampling_ = [] {
|
||||
strata::kernels::SamplerParams s;
|
||||
s.greedy = true;
|
||||
s.temperature = 0.0f;
|
||||
return s;
|
||||
}(); ///< greedy by default; per-request via set_sampling
|
||||
const int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties apply
|
||||
int hist_len_ = 0;
|
||||
bool head_sampling_ = true; ///< set_head_sampling
|
||||
int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split)
|
||||
std::atomic<bool> released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows
|
||||
bool all_resident_ = false; ///< 100% of experts in [lb_, le_) resident in VRAM: zero-doorbell graph
|
||||
bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN)
|
||||
uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's)
|
||||
unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device
|
||||
int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last)
|
||||
const float* hand_in_ = nullptr;
|
||||
float* hand_out_ = nullptr;
|
||||
Verifier* next_ = nullptr;
|
||||
void* next_user_ = nullptr;
|
||||
bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs
|
||||
void stage_inputs(int T, const int32_t* tokens, int64_t pos0);
|
||||
bool staged_ = false;
|
||||
bool copy_used_ = false;
|
||||
bool capture_commit(std::string& err);
|
||||
bool record_window(int T, cudaStream_t cs, std::string& err);
|
||||
// #649: STRATA_VERIFY_TRACE=1 - a host event ring (trace_ev) and GPU breadcrumbs: the profiler's stamp points,
|
||||
// per layer and token group, written to mapped memory (null when the trace is off)
|
||||
void trace_ev(const char* what, int64_t step, int64_t layer, int64_t aux) const;
|
||||
unsigned long long* trace_h_ = nullptr;
|
||||
unsigned long long* trace_m_ = nullptr;
|
||||
size_t trace_n_ = 0;
|
||||
static constexpr int kProfPer = 33; // stamps per layer (32 left the hc-read second
|
||||
// half's up-stamp at slot 32 = the next layer's slot 0: D8)
|
||||
bool prof_on_ = false;
|
||||
unsigned long long* prof_ = nullptr; // device: n_layers * kProfPer + 4 stamps
|
||||
std::vector<unsigned long long> prof_h_;
|
||||
double prof_sum_[2][kProfPer] = {}; // [GDN / QSA layers][stage]
|
||||
int64_t prof_windows_ = 0;
|
||||
|
||||
const WeightTable* wt_ = nullptr;
|
||||
const ModelGeometry* g_ = nullptr;
|
||||
SessionState* ss_ = nullptr;
|
||||
VerifyHits hits_;
|
||||
const NativeHead* head_ = nullptr;
|
||||
int max_t_ = 0;
|
||||
int last_t_ = 0;
|
||||
int64_t last_pos0_ = 0;
|
||||
int32_t last_tokens_[8] = {};
|
||||
int64_t n_vocab_ = 0;
|
||||
cudaStream_t cs_ = nullptr;
|
||||
cudaStream_t sh_cs_ = nullptr;
|
||||
cudaEvent_t ev_fork_ = nullptr, ev_join_ = nullptr;
|
||||
cudaGraphExec_t exec_[9] = {};
|
||||
cudaGraphExec_t commit_exec_ = nullptr;
|
||||
|
||||
// mapped staging (host pointer, device alias)
|
||||
int32_t* h_tok_ = nullptr; int32_t* m_tok_ = nullptr; // T
|
||||
int32_t* h_step_ = nullptr; int32_t* m_step_ = nullptr; // T * kStepCount
|
||||
int32_t* h_pos_ = nullptr; int32_t* m_pos_ = nullptr; // T * n_head
|
||||
int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}]
|
||||
float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd
|
||||
int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids
|
||||
float* h_x_ = nullptr; float* m_x_ = nullptr; // doorbell payload: T * n_embd
|
||||
int32_t* h_ids_ = nullptr; int32_t* m_ids_ = nullptr; // T * k
|
||||
float* h_w_ = nullptr; float* m_w_ = nullptr; // T * k
|
||||
uint32_t* h_seq_ = nullptr; uint32_t* m_seq_ = nullptr;
|
||||
uint32_t* h_flag_ = nullptr; uint32_t* m_flag_ = nullptr;
|
||||
uint32_t* h_flagA_ = nullptr; uint32_t* m_flagA_ = nullptr; // the GPU plan is in place
|
||||
uint32_t* h_flagB_ = nullptr; uint32_t* m_flagB_ = nullptr; // the PCIe share's DMA copies have landed
|
||||
cudaEvent_t commit_done_ = nullptr; // recorded after an async commit (set_commit_async); see wait_commit
|
||||
bool commit_pending_ = false;
|
||||
cudaStream_t copy_ = nullptr; // the copy engine's stream (DMA of missed experts)
|
||||
struct FlagSet { uint32_t* flag; uint32_t value; };
|
||||
FlagSet flag_sets_[2 * 64 * 2] = {}; // host-function arguments, one per (layer, group)
|
||||
static void fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes);
|
||||
static void raise_flag(uint32_t* flag, uint32_t value);
|
||||
int32_t* h_plan_ = nullptr; int32_t* m_plan_ = nullptr; // counts | start | dst | tok | ptr (as int32 pairs)
|
||||
int64_t plan_i32_ = 0; // int32 words in the plan block
|
||||
GpuPlanSink sink_;
|
||||
uint32_t cur_layer_ = 0;
|
||||
static void publish_plan(void* ctx);
|
||||
void set_plan_slot(int grp);
|
||||
bool split_ = false; // opt-in (--spec-split): exact but slower, see the overlap study
|
||||
int groups_[9] = {};
|
||||
float* h_ymiss_ = nullptr; float* m_ymiss_ = nullptr; // T * k * n_embd
|
||||
|
||||
// device
|
||||
void* arena_ = nullptr;
|
||||
int32_t *tok_ = nullptr, *step_ = nullptr, *pos_ = nullptr, *commit_ = nullptr;
|
||||
float *ple_ = nullptr, *emb_ = nullptr, *R_ = nullptr, *mixed_ = nullptr, *bo_ = nullptr;
|
||||
float *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *xn_ = nullptr;
|
||||
uint8_t* xq_ = nullptr; // T columns of q8_1
|
||||
uint8_t* sh_xq_ = nullptr; // T columns of q8_1 for shared expert branch
|
||||
float *qkv_L_ = nullptr, *h_L_ = nullptr, *gate_L_ = nullptr, *beta_L_ = nullptr; // per GDN layer
|
||||
float *z_ = nullptr, *y_ = nullptr, *y_dummy_ = nullptr;
|
||||
float *qfull_ = nullptr, *qcur_ = nullptr, *kcur_ = nullptr, *vcur_ = nullptr, *idx_raw_L_ = nullptr;
|
||||
float *qidx_ = nullptr, *scores_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr, *attn_scratch_ = nullptr;
|
||||
float* tail_snap_ = nullptr; // per QSA layer
|
||||
int32_t* sel_ = nullptr;
|
||||
float *logits_ = nullptr, *w_ = nullptr, *shared_ = nullptr, *parts_ = nullptr, *hit_out_ = nullptr;
|
||||
int32_t *ids_ = nullptr, *hit_slot_ = nullptr, *hit_dst_ = nullptr, *hit_count_ = nullptr;
|
||||
int32_t* plan_ = nullptr; // device copy of the plan block
|
||||
uint8_t* staging_ = nullptr; // VRAM slots for the PCIe share of the misses
|
||||
static constexpr int64_t kStagingBlobs = 16;
|
||||
static constexpr int64_t kPcieGroupRows = 4; // the PCIe call's groups side by side (of <= 16)
|
||||
uint8_t* hit_xq_ = nullptr;
|
||||
uint8_t* nat_xq_ = nullptr; // plan v0.3 P6: q8_1 activations for a native pack's grouped experts
|
||||
float* hit_xs_ = nullptr;
|
||||
void* hit_scratch_ = nullptr;
|
||||
float *head_mixed_ = nullptr, *head_inj_ = nullptr, *head_logits_ = nullptr;
|
||||
uint16_t* sh_bf16_ = nullptr;
|
||||
float *sh_gate_ = nullptr, *sh_up_ = nullptr, *sh_g_ = nullptr;
|
||||
float* hist_snap_ = nullptr; // T * NG_HIST * NG_HC_DIM
|
||||
int64_t cap_ = 0, max_blocks_ = 0, attn_scratch_floats_ = 0;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,144 +0,0 @@
|
||||
// include/strata/core/weights.hpp - the dense weights, loaded into VRAM in ENGINE form.
|
||||
//
|
||||
// The pack is the ARTIFACT's business; this is the ENGINE's. The differences are deliberate, and they run in
|
||||
// BOTH directions:
|
||||
//
|
||||
// * SHRINKING. A tensor whose source type is BF16 is stored in the pack promoted to 32 bits, because that is
|
||||
// lossless and it keeps the canonical decoder simple, but a running engine re-rounds it to 16 - which costs
|
||||
// nothing at all, because the value CAME from 16 bits. Per `tools/pack_budget.py` that saving is the
|
||||
// difference between the dense weights fitting in VRAM beside the expert cache and not fitting at all.
|
||||
//
|
||||
// * GROWING. 90 of the 303 quantized tensors carry fp16 SCALES in the pack (all 58 Q2_0 expert tensors, plus
|
||||
// Q4_0, Q5_0, Q8_0 and IQ4_NL) because that is what the source block holds. Every kernel here takes
|
||||
// `const float* scales`, and fp16 is a subset of f32, so this loader WIDENS them - exactly, changing no
|
||||
// value - for 11,407,360 B. See `docs/pack-format.md` §2.4; assuming 4 bytes per scale instead of reading
|
||||
// `scales_fp16` is what made the plane arithmetic disagree with the pack for a whole round.
|
||||
//
|
||||
// pack 5.305 GiB dense + 0.444 GiB embd
|
||||
// engine 4.067 GiB dense + 0.444 GiB embd + 10.88 MiB widened scales = 4.522 GiB
|
||||
//
|
||||
// WHAT THE LOADER DOES NOT DO: it does not know what any tensor MEANS. It reads a flat index
|
||||
// (`<pack>/index.txt`, written by `tools/pack_index.py`), copies each tensor into one arena at a recorded
|
||||
// offset - as a list of PLANE SEGMENTS, because a scale plane can change width and the rest cannot - and hands
|
||||
// back a name -> WeightRef map. Geometry, forms and semantics belong to the caller.
|
||||
//
|
||||
// WHY AN INDEX FILE AND NOT A JSON PARSER: a JSON parser in the engine would be a new, unaudited component
|
||||
// whose failure mode is a wrong byte offset - which decodes to a plausible weight and produces plausible
|
||||
// logits. Python wrote the manifest and already parses it correctly.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// What the loader had to DO for a tensor, decided by `tools/pack_index.py` and written into the index
|
||||
/// rather than inferred here. The four cases are distinguishable in the manifest only by combining
|
||||
/// `source_type` with `values_fp16`, and getting that combination wrong yields a plausible tensor.
|
||||
enum class WeightKind : int {
|
||||
Verbatim = 0, ///< quantized planes, or F16 already stored as 2 bytes: copy straight through
|
||||
Bf16InF32 = 1, ///< the pack holds the bf16 value promoted to f32: take the HIGH 16 BITS (exact)
|
||||
F32 = 2, ///< copy 4 bytes per element
|
||||
F16InF32 = 3, ///< an f16 value promoted to f32: a real f32->f16 conversion, not a truncation
|
||||
};
|
||||
|
||||
struct WeightRef {
|
||||
const void* data = nullptr; ///< device pointer inside the arena
|
||||
uint64_t bytes = 0;
|
||||
int64_t ne0 = 0; ///< the manifest's own shape, ne0 the CONTIGUOUS axis
|
||||
int64_t ne1 = 0;
|
||||
int64_t elements = 0;
|
||||
WeightKind kind = WeightKind::Verbatim;
|
||||
/// The canonical-form attributes, valid only for a quantized VERBATIM tensor (`code_bits != 0`).
|
||||
int code_bits = 0;
|
||||
int code_bias = 0;
|
||||
int group_elems = 0;
|
||||
bool codebook_iq4nl = false;
|
||||
bool has_offset = false;
|
||||
|
||||
/// THE THREE PLANE SIZES, IN ENGINE FORM, in the order they sit inside `data`. Recorded by the loader
|
||||
/// from what the index TOLD it rather than re-derived by each caller: the one time this layout was
|
||||
/// re-derived independently it assumed 4-byte scales for tensors whose pack scales are fp16, and the
|
||||
/// only reason that was not a silent wrong answer is that the re-derivation checked itself and refused.
|
||||
/// Two places computing one layout is two places to disagree.
|
||||
uint64_t codes_bytes = 0;
|
||||
uint64_t scales_bytes = 0; ///< always 4 B per scale in the arena, whatever the pack held
|
||||
uint64_t offset_bytes = 0; ///< 0 when the form has no offset plane
|
||||
|
||||
/// WHERE THIS TENSOR CAME FROM, so a caller can check the loader's work against the pack's own bytes
|
||||
/// instead of against the loader's opinion of them. Without `src_off` a test can only compare two
|
||||
/// derived numbers; with it, the widening of an fp16 scale plane can be verified value by value against
|
||||
/// `<file>.bin` - and the pack files are named, so `file_id` says which one to open.
|
||||
uint64_t src_off = 0;
|
||||
uint64_t src_bytes = 0;
|
||||
int file_id = 0;
|
||||
bool scales_fp16 = false; ///< the PACK's width, before the loader widened it
|
||||
|
||||
/// WHICH ACTIVATION THIS WEIGHT WANTS - 0 for Q8_0, 1 for Q8_K. Decided by ools/pack_index.py from
|
||||
/// source_type and carried here, because **the S-form CANNOT express it**: Q5_0 and Q5_K are both 8-bit
|
||||
/// with bias -16, and IQ4_NL and IQ4_XS differ in nothing the S-form holds. docs/activation-contract.md.
|
||||
int act_kind = 0;
|
||||
bool wants_q8k() const { return act_kind == 1; }
|
||||
|
||||
bool quantized() const { return code_bits != 0; }
|
||||
|
||||
// Optional native GGUF projection, owned by NativeDense. All references in
|
||||
// one table share its scratch and must execute on one ordered session stream.
|
||||
const void* native_data = nullptr;
|
||||
void* native_q8_1 = nullptr;
|
||||
int native_type = -1;
|
||||
/// Plan v0.3 P1: false when the loader SKIPPED this tensor's canonical bytes because another form serves it
|
||||
/// (native GGUF projections, the native head). The metadata above stays valid; `data` is null.
|
||||
bool resident = true;
|
||||
};
|
||||
|
||||
struct LoadReport {
|
||||
size_t tensors = 0;
|
||||
uint64_t arena_bytes = 0;
|
||||
size_t re_rounded = 0; ///< tensors written as 16 bits out of a 32-bit container
|
||||
uint64_t bytes_saved = 0; ///< what those conversions saved against the pack
|
||||
double read_ms = 0.0;
|
||||
double upload_ms = 0.0;
|
||||
};
|
||||
|
||||
class WeightTable {
|
||||
public:
|
||||
/// The arena size the index asks for, readable WITHOUT loading anything - so a caller can size its
|
||||
/// `DeviceArena` before committing to the load, and a plan that cannot fit is refused at startup rather
|
||||
/// than halfway through a 5 GB upload.
|
||||
/// With `skip`, the size of the compacted arena that holds every tensor EXCEPT the named ones.
|
||||
static bool pool_bytes(const std::string& pack_dir, uint64_t& out, std::string& err,
|
||||
const std::set<std::string>* skip = nullptr);
|
||||
|
||||
/// The `code_bits` field of one row of `<pack_dir>/index.txt`, readable WITHOUT loading anything (0 = the
|
||||
/// pack stores the tensor unquantized, e.g. a --compat-bf16 key; -1 = no such row). #326: the loader has
|
||||
/// to know this before it builds the skip set.
|
||||
static bool index_code_bits(const std::string& pack_dir, const std::string& name, int& code_bits,
|
||||
std::string& err);
|
||||
|
||||
/// Load every tensor in `<pack_dir>/index.txt` into `arena_base`.
|
||||
///
|
||||
/// `arena_bytes` MUST be at least `pool_bytes`; the loader checks rather than trusting the caller,
|
||||
/// because the failure mode otherwise is a device write past the end of the arena.
|
||||
/// With `skip`, the named tensors are not read: their rows keep their metadata with `data == nullptr` and
|
||||
/// `resident == false`, and the other tensors are packed into the compacted arena `pool_bytes` sized.
|
||||
bool load(const std::string& pack_dir, void* arena_base, uint64_t arena_bytes, std::string& err,
|
||||
const std::set<std::string>* skip = nullptr);
|
||||
|
||||
const WeightRef* find(const std::string& name) const;
|
||||
const std::map<std::string, WeightRef>& all() const { return table_; }
|
||||
/// A test seam: one row, as `load` would have made it (the Qwen3.6 prefill harness builds a table from a synthetic
|
||||
/// GGUF without a pack). The caller owns the device memory the row points at.
|
||||
void set(const std::string& name, const WeightRef& ref) { table_[name] = ref; }
|
||||
const LoadReport& report() const { return report_; }
|
||||
|
||||
private:
|
||||
friend class NativeDense;
|
||||
std::map<std::string, WeightRef> table_;
|
||||
LoadReport report_;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,60 +0,0 @@
|
||||
#pragma once
|
||||
#include <hipblas/hipblas.h>
|
||||
#include <hipblas/hipblas-version.h>
|
||||
|
||||
#if hipblasVersionMajor == 0
|
||||
// Ubuntu's hipBLAS 0.54 has no workspace API or compute-type enum. Use its
|
||||
// underlying rocBLAS API directly, including ownership of the real handle,
|
||||
// so the engine's explicit workspace contract is preserved.
|
||||
#include <rocblas/rocblas.h>
|
||||
#define CUBLAS_COMPUTE_32F rocblas_datatype_f32_r
|
||||
#define CUBLAS_DEFAULT_MATH 0
|
||||
#define CUBLAS_GEMM_DEFAULT rocblas_gemm_algo_standard
|
||||
#define CUBLAS_OP_N rocblas_operation_none
|
||||
#define CUBLAS_OP_T rocblas_operation_transpose
|
||||
#define CUBLAS_STATUS_SUCCESS rocblas_status_success
|
||||
#define CUDA_R_16BF rocblas_datatype_bf16_r
|
||||
#define CUDA_R_16F rocblas_datatype_f16_r
|
||||
#define CUDA_R_32F rocblas_datatype_f32_r
|
||||
#define cublasCreate rocblas_create_handle
|
||||
#define cublasDestroy rocblas_destroy_handle
|
||||
#define cublasHandle_t rocblas_handle
|
||||
#define cublasSetStream rocblas_set_stream
|
||||
#define cublasSetWorkspace rocblas_set_workspace
|
||||
#define cublasStatus_t rocblas_status
|
||||
|
||||
inline rocblas_status cublasSetMathMode(rocblas_handle h, int mode) {
|
||||
// This API has only its default arithmetic; GEMM below explicitly selects
|
||||
// FP32 accumulation. Reject any request for a different math mode.
|
||||
if (!h) return rocblas_status_invalid_handle;
|
||||
return mode == CUBLAS_DEFAULT_MATH ? rocblas_status_success : rocblas_status_invalid_value;
|
||||
}
|
||||
inline rocblas_status cublasGemmEx(rocblas_handle h, rocblas_operation trans_a,
|
||||
rocblas_operation trans_b, int m, int n, int k, const void* alpha,
|
||||
const void* a, rocblas_datatype a_type, int lda,
|
||||
const void* b, rocblas_datatype b_type, int ldb, const void* beta,
|
||||
void* c, rocblas_datatype c_type, int ldc,
|
||||
rocblas_datatype compute_type, rocblas_gemm_algo algo) {
|
||||
return rocblas_gemm_ex(h, trans_a, trans_b, m, n, k, alpha,
|
||||
a, a_type, lda, b, b_type, ldb, beta, c, c_type, ldc,
|
||||
c, c_type, ldc, compute_type, algo, 0, 0);
|
||||
}
|
||||
#else
|
||||
#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F
|
||||
#define CUBLAS_DEFAULT_MATH HIPBLAS_DEFAULT_MATH
|
||||
#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT
|
||||
#define CUBLAS_OP_N HIPBLAS_OP_N
|
||||
#define CUBLAS_OP_T HIPBLAS_OP_T
|
||||
#define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS
|
||||
#define CUDA_R_16BF HIP_R_16BF
|
||||
#define CUDA_R_16F HIP_R_16F
|
||||
#define CUDA_R_32F HIP_R_32F
|
||||
#define cublasCreate hipblasCreate
|
||||
#define cublasDestroy hipblasDestroy
|
||||
#define cublasGemmEx hipblasGemmEx
|
||||
#define cublasHandle_t hipblasHandle_t
|
||||
#define cublasSetMathMode hipblasSetMathMode
|
||||
#define cublasSetStream hipblasSetStream
|
||||
#define cublasSetWorkspace hipblasSetWorkspace
|
||||
#define cublasStatus_t hipblasStatus_t
|
||||
#endif
|
||||
@@ -1,2 +0,0 @@
|
||||
#pragma once
|
||||
#include <hip/hip_fp16.h>
|
||||
@@ -1,143 +0,0 @@
|
||||
#pragma once
|
||||
// Included only by STRATA_ENABLE_HIP builds. CUDA builds use NVIDIA headers.
|
||||
#if defined(_WIN32)
|
||||
// hip_runtime.h pulls in <windows.h> on Windows: keep its min/max macros and the rarely used APIs out of the engine.
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#endif
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <hip/hip_version.h>
|
||||
// Do not let HIP's legacy macro corrupt libstdc++ attribute names.
|
||||
#ifdef __noinline__
|
||||
#undef __noinline__
|
||||
#endif
|
||||
#define cudaDevAttrMaxSharedMemoryPerBlockOptin hipDeviceAttributeMaxSharedMemoryPerBlock
|
||||
#define cudaDevAttrMultiProcessorCount hipDeviceAttributeMultiprocessorCount
|
||||
#define cudaDevAttrClockRate hipDeviceAttributeClockRate
|
||||
#define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor
|
||||
#define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor
|
||||
#define cudaDeviceGetAttribute hipDeviceGetAttribute
|
||||
#define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer
|
||||
#define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess
|
||||
#define cudaDeviceProp hipDeviceProp_t
|
||||
#define cudaDeviceSynchronize hipDeviceSynchronize
|
||||
#define cudaDriverGetVersion hipDriverGetVersion
|
||||
#define cudaErrorNotReady hipErrorNotReady
|
||||
#define cudaErrorPeerAccessAlreadyEnabled hipErrorPeerAccessAlreadyEnabled
|
||||
#define cudaErrorStreamCaptureUnsupported hipErrorStreamCaptureUnsupported
|
||||
#define cudaError_t hipError_t
|
||||
#define cudaEventCreate hipEventCreate
|
||||
#define cudaEventCreateWithFlags hipEventCreateWithFlags
|
||||
#define cudaEventDestroy hipEventDestroy
|
||||
#define cudaEventDisableTiming hipEventDisableTiming
|
||||
#define cudaEventElapsedTime hipEventElapsedTime
|
||||
#define cudaEventQuery hipEventQuery
|
||||
#define cudaEventRecord hipEventRecord
|
||||
#define cudaEventSynchronize hipEventSynchronize
|
||||
#define cudaEvent_t hipEvent_t
|
||||
#define cudaFree hipFree
|
||||
#if HIP_VERSION_MAJOR < 7
|
||||
#define cudaFreeHost hipHostFree
|
||||
#else
|
||||
#define cudaFreeHost hipFreeHost
|
||||
#endif
|
||||
#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize
|
||||
#define cudaFuncAttributePreferredSharedMemoryCarveout hipFuncAttributePreferredSharedMemoryCarveout
|
||||
#define cudaGetDevice hipGetDevice
|
||||
#define cudaGetDeviceCount hipGetDeviceCount
|
||||
#define cudaGetDeviceProperties hipGetDeviceProperties
|
||||
#define cudaGetErrorString hipGetErrorString
|
||||
#define cudaGetLastError hipGetLastError
|
||||
#define cudaGraphDestroy hipGraphDestroy
|
||||
#define cudaGraphExecDestroy hipGraphExecDestroy
|
||||
#define cudaGraphExec_t hipGraphExec_t
|
||||
#define cudaGraphGetNodes hipGraphGetNodes
|
||||
#define cudaGraphLaunch hipGraphLaunch
|
||||
#define cudaGraphUpload hipGraphUpload
|
||||
#define cudaGraph_t hipGraph_t
|
||||
#define cudaHostAlloc hipHostMalloc
|
||||
#if HIP_VERSION_MAJOR < 7
|
||||
#define cudaHostAllocDefault hipHostMallocDefault
|
||||
#define cudaHostAllocMapped hipHostMallocMapped
|
||||
#define cudaHostAllocPortable hipHostMallocPortable
|
||||
#else
|
||||
#define cudaHostAllocDefault hipHostAllocDefault
|
||||
#define cudaHostAllocMapped hipHostAllocMapped
|
||||
#define cudaHostAllocPortable hipHostAllocPortable
|
||||
#endif
|
||||
#define cudaHostGetDevicePointer hipHostGetDevicePointer
|
||||
#define cudaHostRegister hipHostRegister
|
||||
#define cudaHostRegisterMapped hipHostRegisterMapped
|
||||
#define cudaHostRegisterPortable hipHostRegisterPortable
|
||||
#define cudaHostRegisterReadOnly hipHostRegisterReadOnly
|
||||
#define cudaHostUnregister hipHostUnregister
|
||||
#define cudaLaunchHostFunc hipLaunchHostFunc
|
||||
#define cudaMalloc hipMalloc
|
||||
#define cudaMallocHost(...) (::strata::hip_compat::malloc_host(__VA_ARGS__))
|
||||
#if defined(_WIN32)
|
||||
// Windows: hipMemGetInfo counts this process's own allocations only, so the desktop's and other programs' share of
|
||||
// the card is invisible to it, and VRAM sized by it overfills the card (WDDM then moves memory out to system RAM and
|
||||
// the GPU slows down). Its free figure is lowered by what Windows' video memory budget for this process withholds
|
||||
// (src/core/device.cu; STRATA_WDDM_BUDGET=0: hipMemGetInfo as it is).
|
||||
namespace strata::hip_compat {
|
||||
hipError_t mem_get_info(size_t* free_bytes, size_t* total_bytes);
|
||||
}
|
||||
#define cudaMemGetInfo ::strata::hip_compat::mem_get_info
|
||||
#else
|
||||
#define cudaMemGetInfo hipMemGetInfo
|
||||
#endif
|
||||
#define cudaMemcpy hipMemcpy
|
||||
#define cudaMemcpy2DAsync hipMemcpy2DAsync
|
||||
#define cudaMemcpyAsync hipMemcpyAsync
|
||||
#define cudaMemcpyPeerAsync hipMemcpyPeerAsync
|
||||
#define cudaMemcpyDefault hipMemcpyDefault
|
||||
#define cudaMemcpyDeviceToDevice hipMemcpyDeviceToDevice
|
||||
#define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost
|
||||
#define cudaMemcpyHostToDevice hipMemcpyHostToDevice
|
||||
#define cudaMemset hipMemset
|
||||
#define cudaMemsetAsync hipMemsetAsync
|
||||
#define cudaPeekAtLastError hipPeekAtLastError
|
||||
#define cudaRuntimeGetVersion hipRuntimeGetVersion
|
||||
#define cudaSetDevice hipSetDevice
|
||||
#define cudaStreamBeginCapture hipStreamBeginCapture
|
||||
#define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal
|
||||
#define cudaStreamCaptureStatus hipStreamCaptureStatus
|
||||
#define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone
|
||||
#define cudaStreamCreate hipStreamCreate
|
||||
#define cudaStreamCreateWithFlags hipStreamCreateWithFlags
|
||||
#define cudaStreamDestroy hipStreamDestroy
|
||||
#define cudaStreamEndCapture hipStreamEndCapture
|
||||
#define cudaStreamIsCapturing hipStreamIsCapturing
|
||||
#define cudaStreamNonBlocking hipStreamNonBlocking
|
||||
#define cudaStreamQuery hipStreamQuery
|
||||
#define cudaStreamSynchronize hipStreamSynchronize
|
||||
#define cudaStreamWaitEvent hipStreamWaitEvent
|
||||
#define cudaStream_t hipStream_t
|
||||
#define cudaSuccess hipSuccess
|
||||
|
||||
namespace strata::hip_compat {
|
||||
template <typename T>
|
||||
inline hipError_t malloc_host(T** pointer, size_t bytes) {
|
||||
return hipHostMalloc(reinterpret_cast<void**>(pointer), bytes, hipHostMallocDefault);
|
||||
}
|
||||
} // namespace strata::hip_compat
|
||||
|
||||
template <typename Kernel>
|
||||
inline hipError_t cudaFuncSetAttribute(Kernel kernel, hipFuncAttribute attribute, int value) {
|
||||
return hipFuncSetAttribute(reinterpret_cast<const void*>(kernel), attribute, value);
|
||||
}
|
||||
inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, unsigned long long flags) {
|
||||
return hipGraphInstantiateWithFlags(exec, graph, flags);
|
||||
}
|
||||
inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph,
|
||||
hipGraphNode_t* error, char* log, size_t size) {
|
||||
return hipGraphInstantiate(exec, graph, error, log, size);
|
||||
}
|
||||
#define __trap() __builtin_trap() // the compiled-out sm_80 paths (never selected on AMD)
|
||||
#define cudaMemcpyToSymbol(symbol, ...) hipMemcpyToSymbol(HIP_SYMBOL(symbol), __VA_ARGS__)
|
||||
|
||||
#include "intrinsics.hpp"
|
||||
@@ -1,2 +0,0 @@
|
||||
#pragma once
|
||||
#include "cuda_runtime.h"
|
||||
@@ -1,162 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// CUDA device intrinsics used by Strata kernels on supported wave32 HIP targets.
|
||||
// This header is included only from the HIP cuda_runtime compatibility shim.
|
||||
#if defined(__HIPCC__)
|
||||
#include <hip/hip_version.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::hip_compat {
|
||||
|
||||
__device__ __forceinline__ int signed_byte(uint32_t word, int lane) {
|
||||
const unsigned value = (word >> (lane * 8)) & 0xffu;
|
||||
return value < 0x80u ? static_cast<int>(value) : static_cast<int>(value) - 0x100;
|
||||
}
|
||||
|
||||
// CUDA's signed __dp4a: four signed byte products accumulated modulo 2^32.
|
||||
__device__ __forceinline__ int dp4a(int a, int b, int c) {
|
||||
#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1200__) || \
|
||||
defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4)
|
||||
// RDNA3 and RDNA4 expose the signed/unsigned dot4 form (v_dot4_i32_iu8). Mark
|
||||
// both packed operands signed to preserve CUDA __dp4a semantics; keep the
|
||||
// portable path for other HIP compilers/targets.
|
||||
return __builtin_amdgcn_sudot4(true, a, true, b, c, false);
|
||||
#elif (defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__)) && __has_builtin(__builtin_amdgcn_sdot4)
|
||||
// RDNA2 has no sudot4 (that is gfx11+), but it has the plain signed v_dot4_i32_i8 (dot1-insts): the same
|
||||
// signed x signed byte products accumulated modulo 2^32, no clamp.
|
||||
return __builtin_amdgcn_sdot4(a, b, c, false);
|
||||
#elif defined(__gfx1012__) && !defined(STRATA_GFX1012_PORTABLE_DOT)
|
||||
// RDNA1 has no native signed dot4. SDWA selects and sign-extends byte
|
||||
// operands directly, avoiding separate shift/mask/sign-extension work.
|
||||
// Adapted from pinned llama.cpp ggml-cuda/common.cuh (MIT; see
|
||||
// third_party/ggml/LICENSE), same modulo-2^32 accumulation contract.
|
||||
int lo, hi;
|
||||
asm("v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0\n"
|
||||
"v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:BYTE_1\n"
|
||||
"v_add3_u32 %0, %1, %2, %0\n"
|
||||
"v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_2\n"
|
||||
"v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_3\n"
|
||||
"v_add3_u32 %0, %1, %2, %0\n"
|
||||
// c changes before the high-byte reads; it must not alias a or b.
|
||||
: "+&v"(c), "=&v"(lo), "=&v"(hi) : "v"(a), "v"(b));
|
||||
return c;
|
||||
#else
|
||||
const uint32_t ua = static_cast<uint32_t>(a);
|
||||
const uint32_t ub = static_cast<uint32_t>(b);
|
||||
uint32_t sum = static_cast<uint32_t>(c);
|
||||
#pragma unroll
|
||||
for (int lane = 0; lane < 4; ++lane)
|
||||
sum += static_cast<uint32_t>(signed_byte(ua, lane) * signed_byte(ub, lane));
|
||||
return static_cast<int>(sum);
|
||||
#endif
|
||||
}
|
||||
|
||||
// CUDA's __byte_perm (default mode): result byte i is byte s.nibble[i] & 7 of the pair {y:x}, x the low word.
|
||||
// HIP's own version indexes a byte array in private memory, which becomes scratch traffic in the i-quant table
|
||||
// lookups; v_perm_b32 is the same selection in one instruction (selector bytes 0-3 pick from its second
|
||||
// operand, 4-7 from its first), so the nibble selector is spread to bytes and masked to 0-7.
|
||||
__device__ __forceinline__ uint32_t byte_perm(uint32_t x, uint32_t y, uint32_t s) {
|
||||
const uint32_t sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12);
|
||||
return __builtin_amdgcn_perm(y, x, sel);
|
||||
}
|
||||
|
||||
// The packed byte operations below work on all four lanes at once (SWAR, Hacker's Delight 2-18): gfx11/gfx12 have
|
||||
// no packed 8-bit subtract, and a per-lane loop costs the Q3_K/Q6_K dots and the i-quant sign expansion several
|
||||
// times the instructions. kHigh is each lane's top bit.
|
||||
constexpr uint32_t kHigh = 0x80808080u;
|
||||
|
||||
// CUDA's packed byte subtract wraps independently in each unsigned byte lane: subtract the low seven bits with the
|
||||
// minuend's top bit forced on (so no borrow crosses a lane), then fix each top bit by XOR.
|
||||
__device__ __forceinline__ int vsub4(int a, int b) {
|
||||
const uint32_t ua = static_cast<uint32_t>(a);
|
||||
const uint32_t ub = static_cast<uint32_t>(b);
|
||||
return static_cast<int>(((ua | kHigh) - (ub & ~kHigh)) ^ ((ua ^ ~ub) & kHigh));
|
||||
}
|
||||
|
||||
// CUDA's packed signed-byte saturating subtract: the wrapping difference, and in each lane that overflowed (operand
|
||||
// signs differ and the result's sign differs from the minuend's) the bound on the minuend's side, 0x7f or 0x80.
|
||||
__device__ __forceinline__ int vsubss4(int a, int b) {
|
||||
const uint32_t ua = static_cast<uint32_t>(a);
|
||||
const uint32_t ub = static_cast<uint32_t>(b);
|
||||
const uint32_t d = static_cast<uint32_t>(vsub4(a, b));
|
||||
const uint32_t overflow = (ua ^ ub) & (ua ^ d) & kHigh;
|
||||
const uint32_t mask = (overflow >> 7) * 0xffu;
|
||||
const uint32_t bound = 0x7f7f7f7fu + ((ua & kHigh) >> 7);
|
||||
return static_cast<int>((d & ~mask) | (bound & mask));
|
||||
}
|
||||
|
||||
// CUDA's four-lane byte compare, returning 0xff for each unequal lane and 0 otherwise: a lane of a ^ b is nonzero
|
||||
// when its low seven bits carry into the top bit on adding 0x7f, or its top bit is already set.
|
||||
__device__ __forceinline__ int vcmpne4(int a, int b) {
|
||||
const uint32_t t = static_cast<uint32_t>(a) ^ static_cast<uint32_t>(b);
|
||||
const uint32_t nonzero = (((t & ~kHigh) + ~kHigh) | t) & kHigh;
|
||||
return static_cast<int>((nonzero >> 7) * 0xffu);
|
||||
}
|
||||
|
||||
// CUDA's mask argument describes participating lanes. The current kernel set uses full
|
||||
// wave32 masks; reject future partial-mask use instead of silently dropping its semantics.
|
||||
__device__ __forceinline__ void require_full_wave_mask(uint32_t mask) {
|
||||
if (mask != 0xffffffffu) __builtin_trap();
|
||||
}
|
||||
|
||||
// Older HIP has no __syncwarp. A wave barrier alone does not order memory.
|
||||
// Release/acquire fences cover the shared-memory exchange used by attention.
|
||||
#if HIP_VERSION_MAJOR < 7
|
||||
__device__ __forceinline__ void syncwarp(uint32_t mask = 0xffffffffu) {
|
||||
require_full_wave_mask(mask);
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup");
|
||||
__builtin_amdgcn_wave_barrier();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup");
|
||||
}
|
||||
#endif
|
||||
|
||||
template <typename T>
|
||||
__device__ __forceinline__ T shfl_xor_sync(uint32_t mask, T value, int lane_mask, int width = 32) {
|
||||
require_full_wave_mask(mask);
|
||||
return __shfl_xor(value, lane_mask, width);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
__device__ __forceinline__ T shfl_down_sync(uint32_t mask, T value, unsigned delta, int width = 32) {
|
||||
require_full_wave_mask(mask);
|
||||
return __shfl_down(value, delta, width);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
__device__ __forceinline__ T shfl_up_sync(uint32_t mask, T value, unsigned delta, int width = 32) {
|
||||
require_full_wave_mask(mask);
|
||||
return __shfl_up(value, delta, width);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
__device__ __forceinline__ T shfl_sync(uint32_t mask, T value, int source_lane, int width = 32) {
|
||||
require_full_wave_mask(mask);
|
||||
return __shfl(value, source_lane, width);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ unsigned ballot_sync(uint32_t mask, int predicate) {
|
||||
require_full_wave_mask(mask);
|
||||
return static_cast<unsigned>(__ballot(predicate));
|
||||
}
|
||||
|
||||
} // namespace strata::hip_compat
|
||||
|
||||
#define __dp4a(a, b, c) (::strata::hip_compat::dp4a((a), (b), (c)))
|
||||
#define __byte_perm(x, y, s) (::strata::hip_compat::byte_perm((x), (y), (s)))
|
||||
#define __vsub4(a, b) (::strata::hip_compat::vsub4((a), (b)))
|
||||
#define __vsubss4(a, b) (::strata::hip_compat::vsubss4((a), (b)))
|
||||
#define __vcmpne4(a, b) (::strata::hip_compat::vcmpne4((a), (b)))
|
||||
#define __shfl_xor_sync(...) (::strata::hip_compat::shfl_xor_sync(__VA_ARGS__))
|
||||
#define __shfl_down_sync(...) (::strata::hip_compat::shfl_down_sync(__VA_ARGS__))
|
||||
#define __shfl_up_sync(...) (::strata::hip_compat::shfl_up_sync(__VA_ARGS__))
|
||||
#define __shfl_sync(...) (::strata::hip_compat::shfl_sync(__VA_ARGS__))
|
||||
#define __ballot_sync(mask, predicate) (::strata::hip_compat::ballot_sync((mask), (predicate)))
|
||||
#if HIP_VERSION_MAJOR < 7
|
||||
#define __syncwarp(...) (::strata::hip_compat::syncwarp(__VA_ARGS__))
|
||||
#endif
|
||||
// AMD's sleep instruction accepts only 0..15; the synchronization loops use it as a
|
||||
// backoff hint, so use its smallest portable delay independently of CUDA cycle counts.
|
||||
#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1)
|
||||
|
||||
#endif // defined(__HIPCC__)
|
||||
@@ -1,4 +0,0 @@
|
||||
#pragma once
|
||||
// CUDA spelling used by the attention kernels; included only in HIP builds.
|
||||
#include <hip/hip_math_constants.h>
|
||||
#define CUDART_INF_F HIP_INF_F
|
||||
@@ -1,61 +0,0 @@
|
||||
// include/strata/kernels/bf16_bits.hpp - the bf16 conversions, written out, as bits.
|
||||
//
|
||||
// bf16 is the TOP HALF of an f32, so `f32_from_bf16` is a shift and needs no rounding at all. The forward
|
||||
// direction does: ggml's `ggml_compute_fp32_to_bf16` adds `((i >> 16) & 1) + 0x7FFF` and truncates 16 bits.
|
||||
//
|
||||
// **THE `& 1` IS ON BIT 16**, the lowest KEPT bit, which is what makes an exact tie round to EVEN. Using bit
|
||||
// 15 there is a plausible mistake: it differs only on exact ties, i.e. almost never on real data, which is
|
||||
// exactly why it would survive any amount of end-to-end testing. `ref/quant.py` documents the same rule for
|
||||
// the same reason.
|
||||
//
|
||||
// WHY THIS IS SEPARATE FROM `f16_bits.hpp`: fp16 and bf16 are not two spellings of one idea. fp16 has 5
|
||||
// exponent bits and 10 mantissa bits; bf16 has 8 and 7. A conversion routine written for one and reused for
|
||||
// the other is wrong in a way that produces plausible numbers - bf16's 2^-9 relative precision looks like a
|
||||
// small fp16 error and is not small at all next to fp16's 2^-11.
|
||||
//
|
||||
// `gr.cu` carried a private copy of `f32_to_bf16_bits` until this header existed. It now includes this.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#if defined(__CUDACC__) || defined(__HIPCC__)
|
||||
#define STRATA_BF16_HD __host__ __device__
|
||||
#else
|
||||
#define STRATA_BF16_HD
|
||||
#endif
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// Round-to-nearest-even f32 -> bf16, returned as raw bits in the LOW half of the uint16.
|
||||
///
|
||||
/// **A NaN IS PASSED THROUGH, QUIETED, AS `ggml_compute_fp32_to_bf16` DOES.** The rounding add alone
|
||||
/// carries out of the mantissa for a NaN: 0x7FFFFFFF became 0x8000 (-0) and 0x7F800001 became 0x7F80 (+inf), so
|
||||
/// a NaN upstream was masked instead of propagated. The test is on the magnitude bits, the result keeps the
|
||||
/// sign and the top mantissa bits and sets the quiet bit (64 = bit 6 of the bf16). Every non-NaN input,
|
||||
/// infinities included, rounds exactly as before.
|
||||
STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) {
|
||||
uint32_t i;
|
||||
#if defined(__HIP_DEVICE_COMPILE__)
|
||||
__builtin_memcpy(&i, &f, 4);
|
||||
#else
|
||||
std::memcpy(&i, &f, 4);
|
||||
#endif
|
||||
if ((i & 0x7FFFFFFFu) > 0x7F800000u) return (uint16_t) ((i >> 16) | 64u);
|
||||
i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
|
||||
return (uint16_t) (i >> 16);
|
||||
}
|
||||
|
||||
/// bf16 bits -> f32. Exact, and no rounding: the low 16 bits of an f32 are simply zero.
|
||||
STRATA_BF16_HD inline float f32_from_bf16(uint16_t h) {
|
||||
const uint32_t i = (uint32_t) h << 16;
|
||||
float f;
|
||||
#if defined(__HIP_DEVICE_COMPILE__)
|
||||
__builtin_memcpy(&f, &i, 4);
|
||||
#else
|
||||
std::memcpy(&f, &i, 4);
|
||||
#endif
|
||||
return f;
|
||||
}
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -1,56 +0,0 @@
|
||||
// include/strata/kernels/bf16_gemv.hpp - the GEMV for a BF16 weight, P2.S5.
|
||||
//
|
||||
// WHY THIS EXISTS WHEN `s_gemv` ALREADY DOES. `s_gemv` decodes the S-family canonical forms (S2/S4/S8) from
|
||||
// `codes` + `scales`, and a BF16 weight is not one of them - it has no codes and no scales, it is a plain
|
||||
// 16-bit matrix. Six tensors per layer are in that state:
|
||||
//
|
||||
// ssm_alpha.weight, ssm_beta.weight GDN, [n_embd, 48]
|
||||
// indexer.q_proj.weight, indexer.k_proj.weight QSA, [n_embd, 512] and [n_embd, 128]
|
||||
// ple_value.weight layer 1, [n_embd, n_embd]
|
||||
// ffn_gate_inp.weight handled inside `router_top10`
|
||||
//
|
||||
// The original entry points take BF16 activation bits for the historical CPU-derived contract. The explicit
|
||||
// FP32 entry point below follows the pinned CUDA single-token MMVF contract. See docs/activation-contract.md
|
||||
// for why activation precision depends on backend and batch geometry rather than weight type alone.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// `y[o] = sum_i f32(x[i]) * f32(w[o*n_in + i])`, with both sides bf16-valued so every product is exact in
|
||||
/// f32 and only the summation order differs.
|
||||
///
|
||||
/// THE WEIGHT LAYOUT IS THE MANIFEST'S: shape [n_in, n_out] with ne0 = n_in CONTIGUOUS, so row `o` is a
|
||||
/// contiguous run of `n_in` bf16 values. That is the same convention `s_gemv` uses, and it is what
|
||||
/// `strata::core::WeightRef::ne0/ne1` already report.
|
||||
void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream);
|
||||
|
||||
/// The row-split variant, for the same reason `s_gemv_split` exists: with one thread per output row the
|
||||
/// parallelism IS the output width, and `ssm_alpha` has 48 of them over 48 SMs. One warp per row, lanes
|
||||
/// striding the reduction axis - which is also what makes the access pattern coalesced in this layout.
|
||||
///
|
||||
/// NOT bit-identical to `bf16_gemv`: the partial sums are added in a different order. Both are kept and both
|
||||
/// are tested, because the naive one is the reference the split one is checked against.
|
||||
void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out,
|
||||
int threads_per_row, void* stream);
|
||||
|
||||
/// Single-token, contiguous 2D BF16-weight/F32-activation MMVF from the pinned llama.cpp CUDA path.
|
||||
/// Preserves pair accumulation, adaptive block size and warp-XOR reduction order. This is a separate
|
||||
/// opt-in entry point; the legacy BF16-activation kernels above retain their behavior.
|
||||
/// `w[o*n_in+i]` is BF16 bits; x/y are F32. n_in must be positive and even, n_out positive, both <= INT_MAX.
|
||||
/// x must be 8-byte aligned, w 4-byte aligned, and y 4-byte aligned. Throws on invalid geometry/pointers.
|
||||
/// The device buffers must not overlap; allocation bounds remain the caller's responsibility.
|
||||
/// No allocations or synchronization, including when stream is null (the CUDA default stream).
|
||||
void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
|
||||
int64_t n_in, int64_t n_out, void* stream);
|
||||
/// `ncols` columns at once: x is [ncols][n_in], y is [ncols][n_out]; each column bitwise equal to a
|
||||
/// `bf16_gemv_fp32_mmvf` call on it.
|
||||
void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols,
|
||||
void* stream);
|
||||
/// bf16_gemv_fp32_mmvf for n_tok (1..8) activation rows x[t * ldx], outputs y[t * ldy + j]; one launch,
|
||||
/// the weight read once, every output bit-identical to its own single-row call.
|
||||
void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
|
||||
int64_t n_in, int64_t n_out, int n_tok, void* stream);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -1,179 +0,0 @@
|
||||
// include/strata/kernels/cpu/expert.hpp - P2.S3: the CPU expert path.
|
||||
//
|
||||
// This is the Q2_0 expert kernel promoted out of `bench/micro/cpu_s2.cpp`, which is the instrument that
|
||||
// measured `c` (Memory/LEDGER.md L9/L10: 15.03 ms for one token's full routed set on 6 cores, DRAM-bound at
|
||||
// 44.14 GB/s) and whose P0.T2 parity passes at 1.461e-06.
|
||||
//
|
||||
// IT IS THE SAME CODE, NOT A COPY. Keeping a second implementation next to a validated one is how a project
|
||||
// ends up with two answers and no way to say which is right, so `cpu_s2.cpp` is expected to become a thin
|
||||
// benchmark over these functions. (Until it is, the two exist side by side and this header says so.)
|
||||
//
|
||||
// WHAT MAKES IT FAST, and each of the three was paid for once:
|
||||
//
|
||||
// * `vpdpbusd` (AVX512-VNNI) does four int8 MACs per instruction. The scalar loop it replaces ran at
|
||||
// 9.89 GB/s on one core; VNNI is the reason the 6-core figure is 42.55 GB/s.
|
||||
// * `vpmultishiftqb` (AVX512-VBMI) unpacks the 2-bit codes eight at a time. Its ARGUMENT ORDER is
|
||||
// (control, data) and was determined empirically - the Intel guide states the opposite, and following the
|
||||
// guide produced 43 of 64 wrong codes.
|
||||
// * The row accumulator stays a FLOAT VECTOR and is reduced ONCE at the end of the row. Reducing per
|
||||
// 64-weight block cost more than the dot products themselves: it made the kernel compute-bound at
|
||||
// 21 GB/s instead of DRAM-bound at 32.
|
||||
//
|
||||
// THE CONTRACT THAT MATTERS, because collapsing it is invisible and cannot match ggml's logits: one Q2_0
|
||||
// WEIGHT block is QK=64 weights with one fp16 scale, while one ACTIVATION chunk is QKA=32 elements with
|
||||
// its OWN scale. So a weight block spans TWO activation chunks with two different scales. Using one scale
|
||||
// per weight block is the natural-looking mistake.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
// ---- geometry, all of it fixed by the artifact (tools/verify_q2_0_geometry.py: 202/202 tensors at QK=64) ----
|
||||
inline constexpr int H = 2560; // n_embd
|
||||
inline constexpr int FF = 640; // expert intermediate width
|
||||
inline constexpr int NE = 512; // routed experts per layer
|
||||
inline constexpr int QK = 64; // QK2_0: weights per fp16 scale
|
||||
inline constexpr int QKA = 32; // QK8_1/QK8_0: ACTIVATION elements per scale
|
||||
inline constexpr int BB = 18; // bytes per 64-weight Q2_0 block: 2 fp16-scale + 16 codes
|
||||
inline constexpr int MAXC = H / QKA; // 80 activation chunks across the widest reduction
|
||||
inline constexpr int ROW_GU = H * 2 / 8; // 640 B of codes per gate/up row
|
||||
inline constexpr int ROW_D = FF * 2 / 8; // 160 B of codes per down row
|
||||
inline constexpr int SC_GU = H / QK; // 40 weight blocks per gate/up row
|
||||
inline constexpr int SC_D = FF / QK; // 10 weight blocks per down row
|
||||
inline constexpr size_t BLOB = 3ull * (H * FF * BB / QK); // 1,382,400
|
||||
|
||||
// ---- the blob's internal layout (one expert) ----
|
||||
inline constexpr size_t O_GU_CODES = 0;
|
||||
inline constexpr size_t O_D_CODES = 2ull * FF * ROW_GU;
|
||||
inline constexpr size_t O_GU_SCALES = O_D_CODES + 1ull * H * ROW_D;
|
||||
inline constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2;
|
||||
|
||||
/// One activation in Strata's planar storage: `QKA` elements per chunk.
|
||||
/// The default legacy quantizer uses FP32 scales and half-away rounding. It is
|
||||
/// not the pinned ggml CPU Q8_0 contract; expert_set_oracle_q8_0 selects that
|
||||
/// experimental contract (FP16-rounded scales and x86 nearest-even codes).
|
||||
///
|
||||
/// The historical function name `act_quant_q8_1` does not describe a native
|
||||
/// ggml block layout. One 64-weight block always spans two 32-element chunks.
|
||||
///
|
||||
/// `hx[k] = scale[k] * sum[k]` is the weight-independent correction the Q2_0 identity needs
|
||||
/// (`sum (c-1) d_w xhat d_x = d_w (d_x*sum(c*xhat) - d_x*sum(xhat))`), precomputed once per layer rather than
|
||||
/// once per row: 640 rows would otherwise recompute it 640 times.
|
||||
struct ActQ {
|
||||
alignas(64) int8_t q[H];
|
||||
float scale[MAXC];
|
||||
int32_t sum[MAXC];
|
||||
float hx[MAXC];
|
||||
int nchunks;
|
||||
};
|
||||
|
||||
/// Per-worker scratch. Owned by the caller and passed in, so the token path performs NO allocations
|
||||
/// (P2.T10) - the kernel itself allocates nothing.
|
||||
struct ExpertScratch {
|
||||
ActQ a1;
|
||||
ActQ a2;
|
||||
alignas(64) float ff[FF];
|
||||
};
|
||||
|
||||
/// Runtime CPU feature check. The kernel uses AVX512-VNNI + AVX512-VBMI + AVX512VL, and code compiled with
|
||||
/// `/arch:AVX512` can emit AVX-512 anywhere in its translation unit, so a machine without them must be
|
||||
/// REFUSED rather than silently run. `s2_expert_scalar` is the fallback and exists for tests.
|
||||
struct CpuFeatures {
|
||||
bool avx512f = false;
|
||||
bool avx512bw = false;
|
||||
bool avx512vl = false;
|
||||
bool avx512_vnni = false;
|
||||
bool avx512_vbmi = false;
|
||||
bool usable() const { return avx512f && avx512bw && avx512vl && avx512_vnni && avx512_vbmi; }
|
||||
/// A one-line description of what is missing, or "ok".
|
||||
const char* reason() const;
|
||||
};
|
||||
CpuFeatures cpu_features();
|
||||
|
||||
/// Exits with a clear message if the CPU cannot run `s2_expert_vnni`. Called once at startup, so a user on an
|
||||
/// older CPU learns why at second zero instead of seeing an illegal instruction at token 4000.
|
||||
void cpu_require_expert_support();
|
||||
|
||||
/// Select the pinned x86 Q8_0 activation contract at BOTH expert quantization
|
||||
/// boundaries and the pinned generic CPU Q2_0 dot reduction in all projections.
|
||||
/// Default false preserves the legacy quantizer and eight-lane FP32 reduction.
|
||||
/// Configure before starting worker threads and do not change during a request.
|
||||
/// GPU expert-cache parity is not established for this mode; the driver must
|
||||
/// reject combining it with that cache. No allocation occurs in either mode.
|
||||
void expert_set_oracle_q8_0(bool enabled);
|
||||
|
||||
/// `x` -> `a` in the configured contract. The function name is historical;
|
||||
/// `n` must be a multiple of QKA and at most H. No allocation occurs.
|
||||
void act_quant_q8_1(const float* x, int n, ActQ& a);
|
||||
|
||||
/// One expert: `out(H) = down( swiglu( gate(x), up(x) ) )`, all three projections Q2_0,
|
||||
/// with the configured activation and dot contracts at both quantization boundaries.
|
||||
///
|
||||
/// `blob` is one 1,382,400-byte expert in the pack's layout; `x` is the H-wide input; `out` is H-wide.
|
||||
void s2_expert_vnni(const uint8_t* blob, const float* x, float* out, ExpertScratch& ws);
|
||||
|
||||
/// The same, with the activation ALREADY quantized in the configured contract.
|
||||
/// Workers may share this read-only activation; each must own its scratch/output.
|
||||
///
|
||||
/// This split exists for the pool. A layer runs TEN experts against ONE activation, so quantizing inside
|
||||
/// `s2_expert_vnni` would do the same 2560-element conversion ten times per layer per token - 480 redundant
|
||||
/// conversions per token. P2.S3's work item is `(blob, x-hat quantized, block sums, weight, out)`, and this
|
||||
/// is the entry point that matches it.
|
||||
void s2_expert_vnni_q(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws);
|
||||
|
||||
/// Plan v0.3 P6: ONE expert applied to up to MAXT tokens that were all routed to it (a speculative verify
|
||||
/// window routes ~1.5 tokens to each distinct expert). The 1.38 MB blob is read and its 2-bit codes unpacked
|
||||
/// ONCE per block for all tokens; only the VNNI dot and the accumulation run per token. Every token's output
|
||||
/// is bitwise equal to `s2_expert_vnni_q` on that token (same operation order per token). Legacy activation
|
||||
/// contract only; with `expert_set_oracle_q8_0(true)` it falls back to one `s2_expert_vnni_q` per token.
|
||||
inline constexpr int MAXT = 8;
|
||||
/// Plan v0.3 P4: the expert in row ranges, so several threads can share one expert. `s2_expert_gu_rows` writes
|
||||
/// ff[r] = silu(gate_r . x) * (up_r . x) for r in [r0, r1) (of FF); `s2_expert_down_rows` writes out[r] for r in
|
||||
/// [r0, r1) (of H) from the intermediate's quantized image. Together with `act_quant_q8_1(ff, FF, a2)` in
|
||||
/// between they are exactly `s2_expert_vnni_q`, row for row (same `row_dot`), so the result is bitwise the same.
|
||||
bool expert_oracle_q8_0_enabled();
|
||||
void s2_expert_gu_rows(const uint8_t* blob, const ActQ& a1, float* ff, int r0, int r1);
|
||||
void s2_expert_down_rows(const uint8_t* blob, const ActQ& a2, float* out, int r0, int r1);
|
||||
|
||||
/// Plan v0.3 P6: the row-range kernels for up to MAXT tokens routed to the same expert (legacy contract only).
|
||||
/// Each token's rows are bitwise the single-token `s2_expert_gu_rows` / `s2_expert_down_rows`.
|
||||
void s2_expert_gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* ff, int r0,
|
||||
int r1);
|
||||
void s2_expert_down_rows_multi(const uint8_t* blob, const ActQ* const* a2, int n_tokens, float* const* out, int r0,
|
||||
int r1);
|
||||
|
||||
struct ExpertScratchMulti {
|
||||
ActQ a2[MAXT];
|
||||
alignas(64) float ff[MAXT][FF];
|
||||
ExpertScratch single; // the oracle-contract fallback
|
||||
};
|
||||
void s2_expert_vnni_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* out,
|
||||
ExpertScratchMulti& ws);
|
||||
|
||||
/// The scalar transcription of ggml's formula - NOT a second opinion, but the ORACLE the VNNI path is checked
|
||||
/// against, and the only path available on a CPU without AVX-512.
|
||||
///
|
||||
/// `quant_acts` makes the oracle consume the SAME INT8 activation values the VNNI path uses, **at BOTH
|
||||
/// stages**. With it OFF the oracle is exact-FP32-activation and the gap between them IS the activation
|
||||
/// contract; with it ON the two differ only by FP32 evaluation order, so a small gap there proves the kernel
|
||||
/// itself correct. That separation is the whole point of P0.T2 and it is why this parameter exists rather
|
||||
/// than two functions.
|
||||
///
|
||||
/// CORRECTION TO THE ORIGINAL: `bench/micro/cpu_s2.cpp`'s comment says "at both stages" but its code
|
||||
/// quantizes only the intermediate, leaving the gate/up projections on raw f32 `x`. That is invisible when
|
||||
/// the caller passes an already-quantized input - which the engine does - and shows up as a ~1.2% gap when it
|
||||
/// does not, which reads as a kernel bug and is not one. This version quantizes both.
|
||||
/// Plan v0.3 P6: rows [r0, r1) of a Q2_0 matrix in the GGUF block layout (18 bytes per 64 weights, `row_bytes`
|
||||
/// per row, `nblocks` blocks each) against `nt` activations: out[t][r].
|
||||
void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
/// The same two for CPUs without AVX-512 (src/kernels/cpu/q2_avx2.cpp, compiled for AVX2 only).
|
||||
void q2_0_gguf_rows_multi_avx2(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
void act_quant_q8_1_avx2(const float* x, int n, ActQ& a);
|
||||
|
||||
void s2_expert_scalar(const uint8_t* blob, const float* x, float* out, bool quant_acts);
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -1,87 +0,0 @@
|
||||
// include/strata/kernels/cpu/expert_layout.hpp - plan v0.3 P6: where each routed expert lives in experts.bin.
|
||||
//
|
||||
// A Q2_0 pack (tools/strata_pack.py) has one blob size for every layer, `BLOB`, in the Strata expert form. A
|
||||
// native pack (tools/iq_pack.py, the IQ2_XS / IQ3_XXS files) keeps each expert's raw GGUF slices, so the blob
|
||||
// size and the formats change from layer to layer; `native_experts.txt` says how. Everything that touches an
|
||||
// expert blob - the arena, the VRAM tier, the prompt path, the CPU pool, the GPU window - asks this table.
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/cpu/expert.hpp"
|
||||
#include "strata/kernels/cpu/native_expert.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
struct ExpertLayout {
|
||||
bool native = false;
|
||||
int64_t n_layers = 0, n_expert = NE;
|
||||
std::vector<NativeFmt> fmt; ///< per layer (native packs)
|
||||
std::vector<uint64_t> offset, bytes; ///< per layer: where its 512 blobs start, bytes per blob
|
||||
/// Plan v0.3 P6: per layer, the absolute offsets of the gate / up / down tensors in their GGUF files, so the
|
||||
/// arena can be filled from the GGUF itself when the pack has no experts.bin (3 x n_layers, 0 = unknown).
|
||||
std::vector<uint64_t> gguf_off;
|
||||
/// Per layer PER ROLE (3 x n_layers, `3 * layer + role`, matching `gguf_off`), the GGUF file - a name beside
|
||||
/// the --native shard - that holds that role's tensor. Empty = the --native shard itself. Per role because a
|
||||
/// shard boundary can fall inside a layer: Unsloth's UD-Q4_K_XL has layer 11's down in shard 2 and its gate
|
||||
/// and up in shard 3 (native_experts.txt v4, the `gate,up,down` shard column).
|
||||
std::vector<std::string> gguf_file;
|
||||
int version = 0; ///< native_experts.txt's header version (0 = none given)
|
||||
uint64_t max_blob = BLOB;
|
||||
uint64_t total = 0; ///< experts.bin size
|
||||
|
||||
uint64_t blob_bytes(int64_t layer) const { return native ? bytes[(size_t) layer] : (uint64_t) BLOB; }
|
||||
uint64_t layer_offset(int64_t layer) const {
|
||||
return native ? offset[(size_t) layer] : (uint64_t) layer * (uint64_t) n_expert * (uint64_t) BLOB;
|
||||
}
|
||||
uint64_t blob_offset(int64_t layer, int64_t expert) const {
|
||||
return layer_offset(layer) + (uint64_t) expert * blob_bytes(layer);
|
||||
}
|
||||
};
|
||||
|
||||
/// Plan v0.3 P6: whether this CPU (and its OS) runs the AVX-512 kernels (F, BW, VL, VNNI, VBMI). Probed in a
|
||||
/// file compiled without AVX-512, so asking is safe everywhere; STRATA_FORCE_AVX2=1 answers no (for tests).
|
||||
bool cpu_avx512_ok();
|
||||
/// Whether this CPU runs AVX-512F + AVX-512BW + AVX-512VL + AVX-512DQ (e.g. Skylake-X i9-9920X) for iq_avx512.cpp.
|
||||
bool cpu_avx512bw_ok();
|
||||
/// Whether this CPU (and its OS) runs the AVX2 kernels (AVX, AVX2, FMA, F16C): the floor of every expert kernel
|
||||
/// (q2_avx2.cpp, iq_avx2.cpp, and ggml-cpu in the portable build). STRATA_FORCE_AVX2 does not change it.
|
||||
bool cpu_avx2_ok();
|
||||
/// Whether this CPU (and its OS) runs AVX (Sandy Bridge and newer): the AVX1 router dot (kq_avx1.cpp) and ggml-cpu in
|
||||
/// a STRATA_ISA_FLOOR=avx build. The other expert rows then run on ggml-cpu (experimental, slow).
|
||||
bool cpu_avx1_ok();
|
||||
/// SSE4.2 + POPCNT: ggml-cpu in a STRATA_ISA_FLOOR=none build.
|
||||
bool cpu_sse42_ok();
|
||||
/// STRATA_FORCE_ISA=avx2|avx|sse caps the probes above (3 = no cap, 2 = AVX2, 1 = AVX, 0 = SSE4.2), so the older-CPU
|
||||
/// paths run on any PC: tests and the experimental builds' checks. ggml-cpu keeps what it was compiled for.
|
||||
int cpu_isa_cap();
|
||||
/// The experimental older-CPU build this engine is ("avx", "sse4.2"), or "" for the normal build (AVX2 floor).
|
||||
const char* isa_floor_build();
|
||||
/// Whether a native pack's layer of this ggml type runs on Strata's own Q2_0 kernels (AVX2 / AVX-512). On a
|
||||
/// CPU without AVX2 (a native, non-portable build: ggml-cpu compiled for this CPU's SSE) a Q2_0 layer takes
|
||||
/// ggml-cpu's own Q2_0 vec_dot like every other native type: slower, but it runs.
|
||||
inline bool q2_native_kernels(int type) { return type == 42 && cpu_avx2_ok(); }
|
||||
/// The CPU's brand string (CPUID 0x80000002..4), for messages; "unknown" when it has none.
|
||||
std::string cpu_name();
|
||||
/// Q2_0 GGUF rows / activation quantizer on the kernels this CPU has.
|
||||
void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out,
|
||||
int r0, int r1);
|
||||
void act_quant_any(const float* x, int n, ActQ& a);
|
||||
|
||||
/// The process-wide layout (canonical Q2_0 until `expert_layout_load` finds a native pack).
|
||||
const ExpertLayout& expert_layout();
|
||||
/// Reads `<pack_dir>/native_experts.txt` when it exists (a native pack), else sets the canonical layout.
|
||||
/// Versions up to kExpertLayoutVersion are read; a newer one is refused (a newer packer wrote it).
|
||||
/// `n_embd` / `n_ff` are the MODEL's widths (ModelGeometry, read from the model file): each layer's `NativeFmt` is
|
||||
/// built with them and its byte count checked against the pack's blob size, so a pack of another geometry is refused
|
||||
/// here by its numbers. Until Phase 2 step 2 of the Qwen3.6 port this passed the compile-time 2560/640
|
||||
/// (geometry-inventory.md row 108), which refused every 2048/512 pack as "blob is X B but its formats make Y".
|
||||
bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int64_t n_embd, int64_t n_ff,
|
||||
std::string& err);
|
||||
/// The newest native_experts.txt this engine reads. v4 = v3 plus the per-role shard column `gate,up,down`,
|
||||
/// written only when some layer's roles are in different shards (every other pack stays v3, byte for byte).
|
||||
inline constexpr int kExpertLayoutVersion = 4;
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -1,26 +0,0 @@
|
||||
// include/strata/kernels/cpu/iq_avx2.hpp - AVX-2 multi-token dot products for the i-quant expert
|
||||
// formats (IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, IQ4_XS) against Q8_K activations (ggml's block_q8_K).
|
||||
//
|
||||
// The AVX-512 kernel's scheme on the CPUs without it (AMD Zen 2/3, Intel Core 12th-14th gen): the weights of a
|
||||
// 32-value chunk are decoded once per verify window and every token applies them with five instructions.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
bool iq256_supported(int ggml_type) noexcept;
|
||||
/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off.
|
||||
void iq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
|
||||
int nt, float* const* ff, int r0, int r1);
|
||||
/// out[t][r] = w_r . a[t], rows [r0, r1).
|
||||
void iq256_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
|
||||
/// out[t][r] = w_r . h[t] for IQ4_NL (type 20) rows against Q8_0 activations (ggml's block_q8_0).
|
||||
/// IQ4_NL is a 32-value-block format, so this does not go through iq256_rows (QK_K blocks, Q8_K acts).
|
||||
void iq4nl256_down_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -1,18 +0,0 @@
|
||||
// include/strata/kernels/cpu/iq_avx512.hpp - plan v0.3 P6: AVX-512 multi-token dot products for the i-quant
|
||||
// expert formats (IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S) against Q8_K activations (ggml's block_q8_K).
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
bool iq512_supported(int ggml_type) noexcept;
|
||||
/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off.
|
||||
void iq512_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
|
||||
int nt, float* const* ff, int r0, int r1);
|
||||
/// out[t][r] = w_r . a[t], rows [r0, r1).
|
||||
void iq512_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -1,18 +0,0 @@
|
||||
// include/strata/kernels/cpu/kq_avx1.hpp - the AVX1 router dot for older CPUs (from the Strata_Dirigo fork).
|
||||
//
|
||||
// bf16_rows_dot_multi (kq_avx2.cpp) is compiled with -mavx2 and uses instructions an AVX-only CPU does
|
||||
// not have (`vpmovzxwd`, `vfmadd`), so an AVX-only host cannot call it at all. This is the same
|
||||
// arithmetic on AVX1 instructions: 8 float lanes per token, one weight stream per row shared by all
|
||||
// `nt` tokens, one horizontal sum per (row, token). AVX1 has no FMA, so the multiply and the add stay
|
||||
// separate; it has no 256-bit integer ops, so the bf16 -> f32 widening runs in 128-bit halves.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
/// Mirrors bf16_rows_dot_multi's arithmetic (same accumulation shape, mul+add instead of FMA).
|
||||
/// Requires cols % 8 == 0 and nt <= 8, exactly like the AVX2 kernel it stands in for.
|
||||
void bf16_rows_dot_multi_avx1(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out);
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -1,25 +0,0 @@
|
||||
// include/strata/kernels/cpu/kq_avx2.hpp - AVX-2 multi-token dot products for Unsloth UD-Q4_K_XL's expert formats
|
||||
// (Q4_K gate/up against Q8_K activations; Q5_1 down against Q8_1, Q8_0 down against Q8_0), bit-exact against
|
||||
// ggml-cpu's AVX2 vec_dot for every token. See src/kernels/cpu/kq_avx2.cpp.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
/// Q4_K (12), Q5_1 (7), Q8_0 (8).
|
||||
bool kq256_supported(int ggml_type) noexcept;
|
||||
/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off.
|
||||
void kq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
|
||||
int nt, float* const* ff, int r0, int r1);
|
||||
/// out[t][r] = w_r . a[t], rows [r0, r1).
|
||||
void kq256_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt,
|
||||
float* const* out, int r0, int r1);
|
||||
|
||||
/// out[r] = w_r . x for BF16 rows (bits), fp32 x: the routing-aware prefetch's router (an estimate only).
|
||||
void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float* out);
|
||||
/// The same for `nt` <= 8 tokens (x: nt rows of cols, cols % 8 == 0), out[t * rows + r].
|
||||
void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out);
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -1,49 +0,0 @@
|
||||
// include/strata/kernels/cpu/native_expert.hpp - plan v0.3 P6: one routed expert in its GGUF form on the CPU.
|
||||
//
|
||||
// The IQ2_XS / IQ3_XXS model files keep their experts in i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS,
|
||||
// IQ3_S gate/up; Q2_0 or IQ4_NL down) whose values cannot be re-expressed in the Q2_0 pack form. A native expert
|
||||
// blob is the three GGUF slices back to back, [gate rows | up rows | down rows], and the arithmetic is ggml-cpu's
|
||||
// own (`ggml_get_type_traits_cpu`): the activation is quantized with the weight type's `vec_dot_type` and each row
|
||||
// is one `vec_dot`, exactly what llama.cpp's CPU backend computes for the same tensor.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
/// Bytes of the largest quantized activation any native layer uses (2560 values as Q8_K: 10 x 292).
|
||||
inline constexpr size_t kNativeActBytes = 4096;
|
||||
/// Bytes of the largest quantized down activation (640 values as Q8_0: 20 x 34, or Q8_K 3 x 292).
|
||||
inline constexpr size_t kNativeHBytes = 1024;
|
||||
|
||||
/// One layer's native expert geometry.
|
||||
struct NativeFmt {
|
||||
int gu_type = -1, d_type = -1; ///< ggml types of gate/up and of down
|
||||
int gu_act = -1, d_act = -1; ///< their vec_dot_type (the activation formats)
|
||||
int64_t n_embd = 0, n_ff = 0;
|
||||
size_t gu_row = 0, d_row = 0; ///< bytes per weight row
|
||||
size_t up_off = 0, down_off = 0; ///< inside the blob
|
||||
size_t bytes = 0; ///< the whole blob
|
||||
size_t act_bytes = 0, h_bytes = 0; ///< quantized activation sizes (n_embd of gu_act, n_ff of d_act)
|
||||
};
|
||||
|
||||
/// Whether this build has the ggml-cpu path.
|
||||
bool native_experts_available() noexcept;
|
||||
/// Fills `f` for a layer; false (with a reason) when ggml-cpu has no dot product for a type.
|
||||
bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err);
|
||||
|
||||
/// x (n_embd floats) -> the gate/up activation (act_bytes).
|
||||
void native_quant_act(const NativeFmt& f, const float* x, void* dst);
|
||||
/// h (n_ff floats) -> the down activation (h_bytes).
|
||||
void native_quant_h(const NativeFmt& f, const float* h, void* dst);
|
||||
|
||||
/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]) for rows r in [r0, r1), `nt` tokens.
|
||||
void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt, float* const* ff,
|
||||
int r0, int r1);
|
||||
/// out[t][r] = down_r . hq[t] for rows r in [r0, r1).
|
||||
void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt, float* const* out,
|
||||
int r0, int r1);
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -1,286 +0,0 @@
|
||||
// include/strata/kernels/cpu/pool.hpp - P2.S3: the CPU expert pool.
|
||||
//
|
||||
// A layer runs TEN experts against ONE activation, and the expert kernel is DRAM-bound (Memory/LEDGER.md L9:
|
||||
// 42.55 GB/s on 6 cores, tracking core count almost exactly). So the pool's job is not to be clever - it is
|
||||
// to keep every physical core reading expert bytes for the whole layer, and to be cheap enough that ten
|
||||
// dispatches per layer cost less than one expert.
|
||||
//
|
||||
// WHY A FLAT BATCH AND NOT A RING. P2.S3 describes a "lock-free SPMC ring", which is what you need when
|
||||
// jobs arrive while others are still being computed. Here they cannot: the host must SUM all ten outputs
|
||||
// before the next layer starts, so a layer is a barrier by construction and the queue never holds more than
|
||||
// one batch. A ring would add a wrap-around to get wrong and buy nothing. What is kept from the phase is
|
||||
// the part that matters: `head`/`done` are single fetch_add counters, one claim per worker, no lock.
|
||||
//
|
||||
// THE COMPLETION PROTOCOL, because this is where a pool usually goes wrong. `run()` waits for `done == n`
|
||||
// AND for every worker to PARK. Waiting only for `done` is not enough: a worker can still be inside the
|
||||
// drain loop after its last `done` increment, and the host resetting `head` underneath it would let that
|
||||
// worker claim a job from the NEXT batch before the next batch has been published.
|
||||
//
|
||||
// **AND `parked` IS NOT ENOUGH EITHER (issue #29).** A worker that went to sleep (after `kSpinBeforeSleep`) is
|
||||
// still counted as parked when it wakes, so for a moment after it has seen a new epoch the host believes it is
|
||||
// idle. On a card with most experts in VRAM the workers sleep in the middle of a request, tiny batches finish
|
||||
// before a sleeper is awake, and that moment comes round constantly: a late worker could claim from the NEXT
|
||||
// batch while the host was still writing it, run a job twice, or add to `done` after the host had reset it -
|
||||
// and `done != n` then never ended, with the GPU waiting on the pool forever. So every claim carries its
|
||||
// batch: `head` is one 64-bit word `epoch | njobs | index`, a claim is a CAS that only succeeds for the epoch
|
||||
// the worker woke for, and a late worker's claim simply fails. A claim that succeeds belongs to the current
|
||||
// batch, whose description the host cannot change until that job's `done` has landed.
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/cpu/expert.hpp"
|
||||
#include "strata/kernels/cpu/native_expert.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::kernels::cpu {
|
||||
|
||||
/// One expert evaluation. `act` is SHARED and read-only across the whole batch - that sharing is the point
|
||||
/// of `s2_expert_vnni_q` and it is what saves 480 redundant activation conversions per token.
|
||||
struct ExpertJob {
|
||||
const uint8_t* blob = nullptr; ///< one 1,382,400-byte expert
|
||||
const ActQ* act = nullptr; ///< the layer's quantized activation, shared
|
||||
float* out = nullptr; ///< H floats, written by exactly one worker
|
||||
float weight = 1.0f; ///< the router weight; applied by the HOST, not here
|
||||
int slot = -1; ///< the job's index, for diagnostics
|
||||
};
|
||||
|
||||
/// Plan v0.3 P6: one expert for the `nt` tokens of a verify window that were routed to it. Every token's output
|
||||
/// is bitwise the single-token job's.
|
||||
struct ExpertJobMulti {
|
||||
const uint8_t* blob = nullptr;
|
||||
int nt = 0;
|
||||
const ActQ* act[MAXT] = {};
|
||||
float* out[MAXT] = {};
|
||||
/// Plan v0.3 P6: a native pack's activations (the layer's `vec_dot_type`), one per token.
|
||||
const void* nact[MAXT] = {};
|
||||
};
|
||||
|
||||
/// How worker threads are allocated across physical/logical CPU cores (#272). `All` is the layout the pool has
|
||||
/// always used and the default; the hybrid-aware ones are opt-in (--pool-affinity auto|p-cores).
|
||||
enum class PoolAffinity {
|
||||
Auto, ///< Hybrid: prioritize physical P-cores, then SMT, then E-cores (defaults to P-core count)
|
||||
PCores, ///< Restrict workers strictly to Performance cores and their SMT siblings
|
||||
All, ///< The default: one worker per physical core in the OS's order, without hybrid distinction
|
||||
};
|
||||
|
||||
struct CpuTopology {
|
||||
bool is_hybrid = false;
|
||||
int p_cores = 0; ///< Physical performance cores
|
||||
int p_threads = 0; ///< Total logical threads on performance cores
|
||||
int e_cores = 0; ///< Efficient cores
|
||||
std::vector<int> worker_cores; ///< Ordered CPU IDs; on Windows, group * 64 + processor within the group
|
||||
int host_core = -1; ///< Logical core reserved for host thread
|
||||
};
|
||||
|
||||
CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity = PoolAffinity::All);
|
||||
|
||||
/// One logical processor per PHYSICAL core, so a worker is never scheduled onto an SMT sibling of another
|
||||
/// worker. On the 6-core/12-thread machine this project measures on, `hardware_concurrency()/2` workers on
|
||||
/// logical processors 0..5 would put every worker on a sibling pair and halve the useful bandwidth - which is
|
||||
/// exactly the kind of error that shows up as "the CPU path is slower than the model says" with no clue why.
|
||||
///
|
||||
/// `skip_first` drops the first core, which P2.S3 reserves for the host loop.
|
||||
std::vector<int> physical_cores(bool skip_first, PoolAffinity affinity = PoolAffinity::All);
|
||||
|
||||
/// **THE RESERVATION IS A FICTION UNLESS THE HOST IS ACTUALLY PUT THERE.**
|
||||
///
|
||||
/// `physical_cores(true)` keeps the workers off the first physical core so that the host loop can spin on
|
||||
/// `cudaEventQuery` without stealing a worker's cycles. Nothing in the pool can enforce the other half of
|
||||
/// that, so this is it: the host loop calls this on entry and restores on exit.
|
||||
///
|
||||
/// MEASURED, and this is why it exists: the pool runs at **36.32 GB/s on 5 workers with nothing else running**
|
||||
/// - exactly 5/6 of L9's 44.14 on 6 - and at **26.9 GB/s inside the host loop**, where the unpinned spinning
|
||||
/// host is free to land on a worker's core or its SMT sibling. That 1.35x is not the kernel.
|
||||
///
|
||||
/// The previous host placement. `valid` is false when querying or setting placement failed.
|
||||
/// Windows uses a reversible CPU Set selection, leaving hard affinity (including Windows 11's implicit
|
||||
/// all-group eligibility) untouched. An empty selection restores inheritance from the process defaults.
|
||||
/// Linux stores the complete, dynamically sized native CPU mask, including CPU IDs above 63.
|
||||
struct ThreadAffinity {
|
||||
#if defined(_WIN32)
|
||||
std::vector<unsigned long> cpu_sets;
|
||||
#else
|
||||
std::vector<unsigned long> mask;
|
||||
#endif
|
||||
bool valid = false;
|
||||
};
|
||||
|
||||
/// Selects one encoded processor for the caller; Windows CPU Sets respect existing hard-affinity limits.
|
||||
/// Restore on the same calling thread. Pool-owned workers use hard group affinity instead.
|
||||
ThreadAffinity pin_current_thread(int core);
|
||||
void restore_thread_affinity(const ThreadAffinity& previous);
|
||||
|
||||
class ExpertPool {
|
||||
public:
|
||||
/// `n_workers <= 0` means "every physical core except the first". Workers are pinned to physical cores
|
||||
/// (minus core 0 by default) and each owns one `ExpertScratch`, so nothing in the token path allocates.
|
||||
///
|
||||
/// **`host_works` PUTS THE HOST THREAD INTO THE DRAIN (R2.2's FIRST HALF).**
|
||||
///
|
||||
/// The pool reserves core 0 for the host loop so the doorbell spin cannot steal a worker's cycles - but
|
||||
/// during `run()` the host does not spin, it waits, so core 0 is idle for the whole drain. Measured on the
|
||||
/// 6-core machine this project targets: the engine's pool drains at **33.7 GB/s** (663.6 MB of expert
|
||||
/// blobs in 19.71 ms/token) where the same kernel on 5 workers should reach 5/6 x 44.14 = 36.8 and the
|
||||
/// machine measures 44.14 GB/s on all six. So the sixth core is being paid for and not used.
|
||||
///
|
||||
/// With `host_works`, `run()` claims jobs itself instead of spinning on `done_`, and the pool is six
|
||||
/// threads on six cores. `false` is the A/B arm and exists so the change is measurable rather than
|
||||
/// asserted - the counter it moves is `pool phases ... drain`, which is host-side and needs no profiler.
|
||||
explicit ExpertPool(int n_workers = 0, bool pin = true, bool host_works = true,
|
||||
PoolAffinity affinity = PoolAffinity::All);
|
||||
/// The watchdog's view of the pool (issue #31): the batch, the counters, every thread's state.
|
||||
void diag(std::FILE* f) const;
|
||||
~ExpertPool();
|
||||
ExpertPool(const ExpertPool&) = delete;
|
||||
ExpertPool& operator=(const ExpertPool&) = delete;
|
||||
|
||||
int workers() const { return n_; }
|
||||
/// Whether the host thread also drains. Reported at startup, because "the engine adapts to the machine it
|
||||
/// is on" is only true if the engine says which adaptation it took.
|
||||
bool host_works() const { return host_works_; }
|
||||
|
||||
bool is_hybrid() const { return topo_.is_hybrid; }
|
||||
int p_cores() const { return topo_.p_cores; }
|
||||
int p_threads() const { return topo_.p_threads; }
|
||||
int e_cores() const { return topo_.e_cores; }
|
||||
PoolAffinity affinity() const { return affinity_; }
|
||||
|
||||
/// Publish `n` jobs, then block until every one has been claimed AND every worker has parked.
|
||||
/// `jobs` must outlive the call (it does, and the workers never touch it afterwards).
|
||||
void run(ExpertJob* jobs, int n);
|
||||
|
||||
/// Plan v0.3 P4: the same outputs as `run`, bitwise, with every expert split by rows across all threads
|
||||
/// (gate/up rows, then the intermediate's quantization, then down rows). With fewer experts than threads -
|
||||
/// the case once the VRAM tier takes half of them - `run` leaves cores idle and each expert streams at one
|
||||
/// core's bandwidth; this streams every expert at all of them. At most `kMaxSplit` experts.
|
||||
void run_split(ExpertJob* jobs, int n);
|
||||
static constexpr int kMaxSplit = 16;
|
||||
/// Plan v0.3 P6: `run_split` for multi-token jobs (at most `kMaxSplitMulti`); the rows of each expert are
|
||||
/// read once for all of its tokens.
|
||||
void run_split_multi(ExpertJobMulti* jobs, int n);
|
||||
/// Plan v0.3 P6: the same for a native pack's layer (ggml-cpu arithmetic, `nact` activations).
|
||||
void run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs, int n);
|
||||
static constexpr int kMaxSplitMulti = 96;
|
||||
/// run_split_multi's phases, accumulated ms: gate/up rows, the intermediate quantization, down rows.
|
||||
double ms_multi_gu = 0, ms_multi_q = 0, ms_multi_down = 0;
|
||||
int64_t multi_bytes = 0;
|
||||
|
||||
/// Total `_mm_pause` iterations spent waiting, over all workers, is no longer counted - see the note on the
|
||||
/// atomics below. It was a LOCKED read-modify-write in the park loop, so measuring the contention added to
|
||||
/// it.
|
||||
long long pauses() const { return 0; }
|
||||
|
||||
/// **WHERE `run()` SPENDS ITS TIME, in milliseconds accumulated over its lifetime.** Three phases per
|
||||
/// layer - wait for every worker to be parked, wait for the drain, wait for them to re-park - and until now
|
||||
/// all three were reported as one number. Without the split there is no way to tell a pool that is slow at
|
||||
/// the WORK from one that is slow at the SYNCHRONISATION, and those need opposite fixes: the first is a
|
||||
/// kernel problem and the second is a barrier problem.
|
||||
///
|
||||
/// Only the host thread touches these, in `run()`, so they need no atomics.
|
||||
void phase_ms(double& wait_park, double& drain, double& repark) const {
|
||||
wait_park = ms_wait_park_;
|
||||
drain = ms_drain_;
|
||||
repark = ms_repark_;
|
||||
}
|
||||
|
||||
/// **A PARKED WORKER SPINS FOR THIS LONG, THEN SLEEPS.** The park is a `_mm_pause` spin because a layer's
|
||||
/// batches are microseconds apart and a wake-up from the OS costs more than that. But a spin that never ends
|
||||
/// keeps every worker's core at 100% while the engine waits for a request - issue #4, "CPU 50% even when
|
||||
/// doing nothing" (7 of the 5700X's 16 threads). Between requests the workers block on `sleep_cv_`. NOT only
|
||||
/// between requests: with most experts in VRAM (a 24 GB card) many layers have no CPU work, so the workers
|
||||
/// also sleep mid-request - which the claim protocol above must survive (issue #29).
|
||||
/// `STRATA_POOL_SPIN_US` overrides it (a test knob: a short spin makes the workers sleep constantly).
|
||||
static constexpr std::chrono::milliseconds kSpinBeforeSleep{20};
|
||||
/// A pool wait that sees no completion for this long is a bug; the engine stops with a message instead of
|
||||
/// spinning forever, and the server starts it again (issue #29).
|
||||
static constexpr std::chrono::seconds kStall{60};
|
||||
|
||||
private:
|
||||
void worker(int id);
|
||||
void drain(int id, ExpertScratch& scratch, uint32_t epoch);
|
||||
void run_phase(int mode, int n_tasks);
|
||||
/// Claim the next job of batch `epoch`, or -1 (that batch is exhausted, or it is not the current one).
|
||||
int claim(uint32_t epoch);
|
||||
/// Publish the batch whose description the caller has just written: reset `done`, then `head`, then the epoch.
|
||||
uint32_t begin_batch(int n);
|
||||
/// The host's waits, bounded by `kStall`.
|
||||
void wait_parked(const char* what);
|
||||
void wait_done(int n);
|
||||
/// Bump `epoch_`, and wake the workers that went to sleep. Every publish goes through here.
|
||||
void publish();
|
||||
|
||||
int n_ = 0;
|
||||
bool host_works_ = true;
|
||||
ExpertJob* jobs_ = nullptr;
|
||||
int njobs_ = 0;
|
||||
/// The host's own scratch when `host_works_`. A separate object rather than a share of `scratch_[i]`,
|
||||
/// because a worker may own any index and the two must not be able to collide.
|
||||
ExpertScratch host_scratch_;
|
||||
// `run()`'s three phases, accumulated. Host-thread only; see `phase_ms`.
|
||||
double ms_wait_park_ = 0.0;
|
||||
double ms_drain_ = 0.0;
|
||||
double ms_repark_ = 0.0;
|
||||
// ---- EACH ATOMIC GETS ITS OWN CACHE LINE, AND THE SPIN COUNTER IS GONE. (Review finding C3.)
|
||||
//
|
||||
// These were six adjacent atomics, which put `head_`, `done_`, `parked_` and `epoch_` on ONE cache line -
|
||||
// the four that workers and the host actually contend on, invalidating each other on every access.
|
||||
//
|
||||
// Worse, the parked spin did `pauses_.fetch_add(1)` on EVERY iteration: a LOCKED read-modify-write, five
|
||||
// workers against one line, at roughly one iteration per `_mm_pause`. So the line the host must WRITE to
|
||||
// publish work (`epoch_`) and READ to confirm the workers are parked (`parked_`) was being hammered by the
|
||||
// very threads waiting for it. That is contention the pool imposes on itself.
|
||||
//
|
||||
// The counter was diagnostic only - `pauses()` was read in one place, to print a number nothing branched on
|
||||
// - so it is deleted rather than amortised. `alignas(64)` then stops the remaining four sharing.
|
||||
// issue #31 diagnostics: each worker's state (kParked, kSleeping, kBetween, or the job it runs) and the host's
|
||||
// (kIdle, kWaitParked, kWaitDone, or its job), printed by the serve watchdog through `diag`
|
||||
static constexpr int32_t kParked = -1, kSleeping = -2, kBetween = -3, kIdle = -10, kWaitParked = -11,
|
||||
kWaitDone = -12;
|
||||
std::unique_ptr<std::atomic<int32_t>[]> wstate_;
|
||||
std::atomic<int32_t> hstate_{kIdle};
|
||||
std::atomic<int64_t> hstate_ms_{0};
|
||||
alignas(64) std::atomic<uint64_t> head_{0}; // epoch << 32 | njobs << 16 | next index (issue #29)
|
||||
alignas(64) std::atomic<uint32_t> done_{0};
|
||||
alignas(64) std::atomic<uint32_t> parked_{0};
|
||||
alignas(64) std::atomic<uint32_t> epoch_{0};
|
||||
alignas(64) std::atomic<bool> stop_{false};
|
||||
// The sleep after `kSpinBeforeSleep`. `sleepers_` is how `publish` knows whether anyone needs waking, so the
|
||||
// token path pays one uncontended load per publish and never takes the mutex while the workers spin.
|
||||
alignas(64) std::atomic<uint32_t> sleepers_{0};
|
||||
std::mutex sleep_mu_;
|
||||
std::condition_variable sleep_cv_;
|
||||
std::chrono::microseconds spin_before_sleep_{kSpinBeforeSleep};
|
||||
std::vector<std::thread> threads_;
|
||||
std::vector<ExpertScratch> scratch_; // one per worker: no allocation, no false sharing of the hot data
|
||||
// run_split state: mode 0 = whole experts, 1 = gate/up row parts, 2 = down row parts
|
||||
int mode_ = 0;
|
||||
int parts_a_ = 1, parts_b_ = 1;
|
||||
struct SplitBuf {
|
||||
alignas(64) float ff[FF];
|
||||
ActQ a2;
|
||||
};
|
||||
std::vector<SplitBuf> split_;
|
||||
// run_split_multi state: mode 3 = gate/up row parts, 4 = down row parts
|
||||
ExpertJobMulti* mjobs_ = nullptr;
|
||||
int64_t mrows_ = 0; // rows of the current multi phase across all its experts (n * FF, then n * H)
|
||||
int mtasks_ = 1; // equal row ranges the phase is cut into
|
||||
struct SplitBufMulti {
|
||||
alignas(64) float ff[MAXT][FF];
|
||||
ActQ a2[MAXT];
|
||||
alignas(64) uint8_t hq[MAXT][kNativeHBytes]; // plan v0.3 P6: native down activations
|
||||
};
|
||||
const NativeFmt* nfmt_ = nullptr;
|
||||
std::vector<SplitBufMulti> split_multi_;
|
||||
PoolAffinity affinity_ = PoolAffinity::All;
|
||||
CpuTopology topo_;
|
||||
};
|
||||
|
||||
} // namespace strata::kernels::cpu
|
||||
@@ -1,61 +0,0 @@
|
||||
// include/strata/kernels/cvec.hpp - a control vector on the residual stream: the engine's side of llama.cpp's
|
||||
// `llama_adapter_cvec` with the `--cvec-mode` / `--cvec-dir` extension of the `experimental-speed-projection`
|
||||
// package (its `02-cvec-projection-mode.patch`, and `01-qwen4exp-cvec-hooks.patch` for WHERE it applies).
|
||||
//
|
||||
// After layer l's FFN write - llama.cpp's `build_cvec(res_hc, il)` right after the layer's second
|
||||
// `build_hc_combine` - every one of the hc residual streams h of every token becomes
|
||||
//
|
||||
// project: h <- h - s_l (h . v_l) v_l v_l = d / |d|, s_l = |d|, d = the scaled direction
|
||||
// add: h <- h + d llama.cpp's stock additive control vector
|
||||
//
|
||||
// for l in [first, last]. `d` is the GGUF's `direction.<src>` times the file's scale (summed over files), with
|
||||
// src = l (per-layer) or one fixed layer (single:L, project mode only), exactly as llama.cpp's loader places it;
|
||||
// layer 0 has no direction. Off unless a vector is loaded (--control-vector-scaled); a loaded one is switched
|
||||
// per request through a device flag, so the captured graphs are the same either way. With the flag off the
|
||||
// result is bit-identical to the engine without a vector: the kernel then only applies the pending residual
|
||||
// write, with the fused read's own arithmetic.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
struct Cvec {
|
||||
const float* dir = nullptr; ///< device, n_layers * n_embd: project = the unit v_l, add = d_l; zero rows elsewhere
|
||||
const float* s = nullptr; ///< device, n_layers: project = s_l, add = 1; 0 = the layer is not steered
|
||||
const int* on = nullptr; ///< device int: 0 = this request runs the stock model
|
||||
int mode = 0; ///< 0 = project, 1 = add
|
||||
int first = 0, last = -1; ///< the steered layers, inclusive
|
||||
int64_t n_embd = 0, hc = 0;
|
||||
bool loaded() const { return dir != nullptr; }
|
||||
/// Layer l's FFN write is followed by the vector (with a real direction there). Decided at load time, never
|
||||
/// per request: it changes where the residual write happens, so the graphs depend on it.
|
||||
bool covers(int64_t l) const { return loaded() && l >= first && l <= last && l < (int64_t) steered.size() && steered[(size_t) l]; }
|
||||
std::vector<bool> steered; ///< host copy of s_l != 0
|
||||
};
|
||||
|
||||
/// The loaded vector (empty until `cvec_upload`).
|
||||
const Cvec& cvec();
|
||||
|
||||
/// Upload a vector built by the loader: `dir` is n_layers * n_embd, `s` n_layers (see `Cvec`). Starts ON.
|
||||
bool cvec_upload(const std::vector<float>& dir, const std::vector<float>& s, int mode, int first, int last,
|
||||
int64_t n_embd, int64_t hc, std::string& err);
|
||||
|
||||
/// A layer split: put the loaded vector's tables on the CURRENT device too (cvec_apply uses the tables of the device
|
||||
/// it runs on). No-op without a vector or when this device has them already.
|
||||
bool cvec_replicate(std::string& err);
|
||||
|
||||
/// The per-request switch, on every device that holds the vector. Synchronizes them when it changes, so call it
|
||||
/// between requests.
|
||||
void cvec_set_enabled(bool on);
|
||||
bool cvec_enabled();
|
||||
|
||||
/// Layer `layer`'s vector on T tokens' residual stacks (`R + t * r_ld`, hc streams of n_embd). With `write`, the
|
||||
/// pending FFN write `R += bo * 2 sigmoid(inj / hc)` (the fused read's arithmetic) is applied first, for callers
|
||||
/// whose writes are folded into the next layer's read; without it, R must already hold the layer's output.
|
||||
void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj,
|
||||
int64_t inj_ld, bool write, void* stream);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -1,27 +0,0 @@
|
||||
// include/strata/kernels/dequant_bf16.hpp - plan v0.3 P5: native GGUF blocks -> BF16 on the device, for the
|
||||
// tensor-core GEMMs of batched prompt processing.
|
||||
//
|
||||
// One thread per 32-element group, transcribed from the reference `dequantize_row_*` functions of the pinned
|
||||
// llama.cpp (`ggml/src/ggml-quants.c`, MIT): Q4_0 (2), Q5_0 (6), Q8_0 (8), Q3_K (11), Q4_K (12), Q5_K (13), Q6_K (14),
|
||||
// IQ4_NL (20), IQ4_XS (23) and Q2_0 (42). A row-major (n_rows, n_cols) tensor of blocks becomes a row-major BF16
|
||||
// matrix; `n_cols` must be a multiple of the type's block size.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
bool dequant_bf16_supported(int ggml_type) noexcept;
|
||||
|
||||
/// `rows` rows of `cols` values starting at block row `row0` (so a caller can dequantize a slice of a tensor).
|
||||
void dequant_bf16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out,
|
||||
void* stream);
|
||||
|
||||
/// The same into FP16 bits (the prompt path's quantized-weight GEMMs: Q2_0 values are exact in FP16).
|
||||
void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out,
|
||||
void* stream);
|
||||
|
||||
/// The same into FP32 (tests and small tensors).
|
||||
void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -1,18 +0,0 @@
|
||||
// include/strata/kernels/dequant_s2.hpp - the S2 decode, host-callable.
|
||||
//
|
||||
// S2 is Q2_0's canonical form and 31.64 GiB of the artifact is Q2_0, so this is the hottest decode in the
|
||||
// engine. Plane layout is docs/pack-format.md's: codes packed 4 per byte LSB-first (element i at byte i/4,
|
||||
// bits (i%4)*2) and one FP32 scale per group of 64. Decode is `(code - 1) * scale` with the subtraction in
|
||||
// the INTEGER domain, which is what makes it bit-exact (docs/pack-format.md §3.1).
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
// Decode `n_blocks` S2 blocks. `codes` is n_blocks*16 bytes, `scales` n_blocks floats, `out` n_blocks*64
|
||||
// floats. All device pointers. Synchronises before returning, so a caller can read `out` immediately -
|
||||
// correctness first; overlap is a Phase 3 concern.
|
||||
void dequant_s2(const uint8_t* codes, const float* scales, float* out, int64_t n_blocks);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -1,45 +0,0 @@
|
||||
// include/strata/kernels/dp4a.hpp - the two instructions the kernels use that Pascal (sm_60) does not have.
|
||||
//
|
||||
// The engine is written for compute capability 7.5 and newer and refuses older cards at CMake configure time
|
||||
// (a Pascal build passes -DSTRATA_EXPERIMENTAL_SM60=ON). A GP100-class card is compute capability 6.0, which is
|
||||
// missing exactly two things the i-quant kernels rely on:
|
||||
//
|
||||
// * `__dp4a`, a byte-wise dot product, available from 6.1 (Pascal GP10x/GV11x). Its fallback below is
|
||||
// llama.cpp's own (`ggml/src/ggml-cuda/common.cuh`), which is the reference for the kernels in this
|
||||
// directory: they are transcribed from llama.cpp's vecdotq.cuh, and that wrapper's operands are the same
|
||||
// sites. It reinterprets the operands as SIGNED bytes and accumulates in int32, which is what `__dp4a`
|
||||
// does for these calls, so the fallback is bit-exact rather than merely close.
|
||||
// * `__nanosleep`, available from 7.0 (Volta). It only paces single-thread doorbell waits, so a loop that
|
||||
// spins without it is correct, merely busier.
|
||||
//
|
||||
// Both are compile-time selections on `__CUDA_ARCH__`, so one source tree builds for Pascal and for RTX
|
||||
// 20/30/40/50 without a #define at the call sites. A HIP build never takes either fallback: `__CUDA_ARCH__` is
|
||||
// undefined there, so `STRATA_DP4A` is `__dp4a` (which `hip_compat/intrinsics.hpp` provides) and the pause is
|
||||
// HIP's own `__nanosleep`.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
#include <cuda_runtime.h> // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a)
|
||||
#endif
|
||||
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610
|
||||
__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) {
|
||||
const int8_t* a8 = (const int8_t*) &a;
|
||||
const int8_t* b8 = (const int8_t*) &b;
|
||||
return c + a8[0] * b8[0] + a8[1] * b8[1] + a8[2] * b8[2] + a8[3] * b8[3];
|
||||
}
|
||||
#define STRATA_DP4A(a, b, c) strata_dp4a((a), (b), (c))
|
||||
#else
|
||||
#define STRATA_DP4A(a, b, c) __dp4a((a), (b), (c))
|
||||
#endif
|
||||
|
||||
/// Yield the thread while a doorbell flag is being polled. The length of the pause is a backoff hint, not a
|
||||
/// contract, and only pre-Volta CUDA has no `__nanosleep` at all.
|
||||
__device__ __forceinline__ void strata_spin_pause() {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 700
|
||||
// sm_6x: the loop spins. Every call site is a single-thread doorbell wait, so nothing else is delayed.
|
||||
#else
|
||||
__nanosleep(100);
|
||||
#endif
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
// include/strata/kernels/elementwise.hpp - the small ops a LAYER needs between its GEMVs, P2.S5.
|
||||
//
|
||||
// These are not interesting kernels and that is why they are in one file with one parity test: they are the
|
||||
// glue in the per-layer graph, and glue that is written inline at each call site is glue with several
|
||||
// slightly different float conventions. Three of them exist because a projection returns a DIFFERENT
|
||||
// quantity from the one the next kernel wants:
|
||||
//
|
||||
// * `gdn_gate` turns (alpha, dt, ssm_a) into the recurrence's `gate`. `ref/gdn.py` L265:
|
||||
// `gate = softplus(w_alpha . x + dt) * ssm_a`, with `softplus(x) = log1p(exp(x))` and the large-x branch
|
||||
// `ggml_compute_softplus_f32` uses. `ssm_a` is NEGATIVE, which is what puts `exp(gate)` in (0,1).
|
||||
// * `scale_inplace` applies the delta net's `1/sqrt(S)` to q. It is a separate op because
|
||||
// `ref/gdn.py` says the two llama.cpp paths apply it in DIFFERENT places, so the caller has to own the
|
||||
// choice rather than have it buried in a kernel.
|
||||
// * `f32_to_f16_bulk` is what lets the f32 arithmetic of the mixer feed the fp16-activation GEMVs.
|
||||
// `docs/activation-contract.md` is explicit that this is NOT the contract for a quantized weight - it is
|
||||
// the bridge between two stages that both already exist, and the contract decision is a separate one.
|
||||
//
|
||||
// `silu_inplace` is here because `shared_expert` has its own copy inline and `gdn` needs one for the conv
|
||||
// output; a third copy would be two too many.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// Decode one canonical embedding row already selected by the caller. Codes are
|
||||
/// packed low bits first (2, 4 or 8 bits); scales/offsets are FP32 per group.
|
||||
/// The optional offset defaults to +0. Multiplication and addition round separately,
|
||||
/// matching the former CPU decoder. Launches asynchronously on the supplied stream.
|
||||
/// The caller validates positive, divisible dimensions and row/plane bounds.
|
||||
void embedding_gather(const uint8_t* codes, const float* scales, const float* offsets,
|
||||
int64_t n, int code_bits, int code_bias, int group_elems,
|
||||
float* out, void* stream);
|
||||
|
||||
/// `y[t][h] = softplus(alpha[t][h] + dt[h]) * ssm_a[h]`, one thread per (t, h). In place is not possible:
|
||||
/// `alpha` is read and `gate` is written, and they are different buffers by construction.
|
||||
///
|
||||
/// `h_v` is the number of v heads (48) and `n_tokens` the leading dimension; the real call is (1, 48).
|
||||
void gdn_gate(const float* alpha, const float* dt, const float* ssm_a, float* gate, int64_t n_tokens,
|
||||
int64_t h_v, void* stream);
|
||||
|
||||
/// `x[i] *= s`, in place.
|
||||
void scale_inplace(float* x, int64_t n, float s, void* stream);
|
||||
/// `dst[i] += src[i]`. **ADDED FOR R4's HIT/MISS SPLIT, WHERE THE TWO HALVES COME FROM DIFFERENT
|
||||
/// ENGINES.** The CPU writes the misses into `parts` and the GPU writes the resident experts into a
|
||||
/// buffer of their own, so that the GPU's work can run CONCURRENTLY with the CPU's instead of after it -
|
||||
/// and the two are summed here, on the stream, immediately before `moe_combine` reads the result.
|
||||
///
|
||||
/// The alternative - having the hit kernel write straight into `parts` - costs the whole overlap, because
|
||||
/// the copy of the misses into `parts` cannot happen until the pool has produced them, and the kernel is
|
||||
/// then ordered behind that copy. Measured: the drain fell 18.2 -> 10.2 ms and the token did not move.
|
||||
void add_inplace(float* dst, const float* src, int64_t n, void* stream);
|
||||
|
||||
/// `y[i] = f16(x[i])`, round-to-nearest-even, using the shared conversion in `f16_bits.hpp`.
|
||||
void f32_to_f16_bulk(const float* x, uint16_t* y, int64_t n, void* stream);
|
||||
|
||||
/// `y[i] = bf16(x[i])`, for the weights whose contract is a bf16 activation - the BF16 `hc_*`, `ssm_alpha`,
|
||||
/// `ssm_beta`, `indexer.*` and `ple_value` tensors.
|
||||
///
|
||||
/// A SEPARATE ENTRY POINT FROM `f32_to_f16_bulk` and not a flag on it, because the two conversions are not
|
||||
/// variants of one idea: fp16 has 5 exponent bits and 10 mantissa bits, bf16 has 8 and 7. A caller that
|
||||
/// picked the wrong one would get a plausible tensor at the wrong precision - 2^-11 against 2^-9, a factor of
|
||||
/// four - and nothing downstream could tell which was intended.
|
||||
void f32_to_bf16_bulk(const float* x, uint16_t* y, int64_t n, void* stream);
|
||||
|
||||
/// `x[i] = x[i] / (1 + exp(-x[i]))`, in place.
|
||||
void silu_inplace(float* x, int64_t n, void* stream);
|
||||
|
||||
/// `build_norm`: `y[r][c] = x[r][c] / sqrt(MEAN_c(x[r]^2) + eps) * w[c]`, over the LAST axis.
|
||||
///
|
||||
/// QSA's norm, used on `attn_q` (24x256), `attn_k` (2x256) and `indexer.q_proj` (4x128). `w` may be null.
|
||||
///
|
||||
/// **IT IS NOT `gdn_l2_norm` AND THE DIFFERENCE IS A FACTOR OF sqrt(cols) = 16 HERE.** `gdn_l2_norm` divides by
|
||||
/// `sqrt(SUM(x^2) + eps)` and applies no weight; this divides by `sqrt(MEAN(x^2) + eps)` and multiplies by `w`.
|
||||
/// Two kernels whose names both say "norm" and whose bodies differ in one `/ cols` is exactly the pair that
|
||||
/// gets swapped, and swapping them produces a well-scaled, plausible tensor - so they are separate entry
|
||||
/// points and the parity test asserts the two readings are OBSERVABLE apart rather than trusting the names.
|
||||
///
|
||||
/// There is NO `(1 + w)` folding: `ref/qsa.py::rms_norm` is `y * w`, and `build_norm` in the source is
|
||||
/// `ggml_rms_norm` followed by a plain multiply. Some norms in this artifact DO fold (the GDN path records
|
||||
/// which); this one does not, and the same `sqrt(cols)`-sized argument applies to getting it wrong.
|
||||
void rms_norm_weighted(float* x, const float* w, int64_t rows, int64_t cols, float eps, void* stream);
|
||||
|
||||
/// *seq = v in MAPPED PINNED memory - THE DOORBELL. A KERNEL and not cudaEventRecord, because round 199
|
||||
/// found that an event record inside a capture is SILENTLY DROPPED while a kernel is captured normally, and
|
||||
/// round 209 measured the host seeing this one's result 0.050 ms into a 39.8 ms graph.
|
||||
///
|
||||
/// It lives here because the caller that needs it - moe_layer - is a HOST translation unit, where
|
||||
/// __global__ and <<<>>> do not exist.
|
||||
/// *seq += 1 - AN INCREMENT, NOT A STORE OF A CALLER-SUPPLIED VALUE. A value passed in is evaluated on the
|
||||
/// HOST at CAPTURE time, so a captured graph would ring the same number on every replay. Reading and
|
||||
/// incrementing in memory is what makes the count advance under cudaGraphLaunch.
|
||||
void doorbell_ring(uint32_t* d_seq, void* stream);
|
||||
|
||||
/// Plan v0.3 P3 token graph: one thread spins until the host-written `*d_flag` equals the ring value `*d_seq`
|
||||
/// (both mapped pinned memory), then fences so everything the host wrote before the flag is visible to the
|
||||
/// nodes that follow. Captured once per layer between `pre[l]` and the parts copy; it is what lets one graph
|
||||
/// hold the whole token (bench/micro/device_wait.cu: 5.2 us per handoff, no driver call).
|
||||
void doorbell_wait(const uint32_t* d_flag, const uint32_t* d_seq, void* stream);
|
||||
|
||||
/// Plan v0.3 P3 token graph: copy `n` floats from MAPPED pinned host memory (`src` is its device pointer) into
|
||||
/// device memory with a kernel, so the handoff stays on the compute queue (a memcpy node is a copy-engine
|
||||
/// operation, which WDDM submits separately and which measured 67 flushes per token).
|
||||
void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream);
|
||||
/// `rows` rows of `width` floats from mapped memory, except the rows listed in hit_rows[0, *count) (device),
|
||||
/// which are written +0.0 instead (a verify window's GPU-computed entries: the pool leaves zeros there).
|
||||
/// multi-GPU: dst[rows[r] * width ..] = src[r * width ..] for r < n (float4; dst may be mapped host memory).
|
||||
void scatter_rows_f32(const float* src, float* dst, const int32_t* rows, int64_t n, int64_t width, void* stream);
|
||||
void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows,
|
||||
const int32_t* count, void* stream);
|
||||
|
||||
/// Plan v0.3 P3: the doorbell's payload and its ring in ONE kernel. Copies `x` (n floats), `ids` and `weights`
|
||||
/// (k each) into the mapped host regions, fences, and increments the mapped sequence number - replacing three
|
||||
/// device-to-host memcpy nodes (copy-engine operations in the middle of the layer chain) and the ring kernel.
|
||||
void doorbell_publish(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out,
|
||||
int32_t* ids_out, float* weights_out, uint32_t* d_seq, void* stream);
|
||||
/// #649 (HIP, STRATA_DOORBELL_STORE=1): the ring stored as `value` instead of incremented over PCIe.
|
||||
void doorbell_publish_value(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k,
|
||||
float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, uint32_t value,
|
||||
void* stream);
|
||||
void doorbell_publish_res(const float* x, const int32_t* ids, const int32_t* d_res, int n_expert, int64_t n, int64_t k,
|
||||
float* x_out, int32_t* ids_out, uint32_t* d_seq, void* stream);
|
||||
|
||||
/// Plan v0.3 P3: copy `n` int32 from mapped pinned host memory into device memory with a kernel (the QSA
|
||||
/// per-token step and positions), instead of a host-to-device memcpy node in the middle of a layer.
|
||||
void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -1,104 +0,0 @@
|
||||
// include/strata/kernels/f16_bits.hpp - the fp16 conversions, written out, as bits.
|
||||
//
|
||||
// WHY THIS IS NOT `__float2half`. Round 193 found `__float2half` producing 0x2600 for a value whose correct
|
||||
// fp16 encoding is 0x26DB, and 0x3C01 for a value that is exactly 1.0 - i.e. wrong bits, not a rounding
|
||||
// difference. The cause was never isolated (it is either `__float2half` itself or `__half_as_ushort`), so
|
||||
// `src/kernels/cuda/quantize_act.cu` replaced it with the version below, which then came out byte-exact over
|
||||
// all 20,480 blocks of the fixture. `shared_expert.cu` carries the same function privately for the same
|
||||
// reason. Three copies of a converter whose failure mode is silent wrong bits is two copies too many, so the
|
||||
// copy lives here and the kernel and its TEST both include it - with the test checking it against vectors
|
||||
// generated by numpy's float16 (an oracle that shares no code with this), which is what neither private copy
|
||||
// had.
|
||||
//
|
||||
// The rounding is ROUND-TO-NEAREST-EVEN, which is what numpy's `.astype(np.float16)` does and what IEEE-754
|
||||
// specifies for the default mode. The three interesting regimes are all handled explicitly and all three are
|
||||
// covered by the test's oracle vectors:
|
||||
//
|
||||
// * normal - exponent fits, mantissa is rounded from 13 surviving bits with a sticky remainder
|
||||
// * subnormal - the implicit 1 is restored and the result is shifted right, so the rounding point MOVES
|
||||
// * overflow - exp >= 31 saturates to inf (0x7C00) and keeps the sign; a NaN input stays a NaN
|
||||
//
|
||||
// `f32_from_f16` deliberately does NOT round: it is used to compare against a reference that holds the same
|
||||
// bits, so it only has to be exact.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#if defined(__CUDACC__) || defined(__HIPCC__)
|
||||
#define STRATA_HD __host__ __device__
|
||||
#else
|
||||
#define STRATA_HD
|
||||
#endif
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// Round-to-nearest-even f32 -> fp16, returned as raw bits.
|
||||
STRATA_HD inline uint16_t f16_from_f32(float f) {
|
||||
uint32_t x;
|
||||
#if defined(__HIP_DEVICE_COMPILE__)
|
||||
__builtin_memcpy(&x, &f, 4);
|
||||
#else
|
||||
std::memcpy(&x, &f, 4);
|
||||
#endif
|
||||
const uint32_t sign = (x >> 16) & 0x8000u;
|
||||
const uint32_t rawexp = (x >> 23) & 0xFFu;
|
||||
int exp = (int) rawexp - 127 + 15;
|
||||
uint32_t man = x & 0x7FFFFFu;
|
||||
// TWO different things reach here and they must not be conflated: an f32 inf/NaN (raw exponent 255) stays
|
||||
// an inf/NaN, and a FINITE value too large for fp16 (1e30) SATURATES TO INF. The version of this function
|
||||
// in quantize_act.cu and shared_expert.cu tests `if (exp >= 31) return sign | 0x7C00 | (man ? 0x200 : 0)`
|
||||
// and therefore returns a NaN for every overflowing finite value - which their own fixtures cannot see,
|
||||
// because all of their values are O(1). Round 198's numpy oracle caught it here on the first run (1e30,
|
||||
// 65536, 1e45: numpy says inf, the conflated test said NaN).
|
||||
if (rawexp == 0xFFu) return (uint16_t) (sign | 0x7C00u | (man ? 0x200u : 0u)); // inf, or a quiet/NaN
|
||||
if (exp >= 31) return (uint16_t) (sign | 0x7C00u); // finite overflow -> inf
|
||||
if (exp <= 0) {
|
||||
if (exp < -10) return (uint16_t) sign; // underflows to a signed zero
|
||||
man |= 0x800000u; // restore the implicit 1
|
||||
const uint32_t sh = (uint32_t) (14 - exp);
|
||||
uint32_t h = (man >> sh) & 0x3FFu;
|
||||
const uint32_t rem = man & ((1u << sh) - 1u);
|
||||
if (rem > (1u << (sh - 1)) || (rem == (1u << (sh - 1)) && (h & 1u))) ++h;
|
||||
return (uint16_t) (sign | h);
|
||||
}
|
||||
uint16_t h = (uint16_t) (sign | ((uint32_t) exp << 10) | (man >> 13));
|
||||
const uint32_t rem = man & 0x1FFFu;
|
||||
if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h; // the carry may bump the exponent
|
||||
return h;
|
||||
}
|
||||
|
||||
/// Exact fp16 bits -> f32. No rounding, no exceptions: every one of the 65,536 inputs maps to a value f32
|
||||
/// represents exactly, including the subnormals (which is why the `ex == 0` case cannot be skipped).
|
||||
STRATA_HD inline float f32_from_f16(uint16_t h) {
|
||||
const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
|
||||
const uint32_t ex = (h >> 10) & 0x1Fu, man = h & 0x3FFu;
|
||||
uint32_t out;
|
||||
if (ex == 0) {
|
||||
// Subnormal or zero. The value is `man * 2^-24`, so after `s` left shifts the leading 1 reaches bit
|
||||
// 10 and the value is `(1 + frac) * 2^(-14-s)`: the f32 exponent field is 113 - s and `frac` is the low
|
||||
// ten bits. Flushing these to zero - which the two private copies of this function in the tree do -
|
||||
// maps 0x0001 to 0.0 instead of 2^-24, a 100% relative error on any KL-quant scale that lands here.
|
||||
if (man == 0) {
|
||||
out = sign;
|
||||
} else {
|
||||
uint32_t m = man;
|
||||
int s = 0;
|
||||
while ((m & 0x400u) == 0) { m <<= 1; ++s; }
|
||||
out = sign | ((uint32_t) (113 - s) << 23) | ((m & 0x3FFu) << 13);
|
||||
}
|
||||
} else if (ex == 31) {
|
||||
out = sign | 0x7F800000u | (man << 13);
|
||||
} else {
|
||||
out = sign | ((ex - 15 + 127) << 23) | (man << 13);
|
||||
}
|
||||
float f;
|
||||
#if defined(__HIP_DEVICE_COMPILE__)
|
||||
__builtin_memcpy(&f, &out, 4);
|
||||
#else
|
||||
std::memcpy(&f, &out, 4);
|
||||
#endif
|
||||
return f;
|
||||
}
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -1,40 +0,0 @@
|
||||
// include/strata/kernels/fused_gdn.hpp - plan v0.3 P3: the gated delta-net step and its output norm in ONE kernel.
|
||||
//
|
||||
// The native step (after llama.cpp's gated_delta_net.cu) gives each warp one (head, column) and strides its 32
|
||||
// lanes over the 128 ROWS of the state, which is stored `[row][head][col]`: every lane's load is 24.5 KB from its
|
||||
// neighbour's, so each 32 B sector delivers 4 useful bytes - 47.6 us per layer for 6.3 MB of state traffic. Here a
|
||||
// block owns one whole head, its 512 threads are (row group of 32, column), and a row's 128 columns are one
|
||||
// contiguous 512 B load. With the head in one block, the per-head RMS norm, the norm weight and the sigmoid(z)
|
||||
// gate of `gdn_out_norm` run in the same kernel.
|
||||
//
|
||||
// S <- g S + k (beta (v - g S^T k))^T (g = exp(gate[head]), per value head; q/k shared by h_v / h_k heads)
|
||||
// o = (S^T q) / sqrt(128)
|
||||
// y = rmsnorm(o) * gamma * act(z) (act = sigmoid for Flash-Next, SiLU for Qwen3.6: `GdnGate`, gdn.hpp)
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/gdn.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// The 4-tap causal conv + SiLU over all `channels` (history is `[channel][3]`, updated), then the L2 norm of
|
||||
/// each of the first `qk_heads` 128-channel heads (q then k), eps as the native `l2_norm` (x / sqrt(sum + eps)).
|
||||
/// One block per 128-channel head; replaces conv_silu + two l2_norm launches.
|
||||
void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads,
|
||||
float eps, void* stream);
|
||||
|
||||
/// alpha and beta, both `(h_v, n_embd)` BF16 against the FP32 activation, with their epilogues:
|
||||
/// gate = softplus(alpha + dt) * ssm_a, beta = sigmoid(beta). One warp per row; replaces two MMVF launches and
|
||||
/// two elementwise kernels.
|
||||
void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
|
||||
float* gate, float* beta, int n_embd, int h_v, void* stream);
|
||||
|
||||
/// The step and the output norm in one kernel: state (S, h_v, S) in place, q/k (h_k, 128) L2-normalised and NOT
|
||||
/// pre-scaled (the 1/sqrt(S) goes on the readout), v/z/y (h_v, 128), gate/beta (h_v), gamma (128). `act` is the
|
||||
/// model's output gate (`GdnGate`); `h_v % h_k == 0`, any h_v (Flash-Next 48, Qwen3.6 32).
|
||||
void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate,
|
||||
const float* beta, const float* z, const float* gamma, float eps, GdnGate act, float* y,
|
||||
int h_k, int h_v, void* stream);
|
||||
|
||||
} // namespace strata::kernels
|
||||
Loaded 100 of 397 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user