diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6c97c14b..4434d766 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,5 +1,5 @@ # Builds Linux and Windows binaries when a version tag (v1.2.0, ...) is pushed and attaches them to a draft release, -# which is published by hand. CUDA kernels compile at run time through NVRTC and the Vulkan shaders are committed, +# which is published by hand. After both binaries are up, the crate goes to crates.io (CARGO_REGISTRY_TOKEN). CUDA kernels compile at run time through NVRTC and the Vulkan shaders are committed, # so the build needs neither the CUDA toolkit nor a Vulkan SDK. name: release on: @@ -47,3 +47,20 @@ jobs: cp target/release/${{ matrix.bin }} ${{ matrix.asset }} gh release upload "$GITHUB_REF_NAME" ${{ matrix.asset }} --repo "$GITHUB_REPOSITORY" shell: bash + crate: + needs: build + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - run: rustup update stable + # The verify build runs dependency build scripts, so it has no token; the upload step compiles nothing. + - run: cargo package --locked + env: + RUSTFLAGS: -C target-cpu=x86-64-v3 + - env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + run: cargo publish --locked --no-verify diff --git a/.gitignore b/.gitignore index 2a9851e0..d313d735 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ /target +/.omp /.claude/ /AGENTS.md /CLAUDE.md diff --git a/Cargo.lock b/Cargo.lock index edc681e6..454663e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -192,6 +192,17 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "crc32fast" version = "1.5.5" @@ -313,6 +324,12 @@ version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + [[package]] name = "esaxx-rs" version = "0.1.10" @@ -427,6 +444,17 @@ dependencies = [ "quick-error", ] +[[package]] +name = "indicatif" +version = "0.18.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c" +dependencies = [ + "console", + "portable-atomic", + "unit-prefix", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -674,6 +702,12 @@ dependencies = [ "miniz_oxide 0.8.9", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -819,15 +853,17 @@ dependencies = [ [[package]] name = "rusting_strata" -version = "1.3.0" +version = "1.5.2" dependencies = [ "anyhow", "ash", "base64 0.22.1", "clap", + "console", "cudarc", "half", "image", + "indicatif", "libloading 0.9.0", "memmap2", "rayon", @@ -1057,6 +1093,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" +[[package]] +name = "unit-prefix" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" + [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 2a377dae..45174620 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,8 +1,19 @@ [package] name = "rusting_strata" -version = "1.3.0" +version = "1.5.2" edition = "2024" license-file = "LICENSE.md" +description = "Pure-Rust GGUF inference engine for MoE models that do not fit in VRAM (CUDA via NVRTC, Vulkan, HIP)" +repository = "https://github.com/RustingStudio/RustingStrata" +readme = "README.md" +keywords = ["llm", "gguf", "inference", "cuda", "vulkan"] +categories = ["science", "command-line-utilities"] +# CI files and the local-CPU build flag stay out of the crate (cargo install from crates.io ignores the latter anyway). +exclude = [".github/", ".cargo/", ".dockerignore"] + +[package.metadata.binstall] +pkg-url = "{ repo }/releases/download/v{ version }/{ name }-{ os-name }-{ target-arch }{ binary-ext }" +pkg-fmt = "bin" [[bin]] name = "rustingstrata" @@ -24,6 +35,8 @@ ash = "0.38" ureq = { version = "3", default-features = false, features = ["rustls"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } base64 = "0.22" +indicatif = { version = "0.18.6", default-features = false } +console = { version = "0.16.6", default-features = false, features = ["std"] } [profile.release] opt-level = 3 diff --git a/README.md b/README.md index 02465a2e..75ee1e63 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,15 @@ [![Reviewed by Aletheore](https://img.shields.io/badge/Reviewed%20by-Aletheore-16140F)](https://aletheore.com) -A pure-Rust inference engine for GGUF models, built for MoE models that do not fit in VRAM. The CUDA kernels are -compiled at run time with NVRTC, and the same kernels run on Vulkan: no C++ build step, no ggml. Experts that do not -fit in VRAM run on the CPU at the same time as the GPU work, and the expert placement adapts to the routing it sees. +RustingStrata is a pure-Rust inference engine for GGUF models, built for MoE models that do not fit in VRAM. Experts +that do not fit in VRAM run on the CPU at the same time as the GPU work. It runs on CUDA and Vulkan with no C++ build +step and no ggml, and it has a chat page and an OpenAI-compatible server. -Supported models: Qwen3, Qwen3-Next, Qwen3.5/3.6, Qwen3.8-Flash-Next, Recursive Flint, Gemma 4, DeepSeek-V4.1-Flash, -GLM-5.3-Flash, Hy4-flash and Inkling 2 Mini. The architectures, the GGUF types and the notes for each model are in -[docs/MODELS.md](docs/MODELS.md). +Supported models: Qwen3, Qwen3-Next, Qwen3.5/3.6, Qwen3.8-Flash-Next, Qwen4-35B-A3B, Recursive Flint, Gemma 4, +DeepSeek-V4.1-Flash, GLM-5.3-Flash, Hy4-flash, Inkling 2 Mini, Kolibri 1.1, GigaChat 4 and Ternary Bonsai 2. The GGUF +types and the notes for each model are in [docs/MODELS.md](docs/MODELS.md). -Version 1.3.0. +Version 1.5.2. ## Numbers @@ -24,80 +24,144 @@ file. Neither file fits in VRAM. | UD-Q2_K_XL (11.7 GiB), decode after a 4K prompt | **113.4 tok/s** | 66.5 | | UD-Q2_K_XL, prefill of a 4K prompt | 2216 tok/s | ~2236 | -The method, the ranges, Vulkan, the other models and the quality checks are in -[docs/BENCHMARKS.md](docs/BENCHMARKS.md). +### Many users at once + +`serve --parallel N` decodes the requests together in one batched forward (CUDA). The table is total decode tok/s on +the same machine. The load script is `tools/loadtest.py`: N streamed chats at once, 128 reply tokens each, greedy. + +| Clients | Qwen3-4B, RustingStrata (Q4_K_M) | Qwen3-4B, vLLM 0.33 (bf16) | Qwen3.6-35B-A3B UD-Q5_K_M, RustingStrata | +|---:|---:|---:|---:| +| 1 | 91.3 | 36.7 | 49.0 | +| 4 | 228.1 | 139.9 | 88.9 | +| 16 | 799.0 | 520.1 | 100.7 | +| 64 | 1698 | 1688-1765 | 129.3 | + +- vLLM runs bf16 weights and RustingStrata runs Q4_K_M, so the Qwen3-4B columns are not like for like. +- The 27 GB MoE file does not fit on the 12 GB card, so vLLM was not run on it. +- The MoE column moves by about 30% between runs on this machine. + +The method, Vulkan, the other models and the quality checks are in [docs/BENCHMARKS.md](docs/BENCHMARKS.md). ## Install -Download a binary for Linux or Windows from the [releases page](https://github.com/RustingStudio/RustingStrata/releases), -or build it (Rust 2024 edition; on Windows install the Visual Studio C++ Build Tools first): +```powershell +# Windows: installs to %LOCALAPPDATA%\Programs\RustingStrata, adds it to PATH, makes a Start menu entry +irm https://raw.githubusercontent.com/RustingStudio/RustingStrata/main/install.ps1 | iex +``` + +```bash +# Linux x86_64: installs to ~/.local/bin +curl -fsSL https://raw.githubusercontent.com/RustingStudio/RustingStrata/main/install.sh | sh -```sh +# Arch Linux (AUR) +yay -S rustingstrata-bin + +# From source (Rust 2024 edition; on Windows install the Visual Studio C++ Build Tools first) cargo build --release # the binary is target/release/rustingstrata ``` -A GPU run needs one of: +Binaries are also on the [releases page](https://github.com/RustingStudio/RustingStrata/releases). + +`rustingstrata update` replaces the binary with the newest release. `rustingstrata update --check` only says whether +one is out, and `serve` prints a line at start when one is. A binary from a package manager (the AUR package) is +updated with that package manager. + +### GPU requirements + +`--gpu` picks CUDA when it loads, else Vulkan. `--backend cuda`, `--backend vulkan` or `--backend hip` chooses one. + +| Backend | Needs | +|---|---| +| CUDA | An NVIDIA driver with the CUDA NVRTC library. Volta (sm_70), Turing (sm_75) and Ampere or newer (sm_80+). | +| Vulkan | A Vulkan 1.3 driver with shaderFloat64, int8/16/64 and subgroup size 32 or a fixed 64. | +| HIP | A ROCm runtime with hiprtc (`libamdhip64.so`, `libhiprtc.so`). Experimental: see [docs/HIP.md](docs/HIP.md). | + +- The first CUDA run compiles the kernels (~15 s) and caches them. HIP compiles for the card's `gfx` target on first + use. +- CUDA 13 dropped Volta, so a V100 needs the 12.x toolkit. Pascal and older cards use Vulkan. +- NVRTC is found by name: `libnvrtc.so`, or `nvrtc64_130_0.dll` or `nvrtc64_120_0.dll` on Windows (on `PATH` or + under `%CUDA_PATH%\bin`). `STRATA_NVRTC` names another file. Without NVRTC the run falls back to Vulkan. +- A Vulkan driver without one of the features is refused at start, with the list of what it lacks. +- A user runs Inkling 2 Mini on an Intel Arc B580 with Vulkan. + +Every GPU tried so far is in [docs/SUPPORTED_GPUS.md](docs/SUPPORTED_GPUS.md). + +### Uninstall + +Delete the binary and the data folders. The models folder can be large: keep it if other tools use the files. + +```bash +rm ~/.local/bin/rustingstrata # AUR: yay -R rustingstrata-bin +rm -r ~/.cache/rusting_strata # kernels, calibration, expert profiles +rm -r ~/.local/share/rusting_strata # downloaded models, usage stats +``` + +Windows (PowerShell): -- an NVIDIA driver with the CUDA NVRTC library (loaded at run time). Volta (sm_70), Turing (sm_75) and Ampere or newer - (sm_80+) work; CUDA 13 dropped Volta, so a V100 needs the 12.x toolkit. Pascal and older use Vulkan. - The library is found by name (`libnvrtc.so`; on Windows `nvrtc64_130_0.dll` or `nvrtc64_120_0.dll`, on `PATH` or - under `%CUDA_PATH%\bin`); `STRATA_NVRTC` names another file. Without it the run falls back to Vulkan. -- a Vulkan 1.3 driver with shaderFloat64, int8/16/64 and subgroup size 32 or a fixed 64 (tested on RTX 3060, Radeon VII - and V100; Intel Arc lacks shaderFloat64). +```powershell +Remove-Item -Recurse "$env:LOCALAPPDATA\Programs\RustingStrata", "$env:LOCALAPPDATA\rusting_strata" +Remove-Item "$([Environment]::GetFolderPath('Programs'))\RustingStrata.lnk" +$d = "$env:LOCALAPPDATA\Programs\RustingStrata" +[Environment]::SetEnvironmentVariable('Path', ((([Environment]::GetEnvironmentVariable('Path','User')) -split ';') -ne $d) -join ';', 'User') +``` -`--gpu` picks CUDA when it loads, else Vulkan; `--backend` chooses. The first CUDA run compiles the kernels (~15 s) and -caches them. Every GPU tried so far is in [docs/SUPPORTED_GPUS.md](docs/SUPPORTED_GPUS.md). +`XDG_CACHE_HOME`, `XDG_DATA_HOME` and `--models-dir` move these folders: delete them where you pointed them. Models +that the chat page found in the Hugging Face or llama.cpp cache stay there. ## Quick start -Run `rustingstrata` with no arguments (double-click `rustingstrata.exe` on Windows). It starts a server on -http://127.0.0.1:8080 and opens a chat page that downloads models from Hugging Face and switches between the ones in -your models folder. Any app that takes an OpenAI-compatible address (Open WebUI, Jan, SillyTavern, code editors) can -use `http://127.0.0.1:8080/v1`. +Run `rustingstrata` with no arguments, or double-click `rustingstrata.exe` on Windows. It starts a server on +http://127.0.0.1:8080 and opens the chat page. The chat page downloads models from Hugging Face and switches between +the models in your models folder. + +Any app that takes an OpenAI-compatible address can use `http://127.0.0.1:8080/v1` (Open WebUI, Jan, SillyTavern, +code editors). -`rustingstrata interface` asks for the model, the mode (terminal chat, chat page, API server, speed test), GPU or CPU, -the context length and the address, prints the command these make and runs it. +`rustingstrata interface` asks a few questions in the terminal, prints the command they make and runs it. With flags: -```sh +```bash M=path/to/model.gguf -rustingstrata calibrate --model $M # once per model and machine: best chunk size, MTP drafts -rustingstrata chat --model $M --gpu # --think for thinking mode, --temp 0.7 to sample +rustingstrata serve --gpu --open # the chat page; it downloads models +rustingstrata calibrate --model $M --dry-run # preview what calibrate will measure +rustingstrata calibrate --model $M # once per model and machine: finds the fastest settings +rustingstrata chat --model $M --gpu # --think false turns thinking off, --temp 0.7 samples rustingstrata generate --model $M --gpu --prompt "Write a haiku about rivers." -n 128 rustingstrata serve --model $M --gpu --addr 127.0.0.1:8080 +rustingstrata serve --model $M --gpu --pretty --graph --status-interval 250ms # live metrics and speed graphs rustingstrata bench --model $M --gpu --pp 512,4096 --tg 128 ``` -Without `--gpu` the model runs on the CPU reference, which is slow and meant for checking. DeepSeek, GLM, Hy4 and -Inkling 2 open the GPU by themselves. +Without `--gpu` the model runs on the CPU reference, which is slow and meant for checking. On a machine without a +usable GPU, use `--fast-cpu`. DeepSeek, GLM, Hy4 and Inkling 2 open the GPU by themselves. ## Docs -- [USAGE.md](docs/USAGE.md): flags, the chat page and MCP tools, the OpenAI and Anthropic APIs, prompt caching, - several GPUs. -- [MODELS.md](docs/MODELS.md): supported architectures and GGUF types, notes and caveats for each model. -- [BENCHMARKS.md](docs/BENCHMARKS.md): every model against llama.cpp; older runs are in the - [benchmark history](docs/README.md#benchmark-history). +- [USAGE.md](docs/USAGE.md): every command and flag, the chat page, the server API, prompt caching, several GPUs. +- [MODELS.md](docs/MODELS.md): supported models and GGUF types, and the notes for each model. - [HOSTING.md](docs/HOSTING.md): running a server for other people. -- [SUPPORTED_GPUS.md](docs/SUPPORTED_GPUS.md) and [AMD.md](docs/AMD.md): the GPUs tried so far and AMD notes. +- [CALIBRATION.md](docs/CALIBRATION.md): `rustingstrata calibrate` and the file it writes. +- [BENCHMARKS.md](docs/BENCHMARKS.md): every model against llama.cpp. Older runs are in the + [benchmark history](docs/README.md#benchmark-history). +- [SUPPORTED_GPUS.md](docs/SUPPORTED_GPUS.md), [AMD.md](docs/AMD.md), [HIP.md](docs/HIP.md): the GPUs tried so far, + AMD notes, the HIP backend. - [VISION.md](docs/VISION.md): image input. [LORA.md](docs/LORA.md): LoRA adapters. +- [ROADMAP.md](ROADMAP.md): what is planned. Ideas from users are welcome. ## Development -```sh -cargo test --release # GPU tests need the model: STRATA_MODEL=path/to/model.gguf +```bash +cargo build --release +cargo test --release # GPU tests need the model: STRATA_MODEL=path/to/model.gguf python -I tools/parity.py $M --extra "--gpu" --tag gpu # agreement with llama.cpp (needs llama-server once) ``` CI only builds, so run the tests before a pull request. -Source map: `src/gguf.rs` (file reader), `src/quant/` (dequantization), `src/model.rs` (CPU reference forward), -`src/cuda/` and `src/vulkan/` (GPU kernels, behind `src/backend.rs`), `src/gpu_model.rs` (GPU forward), -`src/expert_cache.rs` (expert placement), `src/deepseek/`, `src/glm/`, `src/hy4/`, `src/inkling2/` and `src/gemma4/` -(the models with their own forward), `src/serve.rs` (HTTP), `src/chat.rs` (chat templates and tool calls), -`src/main.rs` (CLI). +The command line is in `src/main.rs`, the HTTP server in `src/serve.rs`, the CPU reference forward in `src/model.rs` +and the GPU forward in `src/gpu_model.rs`. The GPU backends are `src/cuda/`, `src/vulkan/` and `src/hip/`. ## License diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 00000000..186ca05c --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,40 @@ +# Roadmap + +Everything here is planned. New architectures and new models come first: when a new model comes out, it is supported +before work returns to this list. + +Ideas from users are welcome. Open an issue, or comment on one, to suggest an item or to move one up. + +Every change keeps single-user greedy output unchanged by default. It must match llama.cpp in `tools/parity.py` +before it ships. + +## Serving + +- Serving many users with MoE models on a machine with a lot of RAM and little VRAM. Continuous batching reads the + experts of a step once for all requests. Single-request speed must not drop. +- Automatic shared prefix caching. Requests that start with the same tokens (a system prompt, a tool list, a long + document) reuse one KV prefix. +- Tensor parallelism: split one model across GPUs by tensor, not only by layer. +- Multi-node serving: run one model across more than one machine. + +## Performance + +- Faster prefill on a small card with the experts in RAM. Prefill is the slowest part on low-end hardware. +- Inkling 2: faster prefill and decode, and less VRAM. +- Vulkan as fast as CUDA on the same card, for every supported model. Today Vulkan is clearly slower. +- Faster cold start from disk when a model is larger than both VRAM and RAM. + +## Backends + +- Apple Silicon: a Metal backend for M-series Macs with unified memory. + +## Features + +- Better MCP support in the chat page and the server. +- Embedding and rerank pipelines with OpenAI-compatible endpoints. +- More modalities beyond the current image input. + +## Model formats + +- Load Hugging Face Safetensors directly. Today the main models load only from GGUF. +- Load the common quantized formats: FP8, AWQ, GPTQ and EXL2. diff --git a/THANKS.md b/THANKS.md index 774f2cf7..6455110f 100644 --- a/THANKS.md +++ b/THANKS.md @@ -41,6 +41,11 @@ If you helped and your name is missing here, that is our mistake. Open an issue - [luckydevil13](https://github.com/luckydevil13): AMD benchmarks and a lot of talk about which models to support. - [ike287](https://github.com/ike287): feedback and feature requests. +## Code + +- [Niko1221](https://github.com/Niko1221/Strata): the HIP backend's device-side compatibility layer (`src/hip/compat.h`) + follows the structure and several implementations of Strata's `include/strata/hip_compat/intrinsics.hpp` (MIT). + ## Ideas - [FredWalter](https://github.com/FredWalter): asked for multi-GPU and Qwen3.8-Flash-Next (issue #1), and later diff --git a/docs/AMD.md b/docs/AMD.md index db93aa8c..ddb4a77e 100644 --- a/docs/AMD.md +++ b/docs/AMD.md @@ -1,73 +1,78 @@ # AMD GPUs -All benchmarks in the README were run on an NVIDIA RTX 3060. AMD GPUs run the Vulkan backend -(`--backend vulkan`), and everything known about them comes from user reports (RX 9070 XT on Linux with RADV, and on -Windows with AMD's driver). Expect problems; this page lists the known ones and what to send when you hit a new one. +An AMD card runs on Vulkan or on HIP. Without `--backend`, a machine without CUDA opens Vulkan. -Needs a Vulkan 1.3 driver and subgroup size 32 or a fixed subgroup size 64. The wave64 path has been tested on -Radeon VII (Vega 20) with RADV Mesa 26.0.8. It runs the same int8 kernels as wave32: each 64-lane subgroup is split -into two logical 32-lane warps. The optimized batched-prefill path can differ from token-by-token inference at near -ties; `--chunk 0` uses token-by-token prefill when closer agreement with the CPU reference matters more than prompt -processing speed. +| Backend | Flags | Needs | +|---|---|---| +| Vulkan | `--gpu --backend vulkan` | Vulkan 1.3 driver, subgroup size 32 or a fixed subgroup size 64 | +| HIP (experimental) | `--gpu --backend hip` | ROCm and an RDNA card. See [HIP.md](HIP.md). | -## First line of the output +Vulkan on AMD is known from user reports only: RX 9070 XT on Linux with RADV, and on Windows with AMD's driver. The +wave64 path was tested on Radeon VII (Vega 20) with RADV Mesa 26.0.8. Expect problems. Tested cards are in +[SUPPORTED_GPUS.md](SUPPORTED_GPUS.md). The README benchmarks are from an NVIDIA RTX 3060. -Every run on Vulkan starts with a line like: +`--chunk 0` prefills token by token. It is slower, and agrees more closely with the CPU reference at near ties. + +## What the driver offers + +`STRATA_VERBOSE=1` prints one line with what the driver has: ``` vulkan: AMD Radeon RX 9070 XT (radv Mesa 26.2.5), device-coherent memory yes, cooperative matrix f16 yes int8 no, conditional rendering yes ``` -- `device-coherent memory` must be `yes` for models whose experts do not all fit in VRAM (see below). -- `cooperative matrix` speeds up prefill. `int8 no` is normal on RDNA. Without it, prefill attention uses a - shared-memory tiled fallback; the `_dp` GEMM kernels still run without tensor cores. -- `conditional rendering` lets decode recover when the CPU expert worker is slow. With `no`, a slow worker is an error. - -## Known issues - -**Slow decode with experts on the CPU, and "GPU waits for the CPU expert worker that timed out and resumed: N".** -While the CPU computes the experts that are not in VRAM, the GPU polls a small mailbox buffer for the answer. On AMD the -GPU caches that buffer unless it comes from device-coherent memory (`VK_AMD_device_coherent_memory`), and then it misses -the answer and waits until it gives up. RADV hides the extension on RDNA4 (RX 9000) unless the driconf option -`radv_device_coherent_memory` is set. RustingStrata sets it before it opens Vulkan (unless you set it yourself) and prints a -warning when an AMD GPU still has no device-coherent memory. If the first line says `device-coherent memory no`, send -the output of `vulkaninfo | grep -i coherent`. A few resumed waits on a busy CPU are normal; hundreds are not. - -**The GPU resets during a long prefill.** amdgpu resets a submission that runs for more than 10 s. Prefill submits -each layer separately, and attention within a chunk is split into smaller submits once its query-key work passes a -budget (`STRATA_VK_ATTN_BUDGET`, query-key pairs per slice, 0 turns slicing off). The default is 268435456 with -cooperative matrices and 33554432 without them (RDNA2 and older: the startup line says `prefill attention: tiled`), -where a pair costs about 8 times more. If it still happens, set a smaller budget (halve it) or try a smaller `--chunk`. +- `device-coherent memory` must be `yes` when not all experts fit in VRAM. +- `cooperative matrix` speeds up prefill. `int8 no` is normal on RDNA. +- `conditional rendering`: with `no`, a slow CPU expert worker is an error. -**"the forward pass produced NaN or infinite logits".** Seen once on Qwen3-Next 80B with a 15K prompt. Rerun with -`STRATA_NAN_TRACE=1`, which prints per-layer magnitudes and the first layer with a non-finite value, and attach the -output. +Current builds add `int8 dot product` and `maxComputeSharedMemorySize` to the line. -**A model split over two cards (`--device 0,1`) is slower than expected.** Each card waits while the other works, and -amdgpu clocks it down in those gaps. `echo high > /sys/class/drm/cardN/device/power_dpm_force_performance_level` (as -root, for each card; `auto` restores the default) keeps the clocks up: 44 to 57 tok/s decode in one two-card report. -The per-device times that `generate` prints on a split show whether a card is slow. +## Known issues -**Load fails for lack of VRAM.** The desktop on the same card takes memory, and the driver's free-memory estimate can -be more than it will allocate. Lower `--ctx`, use `--kv q8`, or a smaller `--chunk`. +| Symptom | What to do | +|---|---| +| Slow decode with experts on the CPU, and hundreds of `worker stalls` at the end of the run | Look for the `no VK_AMD_device_coherent_memory` warning at start. A few stalls on a busy CPU are normal. | +| The GPU resets during a long prefill | Halve `STRATA_VK_ATTN_BUDGET`, or lower `--chunk`. amdgpu resets a job that runs for more than 10 s. | +| `the forward pass produced NaN or infinite logits` | Rerun with `STRATA_NAN_TRACE=1` and attach the output. Seen once on Qwen3-Next 80B with a 15K prompt. | +| A split over two cards (`--device 0,1`) is slower than expected | amdgpu clocks a waiting card down. The command below took one report from 44 to 57 tok/s decode. | +| Load fails for lack of VRAM | Lower `--ctx`, use `--kv q8`, or lower `--chunk`. | + +```bash +# "device-coherent memory no": send this output +vulkaninfo | grep -i coherent +# two cards: as root, for each card ("auto" restores the default) +echo high > /sys/class/drm/cardN/device/power_dpm_force_performance_level +``` ## Switches for testing -Environment variables; set any of them to turn the feature off: - -- `STRATA_VK_NO_COOP`: no cooperative matrices. -- `STRATA_VK_ATTN_BUDGET=N`: query-key pairs of prefill attention per submit (default 268435456 with cooperative matrices, 33554432 without; 0 disables slicing). -- `STRATA_VK_DP_OLD`: use the old per-query prefill attention fallback instead of the tiled one (A/B and rollback). -- `STRATA_VK_NO_COND`: no conditional rendering. -- `STRATA_VK_NO_TQ`: no separate transfer queue for expert uploads. -- `STRATA_VK_SMEM_LIMIT=49152`: treat the device as allowing this much workgroup shared memory. The AMD proprietary driver reports 32768 on an RX 9070 XT although the card has 64 KB; RustingStrata raises that to 49152 itself on RDNA3/4 cards with this driver (no kernel needs more). For any other card that reports too little, set it by hand. Do not set it above what the card really has (issue #20). -- `radv_device_coherent_memory=false`: undo the RADV option RustingStrata sets. - -If one of these makes a problem go away, say which one in the report. +Environment variables. If one of them makes a problem go away, say which one in the issue. + +| Variable | What it does | +|---|---| +| `STRATA_VK_NO_COOP` | No cooperative matrices. | +| `STRATA_VK_ATTN_BUDGET=N` | Query-key pairs of prefill attention per submit. Default 268435456 with cooperative matrices, 33554432 without. `0` turns slicing off. | +| `STRATA_VK_DP_OLD` | The old per-query prefill attention fallback instead of the tiled one. | +| `STRATA_VK_NO_COND` | No conditional rendering. | +| `STRATA_VK_DP4=0` or `1` | Float GEMM (`0`) or int8 dot-product GEMM (`1`) on a card without int8 cooperative matrices. | +| `STRATA_VK_NO_TQ` | No separate transfer queue for expert uploads. | +| `STRATA_VK_SMEM_LIMIT=49152` | Treats the device as allowing this much workgroup shared memory. | +| `radv_device_coherent_memory=false` | Undoes the RADV option RustingStrata sets. RADV hides device-coherent memory on RDNA4 (RX 9000) without it. | + +- A card without cooperative matrices (RDNA2 and older) prints `prefill attention: tiled`. +- `STRATA_VK_DP4` defaults to int8 when the card has int8 dot products in hardware, and always on RADV. Vega 10 + (gfx900) on the AMD proprietary driver takes the float GEMM, about 11x faster there. On RADV, a Vega 64 hung in + long agentic runs with the float GEMM. +- `STRATA_VK_SMEM_LIMIT`: the AMD proprietary driver reports 32768 on an RX 9070 XT although the card has 64 KB. + RustingStrata raises that to 49152 itself. Never set it above what the card has. ## What to send in an issue - GPU model, OS, driver and version (Mesa version on Linux). - The output of `vulkaninfo --summary`. - The full output of the failing command, including the first `vulkan:` line. -- If decode is slow: `rustingstrata bench --model --gpu --backend vulkan --pp 1024 --tg 128` with the same model. +- If decode is slow, the output of this with the same model: + +```bash +rustingstrata bench --model --gpu --backend vulkan --pp 1024 --tg 128 +``` diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index 194604e2..296df749 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -1,16 +1,21 @@ # Benchmarks -Every model RustingStrata runs, measured against llama.cpp; some also against other engines. Raw logs and older runs are in the [benchmark history](README.md#benchmark-history). +Every model RustingStrata runs, measured against llama.cpp. Some are also measured against other engines. Raw logs and +older runs are in the [benchmark history](README.md#benchmark-history). Rules for every entry: -- Same machine, same GGUF file, same prompt length, greedy decoding, in one session. The machine is named per entry. -- llama.cpp is tuned for the file (`-ncmoe`, `-ub`, flash attention) and the setting is written next to the number. -- A number that moves with the page cache, thermals or the text (MTP) is given as a range and the caveat is written below it. -- Entries that were not measured side by side say so. +- Same machine, same GGUF file, same prompt length, greedy decoding, one session. Each entry names its machine. +- llama.cpp is tuned for the file (`-ncmoe`, `-ub`, flash attention). The setting is written next to the number. +- A number that moves with the page cache, thermals or the text (MTP) is a range, with the caveat below it. +- An entry that was not measured side by side says so. Reference machine unless stated: RTX 3060 12 GB, Ryzen 5 7600X, 32 GB RAM. +Server method, for the entries that name it: both engines run as servers and answer the same streamed +`/v1/chat/completions` request with 128 reply tokens, greedy. Prefill is the prompt tokens over the time to the first +token. Decode is the other 127 tokens over the rest. Each server first answers one request that is not counted. + ## Summary | Model (file) | Decode, RustingStrata | Decode, llama.cpp | Other engine | Entry | @@ -18,37 +23,57 @@ Reference machine unless stated: RTX 3060 12 GB, Ryzen 5 7600X, 32 GB RAM. | Qwen3.6-35B-A3B UD-Q5_K_M, 4241-token prompt | 80.5 tok/s (75.1-82.0) | 64.4 (58.8-66.0) | - | [below](#qwen36-35b-a3b-ud-q5_k_m) | | Qwen3.6-35B-A3B UD-Q2_K_XL | 118.2 tok/s (113.4 after 4K) | 68.4 (66.5) | - | [below](#qwen36-35b-a3b-ud-q2_k_xl) | | Qwen3.6-35B-A3B UD-Q3_K_M, 6474-token prompt | 83.0 tok/s (108.0 with MTP) | 67.5 (101.1 with MTP) | PolyStrata 79.2 (113.3 with MTP) | [below](#qwen36-35b-a3b-ud-q3_k_m-vs-polystrata) | +| Qwen4-35B-A3B UD-Q5_K_M (39.5 GB), 8k prompt | 67.5 tok/s (no MTP) | 43.9 (no MTP); as servers with MTP 61.1 vs 44.7 | - | [below](#qwen4-35b-a3b-ud-q5_k_m) | | Qwen3.8-Flash-Next GSQ-RCO IQ2_XS, 1262-token prompt | 33.0 tok/s (29.3-35.8) | 25.6 (23.2-26.9) | - | [below](#qwen38-flash-next-gsq-rco-iq2_xs) | +| Qwen3.8-Flash-Next GSQ-RCO IQ3_XXS, 1.8k-token prompt (RTX 2080 SUPER) | 38.5 tok/s default, 41.5-43.1 opt-in | - | Strata 43.2 | [below](#qwen38-flash-next-gsq-rco-iq3_xxs-vs-strata) | | GLM-5.3-Flash UD-Q2_K_XL (119 GB) | 1.35-1.57 tok/s | 0.57-0.62 | - | [below](#glm-53-flash-ud-q2_k_xl-119-gb) | | DeepSeek-V4.1-Flash IQ2_XXS (249 GB) | 2-3.6 tok/s | 0.3-1.5 | - | [below](#deepseek-v41-flash-iq2_xxs-249-gb) | -| Inkling 2 Mini IQ4_NL (17.6 GB), 512-token prompt | 31.2 tok/s (28.7-33.7) | 8.7-10.5 | - | [below](#inkling-2-mini-iq4_nl-176-gb) | +| Inkling 2 Mini IQ4_NL (17.6 GB), 566-token prompt | 35.8 tok/s (35.6-36.1) | 31.1 (31.0-31.1) | - | [below](#inkling-2-mini-against-llamacpp-as-servers-05k-to-32k-prompts) | +| Kolibri 1.1 Q4_K_M (43.4 GB), 561-token prompt | 33.4 tok/s (32.0-35.8) | 27.0 (9.7-34.8) | - | [below](#kolibri-11-q4_k_m-434-gb) | +| GigaChat 4 37B-A4B Q4_K_M (23 GB), 0.7k prompt | 32.3 tok/s (24.0-40.2) | 37.2 (29.9-39.8) | - | [below](#gigachat-4-37b-a4b-q4_k_m) | +| Ternary Bonsai 2 9B Q2_0 (2.6 GB), 512-token prompt | 77.3 tok/s (PTQ1_0 46.1) | 98.0 (no PTQ1_0) | - | [below](#ternary-bonsai-2-ptq1_0-and-q2_0) | | Recursive Flint 39.8B UD-Q5_K_XL, 4102-token prompt | 64.6 tok/s (63.8-65.6) | 48.6 (47.5-49.3) | - | [below](#recursive-flint-398b-ud-q5_k_xl) | ## Qwen3.6-35B-A3B UD-Q5_K_M -`Qwen3.6-35B-A3B-UD-Q5_K_M.gguf` (25.2 GiB, does not fit in VRAM: a third of the experts are on the GPU). llama.cpp -is build 12191, tuned for the same file (`-cmoe --moe-cache-mib 7500 -ngl 99 -fa on -t 6 -ub 2048 -b 2048`, the best -decode of a 9-config sweep over `-ncmoe`, `--moe-cache-mib` and `--moe-cache-cpu-share`). +- File: `Qwen3.6-35B-A3B-UD-Q5_K_M.gguf`, 25.2 GiB. It does not fit in VRAM: a third of the experts are on the GPU. +- RustingStrata: commit 5a27ed1 (1.2.5). +- llama.cpp: build 12191, with the best decode flags of a 9-config sweep over `-ncmoe`, `--moe-cache-mib` and + `--moe-cache-cpu-share`. + +```bash +rustingstrata serve --gpu --ctx 8192 --mtp 0 +llama-server -cmoe --moe-cache-mib 7500 -ngl 99 -fa on -t 6 -ub 2048 -b 2048 +``` | | CUDA | llama.cpp | |---|---|---| | Decode after 4K prompt | **80.5 tok/s** (75.1-82.0) | 64.4 (58.8-66.0) | | Prefill, 4K prompt | **1530 tok/s** (1451-1596) | 1118-1122 with `-ncmoe 27`, its best prefill flags (2 runs, one load); 793 (367-1063) with the decode flags above | -Measured at commit 5a27ed1 (1.2.5) with `rustingstrata serve --gpu --ctx 8192 --mtp 0` and `llama-server`: the same -4241-token prompt file and the same script for both, greedy, thinking off, 128 tokens, no drafts in either engine. -Two loads per engine in alternating order; in each load a warm-up and the first 4K request are thrown away. Decode is -the mean of runs 4-8 of each load (10 runs, range in brackets). Both engines climb for the first runs after a load; -over all 16 runs it is 78.8 (63.6-82.0) against 60.3 (31.3-66.0). Prefill is 4 new prompts per load (8 runs). +- Prompt: 4241 tokens, the same file and script for both. Greedy, thinking off, 128 tokens, no drafts. +- Two loads per engine in alternating order. A warm-up and the first 4K request of each load are thrown away. +- Decode is the mean of runs 4-8 of each load (10 runs, range in brackets). Prefill is 4 new prompts per load (8 runs). -Not equal: the replies were 128 tokens (RustingStrata) and 125 (llama.cpp, ended by itself). About 20 GiB of RAM was -free for the 25.2 GiB file, so neither engine had the whole file in the page cache. Perplexity against llama.cpp was -not run on this file; for UD-Q3_K_M it is -[below](#quality-vs-llamacpp-qwen36-35b-a3b-ud-q3_k_m). +Caveats: + +- Both engines climb for the first runs after a load. Over all 16 runs decode is 78.8 (63.6-82.0) against 60.3 + (31.3-66.0). +- The replies were 128 tokens (RustingStrata) and 125 (llama.cpp, ended by itself). +- About 20 GiB of RAM was free for the 25.2 GiB file, so neither engine had the whole file in the page cache. +- Perplexity against llama.cpp was not run on this file. For UD-Q3_K_M it is + [below](#quality-vs-llamacpp-qwen36-35b-a3b-ud-q3_k_m). ## Qwen3.6-35B-A3B UD-Q2_K_XL -`Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf`, 11.7 GiB, does not fit in VRAM. llama.cpp build 11876 (2026-10-28), `-ncmoe 12 -ub 2048 -b 2048`, flash attention (its 4K prefill is about 1550 with the default ubatch). +- File: `Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf`, 11.7 GiB. It does not fit in VRAM. +- RustingStrata: mean of 3 rounds of the command below. +- llama.cpp: build 11876 (2026-10-28), `-ncmoe 12 -ub 2048 -b 2048`, flash attention. `llama-server` timings, + 4047-token prompt plus 128 tokens, 3 runs. Its 4K prefill is about 1550 with the default ubatch. + +```bash +rustingstrata bench --gpu --mtp 0 --pp 512,4096,32768 --tg 128 --reps 3 --ctx 32896 +``` | | CUDA | Vulkan | llama.cpp | |---|---|---|---| @@ -59,20 +84,29 @@ not run on this file; for UD-Q3_K_M it is | 32K: prefill / decode | 1800 / 91.9 tok/s | 1582 / 90.7 | - | | Greedy top-1 agreement with llama.cpp (20 prompts x 32 tokens) | 98-99% | 98-99% | 98.3% (its batch vs token-by-token modes) | -Method: `rustingstrata bench --gpu --mtp 0 --pp 512,4096,32768 --tg 128 --reps 3 --ctx 32896`, mean of 3 rounds. llama.cpp from `llama-server` timings, 4047-token prompt plus 128 tokens, 3 runs. MTP gains depend on the text. - -Agreement counts a token when it matches llama.cpp run token by token or with the context as one batch; -llama.cpp's own two modes agree on only 98.3%. The remaining misses are near-ties where -float rounding order picks a different token. The expert placement adapts between runs and the CPU and -GPU expert kernels round differently, so greedy output can change at such near-ties from one run to the next. MTP -on and off give identical greedy tokens. +- MTP gains depend on the text. MTP on and off give identical greedy tokens. +- Agreement counts a token when it matches llama.cpp run token by token or with the context as one batch. +- The misses are near-ties. Expert placement adapts between runs, so greedy output can change there from run to run. With less VRAM, simulated on the 3060 with `--vram-margin` (not measured on real 8 GB or 6 GB cards): ~8 GB keeps 116 / 110 tok/s decode (short / after 4K) and 2128 tok/s 4K prefill, ~6 GB 105 / 97 and 2056. ## Qwen3.6-35B-A3B UD-Q3_K_M vs PolyStrata -`Qwen3.6-35B-A3B-UD-Q3_K_M.gguf` (Unsloth, MTP layer included, 15.9 GiB, does not fit in VRAM). One prompt file for every engine (about 3200 words of repo docs, 6474 tokens in RustingStrata and llama.cpp, 6476 in PolyStrata), chat template with thinking off, greedy, 128 generated tokens, sent through each engine's OpenAI-compatible server by the same script. llama.cpp is b12191 (has `--moe-cache-mib` and `--moe-cache-cpu-share`). Prefill is the first request (cold), decode is the mean of runs 2-4 on the warm server. +- File: `Qwen3.6-35B-A3B-UD-Q3_K_M.gguf` (Unsloth, MTP layer included), 15.9 GiB. It does not fit in VRAM. +- Prompt: about 3200 words of repo docs. 6474 tokens in RustingStrata and llama.cpp, 6476 in PolyStrata. +- Request: chat template with thinking off, greedy, 128 generated tokens. One script sends it to each engine's + OpenAI-compatible server. +- Prefill is the first request (cold). Decode is the mean of runs 2-4 on the warm server. + +```bash +# RustingStrata. The MTP row uses --mtp 1. +rustingstrata serve --gpu --ctx 8192 --mtp 0 +# PolyStrata with its Q3_K_M config (--tail-skip 6, expert profile) +serve/server.py --engine strata +# llama.cpp b12191. The MTP row adds --spec-type draft-mtp. +llama-server -ngl 99 -fa on -ub 2048 -b 2048 -c 8192 +``` | | RustingStrata | PolyStrata | llama.cpp | |---|---|---|---| @@ -80,44 +114,115 @@ keeps 116 / 110 tok/s decode (short / after 4K) and 2128 tok/s 4K prefill, ~6 GB | Decode, no MTP | 83.0 tok/s | 79.2 tok/s (`--no-draft --lookup 0 --window 1`) | 67.5 tok/s (`-ncmoe 36 --moe-cache-mib 5000`); 50.4 with `-ncmoe 22`, no cache | | Decode with MTP | 108.0 tok/s (90% of drafts accepted) | 113.3 tok/s (defaults; acceptance not read) | 101.1 tok/s (87.5% accepted) | -How each was run: - -- RustingStrata: `serve --gpu --ctx 8192 --mtp 0|1`. -- PolyStrata: `serve/server.py --engine strata` with its Q3_K_M config (`--tail-skip 6`, expert profile). No MTP: `--no-draft --lookup 0 --window 1` added, because `--no-draft` alone leaves its n-gram guesses on. With MTP: defaults. -- llama.cpp: `llama-server -ngl 99 -fa on -ub 2048 -b 2048 -c 8192`, no-MTP rows with `-ncmoe 22`/`26`/`30`/`36` and `--moe-cache-mib` 0-5000, `--moe-cache-cpu-share` 0 or 0.5. The MTP row adds `--spec-type draft-mtp`. `-ncmoe 22` with a cache and MTP did not start. -- Sweep (decode tok/s, warm): `-ncmoe 22` no cache 50.4; 22 + 1500 MiB 61.9; 26 + 2500 MiB + share 0.5 65.4; 30 + 3000 + 0.5 63.4; 36 + 5000 + share 0 67.5. In `llama-bench` (`-p 5000`) the cache did not help (52.0 at `-ncmoe 22` against 42.9-47.5 with cache), the server runs are what is listed. +- PolyStrata without MTP needs `--no-draft --lookup 0 --window 1`: `--no-draft` alone leaves its n-gram guesses on. +- llama.cpp sweep (decode tok/s, warm): `-ncmoe 22` no cache 50.4; 22 + 1500 MiB 61.9; 26 + 2500 MiB + share 0.5 + 65.4; 30 + 3000 + 0.5 63.4; 36 + 5000 + share 0 67.5. `-ncmoe 22` with a cache and MTP did not start. -Not equal: +Caveats: -- Each engine's prefill after the first request is served from its prompt cache, so only the first request is a prefill number. +- After the first request each engine serves the prompt from its prompt cache. Only the first request is a prefill + number. - PolyStrata's token count is 2 higher (different tokenizer files). -- PolyStrata offers three sizes of Qwen3.6 (UD-Q3_K_M, UD-Q2_K_XL, UD-Q4_K_M). RustingStrata and llama.cpp take any GGUF. The Q3_K_M file was used for all three. -- With MTP, PolyStrata is ahead of RustingStrata here (113.3 against 108.0). It was not checked why; PolyStrata's draft logic and acceptance were not read. +- With MTP, PolyStrata is ahead of RustingStrata here (113.3 against 108.0). It was not checked why. - PolyStrata's engine for this model is built on llama.cpp's CUDA kernels. What else differs was not checked. -## Qwen3.8-Flash-Next GSQ-RCO IQ2_XS +## Qwen4-35B-A3B UD-Q5_K_M -Two-shard GGUF: shard 1 is 39,225,954,592 B (SHA-256 `92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7`), shard 2 is 28,800,138,432 B (SHA-256 `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`). Measured 2026-11-10 on the reference machine, but with 30 GiB of RAM (below the model's comfort point), so experts stream from the NVMe. +- File: `Qwen4-35B-A3B-UD-Q5_K_M-0000{1,2}-of-00002.gguf`, architecture `qwen4exp`, 39.5 GB in two files. It does not + fit in VRAM. +- Machine: the reference machine, measured 2026-12-04 (RTX 3060 12 GB, Ryzen 5 7600X at 6 threads capped at 4.5 GHz, + 30 GB RAM, NVMe). +- RustingStrata: this release. +- llama.cpp: 1579b02 (b12977), CUDA build. `--n-cpu-moe` and `-ub` were swept per row and the best taken: pp512 + `-ncmoe 28 -ub 2048 -b 2048`, pp8k and pp32k `-ncmoe 30 -ub 2048`, decode `-ncmoe 26` at 512 and `-ncmoe 28` at 8k + and 32k. -The prompt is a fixed WikiText-2 raw test passage plus one instruction: 1,262 tokens raw, 1,273 after the chat template. Exact text and token IDs are in `.posts/data/2026-11-10-qwen38-prompt.txt` and `.posts/data/2026-11-10-qwen38-prompt.ids.txt`. Greedy, 128 generated tokens, same OpenAI-compatible request for both engines. One warm request, then three measured requests per session; two sessions per engine with alternating order, so six measured runs each. Decode is the mean of the measured runs; cold prefill is the first request of each session. +```bash +rustingstrata bench --model --gpu --pp 512,8192,32768 --tg 128 --reps 2 --ctx 33024 +llama-bench -fa 1 -t 6 -r 2 +``` + +No drafts on either side in this table. tok/s: + +| Context | Prefill, RustingStrata | Prefill, llama.cpp | Decode, RustingStrata | Decode, llama.cpp | +|---|---|---|---|---| +| 512 | 554-581 | 463 (±12.6) | 69.0 | 43.6 | +| 8192 | 1533 | 1082 | 67.5 | 43.9 | +| 32768 | 1287 | 1196 | 64.6 | 42.3 | + +Vulkan, same card and command: prefill 444 / 1022 / 920 and decode 61.4 / 56.8 / 55.0 tok/s at 512 / 8192 / 32768. +llama.cpp's Vulkan build is not measured yet. + +As servers, one streamed request: + +```bash +rustingstrata serve --gpu --ctx 16384 +llama-server -ngl 99 --n-cpu-moe 28 -fa on -t 6 -c 16384 +``` + +Time to first token: 1190 vs 1367 ms for a 489-token prompt, 4956 vs 8629 ms for a 6648-token prompt. + +Several clients at once (RustingStrata `--parallel 4`, llama.cpp `-np 4 -ub 512`, same 400-word prompts, 128 reply +tokens): + +| Clients | TTFT, RustingStrata | TTFT, llama.cpp | Total decode, RustingStrata | Total decode, llama.cpp | +|---|---|---|---|---| +| 2 | 1.85 s | 2.57 s | 65.6 | 42.0 | +| 3 | 2.70 s | 3.21 s | 70.2 | 53.1 | +| 4 | 3.04 s | 3.70 s | 79.3 | 48.0 | + +With MTP drafts, one client, warm server (3 warm-up requests, then the median of 4), 400-word prompt, 256 reply +tokens, decode tok/s: + +- RustingStrata `serve --gpu --mtp 0/1/2`: 57.2 / 61.1 / 37.1. +- llama.cpp `llama-server -ngl 99 --n-cpu-moe 28 -fa on -t 6 -ub 512 -np 1 -c 16384`: no draft 28.9. With + `--spec-type draft-mtp --spec-draft-n-max 1/2/3`: 44.7 / 39.9 / 30.0 (acceptance about 0.28 at 3). +- Best against best: 61.1 vs 44.7. Time to first token 1212 vs 1311 ms. +- RustingStrata gains only 7% from one draft, and two drafts are slower than none. + +Memory, cold start (`smaps_rollup` plus `fincore` of the GGUF): RustingStrata touches 17.6-18.9 GB of the file and +holds 0.5 GB of anonymous memory, llama.cpp 24.6-25.1 GB and 0.9 GB. VRAM 11.5 vs 10.4 GB (11.3 with MTP). + +Caveats: + +- One session, two runs a row. The engines ran in turn, not interleaved. +- llama.cpp's pp512 moves a lot with `-ub`, `-b` and the page cache (an earlier sweep gave 224 ±34, `-ub 512` 148.7). + The number above is its best. +- llama-server without drafts is slower here than `llama-bench` (28.9 vs 43.6). + +## Qwen3.8-Flash-Next GSQ-RCO IQ2_XS + +- File: two-shard GGUF. Shard 1 is 39,225,954,592 B (SHA-256 + `92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7`). Shard 2 is 28,800,138,432 B (SHA-256 + `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`). +- Machine: the reference machine with 30 GiB of RAM, measured 2026-11-10. Experts stream from the NVMe. +- Prompt: a fixed WikiText-2 raw test passage plus one instruction. 1,262 tokens raw, 1,273 after the chat template. +- Request: greedy, 128 generated tokens, the same OpenAI-compatible request for both engines. +- Runs: one warm request, then three measured per session. Two sessions per engine in alternating order. +- Decode is the mean of the six measured runs. Cold prefill is the first request of each session. +- llama.cpp b12191 (commit `e95426f16`): `-c 4096 -ngl 99 -fa on -b 512 -ub 512 --cpu-moe --moe-cache-mib 4000`, its + best decode in a small sweep (`-ncmoe` 32-48, MoE cache 1500-4000 MiB). + +```bash +rustingstrata serve --gpu --ctx 4096 --mtp 0 +``` | Engine | Decode, no speculative | Cold prefill | Speculative/MTP | |---|---:|---:|---| | RustingStrata 1.2.1 | 33.0 tok/s (29.3-35.8) | 109.3 tok/s (99.9-118.8) | not available | | llama.cpp b12191 | 25.6 tok/s (23.2-26.9) | 30.9 tok/s (29.2-32.6) | not available | -How each was run: +Neither engine can draft on this file: -- RustingStrata: `serve --gpu --ctx 4096 --mtp 0`. -- llama.cpp b12191 (commit `e95426f16`): `-c 4096 -ngl 99 -fa on -b 512 -ub 512 --cpu-moe --moe-cache-mib 4000`. A small sweep (`-ncmoe` 32-48, MoE cache 1500-4000 MiB) put the best decode result at `--cpu-moe --moe-cache-mib 4000`. - -No MTP row: RustingStrata prints `--mtp 1: not supported for this model (hyper-connections): decoding without drafts`; llama.cpp b12191 starts with `--spec-type draft-mtp` but fails with `context type MTP requested but model doesn't contain MTP layers`. +- RustingStrata prints `--mtp 1: not supported for this model (hyper-connections): decoding without drafts`. +- llama.cpp b12191 starts with `--spec-type draft-mtp` but fails with + `context type MTP requested but model doesn't contain MTP layers`. ### Quality vs llama.cpp (Qwen3.8-Flash-Next IQ2_XS) Same GGUF, 36 WikiText-2 raw test chunks of 512 tokens (9,180 scored), MTP disabled. RustingStrata wrote the KLD base: -``` +```bash rustingstrata perplexity --model M1 --file CORPUS --ctx-len 512 --chunks 36 --gpu --mtp 0 --kld-base rusting.bin llama-perplexity -m M1 -f CORPUS -c 512 --chunks 36 --kl-divergence --kl-divergence-base rusting.bin \ --cpu-moe --moe-cache-mib 4000 -ngl 99 -fa on -b 512 -ub 512 @@ -132,11 +237,88 @@ llama-perplexity -m M1 -f CORPUS -c 512 --chunks 36 --kl-divergence --kl-diverge | RMS Δp | 3.60 +- 0.09% | | Correlation of log-PPL | 99.58% | -Raw logs, server logs and commands: `.posts/data/qwen38-*.{log,txt,err}`, `speed_rs*.jsonl`, `speed_llama*.jsonl`. +## Qwen3.8-Flash-Next GSQ-RCO IQ3_XXS vs Strata + +- Machine: not the reference machine. RTX 2080 SUPER 8 GB, Ryzen 9 7945HX (16 cores), 61 GB RAM, model on btrfs with + compression. +- File: two-shard GGUF from ISTA-DASLab (`Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-0000{1,2}-of-00002.gguf`, 44.9 + 28.8 GB). +- Strata 0.2.24 (engine 0.1.72, source commit `03bb4f4`), built from source for sm_75 by its own + `setup.sh --build --gguf-dir`. Run with `--mtp off --low-ram off --context 8192`. +- Strata's drafting was off (`--spec 2 --suffix-draft 0 --lookup-max-t 0`). Its log shows 0 of 0 drafts accepted. +- RustingStrata: `serve --gpu --ctx 8192 --mtp 0`, at the commit and with the settings named in each row. +- Prompt: 1,801 tokens (README text plus one instruction). A unique prefix makes every request a cold prefill. +- Request: one script for both servers. Chat template with thinking off, greedy, 128 generated tokens, streaming. +- Runs: one warm-up request, then 6 to 8 measured requests per server start. Decode and prefill are the last 3. + +| Configuration | Resident experts | Decode | Prefill | +|---|---:|---:|---:| +| RustingStrata `d235116` (baseline) | — | ~35.5 tok/s | ~440 tok/s | +| RustingStrata `4dd70c8`, default settings | — | ~38.5 tok/s | ~450 tok/s | +| RustingStrata `4dd70c8`, `STRATA_ARENA=1 STRATA_PIN=1 STRATA_PREFILL_CPU=1` | 1,073 | 42.56 tok/s (42.5-42.6) | 469.5 tok/s (466-472) | +| RustingStrata `155f6bc`, same + `STRATA_STAGE_GROUPS=6` | — | 41.5-41.7 tok/s | 470-473 tok/s (server's own count ~495) | +| RustingStrata `f79d72c`, `STRATA_ARENA=1 STRATA_PIN=1 STRATA_PREFILL_CPU=1` | 929 | 41.53 tok/s (41.3-41.7) | **646.4 tok/s** (642.6-651.1; server's own count 649-658) | +| RustingStrata `f79d72c`, same + `--vram-margin 272` | 1,219 | **43.07 tok/s** (43.0-43.1) | **645.7 tok/s** (642.5-647.3) | +| Strata 0.2.24 | ~40% hit rate | 43.1-43.3 tok/s | 536-549 tok/s | + +The rows name the settings of the measured commits. On the current build the tuned configuration is: + +```bash +rustingstrata serve --model MODEL.gguf --gpu --ctx 8192 --mtp 0 --arena --pin --prefill-cpu +``` + +`--arena`, `--pin`, `--prefill-cpu`, `--cpu-frac`, `--no-fused` and `--host-share` are described in +[USAGE.md](USAGE.md#flags). `--arena` uses ~45 GB RAM, adds ~7-11 s load time and evicts the file from the page cache. +`--host-share` measured slower on this machine. + +CLI `bench` on the same machine and model, warm page cache, same starting expert profile per pair. These rows are not +directly comparable to the server rows above. + +```bash +rustingstrata bench --gpu --backend cuda --ctx 8192 --mtp 0 --chunk 2048 --pp 1801 --tg 128 --prompt-file README.md +``` + +| Comparison | Resident experts | Decode | Prefill | +|---|---:|---:|---:| +| Default (no `STRATA_*`, 5 reps): `origin/main` (`0da5d11`) | 1,008 | 32.5 tok/s | 476.5 tok/s | +| Default (no `STRATA_*`, 5 reps): `81b4654` | 1,027 | 37.6 tok/s (+16%) | 485.5 tok/s (+2%) | +| Non-AVX-512 fallback (`STRATA_NO_Z=1`, 4 reps, 40.0% hit): `origin/main`, 8 threads | 1,027 | 31.4 tok/s | 473.7 tok/s | +| Non-AVX-512 fallback (`STRATA_NO_Z=1`, 4 reps, 40.0% hit): `81b4654`, 8 threads | 1,027 | 34.6 tok/s (+10%) | 485.5 tok/s | +| Non-AVX-512 fallback (`STRATA_NO_Z=1`, 4 reps, 40.0% hit): `81b4654`, 16 threads | 1,027 | 38.4 tok/s | 485.1 tok/s | +| Matched residency A/B (tuned flags, 4 reps): pre-`f79d72c` baseline | 960 | 35.5 tok/s | 580.7 tok/s | +| Matched residency A/B (tuned flags, 4 reps): `f79d72c` | 960 | 39.7 tok/s (+12%) | 640.8 tok/s (+10%) | + +Both engines run about 6 of the 10 routed experts of a layer on the CPU. Prefill is bound by staging the experts that +miss VRAM over PCIe. + +Caveats: + +- The `f79d72c` server rows were measured later the same day while `/usr/bin/sunshine` held ~122 MiB VRAM. Nothing + else was on the GPU for the earlier rows. +- Resident expert counts differ across the server rows, so their decode does not isolate code changes at one cache + size. The 960-expert CLI A/B isolates `f79d72c`. +- The opt-in rows need ~45 GB of RAM for the arena and pin threads. They were measured on this machine only. +- Strata keeps its own expert arena in RAM. RustingStrata's default reads the mapped file. +- Before each non-arena RustingStrata run the page cache held all of shard 1. An arena run drops it. +- Prompt token counts differ by 2 (1,803 for Strata, 1,801 for RustingStrata; different tokenizer files). +- Prefill gains depend on the workload. A shorter 1,217-token prompt with a fixed 10% CPU share prefilled slower on + `f79d72c` (251 vs 366 tok/s in one run each). +- llama.cpp was not run on this machine. ## GLM-5.3-Flash UD-Q2_K_XL (119 GB) -Four shards, 119 GB, 30 GB RAM, so experts stream from SSD through the page cache. Measured 2026-11-13 on the reference machine; llama.cpp b12119 with `-ngl 99 --cpu-moe -c 2048`, RustingStrata `serve --gpu` with `STRATA_GLM_CTX=2048`. Both through `/v1/chat/completions` with streaming, 64 greedy tokens, run in the order llama.cpp, RustingStrata, RustingStrata, llama.cpp. The short prompt is "Explain in two sentences why the sky is blue." (23 tokens after the chat template); the long prompt is `tools/prompts/bench-natural.txt` (429 tokens). Each prompt was sent twice per session; decode is the mean of all runs, prefill is the first request of each session (llama.cpp's repeat hits its prompt cache). +- File: four shards, 119 GB. The machine had 30 GB RAM, so experts stream from SSD through the page cache. +- Machine: the reference machine, measured 2026-11-13. +- llama.cpp b12119: `-ngl 99 --cpu-moe -c 2048`. +- Request: `/v1/chat/completions` with streaming, 64 greedy tokens. Order: llama.cpp, RustingStrata, RustingStrata, + llama.cpp. +- Short prompt: "Explain in two sentences why the sky is blue." (23 tokens after the chat template). Long prompt: + `tools/prompts/bench-natural.txt` (429 tokens). +- Each prompt was sent twice per session. Decode is the mean of all runs. Prefill is the first request of each + session, because llama.cpp's repeat hits its prompt cache. + +```bash +STRATA_GLM_CTX=2048 rustingstrata serve --gpu +``` | | RustingStrata | llama.cpp | |---|---|---| @@ -146,7 +328,14 @@ Four shards, 119 GB, 30 GB RAM, so experts stream from SSD through the page cach | First token, 429-token prompt, cold | 84-93 s | 73-76 s | | Load until ready | 5 s | 66-73 s | -Quality vs llama.cpp, same GGUF and prompts, teacher-forced: llama.cpp b12119's own greedy tokens (32 per prompt on the three `tools/glm_ref/p{1,2,3}` prompts) are fed through RustingStrata's GPU forward, and the top-5 distributions are compared at every step. +Quality vs llama.cpp, same GGUF and prompts, teacher-forced. llama.cpp b12119's own greedy tokens (32 per prompt on +the three `tools/glm_ref/p{1,2,3}` prompts) go through RustingStrata's GPU forward. The top-5 distributions are +compared at every step with the `completion_probabilities` in `tools/glm_ref/p{1,2,3}_llama.json`. + +```bash +# STRATA_GLM_PRELOAD=0 was also set, to keep memory pressure down +STRATA_GLM_FORCE= STRATA_GLM_TOP5=1 rustingstrata generate -n 32 +``` | Metric | Result | |---|---| @@ -154,14 +343,15 @@ Quality vs llama.cpp, same GGUF and prompts, teacher-forced: llama.cpp b12119's | Top-5 overlap | 91.9% | | Mean \|dlogprob\| over shared top-5 ids | 0.230 | -How it was run: - -- Speed: the raw JSON lines are in `.posts/data/2026-11-13-glm-bench.log` (local benchmark notes). -- Quality: `STRATA_GLM_FORCE= STRATA_GLM_TOP5=1 rustingstrata generate -n 32` against the `completion_probabilities` stored in `tools/glm_ref/p{1,2,3}_llama.json`; log in `.posts/data/2026-11-13-glm-quality.log`. `STRATA_GLM_PRELOAD=0` was set for the quality runs to keep memory pressure down. +Caveats: -Caveats: everything moves with the page cache, because the model is four times the size of RAM. llama.cpp's repeated-prompt TTFT (8-14 s on the long prompt) is its prompt cache, not prefill. One repeated 429-token RustingStrata request was OOM-killed under global memory pressure after the earlier runs; it is excluded. The four-shard file, build and prompts match the 2026-11-10 run below. +- Everything moves with the page cache, because the model is four times the size of RAM. +- llama.cpp's repeated-prompt TTFT (8-14 s on the long prompt) is its prompt cache, not prefill. +- One repeated 429-token RustingStrata request was OOM-killed under memory pressure. It is excluded. -Previous paired run (2026-11-10, same machine): 1.25-1.40 tok/s against 0.47-0.56 on the short prompt, 1.25-1.33 against 0.53 on a 550-token prompt, first token after 17-19 s against 40-41 s, a 550-token first token after 206-209 s against 107-229 s, and 188/192 top-1 on 3 prompts x 64 tokens. +Previous paired run (2026-11-10, same machine, file and build): 1.25-1.40 tok/s against 0.47-0.56 on the short prompt, +1.25-1.33 against 0.53 on a 550-token prompt, first token after 17-19 s against 40-41 s, a 550-token first token after +206-209 s against 107-229 s, and 188/192 top-1 on 3 prompts x 64 tokens. ## DeepSeek-V4.1-Flash IQ2_XXS (249 GB) @@ -171,17 +361,30 @@ Previous paired run (2026-11-10, same machine): 1.25-1.40 tok/s against 0.47-0.5 | Prefill | ~2 tok/s short, ~0.5 tok/s at 1400 tokens | 0.5-0.9 tok/s | | Top-1 agreement (teacher-forced) | 189/192 short, 21/23 on 1425 tokens | - | -Not measured side by side: the llama.cpp numbers are its first cold runs, the RustingStrata numbers are later runs. The model files were deleted afterwards, so this entry cannot be repeated until they are downloaded again. +Not measured side by side: the llama.cpp numbers are its first cold runs, the RustingStrata numbers are later runs. +The model files were deleted afterwards, so this entry cannot be repeated until they are downloaded again. + +On data-center cards (not this machine, RustingStrata only), with the experts in the page cache: -On data-center cards (not this machine, RustingStrata only), with the experts in the page cache: end-to-end decode 4.5-4.6 tok/s at the default 9 GB VRAM expert budget on an A100 80 GB and an H100 NVL, and 6.6 (A100) and 8.9 (H100 NVL) tok/s at 60 GB, on one 30-token prompt and 33 decode tokens. See [datacenter-nvidia-results.md](datacenter-nvidia-results.md#2026-11-10--deepseek-v41-flash-1017-iq2_xxs). +- End-to-end decode is 4.5-4.6 tok/s at the default 9 GB VRAM expert budget on an A100 80 GB and an H100 NVL. +- At 60 GB it is 6.6 (A100) and 8.9 (H100 NVL) tok/s. +- Both on one 30-token prompt and 33 decode tokens. See + [datacenter-nvidia-results.md](datacenter-nvidia-results.md#2026-11-10-deepseek-v41-flash-1017-iq2_xxs). ## Recursive Flint 39.8B UD-Q5_K_XL -`flint-UD-Q5_K_XL.gguf`, 27.9 GiB, 39.79 B parameters, 49 layers (2 dense, 47 MoE), 256 experts, top-6. Measured -2026-11-14 on the reference machine. Prompt: `tools/prompts/bench-natural.txt` repeated ten times, 4102 tokens -(`.posts/data/2026-11-14-flint-prompt.txt`), chat template, greedy, 200 output tokens, the same OpenAI-compatible -streaming request for both engines. One 4K request thrown away, then three measured; RustingStrata ran first, -llama.cpp second, so llama.cpp got the warmer page cache. +- File: `flint-UD-Q5_K_XL.gguf`, 27.9 GiB, 39.79 B parameters, 49 layers (2 dense, 47 MoE), 256 experts, top-6. +- Machine: the reference machine, measured 2026-11-14. +- Prompt: `tools/prompts/bench-natural.txt` repeated ten times, 4102 tokens. +- Request: chat template, temperature 0, `enable_thinking: false`, 200 output tokens. The same OpenAI-compatible + streaming request for both engines. +- Runs: one 4K request thrown away, then three measured. +- RustingStrata: default placement. The 64.6 warm run used the 1.2.1 build, which has the same placement code as 1.2.2. +- llama.cpp b12191 (commit `e95426f16`): `-ngl 99 -ncmoe 36 -fa on -t 6 -b 2048 -ub 2048 -c 8192`. + +```bash +rustingstrata serve --model M --gpu --ctx 8192 +``` | | RustingStrata 1.2.2 | llama.cpp b12191 | |---|---:|---:| @@ -193,32 +396,17 @@ llama.cpp second, so llama.cpp got the warmer page cache. | Resident experts | 3244 / 12032 (7157 MB VRAM) | - | | Expert traffic | 622.1 MB/token | - | -How each was run: - -- RustingStrata: `serve --model M --gpu --ctx 8192`; default placement. Raw runs in - `.posts/data/2026-11-14-flint-rs-final-server.log` and `2026-11-14-flint-rs-final.jsonl`. The 64.6 warm run used - the 1.2.1 build with the same placement code; 1.2.2 is that code with the unused n-gram/one-shot experiments - removed. -- llama.cpp b12191 (commit `e95426f16`): `-ngl 99 -ncmoe 36 -fa on -t 6 -b 2048 -ub 2048 -c 8192`; raw runs in - `.posts/data/2026-11-14-flint-llama-final-server.log` and `2026-11-14-flint-llama-final.jsonl`. -- Both: `.posts/data/bench.py PORT LABEL 3 PROMPT 200`, temperature 0, `enable_thinking: false`. -- Commands: `.posts/data/2026-11-14-flint-commands.txt`. - -Not equal: +Caveats: - RustingStrata ran before llama.cpp, so llama.cpp had the warmer page cache. - The first 4K request depends on the page cache. A second RustingStrata load decoded 55.9 and 58.8 on its first two - measured requests and was still climbing (`.posts/data/2026-11-14-flint-rs-repeat*.log`). -- Prefill: once the expert pages are cached, a new 4106-token prompt prefilled at 1.14-1.30k tok/s on RustingStrata - and 0.85-1.02k on llama.cpp (mean 0.96k). The first prefill after a model load ranged 0.07-1.0k for both, and the - order (RustingStrata then llama.cpp) changes which pages are cached; raw logs in - `.posts/data/2026-11-14-flint-prefill-*.log`. After the first request both use their prompt cache. -- Decode follows the greedy text: a later RustingStrata run took the "However, they've pasted the same passage..." - route and decoded at 41-46 tok/s (51.2% hit) on the current build; raw run in - `.posts/data/2026-11-14-flint-rs-current*`. The 64.6 tok/s row is the fast route. A same-continuation comparison - (teacher forcing) is still needed before publishing. + measured requests and was still climbing. +- The prefill row is a new 4106-token prompt with the expert pages cached (llama.cpp mean 0.96k). The first prefill + after a model load ranged 0.07-1.0k for both. After the first request both use their prompt cache. +- Decode follows the greedy text. A later RustingStrata run took the "However, they've pasted the same passage..." + route and decoded at 41-46 tok/s (51.2% hit). The 64.6 tok/s row is the fast route. +- Not measured yet: a same-continuation comparison (teacher forcing) and quality (perplexity/KLD). - The file has no MTP/draft head, so neither engine used speculative decoding. -- Quality (perplexity/KLD) is not measured yet; the post says so and is not ready to publish. ## Quality vs llama.cpp (Qwen3.6-35B-A3B UD-Q3_K_M) @@ -233,20 +421,26 @@ Corpus: repo docs prose, 36 chunks x 512 tokens (9180 scored), not wikitext. | RMS dp | 1.83% | | Correlation of log-PPL | 99.88% | -Reproduce: -``` +```bash rustingstrata perplexity --model M --file F --ctx-len 512 --gpu --mtp 0 --kld-base base.bin llama-perplexity -m M -f F -c 512 --kl-divergence --kl-divergence-base base.bin ``` -llama.cpp batch vs token-by-token modes differ by about 1.7% in top-token agreement on their own. + +llama.cpp's batch and token-by-token modes differ by about 1.7% in top-token agreement on their own. ## Inkling 2 Mini IQ4_NL (17.6 GB) -`Inkling-2-Mini-IQ4_NL.gguf` (architecture `inkling2_loop`, 26.07 B parameters), measured 2026-11-21 on the reference -machine (30 GB RAM), warm page cache, in one session. RustingStrata: `bench --pp 64,512,2048 --tg 64 --reps 2` with -`--backend cuda`, `--backend vulkan` and `STRATA_DS_GPU=0`; mean of the two runs, the two runs in brackets. -llama.cpp c622f62 built with CUDA: `llama-bench -t 6 -r 2 -p 64,512,2048 -n 64` with `-ngl 18` (`-ngl 99` runs out -of VRAM; 12, 16 and 20 layers measured within 3% of 18 at 64 and 512 tokens), and with `-ngl 0` at 64, 512 and 2048 tokens. +- File: `Inkling-2-Mini-IQ4_NL.gguf`, architecture `inkling2_loop`, 26.07 B parameters. +- Machine: the reference machine (30 GB RAM), measured 2026-11-21, warm page cache, one session. +- RustingStrata: the command below with `--backend cuda`, with `--backend vulkan` and with `STRATA_DS_GPU=0`. Mean of + the two runs, the two runs in brackets. +- llama.cpp c622f62, CUDA build, with `-ngl 18` and with `-ngl 0`. `-ngl 99` runs out of VRAM. 12, 16 and 20 layers + measured within 3% of 18 at 64 and 512 tokens. + +```bash +rustingstrata bench --pp 64,512,2048 --tg 64 --reps 2 +llama-bench -t 6 -r 2 -p 64,512,2048 -n 64 +``` | | Prefill 64 tokens | Prefill 512 | Prefill 2048 | Decode (tok/s) | |---|---|---|---|---| @@ -256,24 +450,240 @@ of VRAM; 12, 16 and 20 layers measured within 3% of 18 at 64 and 512 tokens), an | llama.cpp, CUDA build, `-ngl 18` | 124.7 ± 3.6 | 383.9 ± 7.2 | 322.6 ± 1.0 | 8.7 ± 1.3 | | llama.cpp, CUDA build, `-ngl 0` | 122.3 ± 5.0 | 377.5 ± 7.8 | 311.9 ± 4.4 | 10.5 ± 1.2 | -Quality vs llama.cpp, same GGUF, teacher-forced: llama.cpp c622f62's greedy tokens (CPU build, `/completion` at -temperature 0) are fed through RustingStrata's forward and the top token is compared at every step -(`tests/inkling2_forward.rs`). Short prompt: 24 of 24. Prompt of several hundred tokens: at least 47 of 48 (one near -tie). The same on the CPU, CUDA and Vulkan paths. - -Caveats: llama.cpp reads the prompt faster (RustingStrata is at 0.6-0.7 of its speed from 512 tokens on): its CUDA -build runs the batch on the GPU even with no layer offloaded, and RustingStrata computes the attention scores of a -chunk on the CPU. `llama-bench` decodes 64 tokens from an empty context, `bench` decodes them after the prompt, so -the decode columns are not the same test. The first run of the 64-token prompt is the first work of the process and -is the slow one of the two. A CPU-only llama.cpp build was not benchmarked with `llama-bench`; its server reported -40.4 tok/s for the prompt and 11.0 tok/s for the reply earlier the same day (one run, not side by side). Vulkan was -run on the RTX 3060 only. Decoding is greedy in both engines. - -The decode column was measured again later the same day, same command, after a decoded token moved onto the GPU -(it was 29.9 / 27.1 / 25.6 on CUDA, 21.5 / 20.9 / 19.8 on Vulkan and 12.0 / 11.6 / 11.3 on the CPU). A desktop app -used part of the GPU during that run. Alternating runs of the old and new build at a 512-token prompt, same load: -CUDA 25.4 to 33.5 tok/s, Vulkan 16.6 to 25.4 tok/s, prefill unchanged (within 1-4%). Most of the Vulkan gain is the -IQ4_NL expert matvec (105 to 270 GB/s on 8 experts of 2304x2304). +Quality vs llama.cpp, same GGUF, teacher-forced (`tests/inkling2_forward.rs`). llama.cpp c622f62's greedy tokens (CPU +build, `/completion` at temperature 0) go through RustingStrata's forward and the top token is compared at every step. +Short prompt: 24 of 24. Prompt of several hundred tokens: at least 47 of 48 (one near tie). The same on the CPU, CUDA +and Vulkan paths. + +Caveats: + +- RustingStrata prefilled at 0.6-0.7 of llama.cpp's speed from 512 tokens on in this run. Its prefill attention moved + to the GPU after it. The + [server comparison of 2026-11-25](#inkling-2-mini-against-llamacpp-as-servers-05k-to-32k-prompts) has the newer + numbers. +- `llama-bench` decodes 64 tokens from an empty context, `bench` decodes them after the prompt. The decode columns + are not the same test. +- The decode column was measured again later the same day, same command, on a newer build. A desktop app used part + of the GPU during that run. +- The first run of the 64-token prompt is the first work of the process and is the slow one of the two. +- A CPU-only llama.cpp build was not benchmarked with `llama-bench`. Its server reported 40.4 tok/s for the prompt and + 11.0 tok/s for the reply earlier the same day (one run, not side by side). +- Vulkan was run on the RTX 3060 only. + +## Inkling 2 Mini against llama.cpp as servers, 0.5k to 32k prompts + +- Files: `Inkling-2-Mini-UD-IQ2_XXS.gguf`, `Inkling-2-Mini-UD-IQ3_XXS.gguf`, `Inkling-2-Mini-IQ4_NL.gguf`. +- Machine: the reference machine (RTX 3060 12 GB, 30 GB RAM), measured 2026-11-25 in one session. The two engines ran + in turn for each file. +- Method: the server method above, no prompt cache, timed by the client. +- RustingStrata a3a6968, CUDA, no other flag. +- llama.cpp 0ce7f213b, CUDA build, with the same `-c` and the flags of its row. + +```bash +rustingstrata serve --ctx 8192 # 0.5k and 3.8k +rustingstrata serve --ctx 40960 # 16k and 32k +llama-server --device CUDA0 -np 1 -t 6 +``` + +Prefill / decode in tok/s, mean of 3 requests (0.5k, 3.8k) or 2 requests (16k, 32k): + +| File | Engine and flags | 0.5k (566 tokens) | 3.8k (4132) | 16k (16604) | 32k (32675) | +|---|---|---|---|---|---| +| UD-IQ2_XXS | RustingStrata | 487.7 / 59.0 | 386.6 / 51.1 | 286.5 / 42.1 | 217.9 / 34.5 | +| | llama.cpp `-ngl 99` (`-ub 96` at 16k and 32k) | 407.9 / 43.0 | 378.3 / 39.8 | 240.0 / 36.2 | 194.2 / 31.2 | +| UD-IQ3_XXS | RustingStrata | 440.1 / 52.0 | 344.5 / 44.2 | 252.9 / 35.0 | 190.1 / 28.6 | +| | llama.cpp `-ngl 99 -ncmoe 6` | 328.6 / 33.5 | 335.9 / 31.6 | | | +| | llama.cpp `-ngl 99 -ncmoe 8 -ub 64 -b 64` (a later run of the same day) | | | 138.9 / 26.8 | 122.9 / 24.2 | +| IQ4_NL | RustingStrata | 295.5 / 35.8 | 256.5 / 31.2 | 202.7 / 27.6 | 162.9 / 23.6 | +| | llama.cpp `-ngl 99 -cmoe -ub 16 -b 16 --moe-cache-mib 8192 --moe-cache-cpu-share 0.95` (6144 at 16k and 32k) | 93.7 / 31.1 | 94.7 / 29.6 | 70.6 / 25.9 | 64.4 / 22.3 | +| | llama.cpp `-ngl 99 -cmoe -ub 256 --moe-cache-mib 1408 --moe-cache-cpu-share 0.95` | 137.9 / 23.0 | 170.5 / 22.8 | | | + +Caveats: + +- The runs of one cell differ by at most 5%. The prefill margin at 3.8k is small for UD-IQ2_XXS and UD-IQ3_XXS: + llama.cpp's own server timings give it 382.9 and 339.7 tok/s there. +- The llama.cpp flags are the best found by hand for each file and context on this card, not a full search. For IQ4_NL + one setting is best at decode and another at prefill, so both are in the table. +- The 16k and 32k prompts are the same text repeated. +- RustingStrata on UD-IQ3_XXS in the later run, from e14e8ca: 263.6 / 37.8 at 16k and 184.1 / 28.1 at 32k. +- A desktop used 389 MiB of VRAM during the session. + +Top token against llama.cpp (same day, same llama.cpp build and files). llama.cpp writes 48 greedy tokens after the +prompt file sent as raw text (`/completion`). `rustingstrata score` reads the same prompt and those 48 tokens, and its +top token is counted at each step. One run a cell. + +| File | 540-token prompt | 4106-token prompt | +|---|---|---| +| UD-IQ2_XXS | 47 of 48 | 48 of 48 | +| UD-IQ3_XXS | 47 of 48 | 46 of 48 | +| IQ4_NL | 47 of 48 | 48 of 48 | + +At each of the five steps that differ, llama.cpp's own first and second tokens are 0.05 to 0.31 apart in log +probability. + +## Kolibri 1.1 Q4_K_M (43.4 GB) + +- File: `Kolibri-1.1-Q4_K_M.gguf`, architecture `kolibri1`. It does not fit in RAM plus VRAM. +- Machine: the reference machine (RTX 3060 12 GB, 30 GB RAM, NVMe), measured 2026-11-25. +- Method: the server method above. The request that is not counted has 0.5k tokens. +- RustingStrata: default flags (9.7 GB of VRAM). +- llama.cpp: the Kolibri fork at 5f4d22289, CUDA build, with `-ngl 4` (its best prefill here) and with + `-ngl 99 -cmoe` (its best decode here). + +```bash +rustingstrata serve --model +llama-server -c 40000 +``` + +Mean, the range of the runs in brackets, the number of runs after it: + +| Prompt | | Prefill (tok/s) | Decode (tok/s) | Runs | +|---|---|---|---|---| +| 0.5k (561 tokens) | RustingStrata | 181.0 (156.9-199.6) | 33.4 (32.0-35.8) | 5 | +| | llama.cpp `-ngl 4` | 145.4 (93.8-165.5) | 15.5 (14.6-16.8) | 5 | +| | llama.cpp `-ngl 99 -cmoe` | 98.5 (10.7-173.7) | 27.0 (9.7-34.8) | 5 | +| 3.8k (3860) | RustingStrata | 148.7 (141.9-152.9) | 23.0 (22.4-23.4) | 3 | +| | llama.cpp `-ngl 4` | 41.3 | 5.9 | 1 | +| | llama.cpp `-ngl 99 -cmoe` | 27.9 | 10.6 | 1 | +| 16k (16163) | RustingStrata | 139.1 (130.8-147.4) | 21.0 (20.9-21.1) | 2 | +| | llama.cpp `-ngl 4` | 48.4 | 3.8 | 1 | +| | llama.cpp `-ngl 99 -cmoe` | 30.0 | 8.7 | 1 | +| 32k (31443) | RustingStrata | 158.8 (146.8-170.9) | 21.1 (20.1-22.0) | 2 | +| | llama.cpp `-ngl 4` | 34.0 | 3.3 | 1 | +| | llama.cpp `-ngl 99 -cmoe` | 32.9 | 9.3 | 1 | + +Quality vs llama.cpp, same GGUF, teacher-forced. The fork's greedy tokens (`-ngl 4`, 48 tokens) go through +`rustingstrata score` and the top token is compared at every step: 45, 46, 44 and 46 of 48 after prompts of 2k, 3.8k, +16k and 32k tokens. The fork against itself (CPU against GPU layers, or `-ngl 2` against `-ngl 4`) gives 45, 45, 40 +and 44 of 48. Every miss is at a step where the reference's two best tokens are close. + +Caveats: + +- The llama.cpp rows at 3.8k and above are one run each. +- The llama.cpp runs were made before the last RustingStrata prefill change, in the same night, not interleaved. The + 0.5k RustingStrata row before that change, run between the two llama.cpp rows, was 132.4 (110.0-148.0) / 33.2. +- The low ends of the llama.cpp ranges at 0.5k are its first runs, with the experts not yet in the page cache. Its + later runs reach 148-166 (`-ngl 4`) and 129-174 (`-cmoe`) tok/s of prefill. +- llama.cpp counts 564 tokens for the 0.5k prompt. +- `--moe-cache-mib 5000` and `--moe-cache-mib 8000 --moe-cache-cpu-share 0.5` were also tried for llama.cpp at 3.8k. + They were slower in decode than `-cmoe` alone (34.9 / 3.8 and 37.6 / 6.6). +- Speed on this file depends on the drive and on how much of the file the page cache holds. + +Vulkan against CUDA on the same card, in a later session of 2026-11-25, after a change to how experts with no slot in +VRAM are copied. Same request and method, `serve --backend vulkan` then `serve --backend cuda`, 3 requests at 0.5k and +3.8k and 2 at 16k and 32k. No llama.cpp run in this session. + +| Prompt | Vulkan prefill (tok/s) | Vulkan decode | CUDA prefill | CUDA decode | +|---|---|---|---|---| +| 0.5k (562 tokens) | 128.8 (114.3-139.2) | 26.8 (24.2-28.6) | 208.9 (178.6-231.8) | 33.7 (33.3-34.0) | +| 3.8k (3861) | 105.6 (100.3-110.7) | 19.5 (18.5-20.4) | 181.7 (172.6-188.1) | 26.4 (25.9-26.7) | +| 16k (16166) | 103.0 (98.1-107.9) | 19.1 (18.7-19.4) | 155.3 (153.7-156.8) | 20.2 (20.0-20.4) | +| 32k (31446) | 100.5 (100.4-100.5) | 19.2 (19.2-19.3) | 162.9 (159.2-166.5) | 21.6 (21.0-22.2) | + +- VRAM in use: 10.2 GB with Vulkan, 9.7 GB with CUDA. +- Vulkan ran first, so CUDA had the warmer page cache. Vulkan was run on the RTX 3060 only. +- Top token against llama.cpp's greedy tokens (48 steps): 43 and 46 with Vulkan, 44 and 46 with CUDA after the 2k and + 3.8k prompts. + +## GigaChat 4 37B-A4B Q4_K_M + +- File: `GigaChat4-37B-A4B-Q4_K_M.gguf`, architecture `gigachat4`, 23 GB. It does not fit in VRAM. +- Machine: the reference machine (RTX 3060 12 GB, Ryzen 5 7600X, 30 GB RAM, NVMe), measured 2026-11-29. +- Method: the server method above. The request that is not counted has 0.5k tokens. +- Prompts: each is a different slice of the repository's docs with a different first line, so no prompt cache is + reused. The length differs from run to run (the range is in the table). +- llama.cpp: the GigaChat 4 branch at 0541e50e2, CUDA build (8.6 GB of VRAM). + +```bash +# RustingStrata, then the same with --mtp 1 +rustingstrata serve --model --gpu --ctx 8192 +llama-server -ngl 99 --n-cpu-moe 24 -c 8192 +``` + +Mean, the range of the runs in brackets: + +| Prompt | | Prefill (tok/s) | Decode (tok/s) | Runs | +|---|---|---|---|---| +| 0.7k (697-765 tokens) | RustingStrata | 259.3 (233.5-317.7) | 32.3 (24.0-40.2) | 4 | +| 0.7k (545-720) | RustingStrata `--mtp 1` | 241.0 (190.3-279.5) | 33.3 (28.9-39.7) | 4 | +| 0.7k (573-715) | llama.cpp `--n-cpu-moe 24` | 281.5 (244.7-303.5) | 37.2 (29.9-39.8) | 4 | +| 3.5k (3440-3896) | RustingStrata | 301.6 (297.5-307.0) | 31.8 (29.2-33.3) | 3 | +| 3.5k (3476-3872) | RustingStrata `--mtp 1` | 279.3 (277.2-280.4) | 30.3 (26.1-37.9) | 3 | +| 3.5k (3586-4448) | llama.cpp `--n-cpu-moe 24` | 430.5 (387.4-455.5) | 39.9 (39.6-40.3) | 3 | + +- llama.cpp is faster on this file: by about 9% in prefill and 15% in decode at 0.7k, and by 43% and 25% at 3.5k. +- RustingStrata's decode rises over the first requests while the expert placement adapts (24.0, 30.7, 34.3, 40.2 at + 0.7k). +- With `--mtp 1` decode is within the run-to-run spread of the run without drafts. + +Quality vs llama.cpp is in [MODELS.md](MODELS.md#gigachat-4-37b-a4b-q4_k_m-23-gb): 625 of 640 top tokens agree over +20 prompts. + +Caveats: + +- One session, the engines in turn (RustingStrata, RustingStrata `--mtp 1`, llama.cpp), not interleaved. +- Other programs held about 11 GB of RAM, so the page cache did not keep the whole file. The first runs read experts + from the drive. +- CUDA only. + +Prefill before and after the commit that streams a chunk's missed experts (2026-12-01, same machine): + +```bash +rustingstrata bench --model --gpu --pp 512,3584 --tg 32 --reps 2 +``` + +| | pp512 (tok/s) | pp3584 (tok/s) | pp3584 with `STRATA_DS_CPU_SHARE=0` | +|---|---|---|---| +| before | 150.3, 181.4 | 308.1 (275.6-359.5) | 83.3 (78.4-88.1) | +| streamed misses | 282.7, 346.2 | 374.4 (331.0-381.4) | 345.1 (321.9-368.2) | + +- "before" is release 1.4.5 (a6329c4) plus the sections-scratch commit. "streamed misses" is the commit that streams + a chunk's missed experts through three VRAM slots. +- The binaries ran in turn, twice each. Every number is the median of the per-prompt rates from `STRATA_DS_PROF`. + pp512 is the warm second prompt of each run, so 2 values each. +- Other jobs kept the load average at 5-13 and about 20 GB of RAM free. Another server held about 3 GB of VRAM. +- Decode after the prompt did not change beyond the spread (33.3 vs 32.8 tok/s at 3.5k). +- Parity vs llama.cpp over the same 20 prompts: 620 of 640 with the streaming commit, 619 of 640 for 1.4.5 in the same + session. + +## Ternary Bonsai 2 PTQ1_0 and Q2_0 + +- Models: PrismML's Ternary Bonsai 2 2B and 9B, architecture `qwen35`, dense. Every weight is in PTQ1_0 or Q2_0. +- Files: 2B PTQ1_0 429 MB, 2B Q2_0 547 MB, 9B PTQ1_0 2.0 GB, 9B Q2_0 2.6 GB. Every file fits in VRAM. +- Machine: the reference machine (RTX 3060 12 GB), measured 2026-11-29. +- llama.cpp: the GigaChat 4 branch at 0541e50e2, CUDA build. It has Q2_0, not PTQ1_0. + +```bash +# RustingStrata, also with --backend vulkan. Decode runs after the prompt. +rustingstrata bench --model --gpu --backend cuda --pp 512,4096 --tg 64 --reps 2 +# llama.cpp. Decode runs at an empty context. +llama-bench -ngl 99 -fa 1 -p 512,4096 -n 64 +``` + +Mean of the runs, the range in brackets where it is wide: + +| Model, file | Engine | pp512 (tok/s) | pp4096 (tok/s) | Decode (tok/s), after 512 / 4096 | +|---|---|---|---|---| +| 2B PTQ1_0 | RustingStrata CUDA | 3757.5 (2884.3-4630.6) | 4773.2 | 174.5 / 168.6 | +| 2B PTQ1_0 | RustingStrata Vulkan | 4246.1 | 4583.3 | 132.2 / 127.6 | +| 2B Q2_0 | RustingStrata CUDA | 4899.3 | 5048.1 | 285.8 / 272.8 | +| 2B Q2_0 | RustingStrata Vulkan | 2997.4 (1208.2-4786.5) | 4963.2 | 281.7 / 269.7 | +| 2B Q2_0 | llama.cpp CUDA | 7089 | 7207 | 288.8 (empty context) | +| 9B PTQ1_0 | RustingStrata CUDA | 1126.7 | 1141.8 | 46.1 / 46.0 | +| 9B PTQ1_0 | RustingStrata Vulkan | 1032.7 | 1083.5 | 33.8 / 33.2 | +| 9B Q2_0 | RustingStrata CUDA | 1220.3 | 1263.4 | 77.3 / 74.6 | +| 9B Q2_0 | RustingStrata Vulkan | 1150.9 | 1097.5 (1006.9-1188.1) | 75.5 / 63.4 | +| 9B Q2_0 | llama.cpp CUDA | 2001 | 1975 | 98.0 (empty context) | + +- llama.cpp cannot run PTQ1_0, so on these files RustingStrata is the only one of the two. +- On Q2_0, llama.cpp prefills 1.4 to 1.6 times faster and decodes the 9B 1.27 times faster. The 2B decodes at the + same speed. +- PTQ1_0 is 22% smaller than Q2_0 but decodes slower here. + +Quality vs llama.cpp is in [MODELS.md](MODELS.md#ternary-bonsai-2-2b-and-9b-ptq1_0): 637 of 640 top tokens agree for +each file. + +Caveats: two runs a cell. The first run of a cell includes warm-up, which gives the wide ranges. ## Not yet measured @@ -283,4 +693,13 @@ IQ4_NL expert matvec (105 to 270 GB/s on 8 experts of 2304x2304). ## Adding an entry -One section per model and file. Give the machine, the file, the llama.cpp build and flags, the RustingStrata command, the number of runs, and what is not equal between the engines. Put raw logs next to the other results in `docs/` or link them. +Write one section per model and file. Give: + +1. The machine. +2. The file. +3. The llama.cpp build and flags. +4. The RustingStrata command. +5. The number of runs. +6. What is not equal between the engines. + +Put raw logs next to the other results in `docs/` or link them. diff --git a/docs/CALIBRATION.md b/docs/CALIBRATION.md new file mode 100644 index 00000000..47c0922c --- /dev/null +++ b/docs/CALIBRATION.md @@ -0,0 +1,129 @@ +# Calibration + +`rustingstrata calibrate` measures which prefill chunk, MTP draft count and short-prompt threshold are fastest for one +model on this machine. It writes them to `strata-.json` in the cache folder, and later runs read that file. + +```bash +rustingstrata calibrate --model model.gguf + +# Live panel: percent done, samples left, ETA +rustingstrata calibrate --model model.gguf --pretty --status-interval 250ms + +# Two tasks, and a trace of every sample +rustingstrata calibrate --model model.gguf --task prose --task coding --pp 128,512,2048 --tg 128 --samples 32 \ + --out ./calib-reports + +# Every .gguf in a folder and its subfolders; a model that fails is reported and the rest go on +rustingstrata calibrate --model ~/models +``` + +One run per model, backend and device combination is enough. Every supported architecture is measured. + +## Flags + +| Flag | Default | Meaning | +|---|---|---| +| `--samples N` | 24 | Most samples of the search. A failed sample counts. | +| `--minutes M` | 30 | Time limit of the search, 0 = none. The best point so far is written, stop reason `time`. | +| `--timeout SECS` | 0 (none) | Time limit of one sample. | +| `--reps N` | 2 | Repetitions inside one sample. Their mean is used. | +| `--warmup N` | 0 | Extra discarded run before each sample. It loads the model a second time. | +| `--pp A,B,C` | `128,512,2048` | Prompt depths. | +| `--tg N` | 64 | Decoded tokens. | +| `--task LABEL` | `prose` | `prose`, `coding` or `user:PATH` (your own prompt file). Repeatable. | +| `--chunk-values A,B` | `256,512,1024,2048,4096` | Prefill chunks to search. | +| `--seed N` | 1 | The same seed gives the same search. | +| `--dry-run` | off | Print the workloads and the values to search. Load nothing. | +| `--out DIR` | none | Also write every sample to `DIR/strata--calib-report.json`. | +| `--pretty`, `--status-interval T` | off | Live panel, and how often it updates. | +| `--mtp-model`, `--draft-model` | none | Measure with that draft file. Needs a single model file. | +| `--ctx`, `--kv` | 4096, f16 | Conditions of the measurement, not searched. | +| `--k`, `--v`, `--ple`, `--threads`, `--cache-ram`, `--ram-margin`, `--max-ram`, `--arena`, `--pin`, `--prefill-cpu`, `--cpu-frac`, `--host-share` | as the other commands | Passed to every measurement. Give the ones you run the model with. | + +The baseline runs first and is outside `--samples`. Calibrate then prints how long the whole budget would take. + +With several GPUs (`--device 0,1`) calibrate keeps the free-VRAM layer split. `--split` is ignored with a note. + +## What is searched + +| Value | Searched | Applies to | +|---|---|---| +| `chunk` | `--chunk-values` | Main engine, Gemma 4, GLM, Hy4, Kolibri, Inkling 2 (capped at 256). DeepSeek has none. | +| `mtp` | `0,1,2,4` | Main-engine models with a draft head, otherwise `0` only. | +| `short` | 32 and one value just above each `--pp` depth (default `32,129,513,2049`) | Main engine only. | + +A prompt shorter than `short` prefills one token at a time. Context length and KV format are never searched. + +Each candidate is scored against the baseline, a run without a calibration file: + +``` +score = sqrt((prefill / baseline_prefill) · (decode / baseline_decode)) +``` + +- The baseline uses the default chunk, short-prompt threshold 32, the physical core count and no drafts. +- That chunk is 4096 for the main engine, 256 for Gemma 4, 512 for GLM, 1024 for Hy4 and Kolibri. For Inkling 2 + `calibrate` starts from 256. +- Another chunk is searched only when the longest `--pp` depth reaches the default chunk. +- A candidate wins when it is more than 2% better than the baseline. If none is, the file holds the baseline's + settings with score 1.02. +- If the baseline fails, calibrate warns and writes a file only when a point beats a neutral reference. + +## Speculative decoding: `calibrate spec` + +`calibrate spec` finds the best spec type and draft count for each task. + +```bash +rustingstrata calibrate spec \ + --model ~/Models/Inkling2/Inkling-2-Mini-UD-Q3_K_XL.gguf \ + --draft-model ~/Models/Inkling2/dspark-Inkling-2-Mini-Q8_0.gguf \ + --tasks prose,coding --spec-types ngram-simple,ngram-mod,ngram-cache \ + --draft-max 4,8,16 --ngram-n 3,6,12 --samples 16 +``` + +| Flag | Values | +|---|---| +| `--spec-types` | `none`, `suffix`, `ngram-simple`, `ngram-map-k`, `ngram-map-k4v`, `ngram-mod`, `ngram-cache` | +| `--draft-max` | Drafts verified per step. | +| `--ngram-n` | Lookup key length. | + +The MTP count is searched too, on the main engine only. The baseline is `none`, 16 drafts, n-gram 12, mtp 0. Each +task's winner goes under `spec` in the same calibration file. Nothing else in the file changes. + +## The calibration file + +The file is `~/.cache/rusting_strata/strata-[-backend][-dev…].json`. `XDG_CACHE_HOME` moves the folder. The +name holds the backend that opened and the device order (`-vulkan`, `-dev0-1`). + +| Field | Meaning | +|---|---| +| `schema` | 2 | +| `arch` | Architecture of the model. | +| `chunk`, `mtp`, `short` | The values later runs read. A DeepSeek file has none. | +| `ctx` | Context of the measurement. Later runs do not apply it. | +| `gpu`, `bytes` | GPU and model file size of the measurement. | +| `aux` | Draft file of the measurement. | +| `measured` | `prefill_tok_s` and `decode_tok_s` of the winner. | +| `best` | The winner's `chunk`, `mtp` and `short`. | +| `search` | `samples_used`, `score`, `stop_reason`, `elapsed_ms`, `seed`. | +| `workloads` | `pp`, `tg` and `task` of each workload. | +| `spec` | Per task: `spec_type`, `draft_max`, `ngram_n`, `acceptance_pct`. | + +The file has no `kv`, `threads` or `split` key. + +## Run again, or ignore the file + +- Run calibrate again after you change the GPU, the driver, the quant, the KV format or the draft file. +- A file measured on another GPU, or on a same-name model file of another size, is ignored with a warning. +- A flag wins over the file: `--chunk`, `--mtp`, `--short`. +- To go back to the defaults, delete the file. + +## Environment variables + +Gemma 4, GLM, Hy4, Kolibri and Inkling 2 take the calibrated chunk through these variables. A value you set yourself +wins over the file. + +| Variable | Prefill chunk of | +|---|---| +| `STRATA_G4_CHUNK` | Gemma 4 | +| `STRATA_GLM_CHUNK` | GLM | +| `STRATA_DS_CHUNK` | Hy4, Kolibri, Inkling 2 | diff --git a/docs/DEEPSEEK_L40S.md b/docs/DEEPSEEK_L40S.md new file mode 100644 index 00000000..99fffbb2 --- /dev/null +++ b/docs/DEEPSEEK_L40S.md @@ -0,0 +1,131 @@ +# DeepSeek-V4.1 on 2x L40S + 1 TB RAM + +Not yet measured on L40S. The settings follow from the code and from the synthetic 2-layer test +(`tests/deepseek_synthetic.rs`, run on one RTX 3060 listed twice). Measure on the real host before you trust them, and +add the numbers to [BENCHMARKS.md](BENCHMARKS.md) with their conditions. + +## Recommended command + +```bash +M=/models/DeepSeek-V4.1-Flash.gguf # the first shard of a split GGUF also works +rustingstrata serve --model $M --gpu --device 0,1 --threads --addr 0.0.0.0:8080 +``` + +```bash +# quick speed check with the per-token profile +STRATA_DS_PROF=1 rustingstrata bench --model $M --gpu --device 0,1 --pp 512,4096 --tg 128 +``` + +What the model supports is in [MODELS.md](MODELS.md). All flags are in [USAGE.md](USAGE.md). + +## Settings + +Plain weights are the non-expert weights. The weight budget is the plain weights plus the expert cache. + +| Flag or variable | Default | What it does | +|---|---|---| +| `--gpu` | on | DeepSeek uses the GPU with or without this flag. | +| `STRATA_DS_GPU` | `1` | `0` runs everything on the CPU, which is slow. | +| `--device 0,1` (`STRATA_DS_DEVICES`) | every CUDA device | The GPUs to use. | +| `--threads N` | one per physical core | CPU threads. The CPU computes the experts that miss VRAM. | +| `--ctx N` (`STRATA_DS_CTX`) | the trained context | Prompt plus reply limit in tokens. | +| `STRATA_DS_GPU_FRACTION` | `0.95`, or `0.8` on a card with less than 8 GB free | Share of free VRAM for the weight budget. | +| `STRATA_DS_GPU_EXPERTS` | unset | The weight budget in GB, split between the GPUs in proportion to their free VRAM. | +| `STRATA_DS_ROOM_GB` | free VRAM less the expert cache and 768 MB | GB of plain weights a GPU takes before the layers move on to the next GPU. | +| `STRATA_DS_CHUNK` | `512` | Prefill tokens per chunk. Larger means fewer weight passes and more scratch memory. | +| `STRATA_DS_CPU_SHARE` | adapts per layer | Share of the VRAM misses that the CPU computes, 0 to 1. Set it only to test a fixed split. | + +- To balance the two cards, set `STRATA_DS_ROOM_GB` to about half of the plain-weight total. A layer's plain weights + and its attention stay on one GPU. +- `STRATA_DS_CHUNK`: a larger chunk gives each routed expert more tokens per weight read. With 384 experts and 6 used, + 512 gives each expert about 8 tokens. 2048 gives about 32, if the scratch memory fits. + +## Check after start + +- The log has a `cuda device N: ...` line for each GPU. +- `STRATA_DS_PROF=1` prints one line per forward pass: the time in `experts` and `attn`, `gpu-round-trips`, + `vram-expert-lookups hit` and `miss`, and `disk_read_MB`. +- With 1 TB of RAM the page cache holds the whole GGUF. Experts that miss VRAM are then read from RAM, not from disk. +- `gpu-round-trips` counts the host-device synchronizations per token. Each one waits for the GPU, so fewer is better. + The count grows with the layer count. The synthetic 2-layer model reports 11 per decoded token on one GPU and 14 + with the layers split over two device entries. + +## CPU threads + +The experts that miss VRAM run on the CPU. On this host the CPU sets much of the decode speed, and most of the prefill +speed when the expert cache is small. Time the CPU expert kernels on the serving host: + +```bash +cargo run --release --example ds_cpu_bench -- IQ2_XXS,Q4_K 8 +``` + +It needs no model file and no GPU. It prints three numbers per quant type: the one-thread dot rate, the decode expert +step and the prefill step. Run it with the physical cores of one socket, of both sockets, and with the logical count. +Then try the same counts with `rustingstrata bench ... --threads N` and keep the fastest. + +Measured on the development machine only (Ryzen 5 7600X, 6 cores and 12 threads): + +- The SMT threads made the CPU expert step 4% to 16% faster in decode and 9% to 21% faster in prefill. The full + DeepSeek model with SMT threads is not measured. +- IQ2_XXS is compute-bound on the CPU, so more cores help in a near-linear way. Q4_K stops at the memory bandwidth. + +## NUMA + +Not measured on two nodes. `numactl --interleave=all` is the reliable way to spread the model's pages over both +sockets. Try it against one socket alone: + +```bash +numactl --interleave=all rustingstrata serve ... +numactl --cpunodebind=0 --membind=0 rustingstrata serve ... --threads +echo 3 > /proc/sys/vm/drop_caches # between the two runs, so the second reads the file under its own policy +``` + +Choose the second only if the model fits in the RAM of one node. + +Without `numactl`, RustingStrata reads the GGUF into the page cache at load with one reader thread per CPU. The pages +should then spread over both sockets, but the scheduler decides where the reader threads run. + +## Build + +The release binary is built for x86-64-v3 (AVX2). On a CPU with AVX-512VL and VNNI it picks a copy of the prefill +kernels for those features at run time, with the same result bits. A local build uses `-C target-cpu=native`. + +Prefill step of `ds_cpu_bench` on the development machine, 6 threads, 48 experts x 8 tokens. The columns are the +release binary's AVX2 kernels alone, the release binary with the run-time copy, and a native build: + +| Quant | x86-64-v3 kernels | With the run-time AVX-512VL copy | Native build | +|---|---|---|---| +| Q2_K | 27.7-27.8 ms | 21.6-22.1 ms | 19.0-20.3 ms | +| IQ1_M | 42.0-42.4 ms | 36.0 ms | 34.9-35.0 ms | +| IQ2_XXS | 30.2-31.1 ms | 29.1-29.5 ms | 27.3-27.5 ms | +| Q4_K | 32.9-34.6 ms | 35.2-35.5 ms | 28.5-29.2 ms | + +The build does not change decode: the memory bandwidth limits it. + +## Problems + +| What you see | What to do | +|---|---| +| The KV rows or the prefill scratch run out of memory on a long context | Lower `STRATA_DS_GPU_FRACTION`. | +| `GPU N: ...; running without it` in the log | A GPU did not open, so the whole model runs on the CPU. Fix that GPU or leave it out of `--device`. | +| The GGUF has MXFP4 experts | Not supported. Use an IQ2_XXS, Q2_K, Q4_K or other GGML k-quant or i-quant GGUF. | +| Decode is much slower than llama.cpp on the same host | Collect the output below. | + +```bash +STRATA_DS_PROF=1 rustingstrata bench --model $M --gpu --device 0,1 --pp 512 --tg 64 --threads +cargo run --release --example ds_cpu_bench -- IQ2_XXS,Q4_K 8 +``` + +Run both with N = the physical cores of one socket, of both sockets, and the logical count. Compare the decode GB/s +of `ds_cpu_bench` with the bandwidth of one socket (from `mlc` or STREAM). Add the llama.cpp command line and its +tokens per second, so both run the same quant and the same expert split. + +## Test and tuning switches + +| Name | What it does | +|---|---| +| `STRATA_DS_PROF=1` | Prints per-token timings and `gpu-round-trips`. | +| `STRATA_DS_CPU_ATTN=1` | Attention on the CPU with f32 keys. For checking only. | +| `STRATA_Q4K_X8=0` | Turns off the 8-row prefill kernels. | +| `STRATA_AVX512=1` | Selects the 512-bit kernels of a binary built with `-C target-feature=+avx512f,+avx512bw,...`. Not faster on Zen 4, so do not build for them there. Not measured on Intel Xeon. | +| `STRATA_BENCH_GAP_US=300` | `ds_cpu_bench` only: idles 300 us before each timed run. | diff --git a/docs/HIP.md b/docs/HIP.md new file mode 100644 index 00000000..79dca90a --- /dev/null +++ b/docs/HIP.md @@ -0,0 +1,277 @@ +# HIP (ROCm) backend + +`--backend hip` runs RustingStrata on an AMD card through ROCm. Status: experimental. It was brought up on one card, +an RX 9070 XT (gfx1201) with ROCm 7.2.3. Every number in this file was measured on that card. + +The Vulkan backend on AMD cards is in [AMD.md](AMD.md). The tested cards are in [SUPPORTED_GPUS.md](SUPPORTED_GPUS.md). + +## Requirements + +- A ROCm runtime with hiprtc: `libamdhip64.so` and `libhiprtc.so`. +- An RDNA card (wave32, gfx10+). +- For the matrix cores: a gfx11 or gfx12 target. Other targets run the slower CUDA-core paths. + +You do not need `hipcc`, ROCm headers or a C++ build step. `cargo build --release` is the whole build. hiprtc compiles +the kernels at run time. The result is cached in `$XDG_CACHE_HOME/rusting_strata/.amdgcn`. + +RustingStrata looks for the two libraries on the loader path, then in `/opt/rocm/lib`, `/usr/lib/x86_64-linux-gnu` +and `/usr/local/lib`. It also tries the names that end in `.so.7` and `.so.6`. + +| Variable | What it does | +|---|---| +| `STRATA_HIP` | Path or name of `libamdhip64.so`. Replaces the search. | +| `STRATA_HIPRTC` | Path or name of `libhiprtc.so`. Replaces the search. | +| `STRATA_HIP_ARCH` | The card's `gfx` target, for example `gfx1201`. Default: read from the driver. | + +## Run + +```bash +rustingstrata serve --model model.gguf --gpu --backend hip +rustingstrata bench --model model.gguf --gpu --backend hip --pp 4096 --tg 48 +# measure chunk, MTP drafts and the short-prompt threshold once; later runs read strata--hip.json +rustingstrata calibrate --model model.gguf --backend hip +``` + +HIP is never picked on its own. Without `--backend hip`, CUDA opens when it loads, else Vulkan. The first line of +output names the card: `hip: (, wave32, B shared memory a block)`. Every other flag is in +[USAGE.md](USAGE.md). + +## What works and what does not + +HIP runs everything the Vulkan backend runs. + +- Models tried: Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B (dense), Qwen3.8-27B (dense), GigaChat 4 37B-A4B and + Inkling 2 Mini. +- `serve`, checked on Qwen3.5-9B: `GET /v1/models`, chat completions with and without `stream: true`, and the prompt + cache across turns (`prompt_tokens_details.cached_tokens` on a follow-up request). + +Not supported: + +- A model split over two cards. `--device 0,1` is refused. Use CUDA or Vulkan for a split. +- A card that reports a 64-wide wave. It is refused. Use `--backend vulkan`. +- GigaChat 4 with the default expert budget on a 16 GB card. See + [Run GigaChat 4 on a 16 GB card](#run-gigachat-4-on-a-16-gb-card). + +## Output compared with Vulkan + +For a repeatable run use `--fixed-experts --mtp 0`. With these two flags: + +- Decode: greedy output is bit-identical to Vulkan on the first four models above. +- Batched prefill: output can differ at a near-tie. Of long prose prompts (64-79 tokens), 4 of 5 agree token for + token on the 35B, 2 of 2 on the dense 9B and 1 of 2 on the dense 27B. + +With the calibrated MTP drafts on, the two backends verify different batch shapes, and 1 of 7 such probes flips too. + +Inkling 2 output under `--fixed-experts` must stay bit-identical to Vulkan. For that reason the flag keeps the older +kernels and the expert slabs. Without it, greedy text can differ at a near tie. See [Inkling 2](#inkling-2). + +## Speed + +One process each. Other backends and cards are in [BENCHMARKS.md](BENCHMARKS.md). + +Short prompts: Qwen3.6-35B-A3B UD-Q4_K_XL (first two rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`. +`calibrate` was run for each backend (chunk 4096; HIP picks `--mtp 3`, Vulkan `--mtp 1`). + +| | HIP | Vulkan (same machine, same model) | +|---|---|---| +| Prefill, pp 1024 / 4096, calibrated | 1104 / 2993 tok/s | 1097 / 2325 tok/s | +| Decode, tg 48, calibrated | 209 / 219 tok/s | 199 / 163 tok/s | +| Qwen3.8-27B dense, pp 1024, prefill / decode | 784 / 39.1 tok/s | 508 / 35.3 tok/s | + +The decode row is the decode that follows each prompt. The pp 1024 run is the first in the process, before expert +placement settles, so it understates both backends. HIP measured 1577-2072 tok/s there when it was not the first run. + +Long prompts: Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`, `--fixed-experts`. A range +is two runs. + +| pp | HIP | Vulkan | HIP, everything on the CUDA cores (`STRATA_HIP_WMMA=0`) | +|---|---|---|---| +| 8192 | 2647-2666 tok/s | 2148-2152 tok/s | 1303-1308 tok/s | +| 32768 | 2026-2029 tok/s | 1661 tok/s | 776-794 tok/s | +| 131072 | 872 tok/s | 731 tok/s | (not run) | +| decode at 8k / 32k / 128k | 68-73 / 64 / 48 tok/s | 71-72 / 68 / 44 tok/s | 74 / 64-65 / - | + +A 128k prompt costs more VRAM in the KV cache than a 16 GB card has left for experts, so most experts stream from +host memory. A shorter `--ctx` or `--kv q8` gives expert slots back. Token-by-token prefill (`--chunk 0`) does not +help. + +## Run GigaChat 4 on a 16 GB card + +```bash +STRATA_DS_GPU_EXPERTS=4 rustingstrata serve --model GigaChat4-37B-A4B-Q4_K_M.gguf --backend hip --mtp 0 +``` + +GigaChat 4 37B-A4B Q4_K_M (23 GB) does not fit in VRAM. The plain weights and part of the experts sit on the card. +The rest of the experts are streamed to it or run on the CPU. The model is described in [MODELS.md](MODELS.md). + +On HIP, cap the expert cache by hand with `STRATA_DS_GPU_EXPERTS`. The default budget (95% of free VRAM) fills the +card: the cache takes about 1.6x the bytes it counts, and about 1.6 GiB of scratch and state is outside the budget. + +| `STRATA_DS_GPU_EXPERTS` | Result | +|---|---| +| unset | A 512-token prompt ran at 29.6 tok/s and decode at 15.5 (with the host-side fallback of the next table). | +| `8` | Reached 14.5 GiB of the 16 GiB within the first prompt chunk. | +| `4` | Peaks at 7.9 GiB including 1.1 GiB held by the desktop. | + +`bench --backend hip --ctx 8192 --mtp 0 --pp 4096 --tg 4 --reps 1`, `STRATA_DS_GPU_EXPERTS=4` unless noted, one run +each. The last row is the default. `STRATA_MLA_SIMT=1` selects the one-wave-a-head kernel, with the same greedy output. + +| | pp 4096 (tok/s) | decode after it (tok/s) | +|---|---|---| +| MLA through the host-side fallback (`mla_heads`) | 137.2 | 18.3 | +| fused MLA, one-wave-a-head kernel (`mla_qpack`) | 198.4, 200.5 | 18.9 | +| fused MLA on the matrix cores (`mla_attn_wmma`) | 338.7 | 19.9 | + +Long prompts, same settings with `--ctx` set to fit. The rows "indexer grid fixed" and "`idx_score_dec`" are the +default. + +| | pp 32768 | pp 65536 | +|---|---|---| +| prefill, one-wave-a-head kernel | 162.3 tok/s | - | +| prefill, `mla_attn_wmma` | 272.8 tok/s | 203.0 tok/s | +| decode after the prompt, `mla_attn_wmma` | 11.9 tok/s | 9.2 tok/s | +| prefill, indexer grid fixed | 319.4 tok/s | 274.8 tok/s | +| decode, `idx_score_dec` | 17.4 tok/s | 16.1 tok/s | +| prefill, `STRATA_IDX_WMMA=1` | 372.1 tok/s | - | +| peak VRAM, including 1.1 GiB of desktop | 8.4 GiB | 9.2 GiB | + +`STRATA_IDX_WMMA=1` computes the indexer scores of a prompt on the matrix cores, with f16 products. Where scores are +close, it changes which keys a query selects. On a 3k-token prompt, 24% of the top-2048 key sets are identical to the +default f32 kernel's. The mean overlap is 99.7% and the lowest 77%. Greedy output flips at the first near-tie, so the +switch is off by default. + +Fix `STRATA_DS_CPU_SHARE` for a repeatable run. By default the CPU's share of the missed experts adapts to timing, +and the CPU computes them at a different precision. Two default runs can differ after a near-tie. + +### Faster prefill + +- `STRATA_DS_PIN=1` page-locks the experts in the mapped model file at load (93 tensors, 21.2 GB, 2.0 s). The pages + stay locked in RAM for the life of the process, so it is off by default. Greedy output does not change. +- `STRATA_DS_CHUNK` sets the prompt chunk in tokens (default 1024). With `STRATA_DS_PIN=1` and budget 4, more than + 1536 does not help: 447.2 tok/s at 2048, 448.1 at 3072 and 411.8 at 4096. + +At pp 4096, `--ctx 5120`, one run each: + +| | prefill (tok/s) | decode (tok/s) | peak VRAM | +|---|---|---|---| +| `STRATA_DS_GPU_EXPERTS=4`, chunk 1024 | 335.9 | 19.3 | 7.9 GiB | +| budget 4, `STRATA_DS_CHUNK=1536` | 365.8, 368.9 | 19.6, 19.4 | 8.1 GiB | +| budget 6, chunk 1024 | 338.0 | 20.7 | 11.3 GiB | +| budget 6, chunk 1536 | 383.5 | 20.8 | 11.5 GiB | +| budget 4, chunk 1536, `STRATA_DS_PIN=1` | 452.0 | 24.7 | 8.1 GiB | + +## Inkling 2 + +Inkling 2 Mini UD-Q4_K_XL, 9070 XT, X470 (PCIe 3.0) with dual-channel DDR4 (36 GB/s read). The model and its command +are in [MODELS.md](MODELS.md). + +### Expert pool + +By default every layer keeps its most used experts in VRAM, and the CPU computes the rest. The routing counts are +saved as `~/.cache/rusting_strata/inkling2-profile-*.f32` when the model unloads. They place the experts of the next +load, so the first run of a model is slower. + +| 12 GB weight budget, desktop holds 3 GB | pp 512 | pp 4096 | decode | +|---|---|---|---| +| slabs and hybrid layers | 443 tok/s | 438 tok/s | 39.8 / 38.9 tok/s | +| pool, no profile yet | 329 | 378 | 49.7 / 55.7 | +| pool, profile of one earlier run | 436 | 426 | 60.5 / 58.9 | + +Decode is the decode after the prompt of each column. With the pool, greedy text is not bit-identical to Vulkan. +`--fixed-experts` keeps the slabs, and its text is. `STRATA_INK_SLABS=1` keeps the slabs and pools only the layers +they leave out. + +A slab is a layer with all 128 experts in VRAM. The first row above is this older layout. Its decode, with +`bench --pp 512 --tg 64`, before and after changes to the expert split and the VRAM cache: + +| | 18 slabs (desktop holds 3.3 GB) | 22 slabs (desktop idle) | +|---|---|---| +| before | 34.5 tok/s | 48.2 tok/s | +| after | 39.5 tok/s | 51.8 tok/s | + +### Prompt chunk size + +`STRATA_DS_PF_TOKENS` sets the rows of a prompt chunk (default 2048 on one card). The scratch costs about 0.55 GB of +VRAM per 1024 rows. The chunk halves when it does not fit. + +9.5 GB weight budget, desktop at 2.2 GB, `bench --pp 512,4096 --tg 32`: + +| rows | pp 512 | pp 4096 | decode | peak VRAM, card | +|---|---|---|---|---| +| 256 | 265 tok/s | 278 tok/s | 49.5 tok/s | 13.47 GB | +| 2048 | 387 | 767 | 48.9 | 14.61 GB | +| 4096 | 393 | 891 | 48.8 | 15.48 GB | + +The code clamps `STRATA_DS_PF_TOKENS` to 2048, so this build cannot repeat the 4096 row. + +`STRATA_INK_PIN=1` page-locks the pooled experts in the mapped file (15.8 GB in 1.8 s): pp 4096 855 tok/s, decode +51-53. That much RAM stays locked while the model is loaded, so it is off by default. + +### Faster kernels + +By default HIP runs Inkling 2 on the faster attention and controller kernels. They sum in another order, so greedy +text can differ from the older kernels and from Vulkan at a near tie. `--fixed-experts` keeps the older kernels. +`STRATA_DS_FAST_KERNELS=0` selects the older kernels, and `1` the faster ones under `--fixed-experts` too. + +`bench --pp 512,4096 --tg 64`, alternating runs with a browser open on the desktop: + +| | pp 4096 | decode | +|---|---|---| +| older kernels | 701, 908, 1001 tok/s | 51-62 tok/s | +| faster kernels | 1531, 1648, 1686 tok/s | 52-66 tok/s | + +## Errors + +| Message or symptom | Fix | +|---|---| +| `no HIP runtime: ...` | Install the ROCm runtime, or point `STRATA_HIP` at `libamdhip64.so`. | +| `hiprtc is required to compile the kernels` | Install hiprtc, or point `STRATA_HIPRTC` at `libhiprtc.so`. | +| `hipInit: ...` | Check that `rocminfo` lists the card and that your user can open `/dev/kfd`. | +| `cannot read the device's gfx architecture; set STRATA_HIP_ARCH (e.g. gfx1201)` | Set `STRATA_HIP_ARCH`. | +| `HIP backend needs wave32; reports warp size 64` | Use `--backend vulkan`. | +| `HIP device N: M device(s) present` | Pass a `--device` index that exists. | +| `the hip backend runs one device: --device 0,1 needs cuda or vulkan` | Pass one index, or use CUDA or Vulkan. | +| `--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)` | Drop one of the two flags. | +| `hiprtc (): ...` and a compiler log | Open an issue with the full output. | +| A fault that names no kernel | Rerun with `STRATA_HIP_SYNC=1`, or `STRATA_HIP_TRACE=1` if the process dies. | +| Output you suspect the matrix cores of | Compare with `STRATA_HIP_WMMA=0`. | +| VRAM fills with GigaChat 4 | Set `STRATA_DS_GPU_EXPERTS=4`. | + +## Switches + +Environment variables for tests and tuning. + +| Variable | What it does | +|---|---| +| `STRATA_HIP_WMMA=0` | CUDA cores instead of matrix cores in prefill. Prefill at pp 1024: 737 tok/s, against 1684. | +| `STRATA_HIP_GRAPH=0` | Runs the forward every time. By default it is captured (+5% decode). | +| `STRATA_NO_GRAPH=1` | Turns capture off for both GPU backends. | +| `STRATA_HIP_SYNC=1` | Waits after every launch, so a hardware exception names its kernel. | +| `STRATA_HIP_TRACE=1` | Prints every launch before it goes out (grid, block, shared memory). | +| `STRATA_FIXED_EXPERTS` | Same as `--fixed-experts`. | +| `STRATA_DS_GPU_EXPERTS=N` | Weight budget in GB (plain weights and expert cache). | +| `STRATA_DS_CPU_SHARE=X` | Fixes the CPU's share of the experts that miss the cache. | +| `STRATA_DS_PROF=1` | Prints timers of the forward (route, experts, attention). | +| `STRATA_DS_CHUNK=N` | GigaChat 4: prompt chunk in tokens. | +| `STRATA_DS_PIN=1` | GigaChat 4: page-locks the routed experts (about 21 GB of RAM). | +| `STRATA_MLA_SIMT=1` | GigaChat 4: MLA prompt attention on the one-wave-a-head kernel. | +| `STRATA_IDX_WMMA=1` | GigaChat 4: prompt indexer scores on the matrix cores. | +| `STRATA_GIGA_CPU_ATTN=1` | GigaChat 4: MLA attention on the CPU. Output matches the GPU until the first near-tie. | +| `STRATA_DS_FAST_KERNELS` | Inkling 2: `0` older kernels, `1` faster kernels. | +| `STRATA_CTRL_TILE=0`, `STRATA_DS_ATTN_OLD=1`, `STRATA_DS_ATTN_KP4=1` | Inkling 2: per-kernel overrides. See [USAGE.md](USAGE.md). | +| `STRATA_INK_SLABS=1` | Inkling 2: slabs, and a pool only for the layers they leave out. | +| `STRATA_INK_PIN=1` | Inkling 2: page-locks the pooled experts. | +| `STRATA_DS_PF_TOKENS=N` | Inkling 2: rows of a prompt chunk. | +| `STRATA_RPW`, `STRATA_RPW_MOE`, `STRATA_RPW_DENSE` | GEMV rows per warp: all, MoE or dense. | +| `STRATA_GEMV_BLOCK`, `STRATA_GEMV_BLOCK_MOE`, `STRATA_GEMV_BLOCK_DENSE` | Threads per block of the integer GEMV. | +| `STRATA_GEMV_LOADW` | Load width of the GEMV kernels, `0` or `1`. | + +## Credits + +The compatibility shim `src/hip/compat.h` follows the structure and several implementations of +`include/strata/hip_compat/intrinsics.hpp` from the Strata project (MIT, (c) 2025 Niko1221, +https://github.com/Niko1221/Strata). See [THANKS.md](../THANKS.md). + +Strata also has prompt attention on the matrix cores (`src/kernels/cuda/qsa_prompt_attn.cu`) and a chunked gated +delta-rule scan (`gdn_chunk.cu`, `gdn_tc.cuh`, `gdn_wmma12.inc`). The matrix-core attention in this backend was +written independently and matches that work in a different design. The chunked scan was measured and not ported. diff --git a/docs/HOSTING.md b/docs/HOSTING.md index 0108692c..619c01b1 100644 --- a/docs/HOSTING.md +++ b/docs/HOSTING.md @@ -1,109 +1,23 @@ # Hosting RustingStrata for other people -This page is for running `rustingstrata serve` as a service that other people or programs use over the network, for -example to sell API access to a model. It covers keys, TLS through a reverse proxy, a systemd unit, health checks, -the usage log for billing, and how many requests one server answers at once. +How to run `rustingstrata serve` for other people, for example to sell API access to a model. Flags that are not +about hosting are in [USAGE.md](USAGE.md). -The [license](../LICENSE.md) allows commercial services built on RustingStrata: you can charge for access to a model that -RustingStrata serves. Keep the license and the credit to the original author. You may not sell RustingStrata itself. The model has -its own license (most Qwen models are Apache 2.0; check the model card). - -## How much one server does - -By default `rustingstrata serve` answers one chat request at a time. Others wait in a queue and run in arrival order. -The queue has no limit unless `--max-waiting N` sets one. Set one on a server that strangers can reach: every waiting -connection holds a socket and a thread. `--max-waiting` counts every open connection (being read, -generated or queued, health checks included), so with `--max-waiting 16` and one reply running 15 places are left -for the queue. Beyond it a connection gets -`503 Service Unavailable` with `Retry-After: 2` (`--max-per-key` keeps one customer from taking all the places). One -request decodes at -the speed in the README (about 113 tok/s for Qwen3.6-35B-A3B Q2_K_XL on an RTX 3060), so that is also the total for -all users of one server. Long prompts block the queue for their prefill time (about 2 s for 4K tokens on the 3060). - -### Several requests at once: `--parallel` - -`--parallel N` keeps N conversations in GPU memory and decodes them together: the requests that are decoding share -each forward pass, up to 4 at a time. A pass reads the attention, recurrent and shared-expert weights once for all -its requests; only the routed experts each request picks are read per request. On the RTX 3060 below, a pass takes -10.6 ms for one request, 15.3 ms for 2 and 25 ms for 4. - -Measured on the RTX 3060 with Qwen3.6-35B-A3B Q2_K_XL, `--ctx 4096`, short prompts and 200-token replies, all -requests sent at once: - -| `--parallel` | Requests | Total | Each request | -|---|---|---|---| -| 1 | 4 | 90 tok/s | one after the other | -| 2 | 2 | 139 tok/s | 69 tok/s | -| 4 | 4 | 164 tok/s | 41 tok/s | -| 4 | 8 | 163 tok/s | 41 tok/s, 4 wait | -| 8 | 8 | 149 tok/s | 19 tok/s | - -A request alone on a `--parallel 4` server decodes at 105 tok/s (106 with `--parallel 1`). - -The gain is smaller for a model whose experts mostly do not fit in VRAM, because the requests in a pass route to -different experts and the CPU computes the missing ones for each. Qwen3-Next-80B-A3B IQ1_S on the same 3060 (9199 -of 24576 experts resident with 4 slots), 4 requests: 56.5 tok/s with `--parallel 1`, 77.5 tok/s with -`--parallel 4`. - -What changes with `--parallel N`: - -- **Memory.** `--ctx` is the context of each slot, so the KV cache and the recurrent state take N times the memory - of one, and fewer experts fit in VRAM. The `plan:` line at start shows the split. With 8 slots of 4096 tokens the - 35B model kept 7008 of its 10240 experts resident. A long `--ctx` costs the most here, and `--kv q8` gets much of - it back. `--parallel 4`, 4 short requests at once on the 3060: - - | `--ctx` | `--kv` | KV for 4 slots | Resident experts | Total | - |---|---|---|---|---| - | 16384 | f16 | 1280 MB | 6876 of 10240 | 160 tok/s | - | 32768 | f16 | 2560 MB | 5567 | 114 tok/s | - | 32768 | q8 | 1360 MB | 6779 | 154 tok/s | - - `--kv q8` is about 6% slower to decode and 14% slower to prefill at 32K of actual context, so it pays off when the - memory it frees holds experts. Greedy output can differ from `--kv f16` at near-ties. -- **Queue.** When every slot is busy, requests wait. A free slot goes to the waiting request whose key holds the - fewest slots, the oldest first among those, so one customer who sends 20 requests at once does not hold back - another customer's one. Without `--api-keys` the queue is first come, first served. -- **More than 4 slots** do not raise the total, because one pass decodes at most 4 requests. They let more users - stream at the same time instead of waiting in the queue, each at a lower speed. -- **Prefill.** Prompts are prefilled one at a time, in chunks (`--chunk`, from `rustingstrata calibrate`). After each - chunk the requests that are decoding run for as long as the chunk took, so a long prompt and the streams share - the GPU evenly: the prompt takes about twice as long to its first token, and each stream pauses for one chunk at a - time. A smaller `--chunk` gives shorter pauses but a slower prefill. A 10K-token prompt that arrives while 3 - requests stream, on the 3060 with `--parallel 4`: - - | `--chunk` | Longest pause of a stream | First token of the long prompt | - |---|---|---| - | 4096 (calibrated) | 2.2 s | 10.2 s | - | 1024 | 0.7 s | 13.9 s | - | 512 | 0.4 s | 16.4 s | - - Prefilled in one piece, the same prompt took 6.5 s to its first token, and the three streams stopped for all of it. -- **MTP drafting is off** (`--mtp` is ignored). With several cards (`--device 0,1`), the slots work over the split - layers too (see [Several GPUs](#several-gpus)). -- **Conversation cache.** Each slot keeps the state of its last conversation, and a request that continues a - conversation goes to the slot that holds it. Other conversations are parked in host memory (`--cache-ram`) as - without `--parallel`. Keys still only reuse their own conversations. -- **Same answers.** A request decodes the same tokens as it would alone on the same server. Greedy output can still - change at near-ties from one run to the next, because the expert placement adapts to the routing it sees (as - with `--parallel 1`). -- Without `--gpu` the option is ignored: the CPU reference runs one request at a time. - -For a server with a few users at a time, `--parallel 4` gives the most total speed. Measure your own mix with your -prompts: long prompts and long contexts change the picture. - -For more users, run one server per GPU and put a load balancer in front (see [Several GPUs](#several-gpus)). +The [license](../LICENSE.md) allows commercial services built on RustingStrata. Keep the license and the credit to +the original author. You may not sell RustingStrata itself. The model has its own license (most Qwen models are +Apache 2.0; check the model card). ## Quick start On a Linux machine with an NVIDIA driver (or a Vulkan 1.3 driver): -```sh -# 1. The binary: a release binary, or build it on this machine (.cargo/config.toml builds for the local CPU). +```bash +# 1. The binary: a release binary, or one built on this machine. cargo build --release sudo install -m 755 target/release/rustingstrata /usr/local/bin/rustingstrata -# 2. A service user, a model, and the calibration for this machine (once per model and machine). It runs as the -# service user, with the --ctx and --kv of the server, because it is kept in that user's ~/.cache/rusting_strata. +# 2. A service user, a model, and the calibration (once per model and machine). Calibrate as the service user, +# with the --ctx and --kv of the server. sudo useradd --system --create-home --home-dir /var/lib/strata strata sudo usermod -aG video,render strata # GPU device access on most distributions M=/srv/models/Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf @@ -119,74 +33,136 @@ beta-corp a81e44f2c7... EOF sudo chown strata /etc/strata/keys.txt && sudo chmod 600 /etc/strata/keys.txt -# 4. Run it on the loopback address; the reverse proxy below is the only thing that faces the network. -# (systemd below runs the same command as a service.) +# 4. Run it on the loopback address. Only the reverse proxy faces the network. sudo -u strata env STRATA_API_KEY= rustingstrata serve --model $M --gpu --ctx 32768 --addr 127.0.0.1:8080 \ --api-keys /etc/strata/keys.txt --usage-log /var/lib/strata/usage.jsonl --max-tokens 4096 --parallel 4 --kv q8 \ --max-per-key 4 ``` -Clients then use the OpenAI address `https://api.example.com/v1` with their key, or the Anthropic address -`https://api.example.com` (`POST /v1/messages`). The request fields RustingStrata honors (sampling, `stop`, tools, -thinking) are listed under [Server API](USAGE.md#server-api); the usage of a streamed reply comes in its last -chunk. +Clients use `https://api.example.com/v1` (OpenAI) or `https://api.example.com` (Anthropic, `POST /v1/messages`) with +their key. The request fields are in [USAGE.md](USAGE.md). A streamed reply reports its usage in the last chunk. ## Keys -- **Admin key** (`--api-key`, or `STRATA_API_KEY` to keep it out of the process list). It can use every route: the - chat APIs, the chat page's stats, loading another model (`/api/load`, from the models folder - or by the path of any GGUF file the server can read; or a chat request whose `model` is another name of - `GET /v1/models`) and downloading models (`/api/download`). Keep it for - yourself. -- **Customer keys** (`--api-keys FILE`). One `name key` pair a line, `#` starts a comment (so a key cannot contain - `#`). Keys must be at least 16 characters, names and keys must not repeat, and the admin key must not be among - them. A customer key reaches only `POST /v1/chat/completions`, - `POST /v1/messages`, `POST /v1/messages/count_tokens` and `GET /v1/models`; other routes answer `403`. It sees - only the loaded model in `/v1/models`, and the `model` of its requests never loads another one. The name goes into - the usage log. -- **Changing the key file.** The server reads the file again when it changes, and the next request uses the new - keys; replies being generated go on. A file that cannot be read or does not parse keeps the old keys (the server - log says why). A file with no keys removes all customer keys when there is an admin key; without one it is refused, - as it is at start, because the server would be open. Write a new file and rename it over the old one, so that the server never reads it half - written: - - ```sh - sudo sh -c 'cp /etc/strata/keys.txt /etc/strata/keys.new && echo "gamma $(openssl rand -hex 24)" >> /etc/strata/keys.new \ - && chown strata /etc/strata/keys.new && chmod 600 /etc/strata/keys.new && mv /etc/strata/keys.new /etc/strata/keys.txt' - ``` - - A removed key gets `401` from its next request on. A key that stays keeps its cached conversations, even when its - line moves. To cut off a customer who used up a prepaid budget, sum the usage log per key and remove the key. +| Key | Set with | Reaches | +|---|---|---| +| Admin | `--api-key`, or `STRATA_API_KEY` to keep it out of the process list | every route | +| Customer | `--api-keys FILE` | `POST /v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/tokenize`, `/detokenize` and `GET /v1/models` | + +- Other routes answer a customer key with `403`, for example `/api/stats`, `/metrics`, `/api/load` and + `/api/download`. +- Only the admin key loads another model: with `/api/load` (a name from the models folder, or the path of any GGUF + file the server can read), or with a chat request that names another model of `GET /v1/models`. - With customer keys and no admin key, nobody can use the admin routes. -- With no key at all the server is open to anyone who reaches it. That is meant for a local machine only. +- With no key at all the server is open to anyone who reaches it. That is for a local machine only. +- Clients send `Authorization: Bearer ` (`Bearer` as written) or `x-api-key: ` (Anthropic). +- Each key reuses only its own cached conversations (`--cache-ram`), so `cached_tokens` and response times tell a + customer nothing about another. End users behind one key are not separated from each other. +- Prompts and replies are never written to disk. + +The key file has one `name key` pair a line, and the name goes into the usage log. `#` starts a comment, so a key +cannot contain `#`. A key has at least 16 characters. Names and keys must not repeat, and the admin key must not be +in the file. + +A changed file applies from the next request. Rename the new file over the old one, so it is never read half written: + +```bash +sudo sh -c 'cp /etc/strata/keys.txt /etc/strata/keys.new && echo "gamma $(openssl rand -hex 24)" >> /etc/strata/keys.new \ + && chown strata /etc/strata/keys.new && chmod 600 /etc/strata/keys.new && mv /etc/strata/keys.new /etc/strata/keys.txt' +``` + +- A removed key gets `401` from its next request on. +- A file that cannot be read or parsed keeps the old keys. The server log says why. +- A file with no keys removes all customer keys. Without an admin key it is refused, as at start. +- To cut off a customer who used up a prepaid budget, sum the usage log per key and remove the key. + +Without keys the server checks the `Host` header. For a LAN name on a server bound to `0.0.0.0`, add +`--allowed-hosts ai-server.lan,ai-server.local` (or `STRATA_ALLOWED_HOSTS`). Names match exactly, ignoring case and +port. + +## Limits per request + +| Limit | Default | A request over it | +|---|---|---| +| `--ctx`, prompt plus reply | 4096 tokens | gets `400` when its prompt fills the context | +| `--max-tokens`, reply length | what the context leaves | has its reply capped | +| Body size | 8 MiB | is refused | +| Silence while sending | 30 s | is closed | +| Whole request, headers and body | 120 s | is refused | +| `--max-per-key`, open requests of a customer key | no limit | gets `429 Too Many Requests`, `Retry-After: 1`, type `rate_limit_error` | +| `--max-waiting`, open connections | no limit | gets `503 Service Unavailable`, `Retry-After: 2` | + +- Set `--max-tokens`. Without it a reply may run until the context is full and hold the server for minutes. It is + also the length when a request asks for none. +- KV memory grows with `--ctx`: about 650 MB at 32K for the 35B model, half that with `--kv q8`. +- `--max-waiting` counts every open connection, health checks included: `--max-waiting 16` with one reply running + leaves 15 places. Set it when strangers can reach the server. +- Set `--max-per-key` below `--max-waiting`, so one customer cannot fill the queue. The OpenAI and Anthropic SDKs + retry the `429`. + +## Parallel requests + +By default one chat request runs at a time, and the others wait in arrival order. One request decodes at about +113 tok/s (Qwen3.6-35B-A3B Q2_K_XL, RTX 3060), so that is the total for all users. A long prompt blocks the queue for +its prefill (about 2 s for 4K tokens on the 3060). + +`--parallel N` keeps N conversations in GPU memory and decodes up to 4 of them together. Measured on the RTX 3060 +with Qwen3.6-35B-A3B Q2_K_XL, `--ctx 4096`, short prompts and 200-token replies, all requests sent at once: + +| `--parallel` | Requests | Total | Each request | +|---|---|---|---| +| 1 | 4 | 90 tok/s | one after the other | +| 2 | 2 | 139 tok/s | 69 tok/s | +| 4 | 4 | 164 tok/s | 41 tok/s | +| 4 | 8 | 163 tok/s | 41 tok/s, 4 wait | +| 8 | 8 | 149 tok/s | 19 tok/s | + +A request alone on a `--parallel 4` server decodes at 105 tok/s (106 with `--parallel 1`). -When the server is reached through a LAN name while bound to `0.0.0.0` (for example `http://ai-server.lan:8080`), -add that name to the Host check: `--allowed-hosts ai-server.lan,ai-server.local` or -`STRATA_ALLOWED_HOSTS=ai-server.lan,ai-server.local`. Names match exactly and ignore case and the port; loopback -names and the bound address stay allowed. Without keys this check still stops DNS rebinding. +- `--parallel 4` gives the most total speed. More slots let more users stream at once, each at a lower speed. +- A free slot goes to the waiting request whose key holds the fewest slots, oldest first. +- MTP drafting is off (`--mtp` is ignored). Without `--gpu`, `--parallel` is ignored. +- `--ctx` is per slot. N slots take N times the KV memory, so fewer experts fit in VRAM. The `GPU memory:` line at start + shows the split. `--kv q8` gets much of it back. -Clients send the key as `Authorization: Bearer ` (OpenAI; `Bearer` as written) or `x-api-key: ` -(Anthropic). +`--parallel 4`, 4 short requests at once on the 3060: -**Privacy between keys.** RustingStrata keeps recent conversation states in GPU and host memory (`--cache-ram`) so that a -request that continues a conversation prefills only the new part. Each key only reuses states that its own requests -made, so one customer cannot tell from `cached_tokens` or from the response time what another customer sent. All -requests under one key count as one user: if a customer serves many end users through one key, the customer's end -users can learn this about each other. RustingStrata does not write prompts or replies to disk; the usage log holds only -counts and times. +| `--ctx` | `--kv` | KV for 4 slots | Resident experts | Total | +|---|---|---|---|---| +| 16384 | f16 | 1280 MB | 6876 of 10240 | 160 tok/s | +| 32768 | f16 | 2560 MB | 5567 | 114 tok/s | +| 32768 | q8 | 1360 MB | 6779 | 154 tok/s | + +`--kv q8` is about 6% slower to decode and 14% slower to prefill at 32K of actual context. Greedy output can differ +from `--kv f16` at near-ties. + +A model whose experts mostly do not fit in VRAM gains less. Qwen3-Next-80B-A3B IQ1_S on the same 3060 (9199 of 24576 +experts resident with 4 slots), 4 requests: 56.5 tok/s with `--parallel 1`, 77.5 tok/s with `--parallel 4`. + +Prompts are prefilled one at a time, in chunks (`--chunk`, from `rustingstrata calibrate`), and the streams decode +between chunks. A smaller `--chunk` gives shorter pauses and a slower prefill. A 10K-token prompt that arrives while +3 requests stream, on the 3060 with `--parallel 4`: + +| `--chunk` | Longest pause of a stream | First token of the long prompt | +|---|---|---| +| 4096 (calibrated) | 2.2 s | 10.2 s | +| 1024 | 0.7 s | 13.9 s | +| 512 | 0.4 s | 16.4 s | + +Prefilled in one piece, the same prompt took 6.5 s to its first token, and the three streams stopped for all of it. ## Reverse proxy and TLS -RustingStrata speaks plain HTTP. Put a reverse proxy in front of it for TLS, and bind RustingStrata to `127.0.0.1`. When keys are -set, RustingStrata accepts any `Host` header, so the proxy can pass the public name through. +RustingStrata speaks plain HTTP. Bind it to `127.0.0.1` and put a reverse proxy in front for TLS. With keys set, it +accepts any `Host` header. -Streaming replies (`"stream": true`) must reach the client as they are written, so turn off response buffering, and -give the proxy a read timeout that is longer than your longest reply. RustingStrata sends nothing, not even the headers of a -stream, until the prompt is prefilled, so the timeout must also cover the wait in the queue plus the prefill of your -longest prompt. A proxy whose timeout you cannot raise (Cloudflare gives up after 100 s without a response) needs a -`--ctx` small enough that the longest prompt prefills in time, or a direct route that bypasses it. +- Turn off response buffering, so streamed replies arrive as they are written. +- The read timeout must cover the wait in the queue, the longest prefill and the longest reply. Nothing is sent, not + even the headers of a stream, until the prompt is prefilled. +- If you cannot raise the timeout (Cloudflare gives up after 100 s without a response), use a `--ctx` small enough + that the longest prompt prefills in time, or a direct route. -**Caddy** (gets and renews the certificate itself): +Caddy (gets and renews the certificate itself): ``` api.example.com { @@ -199,7 +175,7 @@ api.example.com { } ``` -**nginx:** +nginx: ```nginx server { @@ -227,10 +203,9 @@ To keep the chat page and the admin routes off the public address, serve only `/ location / { return 404; } ``` -Then reach the chat page through an SSH tunnel: `ssh -L 8080:127.0.0.1:8080 server`, and open -http://127.0.0.1:8080 with the admin key. +Reach the chat page through an SSH tunnel (`ssh -L 8080:127.0.0.1:8080 server`) at http://127.0.0.1:8080, with the +admin key. -RustingStrata caps the requests each key has open itself (`--max-per-key`, see [Limits per request](#limits-per-request)). A cap on requests per minute belongs in the proxy: ```nginx @@ -276,78 +251,70 @@ TimeoutStopSec=300 WantedBy=multi-user.target ``` -When the GPU device is lost (a driver reset, a GPU hang), no later request can succeed, so `serve` exits with -status 1 and `Restart=on-failure` starts it again. - With the user, keys and calibration of the quick start: -```sh +```bash sudo systemctl daemon-reload && sudo systemctl enable --now strata journalctl -u strata -f ``` -Run `calibrate` as the service user, because the calibration file and the CUDA kernel cache live in that user's -`~/.cache/rusting_strata`. The first start after an update compiles the CUDA kernels (about 15 s); `/health` answers -`503` until the model has loaded. - -In a container that folder is lost when the container exits, and the next one starts uncalibrated with only the -`not calibrated on this machine` line to say so. Set `XDG_CACHE_HOME` to a mounted path (the folder is then -`$XDG_CACHE_HOME/rusting_strata`) for both `calibrate` and `serve`, for example `-v /srv/strata-cache:/cache -e -XDG_CACHE_HOME=/cache`. - -**Stopping and restarting.** On `SIGTERM` (`systemctl stop` or `restart`) the server answers new requests, `/health` -included, with `503` and `Retry-After: 5`, lets the requests it already accepted finish (the queued ones too), saves -the routing profile it learned, so that the next start places the experts as well, and then exits. -`TimeoutStopSec` must cover a full queue, or keep `--max-waiting` low. A load balancer -sends the new requests to the other servers meanwhile, so restarting one server at a time cuts no reply. `systemd` -sends `SIGKILL` after `TimeoutStopSec`; Ctrl+C still stops at once. On Windows there is no such drain. +- Run `calibrate` as the service user: the calibration and the CUDA kernel cache live in its + `~/.cache/rusting_strata`. +- The first start after an update compiles the CUDA kernels (about 15 s). `/health` answers `503` until the model has + loaded. +- When the GPU device is lost (a driver reset, a GPU hang), `serve` exits with status 1 and systemd starts it again. +- On `SIGTERM` (`systemctl stop` or `restart`), new requests and `/health` get `503` with `Retry-After: 5`, and the + accepted requests finish, queued ones too. `TimeoutStopSec` must cover a full queue (or keep `--max-waiting` low): + after it systemd sends `SIGKILL`. +- Behind a load balancer, restarting one server at a time cuts no reply. +- Ctrl+C stops at once. On Windows there is no such drain. ## Docker -The repository has a `Dockerfile` for the server. The image holds the binary, NVRTC for the CUDA kernels and the -Vulkan loader; the GPU driver comes from the host (for NVIDIA cards through the NVIDIA Container Toolkit). +The `Dockerfile` in the repository builds the server image: the binary, NVRTC for the CUDA kernels and the Vulkan +loader. The GPU driver comes from the host, for NVIDIA cards through the NVIDIA Container Toolkit. -```sh +```bash docker build -t rustingstrata . docker run -d --name strata --gpus all -p 127.0.0.1:8080:8080 \ -v /srv/models:/models -v /srv/strata-cache:/cache rustingstrata + +# Calibrate once per model and machine, with the same mounts. +docker run --rm --gpus all -v /srv/models:/models -v /srv/strata-cache:/cache rustingstrata calibrate --model /models/model.gguf ``` -- The default command is `serve --gpu --addr 0.0.0.0:8080 --models-dir /models`: no model is loaded at the start - (`/health` answers `503` until one is), and the chat page at http://127.0.0.1:8080 lists the files in `/models` - and loads the one you pick. Arguments after the image name replace the command, for example - `rustingstrata serve --gpu --addr 0.0.0.0:8080 --model /models/model.gguf` to load a model at the start. -- `/models` is the folder of GGUF files. `/cache` keeps the calibration, the compiled CUDA kernels and the expert - placement; without that mount every new container compiles the kernels again and runs uncalibrated. -- Calibrate once per model and machine, with the same mounts: - `docker run --rm --gpus all -v /srv/models:/models -v /srv/strata-cache:/cache rustingstrata calibrate --model /models/model.gguf`. -- The example publishes the port on the loopback address only. To reach the chat page through a LAN name, add - `-e STRATA_ALLOWED_HOSTS=that-name`; set a key with `-e STRATA_API_KEY=...` before the port faces a network. -- For a Vulkan card (AMD, Intel) pass the render device in place of `--gpus all`: `--device /dev/dri`, and add - `--backend vulkan` to the command. This path has not been run on an AMD or Intel card yet. +- The default command is `serve --gpu --addr 0.0.0.0:8080 --models-dir /models`. No model is loaded at the start, so + `/health` answers `503`. Pick a file of `/models` on the chat page at http://127.0.0.1:8080. +- Arguments after the image name replace the command, for example + `serve --gpu --addr 0.0.0.0:8080 --model /models/model.gguf`. +- `/cache` keeps the calibration, the compiled CUDA kernels and the expert placement. Without that mount every new + container compiles the kernels again and runs uncalibrated. Only the `not calibrated on this machine` line says so. +- The image sets `XDG_CACHE_HOME=/cache`. In an image of your own, set it to a mounted path too. +- The port is published on the loopback address only. For a LAN name, add `-e STRATA_ALLOWED_HOSTS=that-name`. Set + `-e STRATA_API_KEY=...` before the port faces a network. +- For a Vulkan card (AMD, Intel), pass `--device /dev/dri` in place of `--gpus all` and add `--backend vulkan` to the + command. This path has not been run on an AMD or Intel card yet. ## Health checks -`GET /health` needs no key and is answered at once, also while a reply is generated or a model loads: +`GET /health` needs no key and is answered at once, also while a reply is generated or a model loads. -- `200 {"status": "ok", "waiting": N, "slots": S}` once a model is loaded. `waiting` counts the requests being read, - generated or queued besides this one; `slots` is how many are generated at once (`--parallel`). A load balancer - can send the next request to the server with the lowest `waiting / slots`. -- `200 {"status": "ok", "unloaded": true, "waiting": N}` when `--auto-unload` has freed the model: the next chat - request loads it again, so the server stays in rotation. During that load `/health` answers `503 loading`, as for - any load. -- `503 {"status": "loading"}` or `503 {"status": "no model"}` otherwise. -- `503` with an `error` body (no `status`) when `--max-waiting` connections are open, or while the server stops. A - load balancer then treats a full server as down, which sends the next requests elsewhere. +| Answer | When | +|---|---| +| `200 {"status": "ok", "waiting": N, "slots": S}` | a model is loaded | +| `200 {"status": "ok", "unloaded": true, "waiting": N}` | `--auto-unload` freed the model; the next chat request loads it | +| `503 {"status": "loading"}` | a model loads, also after `--auto-unload` | +| `503 {"status": "no model"}` | no model is loaded | +| `503` with an `error` body, no `status` | `--max-waiting` connections are open, or the server stops | -Point the load balancer or your monitoring at it. +`waiting` counts the requests being read, generated or queued besides this one. `slots` is the `--parallel` value. A +load balancer can send the next request to the server with the lowest `waiting / slots`. -`GET /metrics` gives the same numbers and more in Prometheus text format: `strata_up`, `strata_uptime_seconds`, `strata_slots`, -`strata_busy`, `strata_waiting`, `strata_requests_total`, `strata_prompt_tokens_total`, -`strata_cached_prompt_tokens_total`, `strata_completion_tokens_total`, `strata_vram_used_bytes` / -`strata_vram_total_bytes` and, for MoE models, `strata_expert_hits_total` / `strata_expert_misses_total` -(these two restart at each model load). Like `/api/stats` it needs the admin key, and it is answered while a -reply is generated: +`GET /metrics` gives the same and more in Prometheus text format. It needs the admin key, like `/api/stats`: +`strata_up`, `strata_uptime_seconds`, `strata_slots`, `strata_busy`, `strata_waiting`, `strata_requests_total`, +`strata_prompt_tokens_total`, `strata_cached_prompt_tokens_total`, `strata_completion_tokens_total`, +`strata_vram_used_bytes`, `strata_vram_total_bytes`, `strata_ram_cap_bytes` and, for MoE models, +`strata_expert_hits_total` and `strata_expert_misses_total` (these two restart at each model load). ```yaml scrape_configs: @@ -367,52 +334,32 @@ With `--usage-log FILE`, every chat request that reaches the model adds one JSON ``` - `at`: Unix time in seconds when the request started. -- `key`: the key's name from the key file (`admin` for the admin key, empty on a server without keys). -- `prompt_tokens`: all prompt tokens. `cached_tokens` of them came from the conversation cache and were not prefilled - again; many providers bill them at a lower price. -- `prefill_ms`: from when the model takes the request until its prompt is read (the wait in the queue, or for a - slot under `--parallel`, is not included); `decode_ms`: the reply after that. -- `completion_tokens`: reply tokens. `finish` is `stop`, `length` (hit `max_tokens` or the context) or `tool_calls`. -- `finish` is `cut` when the client closed the connection before the end. `completion_tokens` then counts the - tokens decoded so far: a stream has sent nearly all of them, a reply without `stream` has sent none. `error` is a - request that failed on the server; it got a `500` or a stream that stopped. - -Requests refused before the model (bad key, bad JSON, a prompt that fills the context, `503`, `429`) and requests -whose client left while they waited in the queue are not logged. A client that leaves once its prefill has started -is logged as `cut`, with all its prompt tokens. Tokens per key and day, without failed requests: - -```sh +- `key`: the name from the key file, `admin` for the admin key, empty on a server without keys. +- `cached_tokens`: the part of `prompt_tokens` that came from the conversation cache and was not prefilled again. + Many providers bill it at a lower price. +- `prefill_ms`: from when the model takes the request until its prompt is read, without the wait in the queue or for + a slot. `decode_ms`: the reply after that. +- `finish`: `stop`, `length` (hit `max_tokens` or the context), `tool_calls`, `cut` or `error`. +- `cut`: the client left after its prefill started. All its prompt tokens are logged, and `completion_tokens` counts + the tokens decoded so far. A stream has sent nearly all of them, a reply without `stream` none. +- `error`: the request failed on the server. It got a `500` or a stream that stopped. +- Not logged: requests refused before the model (bad key, bad JSON, a prompt that fills the context, `503`, `429`) + and requests whose client left while they waited in the queue. + +Tokens per key and day, without failed requests: + +```bash jq -r 'select(.finish != "error") | [(.at | strftime("%Y-%m-%d")), .key, .prompt_tokens - .cached_tokens, .cached_tokens, .completion_tokens] | @tsv' usage.jsonl \ | awk '{k=$1" "$2; p[k]+=$3; c[k]+=$4; o[k]+=$5} END {for (k in p) print k, p[k], c[k], o[k]}' | sort ``` -The file only grows; rotate it with logrotate (`copytruncate`, since RustingStrata keeps it open). - -## Limits per request - -- `--ctx` is the context length for prompt plus reply (4096 by default). Requests whose prompt fills it get `400`. - KV memory grows with it: about 650 MB at 32K for the 35B model, half that with `--kv q8`. -- `--max-tokens` caps the reply length a request may ask for, and is the length when it asks for none. Without it a - request may decode until the context is full, which holds the server for minutes. -- Bodies over 8 MiB are refused, a connection that sends nothing for 30 s is closed, and a body needs a - `Content-Length` (a chunked upload gets `400`). nginx buffers the request by default, which covers both: a slow - client then holds nginx, not a RustingStrata place. -- A missing or wrong key (`401`), a malformed request (`400`), `GET /v1/models` and the chat page are answered as - soon as they are read, without a place in the queue, so a scan for keys does not delay paying customers. -- A client that disconnects stops its reply within a few tokens, so the next request in the queue starts. One that - leaves while its request waits in the queue costs no prefill: the request is dropped when its turn comes (with - `--parallel`, within a quarter second). -- With `--parallel N`, `--ctx` is per slot: N slots of 32K need N times the KV memory of one. -- `--max-per-key N` caps the requests one customer key may have open at once (generated or queued; a request counts once it is read); more get - `429 Too Many Requests` with `Retry-After: 1` and the OpenAI error type `rate_limit_error`, which the OpenAI and - Anthropic SDKs retry. The admin key is not counted. Set it below `--max-waiting`, so that one customer cannot fill - the whole queue and leave the others with `503`. +The file only grows. Rotate it with logrotate (`copytruncate`, because RustingStrata keeps it open). ## Several GPUs -**One server per GPU, more users.** Start one server per card on its own port and balance between them: +For more users, start one server per card on its own port and balance between them: -```sh +```bash rustingstrata serve --model $M --gpu --device 0 --addr 127.0.0.1:8081 --threads 6 ... rustingstrata serve --model $M --gpu --device 1 --addr 127.0.0.1:8082 --threads 6 ... ``` @@ -424,16 +371,13 @@ upstream strata { least_conn; server 127.0.0.1:8081 max_fails=0; server 127.0.0. proxy_next_upstream error http_503 non_idempotent; ``` -Give each server half of the CPU cores (`--threads`), because each one computes the experts that do not fit in its -VRAM on the CPU. Conversation caches are per server, so a conversation that moves to the other server is prefilled -again; hashing on the key (`hash $http_authorization consistent;` instead of `least_conn`) keeps each customer on one -server. +- Give each server half of the CPU cores (`--threads`): each computes the experts outside its VRAM on the CPU. +- Conversation caches are per server. `hash $http_authorization consistent;` instead of `least_conn` keeps each + customer on one server, so conversations are not prefilled again. -**One server over several GPUs, a bigger model.** `--device 0,1` splits the layers over the cards, so more experts -fit in VRAM. `--parallel` works here too: each card holds the KV cache of its own layers for every slot. The cards -take their layers in turn for each step, so they do not compute at the same time, and the gain over `--parallel 1` -comes from the batching, as on one card. A split server does not park conversations in host memory: each slot only -keeps its last conversation. For many users on cards that each fit the model, one server per card is faster. +For a bigger model, `--device 0,1` splits the layers of one server over the cards, so more experts fit in VRAM. +`--parallel` works here too. A split server does not park conversations in host memory: each slot keeps only its +last conversation. For many users on cards that each fit the model, one server per card is faster. ## Checklist @@ -441,8 +385,8 @@ keeps its last conversation. For many users on cards that each fit the model, on - [ ] An admin key, and customer keys in a file with mode 600. - [ ] The proxy streams without buffering and has a long read timeout. - [ ] `--max-tokens` and `--ctx` fit your price list and your GPU memory (times `--parallel`). -- [ ] `--parallel` set for the number of users you expect at once (4 for the most total speed). -- [ ] `--max-waiting` set (no limit by default) and `--max-per-key` below it, so one customer cannot fill the queue. +- [ ] `--parallel` fits the users you expect at once (4 for the most total speed). +- [ ] `--max-waiting` is set (no limit by default), and `--max-per-key` is below it. - [ ] `--usage-log` is on and rotated. - [ ] `/health` (or `/metrics`) is monitored, and systemd restarts the server on failure. - [ ] `rustingstrata calibrate` ran on this machine as the service user. diff --git a/docs/LORA.md b/docs/LORA.md index 4066e677..7f50f315 100644 --- a/docs/LORA.md +++ b/docs/LORA.md @@ -1,49 +1,38 @@ # LoRA adapters -`--lora` applies a GGUF LoRA adapter when the model loads. The base GGUF is not changed and nothing is requantized, -so one base model can run with or without an adapter, or with a different strength, from the same file. - -The main use is abliteration: an adapter that removes the refusal direction makes any supported base model -uncensored without a separate abliterated download. Other LoRA adapters work too, within the limits below. +`--lora` applies a GGUF LoRA adapter when the model loads. The base GGUF is not changed. The main use is abliteration: +an adapter that removes the refusal direction. Contributed by [@jazir555](https://github.com/jazir555) in [#15](https://github.com/RustingStudio/RustingStrata/pull/15). ## Usage -``` +```bash rustingstrata generate --model MODEL.gguf --lora ADAPTER.gguf --prompt "..." -n 50 -rustingstrata chat --model MODEL.gguf --lora ADAPTER.gguf:0.8 -rustingstrata serve --model MODEL.gguf --lora ADAPTER.gguf:1.0 --ctx 32768 +rustingstrata serve --model MODEL.gguf --lora ADAPTER.gguf:0.8 --ctx 32768 ``` -- `--lora PATH` or `--lora PATH:SCALE`. The scale is 1.0 when it is left out. Windows paths with a drive letter - (`C:\adapters\a.gguf`) work with and without a scale. -- Repeat the flag for several adapters; they add up. -- It works on the CPU and on the GPU (CUDA and Vulkan), in `generate`, `chat`, `serve`, `bench`, `perplexity` and - `score`. -- `calibrate` accepts the flag but ignores it: calibration always measures the base model. +| Flag | Default | Meaning | +|---|---|---| +| `--lora PATH[:SCALE]` | scale 1.0 | The adapter and its strength. Repeatable; adapters add up. | + +- It works on the CPU and the GPU (CUDA and Vulkan), in `generate`, `chat`, `serve`, `bench`, `perplexity` and `score`. + `calibrate` accepts the flag and ignores it. +- Windows paths with a drive letter (`C:\adapters\a.gguf`) work with and without a scale. +- Only the Qwen-family models take adapters: `qwen3`, `qwen3moe`, `qwen3next`, `qwen35`, `qwen35moe`, `qwen4exp`. + `deepseek41`, `glm5-next` and `gemma4` do not apply `--lora`. ## Adapter format -A GGUF adapter as written by llama.cpp's `convert_lora_to_gguf.py`: for each target tensor `NAME` it holds -`NAME.lora_a` and `NAME.lora_b`, and optionally `adapter.lora.alpha` in the metadata. The applied weight is +The format of llama.cpp's `convert_lora_to_gguf.py`: `NAME.lora_a` and `NAME.lora_b` for each target tensor `NAME`, +and an optional `adapter.lora.alpha`. The adapter must be made for the same base model. ``` W' = W + m * B * A m = scale * alpha / rank, or scale when the adapter has no alpha ``` -The adapter must be made for the same base model: a target with a different shape is skipped with a warning. - -## What is applied - -- **Routed expert down projections** (`blk.N.ffn_down_exps.weight`): stay quantized. The correction - `m * B * (A * activation)` is added for each selected expert while the model runs, on the CPU and on the GPU. An - adapter with one expert slice is applied to every expert. -- **Every other target** (`attn_output`, `ssm_out`, `ple_value`, `ffn_down_shexp`, ...): the tensor is dequantized - to F32 once at load, the adapter is added, and the CPU and GPU both read the result. - -These messages on stderr mean a target was left out: +These lines on stderr mean a target is left out: ``` lora: target NAME not found, skipping @@ -51,15 +40,15 @@ lora: target NAME is RxC, adapter is RxC; skipping lora: target NAME has N experts, expected 1; skipping ``` -The last one is for per-expert tensors other than `ffn_down_exps` (the expert gate and up projections), which are -not supported. +The last line is for per-expert tensors other than `blk.N.ffn_down_exps.weight`, which are not supported. One expert +slice for that tensor is applied to every expert. ## Cost and limits -- Prompts are processed token by token instead of in batched chunks, so prefill is slower with an adapter. -- Recorded GPU graphs are off while an adapter is loaded, and the expert correction is computed on the host for each - token, so decode is slower too. MTP drafts still work. -- Each dequantized target is held as F32 in host RAM and counts toward `--max-ram`. -- Only models that run through the Qwen-family forward take adapters (`qwen3`, `qwen3moe`, `qwen3next`, `qwen35`, - `qwen35moe`, `qwen4exp`). `deepseek41`, `glm5-next` and `gemma4` do not apply `--lora`. -- Output is not compared against llama.cpp with the same adapter; the LoRA arithmetic itself is plain F32. +- With `--fast-cpu` an adapter costs almost nothing: 8.7 tok/s against 8.5 without it (Ternary Bonsai 2B, rank-1 + adapter on 48 tensors, i5-8365U). +- Without `--fast-cpu`, prefill runs token by token and decode is slower. MTP drafts still work. +- Without `--fast-cpu`, targets such as `attn_output`, `ssm_out`, `ple_value` and `ffn_down_shexp` are held as F32 in + host RAM and count toward `--max-ram`. The load prints the tensor count and the MB, and stops with an error when + they do not fit. An adapter for every projection of a dense 27B model takes about 100 GB. +- Output is not compared against llama.cpp with the same adapter. diff --git a/docs/MODELS.md b/docs/MODELS.md index 7fd11009..186beaaa 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -1,33 +1,76 @@ # Models -Which GGUF files RustingStrata runs, how each family runs and what was checked. Speed against llama.cpp is in -[BENCHMARKS.md](BENCHMARKS.md); flags are in [USAGE.md](USAGE.md). +Which GGUF files RustingStrata runs, with which command, and what is limited per model. Flags are in +[USAGE.md](USAGE.md). Speed tables are in [BENCHMARKS.md](BENCHMARKS.md). ## Architectures -The engine picks the code path from `general.architecture` in the file. - -| Model family | `general.architecture` | How it runs | +| Model family | `general.architecture` | GPU | Decoding | Notes | +|---|---|---|---|---| +| Qwen3 | `qwen3`, `qwen3moe` | CUDA or Vulkan with `--gpu`, CPU without it | sampling | | +| Qwen3-Next | `qwen3next` | same | sampling | | +| Qwen3.5 / Qwen3.6, [Ternary Bonsai 2](#ternary-bonsai-2-2b-and-9b-ptq1_0) | `qwen35`, `qwen35moe` | same | sampling | | +| Qwen3.8-Flash-Next, [Qwen4-35B-A3B](#qwen4-35b-a3b-ud-q5_k_m-395-gb) | `qwen4exp` | same | sampling | pass the first shard | +| SenseNova-Loop | `sensenova_loop` | same | sampling | | +| Recursive Flint | `flint` | same | sampling | | +| [Gemma 4](#gemma-4-26b-a4b-ud-q4_k_xl-17-gb) | `gemma4` | opens the GPU itself | greedy only | attention runs on the CPU | +| [DeepSeek-V4.1-Flash](#deepseek-v41-flash-iq2_xxs-249-gb) | `deepseek41` | CUDA | greedy only | pass the first shard | +| [GLM-5.3-Flash](#glm-53-flash-ud-q2_k_xl-119-gb) | `glm5-next` | CUDA | greedy only | pass the first shard | +| [Hy4-flash](#hy4-flash-iq2_siq2_xxs-85-gb) | `hy_v4_flash` | CUDA or Vulkan | greedy only | pass the first shard | +| [Kolibri 1.1](#kolibri-11-q4_k_m-434-gb) | `kolibri1` | CUDA or Vulkan | greedy only | | +| [GigaChat 4](#gigachat-4-37b-a4b-q4_k_m-23-gb) | `gigachat4` | CUDA, HIP on AMD | greedy only | MTP drafts, Vulkan untested | +| [Inkling 2 Mini](#inkling-2-mini-iq4_nl-176-gb) | `inkling2_loop`, `inkling2` | CUDA or Vulkan | sampling | | +| Raon-1 mini | `raon1` | CUDA or Vulkan | greedy only | | + +The rows from Gemma 4 down have their own forward: + +- They open the GPU by themselves. `--gpu` is not needed. +- The experts that do not fit in VRAM run on the CPU. +- The chat page of one server loads them like the other models. +- `rustingstrata calibrate` measures their prefill chunk too, except for DeepSeek. See [CALIBRATION.md](CALIBRATION.md). + +Every model runs with `chat`, `generate`, `serve` and `bench`. `score` runs the Qwen-family rows, Kolibri 1.1, +GigaChat 4 and Inkling 2. `check` is in [USAGE.md](USAGE.md). Image input is in [VISION.md](VISION.md). + +VRAM variables of these models: + +| Name | Default | What it does | |---|---|---| -| Qwen3 | `qwen3`, `qwen3moe` | GPU forward with `--gpu` (CUDA or Vulkan), CPU reference without it | -| Qwen3-Next | `qwen3next` | same | -| Qwen3.5 / Qwen3.6 | `qwen35`, `qwen35moe` | same | -| Qwen3.8-Flash-Next | `qwen4exp` | same | -| SenseNova-Loop | `sensenova_loop` | same | -| Recursive Flint | `flint` | same | -| [Gemma 4](#gemma-4-26b-a4b-ud-q4_k_xl-17-gb) | `gemma4` | own forward, matvecs and expert cache on the card, attention on the CPU | -| [DeepSeek-V4.1-Flash](#deepseek-v41-flash-iq2_xxs-249-gb) | `deepseek41` | own forward, matvecs and expert cache on the CUDA card, greedy only | -| [GLM-5.3-Flash](#glm-53-flash-ud-q2_k_xl-119-gb) | `glm5-next` | own forward, matvecs and expert cache on the CUDA card, greedy only | -| [Hy4-flash](#hy4-flash-iq2_siq2_xxs-85-gb) | `hy_v4_flash` | own forward, matvecs and expert cache on CUDA or Vulkan, greedy only | -| [Inkling 2 Mini](#inkling-2-mini-iq4_nl-176-gb) | `inkling2_loop`, `inkling2` | own forward, matvecs and expert cache on CUDA or Vulkan | - -The models with their own forward open the GPU by themselves (no `--gpu` flag), have nothing to calibrate and load -from the chat page of one server like the others. Image input is in [VISION.md](VISION.md). +| `STRATA_DS_GPU_EXPERTS` | unset | VRAM budget in GB for the weights and the expert cache | +| `STRATA_DS_GPU_FRACTION` | per model | Share of the free VRAM the weights take when no budget is set | +| `STRATA_DS_GPU` | `1` | `0` runs everything on the CPU | + +`STRATA_DS_GPU_FRACTION` defaults to 0.9 for Gemma 4, GLM and Inkling 2, and to 0.95 for DeepSeek and GigaChat 4. On +a card with less than 8 GB free it is 0.6 for Inkling 2 and 0.8 for DeepSeek and GigaChat 4. A pair such as +`0.6,0.9` sets both values. + +## GGUF types + +| Group | Types | +|---|---| +| Float | F32, F16, BF16, F8_E4M3 | +| Legacy | Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q8_1 | +| K-quants | Q2_K, Q3_K, Q4_K, Q5_K, Q6_K, Q8_K | +| I-quants | IQ1_S, IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, IQ4_XS, IQ4_NL | +| Low-bit and ternary | Q1_0, Q2_0, PQ2_0, TQ1_0, TQ2_0, PTQ1_0 | +| FP4 | MXFP4, NVFP4 | +| Trellis types of agentionai's llama.cpp fork | TQ2_T, TQK6, TQK7 | + +The Gyro files of agentionai load too. Their names say TQ1_0 and TQ2_0, but the experts are stored in the trellis +types. + +- `Gyro-S-TQ1_0` (TQK6, TQK7) is tested on CPU, CUDA and Vulkan. `Qwen3.8-Flash-Next-Gyro-S-TQ1_0` is a 58 GB file. +- `Gyro-M-TQ2_0` (TQ2_T) has the same layout but was not run here. +- Gyro-L (TQP5 to TQP7) is not supported yet. ## Qwen models -Greedy "The capital of France is" with `--gpu` (CUDA / Vulkan, second run) on an RTX 3060 12 GB with a Ryzen 5 7600X -and 32 GB RAM: +```bash +rustingstrata chat --gpu --model .gguf +``` + +Decode is greedy "The capital of France is" with `--gpu` (CUDA / Vulkan, second run) on an RTX 3060 12 GB with a +Ryzen 5 7600X and 32 GB RAM. | Model | Types | Decode | |---|---|---| @@ -40,111 +83,184 @@ and 32 GB RAM: | Qwen3-Next-80B-A3B-Instruct UD-IQ1_S (most experts on the CPU) | IQ1_S to IQ4_NL, Q4_K to Q8_0, BF16 | 92 / 90 tok/s | | Qwen3.8-Flash-Next GSQ-RCO IQ2_XS (64 GB in two files, pass the `-00001-of-00002` one; 18% of experts fit in VRAM, and with 32 GB RAM the rest are partly read from disk) | Q2_0, IQ1_M to IQ4_XS, Q6_K, Q8_0, F16, BF16 | 22 / 20 tok/s | -## GGUF types +## Qwen4-35B-A3B (UD-Q5_K_M, 39.5 GB) -Supported GGUF types: F32, F16, BF16, Q8_0, Q4_0, Q4_1, Q5_0, Q5_1, Q2_0, TQ1_0, TQ2_0, Q2_K-Q6_K, IQ1_S, IQ1_M, -IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, IQ4_XS, IQ4_NL, NVFP4, and the trellis types TQ2_T, TQK6 and TQK7 of agentionai's -llama.cpp fork. +```bash +rustingstrata chat --gpu --model Qwen4-35B-A3B-UD-Q5_K_M-00001-of-00002.gguf +rustingstrata serve --gpu --model Qwen4-35B-A3B-UD-Q5_K_M-00001-of-00002.gguf --parallel 4 --ctx 16384 +``` -The Gyro files of agentionai load too. Their names say TQ1_0 and TQ2_0, but the experts are stored in the trellis -types and read inputs rotated by a Hadamard transform (`prism.hadamard.*`). `Gyro-S-TQ1_0` (TQK6, TQK7) is tested on -CPU, CUDA and Vulkan. `Gyro-M-TQ2_0` (TQ2_T) has the same layout and only supported types, but was not run here. -Gyro-L (TQP5 to TQP7, PTQ1_0) is not supported yet. +- Pass the `-00001-of-00002` file. The second shard holds the 14.3 GiB n-gram table, which stays in RAM. +- The file does not fit in 12 GB of VRAM. The most used experts stay on the card. The rest run on the CPU. +- `--mtp N` drafts N tokens a step with the MTP layer of the file. See [USAGE.md](USAGE.md). +- `serve --parallel N` works. +- Splitting the layers over two GPUs is in the code but was not run on two cards. + +A request's `reasoning_effort` sets the thinking level of the chat template: + +| `reasoning_effort` | Level in the prompt | +|---|---| +| `xhigh`, `max` | `xhigh` | +| `high`, `medium` | `high` | +| `low`, `minimal` | `low` | +| `off`, `none` | `off`, thinking is off | +| any other value | ignored | + +- Without a level, thinking on renders `high`. Thinking off (`--think false`, `enable_thinking: false`) renders `off`. +- When the level and `enable_thinking` contradict each other, thinking is off. + +Quality: same top token as llama.cpp (1579b02) at 618 (CPU), 615 (CUDA) and 618 (Vulkan) of 640 steps. llama.cpp +agrees with itself at 613 of 640. Speed is in [BENCHMARKS.md](BENCHMARKS.md). + +## Ternary Bonsai 2 (2B and 9B, PTQ1_0) + +```bash +rustingstrata chat --model Ternary-Bonsai-2-9B-PTQ1_0.gguf --gpu +``` + +- PrismML's files: `Ternary-Bonsai-2-2B-PTQ1_0.gguf` (429 MB) and `Ternary-Bonsai-2-9B-PTQ1_0.gguf` (2.0 GB). +- They are Qwen3.5 dense models (`qwen35`) with every weight in PTQ1_0, 1.75 bits a weight. +- The Q2_0 files of the same models load too. + +Quality: llama.cpp does not read PTQ1_0, so the reference is llama.cpp (GigaChat 4 branch at 0541e50e2) on the Q2_0 +file. The PTQ1_0 file gives the same top token at 637 of 640 steps (99.5%), 2B and 9B, CUDA and Vulkan. ## Gemma 4 (26B-A4B UD-Q4_K_XL, 17 GB) -`chat`, `generate` and `serve` detect the `gemma4` architecture and run its own forward: the matrix products and the -routed experts that fit run on the card, attention and the experts that do not fit run on the CPU. The weights take -90% of the free VRAM (`STRATA_DS_GPU_FRACTION`; `STRATA_DS_GPU_EXPERTS=` sets an absolute budget). `--kv`, -`--chunk`, `--parallel` and `--cache-ram` have no effect on it. The prompt goes through the layers in chunks of 256 -tokens (`STRATA_G4_CHUNK`; 1 is token by token). `STRATA_G4_PROF=1` prints the prefill and decode times. +```bash +rustingstrata chat --model .gguf +``` + +- `--kv`, `--chunk`, `--parallel` and `--cache-ram` have no effect. +- Decoding is greedy. +- Image input needs `--mmproj`. See [VISION.md](VISION.md). -Reference machine (RTX 3060 12 GB), a 595-token prompt and 64 reply tokens, warm page cache: +Speed on the reference machine (RTX 3060 12 GB), a 595-token prompt and 64 reply tokens, warm page cache: prefill +109-114 tok/s, decode 34 ms/token (29 tok/s). llama.cpp was not run here. A user report has it well ahead on an RTX +4070 SUPER. -| | 1.3.0 | now | -|---|---|---| -| Prefill | about 30 tok/s | 109-114 tok/s | -| Decode | 45-49 ms/token (20-22 tok/s) | 34 ms/token (29 tok/s) | +## Kolibri 1.1 (Q4_K_M, 43.4 GB) -The 1.3.0 prefill is the wall time less the load and the decode; it had no timer of its own. Decode still pays a -host round trip for each group of matrix products of each layer, and no llama.cpp run was made on this machine; the -report in issue #81 has llama.cpp well ahead on an RTX 4070 SUPER. +The file is [Aleph-Alpha/Kolibri-1.1-GGUF](https://huggingface.co/Aleph-Alpha/Kolibri-1.1-GGUF). -## DeepSeek-V4.1-Flash (IQ2_XXS, 249 GB) +```bash +rustingstrata chat --model Kolibri-1.1-Q4_K_M.gguf +rustingstrata serve --model Kolibri-1.1-Q4_K_M.gguf --addr 127.0.0.1:8080 +``` + +- The GPU is CUDA when an NVIDIA card and driver are present, Vulkan otherwise. `--backend vulkan` or `--backend cuda` + picks one. +- `--think` sets the "Reasoning effort" system section of the chat template. +- Decoding is greedy. The model's thinking arrives inside `content`. +- The file is larger than 30 GB RAM and 12 GB VRAM together. The experts that are not on the card are then read + from the drive, and the first request after a start is slower. +- Vulkan was run on the RTX 3060 only, not on an AMD or Intel card. +- On Vulkan, one attention kernel needs about 35 KB of workgroup shared memory. On a card with a smaller limit that + attention runs on the CPU. + +Quality: same top token as llama.cpp at 45, 46, 44 and 46 of 48 steps after prompts of 2k, 3.8k, 16k and 32k tokens. +Two llama.cpp runs of the same file agree with each other at 40-45 of 48. Speed is in [BENCHMARKS.md](BENCHMARKS.md). + +## GigaChat 4 (37B-A4B Q4_K_M, 23 GB) + +The file is [ai-sage/GigaChat4-37B-A4B](https://huggingface.co/ai-sage/GigaChat4-37B-A4B). + +```bash +rustingstrata chat --model GigaChat4-37B-A4B-Q4_K_M.gguf +rustingstrata serve --model GigaChat4-37B-A4B-Q4_K_M.gguf --addr 127.0.0.1:8080 +``` -`chat`, `generate` and `serve` detect the `deepseek41` architecture and run it on the CPU reference forward, with the -matvecs and a 9 GB expert cache on the CUDA card (no `--gpu` flag needed). Pass the first shard; the others are found -next to it. +- `--mtp 1` drafts one token a step with the MTP layer of the file. It is off by default. +- Thinking is on by default and arrives as `reasoning_content`. `--think false` gives an empty think block. So do + `"think": false` and `"reasoning_effort": "none"` in a request. +- On an AMD card (`--backend hip`) cap the expert cache, for example `STRATA_DS_GPU_EXPERTS=4`, or it fills a 16 GB + card. See [HIP.md](HIP.md). +- `serve` runs one untimed 512-token prefill at load (`warm-up: ... s` in the log), 10 to 17 s from a cold page + cache. A request during it waits. `STRATA_WARMUP=0` skips it, but the first request then prefilled at 33 tok/s + instead of 180 to 231. -```sh +Limits: + +- Decoding is greedy. +- Only CUDA was run (RTX 3060). The Vulkan path is untested. +- MTP drafts need the GPU and no grammar. At a near tie the output with `--mtp 1` can differ from a run without it. +- The model scores every earlier key, so the cost of a token grows with the context. + +Quality: same top token as llama.cpp at 625 of 640 steps (97.7%). Speed is in [BENCHMARKS.md](BENCHMARKS.md). + +## DeepSeek-V4.1-Flash (IQ2_XXS, 249 GB) + +```bash M=DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XXS-00001-of-00006.gguf rustingstrata chat --model $M [--think] rustingstrata generate --model $M --prompt "The capital of France is" -n 64 rustingstrata serve --model $M --addr 127.0.0.1:8080 [--api-key K] ``` -| DeepSeek-V4.1-Flash IQ2_XXS (249 GB), RTX 3060 12 GB, 30 GB RAM | RustingStrata | llama.cpp b12116 (`--cpu-moe`) | -|---|---|---| -| Decode | 1.8 tok/s at first, 2-3.6 tok/s now (VRAM expert cache with LRU) | 0.3-1.5 tok/s (cold) | -| Prefill | ~2 tok/s on short prompts (0.5 s/token), ~0.5 tok/s at 1400 tokens | 0.5-0.9 tok/s (cold) | -| Teacher-forced top-1 vs llama.cpp | 189/192 short, 21/23 on 1425 tokens (misses are near-ties) | - | -| Sampling, tool calls | no sampling; tool calls in `serve` | supported | - -The llama.cpp numbers are from the first cold runs on this box and the RustingStrata numbers from the last runs -before the model was deleted; they were not re-measured side by side, and both move with the page cache. -Decode varies run to run with the page cache, because the experts that miss VRAM are read from the GGUF. -`STRATA_DS_GPU_EXPERTS=` sets the VRAM weight budget; unset, it is 80% of free VRAM (about 9 GB on a 12 GB -card). Prefill is one token at a time. Prompt plus reply is limited only by the model's trained context from the GGUF (1,048,576; `STRATA_DS_CTX` lowers it; checked against llama.cpp only up to a 1425-token prompt), decoding is greedy only, and sampling is not supported. Tool calls work in `serve`: the prompt matches the model template (jinja2 render, three cases byte for byte) and the reply's `<|DSML| calls>` block is parsed, but this path has not been run against the model itself. +- Pass the first shard. The others are found next to it. +- It needs a CUDA card. +- Decoding is greedy. +- Prompt plus reply is limited by the model's trained context from the GGUF (1,048,576). `STRATA_DS_CTX` lowers it. + It was checked against llama.cpp only up to a 1425-token prompt. +- Tool calls work in `serve`, but this path was not run against the model itself. +- The experts that miss VRAM are read from the GGUF, so decode speed moves with the page cache. See + [BENCHMARKS.md](BENCHMARKS.md). ## GLM-5.3-Flash (UD-Q2_K_XL, 119 GB) -`chat`, `generate` and `serve` detect the `glm5-next` architecture (Kimi-delta attention, sparse MLA attention, four-stream -hyper-connections, sigmoid MoE) and run the CPU reference forward, with the dense matvecs and an expert cache on the -CUDA card (`STRATA_DS_GPU_EXPERTS=` sets the budget, which also counts the non-expert weights; unset, it is 90% of -free VRAM, about 10 GB on a 12 GB card). Pass the first shard. - -```sh +```bash M=GLM-5.3-Flash-UD-Q2_K_XL-00001-of-00004.gguf rustingstrata chat --model $M rustingstrata generate --model $M --prompt "The capital of France is" -n 64 rustingstrata serve --model $M --addr 127.0.0.1:8080 [--api-key K] ``` -Greedy output equals llama.cpp b12119 (`--cpu-moe`) for 32 tokens on 3 fixed prompts on the CPU path; with the GPU matvecs -prompts 1 and 2 still match for 32 tokens and prompt 3 flips at the first token, a near-tie (logprob -2.65 against -2.73). Fed llama.cpp's own 64 tokens per prompt (teacher-forced), the GPU path picks the same top-1 on 188 of 192 steps; the four misses are llama.cpp near-ties (margins 0.03-0.53 logprob). Tokenizer ids -match llama.cpp on 29 test strings and the chat template matches `/apply-template` on 2 conversations. -On an RTX 3060 12 GB with 30 GB RAM decode took about 0.4-0.7 s per token with warm page cache (about 55% VRAM expert-cache -hits on a short text); after the 2026-11-12 batching and prompt-preload changes, `bench --pp 1 --tg 24` measured 2.3-2.6 tok/s -warm, 32-token runs fell to 1.5-1.8 tok/s as the page cache turned over, and a 128-token prompt with hot-expert preload -decoded at 1.6 tok/s. A paired run on 2026-11-13 (64 greedy tokens through `serve`, llama.cpp, ours, ours, llama.cpp; short prompt and `tools/prompts/bench-natural.txt`, 429 tokens) gave 1.35 tok/s decode against 0.62 on the long prompt and 1.57 against 0.57 on the short one, load until ready in 5 s against 66-73 s, and a first token after 84-93 s against 73-76 s on the long prompt; on the short prompt the first token came after 17-19 s with a warm page cache against 6-8 s. Everything moves with the page cache. A fresh teacher-forced check on 3 prompts x 32 tokens matched llama.cpp's top token on 96 of 96 steps (top-5 overlap 91.9%, mean |dlogprob| 0.230). -Caveats: prefill runs 512-token chunks layer by layer so each routed expert is read once per chunk (a 380-word, about 550-token prompt prefilled in 209 s with 512-token chunks against 325 s with 128, identical logprobs; short prompts cost more per token because the experts stream from SSD once per chunk, `STRATA_GLM_CHUNK` sets the size); prompt plus reply is limited only by the model's trained context from the GGUF (1,048,576; `STRATA_GLM_CTX` lowers it, and the KV cache grows with the text, so RAM is the real bound; the k-pool sparse-attention indexer takes over past 2048 rows and was checked against llama.cpp up to 3.6k tokens: same top-5 sets, same first token); the NextN/MTP layer is unused; decoding is greedy only; tool calls work in `serve` (the prompt matches llama.cpp's template byte for byte, checked on one tool call and one tool-result round trip); the reasoning -text comes back in `content` before ``. +- Pass the first shard. +- It needs a CUDA card. The weights take 90% of free VRAM, about 10 GB on a 12 GB card. +- Decoding is greedy. +- Prompt plus reply is limited by the model's trained context from the GGUF (1,048,576). `STRATA_GLM_CTX` lowers it. + The KV cache grows with the text, so RAM is the real bound. +- Long prompts were checked against llama.cpp up to 3.6k tokens. +- Short prompts cost more per token. The experts are read from the SSD once per 512-token chunk. +- Tool calls work in `serve`. The NextN/MTP layer is unused. +- The reasoning text comes back in `content` before ``. -## Hy4-flash (IQ2_S/IQ2_XXS, 85 GB) +Quality: fed llama.cpp's own 64 tokens per prompt, the GPU path picks the same top token on 188 of 192 steps. +Speed is in [BENCHMARKS.md](BENCHMARKS.md). -`chat`, `generate`, `serve` and `bench` detect the `hy_v4_flash` architecture (four-stream hyper-connections, gated MLA -attention with sinks, sliding-window and sparse layers, latent MoE, Engram) and run the forward in `src/hy4/`, with -the matvecs and an expert cache on the GPU (no `--gpu` flag needed). Pass the first shard. +## Hy4-flash (IQ2_S/IQ2_XXS, 85 GB) -```sh +```bash M=Hy4-flash-AD-IQ2_S-IQ2_XXS-00001-of-00002.gguf rustingstrata chat --model $M rustingstrata generate --model $M --prompt "The capital of France is" -n 64 rustingstrata serve --model $M --addr 127.0.0.1:8080 [--api-key K] ``` -The GPU is CUDA when an NVIDIA card and driver are present and Vulkan otherwise (AMD, Intel); `--backend vulkan` or -`--backend cuda` picks one, `--device 0,1` spreads the expert cache over several cards, and `STRATA_DS_GPU=0` runs -everything on the CPU. Experts that are not in VRAM are split between the CPU (straight from the mapped file) and the -GPU (during decoding, uploaded into the VRAM cache in place of the least recently used expert), and the split -follows the measured time of each side. `--fixed-experts` (or `STRATA_DS_CPU_SHARE=0`) sends every expert to the GPU, -which is slower here but gives the same text on every run. -The prompt runs layer by layer in chunks of `STRATA_DS_CHUNK` tokens (default 1024), so a routed expert is read once -for all the tokens of a chunk that picked it. When the files fit in RAM with 4 GiB to spare they are read into the -page cache in the background from the start (`STRATA_PRELOAD=0` turns that off). +Pass the first shard. + +| Flag or variable | What it does | +|---|---| +| `--backend vulkan`, `--backend cuda` | Picks the GPU backend. Default: CUDA with an NVIDIA card and driver, Vulkan otherwise (AMD, Intel) | +| `--device 0,1` | Spreads the expert cache over several cards | +| `--fixed-experts` | Sends every expert to the GPU. Slower here, but the same text on every run | +| `STRATA_DS_GPU=0` | Runs everything on the CPU | +| `STRATA_PRELOAD=0` | Turns off the background read of the files into the page cache | + +The background read starts only when the files fit in RAM with 4 GiB to spare. + +Limits: -On an RTX 3060 12 GB with 30 GB RAM and a Ryzen 5 7600X, `bench --pp 16,128,512 --tg 32 --reps 2` measured, with a -warm page cache: +- Decoding is greedy. +- Prompt plus reply is limited to `--ctx`. The default is the model's trained context, or 32768 when the file does + not say. +- Without `--fixed-experts` the greedy text can differ from run to run at near-ties. +- The greedy text can leave llama.cpp's with this IQ2 quant. The first greedy token matches. +- Not measured: an AMD or Intel card (the Vulkan path was run on the RTX 3060 only), more than one card, and a + machine whose RAM holds the whole model. + +Speed on an RTX 3060 12 GB with 30 GB RAM and a Ryzen 5 7600X, `bench --pp 16,128,512 --tg 32 --reps 2`, warm page +cache: | Backend | Prefill 16 / 128 / 512 tokens (tok/s) | Decode (tok/s) | |---|---|---| @@ -152,81 +268,54 @@ warm page cache: | Vulkan (same card) | 1.3 / 8.5 / 13.5 | 2.0 / 3.6 / 3.7 | | CPU only (`STRATA_DS_GPU=0`) | 2.5 / 3.0 / 4.1 | 2.4 / 2.2 / 1.7 | -A 20,000-token prompt of text that does not repeat (this repository's documentation followed by Rust source, -`bench --prompt-file F --pp 20000 --tg 64 --reps 1`, one run each) prefilled at 11.6 tok/s on CUDA and 10.6 tok/s on -Vulkan, and the 64 tokens after it decoded at 3.3 and 1.9 tok/s. - -A token reads about 1.3 GB of expert weights and the model is larger than this box's RAM, so the numbers move with -the page cache; the expert cache policy knobs (`STRATA_DS_LFU`, `STRATA_DS_NOEVICT`) changed nothing measurable. A -CPU-only build of the llama.cpp pull request that adds the model (#32517) decoded at 0.28 tok/s on the same box (one -run, not side by side). Not measured: an AMD or Intel card (the Vulkan path was run on the RTX 3060 only), more than -one card, and a machine whose RAM holds the whole model. - -Checked against that llama.cpp build with tensor dumps: the first greedy token matches, and the last layer's output -differs from llama.cpp's by 14-20%, no more than this engine's integer and f32 paths differ from each other (19%). With -this IQ2 quant that is enough for greedy text to leave llama.cpp's at flat positions. The k-pool indexer of the sparse layers, which takes over past 2048 tokens, was checked -on a 2619-token prompt for layers 0 and 1: its tensors are within 0.2% and at least 508 of the 511 kept groups are the -same at every position (the disputed groups score within 0.1% of the cut). -Caveats: decoding is greedy only, and prompt plus reply is limited to 32,768 tokens (`MAX_CTX` in -`src/hy4/forward.rs`; every layer keeps the key rows of all positions). The GPU and CPU kernels round differently, so -with the adaptive split and with chunked prefill the greedy text can differ from run to run at near-ties; chunked and -token-by-token prefill give the same logits within 1e-3 on the CPU path. `tests/hy4_forward.rs` runs when -`STRATA_HY4_MODEL` points at the first shard. +- A 20,000-token prompt (`bench --prompt-file F --pp 20000 --tg 64 --reps 1`, one run each) prefilled at 11.6 tok/s on + CUDA and 10.6 tok/s on Vulkan. The 64 tokens after it decoded at 3.3 and 1.9 tok/s. +- llama.cpp (CPU-only build of pull request #32517) decoded at 0.28 tok/s on the same machine, one run. ## Inkling 2 Mini (IQ4_NL, 17.6 GB) -`chat`, `generate`, `serve` and `bench` detect the `inkling2_loop` and `inkling2` architectures (Thinking Machines Inkling 2: 24 -layers of which layers 6-17 run three times with message controllers between the passes, so a token is 48 layer runs; -sliding-window attention with a relative bias and sinks, full attention on every sixth layer; 128 experts, 8 used) and -run the forward in `src/inkling2/`, with the matvecs and an expert cache on the GPU (no `--gpu` flag needed). - -```sh +```bash M=Inkling-2-Mini-IQ4_NL.gguf rustingstrata chat --model $M rustingstrata generate --model $M --prompt "The capital of France is" -n 64 rustingstrata serve --model $M --addr 127.0.0.1:8080 [--api-key K] ``` -Unsloth's quants load as well: the files in the `Mainline_Support` folder of `unsloth/Inkling-2-Mini-GGUF` -(architecture `inkling2_loop`), whose experts are NVFP4 with a per-expert `ffn_gate_up_exps.scale` and -`ffn_down_exps.scale`. If a file is named `.gguf_file`, rename it to `.gguf` so the chat page lists it. The files at -the top of that repo use the architecture name `inkling2` and the tensor layout of llama.cpp PR #32695 (one array -entry per layer run, the message queries in `loop_res_query` and `loop_kv_res_query`); they load as well. - -The backend, device and expert options are those of Hy4-flash above: CUDA when an NVIDIA card and driver are present -and Vulkan otherwise, `--backend vulkan` or `--backend cuda` to pick one, `STRATA_DS_GPU=0` for the CPU only, and -`--fixed-experts` for the same text on every run. The prompt runs layer by layer in chunks of `STRATA_DS_CHUNK` tokens -(default 512). The weights take `STRATA_DS_GPU_FRACTION` of the free VRAM (default 0.9, and 0.6 on a card with less than 8 GB -free; a pair such as `0.6,0.9` sets both); the experts that do not fit run on the CPU. - -On an RTX 3060 12 GB with 30 GB RAM and a Ryzen 5 7600X, `bench --pp 64,512,2048 --tg 64 --reps 2` measured (mean of -the two runs, and the two runs): - -| Backend | Prefill 64 / 512 / 2048 tokens (tok/s) | Decode after them (tok/s) | -|---|---|---| -| CUDA | 120.7 (59.2, 182.2) / 259.2 (254.6, 263.9) / 220.2 (218.7, 221.8) | 34.5 / 31.2 / 31.2 | -| Vulkan (same card) | 82.7 (34.5, 130.9) / 226.9 (226.6, 227.1) / 182.6 (179.0, 186.2) | 27.3 / 27.5 / 24.5 | -| CPU only (`STRATA_DS_GPU=0`) | 47.5 / 49.8 / 48.2 | 11.8 / 11.6 / 10.9 | - -The first run of the 64-token prompt is the first work of the process and is the slow one of the two. The decode -column was measured again after a decoded token moved onto the GPU (attention, controllers and mixes in VRAM, one -round trip per layer run for the CPU experts), with the GPU shared with a desktop; the prefill path did not change -(alternating runs within 1-4%). `STRATA_DS_DEVICE=0` runs a decoded token on the host like the prompt. -llama.cpp c622f62 built with CUDA, in the same session (`llama-bench -t 6 -r 2`; `-ngl 99` runs out of VRAM): -with `-ngl 18` prefill 124.7 / 383.9 / 322.6 tok/s and decode 8.7 tok/s, with `-ngl 0` prefill 122.3 / 377.5 tok/s -(64 / 512) and decode 10.5 tok/s. So on this box the prompt is read at 0.6-0.7 of llama.cpp's speed from 512 tokens -on, and the reply is written 3.0-4.0 times as fast. `llama-bench` decodes from an empty context and `bench` decodes -after the prompt. More in [BENCHMARKS.md](BENCHMARKS.md#inkling-2-mini-iq4_nl-176-gb). -Not measured: an AMD or Intel card (the Vulkan path was run on the RTX 3060 only) and more than one card. - -Checked against llama.cpp c622f62 (CPU, temperature 0) by feeding its greedy tokens through this forward: every top -token is the same on a short prompt (24 of 24) and at most one differs on a prompt of several hundred tokens (48 -tokens, a near tie), on the CPU, CUDA and Vulkan paths. `tests/inkling2_forward.rs` runs these when -`STRATA_INKLING2_MODEL` points at the file. With unsloth's `Inkling-2-Mini-UD-Q4_K_M.gguf` (NVFP4 experts), the -32-token greedy text of llama.cpp c622f62 (CUDA, `-ngl 18`) was compared on three prompts: the CPU path matched on two -and CUDA on two (Vulkan, run on the first prompt only, gave the CUDA text). Each difference starts at a token where llama.cpp's own top two -log-probabilities are 0.01 and 0.16 apart. -Caveats: image input through `--mmproj` was not checked on this machine (no projector file here), and prompt plus reply is -limited to `--ctx` (default: the context the model was trained on). The GPU and CPU kernels round differently, so with -the adaptive split and with chunked prefill the greedy text can differ from run to run at near-ties; chunked and -token-by-token prefill give the same logits within 1e-3 on the CPU path. +Unsloth's quants from `unsloth/Inkling-2-Mini-GGUF` load too: + +- The files in the `Mainline_Support` folder (`inkling2_loop`, NVFP4 experts). +- The files at the top of that repo (`inkling2`, the tensor layout of llama.cpp PR #32695). +- If a file is named `.gguf_file`, rename it to `.gguf` so the chat page lists it. + +The backend and expert options are those of [Hy4-flash](#hy4-flash-iq2_siq2_xxs-85-gb): `--backend`, +`STRATA_DS_GPU=0` and `--fixed-experts`. + +Limits: + +- Prompt plus reply is limited to `--ctx`. The default is the model's trained context. +- Image input through `--mmproj` was not checked on the reference machine. +- Without `--fixed-experts` the greedy text can differ from run to run at near-ties. +- Not measured: an AMD or Intel card (the Vulkan path was run on the RTX 3060 only) and more than one card. + +Quality: same top token as llama.cpp c622f62 at 24 of 24 steps on a short prompt. At most one of 48 differs on a +prompt of several hundred tokens, on CPU, CUDA and Vulkan. Speed is in [BENCHMARKS.md](BENCHMARKS.md). + +## Test and tuning switches + +| Name | What it does | +|---|---| +| `STRATA_DS_CHUNK` | Prompt chunk in tokens: default 1024 for Hy4-flash, Kolibri 1.1 and GigaChat 4, 512 for DeepSeek. Inkling 2: 2048 on one card, 512 on several | +| `STRATA_GLM_CHUNK` | Prompt chunk for GLM, default 512 | +| `STRATA_G4_CHUNK` | Prompt chunk for Gemma 4, default 256. 1 is token by token | +| `STRATA_G4_PROF` | `1` prints the prefill and decode times of Gemma 4 | +| `STRATA_DS_PROF` | `1` prints prefill timings | +| `STRATA_DS_CPU_SHARE` | Share of the missed experts that the CPU takes. 0 sends every expert to the GPU | +| `STRATA_FIXED_EXPERTS` | Same as `--fixed-experts` | +| `STRATA_DS_DEVICE` | `0` runs a decoded token of Inkling 2 on the host | +| `STRATA_DS_LFU`, `STRATA_DS_NOEVICT` | Expert cache policy. Nothing measurable changed on Hy4-flash | +| `STRATA_KOL_CPU_ATTN` | `1` keeps the attention of a Kolibri 1.1 prompt chunk on the CPU | +| `STRATA_GIGA_CPU_ATTN` | `1` runs the attention and the indexer of GigaChat 4 on the CPU | +| `STRATA_Q4K_X8` | `0` turns off the 8-row CPU kernels for Q4_K and Q6_K experts | +| `STRATA_NO_PAGEOUT` | `1` keeps uploaded experts in the page cache | +| `STRATA_BENCH_LAYER` | Layer of the ignored test `gemm_expert_throughput` in `tests/kernels.rs` | +| `STRATA_QWEN4_TOKENIZER`, `STRATA_HY4_MODEL`, `STRATA_INKLING2_MODEL` | Files for `tests/qwen4_tokenizer.rs`, `tests/hy4_forward.rs` and `tests/inkling2_forward.rs` | diff --git a/docs/README.md b/docs/README.md index 426cbad0..b335feef 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,23 +1,29 @@ # Docs +Install, quick start and the headline numbers are in the [README](../README.md). + ## Guides -- [USAGE.md](USAGE.md): flags, server API, prompt caching, several GPUs. -- [MODELS.md](MODELS.md): supported architectures and GGUF types, notes and caveats for each model. +- [USAGE.md](USAGE.md): every command and flag, the chat page, the server API, prompt caching, several GPUs. +- [MODELS.md](MODELS.md): supported models and GGUF types, and the notes for each model. - [HOSTING.md](HOSTING.md): running a server for other people (keys, TLS, systemd, usage log). -- [LORA.md](LORA.md): runtime LoRA / abliteration adapters. +- [CALIBRATION.md](CALIBRATION.md): `rustingstrata calibrate` and the file it writes. +- [VISION.md](VISION.md): image input. +- [LORA.md](LORA.md): LoRA and abliteration adapters. - [SUPPORTED_GPUS.md](SUPPORTED_GPUS.md): every GPU tried so far. - [AMD.md](AMD.md): known AMD issues and what to send in a report. +- [HIP.md](HIP.md): the HIP (ROCm) backend for AMD cards. +- [DEEPSEEK_L40S.md](DEEPSEEK_L40S.md): settings for DeepSeek-V4.1 on 2x L40S, not yet measured on that machine. ## Benchmark history -- [BENCHMARKS.md](BENCHMARKS.md): every model against llama.cpp (and other engines where measured), one table per model. +- [BENCHMARKS.md](BENCHMARKS.md): every model against llama.cpp, and other engines where measured. -Raw results and methods, newest work last. The headline numbers are in the [README](../README.md). +Raw results of single runs: - [baseline.md](baseline.md): llama.cpp baseline and `--n-cpu-moe` sweep on the RTX 3060. - [m2-results.md](m2-results.md): GPU forward and parity. - [m4-results.md](m4-results.md): chunked prefill. - [m6-results.md](m6-results.md): v1.0 gate run against llama.cpp. -- [V100-results.md](V100-results.md): V100 bring-up, parity and benchmarks (long; written by `tools/bench_v100.sh`). +- [V100-results.md](V100-results.md): V100 parity and benchmarks, written by `tools/bench_v100.sh`. - [datacenter-nvidia-results.md](datacenter-nvidia-results.md): A100, A30, L40S and H100 test runs and benchmarks. diff --git a/docs/SUPPORTED_GPUS.md b/docs/SUPPORTED_GPUS.md index 6c11a351..3ea3930b 100644 --- a/docs/SUPPORTED_GPUS.md +++ b/docs/SUPPORTED_GPUS.md @@ -1,36 +1,88 @@ # Supported GPUs -Every GPU that has run RustingStrata, what was tested on it, and by whom. "Tested" means a person ran it on that card; -"compiles" means the source builds for that architecture but nobody has run it there. Numbers are from -`rustingstrata bench` on `Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf` unless the row says otherwise, and are only comparable within one -row. +Find your card in the first table. "Tested" means a person ran RustingStrata on that card. "Compiles" means the +source builds for that architecture but nobody has run it there. + +AMD setup is in [AMD.md](AMD.md). The experimental HIP backend, brought up on an RX 9070 XT, is in [HIP.md](HIP.md). ## Tested | GPU | Arch | Backend | Status | Tested by | Notes | | --- | --- | --- | --- | --- | --- | -| NVIDIA RTX 3060 12 GB | Ampere, sm_86 | CUDA | Reference, full test suite passes | maintainer | pp 4096 prefill ~1570 tok/s, decode ~108 tok/s (MTP on, all but ~1% of expert reads hit the GPU cache). Int8 tensor-core GEMM. | -| NVIDIA RTX 3060 12 GB | Ampere, sm_86 | Vulkan | Full test suite passes | maintainer | Cooperative matrices (f16 and int8). Prefill is slower than CUDA. | -| NVIDIA Tesla V100-SXM2 32 GB | Volta, sm_70 | CUDA | Runs, parity measured | TheBrutalX | `m8n8k4` tensor cores, no int8 GEMM (f16 GEMM instead), no `cp.async`. Needs the CUDA 12.x NVRTC (CUDA 13 dropped sm_70). Bring-up: pp 512 836 tok/s, decode 116 tok/s. See [V100-results.md](V100-results.md). | -| NVIDIA Tesla V100-SXM2 32 GB | Volta, sm_70 | Vulkan | Runs, parity measured | TheBrutalX | No cooperative matrices, so the `_dp` kernels run. pp 4096 prefill ~1400 tok/s, decode ~110 tok/s. The f16 GEMM input conversion truncates on this driver; run the kernel tests with `STRATA_VK_F16_TRUNC=1` there. | -| AMD Radeon VII (Vega 20) | GCN5, wave64 | Vulkan | Runs | masanork (PR #5) | RADV Mesa 26.0.8. Each 64-lane subgroup runs as two logical 32-lane warps. See [AMD.md](AMD.md). | +| NVIDIA RTX 3060 12 GB | Ampere, sm_86 | CUDA | Reference, full test suite passes | maintainer | Int8 tensor-core GEMM. | +| NVIDIA RTX 3060 12 GB | Ampere, sm_86 | Vulkan | Full test suite passes | maintainer | Prefill is slower than CUDA. | +| NVIDIA Tesla V100-SXM2 32 GB | Volta, sm_70 | CUDA | Runs, parity measured | TheBrutalX | Needs the CUDA 12.x NVRTC (CUDA 13 dropped sm_70). See [V100-results.md](V100-results.md). | +| NVIDIA Tesla V100-SXM2 32 GB | Volta, sm_70 | Vulkan | Runs, parity measured | TheBrutalX | No cooperative matrices. Run the kernel tests with `STRATA_VK_F16_TRUNC=1` on this driver. | +| AMD Radeon VII (Vega 20) | GCN5, wave64 | Vulkan | Runs | masanork (PR #5) | RADV Mesa 26.0.8. See [AMD.md](AMD.md). | | AMD Radeon RX 9070 XT | RDNA 4 | Vulkan | Runs, known issues | user reports | Linux (RADV) and Windows (AMD driver). See [AMD.md](AMD.md) for the issues and what to send. | -| NVIDIA Turing card | Turing, sm_75 | CUDA | Runs | x-Pepsy (PR #6) | `m16n8k8` tensor cores, no int8 GEMM, 64 KB shared memory (16-key prefill tile at head_dim 256). The GPU model was not recorded in the PR. | -| NVIDIA A100-SXM4 80 GB | Ampere, sm_80 | CUDA | Full test suite passes | yugt | pp 4096 prefill 6203 tok/s, decode 174 tok/s (MTP off, whole model in VRAM). See [datacenter-nvidia-results.md](datacenter-nvidia-results.md). Calibrated in a later job: decode 280 tok/s with MTP 1, 174 with `--mtp 0`. | -| NVIDIA A100-SXM4 80 GB | Ampere, sm_80 | Vulkan | Full test suite passes with `--test-threads=1`; default parallel runs can hang in `vkDestroyDevice` on this driver ([details](datacenter-nvidia-results.md#2026-11-10--parallel-tests-can-hang-in-vkdestroydevice-on-this-driver)) | yugt | Cooperative matrices (f16 and int8). pp 4096 prefill 5589 tok/s, decode 132 tok/s. Calibrated in a later job: decode 234 tok/s with MTP 2, 118 with `--mtp 0`. | -| NVIDIA A30 24 GB | Ampere, sm_80 | CUDA | Full test suite passes | yugt | pp 4096 prefill 3544 tok/s, decode 132 tok/s. Calibrated in a later job: decode 193 tok/s with MTP 1, 132 with `--mtp 0`. | -| NVIDIA A30 24 GB | Ampere, sm_80 | Vulkan | Full test suite passes with `--test-threads=1`; default parallel runs can hang in `vkDestroyDevice` on this driver ([details](datacenter-nvidia-results.md#2026-11-10--parallel-tests-can-hang-in-vkdestroydevice-on-this-driver)) | yugt | Cooperative matrices (f16 and int8). pp 4096 prefill 3326 tok/s, decode 104 tok/s. Calibrated in a later job: decode 162 tok/s with MTP 2, 108 with `--mtp 0`. | -| NVIDIA L40S 48 GB | Ada, sm_89 | CUDA | Full test suite passes | yugt | pp 4096 prefill 9030 tok/s, decode 213 tok/s. Calibrated in a later job: decode 407 tok/s with MTP 2, 214 with `--mtp 0`. | -| NVIDIA L40S 48 GB | Ada, sm_89 | Vulkan | Full test suite passes | yugt | Cooperative matrices (f16 and int8). pp 4096 prefill 8571 tok/s, decode 185 tok/s. Calibrated in a later job: decode 317 tok/s with MTP 2, 197 with `--mtp 0`. | -| NVIDIA H100 NVL 94 GB, H100 80 GB | Hopper, sm_90 | CUDA | Full test suite passes | yugt | pp 4096 prefill 9131 tok/s, decode 246 tok/s (H100 NVL). Calibrated in a later job on an H100 80 GB: decode 498 tok/s with MTP 2, 265 with `--mtp 0`. | -| NVIDIA H100 NVL 94 GB, H100 80 GB | Hopper, sm_90 | Vulkan | Full test suite passes | yugt | Cooperative matrices (f16 and int8). pp 4096 prefill 6428 tok/s, decode 192 tok/s (H100 NVL). Calibrated in a later job on an H100 80 GB: decode 363 tok/s with MTP 2, 216 with `--mtp 0`. | +| NVIDIA Turing card | Turing, sm_75 | CUDA | Runs | x-Pepsy (PR #6) | The GPU model was not recorded in the PR. | +| NVIDIA GeForce GTX 1660 SUPER 6 GB | Turing, sm_75 (TU116, no tensor cores) | CUDA | Runs | PedroRossi | MTP 1-4 measured slower than off here. | +| NVIDIA GeForce GTX 1660 SUPER 6 GB | Turing, sm_75 (TU116) | Vulkan | Runs | PedroRossi | No cooperative matrices. | +| NVIDIA GeForce GTX 1650 Max-Q 4 GB | Turing, sm_75 (TU117, no tensor cores) | CUDA | Runs, parity measured | keylimesoda | | +| NVIDIA A100-SXM4 80 GB | Ampere, sm_80 | CUDA | Full test suite passes | yugt | See [datacenter-nvidia-results.md](datacenter-nvidia-results.md). | +| NVIDIA A100-SXM4 80 GB | Ampere, sm_80 | Vulkan | Full test suite passes with `--test-threads=1`; default parallel runs can hang in `vkDestroyDevice` on this driver ([details](datacenter-nvidia-results.md#2026-11-10-parallel-tests-can-hang-in-vkdestroydevice-on-this-driver)) | yugt | | +| NVIDIA A30 24 GB | Ampere, sm_80 | CUDA | Full test suite passes | yugt | | +| NVIDIA A30 24 GB | Ampere, sm_80 | Vulkan | Full test suite passes with `--test-threads=1`; default parallel runs can hang in `vkDestroyDevice` on this driver ([details](datacenter-nvidia-results.md#2026-11-10-parallel-tests-can-hang-in-vkdestroydevice-on-this-driver)) | yugt | | +| NVIDIA L40S 48 GB | Ada, sm_89 | CUDA | Full test suite passes | yugt | | +| NVIDIA L40S 48 GB | Ada, sm_89 | Vulkan | Full test suite passes | yugt | | +| NVIDIA H100 NVL 94 GB, H100 80 GB | Hopper, sm_90 | CUDA | Full test suite passes | yugt | | +| NVIDIA H100 NVL 94 GB, H100 80 GB | Hopper, sm_90 | Vulkan | Full test suite passes | yugt | | + +The tested Ampere, Ada and Hopper cards have cooperative matrices (f16 and int8) on Vulkan. + +## Measured speed + +`rustingstrata bench` on `Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf`. Compare numbers only within one row. More tables are in +[BENCHMARKS.md](BENCHMARKS.md). + +| GPU | Backend | Prefill, pp 4096 (tok/s) | Decode (tok/s) | Calibrated in a later job: decode (tok/s) | Same job, `--mtp 0` | +| --- | --- | --- | --- | --- | --- | +| RTX 3060 12 GB | CUDA | ~1570 | ~108 | | | +| Tesla V100-SXM2 32 GB | CUDA | pp 512: 836 | 116 | | | +| Tesla V100-SXM2 32 GB | Vulkan | ~1400 | ~110 | | | +| A100-SXM4 80 GB | CUDA | 6203 | 174 | 280 with MTP 1 | 174 | +| A100-SXM4 80 GB | Vulkan | 5589 | 132 | 234 with MTP 2 | 118 | +| A30 24 GB | CUDA | 3544 | 132 | 193 with MTP 1 | 132 | +| A30 24 GB | Vulkan | 3326 | 104 | 162 with MTP 2 | 108 | +| L40S 48 GB | CUDA | 9030 | 213 | 407 with MTP 2 | 214 | +| L40S 48 GB | Vulkan | 8571 | 185 | 317 with MTP 2 | 197 | +| H100 NVL 94 GB | CUDA | 9131 | 246 | 498 with MTP 2 (H100 80 GB) | 265 | +| H100 NVL 94 GB | Vulkan | 6428 | 192 | 363 with MTP 2 (H100 80 GB) | 216 | + +- RTX 3060: MTP on, all but ~1% of expert reads hit the GPU cache. +- V100 CUDA: the bring-up run. +- A100 CUDA: MTP off, whole model in VRAM. + +### GTX 1660 SUPER 6 GB + +`bench --prompt-file` on real text (prose and code), pp 4096 / 16384, GPU clocks locked at 1200 MHz. CUDA: MTP off, +`--ctx 32768`, 2,494 of 10,240 experts resident, driver 550.163.01, NVRTC 12.4. + +| Backend | Path | Prefill | Decode | +| --- | --- | --- | --- | +| CUDA | `MMA_FMA` (default) | 214 / 162 tok/s | 50.0 / 44.2 tok/s | +| CUDA | `m16n8k8` | 103 / 88 tok/s | 50.0 / 44.2 tok/s | +| Vulkan | `_dp` kernels | 274 / 188 tok/s | 38.0 / 33.6 tok/s | + +### GTX 1650 Max-Q 4 GB + +`Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf`, `--ctx 131072 --kv q4 --mtp 0`, real code+docs prompt, CUDA. 35 W TDP, 29 of +10,240 experts resident, driver 620.70.06, NVRTC 13.4. + +| Path | Prefill, pp 4096 / 16384 / 32768 | +| --- | --- | +| `MMA_FMA` with `__dp4a` int8 GEMM (default) | 420.1 / 332.7 / 254.9 tok/s | +| f16 `MMA_FMA` | 191.5 / 149.1 / 115.4 tok/s | +| `m16n8k8` | 113.1 / 95.7 tok/s | + +Decode: 17.9 / 17.4 / 16.3 tok/s. ## Compiles, not run | GPU class | Arch | Backend | What is checked | | --- | --- | --- | --- | -| Turing | sm_75 | CUDA | `cargo test` compiles the whole source with NVRTC for sm_75 (`nvrtc_compiles_full_source_for_sm75`). | -| Volta | sm_70 | CUDA | Same with an NVRTC 12.x (`nvrtc_compiles_full_source_for_sm70`); skipped on CUDA 13. | +| Turing | sm_75 | CUDA | `cargo test` compiles the whole source with NVRTC for sm_75, with and without `MMA_FMA`. | +| Volta | sm_70 | CUDA | Same with an NVRTC 12.x. Skipped on CUDA 13. | ## Not supported @@ -45,17 +97,32 @@ row. | Arch | Matrix multiply | Int8 GEMM | Async copy | Shared memory per block | | --- | --- | --- | --- | --- | | sm_80 and newer | `mma.m16n8k16` | yes | `cp.async` | 100 KB or more | -| sm_75 | `mma.m16n8k8` (two steps per k16) | no | register copy | 64 KB | +| sm_75 with tensor cores | `mma.m16n8k8` (two steps per k16) | no | register copy | 64 KB | +| sm_75 without tensor cores (TU116/TU117) | `MMA_FMA`, with `fma.rn.f16x2` prefill attention | `__dp4a` (IQ2_XS and IQ2_S included) | register copy | 64 KB | | sm_70 | `mma.m8n8k4` (`GEMM_TC`), or CUDA-core FMA with `STRATA_GEMM_FMA=1` | no | register copy | 96 KB opt-in | +TU116/TU117 cards are the GTX 16 series, MX450/MX550, T400-T2000 and CMP 30HX. + +| Variable | What it does | +| --- | --- | +| `STRATA_GEMM_FMA=1` | Selects the `MMA_FMA` path on any sm_75 card. | +| `STRATA_NO_DP4A=1` | Keeps f16 GEMMs. | +| `STRATA_GEMM_TC=1` | Keeps `m16n8k8`. | + ## Add your GPU Open an issue or PR that adds a row. Please send: -1. The first lines of output (`cuda device ...` or `vulkan: ...`), which name the GPU, driver and capabilities. -2. `rustingstrata bench --model --gpu --pp 512,4096 --tg 128 --reps 3` and the model file name. -3. `cargo test --release` result (or the failing test names), and `rustingstrata check --backend vulkan --model ` for - Vulkan. -4. Anything that failed: the exact error text. +1. The first lines of output with `STRATA_VERBOSE=1` (`cuda device ...` or `vulkan: ...`). They name the GPU, driver + and capabilities. +2. The model file name and the output of this command: + + ```bash + rustingstrata bench --model --gpu --pp 512,4096 --tg 128 --reps 3 + ``` + +3. The `cargo test --release` result or the failing test names. For Vulkan, also + `rustingstrata check --backend vulkan --model `. +4. The exact error text of anything that failed. Mark rows "Tested" only for cards you ran yourself. diff --git a/docs/USAGE.md b/docs/USAGE.md index f22cff24..48c2e807 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -1,264 +1,535 @@ # Usage -Everything here applies to `rustingstrata chat`, `generate`, `bench` and `serve` unless noted. See the -[README](../README.md) for install and a quick start, and [HOSTING.md](HOSTING.md) for running a server for other people. +Every command, flag and environment variable of `rustingstrata`. Install and quick start: [README](../README.md). +A server for other people: [HOSTING.md](HOSTING.md). Measured speeds: [BENCHMARKS.md](BENCHMARKS.md). + +## Commands + +| Command | What it does | +|---|---| +| (none) | Starts the server on http://127.0.0.1:8080 and opens the chat page. | +| `interface` | Asks for the model, the mode and the main settings, then runs the command they make. | +| `chat --model M` | Chat in the terminal. `-n` limits a reply (default 2048 tokens). | +| `generate --model M --prompt TEXT` | Generates `-n` tokens (default 32). `--prompt -` reads stdin. | +| `serve` | Chat page and API server. See [Server API](#server-api). | +| `bench --model M` | Speed test. Defaults: `--pp 512,4096`, `--tg 128`, `--reps 3`. | +| `calibrate --model M` | Measures the best settings for this machine. See [Calibration](#calibration). | +| `stats` | Prints what `serve` answered over all runs, by model and by API key name. | +| `update` | Replaces the binary with the newest release. `update --check` only checks. | +| `info`, `check`, `perplexity`, `score` | Developer tools. Run them with `--help`. | + +A failed command prints one `error: ...` line and exits with status 1. Colours go only to a terminal. `NO_COLOR=1` +turns them off. + +`serve` adds each answered chat to `usage.json` next to the default models folder +(`~/.local/share/rusting_strata/usage.json` on Linux). Delete the file to start `stats` again. ## Terminal -`rustingstrata interface` is a short set of questions in the terminal: the model (a numbered list of the models -folder and of the Hugging Face and llama.cpp caches; its last row takes a path to one file, or to a folder whose -models it then lists), the mode (chat in the terminal, -chat page in the browser, API server, speed test), GPU or CPU, the context length and, for a server, the address. -Enter takes the default in brackets. It prints the command the answers make and runs it, so the command can be -copied for the next time. `--models-dir DIR` lists another folder. +`rustingstrata interface` asks for the model, the mode (terminal chat, chat page, API server or speed test), GPU or CPU, +the context length and, for a server, the address. Enter takes the default in brackets. It prints the command it runs, +so you can copy it. + +- Models: the last 10 picked here, the models folder, and the Hugging Face and llama.cpp caches. The last row takes a + path to a file or a folder. `--models-dir DIR` lists another folder. +- GPUs: every NVIDIA card by default. For other cards type their numbers, such as 0,1. -On a terminal the engine's notes on stderr are dim, `warning` and `error` are coloured, and the terminal chats show -the prompt in colour and the reasoning dim. Output that goes to a pipe or a file has no escape codes; `NO_COLOR=1` -turns them off on a terminal too. A failed command prints one `error: ...` line and exits with status 1. +| Flag | Default | What it does | +|---|---|---| +| `--pretty` | off | Status panel on stderr instead of the timestamped speed logs. Needs a terminal, not `TERM=dumb`. | +| `--graph` | off | Adds Braille graphs of prefill and decode speed. Requires `--pretty`. | +| `--status-interval T` | `500ms` with `--pretty`, else `2s` | `100ms` through `5s`. Or `STRATA_STATUS_INTERVAL`; the flag wins. | + +`update` works on Linux and Windows x86_64. The old binary stays as `rustingstrata.old` until the next update. A +source build is replaced by the release build. A binary under `/usr/` or `/opt/` (the AUR package +`rustingstrata-bin`) or in winget's or Scoop's folders is left alone: use the package manager. + +At start, `serve` and a double-clicked binary ask GitHub once, with a 5 s limit, and print one line if a newer release +is out. `STRATA_NO_UPDATE_CHECK=1` turns that off. ## Chat page -`rustingstrata` with no arguments starts the server on http://127.0.0.1:8080 and opens a chat page. The page keeps chats in -the browser, downloads models from Hugging Face (settings; `HF_TOKEN` for gated repos), switches between the -models in the models folder (`%LOCALAPPDATA%\rusting_strata\models` on Windows, `~/.local/share/rusting_strata/models` -elsewhere, or `serve --models-dir`) and the GGUF files that the Hugging Face cache (`~/.cache/huggingface/hub`, -`HF_HUB_CACHE`, `HF_HOME`; `hf download` and llama.cpp `-hf`) and llama.cpp's cache (`~/.cache/llama.cpp`, `LLAMA_CACHE`) -already hold, loads a `.gguf` file from any other folder by its full path (settings, models; -`POST /api/load` with `"path"`, admin key only; the path is one the server sees, so in a container it is a path inside -the container), and shows context use, speed, totals, and CPU, memory and graphics memory use of -the server (status bar at the bottom; click it for details). - -Messages can be edited and resent, deleted, regenerated, and a reply that stopped at the token limit or was stopped by -hand can be continued. Settings hold the sampler values (`temperature`, `top_p`, `top_k`, `seed`, stop strings, max -tokens; empty fields leave the server's flags in effect), named presets, instructions for one chat, and export of chats -as Markdown or JSON and import of a JSON export. The models tab also holds load options (`--ctx`, `--kv`, `--cache-ram`, -`--vram-margin`, `--mtp`, `--chunk`): "apply and reload" loads the model again with them, and they stay until the server -restarts (`POST /api/load` takes them as `options`, admin key only). For a GPU model with no calibration file the -page says so and offers "calibrate", which measures the model and loads it with the result (`POST /api/load` with -`"calibrate": true`). The accent color follows the loaded model's -family (Qwen purple, DeepSeek blue, Gemma multicolor, Flint and GLM gray, anything else green); "color theme" in the -connection and data tab picks one color by hand instead. Open the page with `#selftest` at the end of the address to run its -built-in checks. +`rustingstrata` with no arguments opens the chat page. Chats are kept in the browser. The page offers these models: + +- The models folder: `%LOCALAPPDATA%\rusting_strata\models` on Windows, `~/.local/share/rusting_strata/models` + elsewhere, or `serve --models-dir`. +- GGUF files in the Hugging Face cache (`~/.cache/huggingface/hub`, `HF_HUB_CACHE`, `HF_HOME`) and in llama.cpp's + cache (`~/.cache/llama.cpp`, `LLAMA_CACHE`). +- Downloads from Hugging Face. Set `HF_TOKEN` for gated repos. +- A `.gguf` file by the full path the server sees. In a container that is a path inside the container. + +Empty sampler fields in the settings leave the server's flags in effect. `#selftest` after the address runs the page's +checks. + +The models tab sets `--ctx`, `--kv`, `--cache-ram`, `--vram-margin`, `--mtp`, `--chunk`, `--parallel`, `--device` and +`--auto-unload`. "Apply and reload" loads the model again with them. They stay until the server restarts. `--threads` +is not there: the thread pool is made once, at the first load. For a GPU model with no calibration file the page +offers "calibrate". + +`POST /api/load` does the same for a script, with the admin key only. It takes `"path"`, `"calibrate": true` and +`"options"`: `ctx`, `kv`, `cache_ram`, `vram_margin`, `mtp`, `chunk`, `parallel`, `device` as a string such as +`"0,1"`, `auto_unload` in seconds (0 for never), `status_interval`, `pretty` and `graph`. ### Tools (MCP) -The chat page can call the tools of Model Context Protocol servers. List the servers in a JSON file, in the format -other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the default is `mcp.json` in the -`rusting_strata` folder that holds the default models folder): - - {"mcpServers": { - "files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/me/notes"]}, - "docs": {"url": "https://example.com/mcp", "headers": {"Authorization": "Bearer ..."}} - }} - -- Servers start when the page first asks for them. The tools tab in settings shows each server, its tools and why a - server did not start; untick a server or a tool to keep it from the model. The `tools` switch beside `think` - turns tools on for the replies. -- Each call waits for your answer unless "run tools without asking" is on. The same tab sets how many tool rounds one - reply may take and how long a tool result may be. -- Only tools with text results. Resources, prompts, sampling and OAuth sign-in are not supported. -- Servers come only from the file: the page cannot add a command. The routes (`GET /api/mcp`, `POST /api/mcp/reload`, - `POST /api/mcp/call`) need the admin key when keys are set; customer keys cannot use them. Without keys they answer - only requests from the same computer that name it `localhost`, `127.0.0.1` or `[::1]` and carry no proxy header - (`Forwarded`, `X-Forwarded-*`, `X-Real-IP`). Set `--api-key` to use tools from another machine, and always set it - behind a reverse proxy or a tunnel: a proxy that adds no such header looks like a local browser. -- Tool definitions are part of the prompt. Many tools cost context and prefill time; switch off what a chat does not - need. -- The model needs a chat template with tool calls (the Qwen families have one). -- API clients are not affected: `/v1/chat/completions` and `/v1/messages` take the client's own `tools` as before. -- `STRATA_MCP_TIMEOUT` (seconds, default 120) is how long one answer from a server may take. -- On Windows a command starts through `cmd /c` (for the `npx`/`uvx` shims); this path is not tested yet. +The chat page can call the tools of Model Context Protocol servers. List them in a JSON file, in the format other MCP +clients use. Pass it with `serve --mcp FILE` or `STRATA_MCP`. The default is `mcp.json` in the `rusting_strata` folder +that holds the default models folder. + +```json +{"mcpServers": { + "files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/me/notes"]}, + "docs": {"url": "https://example.com/mcp", "headers": {"Authorization": "Bearer ..."}} +}} +``` + +- The `tools` switch beside `think` turns tools on. The tools tab in settings lists the servers and their tools, and + says why a server did not start. Untick a server or a tool to keep it from the model. +- Each call waits for your answer unless "run tools without asking" is on. The tab also limits the tool rounds per + reply and the length of a tool result. +- Tool definitions cost context and prefill time. The model needs a chat template with tool calls. The Qwen families + have one. +- Only text results work. Resources, prompts, sampling and OAuth sign-in are not supported. +- `STRATA_MCP_TIMEOUT` (seconds, default 120) limits one answer from a server. +- On Windows a command starts through `cmd /c`. This path is not tested yet. +- API clients send their own `tools` and are not affected. + +The routes are `GET /api/mcp`, `POST /api/mcp/reload` and `POST /api/mcp/call`. With keys set they need the admin +key. Without keys they answer only requests from the same computer that name it `localhost`, `127.0.0.1` or `[::1]` +and carry no proxy header (`Forwarded`, `X-Forwarded-*`, `X-Real-IP`). Behind a reverse proxy or a tunnel always set +`--api-key`: a proxy that adds no such header looks like a local browser. ## Flags -- `--ctx` KV cache size in tokens (default 4096). For Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 it is the prompt plus reply limit instead, and the default is the context the model was trained on; their caches grow with the text. -- `--mtp [N]` speculative decoding with the model's draft head. Greedy tokens stay the same; sampling keeps its - distribution. Needs a GGUF with an MTP head (for example the Qwen3.6-35B-A3B MTP files). - Qwen3.8-Flash-Next (`qwen4exp`) takes its head from a companion file: `--mtp-model mtp-...-shared-Q8_0.gguf`. - Drafts only pay when most experts are in VRAM: on the 12 GB reference machine with the IQ2_XS file (CPU experts - on most tokens) `--mtp 1` decodes slower than no drafts. With a `--device 0,1` split the head runs on the - last device (EAGLE3 heads excepted: those decode without drafts on a split). -- `--draft-model PATH` speculative decoding with a separate draft model (needs `--gpu` and one stream, so not with - `--parallel`). The target checks every drafted token, so a draft never decides a token; sampling keeps its - distribution. As with `--mtp`, the batched check rounds differently from one-token decoding, so greedy output can - differ from a run without drafts at a near tie. Two kinds of file work: - - a DFlash or DFlash2 draft: a small block-diffusion model trained for one target model. It reads hidden states - of the target and predicts a whole block of tokens in one pass; the target then checks the block in one - batched pass and keeps the tokens that match. `--mtp N` caps the drafted tokens per step (default: the - draft's block size minus one). The draft must be made for this target: its embedding width, its target - layers and its tensor shapes are checked at load, and a file that does not fit is refused. When the target - GGUF has its own MTP head, the DFlash draft is used instead of that head. - - an ordinary smaller model with the same vocabulary as the target (default `--mtp 4`). - - `PATH` is a `.gguf` file, a Hugging Face `.safetensors` file with its `config.json` next to it, or a - directory holding either. Safetensors DFlash checkpoints are converted once and written next to the source as - `model-dflash-q4_0.gguf` (`STRATA_DFLASH_Q8=1` writes and reads `model-dflash-q8_0.gguf`; - `STRATA_DFLASH_RECONVERT=1` converts again). `STRATA_DFLASH_BLOCK=N` fixes the block size instead of adapting - it to how many drafts are accepted. -- `--spec-type LIST` drafts from text that is already in the context, with no draft model: a comma-separated - list of `suffix`, `ngram-simple`, `ngram-map-k`, `ngram-map-k4v`, `ngram-mod`, `ngram-cache`. It pays on - output that repeats the prompt (code edits, quoting, structured data). It combines with `--mtp`, - `--mtp-model` and `--draft-model`: the lookup drafts when it finds a match (next to a DFlash draft, only on a - long match) and the model drafts otherwise. -- Inkling 2 drafts with `--draft-model PATH` (a DSpark draft file) and with `--spec-type`; it has no MTP head, so - `--mtp` and `--mtp-model` are ignored with a warning. Drafts need the GPU path, and one pass checks at most 16 - rows. In a layer whose experts are not all in VRAM the rows of a check share few experts, so on a card that does - not hold the whole model a draft model gains little. RTX 3060 12 GB, `Inkling-2-Mini-IQ4_NL.gguf` (17.6 GB, 15 - of 24 expert layers in VRAM on CUDA, 16 on Vulkan), `bench --pp 512 --tg 128`, two runs of each: CUDA 31.1 and - 35.2 tok/s without drafts, 48.5 and 52.4 with `--spec-type ngram-simple` (the bench text repeats, so nearly - every draft is accepted), 35.1 and 35.6 with the DSpark file (285 of 294 drafts accepted); Vulkan 22.8 and 27.0 - without drafts, 51.1 and 56.2 with the lookup, 29.2 and 30.4 with the DSpark file. The batched check rounds - differently from one-token decoding, so greedy output can differ at a near tie. -- `--chunk`, `--threads` prefill chunk size and CPU expert threads. On a GPU `--threads` defaults to the physical - core count (SMT siblings only add contention; on the 6-core/12-thread reference machine 6 beats 12 by ~20%). - `rustingstrata calibrate` measures the best chunk and later runs read it from - `~/.cache/rusting_strata/strata-.json` unless flags override. - `XDG_CACHE_HOME` moves that folder to `$XDG_CACHE_HOME/rusting_strata` (on Windows it is - `%LOCALAPPDATA%\rusting_strata`). In a container, set it to a mounted path: `docker run --rm` otherwise discards - the file on exit, and the next container runs uncalibrated. The file names the GPU it was measured on, and a file - measured on another GPU is ignored with a warning. It also holds the size of the GGUF file: another file with the - same name (from another repo or quantizer) does not use it, and a warning asks to calibrate again. Vulkan adds - `-vulkan` to the name, and a run on several cards adds the devices in `--device` order (`-dev0-1`), so a two-card - calibration does not replace the one-card one. -- `STRATA_AVX512=1` uses the AVX-512 kernels for experts that run on the CPU, in a build for a CPU that has - AVX-512 VNNI and VBMI (a `target-cpu=native` build on such a machine; the release binaries do not have them). Their - results differ from the default kernels in the last bits, so greedy output can change at a near tie. -- `--vram-margin` MB of VRAM left free. One value applies to every device; `512,256` gives one per device in - `--device` order, and `0:512,1:256` gives one per GPU index. On a GPU that drives no display, `--vram-margin 256` keeps more experts - resident (+1-2% prefill); 128 runs out of memory. -- `--kv q8` halves the KV cache (345 instead of 650 MB at 32K) at about 6% slower 32K decode and 14% slower 32K prefill. - `--kv q4` and `--kv q2` store it in 4-bit and 2-bit form (about 28% and 19% of the f16 size) for very long - contexts. Attention then reads rounded keys and values, so the output can differ from f16; q2 differs most. - The head size must be a multiple of 32, and `--llama-numerics` needs the f16 cache. `calibrate` takes the - same `--kv` value as the runs that will use it. -- `calibrate --mtp-model PATH` or `--draft-model PATH` measures with that draft file loaded, so the chunk and the - expert placement see the VRAM it takes, and picks the draft count. Runs with the same `--mtp-model` or - `--draft-model` file use that count unless `--mtp` is given; runs with another draft file or none do not. -- `calibrate --model ~/models` calibrates every model in a folder (and its subfolders, as the chat page lists them), - one after another, with the other flags applied to each. A model that fails is reported and the rest go on; Inkling - 2, Hy4, GLM, DeepSeek and Gemma 4 models are skipped: `calibrate` measures the main engine only, and these models - run on their own code path, which reads no calibration file. `--mtp-model` and `--draft-model` need a single file. -- `--thinking-budget N` (`chat` and `serve`) ends the thinking block after `N` tokens by inserting ``, - so the model goes on to the answer (0, the default, is no limit). A request overrides it with - `thinking_budget` or `chat_template_kwargs.thinking_budget` (Anthropic: `thinking.budget_tokens`). -- `--short N` prompts shorter than `N` tokens skip the batched prefill and go token by token (default: from - `rustingstrata calibrate`, else 32). -- `--allowed-hosts ai-server.lan` (or `STRATA_ALLOWED_HOSTS`) allows a LAN name when `serve` is bound to `0.0.0.0`. -- `--auto-unload 600` (`serve`) frees the model after 600 seconds without a chat request: the VRAM and the memory of - the process go back to the system, so an idle home server does not hold the GPU. The next chat request loads the - model again with the same options and is answered after the load; the model stays in `/v1/models` meanwhile, and - `/health` answers `200 {"status": "ok", "unloaded": true}`. Only chat requests count as use and load the model: - the chat page, the model list, `/health` and the stats do not. The file stays in the page cache (`buff/cache`, - which the system takes back when it needs the memory), so the load after an unload is faster than the first one. - The saved conversation (prompt cache) goes with the model: the first request after a load prefills its whole - prompt. -- `--alias prism` (`serve`) is the model name in `/v1/models` and in the replies, whatever file is loaded (default: the - file name), so clients set up for `prism` keep working when another model is loaded. Calibration and the expert - profile stay per file. -- Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 run on their own code path. The server loads them like any other model - (`serve --model `, or from the chat page of a running server, in either direction), with these limits: one - request at a time, greedy (Inkling 2 also samples: `temperature`, `top_k`, `top_p`, `seed`; a seed repeats its - text only with `STRATA_FIXED_EXPERTS=1`, because the adaptive expert split moves the logits a little), - `/v1/chat/completions` only (no `/v1/messages`), and no calibration (`calibrate` does - not cover them). The context limit is `--ctx` (or the page's context setting) when given, else the trained context. -- `--lora PATH:SCALE` applies a LoRA adapter at runtime, see [LORA.md](LORA.md). -- `--mcp FILE` (`serve` only, or `STRATA_MCP`) lists the MCP servers whose tools the chat page may call, see - [Tools (MCP)](#tools-mcp). +Flags apply to `chat`, `generate`, `bench` and `serve` unless noted. A load prints the values it uses and where each +came from: + +``` +settings: ctx 32768, kv q8, chunk 2048 (calibration), mtp 1 (preset), short 32 (default), threads 6 (default), cache-ram 4096 MB +``` + +### Model and device + +| Flag | Default | What it does | +|---|---|---| +| `--gpu` | off | Runs on the GPU. Experts that do not fit in VRAM run on the CPU. | +| `--backend NAME` | `cuda` if it loads, else `vulkan` | `cuda`, `vulkan` or `hip` (AMD through ROCm, see [HIP.md](HIP.md)). | +| `--device LIST` | `0` | GPU index, or several. See [Several GPUs](#several-gpus). | +| `--fast-cpu` | off | Without `--gpu`: a faster CPU path, for a machine without a usable GPU. | +| `--threads N` | calibrated, else the cores | CPU threads for expert work. Linux `--gpu` and `--fast-cpu` runs count physical cores, other runs logical ones. | +| `--mmproj PATH` | an `mmproj*.gguf` next to the model | Projector for image input. See [VISION.md](VISION.md). | +| `--lora PATH:SCALE` | none | LoRA adapter at run time. See [LORA.md](LORA.md). | +| `--ple FILE` | below | Qwen3.8 Flash-Next: the GGUF with the n-gram table. Or `STRATA_PLE`. | +| `--preset FILE` | none | Reads flags from a file. See [Presets](#presets). | + +- `--fast-cpu`: on an i5-8365U with UHD 620, Qwen3.5 2B IQ4_XS decodes 7.6 tok/s against 2.5 tok/s on Vulkan. Greedy + text can differ from the CPU reference at a near tie. +- DeepSeek, GLM, Hy4, Inkling 2, Kolibri and Gemma 4 ignore `--fast-cpu`. Models with multiple PLE layers and + SenseNova-Loop (`sensenova_loop`) prefill token by token. +- Q1_0, PQ2_0, Q8_1, Q8_K and MXFP4 files run only on the CPU. PTQ1_0 weights (Ternary Bonsai from PrismML) are copied + at load: 34/28 of the file's size in RAM, 6.3 GB for the 27B. +- `--ple`: a model file with no table (`per_layer_token_embd.weight`, a `-noPLE` file) takes the one `.gguf` next to + it whose name has `PLE` in it. With none or several, the load stops and asks for `--ple`. The flag also names the + shard of a split model that is in another folder. With your own table in `--ple`, the shard that held the old + table can be deleted: the load skips the one missing shard. See [MODELS.md](MODELS.md). + +### Context and memory + +| Flag | Default | What it does | +|---|---|---| +| `--ctx N` | 4096 | KV cache size in tokens. | +| `--vram-margin MB` | 512 | VRAM left free. `512,256` is per device in `--device` order, `0:512,1:256` per GPU index. | +| `--ram-margin MB`, `--max-ram MB` | 512, 0 | Host RAM left free, or an absolute cap. See [LORA.md](LORA.md). | +| `--cache-ram MB` | 4096 | Host memory for parked conversations. See [Prompt caching](#prompt-caching). | +| `--arena` | off | Reads the model into RAM at load instead of mapping it, if it fits with 6 GB to spare. | +| `--tail-skip R` | 0 (off) | Skips low-ranked experts outside VRAM. Faster decode, other answers. | + +- `--ctx`: for Inkling 2, Hy4, GLM, DeepSeek, Kolibri and Gemma 4 it limits prompt plus reply. Their default is the + context the model was trained on. +- `--vram-margin 256` keeps more experts in VRAM on a GPU that drives no display (+1-2% prefill). 128 runs out of + memory. +- `--arena` drops the file from the page cache. Before a later run that maps the model, `cat` the file to `/dev/null`. +- `--tail-skip R`: a token ranks its picked experts from 0 by routed weight. An expert outside VRAM at rank R or lower + is not computed. With Qwen3.6's 8 picks a token, `--tail-skip 6` drops at most the last two. +- On a GTX 1660 SUPER with 1.7 GB of Qwen3.6-35B-A3B's experts in VRAM, `--tail-skip 6` decodes 6% faster and changes + the most likely next token at 5% of positions. The run ends with a `tail skip: N of M CPU expert picks dropped` line. +- `--tail-skip` works on the main engine and Inkling 2, not with `--parallel`, and on Inkling 2 not with + `--fixed-experts`. The idea is PolyStrata's route tail skip. + +### K/V cache + +| Flag | Default | What it does | +|---|---|---| +| `--kv TYPE` | `f16` | `f16`, `q8`, `q4`, `q2`, `turbo4`, `turbo4-3`, `turbo4-2`, `turbo3`, `turbo2` or `turbo3-2`. | +| `--k TYPE`, `--v TYPE` | from `--kv` | CUDA: one half alone, such as `--k f16 --v q4`. No `turbo4-3`, `turbo4-2`, `turbo3-2`. | + +- `q8` halves the KV cache (345 instead of 650 MB at 32K). 32K decode is about 6% slower, 32K prefill 14%. +- `q4` and `q2` take about 28% and 19% of the f16 size, for very long contexts. q2 differs most from f16. +- `turbo4` (TurboQuant, CUDA only) takes about 28% of the f16 size. The other turbo types are narrower. +- Every type but `f16` rounds keys and values, so the output can differ. +- The head size must be a multiple of 32. `--llama-numerics` needs the f16 cache. +- Vulkan takes `f16`, `q8`, `q4` and `q2`, the same type for K and V. +- Give `calibrate` the `--kv`, `--k` and `--v` of the runs that will use the result. + +### Sampling + +Decoding is greedy unless `--temp` is above 0. The penalties and DRY also need a temperature above 0. They count only +the tokens of the reply, and not inside a tool call. + +| Flag | Default | What it does | +|---|---|---| +| `--temp T` | 0 | Sampling temperature. | +| `--top-k K` | 0 (all) | Samples only from the K most likely tokens. | +| `--top-p P` | 1 | Top-p. | +| `--min-p P` | 0 (off) | Drops tokens whose probability is below P times the best token's. 0 to 1. | +| `--seed N` | from the clock | Random seed. | +| `--presence-penalty X`, `--frequency-penalty X` | 0 | As in the OpenAI API, -2 to 2. | +| `--repeat-penalty X` | 1 (off) | Lowers every token among the last `--penalty-last-n` of the reply. 1.1 is usual. | +| `--penalty-last-n N` | 64 | Window of the three penalties. 0 turns them off, -1 takes the whole reply. | +| `--dry-multiplier X` | 0 (off) | The DRY sampler, against repetition loops. | +| `--dry-base X`, `--dry-allowed-length N` | 1.75, 2 | DRY base, and the repeat length that stays free. | +| `--force-sampling` | off | `serve`: ignores the sampling fields of requests. | + +### Thinking + +| Flag | Default | What it does | +|---|---|---| +| `--think false` | on | Turns thinking off (`chat` and `serve`). | +| `--thinking-budget N` | 0 (no limit) | Ends thinking after N tokens by inserting `` (`chat` and `serve`). | +| `--reasoning-effort LEVEL` | none | `serve`: the `reasoning_effort` of a request that sends none. | +| `--preserve-thinking false` | on | Follows the template. See [Prompt caching](#prompt-caching). | + +`--reasoning-effort` takes `none`, `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, or a number from 0 to +0.99 (Inkling 2). Any other value stops the start. `none` turns thinking off. The levels act only on models whose +template reads one. Qwen4 takes `xhigh`, `high` and `low`. + +### Speed + +| Flag | Default | What it does | +|---|---|---| +| `--chunk N` | calibrated, else 4096 | Prefill chunk in tokens (GPU). | +| `--short N` | calibrated, else 32 | Prompts shorter than N tokens go token by token. | +| `--mtp [N]` | calibrated, else 0 | Drafts N tokens a step with the model's MTP head. | +| `--mtp-model PATH` | none | Takes the MTP head from a companion GGUF. | +| `--draft-model PATH` | none | Drafts with a separate model. Needs `--gpu`. Not with `--parallel`. | +| `--spec-type LIST` | `none` | Drafts from text already in the context, with no draft model. | +| `--spec-draft-n-max N` | 16 | `--spec-type`: most draft tokens checked per step. | +| `--spec-ngram-size-n N`, `--spec-ngram-size-m N`, `--spec-ngram-min-hits N` | 12, 48, 1 | `--spec-type`: key length, draft window, hits before drafting. | +| `--lookup-cache-static FILE`, `--lookup-cache-dynamic FILE` | none | `--spec-type`: lookup cache files. | +| `--prefill-cpu`, `--cpu-frac F` | off, adapts | Prompt chunks run a share of the experts outside VRAM on the CPU. `--cpu-frac` fixes the share, 0 to 1. Output can differ slightly. | +| `--pin` | off | Pins the CPU expert threads to physical cores. Measured on one machine only. | +| `--host-share N` | 0 (off) | Needs `--arena`, CUDA. It was slower in every measurement. | +| `--no-fused` | off | Uses the two-pass CPU expert path. | +| `--fixed-experts` | off | Never moves experts, for runs that repeat. Or `STRATA_FIXED_EXPERTS=1`. | +| `--llama-numerics` | off | Matches llama.cpp's numerics for parity runs. Slower. | + +- `--chunk`: without the flag, a GPU load that runs out of VRAM halves the chunk down to 512 and says so. With the flag + the load fails. +- `--mtp` needs a GGUF with an MTP head, such as the Qwen3.6-35B-A3B MTP files. [MODELS.md](MODELS.md) says which models + have one and which need `--mtp-model`. +- Drafts pay only when most experts are in VRAM. With CPU experts on most tokens, `--mtp 1` decodes slower than no + drafts. +- Drafts keep the sampling distribution. Greedy output can differ at a near tie. A request with a grammar or a logit + bias runs without drafts. +- `--draft-model` takes a DFlash or DFlash2 draft made for this target, or a smaller model with the same vocabulary. It + replaces the target's own MTP head. A DFlash file that does not fit the target is refused. `--mtp N` caps the drafts + per step (default 4, or the block size minus one for DFlash). +- `PATH` is a `.gguf` file, a Hugging Face `.safetensors` file with its `config.json` next to it, or a directory holding + either. A safetensors DFlash checkpoint is converted once, to `model-dflash-q4_0.gguf` next to the source. +- `--spec-type` takes a comma-separated list of `suffix`, `ngram-simple`, `ngram-map-k`, `ngram-map-k4v`, `ngram-mod` + and `ngram-cache`. It pays on output that repeats the prompt: code edits, quoting, structured data. +- Inkling 2 drafts with `--draft-model` (a DSpark file) and `--spec-type`, on the GPU only. It ignores `--mtp` and + `--mtp-model` with a warning. + +### Server + +| Flag | Default | What it does | +|---|---|---| +| `--model PATH` | none | The model to load. Without it the client or the chat page picks one. | +| `--addr ADDR` | `127.0.0.1:8080` | Address to listen on. | +| `--models-dir DIR` | the models folder | Folder of `.gguf` models the chat page offers. | +| `--api-key KEY` | none | The admin key: `Authorization: Bearer KEY` on every request. | +| `--parallel N` | 1 | Requests answered at once (GPU). See [Parallel requests](#parallel-requests). | +| `--max-tokens N` | what the context leaves | Most reply tokens a request may ask for, and the default. | +| `--auto-unload SECONDS` | never | Frees the model after this time without a chat request. | +| `--alias NAME` | the file name | Model name in `/v1/models` and in the replies. | +| `--no-webui` | off | Serves only the API. `/` answers `404`. | +| `--cors-origin LIST` | none | Origins whose pages may call the server from a browser, or `*`. | +| `--allowed-hosts LIST` | `STRATA_ALLOWED_HOSTS` | Allows a LAN name such as `ai-server.lan` when bound to `0.0.0.0`. | +| `--mcp FILE` | `STRATA_MCP` | See [Tools (MCP)](#tools-mcp). | +| `--slot-save-path DIR`, `--prompt-cache FILE` | none | See [Prompt caching](#prompt-caching). | +| `--api-keys FILE`, `--usage-log FILE` | none | Customer keys and the request log. See [HOSTING.md](HOSTING.md). | + +- `--auto-unload 600` frees the VRAM and the process memory after 600 seconds. The next chat request loads the model + again and prefills its whole prompt. Meanwhile the model stays in `/v1/models`, and `/health` answers `200 {"status": + "ok", "unloaded": true}`. +- `--cors-origin http://127.0.0.1:9999` answers a preflight `OPTIONS` with `204` before the key check. Set `--api-key` + with it: without a key any page the browser opens may use the server. + +### Presets + +`--preset FILE` goes after the command. The file has one `name = value` line per flag, named with `-` or `_`. + +```toml +# qwen-32k.toml +model = "/models/Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf" +ctx = 32768 +kv = "q8" +fixed_experts = true +device = [0, 1] +``` + +```bash +rustingstrata serve --preset qwen-32k.toml --ctx 8192 # a flag on the command line wins +rustingstrata calibrate --preset qwen-32k.toml # writes the tuned chunk, mtp and short into the file +``` + +- A key that only another command takes is skipped, so one file serves `serve`, `chat` and `calibrate`. +- A key that is no flag at all is an error. A flag can be set to `true` but not turned off from the file. +- `calibrate --preset` replaces the lines the file had and keeps the comments. + +### Calibration + +```bash +rustingstrata calibrate --model model.gguf +rustingstrata calibrate --model ~/models # every model in the folder and its subfolders +``` + +`calibrate` measures the best chunk, draft count and short-prompt threshold. Later runs read them unless flags override. +The options and the file names are in [CALIBRATION.md](CALIBRATION.md). + +The result goes to `~/.cache/rusting_strata`, to `$XDG_CACHE_HOME/rusting_strata` when that is set, or to +`%LOCALAPPDATA%\rusting_strata` on Windows. In a container, set `XDG_CACHE_HOME` to a mounted path: `docker run --rm` +otherwise discards the file on exit. ## Server API -`serve` speaks the OpenAI chat completions API (`POST /v1/chat/completions`, streamed or not, `GET /v1/models`). - -- `GET /v1/models` lists the loaded model first, then every other model the chat page offers (the models folder, the - Hugging Face and llama.cpp caches), each by its file name without `.gguf`. A chat request whose `model` is one of - these names makes the server load that model in place of the loaded one, and is answered after the load; so a - server started without `--model` serves whichever model the client picks. The replies in progress end first. A - `model` that no listed file has is answered by the loaded model. If the load fails, the request gets `503` with - the reason and the next chat request loads the model that was there before. With API keys only the admin key sees - the other models and switches; a customer key sees and gets the loaded model. -- It runs one request at a time; `--parallel N` (GPU) decodes up to N together (4 requests: 164 tok/s in total on the - RTX 3060, 41 each; see [HOSTING.md](HOSTING.md)). From 8 requests decoding at once (`STRATA_BATCH_MIN` sets the - count), a dense model without MTP, LoRA or recurrent layers on CUDA runs them in one batched forward, and the - prompts of requests that arrive together are prefilled together. That forward - rounds differently from the single-request one, so greedy output under load can differ at near-ties from the same - request run alone. -- `temperature`, `top_k`, `top_p` and `seed` are honored; decoding is greedy when they are left out. -- `presence_penalty` and `frequency_penalty` (OpenAI, -2 to 2) and `dry_multiplier`, `dry_base`, `dry_allowed_length` - (the DRY sampler, llama.cpp server names) act against repetition loops. They count only the tokens of the reply, - not the prompt, and do not apply inside a tool call. `--presence-penalty`, `--frequency-penalty`, - `--dry-multiplier`, `--dry-base` and `--dry-allowed-length` set the values for requests that leave them out. All - are off by default, and they need a temperature above 0: greedy decoding does not use the sampler. -- `repeat_penalty` and `penalty_last_n` (llama.cpp server names; `--repeat-penalty`, `--penalty-last-n`) follow the - same rules. A repeat penalty above 1 (1.1 is usual; 1 is off, the default) lowers every token among the last - `penalty_last_n` tokens of the reply (default 64; 0 turns it off, -1 takes the whole reply). The window is for - the repeat penalty only: the presence and frequency penalties count the whole reply. -- `max_tokens` (or `max_completion_tokens`) and `stop` (up to 16 strings) work as in the OpenAI API; `n` must be 1. -- A request whose last message has role `assistant` (and no tool calls) continues that message: the reply holds only - the new text. The chat page's continue button uses this. -- Thinking is on by default (`--think false` turns it off). A request overrides it with `chat_template_kwargs.enable_thinking` - (Anthropic: `thinking: {"type": "enabled"}`; `enable_thinking: false` turns it off for that request). -- `tools` and `tool_choice` work as in the OpenAI API: calls come back as `tool_calls` with `finish_reason: - "tool_calls"`. `tool_choice: "required"` does not force a call. +```bash +curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" \ + -H "Authorization: Bearer secret" -d '{"messages": [{"role": "user", "content": "Hello"}], "stream": true}' + +# Claude Code. OpenCode and other agents use the OpenAI address. +ANTHROPIC_BASE_URL=http://127.0.0.1:8080 ANTHROPIC_API_KEY=secret ANTHROPIC_MODEL=local \ + ANTHROPIC_SMALL_FAST_MODEL=local claude +``` + +| Route | What it does | +|---|---| +| `POST /v1/chat/completions` | OpenAI chat completions, streamed or not. | +| `GET /v1/models` | The loaded model first, then every other model the chat page offers. | +| `POST /v1/messages` | Anthropic Messages API: text, `tool_use` and `tool_result` blocks, the key in `x-api-key`. | +| `POST /v1/messages/count_tokens` | Token count of a Messages request. | +| `GET /props` | As llama-server: `default_generation_settings.n_ctx`, `n_ctx_train`, `model_alias`, `total_slots`. | +| `POST /tokenize`, `POST /detokenize` | As llama-server. | +| `POST /slots/0?action=save` | Also `restore` and `erase`. See [Slot save and restore](#slot-save-and-restore). | +| `POST /v1/vram` | See [Lend VRAM](#lend-vram). | +| `POST /api/load` | See [Chat page](#chat-page). | +| `GET /health` | See [HOSTING.md](HOSTING.md). | + +### Request fields + +| Field | What it does | +|---|---| +| `model` | A name from `/v1/models`: the file name without `.gguf`. Another name than the loaded one switches the model. | +| `temperature`, `top_k`, `top_p`, `min_p`, `seed` | Sampling. Greedy when left out. | +| `presence_penalty`, `frequency_penalty`, `repeat_penalty`, `penalty_last_n` | As the flags in [Sampling](#sampling). | +| `dry_multiplier`, `dry_base`, `dry_allowed_length` | The DRY sampler. | +| `max_tokens`, `max_completion_tokens` | Reply limit. Without it and `--max-tokens`, a reply runs until the model stops or the context is full. | +| `stop`, `n` | `stop` takes up to 16 strings. `n` must be 1. | +| `logit_bias` | -100 to 100, added to the logits. -100 and `false` ban the token. | +| `grammar` | llama.cpp's GBNF as a string, such as `root ::= "yes" \| "no"` or `grammars/json.gbnf`. | +| `response_format` | Makes the reply JSON. | +| `tools`, `tool_choice` | As in the OpenAI API. `tool_choice: "required"` does not force a call. | +| `chat_template_kwargs.enable_thinking` | Thinking on or off. Anthropic: `thinking: {"type": "enabled"}` or `{"type": "disabled"}`. | +| `reasoning_effort` | `"none"` turns thinking off on every model. It has priority over `enable_thinking`. | +| `thinking_budget`, `chat_template_kwargs.thinking_budget` | Overrides `--thinking-budget`. Anthropic: `thinking.budget_tokens`. | +| `chat_template_kwargs.preserve_thinking` | Overrides `--preserve-thinking`. | + +- `model`: replies in progress end first, and the request is answered after the load. An unknown name is answered by + the loaded model. A failed load gets `503` with the reason, and the next chat request loads the model that was there + before. With API keys only the admin key sees the other models and switches. +- `logit_bias` takes the OpenAI object `{"15339": -100}` and llama.cpp's list + `[[15339, -100], ["hello", 5], ["hello", false]]`. A text applies to each of its tokens. An unknown token id is a + `400`. +- `grammar`: the reply ends only once the grammar is complete. Thinking is off unless `enable_thinking` turns it on. + Then the grammar holds from `` on. A grammar that does not parse is a `400` with the reason. +- `response_format`: `{"type": "json_object"}` takes any JSON object. `{"type": "json_schema", "json_schema": + {"schema": {...}}}` or llama.cpp's `{"type": "json_object", "schema": {...}}` takes JSON that fits the schema. + `{"type": "text"}` is the default. With `grammar` in the same request it is a `400`. +- A schema may use `type` (one or a list), `properties`, `required`, `items`, `enum`, `const`, `anyOf`/`oneOf`, + `allOf` of one schema and local `$ref`s (`#/$defs/...`). Lengths, counts, `pattern`, `format` and number bounds are + not checked. +- `/v1/messages` takes neither `grammar` nor `logit_bias`. +- A request whose last message has role `assistant` and no tool calls continues that message. The reply holds only the + new text. +- A prompt longer than the context gets `400` with `prompt is too long: N tokens, the limit is M (the request exceeds + the available context size; raise --ctx)`. Agents such as Pi start their compaction on it. - The prompt follows the model's own chat template, rendered like llama.cpp's `--jinja`. +- Inkling 2 with thinking off makes the reply start with the answer, except in a request that declares tools. + Per-model thinking levels are in [MODELS.md](MODELS.md). +- `POST /tokenize` takes `{"content": "text", "add_special": false, "with_pieces": false}` and gives + `{"tokens": [...]}`. With pieces each entry is `{"id", "piece"}`. `POST /detokenize` takes `{"tokens": [...]}` and + gives `{"content": "text"}`. -`POST /v1/messages` speaks the Anthropic Messages API (text, `tool_use` and `tool_result` blocks, streamed or not, the -key in `x-api-key`, and `POST /v1/messages/count_tokens`), so Claude Code can use the server: +### Replies -```sh -ANTHROPIC_BASE_URL=http://127.0.0.1:8080 ANTHROPIC_API_KEY=secret ANTHROPIC_MODEL=local ANTHROPIC_SMALL_FAST_MODEL=local claude -``` +- The reasoning is `reasoning_content` on `/v1/chat/completions`, and a `thinking` block before the `text` block on + `/v1/messages`. Streamed, its pieces are `thinking_delta`s, and it stops after an empty `signature_delta`. +- Tool calls come back as `tool_calls` with `finish_reason: "tool_calls"`. A streamed chat sends each call's name as + soon as the model writes it. Models with `` calls (Qwen3.5, Qwen3.6, Qwen3 Coder) also stream a string + argument as it is written. Other formats and the Messages API send the arguments when the call is complete. +- Each reply carries `usage` and llama-server's `timings` block: `prompt_n`, `prompt_ms`, `prompt_per_second`, + `predicted_n`, `predicted_ms`, `predicted_per_second`, `cache_n`. llama-swap shows the speeds from it. +- A streamed reply sends its response head before the prompt runs. While the prompt runs, and while a tool call is + held back, it sends the SSE comment `: keep-alive` every 15 s. + +### Parallel requests + +The server answers one request at a time. `serve --parallel N` (GPU) decodes up to N together. Measured speeds are in +[HOSTING.md](HOSTING.md). -OpenCode and other agents use the OpenAI address. +- MTP drafts are off with `--parallel`. `--parallel` is lowered to the slots that fit in VRAM. +- For a model without experts each slot's KV cache starts at 512 tokens and doubles when needed, up to `--ctx`. A + request whose cache cannot grow for lack of VRAM fails alone. +- From 4 requests decoding at once (16 for a model with experts), one batched forward runs them. Greedy output under + load can then differ at near-ties from the same request run alone. +- An image request (`--mmproj`) takes a slot too. See [VISION.md](VISION.md). + +### Models outside the main engine + +Inkling 2, Hy4, GLM, DeepSeek, Kolibri and Gemma 4 run on their own code path, with these limits. Per-model detail is +in [MODELS.md](MODELS.md). + +- One request at a time. A streamed chat that waits gets its response head after 10 s in the queue, then + `: keep-alive` every 15 s. A refusal after that head is one `data: {"error": ...}` line. +- Greedy. `logit_bias` and `grammar` work. Inkling 2 also samples (`temperature`, `top_k`, `top_p`, `min_p`, `seed`). + A seed repeats its text only with `STRATA_FIXED_EXPERTS=1`. +- `/v1/chat/completions` only, no `/v1/messages`. Tool calls are sent at the end. +- The slot endpoints and `/v1/vram` answer 501. `calibrate` measures their prefill chunk only. ## Prompt caching -- When a request repeats the previous request's messages and adds new ones, only the new part is prefilled - (`usage.prompt_tokens_details.cached_tokens`). -- Qwen3.6's template leaves the think block out of replies before the last user message, so each new user message would - change the earlier turns and force a full prefill. RustingStrata keeps those blocks by default; - `--preserve-thinking false` (or `chat_template_kwargs.preserve_thinking` in a request) follows the template. -- A request with another history (an agent's side request for a title or a summary) parks the conversation's state in - host memory (`--cache-ram`, 4096 MB by default), and the next request that continues it takes it back. -- With customer keys, each key reuses only its own cached conversations; see [HOSTING.md](HOSTING.md). +When a request repeats the previous request's messages and adds new ones, only the new part is prefilled. The reply +reports it as `usage.prompt_tokens_details.cached_tokens`. + +- Qwen3.6's template drops the think block of earlier replies, which forces a full prefill on each new user message. + RustingStrata keeps those blocks by default. `--preserve-thinking false` follows the template. +- A request with another history, such as an agent's side request for a title, parks the conversation in host memory + (`--cache-ram`). The next request that continues it takes it back. +- `--prompt-cache FILE` keeps the last conversation and the newest 4 parked ones over a restart. The file is only read + by the same model, `--kv` and device split, so give each model its own file. With `--cache-ram 0` it parks up to + 2048 MB. +- With customer keys, each key reuses only its own cached conversations. See [HOSTING.md](HOSTING.md). + +### Slot save and restore + +`serve --slot-save-path DIR` turns on llama-server's slot endpoints. They need the admin key and the main engine on +the GPU. Without the flag they answer 501. + +| Request | Result | +|---|---| +| `POST /slots/0?action=save` with `{"filename": "a.bin"}` | Writes slot 0's cached prompt to `DIR/a.bin`. Answers `n_saved`, `n_written`, `timings.save_ms`. | +| `?action=restore` with the same body | Reads it back. Answers `n_restored`, `n_read`, `timings.restore_ms`. | +| `?action=erase` | Drops it. Answers `n_erased`. | + +The next request whose prompt starts with the restored tokens prefills only the rest, even after a restart. A file is +only read by the same model, `--kv` and device split. A file name is letters, digits, `-`, `_` and `.`, with no +folder. Under `--parallel` the slot ids are 0 to N-1, and a slot that is answering a request is refused. + +### Lend VRAM + +`POST /v1/vram` with `{"reserve_mib": N}` shrinks or grows the expert cache until N MiB of the card are free, counting +what every program holds. It needs the admin key and the main engine. `null` or `{}` goes back to the `--vram-margin` +the model loaded with. + +- Experts that lose their slot run on the CPU, so answers go on, slower. +- The answer has `status`, `reserve_mib`, `expert_slots`, `expert_slots_full`, `expert_cache_mib`, + `expert_cache_full_mib`, `vram_free_mib` and a `devices` list, or 400 with the reason. +- The cache never goes below its floor, so check `vram_free_mib` against the reserve. +- An error after the old slots are freed leaves the cache unusable. Load the model again. +- The request follows PolyStrata's `POST /v1/vram`. ## Several GPUs -`--device 0,1` splits the layers over the cards in proportion to their free VRAM, so more experts stay resident. The -cards run one after the other, so one request gets more memory, not twice the speed of one card. MTP drafting is off on -a split model. - -An index is the same card on both backends. NVIDIA cards are counted as CUDA counts them (by default the fastest card -first, which is not the order of `nvidia-smi`), on Vulkan too; the other Vulkan devices follow, dedicated cards before -integrated ones. The load prints the card of every index (`cuda device 1: ...` or `vulkan device 1: ...`). - -The split by free VRAM does not know which card is faster or which sits on a slow PCIe link (x1 riser, x4 slot). -`rustingstrata calibrate --model M.gguf --device 0,1` measures it: it times prefill and decode with the split by free -VRAM, then with layers moved from one card to the other in steps of 15% of the layers, and follows the faster -direction for up to three rounds. A split that is more than 3% faster (prefill tok/s times decode tok/s; each split line prints this product as -a share of the best one so far) is written to the calibration file as layers per card, and later runs with the same -cards in the same `--device` order load with it. -A card with fewer layers keeps more of their experts in VRAM, so fewer are uploaded to it during prefill, and the other -card then keeps fewer of its own: the timings decide. The order of the cards is not searched: to compare, calibrate -`--device 1,0` too. Each order has its own file (`strata--dev0-1.json`, `-dev1-0.json`), and a run uses the -file of the order it is given. - -`--split 30,70` (or `STRATA_SPLIT=30,70`) sets the share of the layers per card by hand, in `--device` order, and -takes precedence over the calibrated split; `calibrate --split 30,70` measures chunk and drafts with that split and -stores it. The load prints each card's layers and its measured host-to-VRAM copy rate. AMD cards clock down in the gaps while the other card works; `echo high > -/sys/class/drm/cardN/device/power_dpm_force_performance_level` (as root, per card) took a two-card split from 44 to 57 -tok/s in one report. +```bash +rustingstrata serve --model model.gguf --gpu --device 0,1 --split 30,70 +``` + +`--device 0,1` splits the layers over the cards in proportion to their free VRAM, so more experts stay in VRAM. The +cards run one after the other: one request gets more memory, not twice the speed of one card. + +- `--split 30,70` (or `STRATA_SPLIT`) sets the share of the layers per card by hand, in `--device` order. Use it when + one card is slower or sits on a slow PCIe link. The load prints each card's layers and its host-to-VRAM copy rate. +- An index is the same card on both backends. NVIDIA cards come first, as CUDA counts them: by default the fastest + first, which is not the order of `nvidia-smi`. Then the other Vulkan devices, dedicated before integrated. The load + prints the card of every index (`cuda device 1: ...` or `vulkan device 1: ...`). +- The MTP head runs on the last device. EAGLE3 heads decode without drafts on a split. +- `--backend hip` runs one device and refuses `--device 0,1`. +- `calibrate` ignores `--split` with a note. Each device order has its own file (`strata--dev0-1.json`, + `-dev1-0.json`), so calibrate `--device 1,0` too to compare orders. +- AMD cards clock down while the other card works. The fix is in [AMD.md](AMD.md). It took a two-card split from 44 to + 57 tok/s in one report. + +### Inkling 2 on several GPUs + +`--device 0,1` is opt-in for Inkling 2: the default is one card, even on a machine with two. With two cards the 24 +expert layers are placed as whole slabs, and the load line says how many and where. The attention and the tail stay on +GPU 0. The kernel switches are in the [variable table](#test-and-tuning-variables). ## Page cache -Experts that do not fit in VRAM are read from the GGUF through the page cache. A file system that keeps file data out -of the page cache (ZFS with `primarycache=metadata`) makes every run read them from disk again; load the model from a -file system that caches data, or from a tmpfs copy. +Experts that do not fit in VRAM are read from the GGUF through the page cache. + +| Case | What to do | +|---|---| +| ZFS with `primarycache=metadata` | Every run reads the experts from disk again. Use a file system that caches data, or a tmpfs copy. | +| btrfs with `compress` (the CachyOS default) | A model larger than RAM had about double the CPU expert time per token against XFS. The load prints a note. Copy the model into a folder marked `chattr +m` or `chattr +C` first, or onto another file system. | +| Network file system (SMB, NFS, a FUSE mount) | The file is not read ahead. `STRATA_PRELOAD=1` reads it ahead all the same. | +| Docker inside an LXC container | The memory limit is not visible. Give the Docker container its own `--memory`, or set `STRATA_PRELOAD=0` and, on ZFS, `STRATA_DIRECT_ROWS=1`. | + +- Model files that fit in RAM with 4 GiB to spare are read into the page cache in the background from the start. On + Linux the RAM is the cgroup's memory limit when that is lower: a container, or a systemd unit with `MemoryMax`. +- A file that holds only the Qwen3.8 Flash-Next n-gram table (27 GB) does not count toward the size. On ZFS, when the + model does not fit in RAM, the rows of that table are read with `O_DIRECT`. +- A model that does not fit is not read ahead, so `serve` runs one untimed 512-token prefill at load for every model + with routed experts. The log says `warm-up: ... s`. +- `STRATA_HUGEPAGE=1` made decode slower on a model larger than RAM (about 69-78 against 115 tok/s). Leave it off there. + +## Test and tuning variables + +| Variable | What it does | +|---|---| +| `STRATA_CPU_PREFILL_CHUNK` | Tokens per `--fast-cpu` prefill chunk (default 32). | +| `STRATA_CPU_SHARED_INT=1` | `--fast-cpu`: the shared integer path also for the Q and IQ types with their own kernels. | +| `STRATA_PTQ1_REPACK=0` | Keeps the file's PTQ1_0 layout: no RAM copy, slower. | +| `STRATA_AVX512=1` | AVX-512 kernels for CPU experts, in a build for a CPU with AVX-512 VNNI and VBMI. Not in the release binaries. Greedy output can change at a near tie. | +| `STRATA_TQ_F32=1` | f32 kernel for the CPU experts of trellis files (Gyro TQ2_T, TQK6, TQK7). Slower, and greedy output differs. | +| `STRATA_DFLASH_Q8=1` | Writes and reads `model-dflash-q8_0.gguf` for a converted DFlash draft. | +| `STRATA_DFLASH_RECONVERT=1`, `STRATA_DFLASH_BLOCK=N` | Converts the DFlash checkpoint again. Fixes the DFlash block size. | +| `STRATA_BATCH_MIN` | Requests decoding at once from which `--parallel` uses the batched forward. | +| `STRATA_VISION_CPU=1` | Keeps the image encoder on the CPU with `--gpu`. See [VISION.md](VISION.md). | +| `STRATA_VERBOSE=1` | Prints the developer lines: what the driver offers, memory details, worker counters. Add them to a bug report. | +| `STRATA_WARMUP=0` | Skips the warm-up prefill of `serve`. | +| `STRATA_PRELOAD` | `1` forces the background read of the model files, `0` turns it off. | +| `STRATA_DIRECT_ROWS` | `1` reads n-gram table rows with `O_DIRECT` on any file system, `0` never. | +| `STRATA_HUGEPAGE=1` | Asks for huge pages on the model map. | +| `STRATA_COLD_KEEP=1` | Marks bytes copied to VRAM reclaimable instead of dropping them from the page cache. | +| `STRATA_ADAPT_EVERY`, `STRATA_ADAPT_SWAPS` | How `serve` learns the expert placement from the reply. Default: 16 swaps every 16 tokens. | +| `STRATA_PREFILL_PROTECT=0` | Lets a prompt place experts freely. By default a prompt in `serve` moves at most 10% of the expert slots. | +| `STRATA_RESET_COUNTS=1` | Turns that `serve` behaviour on for other commands. | +| `STRATA_INKLING2_MODEL` | Path to the GGUF for `tests/inkling2_forward.rs` only. | -When the model files fit in RAM with 4 GiB to spare, they are read into the page cache in the background from the -start and nothing is dropped, so experts that run on the CPU do not wait for the drive on their first use. -`STRATA_PRELOAD=1` forces that, `STRATA_PRELOAD=0` turns it off. +Inkling 2: -Otherwise bytes copied to VRAM are dropped from the page cache (`MADV_DONTNEED`), so on a model close to the machine's -RAM the experts that missed VRAM keep their pages; `STRATA_COLD_KEEP=1` only marks them reclaimable instead. `serve` learns -the placement from the reply (16 swaps every 16 tokens after the prompt); `STRATA_ADAPT_EVERY` and -`STRATA_ADAPT_SWAPS` override that, and `STRATA_RESET_COUNTS=1` turns on the reply-only placement for other commands. +| Variable | Default | What it does | +|---|---|---| +| `STRATA_DS_FAST_KERNELS` | `auto` | `auto`: fast kernels only with more than one device. `1` forces them on one card, `0` off on two. | +| `STRATA_DS_PLAIN_FIRST` | unset; `chat`/`serve`/`bench` set `1` | Keeps the plain weights on GPU 0. | +| `STRATA_DS_PF_TOKENS` | 2048 one card, 512 two | Tokens of one prompt chunk (at most 2048). | +| `STRATA_DS_KV_TOKENS` | `--ctx` | KV rows GPU 0 must still be able to take before it gives up a slab. | +| `STRATA_DS_PROF` | unset | Prints `inkling2: preloaded N/24 ...` and the per-chunk profile. | +| `STRATA_DS_NO_AFFINITY` | unset | Picks the GPU per expert instead of per stacked tensor. | +| `STRATA_DS_NO_SEG_GRAPH` | unset | Does not capture the segmented decode graph. | +| `STRATA_CTRL_TILE` | follows `FAST_KERNELS` | `0` forces the per-token controllers. | +| `STRATA_DS_ATTN_OLD`, `STRATA_DS_ATTN_KP4` | off | `1` selects the old, or the four-query, attention kernels. `OLD` wins over the Q8 switches. | +| `STRATA_DS_ATTN_Q8_SHARED`, `STRATA_DS_ATTN_Q8_HD128` | on | CUDA Q8 attention kernels for head dimension 128, prefill and decode. `0` turns one off. | diff --git a/docs/VISION.md b/docs/VISION.md index 8b7fe90d..c6b362b8 100644 --- a/docs/VISION.md +++ b/docs/VISION.md @@ -1,140 +1,87 @@ -# Vision / multimodal plan - -Status: Qwen3-VL image input works on the CPU path and on the GPU path. The projector, image -preprocessing, prompt expansion and M-RoPE text integration run against `qwen3.5-2b` + -`qwen3.5-2b-mmproj.gguf`; `generate`/`chat --image` and `serve` image requests (OpenAI `image_url` and -Anthropic image blocks) work with or without `--gpu`. - -Gemma 4 (`gemma4v`) image input works through `generate --image`, `chat --image` and `serve` (OpenAI -`image_url`/Anthropic `image` blocks); `chat`/`serve` use the model's `tokenizer.chat_template` (system -turn, `<|think|>` when `--think`, empty `<|channel>thought` when not). Its encoder (`2*x-1` patches, x/y -position tables, RMS ViT with split NEOX RoPE, 3x3 average pooling, `v.std_bias`/`v.std_scale` and -`mm.input_projection`) matches `llama-mtmd-debug -p encode` on the 26B-A4B mmproj. Gemma 4 text uses -normal RoPE, so image tokens take sequential positions and the prompt inserts `<|image>` (BOI), the -soft tokens and `` (EOI). The `gemma4uv` unified embedder (big 48x48 conv patch, three -LayerNorms, x/y position tables, unweighted RMS norm, `mm.input_projection`) is verified against -`llama-mtmd-debug -p encode` with the 0.8B unified mmproj. GLM-4V and DeepSeek-OCR have no matching text -forward in this repo and stay rejected. - -GPU image prompts prefill on the CPU (`vision::feed_prompt` with `Model::step_embed`), upload the KV and -recurrent state into `GpuModel::load_state`, and decode on the GPU. The GPU's RoPE position is decoupled -from the KV row through `GpuModel::rope_offset`/`rope_buf`, so text after an image resumes at the -projector's `next_position` while the cache row stays contiguous. Gemma 4 uses normal RoPE and is -wired through `generate`, `chat` and `serve`; `generate` is raw completion, so a chat-tuned Gemma 4 -needs the template in `--prompt` (or use `chat`), while `chat`/`serve` apply it. GLM-4V/DeepSeek-OCR need a matching text forward before -their projectors can be used. - -The goal is image input for the Qwen family first (`qwen35`, `qwen35moe`, `qwen4exp`, `qwen3next`, -`qwen3`, `qwen3moe`) with a shared `clip` loader and projector registry. The registry also carries Gemma 4 -(`gemma4v`, `gemma4uv`). DeepSeek V4.1-Flash and GLM-5.3 are text-only upstream; their multimodal -variants use different text architectures, so there is no matching projector to wire. Audio projectors are -out of scope. - -## Layout +# Vision: image input -``` -src/vision/mod.rs VisionSpec, mmproj discovery/validation, registry -src/vision/mmproj.rs CLIP GGUF metadata + tensor access -src/vision/image.rs decode, data URL/HTTP fetch, smart resize, normalize -src/vision/projector.rs VisionProjector struct + Qwen3VL encoder -src/vision/prompt.rs image spans, placeholder expansion, token embeddings/positions +`generate`, `chat` and `serve` take images, on the CPU and on the GPU. The model needs its projector file (an mmproj +GGUF). The general flag reference is in [USAGE.md](USAGE.md). + +## Models that take images + +| Model | Checked with | +|---|---| +| Qwen3-VL projectors (`qwen3vl_merger`) | `qwen3.5-2b` with `qwen3.5-2b-mmproj.gguf`, and the Qwen3.6-35B-A3B mmproj | +| Qwen3.8 Flash-Next (`qwen4exp`, same projector, `projection_dim` 2560) | unsloth's UD-IQ2_XS with `mmproj-F16.gguf` | +| Gemma 4 (`gemma4v`) | the `gemma-4-26B-A4B` mmproj-F16 | +| Gemma 4 unified (`gemma4uv`) | the `gemma-4-unified-0.8B-tiny` mmproj-f16 with its Q2_K text GGUF | +| Inkling 2 | the Inkling 2 mmproj-F16 | + +The target is the whole Qwen family: `qwen35`, `qwen35moe`, `qwen4exp`, `qwen3next`, `qwen3`, `qwen3moe`. + +## Commands + +```bash +# The first mmproj*.gguf next to the model is used +rustingstrata generate --model model.gguf --image photo.png --prompt "Describe this picture: " + +rustingstrata chat --model model.gguf --mmproj mmproj.gguf --image photo.png + +rustingstrata serve --model model.gguf --mmproj mmproj.gguf --gpu ``` -Dependencies: `image` (png/jpeg/webp) and `base64`. Reuse `ureq` for remote URLs. Both are already in -the local cargo cache. +| Flag | Default | Meaning | +|---|---|---| +| `--image SRC` | none | A file path, a data URL or an `http(s)` URL. Repeatable. | +| `--mmproj FILE` | the first `mmproj*.gguf` next to the model | The projector file. `none` loads no projector. | -## Projector interface +- In `generate`, each image goes where the prompt has ``. Without ``, all images go before the prompt. +- `generate` is raw completion. A chat-tuned Gemma 4 needs its template in `--prompt`, or use `chat`. +- `chat` and `serve` use the model's `tokenizer.chat_template`. `--think` turns Gemma 4 thinking on. +- Image files are png, jpeg or webp. -```rust -pub struct PreprocessedImage { pub width: usize, pub height: usize, pub rgb: Vec } // interleaved RGB +## Server requests -pub struct VisionProjector { - pub cfg: ClipConfig, - pub model: ClipModel, -} +`serve` reads OpenAI `image_url` parts and Anthropic `image` blocks (base64 or URL): -impl VisionProjector { - pub fn preprocess(&self, image: &image::RgbImage) -> anyhow::Result; - pub fn count_tokens(&self, width: usize, height: usize) -> anyhow::Result<(usize, usize)>; - pub fn encode(&self, img: &PreprocessedImage) -> anyhow::Result>>; // merged_tokens x projection_dim - pub fn image_token_count(&self, img: &PreprocessedImage) -> anyhow::Result; - pub fn positions(&self, start: usize, width: usize, height: usize) -> Vec<[i32; 4]>; -} +```json +{"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}} +{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "..."}} ``` -`count_tokens` returns the number of merged image tokens (`nx * ny / merge^2`) and the token grid -(`nx/merge`, `ny/merge`). - -## Qwen3-VL projector - -The mmproj metadata is `clip.projector_type=qwen3vl_merger`, `clip.vision.image_size=768`, -`patch_size=16`, `spatial_merge_size=2`, `image_mean/std=[0.5; 3]`, `use_gelu=true`. The tensor set is -`v.patch_embd.weight`, `v.patch_embd.weight.1`, `v.patch_embd.bias`, `v.position_embd.weight`, -`v.blk.N.{ln1,ln2,attn_qkv,attn_out,ffn_up,ffn_down}.{weight,bias}`, `v.post_ln.{weight,bias}`, -`mm.0.{weight,bias}`, `mm.2.{weight,bias}`. - -Pipeline: - -1. Smart resize: preserve aspect ratio, align to `patch_size * merge = 32`, keep pixel count in - `[8*32*32, 4096*32*32]`; bilinear resize with align-corners like `mtmd_image.cpp`. -2. Normalize RGB to `(v/255 - mean) / std`, keep interleaved RGB `[w][h][c]`. -3. Patch conv 16x16 stride 16, two convs summed; add patch bias. Tensor `v.patch_embd.weight` is - `[16,16,3,1024]` and `.1` the same, row order `(kx, ky, c)`. -4. Resize `v.position_embd.weight` from 48x48 to `(nx, ny)` with bilinear + antialias - (`ggml_interpolate` defaults), add to patches. -5. LayerNorm (not RMS) pre-LN if present; 24/27 blocks: LayerNorm -> fused QKV -> M-RoPE (vision, - 2-D: first 16 pairs y, next 16 x) -> softmax attention -> output projection + bias -> residual; - LayerNorm -> FFN up/GELU/down -> residual. NORMAL LayerNorm and exact tanh GELU. -6. Post LayerNorm. Rearrange patches into 2x2 merged blocks: within a block the 4 patch features are - `(h1=0,w1=0), (h1=0,w1=1), (h1=1,w1=0), (h1=1,w1=1)`, i.e. row-major. Blocks are ordered - `(h2, w2)` row-major. -7. `mm.0` (4*n_embd -> 4*n_embd) + GELU + `mm.2` (4*n_embd -> projection_dim). Deepstack features are - concatenated when metadata enables them. - -Positions for the text model come from `mtmd_image_tokens_get_decoder_pos`: image tokens start at the -placeholder position `p0`; `t = p0`, `x = p0 + i % nx`, `y = p0 + i / nx`, `z = 0`; text resumes at -`p0 + max(nx, ny)`. - -## Text-model integration - -- `ModelConfig.mrope_sections` parses `{arch}.rope.dimension_sections`. -- `State.rope_pos` is the M-RoPE position of the next token; `State.pos` remains the KV row. Image tokens - advance the KV row by one but the RoPE position by `max(nx, ny)`. -- `Model::step_embed` feeds a precomputed embedding at explicit positions; text-only `step` is unchanged. -- `generate --image` and `chat --image` load the projector, encode the images, expand ``, and feed the - prompt through `feed_prompt`. -- `serve` parses OpenAI `image_url` blocks and Anthropic `image` blocks (base64 or URL); `Msg` carries the - image URLs and the template renders one `` placeholder per image. The chat page has an attach - button, drag/paste, previews and sends `image_url` blocks with the message. -- GPU image prompts: prefill on the CPU, copy the CPU state into the GPU's KV/recurrent buffers - (`GpuModel::load_state`), then decode on the GPU. The CPU prefill does the full M-RoPE; the GPU only needs - the text RoPE offset (`GpuModel::rope_offset`), so no CUDA/Vulkan M-RoPE kernel is needed. -- `tests/gpu_model.rs::gpu_image_prefill_matches_cpu` checks the CPU prefill logits against the GPU on - CUDA and Vulkan, the KV-row/RoPE-offset split, and that decoding names the image color. It runs on the - default model (whose sibling `mmproj-F16.gguf` is found by `find_sibling`) or `STRATA_MODEL`. -- Gemma 4 `generate --image` builds `<|image>` + soft tokens + ``, feeds the projector rows - through `Gemma4Model::step_embed_opt` (no sqrt(n_embd) scaling, matching embedding batches) and - decodes greedily. -- `tests/vision.rs::gemma4v_*` compare the encoder with `llama-mtmd-debug -p encode -n 96` for white and - red images, and check the 40-token preprocessing floor (64x64 -> 336x336 -> 7x7 tokens). -- `tests/vision.rs::gemma4uv_*` do the same for the unified projector (96x96 -> 2x2 tokens; sum and - edge values match llama.cpp, and 64x64 still grows to 336x336/49 tokens). -- Dense Gemma 4 text layers (no expert router) are supported, so the 0.8B unified GGUF can be loaded - and driven with the uv projector; the 0.8B community checkpoint is a toy model, so the numeric - projector check is the meaningful parity test. -- Gemma 4 `chat`/`serve` encode each image once, expand the message's `` markers, reuse the KV - prefix while the rendered conversation extends it, and decode greedily. `serve` is API-only (no web - chat page) and rejects tools (the text template supports them, but the server does not parse calls yet); - it needs `--model` because the `--models-dir` picker goes through `ModelConfig`. -- Still to do: a GPU-native image prefill (chunked, with per-row M-RoPE) for long prompts. - -## Validation - -- Golden embeddings from `llama-mtmd-debug -m --mmproj -p encode --image `. -- First target: `qwen3.5-2b` + `qwen3.5-2b-mmproj.gguf` (24 blocks, 1024 hidden, F32 patch/position, - BF16 block weights). -- Second: `Qwen3.6-35B-A3B` mmproj-F16 (27 blocks, 1152 hidden). -- Gemma 4: `gemma-4-26B-A4B` mmproj-F16 (`gemma4v`) and `gemma-4-unified-0.8B-tiny` mmproj-f16 - (`gemma4uv`, 48x48 conv patch, 3840-wide embedder, 2048 projection) with its Q2_K text GGUF. -- Unit tests: smart resize, bilinear/antialias resize, normalization, patch merge order, M-RoPE vision - pairs, position mapping. +The chat page has an attach button, paste and previews. It sends `image_url` parts with the message. + +An `http(s)` image is fetched only from a public address: + +- Loopback, private, link-local, 100.64.0.0/10 and reserved addresses are refused. This also holds for IPv4-mapped, + NAT64 and 6to4 IPv6 addresses, and for every redirect. +- With `HTTP(S)_PROXY` or `ALL_PROXY` set, the download goes through the proxy (`NO_PROXY` applies). Redirects are not + followed then. +- The proxy resolves the host again. A DNS answer that changes after the check is not caught. + +## GPU + +With `--gpu` the encoders (Qwen3-VL, Gemma 4, Inkling 2) run on the GPU, with CUDA or Vulkan. + +- A 1024x768 image with the Qwen3.6-35B-A3B mmproj-BF16 on the RTX 3060 encodes in 4.1 to 4.5 s with CUDA and 3.8 to + 4.7 s with Vulkan, against 24 s on the CPU (12 threads). +- An operation that fails on the GPU, for example for lack of VRAM, is reported once. It stays on the CPU for the rest + of the run. +- The GPU encoder rounds differently, so its embeddings differ slightly from the CPU ones. + +## Limits and errors + +- Without a projector, `serve` answers an image request with a `400` that names `--mmproj`. +- Gemma 4 in `chat` and `serve` decodes greedily. Its `serve` rejects tools and answers on `/v1/chat/completions` + only. +- A Qwen3-VL image is resized with its aspect ratio kept, to a pixel count in `[8*32*32, 4096*32*32]`. +- A Gemma 4 image takes at least 40 tokens: a 64x64 image grows to 336x336. + +## Not working or planned + +- GLM-4V and DeepSeek-OCR projectors are rejected. RustingStrata has no matching text forward for them. +- DeepSeek V4.1-Flash and GLM-5.3 are text-only upstream, so they take no images. +- Audio projectors are out of scope. + +## Environment variables + +| Variable | Meaning | +|---|---| +| `STRATA_VISION_CPU=1` | Keep the whole image encoder on the CPU. | +| `STRATA_ALLOW_PRIVATE_IMAGE_URLS=1` | Turn the address check off, for a trusted local setup. | diff --git a/docs/datacenter-nvidia-results.md b/docs/datacenter-nvidia-results.md index b494f63e..7585bc29 100644 --- a/docs/datacenter-nvidia-results.md +++ b/docs/datacenter-nvidia-results.md @@ -1,21 +1,23 @@ # A100, A30, L40S and H100 results -Four data-center NVIDIA cards on one Slurm cluster, one GPU per job. Rocky Linux 8.10, driver 615.71.09 (Vulkan -1.4.351), NVRTC 13.0 from the CUDA 13.0.1 toolkit, Rust 1.99.1, `target-cpu=native`. A job runs on whichever node with -the requested GPU type is free, so the host CPU can differ between jobs, and the `h100` type is either an H100 NVL or an -H100 80GB HBM3. Each section lists the hosts it ran on. Numbers are comparable within one job only. +Four data-center NVIDIA cards on one Slurm cluster, one GPU per job. Software: Rocky Linux 8.10, driver 615.71.09 +(Vulkan 1.4.351), NVRTC 13.0 from the CUDA 13.0.1 toolkit, Rust 1.99.1, `target-cpu=native`. -- [Calibrated runs: Q2_K_XL, Q8_0 and BF16](#2026-11-10--calibrated-runs-q2_k_xl-q8_0-and-bf16) -- [DeepSeek-V4.1-Flash-1017 IQ2_XXS](#2026-11-10--deepseek-v41-flash-1017-iq2_xxs) -- [First round: benchmarks without calibration](#2026-11-10--first-round-benchmarks-without-calibration) -- [Test suite](#2026-11-10--test-suite) -- [Vulkan hang in parallel tests](#2026-11-10--parallel-tests-can-hang-in-vkdestroydevice-on-this-driver) +A job runs on whichever node with the requested GPU type is free, so the host CPU can differ between jobs. The `h100` +type is either an H100 NVL or an H100 80GB HBM3. Each section lists its hosts. Numbers are comparable within one job +only. -## 2026-11-10 — calibrated runs: Q2_K_XL, Q8_0 and BF16 +- [Calibrated runs of Q2_K_XL, Q8_0 and BF16](#2026-11-10-calibrated-runs-of-q2_k_xl-q8_0-and-bf16) +- [DeepSeek-V4.1-Flash-1017 IQ2_XXS](#2026-11-10-deepseek-v41-flash-1017-iq2_xxs) +- [First round, benchmarks without calibration](#2026-11-10-first-round-benchmarks-without-calibration) +- [Test suite](#2026-11-10-test-suite) +- [Vulkan hang in parallel tests](#2026-11-10-parallel-tests-can-hang-in-vkdestroydevice-on-this-driver) + +## 2026-11-10: calibrated runs of Q2_K_XL, Q8_0 and BF16 Commit `e1c2d6e`. Each job builds, then runs on one card: -```sh +```bash rustingstrata bench --model $M --gpu --backend cuda --pp 512,4096 --tg 128 --reps 3 # uncalibrated rustingstrata calibrate --model $M --backend cuda rustingstrata bench --model $M --gpu --backend cuda --pp 512,4096 --tg 128 --reps 3 # calibrated @@ -24,8 +26,8 @@ rustingstrata check --model $M --backend vulkan # then the same four steps with --backend vulkan ``` -`XDG_CACHE_HOME` is a new directory per job, so the first bench has no calibration file, and the calibrated runs read -the file `calibrate` wrote. Mean (min-max) of 3 repetitions, tok/s. +`XDG_CACHE_HOME` is a new directory per job. So the first bench has no calibration file, and the calibrated runs read +the file that `calibrate` wrote. Speeds are mean (min-max) of 3 repetitions, tok/s. | File | Size | sha256 | Job size | | --- | --- | --- | --- | @@ -50,41 +52,27 @@ What `calibrate` chose (chunk / MTP drafts / short threshold): | BF16 | CUDA | 4096 / 1 / 8 | 4096 / 0 / 8 | 4096 / 0 / 8 | 4096 / 1 / 8 | | BF16 | Vulkan | 4096 / 1 / 8 | 4096 / 0 / 8 | 4096 / 0 / 8 | 4096 / 1 / 8 | -What the numbers show: - -- **MTP is what calibration adds to decode.** Calibrated with MTP on, decode after 512 is 1.47-1.93x the same run - with `--mtp 0` for Q2_K_XL, 1.40-1.88x for Q8_0 and 1.18-1.41x for BF16. Calibrated with `--mtp 0` decodes at the - uncalibrated CUDA speed (within 0.4% wherever all experts are resident and the first repetition was not slower). - The resident-experts column reads 10496 instead of 10240 when MTP is on: the MTP layer's experts are loaded too. -- **MTP costs prefill.** pp 4096 prefill with MTP on is 4-13% lower than with `--mtp 0` (H100 HBM3 Q2_K_XL CUDA 8304 - against 9530 tok/s), and 23% lower for Q2_K_XL Vulkan on the A30. -- **Calibrated Vulkan decode with MTP varies more.** After 4096 tokens, every MTP-on Vulkan row has a minimum - 17-41% below its maximum (A100 Q2_K_XL 180.3-260.7, H100 HBM3 Q2_K_XL 258.4-415.8), against 0.5-4% for the CUDA - rows with MTP. -- **Uncalibrated rows include one-time startup work.** In the uncalibrated Vulkan rows, one `pp 512` repetition - (presumably the first; the JSON keeps only mean, min and max) is far slower: minima of 85-205 tok/s where all - experts are resident. As in the first round, this is pipeline compilation, and it pulls the means down. The runs - after `calibrate` do not show it, probably because the driver's shader cache in `$XDG_CACHE_HOME/nvidia/GLCache` - holds the pipelines by then. Uncalibrated CUDA `pp 512` has a slow repetition on some cards too (minima 707 on the - L40S and 871 on the H100 HBM3 for Q2_K_XL, 447 on the L40S for Q8_0, 747 on the A100 for BF16), likely the first - use of kernels the per-job cache does not yet hold. So most of the `pp 512` prefill gain is not calibration: L40S - Q2_K_XL CUDA is 4607 tok/s uncalibrated and 6518 calibrated with `--mtp 0`, chunk 4096 in both. Compare with the - `--mtp 0` row or with the uncalibrated maximum, not with the uncalibrated mean. -- **Q8_0 decodes faster than Q2_K_XL** (separate jobs: the A100 and H100 ran on different nodes with the same CPU - model, the L40S on the same node) with CUDA on the A100 (200 against 179 tok/s with MTP off, 305 against 295 - calibrated) and on the H100 HBM3 (298 against 272, and 532 against 524), and slower on the L40S (169 against 221). -- **BF16 fits on the A100 and H100 NVL** (all 10240 experts resident). There it decodes at 176 / 237 tok/s with CUDA - (calibrated, `--mtp 0`) and 248 / 330 with MTP 1. Vulkan BF16 decode is 56-60% of CUDA (A100 98 against 176, H100 - NVL 142 against 237, both with `--mtp 0`). -- **Where experts do not fit, the first run is a cold start.** Q8_0 on the A30 (6479 of 10240 experts resident, 98.6% - hit rate), BF16 on the L40S (6657, 98.8%) and BF16 on the A30 (3133, 83.2%) read the missing experts from the GGUF - through the page cache. The uncalibrated bench is the first command in the job to touch the file, so some of its - repetitions read from the cluster file system (pp 512 minima of 17.6, 3.6 and 2.3 tok/s). It also starts without - a routing profile, so the resident experts are chosen in layer order; later runs load the profile it saved (BF16 - L40S CUDA misses 2995 uncalibrated, 2253 calibrated). On these cards the step from uncalibrated to `--mtp 0` - (decode after 512: Q8_0 A30 CUDA 126 to 137 tok/s, BF16 L40S 60 to 85) is the warm page cache and the profile, not - calibration. Past that, Q8_0 on the A30 gains from MTP like the other cards (209 tok/s), and `calibrate` chose MTP 0 - for BF16 on both cards. +What the numbers mean: + +- MTP is what calibration adds to decode. With MTP on, decode after 512 is 1.47-1.93x the `--mtp 0` run for Q2_K_XL, + 1.40-1.88x for Q8_0 and 1.18-1.41x for BF16. Calibrated with `--mtp 0` decodes at the uncalibrated CUDA speed. +- MTP costs prefill. pp 4096 prefill with MTP on is 4-13% lower than with `--mtp 0`, and 23% lower for Q2_K_XL Vulkan + on the A30. +- Calibrated Vulkan decode with MTP varies more. After 4096 tokens every such row has a minimum 17-41% below its + maximum, against 0.5-4% for the CUDA rows with MTP. + +What is not comparable: + +- An uncalibrated mean with a calibrated mean. One uncalibrated `pp 512` repetition includes one-time startup work: + Vulkan pipeline compilation, and on some cards probably the first use of CUDA kernels. Compare with the `--mtp 0` + row or with the uncalibrated maximum. +- Rows where the experts do not fit: Q8_0 on the A30, BF16 on the L40S and on the A30. The uncalibrated run there is + a cold start. It reads the missing experts from the cluster file system and has no routing profile yet. The step + from uncalibrated to `--mtp 0` is the warm page cache and the profile, not calibration. +- Q8_0 with Q2_K_XL. They ran in separate jobs. The A100 and H100 jobs ran on different nodes with the same CPU model, + the L40S jobs on the same node. + +The resident experts column reads 10496 instead of 10240 when MTP is on: the MTP layer's experts are loaded too. ### Qwen3.6-35B-A3B UD-Q2_K_XL @@ -173,37 +161,44 @@ What the numbers show: | H100 NVL | Vulkan | calibrated | 1 | 10496/10496 | 3640.9 (2502.5-4212.2) | 170.9 (170.4-171.4) | 6593.0 (6574.9-6615.4) | 158.5 (138.9-168.3) | | H100 NVL | Vulkan | calibrated, `--mtp 0` | 0 | 10240/10240 | 3694.6 (2281.7-4423.6) | 141.6 (141.4-141.8) | 7297.2 (7271.2-7317.4) | 138.3 (138.1-138.4) | -## 2026-11-10 — DeepSeek-V4.1-Flash-1017 IQ2_XXS +## 2026-11-10: DeepSeek-V4.1-Flash-1017 IQ2_XXS + +Commit `e1c2d6e`. One job per card, 32 cores and 240 GB RAM. -`ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF`: the five `IQ2_XXS` shards (138.2 GB) and -`DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf` (110.6 GB), linked as `...-IQ2_XXS-00006-of-00006.gguf`, 248.8 GB in all, -sha256 checked for each file. Commit `e1c2d6e`. One job per card, 32 cores and 240 GB RAM: +Model: `ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF`. The five `IQ2_XXS` shards (138.2 GB) and +`DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf` (110.6 GB), linked as `...-IQ2_XXS-00006-of-00006.gguf`. 248.8 GB in all, +sha256 checked for each file. | Job | Card | Host CPU | Node | | --- | --- | --- | --- | | A100 | A100-SXM4-80GB | EPYC 7413 | not the node of the earlier DeepSeek attempt on this card type | | H100 | H100 NVL | EPYC 9224 | same node as an earlier DeepSeek job that ended 4 minutes before, so part of the file was already in its page cache | -```sh +```bash rustingstrata check --model $M STRATA_DS_PROF=1 rustingstrata generate --model $M --prompt "The capital of France is" -n 16 # twice for each VRAM expert budget B in 9 and 60 (GB): STRATA_DS_PROF=1 STRATA_DS_GPU_EXPERTS=$B rustingstrata generate --model $M --prompt "$P" -n 128 ``` -`check`: `check: deepseek41 ok: 40 layers, 384 experts (6 used), 1043 tensors, tensor table valid (CPU reference -only; no GPU path yet)`; `generate` did use the card (`cuda device 0: ...` in every run's log). The first `generate` -printed ` Paris. The quick brown fox jumps over the lazy dog. The quick` on both cards. `$P` is "The history of the -printing press begins in East Asia, where woodblock printing was used centuries before movable type appeared in -Europe. The technology spread west along", 30 tokens. Every run on both cards printed the same 33 tokens and then -stopped at the end-of-sequence token: " trade routes, and by the 15th century, Gutenberg's press revolutionized -communication. This timeline traces the evolution from early woodblock methods to modern printing techniques." +`$P` is a prompt of 30 tokens: "The history of the printing press begins in East Asia, where woodblock printing was +used centuries before movable type appeared in Europe. The technology spread west along". Every run on both cards +printed the same 33 tokens and then stopped at the end-of-sequence token. -`STRATA_DS_PROF` prints one line per forward pass; prefill is one token at a time, so the first 30 lines are the prompt -and the other 33 are decode. The `total` on each line covers the 40 layers only: the output norm, the vocabulary -projection, argmax and detokenizing come after it. So the rates in this table are layer time, an upper bound; the -end-to-end rates are in the next table. Hit rate is the VRAM expert cache over the decode lines, and storage read is -`read_bytes` of `/proc/self/io` at the last line. +`check` printed the line below. `generate` did use the card: every run's log has a `cuda device 0: ...` line. + +``` +check: deepseek41 ok: 40 layers, 384 experts (6 used), 1043 tensors, tensor table valid (CPU reference only; no GPU path yet) +``` + +How to read the table: + +- `STRATA_DS_PROF` prints one line per forward pass. At this commit prefill runs one token at a time, so the first 30 + lines are the prompt and the other 33 are decode. +- The rates are layer time: the 40 layers only, without the output norm, the vocabulary projection, argmax and + detokenizing. They are an upper bound. The end-to-end rates are in the next table. +- Hit rate is the VRAM expert cache over the decode lines. Storage read is `read_bytes` of `/proc/self/io` at the + last line. | Card | Run | Wall time | Prefill, 30 tokens (layers) | Decode layer time, ms per token: mean (min-max) | Decode tok/s (layers) | VRAM hit rate | Storage read | | --- | --- | --- | --- | --- | --- | --- | --- | @@ -220,12 +215,15 @@ end-to-end rates are in the next table. Hit rate is the VRAM expert cache over t ### End to end -Two more jobs, built from a docs-only revision of this change (same code as `e1c2d6e`), same files, on other -nodes: A100-SXM4-80GB with an EPYC 7413 (24 CPUs, 200 GB RAM) and H100 NVL with a Xeon Gold 5418Y (16 CPUs, 120 GB -RAM). Each ran the same `generate` once with a 60 GB budget to fill -the page cache, then three pairs of `generate -n 1` and `generate -n 128` per budget, timed with `date +%s.%N` -around each process. `-n 1` stops after the prompt, `-n 128` runs the same prompt plus the 33 decode steps, so model -load and prefill cancel and (mean wall of `-n 128` - mean wall of `-n 1`) / 33 is the end-to-end decode time per token. +Two more jobs on other nodes, with the same files, built from a docs-only revision (same code as `e1c2d6e`): +A100-SXM4-80GB with an EPYC 7413 (24 CPUs, 200 GB RAM) and H100 NVL with a Xeon Gold 5418Y (16 CPUs, 120 GB RAM). + +- Each job ran the same `generate` once with a 60 GB budget to fill the page cache. +- Then it ran three pairs of `generate -n 1` and `generate -n 128` per budget, timed with `date +%s.%N` around each + process. +- `-n 1` stops after the prompt. `-n 128` runs the same prompt plus the 33 decode steps. So model load and prefill + cancel. +- End-to-end decode time per token is (mean wall of `-n 128` - mean wall of `-n 1`) / 33. | Card (host) | Budget | Wall, `-n 1` (s) | Wall, `-n 128` (s) | End-to-end decode | Per pair | Layer time in the `-n 128` runs | | --- | --- | --- | --- | --- | --- | --- | @@ -234,32 +232,38 @@ load and prefill cancel and (mean wall of `-n 128` - mean wall of `-n 1`) / 33 i | H100 NVL (Xeon Gold 5418Y) | 9 GB | 9.81, 8.38, 9.24 | 15.93, 17.14, 16.31 | 222 ms, 4.5 tok/s | 3.8-5.4 tok/s | 228 ms, 4.4 tok/s | | H100 NVL (Xeon Gold 5418Y) | 60 GB | 6.40, 6.42, 6.31 | 9.96, 9.75, 10.53 | 112 ms, 8.9 tok/s | 7.8-9.9 tok/s | 104 ms, 9.7 tok/s | -The A100's first 9 GB pair is left out: its `-n 1` read 5.1 GB from storage (109 s). Every other timed run read -14-16 MB. Each process's wall time moves by up to 1.4 s between runs, about 40 ms per decode token, so the difference -between end-to-end and layer time (-6 to 18 ms here) is within that noise: the part after the layers is small next to -the layers. All runs printed the same text as above. - -- Until the experts this prompt uses are in the page cache, reading them from the cluster file system decides the - speed (seconds to a minute per token; the warm-up runs took 44 minutes on the A100 node and 32 on the H100 node). - After that, end-to-end decode is 4.5-4.6 tok/s with the default 9 GB budget on both cards, and 6.6 (A100) and - 8.9 (H100 NVL) tok/s with 60 GB. -- The host matters at 9 GB: the H100 NVL's layer time was 152 ms per token with 32 CPUs on an EPYC 9224 node and - 228 ms with 16 CPUs on a Xeon Gold 5418Y node (different node, CPU model and core - count); at 60 GB it was 97 and 104 ms. -- In the warm H100 NVL runs on the EPYC 9224, the expert part of a decode token is 104 ms at 9 GB and 50 ms at - 60 GB; attention is 28-29 ms in both. On the A100 at 60 GB it is 70-78 ms for experts and 36-38 ms for attention. -- Maximum resident set size was 34-36 GiB in the 128-token runs of the first two jobs. Over the 33 decode tokens, the - 60 GB budget raises the VRAM hit rate from 23% to 84%; the misses are read from the page cache. -- These numbers rest on one raw prompt and 33 decode tokens (the model ended there), so they say nothing about long - prompts or long replies. +- The A100's first 9 GB pair is left out: its `-n 1` read 5.1 GB from storage (109 s). Every other timed run read + 14-16 MB. +- Each process's wall time moves by up to 1.4 s between runs, about 40 ms per decode token. The difference between + end-to-end and layer time (-6 to 18 ms here) is within that noise. + +What the numbers mean: + +- Until the experts this prompt uses are in the page cache, the cluster file system decides the speed: seconds to a + minute per token. The warm-up runs took 44 minutes on the A100 node and 32 on the H100 node. +- Warm, end-to-end decode is 4.5-4.6 tok/s with the 9 GB budget on both cards. With 60 GB it is 6.6 (A100) and 8.9 + (H100 NVL) tok/s, and the VRAM hit rate rises from 23% to 84%. +- The host matters at 9 GB. The H100 NVL's layer time was 152 ms per token with 32 CPUs on an EPYC 9224 node and + 228 ms with 16 CPUs on a Xeon Gold 5418Y node. At 60 GB it was 97 and 104 ms. + +What is not comparable: + +- These numbers rest on one raw prompt and 33 decode tokens. They say nothing about long prompts or long replies. - The README's numbers (RTX 3060 12 GB, 30 GB RAM, 2-3.6 tok/s decode) are from another machine and were not re-run - here, so the two are not a side-by-side comparison. + here. The two are not a side-by-side comparison. + +Maximum resident set size was 34-36 GiB in the 128-token runs of the first two jobs. -## 2026-11-10 — first round: benchmarks without calibration +## 2026-11-10: first round, benchmarks without calibration + +Commit `7264e57` (v1.2.1). One GPU per job with 8 CPU cores and 48 GB RAM, no `calibrate` run, MTP off. + +```bash +rustingstrata bench --model $M --gpu --backend {cuda,vulkan} --pp 512,4096 --tg 128 --reps 3 +``` -Commit `7264e57` (v1.2.1), one GPU per job with 8 CPU cores and 48 GB RAM. Model: `Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf` -(sha256 `ed7cda7e...f37fb0c`); it fits in VRAM on every card here, so all 10240 experts are resident and the expert -hit rate is 100%. +Model: `Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf` (sha256 `ed7cda7e...f37fb0c`). It fits in VRAM on every card here, so all +10240 experts are resident and the expert hit rate is 100%. | GPU | VRAM | Arch | Host CPU | | --- | --- | --- | --- | @@ -269,8 +273,7 @@ hit rate is 100%. | H100 NVL | 95830 MiB | sm_90 | EPYC 9224 | | H100 80GB HBM3 (tests only) | 81559 MiB | sm_90 | Xeon Platinum 8470 | -`rustingstrata bench --model $M --gpu --backend {cuda,vulkan} --pp 512,4096 --tg 128 --reps 3`, no `calibrate` run, MTP -off. Mean (min-max) of 3 repetitions, tok/s. +Mean (min-max) of 3 repetitions, tok/s: | GPU | Backend | pp 512 prefill | decode after 512 | pp 4096 prefill | decode after 4096 | | --- | --- | --- | --- | --- | --- | @@ -283,8 +286,8 @@ off. Mean (min-max) of 3 repetitions, tok/s. | H100 NVL | CUDA | 5718.3 (5505.3-5868.2) | 253.1 (251.6-253.8) | 9130.8 (9115.2-9153.7) | 245.8 (245.1-246.1) | | H100 NVL | Vulkan | 2967.8 (118.2-4396.9) | 174.0 (95.5-213.3) | 6428.2 (5569.7-6857.7) | 191.5 (164.5-205.1) | -The first Vulkan repetition of `pp 512` includes pipeline compilation (the 118-143 tok/s minima), as on the V100. -The numbers are comparable within a row only: the four cards sit in hosts with different CPUs. +- The numbers are comparable within a row only: the four cards sit in hosts with different CPUs. +- The first Vulkan repetition of `pp 512` includes pipeline compilation. That gives the 118-143 tok/s minima. Startup lines: @@ -305,26 +308,37 @@ vulkan: NVIDIA H100 NVL (NVIDIA 615.71.09), cooperative matrix f16 yes int8 yes, plan: weights+state+scratch 1984 MB (KV 82 MB for 4224 tokens, prefill 512 MB), expert slots 10002 MB, resident experts 10240/10240 ``` -`rustingstrata check --backend vulkan --model $M` on each card: 96 (kernel, specialization) pairs checked, largest 49152 -bytes (`gemmi`) of 49152 allowed. +`rustingstrata check --backend vulkan --model $M` on each card: 96 (kernel, specialization) pairs checked, largest +49152 bytes (`gemmi`) of 49152 allowed. -## 2026-11-10 — test suite +## 2026-11-10: test suite -`STRATA_MODEL=$M cargo test --release --no-fail-fast -- --nocapture` on A100, A30, L40S and H100 80GB HBM3: 185 passed, -0 failed, 5 ignored on each. H100 NVL ran the same suite without `--nocapture` at `7264e57`: 185 passed, 0 failed, -5 ignored. A30 also passed with `--test-threads=1`. +```bash +STRATA_MODEL=$M cargo test --release --no-fail-fast -- --nocapture +``` + +Result on A100, A30, L40S and H100 80GB HBM3: 185 passed, 0 failed, 5 ignored on each. + +- H100 NVL ran the same suite without `--nocapture` at `7264e57`: 185 passed, 0 failed, 5 ignored. +- A30 also passed with `--test-threads=1`. +- Both backends were open in every run: each log has 48 `cuda device 0:` lines and 47 `vulkan:` device lines. +- The only skips are `no glslc` (`spirv_is_fresh`) and `STRATA_TEST_BACKENDS does not select cuda`. +- The `--nocapture` runs also ran the default-model checks, and they passed: the 0.05 logit tolerance of + `gpu_forward_matches_cpu_reference`, the type-coverage counts in `tests/kernels.rs`, and the shapes in + `tests/quant.rs` and `tests/gguf.rs`. -- Both backends were open in every run: each log has 48 `cuda device 0:` lines and 47 `vulkan:` device lines. The only - skips are `no glslc` (`spirv_is_fresh`) and `STRATA_TEST_BACKENDS does not select cuda`. -- The runs with `--nocapture` include the `tests/common` change that recognises the default model by file name, so the - default-model checks (the 0.05 logit tolerance of `gpu_forward_matches_cpu_reference`, the type-coverage counts in - `tests/kernels.rs`, the shapes in `tests/quant.rs` and `tests/gguf.rs`) ran and passed. Before it they were skipped - on any machine where the file is not at the path in `DEFAULT_MODEL`. +## 2026-11-10: parallel tests can hang in `vkDestroyDevice` on this driver + +Workaround: run the suite with one test thread. It did not hang in 30 runs. + +```bash +cargo test --release -- --test-threads=1 +``` -## 2026-11-10 — parallel tests can hang in `vkDestroyDevice` on this driver +The results are not affected: every run that finished passed. -One full `cargo test --release` on the A30 stopped in `tests/kernels.rs`: no output for five minutes, GPU utilisation -0%, one thread at 100% CPU. `gdb` on the test process: +What the hang looks like: one full `cargo test --release` on the A30 stopped in `tests/kernels.rs`. No output for +five minutes, GPU utilisation 0%, one thread at 100% CPU. `gdb` on the test process: ``` Thread 6: pthread_join <- libnvidia-eglcore.so.615.71.09 <- vkDestroyDevice <- ::drop (src/vulkan/mod.rs:279) @@ -334,16 +348,14 @@ Thread 40: pthread_mutex_lock <- vkCreateInstance <- Vk::new <- elementwise_ops_ 4 threads: __pthread_mutex_lock_full <- Inner::submit / Inner::buffer (other tests' devices) ``` -A test thread destroying its device waits for a driver thread that spins in its thread-local destructor and never -exits; the tests that start next wait on a loader mutex in `vkCreateInstance`. +A test thread that destroys its device waits for a driver thread. That thread spins in its thread-local destructor +and never exits. The tests that start next wait on a loader mutex in `vkCreateInstance`. -How often, with the `kernels` test binary run 15 times per card and killed after 240 s (600 s for the serial runs): +How often: the `kernels` test binary, run 15 times per card and killed after 240 s (600 s for the serial runs). | Run | A30 | A100 | | --- | --- | --- | | parallel (default test threads) | 2 of 15 hung, the others took 34-40 s | 3 of 15 hung, the others took 31-41 s | | `--test-threads=1` | 0 of 15 hung (51-85 s) | 0 of 15 hung (53-94 s) | -A hung run stopped after a different number of tests each time (0 to 12 finished). L40S and H100 were not looped. The -results are not affected: every run that finished passed. Until this is solved, `cargo test --release -- ---test-threads=1` is the way to run the suite on this driver: it did not hang in these 30 runs. +A hung run stopped after a different number of tests each time (0 to 12 finished). L40S and H100 were not looped. diff --git a/examples/dotn_bench.rs b/examples/dotn_bench.rs new file mode 100644 index 00000000..2e937b41 --- /dev/null +++ b/examples/dotn_bench.rs @@ -0,0 +1,37 @@ +//! Single-thread ns per row of int_dot / int_dot4 / int_dot8 on a real expert row (gate of a layer of each type). +use rusting_strata::gguf::Gguf; +use rusting_strata::model::Model; +use rusting_strata::cpu_moe::{int_dot, int_dot4, int_dot8, quantize_q8k}; +use std::time::Instant; +fn main() -> anyhow::Result<()> { + let a: Vec = std::env::args().collect(); + let g = Gguf::open(std::path::Path::new(&a[1]))?; + let m = Model::load(&g)?; + let mut seen = std::collections::BTreeSet::new(); + for il in 0..m.cfg.n_layer { + for name in ["ffn_gate_exps.weight", "ffn_down_exps.weight"] { + let Ok(t) = m.w.layer(il, name) else { continue }; + if !seen.insert(t.ty.name()) { continue; } + let e = t.expert(7, m.cfg.n_expert); + let rb = e.row_bytes(); + let xs: Vec> = (0..8).map(|k| quantize_q8k(&(0..t.cols).map(|i| ((i * 31 + k * 7) % 97) as f32 * 0.01 - 0.5).collect::>())).collect(); + let rows = 64.min(e.rows); + let it = 2000; + let d1 = int_dot(t.ty).unwrap(); + let t0 = Instant::now(); + let mut s = 0f32; + for _ in 0..it { for r in 0..rows { for k in 0..8 { s += d1(&e.data[r * rb..(r + 1) * rb], &xs[k]); } } } + let n1 = t0.elapsed().as_nanos() as f64 / (it * rows) as f64; + let n4 = int_dot4(t.ty).map(|d4| { let t0 = Instant::now(); for _ in 0..it { for r in 0..rows { for k in [0, 4] { s += d4(&e.data[r * rb..(r + 1) * rb], [&xs[k], &xs[k + 1], &xs[k + 2], &xs[k + 3]])[0]; } } } t0.elapsed().as_nanos() as f64 / (it * rows) as f64 }); + let n8 = int_dot8(t.ty).map(|d8| { let t0 = Instant::now(); for _ in 0..it { for r in 0..rows { s += d8(&e.data[r * rb..(r + 1) * rb], std::array::from_fn(|k| &xs[k][..]))[0]; } } t0.elapsed().as_nanos() as f64 / (it * rows) as f64 }); + let mut buf = vec![0f32; t.cols]; + let t0 = Instant::now(); + for _ in 0..it { for r in 0..rows { e.row(r, &mut buf); s += buf[r % t.cols]; } } + let nd = t0.elapsed().as_nanos() as f64 / (it * rows) as f64; + println!(" dequant row to f32: {nd:.0} ns"); + println!("{:8} {} cols {:5}: 8 tokens per row: 8x dot {:6.0} ns, 2x dot4 {:>6} ns, dot8 {:>6} ns ({s:.0})", t.ty.name(), name, t.cols, n1, + n4.map_or("-".into(), |v| format!("{v:.0}")), n8.map_or("-".into(), |v| format!("{v:.0}"))); + } + } + Ok(()) +} diff --git a/examples/ds_cpu_bench.rs b/examples/ds_cpu_bench.rs new file mode 100644 index 00000000..c6a0d6be --- /dev/null +++ b/examples/ds_cpu_bench.rs @@ -0,0 +1,116 @@ +//! CPU routed-expert microbenchmark at DeepSeek-V4.1-Flash shapes (n_embd 4096, expert FFN 2048, 6 used), on random +//! weights in RAM (larger than the CPU caches). No GPU, no model file. Run it on the host that will serve the model +//! to pick `--threads`: +//! cargo run --release --example ds_cpu_bench -- [types, default Q4_K,IQ2_XXS] [threads, default all] [tokens per expert, default 8] [n_embd, default 4096] [expert FFN, default 2048] +//! Prints, per quant type: one-thread dot rate, the decode expert step (6 experts on one token) as three separate +//! matvecs per expert and as two fused passes, and the prefill step (every expert of a chunk on its tokens). +//! Set STRATA_AVX512=1 to time the AVX-512 kernels of a binary built with them. +//! Set STRATA_BENCH_GAP_US=300 to idle 300 us before each timed run (the GPU part of a layer) and print the mean. +use rusting_strata::deepseek::mat::{Mat, matvec_many_cpu, matvec_many_cpu_shared, matvec_rows}; +use rusting_strata::quant::GgmlType; +use std::time::Instant; + +const USED: usize = 6; +const POOL: usize = 48; + +fn mat(data: &[u8], ty: GgmlType, rows: usize, cols: usize) -> Mat<'_> { + Mat { data, ty, rows, cols, cpu: true, gpu: None, scale: 1.0 } +} + +/// Best of `reps` timed runs. STRATA_BENCH_GAP_US=N idles the calling thread N us before each run, as the GPU part +/// of a layer does in the engine, so the pool threads go to sleep in between; the mean is then the number to read. +fn best(reps: usize, mut f: impl FnMut()) -> f64 { + let gap = std::env::var("STRATA_BENCH_GAP_US").ok().and_then(|v| v.parse().ok()).map(std::time::Duration::from_micros); + f(); + let ts: Vec = (0..reps).map(|_| { + if let Some(g) = gap { std::thread::sleep(g); } + let t = Instant::now(); f(); t.elapsed().as_secs_f64() + }).collect(); + if gap.is_some() { println!(" (gap {gap:?}: mean {:.3} ms of {reps})", ts.iter().sum::() / reps as f64 * 1e3); } + ts.into_iter().fold(f64::MAX, f64::min) +} + +fn main() { + let a: Vec = std::env::args().collect(); + let types: Vec = a.get(1).map_or("Q4_K,IQ2_XXS", |s| s.as_str()).split(',').map(|n| { + (0..200).filter_map(|i| GgmlType::from_u32(i).ok()).find(|t| t.name() == n).unwrap_or_else(|| panic!("type {n}")) + }).collect(); + if let Some(t) = a.get(2).and_then(|s| s.parse().ok()) { rayon::ThreadPoolBuilder::new().num_threads(t).build_global().unwrap(); } + let per: usize = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(8); + // DeepSeek-V3/R1 shapes: 7168 2048. + let nn: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(4096); + let ff: usize = a.get(5).and_then(|s| s.parse().ok()).unwrap_or(2048); + println!("threads {} avx512 {}", rayon::current_num_threads(), std::env::var_os("STRATA_AVX512").is_some()); + let mut r = 0x9E3779B97F4A7C15u64; + let x: Vec = (0..nn).map(|i| ((i as f32 * 0.7548777).fract() - 0.5) * 2.0).collect(); + for ty in types { + let (gb, db) = (ff * ty.row_bytes(nn as u64), nn * ty.row_bytes(ff as u64)); + // Random bytes with every f16 scale field set to a small number: rates do not depend on the values. + let mut buf = |len: usize| -> Vec { + let mut v: Vec = (0..len).map(|_| { r ^= r << 13; r ^= r >> 7; r ^= r << 17; r as u8 }).collect(); + for b in v.chunks_exact_mut(ty.block_bytes()) { if b.len() >= 2 { b[0] = 0x1f; b[1] = 0x20; } } + v + }; + let (g, u, d) = (buf(POOL * gb), buf(POOL * gb), buf(POOL * db)); + let ex = |e: usize| [mat(&g[e * gb..(e + 1) * gb], ty, ff, nn), mat(&u[e * gb..(e + 1) * gb], ty, ff, nn), mat(&d[e * db..(e + 1) * db], ty, nn, ff)]; + let bytes = USED as f64 * (2 * gb + db) as f64; + + // One thread, one matrix in L2: the kernel's own rate. + let xq = rusting_strata::cpu_moe::quantize_q8k(&x); + let dot = rusting_strata::cpu_moe::int_dot(ty).expect("no integer dot"); + let rb = ty.row_bytes(nn as u64); + let rows = 256; + let t = best(20, || { let mut s = 0f32; for i in 0..rows { s += dot(&g[i * rb..(i + 1) * rb], &xq); } std::hint::black_box(s); }); + println!("{}: 1-thread dot {:.2} GB/s ({:.0} ns/row of {nn})", ty.name(), (rows * rb) as f64 / t / 1e9, t / rows as f64 * 1e9); + if let Some(dot4) = rusting_strata::cpu_moe::int_dot4(ty) { + let t = best(20, || { let mut s = 0f32; for i in 0..rows { s += dot4(&g[i * rb..(i + 1) * rb], [&xq, &xq, &xq, &xq])[3]; } std::hint::black_box(s); }); + println!("{}: 1-thread dot4 {:.0} ns/row (4 activations)", ty.name(), t / rows as f64 * 1e9); + } + + // Decode: 6 experts of one token, a different set every rep so the weights come from RAM. + let mut set = 0; + let mut pick = || { set = (set + USED) % (POOL - USED); (set..set + USED).collect::>() }; + let sep = best(20, || { + let (mut gy, mut uy, mut dy, mut mix) = (vec![0f32; ff], vec![0f32; ff], vec![0f32; nn], vec![0f32; nn]); + for e in pick() { + let [gm, um, dm] = ex(e); + gm.matvec(&x, &mut gy); + um.matvec(&x, &mut uy); + for (g, u) in gy.iter_mut().zip(&uy) { *g = *g / (1.0 + (-*g).exp()) * u; } + dm.matvec(&gy, &mut dy); + for j in 0..nn { mix[j] += dy[j]; } + } + std::hint::black_box(mix); + }); + let fused = best(20, || { + let es = pick(); + let gu: Vec = es.iter().flat_map(|&e| { let [g, u, _] = ex(e); [g, u] }).collect(); + let y = matvec_many_cpu_shared(&gu, &x).unwrap(); + let acts: Vec> = y.chunks_exact(2 * ff).map(|c| c[..ff].iter().zip(&c[ff..]).map(|(g, u)| g / (1.0 + (-g).exp()) * u).collect()).collect(); + let downs: Vec = es.iter().map(|&e| ex(e)[2]).collect(); + let dy = matvec_many_cpu(&downs, &acts.iter().map(|a| a.as_slice()).collect::>()).unwrap(); + let mut mix = vec![0f32; nn]; + for d in dy.chunks_exact(nn) { for j in 0..nn { mix[j] += d[j]; } } + std::hint::black_box(mix); + }); + println!("{}: decode 6 experts: separate matvecs {:.2} ms ({:.1} GB/s), fused {:.2} ms ({:.1} GB/s)", + ty.name(), sep * 1e3, bytes / sep / 1e9, fused * 1e3, bytes / fused / 1e9); + + // Prefill: POOL experts, `per` tokens each (each weight row read once for its tokens). + let xs: Vec> = (0..per).map(|t| x.iter().map(|v| v * (1.0 + t as f32 * 0.01)).collect()).collect(); + let xr: Vec<&[f32]> = xs.iter().map(|v| v.as_slice()).collect(); + let pre = best(3, || { + use rayon::prelude::*; + let out: Vec> = (0..POOL).into_par_iter().map(|e| { + let [gm, um, dm] = ex(e); + let (gy, uy) = (matvec_rows(&gm, &xr), matvec_rows(&um, &xr)); + let act: Vec = gy.iter().zip(&uy).map(|(g, u)| g / (1.0 + (-g).exp()) * u).collect(); + matvec_rows(&dm, &act.chunks_exact(ff).collect::>()) + }).collect(); + std::hint::black_box(out); + }); + println!("{}: prefill {POOL} experts x {per} tokens: {:.1} ms, {:.0} token-experts/s ({:.1} GB/s of weights, {:.2} TFLOPS)", + ty.name(), pre * 1e3, (POOL * per) as f64 / pre, POOL as f64 * (2 * gb + db) as f64 / pre / 1e9, + (POOL * per * 6 * nn * ff) as f64 / pre / 1e12); + } +} diff --git a/examples/host_attn_bench.rs b/examples/host_attn_bench.rs new file mode 100644 index 00000000..dd98a2eb --- /dev/null +++ b/examples/host_attn_bench.rs @@ -0,0 +1,27 @@ +//! cargo run --release --example host_attn_bench -- [positions]: one CPU decode-attention call over a q4 cache. +use rusting_strata::host_attn::{HostAttn, run}; +fn main() { + let n: usize = std::env::args().nth(1).map_or(52_000, |s| s.parse().unwrap()); + let (nh, nkv, hd) = (24, 4, 256); + let rb = hd / 2 + hd / 16; + let mut seed = 1u32; + let mut rnd = || { seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); seed }; + let mut kc = vec![0u8; n * nkv * rb]; + let mut vc = vec![0u8; n * nkv * rb]; + for (k, v) in kc.iter_mut().zip(vc.iter_mut()) { *k = rnd() as u8; *v = rnd() as u8; } + for r in 0..n * nkv { for b in 0..hd / 32 { let o = r * rb + hd / 2 + 2 * b; let d = half::f16::from_f32(0.05).to_le_bytes(); kc[o..o + 2].copy_from_slice(&d); vc[o..o + 2].copy_from_slice(&d); } } + let nt: usize = std::env::args().nth(2).map_or(1, |s| s.parse().unwrap()); + let q1: Vec = (0..nh * hd).map(|_| (rnd() % 1000) as f32 / 1000.0 - 0.5).collect(); + let q: Vec = (0..nt).flat_map(|_| q1.clone()).collect(); + let step: Vec = (0..nt).flat_map(|t| [(n - nt + t) as i32, 0]).collect(); + let mut part = vec![0f32; nt * nh * (hd + 2)]; + let a = HostAttn { q: q.as_ptr() as usize, step: step.as_ptr() as usize, part: part.as_mut_ptr() as usize, kc: kc.as_ptr() as usize, vc: vc.as_ptr() as usize, nh, nkv, hd, nt, scale: 1.0 / 16.0, mode: 2 }; + run(&a); + let t = std::time::Instant::now(); + let gap: u64 = std::env::var("GAP_US").ok().map_or(0, |s| s.parse().unwrap()); + let mut busy = 0.0; + for _ in 0..20 { if gap > 0 { std::thread::sleep(std::time::Duration::from_micros(gap)); } let t1 = std::time::Instant::now(); run(&a); busy += t1.elapsed().as_secs_f64(); } + let _ = t; let ms = busy * 1e3 / 20.0; + let gb = (2 * n * nkv * rb) as f64 / 1e9; + println!("{n} positions: {ms:.2} ms/call, {:.1} GB/s, x16 layers = {:.1} ms/token; check {:.6} {:.6}", gb / ms * 1e3, ms * 16.0, part[(nt - 1) * nh * (hd + 2)], part[(nt - 1) * nh * (hd + 2) + hd + 1]); +} diff --git a/examples/moe_cpu_layer_bench.rs b/examples/moe_cpu_layer_bench.rs new file mode 100644 index 00000000..51a8cd88 --- /dev/null +++ b/examples/moe_cpu_layer_bench.rs @@ -0,0 +1,82 @@ +//! CPU routed-expert step on a real GGUF: `cpu_moe::experts` for `k` random experts of every MoE layer in turn (the +//! decode worker's work for one token), timed per token with the bytes it read. Picks new experts every call, so the +//! weights come from RAM (or the page cache), not from the CPU caches. +//! cargo run --release --example moe_cpu_layer_bench -- MODEL.gguf [experts per layer, default 6] [tokens, default 64] +//! Set RAYON_NUM_THREADS to try other thread counts, and STRATA_BENCH_GAP_US=N to idle N us between layers (the GPU part). +use rusting_strata::gguf::Gguf; +use rusting_strata::model::Model; +use std::time::Instant; + +fn main() -> anyhow::Result<()> { + let a: Vec = std::env::args().collect(); + let g = Gguf::open(std::path::Path::new(&a[1]))?; + let m = Model::load(&g)?; + let k: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(6); + let toks: usize = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(64); + let gap = std::env::var("STRATA_BENCH_GAP_US").ok().and_then(|v| v.parse().ok()).map(std::time::Duration::from_micros); + let c = &m.cfg; + anyhow::ensure!(k <= c.n_expert, "requested {k} experts per layer, but model has only {}", c.n_expert); + let layers: Vec = (0..c.n_layer).filter(|&il| m.w.layer(il, "ffn_gate_exps.weight").is_ok()).collect(); + let mut rng = 0x9E3779B97F4A7C15u64; + let mut next = || { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; rng }; + let h: Vec = (0..c.n_embd).map(|i| ((i * 7919 % 1000) as f32 / 1000.0 - 0.5) * 0.1).collect(); + let bytes_of = |il: usize, e: usize| -> usize { + ["ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight"].iter() + .map(|s| m.w.layer(il, s).unwrap().expert(e, c.n_expert).data.len()).sum() + }; + // Touch every expert once so the page cache holds them (as a warm server's would). + let t = Instant::now(); + let mut sum = 0u64; + for &il in &layers { for e in 0..c.n_expert { for s in ["ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight"] { + let d = m.w.layer(il, s).unwrap().expert(e, c.n_expert).data; let mut i = 0; while i < d.len() { sum += d[i] as u64; i += 4096; } + } } } + eprintln!("touched all experts in {:.1} s ({sum})", t.elapsed().as_secs_f64()); + let mut per_layer = vec![(0u128, 0usize); c.n_layer]; + let mut per_tok = Vec::new(); + let mut total_bytes = 0usize; + for tk in 0..toks + 4 { + let mut ns = 0u128; let mut by = 0usize; + for &il in &layers { + let mut sel: Vec<(usize, f32)> = Vec::new(); + while sel.len() < k { let e = (next() % c.n_expert as u64) as usize; if !sel.iter().any(|s| s.0 == e) { sel.push((e, 0.1)); } } + by += sel.iter().map(|s| bytes_of(il, s.0)).sum::(); + if let Some(gp) = gap { std::thread::sleep(gp); } + if std::env::var_os("BENCH_WARM").is_some() { std::hint::black_box(rusting_strata::cpu_moe::experts(&m, il, &h, &sel)); } + let t = Instant::now(); + let ntok: usize = std::env::var("BENCH_TOKENS").ok().and_then(|v| v.parse().ok()).unwrap_or(1); + let fused = std::env::var_os("BENCH_FUSED").is_some(); + let y = if ntok > 1 { + let hs: Vec> = (0..ntok).map(|t| h.iter().map(|v| v * (1.0 + t as f32 * 0.01)).collect()).collect(); + let pairs: Vec<(usize, usize, f32)> = sel.iter().flat_map(|&(e, _)| (0..ntok).map(move |t| (t, e, 0.0))).collect(); + rusting_strata::cpu_moe::expert_rows(&m, il, &hs, &pairs) + } else if fused { rusting_strata::cpu_moe::experts_fused(&m, il, &h, &sel) } else { rusting_strata::cpu_moe::experts(&m, il, &h, &sel) }; + if std::env::var_os("BENCH_CHECK").is_some() { + let r = if ntok > 1 { + let hs: Vec> = (0..ntok).map(|t| h.iter().map(|v| v * (1.0 + t as f32 * 0.01)).collect()).collect(); + let pairs: Vec<(usize, usize, f32)> = sel.iter().flat_map(|&(e, _)| (0..ntok).map(move |t| (t, e, 0.0))).collect(); + rusting_strata::cpu_moe::expert_rows_two_pass(&m, il, &hs, &pairs) + } else if fused { rusting_strata::cpu_moe::experts(&m, il, &h, &sel) } else { rusting_strata::cpu_moe::experts_fused(&m, il, &h, &sel) }; + assert!(y.len() == r.len() && y.iter().zip(&r).all(|(a, b)| a.to_bits() == b.to_bits()), "layer {il}: fused differs"); + } + let dt = t.elapsed().as_nanos(); ns += dt; + if tk >= 4 { per_layer[il].0 += dt; per_layer[il].1 += sel.iter().map(|s| bytes_of(il, s.0)).sum::(); } + std::hint::black_box(y); + } + if tk >= 4 { per_tok.push(ns as f64 / 1e6); total_bytes += by; } + } + if std::env::var_os("BENCH_LAYERS").is_some() { + let mut groups: std::collections::BTreeMap = Default::default(); + for &il in &layers { + let ty = |s: &str| m.w.layer(il, s).unwrap().ty.name(); + let key = format!("{}/{}", ty("ffn_gate_exps.weight"), ty("ffn_down_exps.weight")); + let e = groups.entry(key).or_default(); e.0 += per_layer[il].0; e.1 += per_layer[il].1; + } + for (k, (ns, by)) in groups { println!(" {k:20} {:6.2} ms/token {:5.1} GB/s", ns as f64 / 1e6 / toks as f64, by as f64 / ns as f64); } + } + let mean = per_tok.iter().sum::() / per_tok.len() as f64; + let mut s = per_tok.clone(); s.sort_by(|a, b| a.partial_cmp(b).unwrap()); + println!("{k} experts x {} layers: {:.2} ms/token (median {:.2}), {:.1} MB/token, {:.1} GB/s, threads {}", + layers.len(), mean, s[s.len() / 2], total_bytes as f64 / toks as f64 / 1e6, + total_bytes as f64 / (mean * 1e-3 * toks as f64) / 1e9, rayon::current_num_threads()); + Ok(()) +} diff --git a/examples/pin_bench.rs b/examples/pin_bench.rs new file mode 100644 index 00000000..1a7b4ce9 --- /dev/null +++ b/examples/pin_bench.rs @@ -0,0 +1,92 @@ +//! Bounds a pinned host-RAM expert tier: 1 GB of a model file's bytes sent to the card in 4 MB pieces, (a) through +//! a 64 MB pinned ring (memcpy from the mapped file, then DMA, as `Gpu::htod`) or (b) by DMA straight from a pinned +//! copy, each alone and while 11 threads read 5 GB of the same file (a stand-in for the CPU experts of a prefill). +//! cargo run --release --example pin_bench -- [staged GB, default 5] +use cudarc::driver::{CudaContext, result}; +use std::collections::VecDeque; +use std::time::Instant; + +const GB: usize = 1 << 30; +const PIECE: usize = 4 << 20; +const RING: usize = 64 << 20; + +fn cpu_read(d: &[u8], threads: usize) -> u64 { + let n = d.len() / threads; + std::thread::scope(|s| { + let hs: Vec<_> = (0..threads).map(|t| s.spawn(move || { + let c = &d[t * n..(t + 1) * n]; + let (_, w, _) = unsafe { c.align_to::() }; + w.iter().fold(0u64, |a, &x| a ^ x) + })).collect(); + hs.into_iter().map(|h| h.join().unwrap()).fold(0, |a, x| a ^ x) + }) +} + +fn main() -> anyhow::Result<()> { + let a: Vec = std::env::args().collect(); + let f = std::fs::File::open(&a[1])?; + let staged: usize = a.get(2).and_then(|v| v.parse().ok()).unwrap_or(5); + let m = unsafe { memmap2::Mmap::map(&f)? }; + let src = &m[4 * GB..5 * GB]; + let cpu = &m[8 * GB..13 * GB]; + // Warm both regions. + std::hint::black_box(cpu_read(src, 11) ^ cpu_read(cpu, 11)); + + let ctx = CudaContext::new(0)?; + let st = ctx.default_stream(); + let dev = st.alloc_zeros::(GB)?; + let dptr = { use cudarc::driver::DevicePtr; let (p, _g) = dev.device_ptr(&st); p }; + let mut ring = unsafe { ctx.alloc_pinned::(RING)? }; + let rbase = ring.as_mut_ptr()? as usize; + let mut pin = unsafe { ctx.alloc_pinned::(GB)? }; + let pbase = pin.as_mut_ptr()? as usize; + unsafe { std::ptr::copy_nonoverlapping(src.as_ptr(), pbase as *mut u8, GB) }; + + let ring_pass = || -> anyhow::Result<()> { + let mut head = 0usize; + let mut busy: VecDeque<(usize, usize, cudarc::driver::CudaEvent)> = VecDeque::new(); + for (i, c) in src.chunks(PIECE).enumerate() { + if head + c.len() > RING { head = 0; } + let (x, y) = (head, head + c.len()); + while busy.iter().any(|&(s, e, _)| s < y && x < e) { busy.pop_front().unwrap().2.synchronize()?; } + unsafe { + let p = (rbase + x) as *mut u8; + std::ptr::copy_nonoverlapping(c.as_ptr(), p, c.len()); + result::memcpy_htod_async(dptr + (i * PIECE) as u64, std::slice::from_raw_parts(p, c.len()), st.cu_stream())?; + } + busy.push_back((x, y, st.record_event(None)?)); + head = y; + } + Ok(st.synchronize()?) + }; + let pin_pass = || -> anyhow::Result<()> { + for i in 0..GB / PIECE { + unsafe { result::memcpy_htod_async(dptr + (i * PIECE) as u64, std::slice::from_raw_parts((pbase + i * PIECE) as *const u8, PIECE), st.cu_stream())?; } + } + Ok(st.synchronize()?) + }; + let stage = |pinned: bool| -> anyhow::Result { + ctx.bind_to_thread()?; + let t = Instant::now(); + for _ in 0..staged { if pinned { pin_pass()? } else { ring_pass()? } } + Ok(t.elapsed().as_secs_f64() * 1e3) + }; + let cpu_alone = || { let t = Instant::now(); std::hint::black_box(cpu_read(cpu, 11)); t.elapsed().as_secs_f64() * 1e3 }; + stage(false)?; stage(true)?; + println!("staged {staged} GB in 4 MB pieces; CPU load reads 5 GB on 11 threads (times in ms)"); + for r in 0..3 { + let c0 = cpu_alone(); + let (ra, pa) = (stage(false)?, stage(true)?); + let both = |pinned: bool| -> anyhow::Result<(f64, f64)> { + std::thread::scope(|s| { + let h = s.spawn(|| stage(pinned)); + let c = cpu_alone(); + Ok((h.join().unwrap()?, c)) + }) + }; + let (rb, rc) = both(false)?; + let (pb, pc) = both(true)?; + println!("round {r}: alone cpu {c0:.0} ring {ra:.0} pinned {pa:.0} | together: ring {rb:.0} + cpu {rc:.0} ; pinned {pb:.0} + cpu {pc:.0}"); + } + Ok(()) +} diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 00000000..f5b14e7e --- /dev/null +++ b/install.ps1 @@ -0,0 +1,36 @@ +# Installs the newest RustingStrata release for Windows x86_64 into %LOCALAPPDATA%\Programs\RustingStrata, adds that +# folder to the user PATH and makes a Start menu shortcut that opens the chat page. No admin rights needed. +# irm https://raw.githubusercontent.com/RustingStudio/RustingStrata/main/install.ps1 | iex +# Later updates: rustingstrata update +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' # the progress bar makes Invoke-WebRequest many times slower on PowerShell 5 +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + +$dir = Join-Path $env:LOCALAPPDATA 'Programs\RustingStrata' +$exe = Join-Path $dir 'rustingstrata.exe' +$url = 'https://github.com/RustingStudio/RustingStrata/releases/latest/download/rustingstrata-windows-x86_64.exe' +New-Item -ItemType Directory -Force $dir | Out-Null +Write-Host "downloading $url" +Invoke-WebRequest -UseBasicParsing $url -OutFile "$exe.new" +try { Move-Item -Force "$exe.new" $exe } +catch { throw "could not replace $exe (is rustingstrata running? close it and run this again)" } +Write-Host "installed $(& $exe --version) to $exe" + +$path = [Environment]::GetEnvironmentVariable('Path', 'User') +if (($path -split ';') -notcontains $dir) { + [Environment]::SetEnvironmentVariable('Path', (($path, $dir) | Where-Object { $_ }) -join ';', 'User') + $env:Path += ";$dir" + Write-Host "added $dir to your PATH (new terminals see it)" +} + +$lnk = Join-Path ([Environment]::GetFolderPath('Programs')) 'RustingStrata.lnk' +$s = (New-Object -ComObject WScript.Shell).CreateShortcut($lnk) +$s.TargetPath = $exe +$s.WorkingDirectory = $dir +$s.Description = 'RustingStrata chat page' +$s.Save() +Write-Host "Start menu: RustingStrata (opens the chat page in the browser; it downloads models)" +Write-Host '' +Write-Host 'Start: rustingstrata serve --gpu --open (chat page in the browser)' +Write-Host ' or: rustingstrata interface (a few questions in the terminal)' +Write-Host 'Update: rustingstrata update' diff --git a/install.sh b/install.sh new file mode 100755 index 00000000..161c2516 --- /dev/null +++ b/install.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Installs the newest RustingStrata release for Linux x86_64 into ~/.local/bin (or $RUSTINGSTRATA_DIR): +# curl -fsSL https://raw.githubusercontent.com/RustingStudio/RustingStrata/main/install.sh | sh +# Later updates: rustingstrata update +set -eu + +[ "$(uname -s)" = Linux ] && [ "$(uname -m)" = x86_64 ] || { + echo "error: release binaries are for Linux and Windows x86_64; build from source on $(uname -s) $(uname -m):" >&2 + echo " https://github.com/RustingStudio/RustingStrata#install" >&2 + exit 1 +} +dir=${RUSTINGSTRATA_DIR:-$HOME/.local/bin} +url=https://github.com/RustingStudio/RustingStrata/releases/latest/download/rustingstrata-linux-x86_64 +mkdir -p "$dir" +echo "downloading $url" +if command -v curl >/dev/null; then + curl -fL --progress-bar -o "$dir/rustingstrata.new" "$url" +else + wget -q --show-progress -O "$dir/rustingstrata.new" "$url" +fi +chmod 755 "$dir/rustingstrata.new" +mv -f "$dir/rustingstrata.new" "$dir/rustingstrata" +echo "installed $("$dir/rustingstrata" --version) to $dir/rustingstrata" +case ":$PATH:" in + *":$dir:"*) ;; + *) echo "note: $dir is not in PATH; add it (for bash: echo 'export PATH=\"$dir:\$PATH\"' >> ~/.bashrc) or run $dir/rustingstrata" ;; +esac +echo +echo "Start: rustingstrata serve --gpu --open (chat page in the browser; it downloads models)" +echo " or: rustingstrata interface (a few questions in the terminal)" +echo "Update: rustingstrata update" diff --git a/src/backend.rs b/src/backend.rs index 12fad957..a501e759 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -58,17 +58,33 @@ unsafe impl Plain for u64 {} /// Device memory, recorded graphs and kernel ops. Host copies are synchronous; device work runs in queue order. /// Pointer arguments are device addresses; strides are in floats unless named otherwise. -/// The backend `kind` ("cuda" or "vulkan") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. +/// The backend `kind` ("cuda", "vulkan" or "hip") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. +/// Refuses a `--device` list with several indices on the HIP backend: `hip::Gpu` opens one device per process +/// (hipSetDevice runs once, in `Gpu::new`), so a split over two cards would run both layers on the first one. +pub fn check_devices(kind: Option<&str>, devices: &[usize]) -> anyhow::Result<()> { + if kind == Some("hip") && devices.len() > 1 { + anyhow::bail!("the hip backend runs one device: --device {} needs cuda or vulkan", devices.iter().map(|d| d.to_string()).collect::>().join(",")); + } + Ok(()) +} + +/// Opens every device of a `--device` list, after the check above. Callers open a list through this, not one device at a time. +pub fn open_all(kind: Option<&str>, devices: &[usize]) -> anyhow::Result>> { + check_devices(kind, devices)?; + devices.iter().map(|&d| open(kind, d)).collect() +} + pub fn open(kind: Option<&str>, device: usize) -> anyhow::Result> { match kind { Some("cuda") => Ok(Box::new(crate::cuda::Gpu::new(device)?)), Some("vulkan") => Ok(Box::new(crate::vulkan::Vk::new(device)?)), - Some(k) => anyhow::bail!("unknown backend {k:?} (cuda or vulkan)"), + Some("hip") => Ok(Box::new(crate::hip::Gpu::new(device)?)), + Some(k) => anyhow::bail!("unknown backend {k:?} (cuda, vulkan or hip)"), None => match crate::cuda::Gpu::new(device) { Ok(g) => Ok(Box::new(g)), Err(c) if format!("{c}") == "CUDA init" => { let v = crate::vulkan::Vk::new(device).map_err(|v| anyhow::anyhow!("no GPU backend loads: CUDA: {c:#}; Vulkan: {v:#}"))?; - eprintln!("CUDA unavailable ({c:#}), using Vulkan"); + crate::say!("CUDA unavailable ({c:#}), using Vulkan"); Ok(Box::new(v)) } Err(c) => Err(c), @@ -91,13 +107,59 @@ pub fn device_order(cuda: &[Option], vk: &[T]) -> Vec Vec<(usize, usize, [bool; 4])> { + let (mut segs, mut a, n) = (vec![], 0, pos.len()); + while a < n { + let inc: [bool; 4] = std::array::from_fn(|s| a + 1 < n && pos[a + 1][s] - pos[a][s] == 1); + let fits = |r: usize| (0..4).all(|s| pos[a + r][s] == pos[a][s] + if inc[s] { r as i32 } else { 0 }); + let len = (1..n - a).take_while(|&r| fits(r)).count() + 1; + segs.push((a, len, inc)); + a += len; + } + segs +} + +/// `rope_mrope` of many tokens (`per` heads each, `stride` floats apart) at `x`, run by `segs` (`mrope_segments`): +/// `pos` holds each segment's first positions as four [position, 0] pairs. A section that moves turns token by token, +/// one that stays turns the segment's tokens as one. +pub fn rope_mrope_segments(g: &dyn Backend, x: u64, stride: usize, per: usize, segs: &[(usize, usize, [bool; 4])], pos: u64, + n_rot: usize, base: f32, sections: [usize; 4]) -> anyhow::Result<()> { + for (k, &(a, len, inc)) in segs.iter().enumerate() { + let (half, mut lo, xa) = (n_rot / 2, 0, x + (4 * a * per * stride) as u64); + for (s, n) in sections.into_iter().enumerate() { + let hi = if s == 3 { half } else { (lo + n).min(half) }; + let p = pos + (32 * k + 8 * s) as u64; + if hi > lo { g.rope_pairs(xa, stride, len * per, if inc[s] { per } else { len * per }, n_rot, p, base, lo, hi)?; } + lo = hi; + } + } + Ok(()) +} /// The weight type `Backend::upload` stores a tensor of type `ty` as: F16 as F32 (no F16 kernels; F32 holds every F16 /// value exactly). Expert tensors are copied raw by `GpuModel::load_part`, not through `upload`. pub fn upload_type(ty: GgmlType) -> GgmlType { if ty == GgmlType::F16 { GgmlType::F32 } else { ty } } +pub trait PrefillRead { + fn rows(&self) -> anyhow::Result<&[f32]>; +} + +pub trait DeviceTimer { + fn stop(&mut self) -> anyhow::Result<()>; + fn elapsed(&self) -> anyhow::Result; +} + pub trait Backend: Send { - /// "cuda" or "vulkan". + /// "cuda", "vulkan" or "hip". fn name(&self) -> &'static str; /// The GPU's name as the driver reports it. fn device(&self) -> String; @@ -107,8 +169,18 @@ pub trait Backend: Send { } /// Zeroed buffer of `bytes` (at least 1). fn alloc(&self, bytes: usize) -> anyhow::Result; + /// Zeroed buffer of `bytes` in host RAM the device reads over PCIe (CUDA: mapped pinned memory). Backends + /// without it fall back to device memory. + fn alloc_host(&self, bytes: usize) -> anyhow::Result { self.alloc(bytes) } + /// Decode attention of `nt` tokens over a host-RAM cache (`alloc_host`) computed on the CPU, written to `out` + /// with the output gate `qg` applied. Ok(false): not supported here, use `attn_decode_q`. + fn attn_host(&self, _q: u64, _kc: u64, _vc: u64, _qg: u64, _out: u64, _step: u64, _nh: usize, _nkv: usize, _hd: usize, _scale: f32, _nt: usize) -> anyhow::Result { Ok(false) } fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()>; fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()>; + /// Queue a read of immutable prefill activations beside routing, when supported. + fn begin_prefill_read(&self, _src: &Buf, _offset: usize, _count: usize) -> anyhow::Result>> { + Ok(None) + } fn dtod(&self, src: &Buf, src_off: usize, dst: &Buf, dst_off: usize, bytes: usize) -> anyhow::Result<()>; /// Zero all of `dst`. fn memset(&self, dst: &Buf) -> anyhow::Result<()>; @@ -116,12 +188,30 @@ pub trait Backend: Send { fn mem_info(&self) -> anyhow::Result<(usize, usize)>; /// Wait for all queued device work. fn sync(&self) -> anyhow::Result<()>; + /// `sync`, and the memory of dropped buffers is free for other programs after it. + fn sync_freed(&self) -> anyhow::Result<()> { self.sync() } + /// Time work queued on the main stream. Record a stop after joining any dependent streams. + fn device_timer(&self) -> anyhow::Result>> { Ok(None) } + /// A second queue for host-to-device copies, so they run beside the kernels (a prompt chunk's expert staging). + /// `htod_side` queues a copy there; `side_mark`/`main_mark` record the point each queue has reached, and + /// `main_waits`/`side_waits` hold the other queue there. A backend with one queue copies in order with its + /// kernels, so these defaults are already correct. + fn htod_side(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { self.htod(src, dst, off) } + /// Page-lock `data` (host memory that outlives this backend, such as the mapped model file), so `htod` from it + /// is a DMA without a copy through a staging buffer. False when the backend does not do that. + fn pin_host(&self, _data: &[u8]) -> anyhow::Result { Ok(false) } + fn side_mark(&self) -> anyhow::Result { Ok(0) } + fn main_waits(&self, _side_mark: usize) -> anyhow::Result<()> { Ok(()) } + fn main_mark(&self) -> anyhow::Result { Ok(0) } + fn side_waits(&self, _main_mark: usize) -> anyhow::Result<()> { Ok(()) } /// Run the ops `f` queues as the graph recorded under `key`, recording it on first use. `f` runs only when /// recording, so its ops must read per-call values from device memory. fn graph(&self, key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()>; /// Free the graph recorded under `key`, if there is one. For a caller whose keys change as it runs (a graph holds /// device memory, and CUDA stops recording at a fixed number of them). fn graph_drop(&self, _key: u64) -> anyhow::Result<()> { Ok(()) } + /// Free every recorded graph, after buffers they use were replaced (a slot's KV cache grew). + fn graph_clear(&self) -> anyhow::Result<()> { Ok(()) } /// Queue the ops of `f`, none of which reads what another writes, with no ordering among them (Vulkan: no /// barriers between them); ops after the batch see all their results. fn batch(&self, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { f() } @@ -131,6 +221,13 @@ pub trait Backend: Send { fn beside(&self, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { f() } /// Ops after this see the copies of every `beside` so far. fn beside_join(&self) -> anyhow::Result<()> { Ok(()) } + /// The host copies of `f` on a stream of their own (CUDA), after the ops queued before and beside every op queued + /// after, until `copy_join`. Unlike `beside`, the kernels `batch` puts on its second stream do not wait for them. + fn copy_beside(&self, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { f() } + /// Like `copy_beside`, for transfers whose buffers are already safe to write beside outstanding work. + fn copy_independent(&self, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { f() } + /// Ops after this see the copies of the last `copy_beside` or `copy_independent`. + fn copy_join(&self) -> anyhow::Result<()> { Ok(()) } /// Submit the ops queued so far without waiting. Long prefills call it per layer: amdgpu resets the GPU when one /// submission runs over its timeout (10 s). fn kick(&self) -> anyhow::Result<()> { Ok(()) } @@ -150,6 +247,10 @@ pub trait Backend: Send { /// Zeroed host memory of `words` u32 that kernels read and write at the `Buf` address. The host pointer is /// valid while the `Buf` lives. fn host_mailbox(&self, words: usize) -> anyhow::Result<(Buf, *mut u32)>; + /// Host memory of `bytes` that `dtod`, `get` and `put` reach, for state the device copies in and out rarely (the + /// saved state of each `--parallel` slot), so that it takes RAM instead of VRAM. `None` where the backend has + /// none; the caller then allocates VRAM. + fn host_buf(&self, _bytes: usize) -> anyhow::Result> { Ok(None) } /// Refuse, before any weight is uploaded, if a pipeline these weight types (`GpuModel`'s upload types) need would /// exceed the device's shared-memory limit; `verbose` also lists each checked (kernel, specialization) pair. @@ -181,8 +282,11 @@ pub trait Backend: Send { Ok(GpuTensor::new(t.ty, t.rows, t.cols, b).with_scale(t.scale)) } - /// u16 words of a KV cache for `n` values: f16, or q8 with one f16 scale per 32 values. + /// u16 words of a KV cache row for `n` values in the K format (and, separately, the V format). + /// `kv_row_words` is the size of one K row plus one V row. fn kv_words(&self, n: usize) -> usize; + fn kv_words_v(&self, n: usize) -> usize { self.kv_words(n) } + fn kv_row_words(&self, n: usize) -> usize { self.kv_words(n) + self.kv_words_v(n) } /// GEMM over a tile list: for each tile, positions m0 .. m0 + cnt get y[m, 0..rows] = W_tile x[xrow[m]] (x row m /// when `xrow` is 0). `tiles` is a device array of [w, m0 | cnt << 32]. `act`: 0 stores, 1 computes /// y = silu(y) * result (SwiGLU with the gate already in y), 2 adds to y; `| SAME_X` as below. `n_x`: rows of x @@ -202,6 +306,9 @@ pub trait Backend: Send { /// `gemvn` that reads x pre-quantized by `quant_xq` at `xq` (0 = quantize x itself; float weights read x). fn gemvq(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()>; /// `gemvq` of `a` into `ya` and of `b` into `yb` on the same x (columns alike; output rows `a.rows` / `b.rows` apart). + /// `gemvq2` of one token and then `hc_silu(ya, sc, a.rows)`, in one launch where the backend can (false: nothing + /// was run, the caller runs the two). + fn gemvq2_silu(&self, _a: &GpuTensor, _b: &GpuTensor, _x: u64, _ya: u64, _yb: u64, _sc: f32) -> anyhow::Result { Ok(false) } fn gemvq2(&self, a: &GpuTensor, b: &GpuTensor, x: u64, x_stride: usize, xq: u64, ya: u64, yb: u64, nt: usize) -> anyhow::Result<()> { self.gemvq(a, x, x_stride, xq, ya, a.rows, nt)?; self.gemvq(b, x, x_stride, xq, yb, b.rows, nt) @@ -223,6 +330,12 @@ pub trait Backend: Send { /// bytes. `pair` = (w2, y2) also computes the same product for the matrices at byte offset w2 into the output at /// byte offset y2. `xq` (not 0): x pre-quantized by `quant_xq` (k / xg rows), read in place of x. fn moe_gemv(&self, ty: GgmlType, rows: usize, cols: usize, w: u64, stride: usize, ids: u64, k: usize, x: u64, x_stride: usize, xg: usize, y: u64, pair: Option<(i64, i64)>, xq: u64) -> anyhow::Result<()>; + /// `moe_gemv` in about `blocks` thread blocks (more rows a warp): for weights read over PCIe (the host share), + /// whose blocks wait on the link and would otherwise hold SMs the VRAM GEMVs beside them need. + fn moe_gemv_blocks(&self, ty: GgmlType, rows: usize, cols: usize, w: u64, stride: usize, ids: u64, k: usize, x: u64, x_stride: usize, xg: usize, y: u64, pair: Option<(i64, i64)>, xq: u64, blocks: usize) -> anyhow::Result<()> { + let _ = blocks; + self.moe_gemv(ty, rows, cols, w, stride, ids, k, x, x_stride, xg, y, pair, xq) + } /// out = the first `rows` rows of `w` as floats (a test helper). fn dequant(&self, w: &GpuTensor, rows: usize, out: u64) -> anyhow::Result<()>; /// Quantize `nt` rows of n floats (row t at x + 4 * t * x_stride bytes) for `gemvq` / `moe_gemv` into `out`: @@ -279,6 +392,12 @@ pub trait Backend: Send { fn add(&self, x: u64, y: u64, n: usize) -> anyhow::Result<()>; /// g = silu(g) * u. fn swiglu(&self, g: u64, u: u64, n: usize) -> anyhow::Result<()>; + /// g = silu(min(g, lim)) * clamp(u, -lim, lim). + fn swiglu_clamp(&self, _g: u64, _u: u64, _n: usize, _lim: f32) -> anyhow::Result<()> { anyhow::bail!("{}: swiglu_clamp not implemented", self.name()) } + /// DeepSeek-V4.1 query (or de-roped output) rows for `mla_attn`: x rows (hd, `xs` apart) times `scale` into y rows + /// (`ow` wide, `ys` apart), the last `n_rot` dims rotated in adjacent pairs by `cs` (cos, sin a pair; `inverse` + /// de-ropes); dims hd..ow are zero but `sink + row % nh`, which is 1 (`sink` 0: none). + fn ds_rope(&self, _x: u64, _xs: usize, _y: u64, _ys: usize, _rows: usize, _nh: usize, _hd: usize, _ow: usize, _n_rot: usize, _cs: u64, _inverse: bool, _scale: f32, _sink: usize) -> anyhow::Result<()> { anyhow::bail!("{}: ds_rope not implemented", self.name()) } /// Beta*tanh(gate/beta) * sigmoid(gate) * lb*tanh(up/lb) as in `situ`, directly quantized as `quant_xq` into `xq`. fn situ_q(&self, _y: u64, _n: usize, _rows: usize, _scale: u64, _beta: f32, _lb: f32, _xq: u64) -> anyhow::Result<()> { anyhow::bail!("{}: situ_q not implemented", self.name()) } /// `x[i] = cap * tanh(x[i] / cap)` for `i < n`. @@ -321,6 +440,10 @@ pub trait Backend: Send { fn ink_clip(&self, x: u64, scale: u64, w: usize, rows: usize, thr: f32, eps: f32, mul: f32, dst: u64) -> anyhow::Result<()> { self.ink_clip_n(x, scale, w, rows, 1, thr, eps, mul, dst, 0, 1, 0, 0.0, 1.0) } + /// Like `ink_clip`, for a V cache. + fn ink_clip_v(&self, x: u64, scale: u64, w: usize, rows: usize, thr: f32, eps: f32, mul: f32, dst: u64) -> anyhow::Result<()> { + self.ink_clip_n_v(x, scale, w, rows, 1, thr, eps, mul, dst, 0, 1, 0, 0.0, 1.0) + } /// Batched `ink_clip` over `nt` tokens of `rows` rows each (`x`: `[nt][rows][w]`, `scale`: `[rows][w]` or 0). /// When `dst != 0`, stores token `tok` at KV row `(dst_at0 + tok) % dst_ring`. When `log_alpha != 0.0`, /// scales `mul` by `1 + log_alpha * ln(max((pos0 + tok + 1) / log_floor, 1))`. @@ -332,6 +455,15 @@ pub trait Backend: Send { ) -> anyhow::Result<()> { anyhow::bail!("{}: Inkling 2 device decode not implemented", self.name()) } + /// Like `ink_clip_n`, for a V cache. Backends with one format for both halves treat it identically. + fn ink_clip_n_v( + &self, x: u64, scale: u64, w: usize, rows: usize, nt: usize, + thr: f32, eps: f32, mul: f32, + dst: u64, dst_at0: usize, dst_ring: usize, + pos0: usize, log_alpha: f32, log_floor: f32, + ) -> anyhow::Result<()> { + self.ink_clip_n(x, scale, w, rows, nt, thr, eps, mul, dst, dst_at0, dst_ring, pos0, log_alpha, log_floor) + } /// Graph-capturable `ink_clip_n`: reads `pos0` from device `i32` pointer `pos_ptr` (`dst_at0 = pos0 % dst_ring`). fn ink_clip_pos( &self, _x: u64, _scale: u64, _w: usize, _rows: usize, _nt: usize, @@ -341,6 +473,15 @@ pub trait Backend: Send { ) -> anyhow::Result<()> { anyhow::bail!("{}: Inkling 2 device decode not implemented", self.name()) } + /// Like `ink_clip_pos`, for a V cache. + fn ink_clip_pos_v( + &self, x: u64, scale: u64, w: usize, rows: usize, nt: usize, + thr: f32, eps: f32, mul: f32, + dst: u64, dst_ring: usize, + pos_ptr: u64, log_alpha: f32, log_floor: f32, + ) -> anyhow::Result<()> { + self.ink_clip_pos(x, scale, w, rows, nt, thr, eps, mul, dst, dst_ring, pos_ptr, log_alpha, log_floor) + } /// Attention of one token over `rows` key and value rows (`nkv * hd` wide in active KV format; the token's own row is `at`, the /// row before it `at - 1` modulo `rows`). Logit: q.k / sqrt(hd) + r.bias[distance] (distance < `ext`) - sink, a /// softmax with one more logit of 0, times sigmoid(gate). `hd` divides 128. `sc`: `nh * rows.div_ceil(64) * (hd + 2)` @@ -369,11 +510,47 @@ pub trait Backend: Send { /// Inkling 2 sigmoid top-k router for `rows` tokens: picks top `k` from `logits` (`[rows, n_expert]`) using /// `sigmoid(logit) + bias`, writes indices `[rows, k]` to `ids`, normalized unbiased probs * `exp_scale` (* `dn_sc[id]` /// if non-null) to `wts`, and optional `gu_sc[id]` (or `1.0`) to `gsc_out`. + /// Attention of `nt` queries, each over its own key list: row t of `idx` (`ns` u32 positions, the first `cnt[t]` + /// valid) names the rows of the f16 caches `kc`/`vc` (`[(pos * nkv + g) * hd]`) that query t attends. `q` and + /// `out` are f32 `[t][head][hd]`. Kolibri's sparse layers. + fn attn_sel(&self, _q: u64, _kc: u64, _vc: u64, _idx: u64, _cnt: u64, _out: u64, _nt: usize, _nh: usize, _nkv: usize, _hd: usize, _ns: usize, _scale: f32) -> anyhow::Result<()> { anyhow::bail!("{}: attention over key lists not implemented", self.name()) } + /// Lightning-indexer scores: out[t][j] = sum over heads h of max(q[t][h] . k[j], 0) * w[t][h]; q f32 + /// [nt][nh][hd], w f32 [nt][nh], k f32 [nk][hd]. The queries are the last nt of the nk positions; only the scores + /// up to each query's own position (j <= nk - nt + t) are defined. + fn idx_score(&self, _q: u64, _w: u64, _k: u64, _out: u64, _nt: usize, _nk: usize, _nh: usize, _hd: usize) -> anyhow::Result<()> { anyhow::bail!("{}: indexer scores not implemented", self.name()) } + /// Absorbed MLA attention: `nh` heads of pre-scaled f32 queries (hd) over f16 latent rows `kc` (hd, V their first + /// vd); query t sees `cnt[t]` keys, positions `idx[t * ns..]` or 0.. when `idx` is 0. `out`: f32 [t][head][vd]. + /// `qp` (not 0): the query dims from vd on are read there (rows `qps` apart) and `q` holds only the first vd + /// (rows vd apart); all dims are scaled by `qsc`. + fn mla_attn(&self, _q: u64, _kc: u64, _idx: u64, _cnt: u64, _out: u64, _nt: usize, _nh: usize, _hd: usize, _vd: usize, _ns: usize, _nmax: usize, _qp: u64, _qps: usize, _qsc: f32) -> anyhow::Result<()> { anyhow::bail!("{}: MLA attention not implemented", self.name()) } + /// Attention of a vision encoder: each of the `n` rows of `q` sees all `n` keys (no mask). `q`, `k`, `v` and `out` + /// are f32 `[n][nh][hd]`. + /// Layer norm with bias of `rows` rows of `n` (vision encoder): out = (x - mean) / sqrt(var + eps) * w + b. + fn vit_norm(&self, _x: u64, _out: u64, _w: u64, _b: u64, _rows: usize, _n: usize, _eps: f32) -> anyhow::Result<()> { anyhow::bail!("{}: vit_norm not implemented", self.name()) } + /// y[r][c] = act(y[r][c] + bias[c]), rows `stride` floats apart; act 0 none, 1 GELU (tanh), 2 GELU (erf), 3 quick + /// GELU, 4 SiLU. rows <= 65535. + fn vit_bias(&self, _y: u64, _stride: usize, _bias: u64, _rows: usize, _cols: usize, _act: i32) -> anyhow::Result<()> { anyhow::bail!("{}: vit_bias not implemented", self.name()) } + /// `ops::rope_vision` of Qwen3-VL tokens in 2x2 merge order (`m` the merge size, `mx` merged blocks a row), x + /// [n][nh][hd]. n <= 65535. + fn vit_rope(&self, _x: u64, _n: usize, _nh: usize, _hd: usize, _m: usize, _mx: usize, _base: f32) -> anyhow::Result<()> { anyhow::bail!("{}: vit_rope not implemented", self.name()) } + fn vit_attn(&self, _q: u64, _k: u64, _v: u64, _out: u64, _n: usize, _nh: usize, _hd: usize, _scale: f32) -> anyhow::Result<()> { anyhow::bail!("{}: vision attention not implemented", self.name()) } + /// Whether `ink_slots` and `ink_ffn_sum_mb` exist here. + fn ink_pool(&self) -> bool { false } + /// Inkling 2 decode with an expert pool: the lookup of `ink_route`'s experts in `table` (`slots`, `wh`), the + /// routing and on a miss `h` (nh floats, at word `h_off`) written to the CPU worker's mailbox `mb`. + fn ink_slots(&self, _ids: u64, _wts: u64, _table: u64, _slots: u64, _wh: u64, _h: u64, _mb: u64, _nh: usize, _h_off: usize, _step: u64, _k: usize) -> anyhow::Result<()> { + anyhow::bail!("{}: no Inkling 2 expert pool kernels", self.name()) + } + /// `ink_ffn_sum` of the pool's experts, plus the CPU worker's answer at word `y_off` of `mb` when one missed. + fn ink_ffn_sum_mb(&self, _acc: u64, _d: u64, _wh: u64, _k: usize, _n: usize, _mb: u64, _y_off: usize, _step: u64, _slots: u64) -> anyhow::Result<()> { + anyhow::bail!("{}: no Inkling 2 expert pool kernels", self.name()) + } fn ink_route(&self, _logits: u64, _bias: u64, _ids: u64, _wts: u64, _gu_sc: u64, _dn_sc: u64, _gsc_out: u64, _n_expert: usize, _k: usize, _exp_scale: f32, _rows: usize) -> anyhow::Result<()> { anyhow::bail!("{}: Inkling 2 router not implemented", self.name()) } - /// Gyro files (`config::Hadamard`): each of `rows` rows of n floats at `x` (times silu(x) * u first when `u` is - /// not 0) becomes H (s x) per `block` values, written to `out`, which may be `x`. `s`: the row's n signs as floats. - fn hadamard(&self, _x: u64, _u: u64, _s: u64, _out: u64, _n: usize, _block: usize, _rows: usize) -> anyhow::Result<()> { - anyhow::bail!("this file rotates its expert inputs (prism.hadamard), which the {} backend does not do", self.name()) + /// Rotated files (`config::Hadamard`): each of `rows` rows of n floats at `x` (times silu(x) * u first when `u` is + /// not 0) becomes H (s x) per `block` values, written to `out`. `s`: the row's n signs as floats. With `perm` (n u32 + /// indices, not 0) value c of a row is x[perm[c]] of that row and `out` must not be `x`; otherwise `out` may be `x`. + fn hadamard(&self, _x: u64, _u: u64, _s: u64, _perm: u64, _out: u64, _n: usize, _block: usize, _rows: usize) -> anyhow::Result<()> { + anyhow::bail!("this file rotates its matrix inputs (prism.hadamard), which the {} backend does not do", self.name()) } /// The SwiGLU of `rows` rows of n for a GEMV with quantized weights: either g = silu(g) * u (returns 0), or /// silu(g) * u quantized into `xq` as `quant_xq` does (returns xq, for the GEMV's xq; g is then left as is). @@ -389,6 +566,26 @@ pub trait Backend: Send { /// `interleave`: value head h reads key head h / (nv / nk), else h % nk. /// `dt_bias` not 0: beta and g are raw, and the kernel applies `ssm_gates` (with `dt_bias` and `a`) as it reads them. fn deltanet(&self, y: u64, s: u64, beta: u64, g: u64, dt_bias: u64, a: u64, o: u64, nk: usize, nv: usize, interleave: bool, dk: usize, dv: usize, scale: f32, t: usize, ych: usize, snap: u64, nsnap: usize) -> anyhow::Result<()>; + /// `conv_silu` (no norm) of rows r = 0..states.len(), `ch` floats apart in qkv and y, each with its conv state + /// states[r]; `tab` is a device table that holds states[r] at tab[2r], for a backend that does all rows in one launch. + fn conv_silu_rows(&self, qkv: u64, tab: u64, states: &[u64], w: u64, y: u64, ch: usize, kw: usize, eps: f32) -> anyhow::Result<()> { + let _ = tab; + for (r, &s) in states.iter().enumerate() { + let o = (4 * r * ch) as u64; + self.conv_silu(qkv + o, s, w, y + o, ch, kw, 0, eps)?; + } + Ok(()) + } + /// `deltanet` of one token a row (gates applied), row r at token r's place in y, beta, g and o, with its state + /// states[r]; `tab` holds states[r] at tab[2r + 1] (as in `conv_silu_rows`). + fn deltanet_rows(&self, y: u64, tab: u64, states: &[u64], beta: u64, g: u64, o: u64, nk: usize, nv: usize, interleave: bool, dk: usize, dv: usize, scale: f32, ych: usize) -> anyhow::Result<()> { + let _ = tab; + for (r, &s) in states.iter().enumerate() { + self.deltanet(y + (4 * r * ych) as u64, s, beta + (4 * r * nv) as u64, g + (4 * r * nv) as u64, 0, 0, o + (4 * r * nv * dv) as u64, + nk, nv, interleave, dk, dv, scale, 1, ych, 0, 0)?; + } + Ok(()) + } /// Stride (in tokens) between saved DeltaNet checkpoints in `snap` (`1` saves every token, `4` saves every 4th token). fn delta_snap_stride(&self) -> usize { 1 } fn deltanet_strided(&self, y: u64, s: u64, beta: u64, g: u64, dt_bias: u64, a: u64, o: u64, nk: usize, nv: usize, interleave: bool, dk: usize, dv: usize, scale: f32, t: usize, ych: usize, snap: u64, nsnap: usize, _snap_stride: usize) -> anyhow::Result<()> { @@ -435,6 +632,19 @@ pub trait Backend: Send { fn hc_silu(&self, _x: u64, _sc: f32, _n: usize) -> anyhow::Result<()> { anyhow::bail!("{}: hyper-connections not implemented", self.name()) } /// out[t] = sum over streams c of xn[t][c] * sigmoid(g[t][c]) / hc, for t < nt. fn hc_mix(&self, _xn: u64, _g: u64, _out: u64, _n: usize, _hc: usize, _nt: usize) -> anyhow::Result<()> { anyhow::bail!("{}: hyper-connections not implemented", self.name()) } + /// `hc_write` and then `rms_norm_streams` of the streams it wrote (into `xn`), in one launch where the backend can. + /// `cnt`: `nt` zeroed u32 the fused kernel uses (and leaves zero) to clear `out` after every stream read it. + fn hc_write_norm(&self, r: u64, out: u64, inj: u64, w: u64, xn: u64, n: usize, hc: usize, nt: usize, clear: bool, eps: f32, cnt: u64) -> anyhow::Result<()> { + let _ = cnt; + self.hc_write(r, out, inj, n, hc, nt, clear)?; + self.rms_norm_streams(r, w, xn, n, hc, nt, eps) + } + /// `hc_mix`, then `quant_xq` of its output into `xq` when `xq` is not 0, in one launch where the backend can. + fn hc_mix_q(&self, xn: u64, g: u64, out: u64, n: usize, hc: usize, nt: usize, xq: u64) -> anyhow::Result<()> { + self.hc_mix(xn, g, out, n, hc, nt)?; + if xq != 0 { self.quant_xq(out, n, n, nt, xq)?; } + Ok(()) + } /// Stream c of r[t] += out[t] * 2 sigmoid(inj[t][c] / hc), for t < nt; `clear`: zero out afterwards. fn hc_write(&self, _r: u64, _out: u64, _inj: u64, _n: usize, _hc: usize, _nt: usize, _clear: bool) -> anyhow::Result<()> { anyhow::bail!("{}: hyper-connections not implemented", self.name()) } /// PLE gate (see `Model::ple`): key and query rows of hc * n per token, value rows of n. @@ -479,13 +689,28 @@ pub trait Backend: Send { /// wts[j] on a hit, else 0), then the routing and (on a miss) `h` (rows of nh) written to the layer mailbox at /// `mb` and its request flag raised. `mb` = 0 skips every mailbox store where `moe_mailbox_optional` holds. `pid` /// (0 = none) receives the last token's ids, the prediction the next token's prefetch uses. - fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool) -> anyhow::Result<()>; + /// `hid`, `hmin`: the host share (see moe_route in kernels.cu); 0, 0 without one. Only CUDA takes it + /// (`host_share`); the others leave every missed expert to the CPU. + fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool, hid: u64, hmin: i32) -> anyhow::Result<()>; /// `mb` = 0: no CPU part. Otherwise adds the CPU result at word `y_off` of the mailbox once its done flag is `seq`. fn moe_combine(&self, x: u64, ye: u64, w: u64, k: usize, sh: u64, sg: u64, mb: u64, y_off: usize, step: u64, slots: u64, n: usize, t: usize) -> anyhow::Result<()>; /// Whether `moe_route`/`moe_combine` accept `mb = 0`, i.e. a fully resident expert cache costs the CPU worker /// nothing (no mailbox traffic at all). False where the kernels read the mailbox unconditionally (Vulkan). /// Most tokens of one `gemvn`/verify forward: 4 unless the backend's kernels take `cpu_worker::TMAX`. fn verify_rows(&self) -> usize { 4 } + /// Whether `moe_route` takes a host share and `host_register` can make host memory readable by kernels. + fn host_share(&self) -> bool { false } + + /// Whether this range is already registered for direct host-to-device DMA. + fn host_is_pinned(&self, _data: &[u8]) -> bool { false } + + /// Pins `len` bytes at host address `p` and maps them for kernels at the same address (UVA). + /// The backend releases the registration on drop. + fn host_register(&self, _p: usize, _len: usize) -> anyhow::Result { Ok(false) } + /// The device address at which kernels read `data` in place over the bus, when `pin_host` registered the pages + /// under it; None otherwise (CUDA, Vulkan, or bytes outside every registered range). + fn host_ptr(&self, _data: &[u8]) -> Option { None } + fn moe_mailbox_optional(&self) -> bool { false } /// Whether `moe_prefetch` does anything here (CUDA: yes; Vulkan: no kernel, the knob is ignored). @@ -529,7 +754,15 @@ impl<'a> dyn Backend + 'a { #[cfg(test)] mod tests { - use super::device_order; + use super::{check_devices, device_order}; + + #[test] + fn hip_refuses_a_device_split_and_nothing_else() { + assert!(check_devices(Some("hip"), &[0, 1]).is_err()); + assert!(check_devices(Some("hip"), &[0]).is_ok()); + assert!(check_devices(Some("cuda"), &[0, 1]).is_ok()); + assert!(check_devices(None, &[0, 1]).is_ok()); + } /// Identifiers are letters here. Two cards of one model have one name and two identifiers, so names play no part. #[test] diff --git a/src/calibrate.rs b/src/calibrate.rs new file mode 100644 index 00000000..1da857d3 --- /dev/null +++ b/src/calibrate.rs @@ -0,0 +1,530 @@ +//! Universal calibration search. +//! +//! This module is the model- and backend-agnostic half of `rustingstrata calibrate`. It knows nothing about GGUFs, +//! GPUs or tokenizers: the caller supplies a `measure` closure that, given a set of knobs and a workload matrix, +//! returns throughput numbers. That makes the same search usable with every engine the binary supports. +//! +//! The search is deliberately small-budget and noise-aware: +//! * a deterministic low-discrepancy coarse sweep over the joint knob space, +//! * multi-start coordinate descent from the best coarse points (escapes the local minima of a single greedy walk), +//! * a final joint polish, +//! * a hard sample budget with early stopping, +//! * a baseline measured with the settings a user gets today, not the first point of the search space. + +use anyhow::Result; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::time::Instant; + +/// A point in the knob space. Values are numeric: integer knobs are rounded by the caller when they are applied. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Knobs(pub BTreeMap); + +impl Knobs { + pub fn get(&self, name: &str) -> Option { self.0.get(name).copied() } + pub fn i(&self, name: &str) -> Option { self.get(name).map(|v| v.round().max(0.0) as usize) } + pub fn set(&mut self, name: &str, value: f64) { self.0.insert(name.to_string(), value); } + /// A short, stable label used in progress lines and in the JSON report. + pub fn label(&self) -> String { + self.0.iter().map(|(k, v)| format!("{k}={}", if v.fract() == 0.0 { format!("{v:.0}") } else { format!("{v:.2}") })) + .collect::>().join(" ") + } +} + +/// One discrete knob. `reload` marks knobs whose change needs a fresh model load; the measurement closure can use it +/// to avoid reloading on cheap changes. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct KnobSpec { + pub name: String, + pub values: Vec, + #[serde(default)] + pub reload: bool, +} + +impl KnobSpec { + pub fn new(name: &str, values: impl IntoIterator, reload: bool) -> Self { + Self { name: name.into(), values: values.into_iter().collect(), reload } + } +} + +/// A prompt/decode pair to benchmark. `task` is a label the measurement closure interprets ("prose", "coding", +/// "user:PATH"); it is passed through so the report records which corpus produced the numbers. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Workload { + pub pp: usize, + pub tg: usize, + pub task: String, +} + +impl Workload { + pub fn new(pp: usize, tg: usize, task: &str) -> Self { Self { pp, tg, task: task.into() } } + pub fn label(&self) -> String { format!("{}pp/{}tg/{}", self.pp, self.tg, self.task) } +} + +/// Throughput of one workload measurement. Higher is better. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Measurement { + pub prefill_tok_s: f64, + pub decode_tok_s: f64, + #[serde(default)] + pub drafts_offered: usize, + #[serde(default)] + pub drafts_accepted: usize, +} + +impl Measurement { + pub fn valid(&self) -> bool { + [self.prefill_tok_s, self.decode_tok_s].iter().all(|v| v.is_finite() && *v > 0.0) + } +} + +/// Relative importance of prefill throughput and decode throughput. Each is divided by its own baseline, so the +/// units cancel. A weighted geometric mean (rather than an arithmetic one) cannot hide a regression in one signal +/// behind a large gain in the other. Time to first token is deliberately not a separate signal: for greedy decoding +/// it is the prefill time, so giving it a weight would just reweight prefill. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Objective { + pub prefill: f64, + pub decode: f64, +} + +impl Objective { + /// Balanced default: prompt handling and reply generation count equally. + pub fn balanced() -> Self { Self { prefill: 0.5, decode: 0.5 } } + fn normalized(&self) -> Self { + let sum = self.prefill + self.decode; + if sum <= 0.0 || !sum.is_finite() { return Self::balanced(); } + Self { prefill: self.prefill / sum, decode: self.decode / sum } + } + /// Score of one measurement relative to its baseline. + pub fn score(&self, m: &Measurement, base: &Measurement) -> f64 { + let clamp = |v: f64| v.clamp(1e-3, 1e3); + let pf = clamp(m.prefill_tok_s / base.prefill_tok_s); + let dec = clamp(m.decode_tok_s / base.decode_tok_s); + let o = self.normalized(); + pf.powf(o.prefill) * dec.powf(o.decode) + } +} + +/// Score of a full workload matrix: geometric mean over workloads, so each prompt depth counts equally. Every depth +/// is compared with its own baseline, so the ratio means what it says at every prompt length. +pub fn aggregate_score(ms: &[Measurement], bases: &[Measurement], obj: &Objective) -> f64 { + let fallback = bases.first().cloned().unwrap_or_default(); + let mut acc = 0.0; + let mut n = 0; + for (i, m) in ms.iter().enumerate() { + if !m.valid() { continue; } + let base = bases.get(i).unwrap_or(&fallback); + acc += obj.score(m, base).ln(); + n += 1; + } + if n == 0 { 0.0 } else { (acc / n as f64).exp() } +} + +/// One evaluated candidate. `error` is set (and `score` is zero) when a measurement failed, e.g. an OOM at a large +/// chunk: failed points stay in the trace so the report explains why a region of the space was skipped. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Trial { + pub knobs: Knobs, + pub measurements: Vec, + pub score: f64, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + pub elapsed_ms: u128, + /// How many workloads were measured. Coarse trials use the first workload only; they must not be compared with + /// full-matrix scores, nor can they win the search. + pub workloads: usize, +} + +/// Budget and stopping settings. +#[derive(Clone, Debug)] +pub struct SearchConfig { + /// Hard cap on measurement closure calls. Reaching it always stops the search. + pub samples: usize, + /// Number of coarse low-discrepancy points (capped at a third of the budget). + pub coarse: usize, + /// Multi-start count for coordinate descent. + pub starts: usize, + /// Stop after this many full refinement rounds without an improvement. + pub patience: usize, + /// Deterministic seed (also used for the low-discrepancy sequence). + pub seed: u64, + /// Wall-clock end: no sample starts after it, and the best so far is the result (stop reason "time"). + pub deadline: Option, +} + +impl Default for SearchConfig { + fn default() -> Self { Self { samples: 24, coarse: 8, starts: 3, patience: 2, seed: 1, deadline: None } } +} + +/// Result of a search, including the full trace for the JSON report. +#[derive(Debug, Serialize, Deserialize)] +pub struct SearchResult { + pub best: Trial, + pub baseline: Vec, + pub trials: Vec, + pub samples_used: usize, + pub stop_reason: String, + pub elapsed_ms: u128, + pub seed: u64, +} + +/// Radical inverse in a prime base: a deterministic, well-spread point set in `[0,1)^dims`. No dependencies, same +/// points on every run for a given seed, so a calibration can be reproduced from its recorded seed. +pub fn low_discrepancy(index: usize, dims: usize, seed: u64) -> Vec { + const PRIMES: [u64; 12] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]; + (0..dims).map(|d| { + let base = PRIMES.get(d).copied().unwrap_or(37); + let mut n = index as u64 + seed.wrapping_mul(base); + let mut f = 1.0 / base as f64; + let mut out = 0.0; + while n > 0 { + out += f * (n % base) as f64; + n /= base; + f /= base as f64; + } + out + }).collect() +} + +/// Map a unit point to knob values by nearest candidate (a small jitter-free quantization of the unit cube). +fn quantize(space: &[KnobSpec], unit: &[f64]) -> Knobs { + let mut k = Knobs::default(); + for (spec, u) in space.iter().zip(unit) { + let i = (u.clamp(0.0, 0.999999) * spec.values.len() as f64) as usize; + k.set(&spec.name, spec.values[i.min(spec.values.len() - 1)]); + } + k +} + +fn default_knobs(space: &[KnobSpec]) -> Knobs { + let mut k = Knobs::default(); + for s in space { if let Some(v) = s.values.first() { k.set(&s.name, *v); } } + k +} + +/// The gain over the baseline a candidate needs to be written (2%, about the spread of one bench run). +pub const MIN_GAIN: f64 = 1.02; + +/// Run the search. `measure` is called once per sample with the workload matrix; it should apply the knobs, take its +/// own repetitions and return one measurement per workload. `baseline` has one measurement per workload, taken with +/// `baseline_knobs` (the settings a user gets without a calibration file). The baseline competes in the search: a +/// candidate slower than today's defaults must not be written as the winner. +pub fn search(space: &[KnobSpec], workloads: &[Workload], cfg: &SearchConfig, obj: &Objective, + baseline_knobs: &Knobs, baseline: Vec, mut measure: F) -> Result +where F: FnMut(&Knobs, &[Workload]) -> Result> +{ + anyhow::ensure!(!space.is_empty() && !workloads.is_empty(), "calibration needs a knob space and at least one workload"); + let fallback = baseline.iter().find(|m| m.valid()).cloned().unwrap_or_else(|| Measurement { prefill_tok_s: 1.0, decode_tok_s: 1.0, ..Default::default() }); + let mut baselines = baseline.clone(); + while baselines.len() < workloads.len() { baselines.push(fallback.clone()); } + let start = Instant::now(); + let mut trials: Vec = Vec::new(); + // The baseline is a real trial, measured outside the sample budget. Its ratios against itself are 1.0, so the + // search can never pick a slower point unless the baseline measurement itself failed. It enters at MIN_GAIN: a + // candidate must beat today's defaults by more than run-to-run noise, or noise picks the winner. + trials.push(Trial { + knobs: baseline_knobs.clone(), + measurements: baseline.clone(), + score: aggregate_score(&baseline, &baselines, obj) * MIN_GAIN, + error: if baseline.iter().any(|m| m.valid()) { None } else { Some("baseline measurement failed".to_string()) }, + elapsed_ms: 0, + workloads: workloads.len(), + }); + let mut used = 0usize; + let late = || cfg.deadline.is_some_and(|d| Instant::now() >= d); + let full = |used: usize| used >= cfg.samples || late(); + let mut n = 0usize; + + let mut evaluate = |knobs: &Knobs, subset: &[Workload]| -> Result { + crate::term::calibration_sample_start(&format!("sample {}/{}", n + 1, cfg.samples)); + let t0 = Instant::now(); + let (measurements, error) = match measure(knobs, subset) { + Ok(ms) if ms.iter().any(|m| m.valid()) => (ms, None), + Ok(ms) => (ms, Some("no valid measurement (all rates were zero or non-finite)".to_string())), + Err(e) => (vec![], Some(format!("{e:#}"))), + }; + let score = if error.is_some() { 0.0 } else { aggregate_score(&measurements, &baselines, obj) }; + n += 1; + let valid: Vec<_> = measurements.iter().filter(|m| m.valid()).collect(); + let (prefill_rate, decode_rate, draft_rates) = if valid.is_empty() { (None, None, None) } else { + let count = valid.len() as f64; + let (prefill, decode, offered, accepted) = valid.iter().fold((0.0, 0.0, 0usize, 0usize), |a, m| { + (a.0 + m.prefill_tok_s, a.1 + m.decode_tok_s, a.2 + m.drafts_offered, a.3 + m.drafts_accepted) + }); + (Some(prefill / count), Some(decode / count), (offered > 0).then_some((offered, accepted))) + }; + let detail = prefill_rate.zip(decode_rate).map_or_else(String::new, |(p, d)| { + let draft = draft_rates.map_or_else(String::new, |(offered, accepted)| format!(" · draft {:.1}%", accepted as f64 * 100.0 / offered as f64)); + format!(" · prefill {p:.0} tok/s · decode {d:.1} tok/s{draft}") + }); + crate::term::calibration_sample_done(&format!("sample {n}/{}", cfg.samples), prefill_rate, decode_rate, draft_rates); + let what = error.as_deref().map_or_else(|| format!("score {score:.3}"), |e| format!("failed: {}", e.lines().next().unwrap_or(""))); + crate::say!("sample {n}/{}: {} on {} workload(s), {what}{detail} ({:.0} s)", cfg.samples, knobs.label(), subset.len(), t0.elapsed().as_secs_f64()); + Ok(Trial { knobs: knobs.clone(), measurements, score, error, elapsed_ms: t0.elapsed().as_millis(), workloads: subset.len() }) + }; + + // One bench child per distinct (knob point, workload set): repeats cost a full model load and consume budget + // without adding information. `seen` is shared by every stage, including all starts. + let mut seen: std::collections::HashSet<(String, usize)> = std::collections::HashSet::new(); + // The baseline was measured outside the budget: never spend a sample repeating it. + seen.insert((baseline_knobs.label(), workloads.len())); + let mut eval_unique = |knobs: &Knobs, subset: &[Workload]| -> Result> { + if !seen.insert((knobs.label(), subset.len())) { return Ok(None); } + evaluate(knobs, subset).map(Some) + }; + + // Stage A: coarse joint sweep, on the cheapest (first) workload. These scores are only used to pick starting + // points for Stage B; they are never compared with full-matrix scores or allowed to win. + let coarse = cfg.coarse.min(cfg.samples / 3).min(16).max(1); + for i in 0..coarse { + if full(used) { break } + let k = quantize(space, &low_discrepancy(i, space.len(), cfg.seed)); + if let Some(trial) = eval_unique(&k, &workloads[..1])? { + used += 1; + trials.push(trial); + } + if full(used) { break } + } + + // Stage B: multi-start coordinate descent on the full matrix. + let mut seeds: Vec<(Knobs, f64)> = trials.iter().filter(|t| t.error.is_none()) + .map(|t| (t.knobs.clone(), t.score)).collect(); + seeds.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); + seeds.dedup_by(|a, b| a.0 == b.0); + seeds.truncate(cfg.starts.max(1)); + if seeds.is_empty() { seeds.push((default_knobs(space), 0.0)); } + + let mut converged_all = true; + for (cur, _seed_score) in seeds.into_iter() { + let mut stop_reason = "budget".to_string(); + // Re-measure the seed on the full matrix before comparing it with full-matrix candidates. Otherwise a point + // that only wins on the shortest prompt would start with an inflated score and reject real improvements. + let mut cur_trial = if full(used) { break } else if let Some(t) = eval_unique(&cur, workloads)? { + used += 1; + trials.push(t.clone()); + t + } else { + trials.iter().find(|t| t.workloads == workloads.len() && t.knobs == cur).cloned() + .unwrap_or_else(|| Trial { knobs: cur.clone(), measurements: vec![], score: 0.0, error: None, + elapsed_ms: 0, workloads: workloads.len() }) + }; + let mut stale = 0; + for _ in 0..cfg.patience.max(1) + 2 { + let mut improved = false; + for s in space { + let original = cur_trial.knobs.get(&s.name); + let mut local_best = cur_trial.clone(); + for &v in &s.values { + if Some(v) == original || full(used) { continue } + let mut candidate = cur_trial.knobs.clone(); + candidate.set(&s.name, v); + if let Some(t) = eval_unique(&candidate, workloads)? { + used += 1; + trials.push(t.clone()); + if t.error.is_none() && t.score > local_best.score { local_best = t; } + } + if full(used) { break; } + } + match local_best.error.clone() { + None if local_best.score > cur_trial.score => { cur_trial = local_best; improved = true; } + _ => {} + } + if full(used) { break; } + } + if !improved { stale += 1; if stale >= cfg.patience.max(1) { stop_reason = "converged".into(); } } + else { stale = 0; } + if full(used) || stop_reason == "converged" { break; } + } + if full(used) { converged_all = false; break; } + if stop_reason != "converged" { converged_all = false; } + } + + // Stage C: one coordinate pass from the overall winner over the cheap knobs. + let best_so_far = trials.iter().filter(|t| t.error.is_none() && t.workloads == workloads.len()) + .max_by(|a, b| a.score.partial_cmp(&b.score).unwrap_or(std::cmp::Ordering::Equal)).cloned(); + let mut best = best_so_far.unwrap_or_else(|| Trial { + knobs: default_knobs(space), measurements: vec![], score: 0.0, + error: Some("no successful full-matrix measurement".into()), elapsed_ms: 0, workloads: 0, + }); + if !full(used) { + for s in space.iter().filter(|s| !s.reload) { + let original = best.knobs.get(&s.name); + for &v in &s.values { + if Some(v) == original || full(used) { continue } + let mut candidate = best.knobs.clone(); + candidate.set(&s.name, v); + if let Some(t) = eval_unique(&candidate, workloads)? { + used += 1; + trials.push(t.clone()); + if t.error.is_none() && t.score > best.score { best = t; } + } + } + } + } + let stop_reason = if late() { "time" } else if full(used) || !converged_all { "budget" } else { "converged" }.to_string(); + Ok(SearchResult { + best, baseline, trials, samples_used: used, stop_reason, + elapsed_ms: start.elapsed().as_millis(), seed: cfg.seed, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn space() -> Vec { + vec![KnobSpec::new("chunk", [256.0, 1024.0, 4096.0], false), + KnobSpec::new("mtp", [0.0, 1.0, 2.0], false)] + } + fn workloads() -> Vec { vec![Workload::new(128, 16, "prose"), Workload::new(512, 16, "prose")] } + fn base() -> Measurement { Measurement { prefill_tok_s: 100.0, decode_tok_s: 20.0, ..Default::default() } } + fn baseline_knobs() -> Knobs { let mut k = Knobs::default(); k.set("chunk", 256.0); k.set("mtp", 0.0); k } + + #[test] + fn objective_is_a_geometric_mean_of_two_signals() { + let o = Objective::balanced(); + assert!((o.score(&base(), &base()) - 1.0).abs() < 1e-9); + let better = Measurement { prefill_tok_s: 200.0, decode_tok_s: 10.0, ..Default::default() }; + assert!((o.score(&better, &base()) - 1.0).abs() < 1e-9, "2x prefill and 0.5x decode cancel"); + let gain = Measurement { prefill_tok_s: 200.0, decode_tok_s: 40.0, ..Default::default() }; + assert!((o.score(&gain, &base()) - 2.0).abs() < 1e-9); + let mixed = Measurement { prefill_tok_s: 1000.0, decode_tok_s: 1.0, ..Default::default() }; + assert!(o.score(&mixed, &base()) < 1.0, "a big regression must not be hidden by one gain"); + } + + #[test] + fn low_discrepancy_is_deterministic_and_spread() { + assert_eq!(low_discrepancy(7, 3, 42), low_discrepancy(7, 3, 42)); + let pts: Vec<_> = (0..16).map(|i| low_discrepancy(i, 2, 1)).collect(); + let xs: std::collections::BTreeSet<_> = pts.iter().map(|p| format!("{:.2}", p[0])).collect(); + assert!(xs.len() >= 8, "coarse points should cover the first dimension: {xs:?}"); + } + + #[test] + fn search_respects_the_sample_budget_and_finds_the_best_region() { + let mut calls = 0; + let cfg = SearchConfig { samples: 12, coarse: 4, starts: 2, patience: 1, seed: 5, deadline: None }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { + calls += 1; + let boost = if k.i("chunk") == Some(1024) { 2.0 } else { 1.0 } * if k.i("mtp") == Some(1) { 1.5 } else { 1.0 }; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) + }).unwrap(); + assert!(calls <= cfg.samples, "used {calls} above budget {}", cfg.samples); + assert_eq!(r.samples_used, calls); + assert_eq!(r.best.knobs.i("chunk"), Some(1024)); + assert_eq!(r.best.knobs.i("mtp"), Some(1)); + assert!(r.best.score > 1.0); + } + + #[test] + fn every_start_gets_a_full_descent_not_one_round() { + // A flat landscape never converges: each of the three starts must run several full rounds. With the old + // stop_reason leak, starts 2 and 3 got a single round after start 1 converged. + // A bigger space gives each start real room to move: scores improve with both knob values, so no start + // converges immediately. (Measured points are memoized, so call-count-based landscapes are not useful.) + let big: Vec = vec![ + KnobSpec::new("chunk", (1..=8).map(|i| i as f64 * 100.0), false), + KnobSpec::new("mtp", (0..8).map(|i| i as f64), false), + ]; + let cfg = SearchConfig { samples: 40, coarse: 3, starts: 3, patience: 2, seed: 9, deadline: None }; + let r = search(&big, &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { + let boost = 1.0 + k.i("chunk").unwrap() as f64 / 1000.0 + k.i("mtp").unwrap() as f64 / 100.0; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) + }).unwrap(); + assert!(r.samples_used > 25, "each start should get several rounds, not one: {}", r.samples_used); + } + + #[test] + fn short_prompt_only_gains_cannot_win_the_search() { + let cfg = SearchConfig { samples: 14, coarse: 6, starts: 3, patience: 1, seed: 3, deadline: None }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, subset| { + let mtp = k.i("mtp").unwrap(); + Ok(subset.iter().map(|w| { + let boost = if mtp == 1 { if w.pp == 128 { 2.0 } else { 0.25 } } else { 1.0 }; + Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() } + }).collect()) + }).unwrap(); + assert_ne!(r.best.knobs.i("mtp"), Some(1), "the short-prompt-only gain must not win"); + assert_eq!(r.best.measurements.len(), 2); + } + + #[test] + fn failed_measurements_are_recorded_and_never_win() { + let cfg = SearchConfig { samples: 8, coarse: 4, starts: 1, patience: 1, seed: 2, deadline: None }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { + if k.i("mtp") == Some(1) { anyhow::bail!("out of memory") } + Ok(vec![base(), base()]) + }).unwrap(); + assert_ne!(r.best.knobs.i("mtp"), Some(1)); + assert!(r.trials.iter().any(|t| t.error.as_deref().is_some_and(|e| e.contains("out of memory")))); + } + + #[test] + fn an_empty_baseline_still_allows_the_search_to_run() { + let cfg = SearchConfig { samples: 10, coarse: 3, starts: 1, patience: 1, seed: 6, deadline: None }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![], |_, _| { + Ok(vec![Measurement { prefill_tok_s: 100.0, decode_tok_s: 20.0, ..Default::default() }]) + }).unwrap(); + assert!(r.best.error.is_none()); + assert!(r.samples_used > 0); + } + + #[test] + fn the_same_knob_point_is_never_measured_twice() { + let cfg = SearchConfig { samples: 60, coarse: 6, starts: 3, patience: 2, seed: 7, deadline: None }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { + let boost = 1.0 + k.i("chunk").unwrap() as f64 / 10000.0 + k.i("mtp").unwrap() as f64 / 10.0; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) + }).unwrap(); + let keys: std::collections::HashSet<_> = r.trials.iter() + .map(|t| (t.knobs.label(), t.workloads)).collect(); + assert_eq!(keys.len(), r.trials.len(), "a repeated sample never adds information"); + assert!(r.trials.len() > cfg.coarse, "the search should still do real refinement"); + } + + #[test] + fn every_start_converging_is_recorded_as_converged() { + // A flat landscape: no move ever improves, so all starts stop on patience before the budget is used. + let cfg = SearchConfig { samples: 60, coarse: 3, starts: 2, patience: 2, seed: 4, deadline: None }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |_, _| { + Ok(vec![base(), base()]) + }).unwrap(); + assert!(r.samples_used < cfg.samples, "should stop early: {}", r.samples_used); + assert_eq!(r.stop_reason, "converged"); + } + + #[test] + fn deadline_stops_the_search() { + let space = vec![KnobSpec::new("chunk", [256.0, 512.0, 1024.0], true)]; + let ws = vec![Workload::new(128, 16, "prose")]; + let mut calls = 0; + let cfg = SearchConfig { samples: 20, deadline: Some(Instant::now()), ..Default::default() }; + let r = search(&space, &ws, &cfg, &Objective::balanced(), &Knobs::default(), vec![], |_, _| { + calls += 1; + Ok(vec![Measurement { prefill_tok_s: 1.0, decode_tok_s: 1.0, ..Default::default() }]) + }).unwrap(); + assert_eq!((calls, r.samples_used, r.stop_reason.as_str()), (0, 0, "time")); + } + + #[test] + fn a_slower_candidate_can_never_beat_the_baseline() { + let cfg = SearchConfig { samples: 20, coarse: 6, starts: 3, patience: 2, seed: 11, deadline: None }; + let base_knobs = baseline_knobs(); + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &base_knobs, + vec![base(), base()], |_, _| { + Ok(vec![Measurement { prefill_tok_s: 50.0, decode_tok_s: 10.0, ..Default::default() }]) + }).unwrap(); + assert_eq!(r.best.knobs, base_knobs, "a slower point must not be written"); + assert!((r.best.score - MIN_GAIN).abs() < 1e-9, "the baseline wins at score MIN_GAIN"); + assert!(r.trials.iter().any(|t| t.knobs == base_knobs && t.score == MIN_GAIN)); + } + + #[test] + fn aggregate_score_ignores_invalid_workloads() { + let bad = Measurement::default(); + let bases = [base(), base()]; + assert!((aggregate_score(&[base(), bad.clone()], &bases, &Objective::balanced()) - 1.0).abs() < 1e-9); + assert_eq!(aggregate_score(&[bad], &bases, &Objective::balanced()), 0.0); + } +} diff --git a/src/chat.rs b/src/chat.rs index fef7f166..fb03768a 100644 --- a/src/chat.rs +++ b/src/chat.rs @@ -54,7 +54,7 @@ impl Json { } /// A tool-call parameter value as the Qwen3.6 template prints it: lists and objects as JSON, other values /// through Jinja's `string` filter (Python spelling for booleans and null). - fn param(&self) -> String { + pub(crate) fn param(&self) -> String { match self { Json::Str(s) => s.clone(), Json::Bool(b) => (if *b { "True" } else { "False" }).into(), @@ -125,9 +125,10 @@ impl Msg { pub fn new(role: &str, content: &str) -> Msg { Msg { role: role.into(), content: content.into(), reasoning: None, calls: vec![], images: vec![] } } /// Parses one OpenAI message. Roles are limited to the ones the templates know, because the role goes into the - /// prompt verbatim. + /// prompt verbatim. OpenAI's `developer` role means `system` and is read as one (#136). pub fn from_json(m: &Json) -> anyhow::Result { let role = m.get("role").as_str().context("message without role")?; + let role = if role == "developer" { "system" } else { role }; if !["system", "user", "assistant", "tool"].contains(&role) { bail!("unknown role {role:?}"); } let mut images = vec![]; let content = match m.get("content") { @@ -187,7 +188,7 @@ impl Msg { }).collect::>()?, _ => bail!("tool_calls must be an array on an assistant message"), }; - Ok(Msg { role: role.into(), content, reasoning: m.get("reasoning_content").as_str().map(Into::into), calls, images }) + Ok(Msg { role: role.into(), content, reasoning: m.get("reasoning_content").as_str().or_else(|| m.get("reasoning").as_str()).map(Into::into), calls, images }) } } @@ -210,14 +211,21 @@ pub enum Template { /// Qwen3.6: `` calls, contents trimmed, an empty think block when thinking is off. Xml, /// Qwen3 2507 and Qwen3-Next: `{"name": .., "arguments": ..}` calls. `reasoning` (2507) puts the turns after the - /// last user query in a think block. - Json { reasoning: bool }, + /// last user query in a think block; `hybrid` (Qwen3, which has `enable_thinking`) closes an empty think block + /// when thinking is off. + Json { reasoning: bool, hybrid: bool }, /// DeepSeek-V4.1: `<|User|>`/`<|Assistant|>` turns, think mode with a reasoning-effort line. Plain chat only; // ponytail: no DSML tool calls, add when serving DeepSeek tools matters. Ds, /// Recursive Flint: `<|system|>`/`<|user|>`/`<|assistant|>`/`<|observation|>` turns and compact /// `name....` calls. Flint, + /// Qwen4: a system turn with `Reasoning effort is set to xhigh|high|low|off.` (and the tools) before every + /// conversation, an always-present `..` in each assistant turn, `` calls as in + /// Qwen3.6. `effort` is a request's `reasoning_effort` (see `with_effort`); without one, think on renders high. + // ponytail: tool results print in message order; the template re-sorts them by tool_call_id (Msg keeps no ids). + // Clients send results in call order, so add ids to Msg only if one does not. + Qwen4 { effort: Option<&'static str> }, } const XML_RULES: &str = "\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n"; @@ -298,6 +306,42 @@ fn render_ds(msgs: &[Msg], tools: &[Json], think: bool, preserve: bool, generate s } +/// Qwen4's chat template (the GGUF's `tokenizer.chat_template`): see `Template::Qwen4`. +fn render_qwen4(msgs: &[Msg], tools: &[Json], effort: Option<&str>, think: bool, preserve: bool, generate: bool) -> String { + let effort = effort.unwrap_or(if think { "high" } else { "off" }); + let think = effort != "off"; + let mut s = format!("<|im_start|>system\nReasoning effort is set to {effort}."); + if !tools.is_empty() { + s += "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n\n"; + for t in tools { s += &t.dump(); s += "\n"; } + s += "\n\nIf you choose to call a function, use exactly this format:\n\n\n\n{parameter-value}\n\n\n"; + } + s += "<|im_end|>\n"; + let last_user = if preserve { None } else { msgs.iter().rposition(|m| m.role == "user") }; + for (i, m) in msgs.iter().enumerate() { + match m.role.as_str() { + "system" | "user" => s += &format!("<|im_start|>{}\n{}<|im_end|>\n", m.role, m.content), + "assistant" => { + let (r, c) = split_think(m, &m.content); + let r = if last_user.is_some_and(|u| i < u) { "" } else { r.trim() }; + s += &format!("<|im_start|>assistant\n{r}{}", c.trim()); + for call in &m.calls { + s += &format!("\n\n", call.name); + if let Json::Obj(o) = &call.args { + for (k, v) in o { s += &format!("\n{}\n\n", v.as_str().map_or_else(|| v.dump(), String::from)); } + } + s += "\n"; + } + s += "<|im_end|>\n"; + } + "tool" => s += &format!("<|im_start|>tool\n{}\n<|im_end|>\n", m.content), + _ => {} + } + } + if generate { s += if think { "<|im_start|>assistant\n" } else { "<|im_start|>assistant\n" }; } + s +} + /// Recursive Flint: escape the template's own markers in user text and drop NULs and think tags. fn flint_text(s: &str) -> String { let mut t = s.replace('\0', "").replace(" thinking", "").replace("", ""); @@ -421,9 +465,13 @@ impl Template { /// The family of a GGUF's `tokenizer.chat_template`. Files without one get Qwen3.6's format. pub fn detect(src: Option<&str>) -> Template { match src { + // Qwen4 GGUFs in the wild contain equivalent templates with different + // Jinja variable names (`reasoning` or `think_completion`). Match the + // stable protocol markers rather than one source-template expression. + Some(s) if s.contains("Reasoning effort is set to") && s.contains("") && s.contains("content") => Template::Qwen4 { effort: None }, Some(s) if s.contains("|DSML|") => Template::Ds, Some(s) if s.contains("<|observation|>") && s.contains("<|begin_of_text|>") => Template::Flint, - Some(s) if !s.contains(" Template::Json { reasoning: s.contains("reasoning_content") }, + Some(s) if !s.contains(" Template::Json { reasoning: s.contains("reasoning_content"), hybrid: s.contains("enable_thinking") }, _ => Template::Xml, } } @@ -440,12 +488,11 @@ impl Template { match *self { Template::Flint => s += &render_flint(msgs, tools, generate), Template::Ds => s += &render_ds(msgs, tools, think, preserve, generate), + Template::Qwen4 { effort } => s += &render_qwen4(msgs, tools, effort, think, preserve, generate), Template::Xml => { - let (n_sys, sys) = match msgs { - [a, b, ..] if a.role == "system" && b.role == "system" => (2, format!("{}\n{}", a.content.trim(), b.content.trim())), - [a, ..] if a.role == "system" => (1, a.content.trim().to_string()), - _ => (0, String::new()), - }; + // Every leading system message goes into the one system block (SillyTavern sends a card as many). + let n_sys = msgs.iter().take_while(|m| m.role == "system").count(); + let sys = msgs[..n_sys].iter().map(|m| m.content.trim()).collect::>().join("\n"); if !tools.is_empty() { s += "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n"; for t in tools { s += "\n"; s += &t.dump(); } @@ -480,12 +527,13 @@ impl Template { s += &format!("\n\n{c}\n"); tool_end(&mut s, i); } - _ => {} // later system messages are dropped + // Qwen's own template refuses a later system message; dropping it lost text without a word (#143). + _ => s += &format!("<|im_start|>system\n{c}<|im_end|>\n"), } } if generate { s += if think { "<|im_start|>assistant\n\n" } else { "<|im_start|>assistant\n\n\n\n\n" }; } } - Template::Json { reasoning } => { + Template::Json { reasoning, hybrid } => { let sys = msgs.first().filter(|m| m.role == "system").map(|m| m.content.as_str()); if !tools.is_empty() { s += "<|im_start|>system\n"; @@ -523,12 +571,30 @@ impl Template { _ => {} } } - if generate { s += "<|im_start|>assistant\n"; } + if generate { s += if hybrid && !think { "<|im_start|>assistant\n\n\n\n\n" } else { "<|im_start|>assistant\n" }; } } } s } + /// The template a request renders with, and its thinking switch. Qwen4 takes the request's `reasoning_effort`: + /// its own levels xhigh, high, low and off, and the OpenAI names clients send (max, medium, minimal, none) as the + /// nearest of them. Where its jinja raises, a request still gets a reply: an unknown level is ignored, and + /// thinking is off when either the level or `enable_thinking` (or a grammar) says so. Other templates are + /// returned as they are. + pub fn with_effort(self, effort: Option<&str>, think: Option) -> (Template, Option) { + let Template::Qwen4 { .. } = self else { return (self, think) }; + let e = match effort.unwrap_or("") { + "xhigh" | "max" => "xhigh", + "high" | "medium" => "high", + "low" | "minimal" => "low", + "off" | "none" => "off", + _ => return (self, think), + }; + let e = if think == Some(false) { "off" } else { e }; + (Template::Qwen4 { effort: Some(e) }, Some(e != "off")) + } + /// The prompt that ends inside the last message when it is an assistant message without tool calls, so the /// model continues that reply (prefill, as llama.cpp's server and the Anthropic Messages API do). `None` when /// the last message is not one. @@ -557,35 +623,67 @@ impl Template { if rest.is_empty() { break; } let inner; (inner, rest) = rest.strip_prefix(TAG)?.split_once("")?; - calls.push(match self { Template::Ds | Template::Flint => unreachable!(), Template::Xml => xml_call(inner, tools)?, Template::Json { .. } => json_call(inner)? }); + calls.push(match self { Template::Ds | Template::Flint => unreachable!(), Template::Xml | Template::Qwen4 { .. } => xml_call(inner, tools)?, Template::Json { .. } => json_call(inner)? }); } Some((text[..start].trim_end().to_string(), calls)) } + /// The calls of a reply that broke off inside a later call (max_tokens, a stop string) or went on past its + /// calls: those up to the last ``, the rest dropped. `None` when no call finished. + pub fn finished_calls(&self, text: &str, tools: &[Json]) -> Option<(String, Vec<(String, String)>)> { + if matches!(self, Template::Ds | Template::Flint) { return None; } + let end = text.rfind("")? + "".len(); + self.parse_calls(&text[..end], tools) + } + /// The calls of a reply that is still being written, as (name, arguments) for a stream: the arguments of each are + /// a prefix of what `parse_calls` gives for the finished reply. A finished call is whole; in the call still open + /// (`` arrives. Other templates give finished calls only (DeepSeek and Flint none). + // ponytail: rescans the whole reply each token (quadratic); fine for the size of a reply. + pub fn partial_calls(&self, text: &str, tools: &[Json]) -> Vec<(String, String)> { + let mut out = Vec::new(); + if matches!(self, Template::Ds | Template::Flint) { return out; } + let Some(start) = text.find(TAG) else { return out }; + let mut rest = &text[start..]; + while let Some(r) = rest.trim_start().strip_prefix(TAG) { + let Some((inner, after)) = r.split_once("") else { + if matches!(self, Template::Xml | Template::Qwen4 { .. }) && let Some(c) = xml_partial(r, tools) { out.push(c); } + break; + }; + match if matches!(self, Template::Xml | Template::Qwen4 { .. }) { xml_call(inner, tools) } else { json_call(inner) } { Some(c) => out.push(c), None => break } + rest = after; + } + out + } } -/// DeepSeek reply: a `<|DSML| calls>` block of `invoke` items with `parameter name=".." string="true|false"`. A -/// parameter is a string when the model says so, else JSON (a string if it does not parse). The reply's thinking part -/// is skipped, so a tag inside it is not taken for a call. +/// DeepSeek reply: a `<|DSML| calls>` block of `invoke` items with `parameter name=".." string="true|false"`. // ponytail: not run against the real model (the weights are deleted); the format is the template's own. -fn ds_calls(text: &str) -> Option<(String, Vec<(String, String)>)> { +fn ds_calls(text: &str) -> Option<(String, Vec<(String, String)>)> { markup_calls(text, "|DSML| ", "calls") } + +/// A `<{p}{block}>` block of `<{p}invoke name="..">` items with `<{p}parameter name=".." string="true|false">` +/// (DeepSeek DSML, GigaChat 4 GCML). A parameter is a string when the model says so, else JSON (a string if it does +/// not parse). The reply's thinking part is skipped, so a tag inside it is not taken for a call. +pub fn markup_calls(text: &str, p: &str, block: &str) -> Option<(String, Vec<(String, String)>)> { + let (open, close) = (format!("<{p}{block}>"), format!("")); + let (inv, inv_end, par, par_end) = (format!("<{p}invoke name=\""), format!(""), format!("<{p}parameter name=\""), format!("")); let from = text.rfind("").map_or(0, |p| p + 8); - let start = from + text[from..].find(DS_CALLS)?; - let mut rest = text[start..].strip_prefix(DS_CALLS)?; + let start = from + text[from..].find(&open)?; + let mut rest = &text[start + open.len()..]; let mut calls = Vec::new(); loop { rest = rest.trim_start(); - if let Some(x) = rest.strip_prefix("") { + if let Some(x) = rest.strip_prefix(close.as_str()) { if !x.trim().is_empty() || calls.is_empty() { return None; } break; } - let (name, mut r) = rest.strip_prefix("<|DSML| invoke name=\"")?.split_once("\">")?; + let (name, mut r) = rest.strip_prefix(inv.as_str())?.split_once("\">")?; let mut args = Vec::new(); loop { r = r.trim_start(); - if let Some(x) = r.strip_prefix("") { rest = x; break; } - let (head, x) = r.strip_prefix("<|DSML| parameter name=\"")?.split_once("\">")?; + if let Some(x) = r.strip_prefix(inv_end.as_str()) { rest = x; break; } + let (head, x) = r.strip_prefix(par.as_str())?.split_once("\">")?; let (k, string) = head.split_once("\" string=\"")?; - let (v, x) = x.split_once("")?; + let (v, x) = x.split_once(par_end.as_str())?; r = x; args.push((k.to_string(), if string == "true" { Json::Str(v.into()) } else { serde_json::from_str(v).unwrap_or_else(|_| Json::Str(v.into())) })); } @@ -621,16 +719,45 @@ fn xml_call(inner: &str, tools: &[Json]) -> Option<(String, String)> { let (k, x) = r.strip_prefix("')?; let (v, x) = x.split_once("")?; r = x; - let v = v.strip_prefix('\n').unwrap_or(v); - let v = v.strip_suffix('\n').unwrap_or(v); - let string = props.get(k).get("type").as_str() == Some("string"); - // The template prints earlier calls' booleans and null in Python spelling, and the model copies it. - let py = |v: &str| match v.trim() { "True" => Some(Json::Bool(true)), "False" => Some(Json::Bool(false)), "None" => Some(Json::Null), _ => None }; - args.push((k.to_string(), if string { Json::Str(v.into()) } else { serde_json::from_str(v).ok().or_else(|| py(v)).unwrap_or_else(|| Json::Str(v.into())) })); + args.push((k.to_string(), xml_value(v, props.get(k)))); } Some((name.to_string(), Json::Obj(args).dump())) } +fn xml_value(v: &str, prop: &Json) -> Json { + let v = v.strip_prefix('\n').unwrap_or(v); + let v = v.strip_suffix('\n').unwrap_or(v); + // The template prints earlier calls' booleans and null in Python spelling, and the model copies it. + let py = |v: &str| match v.trim() { "True" => Some(Json::Bool(true)), "False" => Some(Json::Bool(false)), "None" => Some(Json::Null), _ => None }; + if prop.get("type").as_str() == Some("string") { Json::Str(v.into()) } else { serde_json::from_str(v).ok().or_else(|| py(v)).unwrap_or_else(|| Json::Str(v.into())) } +} + +/// The open call of `partial_calls`: `r` is the text after its ``. +fn xml_partial(r: &str, tools: &[Json]) -> Option<(String, String)> { + let (name, mut r) = r.trim_start().strip_prefix("')?; + let props = tools.iter().map(|t| t.get("function")).find(|f| f.get("name").as_str() == Some(name))?.get("parameters").get("properties"); + let key = |k: &str| serde_json::to_string(k).unwrap(); + let mut s = String::from("{"); + while let Some((k, x)) = r.trim_start().strip_prefix("')) { + let sep = if s.len() > 1 { ", " } else { "" }; + if let Some((v, x)) = x.split_once("") { + s += &format!("{sep}{}: {}", key(k), xml_value(v, props.get(k)).dump()); + r = x; + continue; + } + if props.get(k).get("type").as_str() == Some("string") { + // The value so far, less a tail that could still be the `\n` that ends it. + let v = x.strip_prefix('\n').unwrap_or(x); + let end = "\n"; + let hold = (1..=end.len().min(v.len())).rev().find(|&n| v.ends_with(&end[..n])).unwrap_or(0); + let q = key(&v[..v.len() - hold]); + s += &format!("{sep}{}: {}", key(k), &q[..q.len() - 1]); + } + break; + } + Some((name.to_string(), s)) +} + /// Streams reply text but holds back everything from a `` tag on (unless `no_tag`), so a call is never /// sent as content, and ends the reply before the first of the `stops` strings. #[derive(Default)] @@ -672,14 +799,27 @@ impl Hold { /// Splits a reply that starts inside an open think block into reasoning and answer at ``, /// holding back a tail that could still become the tag. -pub struct Think { open: bool, lead: bool, buf: String } +pub struct Think { open: bool, lead: bool, start: bool, rlead: bool, buf: String } impl Think { const TAG: &'static str = ""; - pub fn new(open: bool) -> Think { Think { open, lead: false, buf: String::new() } } + pub fn new(open: bool) -> Think { Think { open, lead: false, start: !open, rlead: false, buf: String::new() } } /// (reasoning, answer) that are safe to send after adding `piece`. pub fn feed(&mut self, piece: &str) -> (String, String) { self.buf += piece; + // A template that does not open the block (Qwen3-0.6B) leaves the model to write `` itself. + if self.start { + let t = self.buf.trim_start(); + if t.len() < 7 && "".starts_with(t) { return (String::new(), String::new()); } + self.start = false; + if let Some(r) = t.strip_prefix("") { (self.buf, self.open, self.rlead) = (r.to_string(), true, true); } + } + // The newlines after a model-written ``, which may come in later pieces. + if self.rlead { + let t = self.buf.trim_start_matches('\n'); + if t.is_empty() { self.buf.clear(); return (String::new(), String::new()); } + (self.buf, self.rlead) = (t.to_string(), false); + } if !self.open { let b = std::mem::take(&mut self.buf); return (String::new(), self.answer(b)); } if let Some(p) = self.buf.find(Self::TAG) { self.open = false; @@ -713,6 +853,43 @@ impl Think { #[cfg(test)] mod think_tests { use super::*; + /// Issue 143: SillyTavern sends a card as many system messages, some after the chat starts; none is lost. + #[test] + fn xml_keeps_every_system_message() { + let m = |r, c| Msg::new(r, c); + let p = Template::Xml.render(&[m("system", "A"), m("system", "B"), m("system", "C"), m("user", "hi"), m("system", "D"), m("user", "x")], &[], false, false, true); + assert!(p.starts_with("<|im_start|>system\nA\nB\nC<|im_end|>\n<|im_start|>user\nhi"), "{p}"); + assert!(p.contains("<|im_end|>\n<|im_start|>system\nD<|im_end|>\n<|im_start|>user\nx"), "{p}"); + } + /// Issue 136: a `developer` message is a `system` message; a role no template knows is still refused. + #[test] + fn developer_role_is_system() { + let m = |r: &str| Msg::from_json(&serde_json::from_str::(&format!(r#"{{"role":"{r}","content":"be brief"}}"#)).unwrap()); + assert_eq!(m("developer").unwrap().role, "system"); + assert!(m("narrator").is_err()); + } + /// Issue 122: at every point of a reply, each streamed call is a prefix of the call the finished reply parses to, + /// and a long string parameter streams before its call ends. + #[test] + fn partial_calls_are_prefixes() { + let tools: Vec = serde_json::from_str(r#"[{"type":"function","function":{"name":"write","parameters":{"properties": + {"path":{"type":"string"},"n":{"type":"integer"},"content":{"type":"string"}}}}}]"#).unwrap(); + let text = "Ok.\n\n\n\na \"b\".rs\n\n\n3\n\n\ + \nfn main() {\n\tprintln!(\"é\");\n}\n\n\n\n\n\n\ + \n\nx\n\n\n"; + let (_, done) = Template::Xml.parse_calls(text, &tools).unwrap(); + let mut grew = false; + for (p, _) in text.char_indices() { + for (k, (f, a)) in Template::Xml.partial_calls(&text[..p], &tools).iter().enumerate() { + assert_eq!(f, &done[k].0); + assert!(done[k].1.starts_with(a.as_str()), "at {p}: {a:?} vs {:?}", done[k].1); + grew |= k == 0 && a.contains("println"); + } + } + assert!(grew); + assert_eq!(Template::Xml.partial_calls(text, &tools), done); + assert!(Template::Xml.partial_calls("\n\n\nx", &tools).is_empty()); + } #[test] fn image_source_must_be_a_url() { let req = |url: &str| crate::serve::chat_request(format!(r#"{{"messages":[{{"role":"user","content":[{{"type":"image_url","image_url":{{"url":"{url}"}}}}]}}]}}"#).as_bytes()); @@ -727,6 +904,20 @@ mod think_tests { let (x, y) = t.finish(); r += &x; a += &y; assert_eq!((r.trim_end(), a.as_str()), ("hm ok", "Hi!")); } + /// The model opens the block itself when the template did not: it is still reasoning; other text is not. + #[test] + fn model_written_think_tag_opens_the_block() { + let run = |ps: &[&str]| { + let (mut t, mut r, mut a) = (Think::new(false), String::new(), String::new()); + for p in ps { let (x, y) = t.feed(p); r += &x; a += &y; } + let (x, y) = t.finish(); r += &x; a += &y; + (r.trim_end().to_string(), a) + }; + assert_eq!(run(&["\nhm", "\n\n4"]), ("hm".into(), "4".into())); + assert_eq!(run(&["", "\n", "hm", "4"]), ("hm".into(), "4".into())); + assert_eq!(run(&["", "4"]), ("".into(), "4".into())); + assert_eq!(run(&["<"]), ("".into(), "<".into())); + } } #[cfg(test)] @@ -810,3 +1001,91 @@ mod flint_tests { assert_eq!(Template::Flint.parse_calls("plain", &[]), None); } } + +#[cfg(test)] +mod qwen4_tests { + use super::*; + // Expected strings come from rendering the Qwen4-35B-A3B GGUF's chat template with jinja2 (tools/qwen4_ref/render_template.py). + const SYS_HIGH: &str = "<|im_start|>system\nReasoning effort is set to high.<|im_end|>\n"; + + #[test] + fn qwen4_plain_chat() { + let t = Template::Qwen4 { effort: None }; + let u = [Msg::new("user", "Hi")]; + assert_eq!(t.render(&u, &[], true, false, true), "<|im_start|>system\nReasoning effort is set to high.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n"); + assert_eq!(t.render(&u, &[], false, false, true), "<|im_start|>system\nReasoning effort is set to off.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n"); + let mut a = Msg::new("assistant", "Hello."); + a.reasoning = Some("greet".into()); + let m = [Msg::new("system", "Be brief."), Msg::new("user", "Hi"), a, Msg::new("user", "Bye")]; + assert_eq!(t.render(&m, &[], true, false, true), format!("{SYS_HIGH}<|im_start|>system\nBe brief.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\nHello.<|im_end|>\n<|im_start|>user\nBye<|im_end|>\n<|im_start|>assistant\n")); + assert_eq!(t.render(&m, &[], true, true, true), format!("{SYS_HIGH}<|im_start|>system\nBe brief.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\ngreetHello.<|im_end|>\n<|im_start|>user\nBye<|im_end|>\n<|im_start|>assistant\n")); + // Reasoning inline in the content is split off like a reasoning field; the reply after the last user turn keeps it. + let m = [Msg::new("user", "Hi"), Msg::new("assistant", "\ngreet\n\n\nHello.\n")]; + assert_eq!(t.render(&m, &[], true, false, false), format!("{SYS_HIGH}<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\ngreetHello.<|im_end|>\n")); + } + + #[test] + fn qwen4_tools() { + let tool: Json = serde_json::from_str(r#"{"type":"function","function":{"name":"get_weather","description":"Get the weather for a city.","parameters":{"type":"object","properties":{"city":{"type":"string","description":"City name"},"days":{"type":"integer","description":"Days ahead"}},"required":["city"]}}}"#).unwrap(); + let tool = tool_def(&tool).unwrap(); + let mut a = Msg::new("assistant", ""); + a.calls.push(Call { name: "get_weather".into(), args: serde_json::from_str(r#"{"city":"Paris","days":3}"#).unwrap() }); + let m = [Msg::new("user", "Weather in Paris?"), a, Msg::new("tool", "Sunny, 21C")]; + assert_eq!(Template::Qwen4 { effort: None }.render(&m, &[tool], true, false, true), "<|im_start|>system\nReasoning effort is set to high.\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n\n{\"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"description\": \"Get the weather for a city.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}, \"days\": {\"type\": \"integer\", \"description\": \"Days ahead\"}}, \"required\": [\"city\"]}}}\n\n\nIf you choose to call a function, use exactly this format:\n\n\n\n{parameter-value}\n\n\n<|im_end|>\n<|im_start|>user\nWeather in Paris?<|im_end|>\n<|im_start|>assistant\n\n\n\nParis\n\n\n3\n\n\n<|im_end|>\n<|im_start|>tool\nSunny, 21C\n<|im_end|>\n<|im_start|>assistant\n"); + } + + #[test] + fn qwen4_detect() { + let src = include_str!("../tools/qwen4_ref/template.jinja"); + assert_eq!(Template::detect(Some(src)), Template::Qwen4 { effort: None }); + let q4_km = r#"{# Qwen4 GGUF variant #} +{{- 'Reasoning effort is set to ' + effort + '.' -}} +{{- '<|im_start|>assistant\\n' -}} +{{- think_completion + content -}}"#; + assert_eq!(Template::detect(Some(q4_km)), Template::Qwen4 { effort: None }); + assert_eq!(Template::detect(Some("{{ 'Reasoning effort is set to high' }}")), Template::Xml); + } + + #[test] + fn qwen4_effort() { + let t = Template::Qwen4 { effort: None }; + let u = [Msg::new("user", "Hi")]; + let render = |effort: &str, think: Option| { + let (t, think) = t.with_effort(Some(effort), think); + t.render(&u, &[], think.unwrap_or(true), false, true) + }; + let want = |e: &str, open: &str| format!("<|im_start|>system\nReasoning effort is set to {e}.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n{open}"); + assert_eq!(render("low", None), want("low", "")); + assert_eq!(render("xhigh", Some(true)), want("xhigh", "")); + assert_eq!(render("off", None), want("off", "")); + assert_eq!(render("none", None), want("off", "")); + assert_eq!(render("off", Some(false)), want("off", "")); + // The OpenAI names that the template does not have (clients send "medium" by default). + assert_eq!(render("medium", None), want("high", "")); + assert_eq!(render("minimal", None), want("low", "")); + assert_eq!(render("max", None), want("xhigh", "")); + // Where the jinja raises: off wins a contradiction, and an unknown level leaves the default. + assert_eq!(render("off", Some(true)), want("off", "")); + assert_eq!(render("low", Some(false)), want("off", "")); + assert_eq!(render("7", None), want("high", "")); + assert_eq!(render("7", Some(false)), want("off", "")); + // Other templates ignore the level. + assert_eq!(Template::Xml.with_effort(Some("medium"), None), (Template::Xml, None)); + } + + /// The reply continues the prompt: after `` it is reasoning until ``; after `` it is all answer. + #[test] + fn qwen4_reply_split() { + let run = |open: bool, ps: &[&str]| { + let (mut t, mut r, mut a) = (Think::new(open), String::new(), String::new()); + for p in ps { let (x, y) = t.feed(p); r += &x; a += &y; } + let (x, y) = t.finish(); r += &x; a += &y; + (r, a) + }; + let on = Template::Qwen4 { effort: None }.render(&[Msg::new("user", "Hi")], &[], true, false, true); + let off = Template::Qwen4 { effort: None }.render(&[Msg::new("user", "Hi")], &[], false, false, true); + assert!(on.trim_end().ends_with("") && !off.trim_end().ends_with("")); + assert_eq!(run(true, &["hm ok", "", "Hi!"]), ("hm ok".into(), "Hi!".into())); + assert_eq!(run(false, &["Hi!", " there"]), ("".into(), "Hi! there".into())); + } +} diff --git a/src/config.rs b/src/config.rs index c5b3bdea..def33f4d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -86,16 +86,19 @@ fn arch(name: &str) -> Option { }) } -/// `prism.hadamard.*` of agentionai's Gyro files. Every routed expert matrix is stored as `W diag(s) H^T` over blocks -/// of `block` input columns (H the normalized Sylvester-Walsh-Hadamard matrix, s a vector of +1 and -1), so its input -/// x has to become `H (s x)` first: the layer input before gate and up, the SwiGLU output before down. The router and -/// the shared expert see the unrotated values. +/// `prism.hadamard.*`: matrices stored as `W diag(s) H^T` over blocks of `block` input columns (H the normalized +/// Sylvester-Walsh-Hadamard matrix, s a vector of +1 and -1), so their input x has to become `H (s x)` first. +/// agentionai's Gyro files rotate only the routed experts: the layer input before gate and up, the SwiGLU output +/// before down; the router and the shared expert see the unrotated values. PrismML's Ternary Bonsai files (`dense`) +/// rotate every matrix but `ssm_alpha` / `ssm_beta` and the output head (tied or not), and store the token embedding +/// rotated (a looked-up row z becomes `s (H z)`); with `gdn_v_grouped` the input of `ssm_out` is first reordered from +/// the tiled value-head order [hd, nk, rep] to the grouped one [hd, rep, nk]. #[derive(Clone)] -pub struct Hadamard { pub block: usize, signs: Vec> } +pub struct Hadamard { pub block: usize, signs: Vec>, pub dense: bool, gdn_v_grouped: bool } impl std::fmt::Debug for Hadamard { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "Hadamard {{ block: {}, widths: {:?} }}", self.block, self.signs.iter().map(|s| s.len()).collect::>()) + write!(f, "Hadamard {{ block: {}, widths: {:?}, dense: {} }}", self.block, self.signs.iter().map(|s| s.len()).collect::>(), self.dense) } } @@ -106,22 +109,38 @@ impl Hadamard { let Some(version) = key("version") else { return Ok(None) }; let text = |k: &str| key(k).and_then(|v| v.as_str()).unwrap_or(""); let arr = |k: &str| key(k).and_then(|v| v.as_arr()).unwrap_or(&[]); + let flag = |k: &str| key(k).is_some_and(|v| matches!(v, Value::Bool(true))); let block = key("block_size").and_then(|v| v.as_u64()).unwrap_or(0) as usize; - anyhow::ensure!(version.as_u64() == Some(1) && text("transform") == "normalized-sylvester-walsh-hadamard" && text("axis") == "input-last-dimension" - && block > 1 && block.is_power_of_two() && arr("inverse_weight_names").is_empty(), - "unsupported prism.hadamard metadata (version {version:?}, transform {:?}, axis {:?}, block_size {block})", text("transform"), text("axis")); - // ponytail: all routed experts rotated or none (true for the Gyro files); a table per layer if a file ever - // rotates only some of them. + let tied = flag("tied_output"); + anyhow::ensure!(matches!(version.as_u64(), Some(1 | 2)) && (version.as_u64() == Some(2)) == tied + && text("transform") == "normalized-sylvester-walsh-hadamard" && text("axis") == "input-last-dimension" + && block > 1 && block.is_power_of_two(), + "unsupported prism.hadamard metadata (version {version:?}, tied_output {tied}, transform {:?}, axis {:?}, block_size {block})", text("transform"), text("axis")); let mut named: Vec<&str> = arr("weight_names").iter().filter_map(|v| v.as_str()).collect(); - let mut routed: Vec<&str> = g.tensors.keys().map(|n| n.as_str()) - .filter(|n| n.starts_with("blk.") && ["gate", "up", "down"].iter().any(|r| n.ends_with(&format!(".ffn_{r}_exps.weight")))).collect(); named.sort_unstable(); - routed.sort_unstable(); - anyhow::ensure!(named == routed, "prism.hadamard.weight_names lists {} tensors, the file has {} routed expert tensors: only files with every routed expert rotated are supported", named.len(), routed.len()); - let mut widths: Vec = routed.iter().map(|n| g.tensors[*n].dims[0] as usize).collect(); + let inverse: Vec<&str> = arr("inverse_weight_names").iter().filter_map(|v| v.as_str()).collect(); + let routed = |n: &str| ["gate", "up", "down"].iter().any(|r| n.ends_with(&format!(".ffn_{r}_exps.weight"))); + // Every matrix that llama.cpp's loader lets a file rotate (it only rotates inputs of the plain matmul path). + const KINDS: [&str; 10] = ["attn_q", "attn_k", "attn_v", "attn_qkv", "attn_gate", "attn_output", "ffn_gate", "ffn_up", "ffn_down", "ssm_out"]; + let foldable = |n: &str| n == "output.weight" || n.starts_with("blk.") && KINDS.iter().any(|k| n.ends_with(&format!(".{k}.weight"))); + let mut want: Vec<&str> = g.tensors.keys().map(|n| n.as_str()).filter(|n| routed(n)).collect(); + let dense = !inverse.is_empty(); + if dense { + // ponytail: all of a dense file rotated or none (true for the Bonsai files); a per-tensor table if a file + // ever mixes, and the MoE shared expert / router rules if a rotated dense file has experts. + anyhow::ensure!(inverse == ["token_embd.weight"] && want.is_empty(), "unsupported prism.hadamard.inverse_weight_names {inverse:?} (only token_embd.weight of a dense model)"); + want = g.tensors.keys().map(|n| n.as_str()).filter(|n| foldable(n)).collect(); + } else { + anyhow::ensure!(!tied, "prism.hadamard.tied_output needs a rotated token_embd.weight"); + } + want.sort_unstable(); + anyhow::ensure!(named == want, "prism.hadamard.weight_names lists {} tensors, the file has {} {}: only files with all of them rotated are supported", + named.len(), want.len(), if dense { "rotatable matrices" } else { "routed expert tensors" }); + anyhow::ensure!(!tied || !g.tensors.contains_key("output.weight"), "prism.hadamard.tied_output with an output.weight"); + let mut widths: Vec = want.iter().chain(&inverse).map(|n| g.tensors[*n].dims[0] as usize).collect(); widths.sort_unstable(); widths.dedup(); - anyhow::ensure!(widths.iter().all(|w| w % block == 0), "prism.hadamard.block_size {block} does not divide the expert widths {widths:?}"); + anyhow::ensure!(widths.iter().all(|w| w % block == 0), "prism.hadamard.block_size {block} does not divide the input widths {widths:?}"); let signs = match text("sign_mode") { "identity" => widths.iter().map(|&w| vec![1f32; w]).collect(), "explicit" => { @@ -138,7 +157,26 @@ impl Hadamard { } mode => bail!("unsupported prism.hadamard.sign_mode {mode:?}"), }; - Ok(Some(Hadamard { block, signs })) + Ok(Some(Hadamard { block, signs, dense, gdn_v_grouped: flag("gdn_v_grouped") })) + } + + /// The input of `ssm_out` (value heads in the tiled order of `nk` key heads, `nv` value heads of `hd` values) + /// becomes `H (s x)`, first regrouped when the file says so. + pub fn rotate_ssm_out(&self, x: &mut [f32], nk: usize, nv: usize) { + if let Some(p) = self.ssm_out_perm(x.len(), nk, nv) { + let y = x.to_vec(); + for (o, &i) in x.iter_mut().zip(&p) { *o = y[i as usize]; } + } + self.rotate(x); + } + + /// Where entry j of the regrouped `ssm_out` input comes from (`None`: no reorder). The tiled order has entry + /// h + hd (k + nk r), the grouped one h + hd (r + rep k). + pub fn ssm_out_perm(&self, n: usize, nk: usize, nv: usize) -> Option> { + let rep = nv / nk; + if !self.gdn_v_grouped || rep <= 1 { return None; } + let hd = n / nv; + Some((0..n).map(|j| { let (h, r, k) = (j % hd, j / hd % rep, j / hd / rep); (h + hd * (k + nk * r)) as u32 }).collect()) } /// The signs for an input of `n` values. @@ -181,7 +219,7 @@ impl Hadamard { #[test] fn hadamard_rotation_is_the_matrix_product() { - let h = Hadamard { block: 8, signs: vec![(0..16).map(|i| if i % 3 == 0 { -1.0 } else { 1.0 }).collect()] }; + let h = Hadamard { block: 8, signs: vec![(0..16).map(|i| if i % 3 == 0 { -1.0 } else { 1.0 }).collect()], dense: true, gdn_v_grouped: true }; let x: Vec = (0..16).map(|i| (i * i) as f32 - 20.0).collect(); let y = h.rotated(&x); for r in 0..16 { @@ -193,6 +231,14 @@ fn hadamard_rotation_is_the_matrix_product() { assert!(back.iter().zip(&x).all(|(a, b)| (a - b).abs() < 1e-4), "unrotate: {back:?} vs {x:?}"); } +#[test] +fn hadamard_ssm_out_regroups_the_value_heads() { + // 2 key heads, 4 value heads of 2 values: tiled order is (k, r) = (0,0) (1,0) (0,1) (1,1), grouped (0,0) (0,1) (1,0) (1,1). + let h = Hadamard { block: 8, signs: vec![vec![1.0; 8]], dense: true, gdn_v_grouped: true }; + assert_eq!(h.ssm_out_perm(8, 2, 4).unwrap(), [0, 1, 4, 5, 2, 3, 6, 7]); + assert!(h.ssm_out_perm(8, 4, 4).is_none()); +} + #[derive(Clone, Debug)] pub struct ModelConfig { pub arch: String, @@ -262,7 +308,7 @@ pub struct ModelConfig { } /// Architectures with their own forward and server outside `ModelConfig` (`src/main.rs` dispatches on them). -pub const OWN_ARCHS: [&str; 6] = ["gemma4", "glm5-next", "deepseek41", crate::hy4::ARCH, crate::inkling2::ARCH, crate::inkling2::ARCH_RUNS]; +pub const OWN_ARCHS: [&str; 9] = ["gemma4", "glm5-next", "deepseek41", crate::hy4::ARCH, crate::kolibri::ARCH, crate::gigachat4::ARCH, crate::inkling2::ARCH, crate::inkling2::ARCH_RUNS, crate::raon::ARCH]; impl ModelConfig { pub fn from_gguf(g: &Gguf) -> anyhow::Result { diff --git a/src/cpu_moe.rs b/src/cpu_moe.rs index a218d43e..bbdc6023 100644 --- a/src/cpu_moe.rs +++ b/src/cpu_moe.rs @@ -26,23 +26,25 @@ static SIGNS: [[i8; 8]; 128] = { /// Quantizes `x` in blocks of 256; a short last block is zero-padded (Q2_0 rows can hold 64 * k values). pub fn quantize_q8k(x: &[f32]) -> Vec { - x.chunks(256).map(|b| { - let mut pad = [0f32; 256]; - let b = if b.len() == 256 { b } else { pad[..b.len()].copy_from_slice(b); &pad[..] }; - // The first value of largest magnitude (a max over |v| first, which vectorizes). - let amax = b.iter().fold(0f32, |m, &v| m.max(v.abs())); - if amax == 0.0 { return Q8K { d: 0.0, qs: [0; 256], bs: [0; 16] }; } - let max = *b.iter().find(|v| v.abs() == amax).unwrap(); - let is = -127.0 / max; - let mut qs = [0i8; 256]; - #[cfg(target_feature = "avx2")] - avx2::quant_block(is, b, &mut qs); - #[cfg(not(target_feature = "avx2"))] - for (q, &v) in qs.iter_mut().zip(b) { *q = ((is * v).round_ties_even() as i32).min(127) as i8; } - let mut bs = [0i16; 16]; - for (s, c) in bs.iter_mut().zip(qs.chunks_exact(16)) { *s = c.iter().map(|&v| v as i16).sum(); } - Q8K { d: 1.0 / is, qs, bs } - }).collect() + x.chunks(256).map(quantize_q8k_block).collect() +} + +fn quantize_q8k_block(b: &[f32]) -> Q8K { + let mut pad = [0f32; 256]; + let b = if b.len() == 256 { b } else { pad[..b.len()].copy_from_slice(b); &pad[..] }; + // The first value of largest magnitude (a max over |v| first, which vectorizes). + let amax = b.iter().fold(0f32, |m, &v| m.max(v.abs())); + if amax == 0.0 { return Q8K { d: 0.0, qs: [0; 256], bs: [0; 16] }; } + let max = *b.iter().find(|v| v.abs() == amax).unwrap(); + let is = -127.0 / max; + let mut qs = [0i8; 256]; + #[cfg(target_feature = "avx2")] + avx2::quant_block(is, b, &mut qs); + #[cfg(not(target_feature = "avx2"))] + for (q, &v) in qs.iter_mut().zip(b) { *q = ((is * v).round_ties_even() as i32).min(127) as i8; } + let mut bs = [0i16; 16]; + for (s, c) in bs.iter_mut().zip(qs.chunks_exact(16)) { *s = c.iter().map(|&v| v as i16).sum(); } + Q8K { d: 1.0 / is, qs, bs } } fn d16(b: &[u8]) -> f32 { f16::from_le_bytes([b[0], b[1]]).to_f32() } @@ -295,18 +297,175 @@ fn dot_tq1_0(row: &[u8], xq: &[Q8K]) -> f32 { sumf } -/// TQ2_0: 64 bytes of 2-bit codes (code - 1 in -1..2), then f16 d; 256 values a block. -fn dot_tq2_0(row: &[u8], xq: &[Q8K]) -> f32 { - let mut sumf = 0.0; - for (b, y) in row.chunks_exact(66).zip(xq) { - let mut s = 0i32; - for j in 0..2 { for l in 0..4 { for m in 0..32 { - let code = (b[32 * j + m] >> (2 * l)) & 3; - s += (code as i32 - 1) * y.qs[128 * j + 32 * l + m] as i32; - } } } - sumf += d16(&b[64..]) * y.d * s as f32; +type AffineDot = fn(&[u8], [&[Q8K]; N]) -> [f32; N]; + +/// Layout metadata selects the coefficient group width. Each decoder writes signed +/// integer codes and one scale and offset per group, without requantizing the weights. +macro_rules! affine_layouts { + ($uniform:ident, $grouped:ident, $ty:expr) => { + match $ty { + GgmlType::PTQ1_0 => $uniform!(PTQ1_0, unpack_ptq1_0), + GgmlType::PTQ1R => $uniform!(PTQ1R, unpack_ptq1r), + GgmlType::TQ2_0 => $uniform!(TQ2_0, unpack_tq2_0), + GgmlType::Q1_0 => $grouped!(Q1_0, 128, unpack_q1_0), + GgmlType::PQ2_0 => $grouped!(PQ2_0, 128, unpack_q2_0), + GgmlType::Q8_1 => $grouped!(Q8_1, 32, unpack_q8_1), + GgmlType::Q8K => $grouped!(Q8K, 256, unpack_q8k), + GgmlType::MXFP4 => $grouped!(MXFP4, 32, unpack_mxfp4), + GgmlType::TQ1_0 => $grouped!(TQ1_0, 256, unpack_tq1_0), + GgmlType::Q2_0 => $grouped!(Q2_0, 64, unpack_q2_0), + GgmlType::Q2K => $grouped!(Q2K, 16, unpack_q2k), + GgmlType::Q3K => $grouped!(Q3K, 16, unpack_q3k), + GgmlType::Q4_0 => $grouped!(Q4_0, 32, unpack_q4_0), + GgmlType::Q4_1 => $grouped!(Q4_1, 32, unpack_q4_1), + GgmlType::Q4K => $grouped!(Q4K, 32, unpack_q4k), + GgmlType::Q5_0 => $grouped!(Q5_0, 32, unpack_q5_0), + GgmlType::Q5_1 => $grouped!(Q5_1, 32, unpack_q5_1), + GgmlType::Q5K => $grouped!(Q5K, 32, unpack_q5k), + GgmlType::Q6K => $grouped!(Q6K, 16, unpack_q6k), + GgmlType::Q8_0 => $grouped!(Q8_0, 32, unpack_q8_0), + GgmlType::IQ1S => $grouped!(IQ1S, 32, unpack_iq1s), + GgmlType::IQ1M => $grouped!(IQ1M, 8, unpack_iq1m), + GgmlType::IQ2XXS => $grouped!(IQ2XXS, 32, unpack_iq2xxs), + GgmlType::IQ2XS => $grouped!(IQ2XS, 16, unpack_iq2xs), + GgmlType::IQ2S => $grouped!(IQ2S, 16, unpack_iq2s), + GgmlType::IQ3XXS => $grouped!(IQ3XXS, 32, unpack_iq3xxs), + GgmlType::IQ3S => $grouped!(IQ3S, 32, unpack_iq3s), + GgmlType::IQ4NL => $grouped!(IQ4NL, 32, unpack_iq4nl), + GgmlType::IQ4XS => $grouped!(IQ4XS, 32, unpack_iq4xs), + GgmlType::NVFP4 => $grouped!(NVFP4, 16, unpack_nvfp4), + _ => None, + } + }; +} + +pub(crate) fn affine_block_elems(ty: GgmlType) -> Option { + if !shared_int_by_default(ty) && !prefer_shared_int() { + return None; } - sumf + macro_rules! size { + ($kind:ident, $($args:tt)*) => { Some(GgmlType::$kind.block_elems()) }; + } + affine_layouts!(size, size, ty) +} + +fn affine_dot1(ty: GgmlType) -> Option f32> { + macro_rules! uniform { + ($kind:ident, $unpack:ident) => { + Some(|row, x| affine_dot::<1, { GgmlType::$kind.block_bytes() }, { GgmlType::$kind.block_elems() }, SIMD>(row, [x], crate::quant::$unpack)[0]) + }; + } + macro_rules! grouped { + ($kind:ident, $group:literal, $unpack:ident) => { + Some(|row, x| grouped_affine_dot::<1, { GgmlType::$kind.block_bytes() }, { GgmlType::$kind.block_elems() }, $group, SIMD>( + row, [x], |b, codes, coeff| crate::quant::$unpack(b, |i, q, d, m| { + codes[i] = q; + if i % $group == 0 { coeff[i / $group] = (d, m); } + debug_assert_eq!(coeff[i / $group].0.to_bits(), d.to_bits()); + debug_assert_eq!(coeff[i / $group].1.to_bits(), m.to_bits()); + }), + )[0]) + }; + } + affine_layouts!(uniform, grouped, ty) +} + +fn affine_kernel(ty: GgmlType) -> Option> { + macro_rules! uniform { + ($kind:ident, $unpack:ident) => { + Some(|row, xs| affine_dot::(row, xs, crate::quant::$unpack)) + }; + } + macro_rules! grouped { + ($kind:ident, $group:literal, $unpack:ident) => { + Some(|row, xs| grouped_affine_dot::( + row, xs, |b, codes, coeff| crate::quant::$unpack(b, |i, q, d, m| { + codes[i] = q; + if i % $group == 0 { coeff[i / $group] = (d, m); } + debug_assert_eq!(coeff[i / $group].0.to_bits(), d.to_bits()); + debug_assert_eq!(coeff[i / $group].1.to_bits(), m.to_bits()); + }), + )) + }; + } + affine_layouts!(uniform, grouped, ty) +} + +#[inline(always)] +fn grouped_affine_dot( + row: &[u8], xs: [&[Q8K]; N], unpack: impl Fn(&[u8], &mut [i16; ELEMS], &mut [(f32, f32); 32]), +) -> [f32; N] { + const { assert!(ELEMS > 0 && 256 % ELEMS == 0 && ELEMS % GROUP == 0 && GROUP >= 8); } + let mut out = [0.0; N]; + let mut codes = [0; ELEMS]; + let mut coeff = [(0.0, 0.0); 32]; + for (i, block) in row.chunks_exact(BYTES).enumerate() { + unpack(block, &mut codes, &mut coeff); + let start = i % (256 / ELEMS) * ELEMS; + for (sum, x) in out.iter_mut().zip(xs) { + let x = &x[i / (256 / ELEMS)]; + let mut block_sum = 0.0; + for (g, (w, &(scale, offset))) in codes.chunks_exact(GROUP).zip(&coeff).enumerate() { + let first = start + g * GROUP; + let q = &x.qs[first..first + GROUP]; + #[cfg(target_feature = "avx2")] + let dot = if SIMD { avx2::signed_codes_dot(w, q) } else { signed_codes_dot(w, q) }; + #[cfg(not(target_feature = "avx2"))] + let dot = signed_codes_dot(w, q); + let bias = if offset == 0.0 { + 0.0 + } else { + let sum: i32 = if GROUP % 16 == 0 { + x.bs[first / 16..(first + GROUP) / 16].iter().map(|&v| v as i32).sum() + } else { + q.iter().map(|&v| v as i32).sum() + }; + offset * sum as f32 + }; + block_sum += scale * dot as f32 + bias; + } + *sum += x.d * block_sum; + } + } + out +} + +#[inline(always)] +fn signed_codes_dot(w: &[i16], q: &[i8]) -> i32 { + w.iter().zip(q).map(|(&w, &q)| w as i32 * q as i32).sum() +} + +#[inline(always)] +fn affine_dot( + row: &[u8], xs: [&[Q8K]; N], unpack: impl Fn(&[u8], &mut [u8; ELEMS]) -> (f32, f32), +) -> [f32; N] { + const { assert!(ELEMS > 0 && 256 % ELEMS == 0 && ELEMS % 16 == 0); } + let mut out = [0.0; N]; + let mut codes = [0; ELEMS]; + for (i, block) in row.chunks_exact(BYTES).enumerate() { + let (scale, offset) = unpack(block, &mut codes); + let start = i % (256 / ELEMS) * ELEMS; + for (sum, x) in out.iter_mut().zip(xs) { + let x = &x[i / (256 / ELEMS)]; + let q: &[i8; ELEMS] = x.qs[start..start + ELEMS].try_into().unwrap(); + let dot = affine_codes_dot::(&codes, q); + let bias_sum: i32 = x.bs[start / 16..(start + ELEMS) / 16].iter().map(|&v| v as i32).sum(); + *sum += x.d * (scale * dot as f32 + offset * bias_sum as f32); + } + } + out +} + +#[inline(always)] +fn affine_codes_dot(codes: &[u8; N], q: &[i8; N]) -> i32 { + #[cfg(target_feature = "avx2")] + if SIMD && N % 32 == 0 { return avx2::affine_codes_dot(codes, q); } + + let mut sums = [0i32; 16]; + for (codes, q) in codes.chunks_exact(16).zip(q.chunks_exact(16)) { + for i in 0..16 { sums[i] += codes[i] as i32 * q[i] as i32; } + } + sums.iter().sum() } /// Q4_0 (`T` = 2, 18 bytes), Q4_1 (3, 20), Q5_0 (6, 22), Q5_1 (7, 24): block bytes, offset of the 32 high bits @@ -395,6 +554,7 @@ fn dot_q6k(row: &[u8], xq: &[Q8K]) -> f32 { #[cfg(target_feature = "avx2")] mod avx2 { use super::{Q8K, SIGNS, d16, iq1m_d}; + use crate::quant::GgmlType; use crate::quant::tables::*; use std::arch::x86_64::*; @@ -417,35 +577,45 @@ mod avx2 { #[inline(always)] fn sg(i: usize) -> i64 { unsafe { std::mem::transmute::<[i8; 8], i64>(SIGNS[i]) } } - pub fn dot_iq2xs(row: &[u8], xq: &[Q8K]) -> f32 { + pub fn dot_iq2xs(row: &[u8], xq: &[Q8K]) -> f32 { dotn_iq2xs(row, [xq])[0] } + #[inline(always)] + pub fn dot4_iq2xs(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dotn_iq2xs(row, xq) } + /// `N` dots of one row (see `super::int_dot4`): each block is decoded once for all activations. + #[inline(always)] + fn dotn_iq2xs(row: &[u8], xq: [&[Q8K]; N]) -> [f32; N] { unsafe { - let mut acc = _mm256_setzero_ps(); - for (b, y) in row.chunks_exact(74).zip(xq) { - let mut sumi = _mm256_setzero_si256(); + let mut acc = [_mm256_setzero_ps(); N]; + for (i, b) in row.chunks_exact(74).enumerate() { + let mut sumi = [_mm256_setzero_si256(); N]; for ib in 0..8 { let v = u64::from_le_bytes(b[2 + 8 * ib..10 + 8 * ib].try_into().unwrap()); let (q0, q1, q2, q3) = (v as u16, (v >> 16) as u16, (v >> 32) as u16, (v >> 48) as u16); let g = |q: u16| IQ2XS_GRID[(q & 511) as usize] as i64; let grid = _mm256_set_epi64x(g(q3), g(q2), g(q1), g(q0)); let signs = _mm256_set_epi64x(sg((q3 >> 9) as usize), sg((q2 >> 9) as usize), sg((q1 >> 9) as usize), sg((q0 >> 9) as usize)); - let q8 = _mm256_loadu_si256(y.qs.as_ptr().add(32 * ib) as *const __m256i); - let dot = _mm256_maddubs_epi16(grid, _mm256_sign_epi8(q8, signs)); let sc = b[66 + ib]; let ls = _mm256_set_m128i(_mm_set1_epi16(2 * (sc >> 4) as i16 + 1), _mm_set1_epi16(2 * (sc & 0xF) as i16 + 1)); - sumi = _mm256_add_epi32(sumi, _mm256_madd_epi16(dot, ls)); + for k in 0..N { + let dot = _mm256_maddubs_epi16(grid, _mm256_sign_epi8(q8(&xq[k][i], 32 * ib), signs)); + sumi[k] = _mm256_add_epi32(sumi[k], _mm256_madd_epi16(dot, ls)); + } } - acc = _mm256_fmadd_ps(ds(b, y.d), _mm256_cvtepi32_ps(sumi), acc); + for k in 0..N { acc[k] = _mm256_fmadd_ps(ds(b, xq[k][i].d), _mm256_cvtepi32_ps(sumi[k]), acc[k]); } } - 0.125 * hsum(acc) + acc.map(|a| 0.125 * hsum(a)) } } - pub fn dot_iq3xxs(row: &[u8], xq: &[Q8K]) -> f32 { + pub fn dot_iq3xxs(row: &[u8], xq: &[Q8K]) -> f32 { dotn_iq3xxs(row, [xq])[0] } + #[inline(always)] + pub fn dot4_iq3xxs(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dotn_iq3xxs(row, xq) } + #[inline(always)] + fn dotn_iq3xxs(row: &[u8], xq: [&[Q8K]; N]) -> [f32; N] { unsafe { - let mut acc = _mm256_setzero_ps(); - for (b, y) in row.chunks_exact(98).zip(xq) { + let mut acc = [_mm256_setzero_ps(); N]; + for (i, b) in row.chunks_exact(98).enumerate() { let (qs, gas) = (&b[2..66], &b[66..98]); - let mut sumi = _mm256_setzero_si256(); + let mut sumi = [_mm256_setzero_si256(); N]; for ib in 0..8 { let v = u64::from_le_bytes(qs[8 * ib..8 * ib + 8].try_into().unwrap()); let g = |i: usize| IQ3XXS_GRID[(v >> (8 * i)) as u8 as usize] as i32; @@ -453,40 +623,47 @@ mod avx2 { let aux = u32::from_le_bytes(gas[4 * ib..4 * ib + 4].try_into().unwrap()); let s = |l: u32| sg(((aux >> (7 * l)) & 127) as usize); let signs = _mm256_set_epi64x(s(3), s(2), s(1), s(0)); - let q8 = _mm256_loadu_si256(y.qs.as_ptr().add(32 * ib) as *const __m256i); - let dot = _mm256_maddubs_epi16(grid, _mm256_sign_epi8(q8, signs)); - sumi = _mm256_add_epi32(sumi, _mm256_madd_epi16(dot, _mm256_set1_epi16(2 * (aux >> 28) as i16 + 1))); + let ls = _mm256_set1_epi16(2 * (aux >> 28) as i16 + 1); + for k in 0..N { + let dot = _mm256_maddubs_epi16(grid, _mm256_sign_epi8(q8(&xq[k][i], 32 * ib), signs)); + sumi[k] = _mm256_add_epi32(sumi[k], _mm256_madd_epi16(dot, ls)); + } } - acc = _mm256_fmadd_ps(ds(b, y.d), _mm256_cvtepi32_ps(sumi), acc); + for k in 0..N { acc[k] = _mm256_fmadd_ps(ds(b, xq[k][i].d), _mm256_cvtepi32_ps(sumi[k]), acc[k]); } } - 0.25 * hsum(acc) + acc.map(|a| 0.25 * hsum(a)) } } - pub fn dot_iq3s(row: &[u8], xq: &[Q8K]) -> f32 { + pub fn dot_iq3s(row: &[u8], xq: &[Q8K]) -> f32 { dotn_iq3s(row, [xq])[0] } + #[inline(always)] + pub fn dot4_iq3s(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dotn_iq3s(row, xq) } + #[inline(always)] + fn dotn_iq3s(row: &[u8], xq: [&[Q8K]; N]) -> [f32; N] { unsafe { // Byte k of a lane picks sign byte k / 8, then bit k % 8 (llama.cpp k_mask1 / k_mask2). let m1 = _mm256_set_epi64x(0x0303030303030303, 0x0202020202020202, 0x0101010101010101, 0); let m2 = _mm256_set1_epi64x(0x8040201008040201u64 as i64); let shl = _mm256_set_epi32(1, 2, 3, 4, 5, 6, 7, 8); - let mut acc = _mm256_setzero_ps(); - for (b, y) in row.chunks_exact(110).zip(xq) { + let mut acc = [_mm256_setzero_ps(); N]; + for (i, b) in row.chunks_exact(110).enumerate() { let (qs, qh) = (&b[2..66], &b[66..74]); - let mut sumi = _mm256_setzero_si256(); + let mut sumi = [_mm256_setzero_si256(); N]; for ib in 0..8 { let lo = _mm256_cvtepu8_epi32(_mm_loadl_epi64(qs[8 * ib..].as_ptr() as *const __m128i)); let hi = _mm256_and_si256(_mm256_sllv_epi32(_mm256_set1_epi32(qh[ib] as i32), shl), _mm256_set1_epi32(256)); let grid = _mm256_i32gather_epi32(IQ3S_GRID.as_ptr() as *const i32, _mm256_or_si256(lo, hi), 4); let sb = i32::from_le_bytes(b[74 + 4 * ib..78 + 4 * ib].try_into().unwrap()); let s = _mm256_cmpeq_epi8(_mm256_and_si256(_mm256_shuffle_epi8(_mm256_set1_epi32(sb), m1), m2), m2); - let q8 = _mm256_loadu_si256(y.qs.as_ptr().add(32 * ib) as *const __m256i); - let dot = _mm256_maddubs_epi16(grid, _mm256_sub_epi8(_mm256_xor_si256(s, q8), s)); - let ls = 2 * (b[106 + ib / 2] >> (4 * (ib % 2)) & 0xF) as i16 + 1; - sumi = _mm256_add_epi32(sumi, _mm256_madd_epi16(dot, _mm256_set1_epi16(ls))); + let ls = _mm256_set1_epi16(2 * (b[106 + ib / 2] >> (4 * (ib % 2)) & 0xF) as i16 + 1); + for k in 0..N { + let dot = _mm256_maddubs_epi16(grid, _mm256_sub_epi8(_mm256_xor_si256(s, q8(&xq[k][i], 32 * ib)), s)); + sumi[k] = _mm256_add_epi32(sumi[k], _mm256_madd_epi16(dot, ls)); + } } - acc = _mm256_fmadd_ps(ds(b, y.d), _mm256_cvtepi32_ps(sumi), acc); + for k in 0..N { acc[k] = _mm256_fmadd_ps(ds(b, xq[k][i].d), _mm256_cvtepi32_ps(sumi[k]), acc[k]); } } - hsum(acc) + acc.map(|a| hsum(a)) } } @@ -513,6 +690,172 @@ mod avx2 { } } + /// `dot_iq4xs` of one row with four activations (see `super::int_dot4`): each 32-value group is decoded once, + /// and every lane runs `dot_iq4xs`'s operations in its order. + pub fn dot4_iq4xs(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + unsafe { + let values = _mm_loadu_si128(KVALUES_IQ4NL.as_ptr() as *const __m128i); + let m4 = _mm_set1_epi8(0xF); + let mut acc = [_mm256_setzero_ps(); 4]; + for (i, b) in row.chunks_exact(136).enumerate() { + let sh = u16::from_le_bytes([b[2], b[3]]); + let mut sumi = [_mm256_setzero_si256(); 4]; + for ib in 0..8 { + let bits = _mm_loadu_si128(b.as_ptr().add(8 + 16 * ib) as *const __m128i); + let w = _mm256_set_m128i(_mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4)), + _mm_shuffle_epi8(values, _mm_and_si128(bits, m4))); + let aw = _mm256_sign_epi8(w, w); + let ls = ((b[4 + ib / 2] >> (4 * (ib % 2))) & 0xF) as i16 | ((((sh >> (2 * ib)) & 3) as i16) << 4); + let sc = _mm256_set1_epi16(ls - 32); + for k in 0..4 { + let p16 = _mm256_maddubs_epi16(aw, _mm256_sign_epi8(q8(&xq[k][i], 32 * ib), w)); + sumi[k] = _mm256_add_epi32(sumi[k], _mm256_madd_epi16(p16, sc)); + } + } + for k in 0..4 { acc[k] = _mm256_fmadd_ps(ds(b, xq[k][i].d), _mm256_cvtepi32_ps(sumi[k]), acc[k]); } + } + acc.map(|a| hsum(a)) + } + } + + #[inline(always)] + pub(super) fn signed_codes_dot(w: &[i16], q: &[i8]) -> i32 { + unsafe { + let mut sum = _mm256_setzero_si256(); + let (mut w, mut q) = (w.chunks_exact(16), q.chunks_exact(16)); + for (w, q) in w.by_ref().zip(q.by_ref()) { + let w = _mm256_loadu_si256(w.as_ptr().cast()); + let q = _mm256_cvtepi8_epi16(_mm_loadu_si128(q.as_ptr().cast())); + sum = _mm256_add_epi32(sum, _mm256_madd_epi16(w, q)); + } + hsum_i32(sum) + super::signed_codes_dot(w.remainder(), q.remainder()) + } + } + + #[inline(always)] + pub(super) fn affine_codes_dot(codes: &[u8; N], q: &[i8; N]) -> i32 { + unsafe { + let ones = _mm256_set1_epi16(1); + let mut sum = _mm256_setzero_si256(); + for (w, x) in codes.chunks_exact(32).zip(q.chunks_exact(32)) { + let w = _mm256_loadu_si256(w.as_ptr().cast()); + let x = _mm256_loadu_si256(x.as_ptr().cast()); + // Codes <= 127 keep each signed pair within i16, even for an activation of -128. + let pairs = _mm256_maddubs_epi16(w, x); + sum = _mm256_add_epi32(sum, _mm256_madd_epi16(pairs, ones)); + } + hsum_i32(sum) + } + } + + pub fn dot_ptq1_0(row: &[u8], xq: &[Q8K]) -> f32 { ptq1_0(row, [xq])[0] } + + pub fn dot4_ptq1_0(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { ptq1_0(row, xq) } + + pub fn dot_ptq1r(row: &[u8], xq: &[Q8K]) -> f32 { ptq1r_tile::<1, 1>([row], [xq])[0][0] } + + pub fn dot4_ptq1r(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { ptq1r_tile::<1, 4>([row], xq)[0] } + + /// PTQ1_0R (`quant::repack_ptq1_0`) rows times activations, `R * A` <= 8 products at once. Crumb l of a block's 32 + /// code bytes is its elements 32 l.., so a group is a shift and a mask, and its codes 0..2 (value + 1) are the + /// unsigned operand of `maddubs`; the block's activation sum (eight Q8_K sub-block sums) is taken off in i16 to + /// remove the offset (each lane stays within 4 * 2 * 2 * 127 + 16 * 127, inside i16). Every product is the exact + /// integer dot of each block, scaled by d * y.d and added with one fma in block order: the same bits for any + /// tile shape, so decode (8 rows by 1), prefill (2 by 4), `int_dot` and `int_dot4` agree. + #[inline(always)] + pub fn ptq1r_tile(rows: [&[u8]; R], xs: [&[Q8K]; A]) -> [[f32; A]; R] { + unsafe { + let (m3, ones, zero) = (_mm256_set1_epi8(3), _mm256_set1_epi16(1), _mm256_setzero_si256()); + let mut accv = _mm256_setzero_ps(); + let mut accs = [[0f32; A]; R]; + for i in 0..rows[0].len() / 34 { + let (half, offset) = (i / 2, 128 * (i % 2)); + let mut sums = [[zero; A]; R]; + for g in 0..4 { + // The code bytes are loaded again for each group (from L1): eight tiles of them do not fit the + // registers beside the sums. + let w: [__m256i; R] = std::array::from_fn(|r| _mm256_and_si256(_mm256_srl_epi16( + _mm256_loadu_si256(rows[r].as_ptr().add(34 * i).cast()), _mm_cvtsi32_si128(2 * g as i32)), m3)); + for a in 0..A { + let x = q8(&xs[a][half], offset + 32 * g); + for r in 0..R { sums[r][a] = _mm256_add_epi16(sums[r][a], _mm256_maddubs_epi16(w[r], x)); } + } + } + let bs: [__m256i; A] = std::array::from_fn(|a| _mm256_zextsi128_si256(_mm_loadu_si128(xs[a][half].bs.as_ptr().add(offset / 16).cast()))); + let dots: [[__m256i; A]; R] = std::array::from_fn(|r| std::array::from_fn(|a| _mm256_madd_epi16(_mm256_sub_epi16(sums[r][a], bs[a]), ones))); + let d: [f32; R] = std::array::from_fn(|r| d16(&rows[r][34 * i + 32..])); + if R * A == 8 { + let t = hsum8(std::array::from_fn(|k| dots[k / A][k % A])); + let sc: [f32; 8] = std::array::from_fn(|k| d[k / A] * xs[k % A][half].d); + let sc = _mm256_setr_ps(sc[0], sc[1], sc[2], sc[3], sc[4], sc[5], sc[6], sc[7]); + accv = _mm256_fmadd_ps(sc, _mm256_cvtepi32_ps(t), accv); + } else { + for r in 0..R { + for a in 0..A { accs[r][a] = (d[r] * xs[a][half].d).mul_add(hsum_i32(dots[r][a]) as f32, accs[r][a]); } + } + } + } + if R * A == 8 { + let mut lanes = [0f32; 8]; + _mm256_storeu_ps(lanes.as_mut_ptr(), accv); + for (k, v) in lanes.into_iter().enumerate() { accs[k / A][k % A] = v; } + } + accs + } + } + + /// The four vectors follow the PTQ1_0 file's interleaved trit layout. Each 16-bit + /// multiplier selects a power of three for two packed bytes. Masking after the + /// multiply isolates the low byte, independently of the adjacent byte. + #[inline(always)] + fn ptq1_0(row: &[u8], xs: [&[Q8K]; N]) -> [f32; N] { + unsafe { + let powers = |lo, hi| _mm256_set_m128i(_mm_set1_epi16(hi), _mm_set1_epi16(lo)); + let c0 = powers(1, 3); + let c1 = powers(9, 27); + let c2 = _mm256_set_m128i(_mm_set_epi64x(0x0003000300030003, 0x0001000100010001), _mm_set1_epi16(81)); + let c3 = _mm256_setr_epi16(9, 9, 9, 9, 27, 27, 27, 27, 81, 81, 81, 81, 1, 3, 9, 27); + let tail = _mm_setr_epi8(4, 5, 6, 7, 8, 9, 10, 11, 4, 5, 6, 7, 8, 9, 10, 11); + let last = _mm_setr_epi8(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 12, 13, 12, 13, 12, 13); + let ones = _mm256_set1_epi8(1); + let byte_mask = _mm256_set1_epi16(255); + let trits = |packed, pow| { + let even = _mm256_and_si256(_mm256_mullo_epi16(packed, pow), byte_mask); + let odd = _mm256_slli_epi16::<8>(_mm256_mullo_epi16(_mm256_srli_epi16::<8>(packed), pow)); + let biased = _mm256_xor_si256(_mm256_or_si256(even, odd), _mm256_set1_epi8(-128)); + _mm256_sub_epi8(_mm256_set1_epi8(-1), _mm256_add_epi8( + _mm256_cmpgt_epi8(biased, _mm256_set1_epi8(-43)), + _mm256_cmpgt_epi8(biased, _mm256_set1_epi8(42)), + )) + }; + let mut acc = [_mm256_setzero_ps(); N]; + for (i, b) in row.chunks_exact(28).enumerate() { + let head = _mm_loadu_si128(b.as_ptr().cast()); + let end = _mm_loadu_si128(b.as_ptr().add(12).cast()); + let repeated = _mm256_broadcastsi128_si256(head); + let weights = [ + trits(repeated, c0), + trits(repeated, c1), + trits(_mm256_set_m128i(_mm_shuffle_epi8(end, tail), head), c2), + trits(_mm256_set_m128i(_mm_shuffle_epi8(end, last), _mm_shuffle_epi8(end, tail)), c3), + ]; + let d = d16(&b[26..]); + for (acc, x) in acc.iter_mut().zip(xs) { + let y = &x[i / 2]; + let offset = 128 * (i % 2); + let mut sum = _mm256_setzero_si256(); + for (g, w) in weights.into_iter().enumerate() { + let signed = _mm256_sign_epi8(q8(y, offset + 32 * g), w); + sum = _mm256_add_epi16(sum, _mm256_maddubs_epi16(ones, signed)); + } + let dot = _mm256_madd_epi16(sum, _mm256_set1_epi16(1)); + *acc = _mm256_fmadd_ps(_mm256_set1_ps(d * y.d), _mm256_cvtepi32_ps(dot), *acc); + } + } + acc.map(|v| hsum(v)) + } + } + /// Ternary `TQ1_0` (54 bytes = 256 trits in `{-1, 0, +1}`, f16 `d`): unpack `u_n = trit + 1` in `{0, 1, 2}` /// via `(3 * (v * 3^n mod 256)) >> 8` (`> 85` and `> 170`), dot against signed `Q8K` with `_mm256_maddubs_epi16`, /// and subtract `y.bs` once per block to account for the `-1` offset. @@ -622,18 +965,23 @@ mod avx2 { } /// `dot_iq4nl` of one row with four activations (see `super::int_dot4`). - pub fn dot4_iq4nl(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + #[inline(always)] + pub fn dot4_iq4nl(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dotn_iq4nl(row, xq) } + #[inline(always)] pub fn dot8_iq4nl(row: &[u8], xq: [&[Q8K]; 8]) -> [f32; 8] { dotn_iq4nl(row, xq) } + #[inline(always)] pub fn dot16_iq4nl(row: &[u8], xq: [&[Q8K]; 16]) -> [f32; 16] { dotn_iq4nl(row, xq) } + #[inline(always)] + fn dotn_iq4nl(row: &[u8], xq: [&[Q8K]; N]) -> [f32; N] { unsafe { let values = _mm_loadu_si128(KVALUES_IQ4NL.as_ptr() as *const __m128i); let (m4, ones) = (_mm_set1_epi8(0xF), _mm256_set1_epi16(1)); // Sums of the even and of the odd blocks, as the two accumulators of `dot_iq4nl`. - let (mut even, mut odd) = ([_mm256_setzero_ps(); 4], [_mm256_setzero_ps(); 4]); - let blk = |b: &[u8], i: usize, acc: &mut [__m256; 4]| { + let (mut even, mut odd) = ([_mm256_setzero_ps(); N], [_mm256_setzero_ps(); N]); + let blk = |b: &[u8], i: usize, acc: &mut [__m256; N]| { let bits = _mm_loadu_si128(b.as_ptr().add(2) as *const __m128i); let w = _mm256_set_m128i(_mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4)), _mm_shuffle_epi8(values, _mm_and_si128(bits, m4))); let aw = _mm256_sign_epi8(w, w); - for k in 0..4 { + for k in 0..N { let y = &xq[k][i / 8]; let p16 = _mm256_maddubs_epi16(aw, _mm256_sign_epi8(q8(y, i % 8 * 32), w)); acc[k] = _mm256_fmadd_ps(ds(b, y.d), _mm256_cvtepi32_ps(_mm256_madd_epi16(p16, ones)), acc[k]); @@ -696,7 +1044,44 @@ mod avx2 { } } - pub fn dot_iq2s(row: &[u8], xq: &[Q8K]) -> f32 { + /// `dot_iq2xxs` of one row with four activations (see `super::int_dot4`): the grid, signs and scale once. + #[inline(always)] + pub fn dot4_iq2xxs(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dotn_iq2xxs(row, xq) } + /// Eight activations a row read (`super::int_dot8`), the same sums as one at a time. + #[inline(always)] pub fn dot8_iq2xxs(row: &[u8], xq: [&[Q8K]; 8]) -> [f32; 8] { dotn_iq2xxs(row, xq) } + #[inline(always)] pub fn dot8_iq2xs(row: &[u8], xq: [&[Q8K]; 8]) -> [f32; 8] { dotn_iq2xs(row, xq) } + #[inline(always)] pub fn dot8_iq2s(row: &[u8], xq: [&[Q8K]; 8]) -> [f32; 8] { dotn_iq2s(row, xq) } + #[inline(always)] pub fn dot8_iq3xxs(row: &[u8], xq: [&[Q8K]; 8]) -> [f32; 8] { dotn_iq3xxs(row, xq) } + #[inline(always)] pub fn dot8_iq3s(row: &[u8], xq: [&[Q8K]; 8]) -> [f32; 8] { dotn_iq3s(row, xq) } + #[inline(always)] + fn dotn_iq2xxs(row: &[u8], xq: [&[Q8K]; N]) -> [f32; N] { + unsafe { + let mut acc = [_mm256_setzero_ps(); N]; + for (i, b) in row.chunks_exact(66).enumerate() { + let mut sumi = [_mm256_setzero_si256(); N]; + for ib in 0..8 { + let g = |l: usize| IQ2XXS_GRID[b[2 + 8 * ib + l] as usize] as i64; + let aux = u32::from_le_bytes(b[6 + 8 * ib..10 + 8 * ib].try_into().unwrap()); + let s = |l: u32| sg(((aux >> (7 * l)) & 127) as usize); + let grid = _mm256_set_epi64x(g(3), g(2), g(1), g(0)); + let signs = _mm256_set_epi64x(s(3), s(2), s(1), s(0)); + let sc = _mm256_set1_epi16(2 * (aux >> 28) as i16 + 1); + for k in 0..N { + let dot = _mm256_maddubs_epi16(grid, _mm256_sign_epi8(q8(&xq[k][i], 32 * ib), signs)); + sumi[k] = _mm256_add_epi32(sumi[k], _mm256_madd_epi16(dot, sc)); + } + } + for k in 0..N { acc[k] = _mm256_fmadd_ps(ds(b, xq[k][i].d), _mm256_cvtepi32_ps(sumi[k]), acc[k]); } + } + acc.map(|a| 0.125 * hsum(a)) + } + } + + pub fn dot_iq2s(row: &[u8], xq: &[Q8K]) -> f32 { dotn_iq2s(row, [xq])[0] } + #[inline(always)] + pub fn dot4_iq2s(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dotn_iq2s(row, xq) } + #[inline(always)] + fn dotn_iq2s(row: &[u8], xq: [&[Q8K]; N]) -> [f32; N] { unsafe { // As in dot_iq3s: byte k of a lane picks sign byte k / 8, then bit k % 8. let m1 = _mm256_set_epi64x(0x0303030303030303, 0x0202020202020202, 0x0101010101010101, 0); @@ -709,8 +1094,8 @@ mod avx2 { // Scale words: the low lane takes byte 2 ib of the 16 block scales, the high lane byte 2 ib + 1. let sm0 = _mm256_set_epi64x(0x8001800180018001u64 as i64, 0x8001800180018001u64 as i64, 0x8000800080008000u64 as i64, 0x8000800080008000u64 as i64); let (sstep, n15) = (_mm256_set1_epi16(2), _mm_set1_epi8(15)); - let mut acc = _mm256_setzero_ps(); - for (b, y) in row.chunks_exact(82).zip(xq) { + let mut acc = [_mm256_setzero_ps(); N]; + for (i, b) in row.chunks_exact(82).enumerate() { let qh = _mm256_broadcastsi128_si256(_mm_loadl_epi64(b[66..74].as_ptr() as *const __m128i)); let mut idx = [0u16; 32]; for (h, hq) in [hq0, hq1].into_iter().enumerate() { @@ -721,51 +1106,63 @@ mod avx2 { let sc = _mm_loadl_epi64(b[74..82].as_ptr() as *const __m128i); let sc = _mm_unpacklo_epi8(_mm_and_si128(sc, n15), _mm_and_si128(_mm_srli_epi16(sc, 4), n15)); let sc = _mm256_broadcastsi128_si256(_mm_add_epi8(_mm_add_epi8(sc, sc), _mm_set1_epi8(1))); - let (mut sm, mut sumi) = (sm0, _mm256_setzero_si256()); + let (mut sm, mut sumi) = (sm0, [_mm256_setzero_si256(); N]); for ib in 0..8 { let g = |l: usize| IQ2S_GRID[idx[4 * ib + l] as usize & 1023] as i64; let grid = _mm256_set_epi64x(g(3), g(2), g(1), g(0)); let sb = i32::from_le_bytes(b[34 + 4 * ib..38 + 4 * ib].try_into().unwrap()); let s = _mm256_cmpeq_epi8(_mm256_and_si256(_mm256_shuffle_epi8(_mm256_set1_epi32(sb), m1), m2), m2); - let dot = _mm256_maddubs_epi16(grid, _mm256_sub_epi8(_mm256_xor_si256(s, q8(y, 32 * ib)), s)); - sumi = _mm256_add_epi32(sumi, _mm256_madd_epi16(dot, _mm256_shuffle_epi8(sc, sm))); + let ls = _mm256_shuffle_epi8(sc, sm); + for k in 0..N { + let dot = _mm256_maddubs_epi16(grid, _mm256_sub_epi8(_mm256_xor_si256(s, q8(&xq[k][i], 32 * ib)), s)); + sumi[k] = _mm256_add_epi32(sumi[k], _mm256_madd_epi16(dot, ls)); + } sm = _mm256_add_epi16(sm, sstep); } - acc = _mm256_fmadd_ps(ds(b, y.d), _mm256_cvtepi32_ps(sumi), acc); + for k in 0..N { acc[k] = _mm256_fmadd_ps(ds(b, xq[k][i].d), _mm256_cvtepi32_ps(sumi[k]), acc[k]); } } - 0.125 * hsum(acc) + acc.map(|a| 0.125 * hsum(a)) } } - /// Products of 32 IQ1 grid values (-1, 0, 1) with q8, in pairs (maddubs needs an unsigned first operand). + pub fn dot_iq1s(row: &[u8], xq: &[Q8K]) -> f32 { dotn_iq1s(row, [xq])[0] } #[inline(always)] - unsafe fn dot1(g: __m256i, q: __m256i) -> __m256i { unsafe { _mm256_maddubs_epi16(_mm256_sign_epi8(g, g), _mm256_sign_epi8(q, g)) } } - - pub fn dot_iq1s(row: &[u8], xq: &[Q8K]) -> f32 { + pub fn dot4_iq1s(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dotn_iq1s(row, xq) } + #[inline(always)] + fn dotn_iq1s(row: &[u8], xq: [&[Q8K]; N]) -> [f32; N] { unsafe { - let mut acc = _mm256_setzero_ps(); - let mut sumf = 0.0; - for (b, y) in row.chunks_exact(50).zip(xq) { - let mut sumi = _mm256_setzero_si256(); + let mut acc = [_mm256_setzero_ps(); N]; + let mut sumf = [0f32; N]; + for (i, b) in row.chunks_exact(50).enumerate() { + let mut sumi = [_mm256_setzero_si256(); N]; for ib in 0..8 { let qh = u16::from_le_bytes([b[34 + 2 * ib], b[35 + 2 * ib]]) as usize; let g = |l: usize| IQ1S_GRID[b[2 + 4 * ib + l] as usize | ((qh >> (3 * l)) & 7) << 8] as i64; - let ls = 2 * ((qh >> 12) & 7) as i32 + 1; - let p = dot1(_mm256_set_epi64x(g(3), g(2), g(1), g(0)), q8(y, 32 * ib)); - sumi = _mm256_add_epi32(sumi, _mm256_madd_epi16(p, _mm256_set1_epi16(ls as i16))); + let ls = _mm256_set1_epi16(2 * ((qh >> 12) & 7) as i16 + 1); + // Grid values (-1, 0, 1) times q8 in pairs: maddubs needs an unsigned first operand, so |g| and sign(q8, g). + let grid = _mm256_set_epi64x(g(3), g(2), g(1), g(0)); + let ag = _mm256_sign_epi8(grid, grid); + for k in 0..N { + let p = _mm256_maddubs_epi16(ag, _mm256_sign_epi8(q8(&xq[k][i], 32 * ib), grid)); + sumi[k] = _mm256_add_epi32(sumi[k], _mm256_madd_epi16(p, ls)); + } } // Delta term: sum of ±scale (sign in bit 15 of qh) times each 32 values' q8 sum. let qh = _mm_loadu_si128(b[34..50].as_ptr() as *const __m128i); let ls = _mm_or_si128(_mm_slli_epi16(_mm_and_si128(_mm_srli_epi16(qh, 12), _mm_set1_epi16(7)), 1), _mm_set1_epi16(1)); let ls = _mm_sign_epi16(ls, _mm_or_si128(qh, _mm_set1_epi16(1))); - let bs = |i: usize| _mm_loadu_si128(y.bs[8 * i..].as_ptr() as *const __m128i); - let s = _mm_add_epi32(_mm_madd_epi16(_mm_unpacklo_epi16(ls, ls), bs(0)), _mm_madd_epi16(_mm_unpackhi_epi16(ls, ls), bs(1))); - let s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0b01_00_11_10)); - let s1 = _mm_cvtsi128_si32(_mm_add_epi32(s, _mm_shuffle_epi32(s, 0b10_11_00_01))); - acc = _mm256_fmadd_ps(ds(b, y.d), _mm256_cvtepi32_ps(sumi), acc); - sumf += d16(b) * y.d * 0.125 * s1 as f32; + let (l0, l1) = (_mm_unpacklo_epi16(ls, ls), _mm_unpackhi_epi16(ls, ls)); + for k in 0..N { + let y = &xq[k][i]; + let bs = |i: usize| _mm_loadu_si128(y.bs[8 * i..].as_ptr() as *const __m128i); + let s = _mm_add_epi32(_mm_madd_epi16(l0, bs(0)), _mm_madd_epi16(l1, bs(1))); + let s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0b01_00_11_10)); + let s1 = _mm_cvtsi128_si32(_mm_add_epi32(s, _mm_shuffle_epi32(s, 0b10_11_00_01))); + acc[k] = _mm256_fmadd_ps(ds(b, y.d), _mm256_cvtepi32_ps(sumi[k]), acc[k]); + sumf[k] += d16(b) * y.d * 0.125 * s1 as f32; + } } - hsum(acc) + sumf + std::array::from_fn(|k| hsum(acc[k]) + sumf[k]) } } @@ -780,33 +1177,41 @@ mod avx2 { t }); - pub fn dot_iq1m(row: &[u8], xq: &[Q8K]) -> f32 { + pub fn dot_iq1m(row: &[u8], xq: &[Q8K]) -> f32 { dotn_iq1m(row, [xq])[0] } + #[inline(always)] + pub fn dot4_iq1m(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dotn_iq1m(row, xq) } + #[inline(always)] + fn dotn_iq1m(row: &[u8], xq: [&[Q8K]; N]) -> [f32; N] { unsafe { let (t, nine) = (&**IQ1M_W, _mm256_set1_epi8(9)); - let mut acc = _mm256_setzero_ps(); - for (b, y) in row.chunks_exact(56).zip(xq) { + let mut acc = [_mm256_setzero_ps(); N]; + for (i, b) in row.chunks_exact(56).enumerate() { // Weights 8 * grid + delta (-9..=9), so one 0.125 at the end gives grid + delta / 8. The table holds // them plus 9 (unsigned for maddubs), taken off the pair sums again with 9 * q8. let sc = u64::from_le_bytes(b[48..56].try_into().unwrap()); let ls: [i16; 16] = std::array::from_fn(|i| 2 * ((sc >> (16 * (i / 4) + 3 * (i % 4))) & 7) as i16 + 1); - let mut sumi = _mm256_setzero_si256(); + let mut sumi = [_mm256_setzero_si256(); N]; for ib in 0..8 { - let ls = |h: usize| ls[2 * ib + h] as i32; + let lsv = _mm256_set_m128i(_mm_set1_epi16(ls[2 * ib + 1]), _mm_set1_epi16(ls[2 * ib])); let qh = u16::from_le_bytes([b[32 + 2 * ib], b[33 + 2 * ib]]) as usize; let g = |l: usize| t[b[4 * ib + l] as usize | ((qh >> (4 * l)) & 15) << 8] as i64; - let q = q8(y, 32 * ib); - let p = _mm256_sub_epi16(_mm256_maddubs_epi16(_mm256_set_epi64x(g(3), g(2), g(1), g(0)), q), _mm256_maddubs_epi16(nine, q)); - sumi = _mm256_add_epi32(sumi, udot_scale(p, ls(0), ls(1))); + let grid = _mm256_set_epi64x(g(3), g(2), g(1), g(0)); + for k in 0..N { + let q = q8(&xq[k][i], 32 * ib); + let p = _mm256_sub_epi16(_mm256_maddubs_epi16(grid, q), _mm256_maddubs_epi16(nine, q)); + sumi[k] = _mm256_add_epi32(sumi[k], _mm256_madd_epi16(p, lsv)); + } } - acc = _mm256_fmadd_ps(_mm256_set1_ps(iq1m_d(b) * y.d), _mm256_cvtepi32_ps(sumi), acc); + let d = iq1m_d(b); + for k in 0..N { acc[k] = _mm256_fmadd_ps(_mm256_set1_ps(d * xq[k][i].d), _mm256_cvtepi32_ps(sumi[k]), acc[k]); } } - 0.125 * hsum(acc) + acc.map(|a| 0.125 * hsum(a)) } } pub fn dot_q2k(row: &[u8], xq: &[Q8K]) -> f32 { unsafe { - let mut acc = _mm256_setzero_ps(); + let mut sumf = 0f32; for (b, y) in row.chunks_exact(84).zip(xq) { let sc = &b[0..16]; let mut sumi = _mm256_setzero_si256(); @@ -819,16 +1224,75 @@ mod avx2 { } let mins = _mm256_cvtepu8_epi16(_mm_and_si128(_mm_srli_epi16(_mm_loadu_si128(sc.as_ptr() as *const __m128i), 4), _mm_set1_epi8(0xF))); let m = _mm256_madd_epi16(mins, _mm256_loadu_si256(y.bs.as_ptr() as *const __m256i)); - acc = _mm256_fmadd_ps(_mm256_set1_ps(y.d * d16(&b[80..])), _mm256_cvtepi32_ps(sumi), acc); - acc = _mm256_fmadd_ps(_mm256_set1_ps(-y.d * d16(&b[82..])), _mm256_cvtepi32_ps(m), acc); + sumf += y.d * d16(&b[80..]) * hsum_i32(sumi) as f32 - y.d * d16(&b[82..]) * hsum_i32(m) as f32; } - hsum(acc) + sumf + } + } + + /// `dot_q2k` of one row with four activations (see `super::int_dot4`). + #[inline(always)] + pub fn dot4_q2k(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + unsafe { + let mut sumf = [0f32; 4]; + for (i, b) in row.chunks_exact(84).enumerate() { + let sc = &b[0..16]; + let mut sumi = [_mm256_setzero_si256(); 4]; + for n in 0..2 { + let bits = ld(b, 16 + 32 * n); + for kk in 0..4 { + let g = 8 * n + 2 * kk; + let w = crumb(bits, kk); + for k in 0..4 { + sumi[k] = _mm256_add_epi32(sumi[k], udot32(w, q8(&xq[k][i], 32 * (4 * n + kk)), (sc[g] & 0xF) as i32, (sc[g + 1] & 0xF) as i32)); + } + } + } + let mins = _mm256_cvtepu8_epi16(_mm_and_si128(_mm_srli_epi16(_mm_loadu_si128(sc.as_ptr() as *const __m128i), 4), _mm_set1_epi8(0xF))); + let (d, dm) = (d16(&b[80..]), d16(&b[82..])); + let m: [__m256i; 4] = std::array::from_fn(|k| _mm256_madd_epi16(mins, _mm256_loadu_si256(xq[k][i].bs.as_ptr() as *const __m256i))); + let h: [i32; 8] = std::mem::transmute(hsum8([sumi[0], sumi[1], sumi[2], sumi[3], m[0], m[1], m[2], m[3]])); + for k in 0..4 { let y = &xq[k][i]; sumf[k] += y.d * d * h[k] as f32 - y.d * dm * h[4 + k] as f32; } + } + sumf + } + } + + /// `dot_q3k` of one row with four activations (see `super::int_dot4`). + #[inline(always)] + pub fn dot4_q3k(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + unsafe { + let mut sumf = [0f32; 4]; + for (i, b) in row.chunks_exact(110).enumerate() { + let (hm, sc) = (ld(b, 0), crate::quant::q3k_scales(b)); + let mut sumi = [_mm256_setzero_si256(); 4]; + for n in 0..2 { + let bits = ld(b, 32 + 32 * n); + for kk4 in 0..4 { + let kk = 4 * n + kk4; + let mask = _mm256_set1_epi8(1 << kk); + let low = _mm256_cmpeq_epi8(_mm256_and_si256(hm, mask), _mm256_setzero_si256()); + let w = _mm256_sub_epi8(crumb(bits, kk4), _mm256_and_si256(low, _mm256_set1_epi8(4))); + let aw = _mm256_sign_epi8(w, w); + let s = _mm256_set_m128i(_mm_set1_epi16(sc[2 * kk + 1] as i16 - 32), _mm_set1_epi16(sc[2 * kk] as i16 - 32)); + for k in 0..4 { + let p = _mm256_maddubs_epi16(aw, _mm256_sign_epi8(q8(&xq[k][i], 32 * kk), w)); + sumi[k] = _mm256_add_epi32(sumi[k], _mm256_madd_epi16(p, s)); + } + } + } + let d = d16(&b[108..]); + let z = _mm256_setzero_si256(); + let h: [i32; 8] = std::mem::transmute(hsum8([sumi[0], sumi[1], sumi[2], sumi[3], z, z, z, z])); + for k in 0..4 { sumf[k] += d * xq[k][i].d * h[k] as f32; } + } + sumf } } pub fn dot_q3k(row: &[u8], xq: &[Q8K]) -> f32 { unsafe { - let mut acc = _mm256_setzero_ps(); + let mut sumf = 0f32; for (b, y) in row.chunks_exact(110).zip(xq) { let (hm, sc) = (ld(b, 0), crate::quant::q3k_scales(b)); let mut sumi = _mm256_setzero_si256(); @@ -845,9 +1309,9 @@ mod avx2 { sumi = _mm256_add_epi32(sumi, _mm256_madd_epi16(p, s)); } } - acc = _mm256_fmadd_ps(_mm256_set1_ps(y.d * d16(&b[108..])), _mm256_cvtepi32_ps(sumi), acc); + sumf += d16(&b[108..]) * y.d * hsum_i32(sumi) as f32; } - hsum(acc) + sumf } } @@ -893,6 +1357,39 @@ mod avx2 { } } + /// `dot_q2_0` of one row with four activations (see `super::int_dot4`): each block's crumbs are decoded once, + /// and every lane runs `dot_q2_0`'s operations in its order. + pub fn dot4_q2_0(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dotn_q2_0(row, xq) } + #[inline(always)] pub fn dot8_q2_0(row: &[u8], xq: [&[Q8K]; 8]) -> [f32; 8] { dotn_q2_0(row, xq) } + #[inline(always)] pub fn dot16_q2_0(row: &[u8], xq: [&[Q8K]; 16]) -> [f32; 16] { dotn_q2_0(row, xq) } + #[inline(always)] + fn dotn_q2_0(row: &[u8], xq: [&[Q8K]; N]) -> [f32; N] { + unsafe { + let (mut acc, mut sumf) = ([_mm256_setzero_ps(); N], [0f32; N]); + let ones = _mm256_set1_epi16(1); + for (i, sb) in row.chunks(72).enumerate() { + let m: [[f32; 8]; N] = std::array::from_fn(|k| { + let bs = _mm256_madd_epi16(_mm256_loadu_si256(xq[k][i].bs.as_ptr() as *const __m256i), ones); + let mut m = [0f32; 8]; + _mm256_storeu_ps(m.as_mut_ptr(), _mm256_cvtepi32_ps(_mm256_hadd_epi32(bs, bs))); + m + }); + for (j, b) in sb.chunks_exact(18).enumerate() { + let (w0, w1) = q2_0_crumbs(b); + let db = d16(b); + for k in 0..N { + let y = &xq[k][i]; + let p = _mm256_add_epi16(_mm256_maddubs_epi16(w0, q8(y, 64 * j)), _mm256_maddubs_epi16(w1, q8(y, 64 * j + 32))); + let d = db * y.d; + acc[k] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(_mm256_madd_epi16(p, ones)), acc[k]); + sumf[k] -= d * m[k][j + j / 2 * 2]; + } + } + } + std::array::from_fn(|k| hsum(acc[k]) + sumf[k]) + } + } + /// Q4_0, Q4_1, Q5_0, Q5_1 (scalar `dot_q4`). pub fn dot_q4(row: &[u8], xq: &[Q8K]) -> f32 { let (bb, oh, oq) = super::q4_layout(T); @@ -916,59 +1413,389 @@ mod avx2 { } } - pub fn dot_q4k(row: &[u8], xq: &[Q8K]) -> f32 { + /// Horizontal sum of eight i32. + #[inline(always)] + unsafe fn hsum_i32(v: __m256i) -> i32 { unsafe { + let s = _mm_add_epi32(_mm256_castsi256_si128(v), _mm256_extracti128_si256::<1>(v)); + let s = _mm_add_epi32(s, _mm_unpackhi_epi64(s, s)); + _mm_cvtsi128_si32(_mm_add_epi32(s, _mm_shuffle_epi32::<1>(s))) + } } + + /// Lane j: the sum of the eight i32 of `v[j]` (exact, as eight `hsum_i32`). + #[inline(always)] + unsafe fn hsum8(v: [__m256i; 8]) -> __m256i { unsafe { + let a = _mm256_hadd_epi32(_mm256_hadd_epi32(v[0], v[1]), _mm256_hadd_epi32(v[2], v[3])); + let b = _mm256_hadd_epi32(_mm256_hadd_epi32(v[4], v[5]), _mm256_hadd_epi32(v[6], v[7])); + _mm256_add_epi32(_mm256_permute2x128_si256::<0x20>(a, b), _mm256_permute2x128_si256::<0x31>(a, b)) + } } + + /// Q8_0 times activation `y` over the blocks (up to 8, one Q8_K block) at `b`, added to `sumf` in the steps of + /// the scalar `dot_q8_0`: d16 * y.d * sum per block, in order. + #[inline(always)] + unsafe fn q8_0_8(b: &[u8], y: &Q8K, sumf: &mut f32) { unsafe { + let ones = _mm256_set1_epi16(1); + let s = |j: usize| { + let w = _mm256_loadu_si256(b[34 * j + 2..].as_ptr() as *const __m256i); + _mm256_madd_epi16(_mm256_maddubs_epi16(_mm256_sign_epi8(w, w), _mm256_sign_epi8(q8(y, 32 * j), w)), ones) + }; + if b.len() < 272 { + for j in 0..b.len() / 34 { *sumf += d16(&b[34 * j..]) * y.d * hsum_i32(s(j)) as f32; } + return; + } + let d = _mm256_mul_ps(_mm256_setr_ps(d16(b), d16(&b[34..]), d16(&b[68..]), d16(&b[102..]), d16(&b[136..]), d16(&b[170..]), d16(&b[204..]), d16(&b[238..])), _mm256_set1_ps(y.d)); + for v in std::mem::transmute::<__m256, [f32; 8]>(_mm256_mul_ps(d, _mm256_cvtepi32_ps(hsum8(std::array::from_fn(s))))) { *sumf += v; } + } } + + /// Q4_K with the integer sums of the scalar `dot_q4k` and its float steps per block in its order, so this, + /// `dot4_q4k` and the 8-row prefill kernel `q4k_x8` give the same bits. + pub fn dot_q4k(row: &[u8], xq: &[Q8K]) -> f32 { dot4_q4k_n(row, [xq])[0] } + + /// `dot_q4k` of one row with four activations (see `super::int_dot4`). + #[inline(always)] + pub fn dot4_q4k(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { dot4_q4k_n(row, xq) } + + #[inline(always)] + fn dot4_q4k_n(row: &[u8], xq: [&[Q8K]; T]) -> [f32; T] { unsafe { let m4 = _mm256_set1_epi8(0xF); - let mut acc = _mm256_setzero_ps(); - let mut sumf = 0.0; - for (b, y) in row.chunks_exact(144).zip(xq) { + let mut sumf = [0f32; T]; + for (i, b) in row.chunks_exact(144).enumerate() { let sm: [(u8, u8); 8] = std::array::from_fn(|j| crate::quant::scale_min_k4(j, &b[4..16])); - let mut sumi = _mm256_setzero_si256(); + let mut sumi = [_mm256_setzero_si256(); T]; for j in 0..4 { let bits = ld(b, 16 + 32 * j); let (s0, s1) = (sm[2 * j].0 as i32, sm[2 * j + 1].0 as i32); - sumi = _mm256_add_epi32(sumi, udot32(_mm256_and_si256(bits, m4), q8(y, 64 * j), s0, s0)); - sumi = _mm256_add_epi32(sumi, udot32(_mm256_and_si256(_mm256_srli_epi16(bits, 4), m4), q8(y, 64 * j + 32), s1, s1)); + let (w0, w1) = (_mm256_and_si256(bits, m4), _mm256_and_si256(_mm256_srli_epi16(bits, 4), m4)); + for k in 0..T { + let y = &xq[k][i]; + sumi[k] = _mm256_add_epi32(sumi[k], udot32(w0, q8(y, 64 * j), s0, s0)); + sumi[k] = _mm256_add_epi32(sumi[k], udot32(w1, q8(y, 64 * j + 32), s1, s1)); + } + } + let (d, dm) = (d16(b), d16(&b[2..])); + for k in 0..T { + let y = &xq[k][i]; + let m: i32 = (0..8).map(|j| sm[j].1 as i32 * (y.bs[2 * j] + y.bs[2 * j + 1]) as i32).sum(); + sumf[k] += d * y.d * hsum_i32(sumi[k]) as f32 - dm * y.d * m as f32; } - let m: i32 = (0..8).map(|j| sm[j].1 as i32 * (y.bs[2 * j] + y.bs[2 * j + 1]) as i32).sum(); - acc = _mm256_fmadd_ps(_mm256_set1_ps(y.d * d16(b)), _mm256_cvtepi32_ps(sumi), acc); - sumf -= y.d * d16(&b[2..]) * m as f32; } - hsum(acc) + sumf + sumf } } - /// Q8_0 (scalar `dot_q8_0`): |w| times q8 with w's sign, as maddubs needs an unsigned first operand. - pub fn dot_q8_0(row: &[u8], xq: &[Q8K]) -> f32 { - unsafe { - let (ones, mut acc) = (_mm256_set1_epi16(1), _mm256_setzero_ps()); - for (i, b) in row.chunks_exact(34).enumerate() { - let (y, o) = (&xq[i / 8], i % 8 * 32); - let w = _mm256_loadu_si256(b[2..34].as_ptr() as *const __m256i); - let p = _mm256_maddubs_epi16(_mm256_sign_epi8(w, w), _mm256_sign_epi8(q8(y, o), w)); - acc = _mm256_fmadd_ps(ds(b, y.d), _mm256_cvtepi32_ps(_mm256_madd_epi16(p, ones)), acc); + /// Eight bytes at `p` as eight i32 lanes. + #[inline(always)] + unsafe fn lanes(p: *const u8) -> __m256i { unsafe { _mm256_cvtepu8_epi32(_mm_loadl_epi64(p as *const __m128i)) } } + + /// Interleaves 8 Q4_K rows of `rb` bytes from `w` into `tile` (`super::X8_BLOCK` per block of 256 columns). + pub fn repack_q4k_x8(w: &[u8], rb: usize, tile: &mut [u8]) { + let (k1, k2, k3) = (0x3f3f3f3fu32, 0x0f0f0f0fu32, 0x03030303u32); + for (i, t) in tile.chunks_exact_mut(super::X8_BLOCK).enumerate() { + let b: [&[u8]; 8] = std::array::from_fn(|r| &w[r * rb + 144 * i..][..144]); + for r in 0..8 { + t[4 * r..4 * r + 4].copy_from_slice(&d16(b[r]).to_le_bytes()); + t[32 + 4 * r..36 + 4 * r].copy_from_slice(&d16(&b[r][2..]).to_le_bytes()); + // The 8 scales and 8 mins of `scale_min_k4`, four at a time (llama.cpp's utmp masks). + let u = |o: usize| u32::from_le_bytes(b[r][4 + o..8 + o].try_into().unwrap()); + let (u0, u1, u2) = (u(0), u(4), u(8)); + let sc = (u0 & k1) as u64 | (((u2 & k2) | ((u0 >> 6) & k3) << 4) as u64) << 32; + let mn = (u1 & k1) as u64 | ((((u2 >> 4) & k2) | ((u1 >> 6) & k3) << 4) as u64) << 32; + for s in 0..8 { t[64 + 8 * s + r] = (sc >> (8 * s)) as u8; t[128 + 8 * s + r] = (mn >> (8 * s)) as u8; } + } + // The 4-byte runs: an 8x8 transpose of 32-bit lanes per 32 bytes of the 8 rows. + unsafe { + for c in 0..4 { runs8(std::array::from_fn(|r| ld(b[r], 16 + 32 * c)), t.as_mut_ptr().add(192 + 256 * c)); } } - hsum(acc) } } - /// `dot_q8_0` of one row with four activations (see `super::int_dot4`). - pub fn dot4_q8_0(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { - unsafe { - let (ones, mut acc) = (_mm256_set1_epi16(1), [_mm256_setzero_ps(); 4]); - for (i, b) in row.chunks_exact(34).enumerate() { - let w = _mm256_loadu_si256(b[2..34].as_ptr() as *const __m256i); - let aw = _mm256_sign_epi8(w, w); - for k in 0..4 { - let y = &xq[k][i / 8]; - let p = _mm256_maddubs_epi16(aw, _mm256_sign_epi8(q8(y, i % 8 * 32), w)); - acc[k] = _mm256_fmadd_ps(ds(b, y.d), _mm256_cvtepi32_ps(_mm256_madd_epi16(p, ones)), acc[k]); + /// 32 bytes of each of 8 rows as 8 runs of 4 bytes at `o`: run k (32 bytes at o + 32k) holds bytes 4k..4k+4 of + /// rows 0..8 in row order (an 8x8 transpose of 32-bit lanes). + #[inline(always)] + unsafe fn runs8(v: [__m256i; 8], o: *mut u8) { unsafe { + let t0: [__m256i; 4] = std::array::from_fn(|h| _mm256_unpacklo_epi32(v[2 * h], v[2 * h + 1])); + let t1: [__m256i; 4] = std::array::from_fn(|h| _mm256_unpackhi_epi32(v[2 * h], v[2 * h + 1])); + let u = [_mm256_unpacklo_epi64(t0[0], t0[1]), _mm256_unpackhi_epi64(t0[0], t0[1]), _mm256_unpacklo_epi64(t1[0], t1[1]), _mm256_unpackhi_epi64(t1[0], t1[1]), + _mm256_unpacklo_epi64(t0[2], t0[3]), _mm256_unpackhi_epi64(t0[2], t0[3]), _mm256_unpacklo_epi64(t1[2], t1[3]), _mm256_unpackhi_epi64(t1[2], t1[3])]; + for k in 0..4 { + _mm256_storeu_si256(o.add(32 * k) as *mut __m256i, _mm256_permute2x128_si256::<0x20>(u[k], u[k + 4])); + _mm256_storeu_si256(o.add(32 * k + 128) as *mut __m256i, _mm256_permute2x128_si256::<0x31>(u[k], u[k + 4])); + } + } } + + /// Interleaves 8 Q6_K rows of `rb` bytes from `w` into `tile` (`super::Q6_X8_BLOCK` per block of 256 columns): + /// d[8] as f32 (32), the 16 scales as [group][row] bytes (128), and the 256 unsigned 6-bit codes of each row in + /// value order as 64 runs of 4 bytes, run k of rows 0..8 together (2048). A weight is d * scale * (code - 32). + pub fn repack_q6k_x8(w: &[u8], rb: usize, tile: &mut [u8]) { + for (i, t) in tile.chunks_exact_mut(super::Q6_X8_BLOCK).enumerate() { + let b: [&[u8]; 8] = std::array::from_fn(|r| &w[r * rb + 210 * i..][..210]); + for r in 0..8 { + t[4 * r..4 * r + 4].copy_from_slice(&d16(&b[r][208..]).to_le_bytes()); + for g in 0..16 { t[32 + 8 * g + r] = b[r][192 + g]; } + } + // The codes as `dot_q6k` builds them: vector 4n + k holds values 128n + 32k .. +32. + unsafe { + let m4 = _mm256_set1_epi8(0xF); + for n in 0..2 { + for k in 0..4 { + let code = |r: usize| { + let lo = ld(b[r], 64 * n + 32 * (k % 2)); + let lo = if k < 2 { _mm256_and_si256(lo, m4) } else { _mm256_and_si256(_mm256_srli_epi16(lo, 4), m4) }; + _mm256_or_si256(lo, _mm256_slli_epi16(crumb(ld(b[r], 128 + 32 * n), k), 4)) + }; + runs8(std::array::from_fn(code), t.as_mut_ptr().add(160 + 256 * (4 * n + k))); + } } } - acc.map(|a| hsum(a)) } } + /// 8 Q3_K rows in the layout of `repack_q6k_x8`: d[8], the 16 scales less 32 as signed bytes, and the codes plus + /// 4 (0..8), so a weight is d * scale * (code - 4), as in `dot_q3k`. + pub fn repack_q3k_x8(w: &[u8], rb: usize, tile: &mut [u8]) { + for (i, t) in tile.chunks_exact_mut(super::Q6_X8_BLOCK).enumerate() { + let b: [&[u8]; 8] = std::array::from_fn(|r| &w[r * rb + 110 * i..][..110]); + for r in 0..8 { + t[4 * r..4 * r + 4].copy_from_slice(&d16(&b[r][108..]).to_le_bytes()); + let sc = crate::quant::q3k_scales(b[r]); + for g in 0..16 { t[32 + 8 * g + r] = (sc[g] as i32 - 32) as i8 as u8; } + } + unsafe { + for v in 0..8 { + // Values 32v..32v+32: crumb v % 4 of the bytes at 32 + 32(v / 4), plus 4 where bit v of the mask is set. + let code = |r: usize| { + let hi = _mm256_and_si256(_mm256_srl_epi16(ld(b[r], 0), _mm_cvtsi32_si128(v as i32)), _mm256_set1_epi8(1)); + _mm256_or_si256(crumb(ld(b[r], 32 + 32 * (v / 4)), v % 4), _mm256_slli_epi16(hi, 2)) + }; + runs8(std::array::from_fn(code), t.as_mut_ptr().add(160 + 256 * v)); + } + } + } + } + + /// 8 Q2_K rows in a `super::Q2_X8_BLOCK` tile: the layout of `repack_q6k_x8` with the 4-bit scales and the codes + /// (0..4), then dmin[8] as f32 (2208) and the 16 mins as [group][row] bytes (2240), as in `dot_q2k`. + pub fn repack_q2k_x8(w: &[u8], rb: usize, tile: &mut [u8]) { + for (i, t) in tile.chunks_exact_mut(super::Q2_X8_BLOCK).enumerate() { + let b: [&[u8]; 8] = std::array::from_fn(|r| &w[r * rb + 84 * i..][..84]); + for r in 0..8 { + t[4 * r..4 * r + 4].copy_from_slice(&d16(&b[r][80..]).to_le_bytes()); + t[2208 + 4 * r..2212 + 4 * r].copy_from_slice(&d16(&b[r][82..]).to_le_bytes()); + for g in 0..16 { t[32 + 8 * g + r] = b[r][g] & 0xF; t[2240 + 8 * g + r] = b[r][g] >> 4; } + } + unsafe { + for v in 0..8 { runs8(std::array::from_fn(|r| crumb(ld(b[r], 16 + 32 * (v / 4)), v % 4)), t.as_mut_ptr().add(160 + 256 * v)); } + } + } + } + + /// The low 16 bits of the i32 lanes of `lo` and `hi` as one i16 pair a lane, for `_mm256_madd_epi16`. + #[inline(always)] + unsafe fn pair16(lo: __m256i, hi: __m256i) -> __m256i { unsafe { _mm256_or_si256(_mm256_and_si256(lo, _mm256_set1_epi32(0xFFFF)), _mm256_slli_epi32(hi, 16)) } } + + /// The 16-group k-quants (Q6_K, Q3_K, Q2_K) times `T` activations for the 8 rows of a tile of `BB` bytes a block + /// (`repack_q6k_x8`, `repack_q3k_x8`, `repack_q2k_x8`), as `q4k_x8`: lane r collects row r. A weight is + /// d * scale * (code - OFF), less dmin * min where the block holds mins (Q2_K). Per row the integer sums and float + /// steps are those of the scalar dot, so the bits are the same. `V`: VNNI `vpdpbusd` (only in a caller with + /// AVX-512VL/VNNI), else maddubs. + #[inline(always)] + pub fn k16_x8(tile: &[u8], xq: [&[Q8K]; T]) -> [[f32; 8]; T] { + unsafe { + let mut acc = [_mm256_setzero_ps(); T]; + for (i, t) in tile.chunks_exact(BB).enumerate() { + let p = t.as_ptr(); + let sc: [__m256i; 16] = std::array::from_fn(|g| _mm256_cvtepi8_epi32(_mm_loadl_epi64(p.add(32 + 8 * g) as *const __m128i))); + let mut isum = [_mm256_setzero_si256(); T]; + for g in 0..16 { + // Group g: 16 values in 4 runs; codes <= 63 times q8 <= 128, two pairs a lane, stay within i16. + let w: [__m256i; 4] = std::array::from_fn(|k| _mm256_loadu_si256(p.add(160 + 32 * (4 * g + k)) as *const __m256i)); + let s2 = pair16(sc[g], sc[g]); + for u in 0..T { + let q = xq[u][i].qs.as_ptr().add(16 * g); + let qb = |k: usize| _mm256_set1_epi32((q.add(4 * k) as *const i32).read_unaligned()); + if V { + let mut a = _mm256_dpbusd_epi32(_mm256_setzero_si256(), w[0], qb(0)); + for k in 1..4 { a = _mm256_dpbusd_epi32(a, w[k], qb(k)); } + isum[u] = _mm256_add_epi32(isum[u], _mm256_mullo_epi32(a, sc[g])); + } else { + let a = _mm256_add_epi16(_mm256_maddubs_epi16(w[0], qb(0)), _mm256_maddubs_epi16(w[1], qb(1))); + let b = _mm256_add_epi16(_mm256_maddubs_epi16(w[2], qb(2)), _mm256_maddubs_epi16(w[3], qb(3))); + isum[u] = _mm256_add_epi32(isum[u], _mm256_add_epi32(_mm256_madd_epi16(a, s2), _mm256_madd_epi16(b, s2))); + } + } + } + let d = _mm256_loadu_ps(p as *const f32); + // Scales (and Q2_K mins) of groups 2q and 2q+1 as i16 pairs, against the pairs of activation group sums. + let sp: [__m256i; 8] = std::array::from_fn(|q| pair16(sc[2 * q], sc[2 * q + 1])); + let mins = BB > super::Q6_X8_BLOCK; + let mp: [__m256i; 8] = std::array::from_fn(|q| if mins { pair16(lanes(p.add(2240 + 16 * q)), lanes(p.add(2248 + 16 * q))) } else { _mm256_setzero_si256() }); + for u in 0..T { + let y = &xq[u][i]; + let bp = |q: usize| _mm256_set1_epi32(y.bs[2 * q] as u16 as i32 | (y.bs[2 * q + 1] as i32) << 16); + let mut s = isum[u]; + if OFF != 0 { + // The -OFF offset: OFF times the sum over groups of scale times activation group sum. + let mut m = _mm256_setzero_si256(); + for q in 0..8 { m = _mm256_add_epi32(m, _mm256_madd_epi16(sp[q], bp(q))); } + s = _mm256_sub_epi32(s, _mm256_mullo_epi32(m, _mm256_set1_epi32(OFF))); + } + let yd = _mm256_set1_ps(y.d); + let mut v = _mm256_mul_ps(_mm256_mul_ps(d, yd), _mm256_cvtepi32_ps(s)); + if mins { + let mut m = _mm256_setzero_si256(); + for q in 0..8 { m = _mm256_add_epi32(m, _mm256_madd_epi16(mp[q], bp(q))); } + v = _mm256_sub_ps(v, _mm256_mul_ps(_mm256_mul_ps(_mm256_loadu_ps(p.add(2208) as *const f32), yd), _mm256_cvtepi32_ps(m))); + } + acc[u] = _mm256_add_ps(acc[u], v); + } + } + std::array::from_fn(|u| std::mem::transmute::<__m256, [f32; 8]>(acc[u])) + } + } + + /// Q4_K times `T` activations for the 8 rows of a `repack_q4k_x8` tile: one 32-byte load serves 8 rows, + /// each activation run of 4 bytes is broadcast, and the i32 lane r collects row r (llama.cpp's + /// `ggml_gemm_q4_K_8x8_q8_K` idea). Per row the integer sums and float steps are those of the scalar `dot_q4k`, + /// so the bits are the same. `V` as in `k16_x8`. + #[inline(always)] + pub fn q4k_x8(tile: &[u8], xq: [&[Q8K]; T]) -> [[f32; 8]; T] { + unsafe { + let m4 = _mm256_set1_epi8(0xF); + let mut acc = [_mm256_setzero_ps(); T]; + for (i, t) in tile.chunks_exact(super::X8_BLOCK).enumerate() { + let p = t.as_ptr(); + let mut isum = [_mm256_setzero_si256(); T]; + for j in 0..4 { + // Sub-blocks 2j (low nibbles) and 2j+1 (high nibbles): 8 products of 4 a lane stay within i16. + let (mut a0, mut a1) = ([_mm256_setzero_si256(); T], [_mm256_setzero_si256(); T]); + for k in 0..8 { + let w = _mm256_loadu_si256(p.add(192 + 32 * (8 * j + k)) as *const __m256i); + let (w0, w1) = (_mm256_and_si256(w, m4), _mm256_and_si256(_mm256_srli_epi16(w, 4), m4)); + for u in 0..T { + let q = xq[u][i].qs.as_ptr(); + let q0 = _mm256_set1_epi32((q.add(64 * j + 4 * k) as *const i32).read_unaligned()); + let q1 = _mm256_set1_epi32((q.add(64 * j + 32 + 4 * k) as *const i32).read_unaligned()); + if V { a0[u] = _mm256_dpbusd_epi32(a0[u], w0, q0); a1[u] = _mm256_dpbusd_epi32(a1[u], w1, q1); } + else { a0[u] = _mm256_add_epi16(a0[u], _mm256_maddubs_epi16(w0, q0)); a1[u] = _mm256_add_epi16(a1[u], _mm256_maddubs_epi16(w1, q1)); } + } + } + let (s0, s1) = (lanes(p.add(64 + 16 * j)), lanes(p.add(72 + 16 * j))); + if V { + for u in 0..T { isum[u] = _mm256_add_epi32(isum[u], _mm256_add_epi32(_mm256_mullo_epi32(a0[u], s0), _mm256_mullo_epi32(a1[u], s1))); } + } else { + // maddubs leaves i16 pairs: each i32 lane takes the scale in both halves. + let (s0, s1) = (pair16(s0, s0), pair16(s1, s1)); + for u in 0..T { isum[u] = _mm256_add_epi32(isum[u], _mm256_add_epi32(_mm256_madd_epi16(a0[u], s0), _mm256_madd_epi16(a1[u], s1))); } + } + } + let (d, dm) = (_mm256_loadu_ps(p as *const f32), _mm256_loadu_ps(p.add(32) as *const f32)); + // Lane r: the mins of sub-blocks 2q and 2q+1 as an i16 pair. + let mp: [__m256i; 4] = std::array::from_fn(|q| _mm256_or_si256(lanes(p.add(128 + 16 * q)), _mm256_slli_epi32(lanes(p.add(136 + 16 * q)), 16))); + for u in 0..T { + let y = &xq[u][i]; + let mut ms = _mm256_setzero_si256(); + for q in 0..4 { + let pr = (y.bs[4 * q] + y.bs[4 * q + 1]) as u16 as i32 | ((y.bs[4 * q + 2] + y.bs[4 * q + 3]) as i32) << 16; + ms = _mm256_add_epi32(ms, _mm256_madd_epi16(mp[q], _mm256_set1_epi32(pr))); + } + let yd = _mm256_set1_ps(y.d); + let v = _mm256_sub_ps(_mm256_mul_ps(_mm256_mul_ps(d, yd), _mm256_cvtepi32_ps(isum[u])), _mm256_mul_ps(_mm256_mul_ps(dm, yd), _mm256_cvtepi32_ps(ms))); + acc[u] = _mm256_add_ps(acc[u], v); + } + } + std::array::from_fn(|u| std::mem::transmute::<__m256, [f32; 8]>(acc[u])) + } + } + + /// Interleaves 8 Q8_0 rows into `tile` (`super::Q8_X8_BLOCK` per block of 32 columns): d[8] as f32 (32) and the + /// 32 values of each row as 8 runs of 4 bytes, run k of rows 0..8 together (256). + pub fn repack_q8_0_x8(w: &[u8], rb: usize, tile: &mut [u8]) { + for (i, t) in tile.chunks_exact_mut(super::Q8_X8_BLOCK).enumerate() { + let b: [&[u8]; 8] = std::array::from_fn(|r| &w[r * rb + 34 * i..][..34]); + for r in 0..8 { t[4 * r..4 * r + 4].copy_from_slice(&d16(b[r]).to_le_bytes()); } + unsafe { runs8(std::array::from_fn(|r| ld(b[r], 2)), t.as_mut_ptr().add(32)); } + } + } + + /// Q8_0 times `T` activations for the 8 rows of a `repack_q8_0_x8` tile, as `q4k_x8`; the bits of the scalar + /// `dot_q8_0` per row. With VNNI the weights go in as w + 128 (unsigned) and 128 times the activation sum comes + /// off; maddubs takes |w| and moves w's sign onto the activation instead. + #[inline(always)] + pub fn q8_0_x8(tile: &[u8], xq: [&[Q8K]; T]) -> [[f32; 8]; T] { + unsafe { + let mut acc = [_mm256_setzero_ps(); T]; + for (i, t) in tile.chunks_exact(super::Q8_X8_BLOCK).enumerate() { + let (p, j, o) = (t.as_ptr(), i / 8, i % 8 * 32); + let mut s = [_mm256_setzero_si256(); T]; + for k in 0..8 { + let w = _mm256_loadu_si256(p.add(32 + 32 * k) as *const __m256i); + let qb = |u: usize| _mm256_set1_epi32((xq[u][j].qs.as_ptr().add(o + 4 * k) as *const i32).read_unaligned()); + if V { + let uw = _mm256_xor_si256(w, _mm256_set1_epi8(-128)); + for u in 0..T { s[u] = _mm256_dpbusd_epi32(s[u], uw, qb(u)); } + } else { + let aw = _mm256_sign_epi8(w, w); + for u in 0..T { s[u] = _mm256_add_epi32(s[u], _mm256_madd_epi16(_mm256_maddubs_epi16(aw, _mm256_sign_epi8(qb(u), w)), _mm256_set1_epi16(1))); } + } + } + let d = _mm256_loadu_ps(p as *const f32); + for u in 0..T { + let y = &xq[u][j]; + let s = if V { _mm256_sub_epi32(s[u], _mm256_set1_epi32(128 * (y.bs[o / 16] as i32 + y.bs[o / 16 + 1] as i32))) } else { s[u] }; + acc[u] = _mm256_add_ps(acc[u], _mm256_mul_ps(_mm256_mul_ps(d, _mm256_set1_ps(y.d)), _mm256_cvtepi32_ps(s))); + } + } + std::array::from_fn(|u| std::mem::transmute::<__m256, [f32; 8]>(acc[u])) + } + } + + /// `super::rows_x8` for Q4_K, Q6_K, Q3_K, Q2_K and Q8_0 (false for another type); `V` as in `k16_x8`. + #[inline(always)] + pub fn rows_x8(ty: GgmlType, w: &[u8], rb: usize, xq: &[Vec], sc: f32, o: &mut [f32]) -> bool { + macro_rules! go { ($repack:path, $bb:expr, $tb:expr, $kern:ident $(, $g:expr)*) => {{ + let n = xq.len(); + let mut tile = vec![0u8; rb / $bb * $tb]; + for (g, o) in o.chunks_exact_mut(8 * n).enumerate() { + $repack(&w[8 * g * rb..8 * (g + 1) * rb], rb, &mut tile); + let mut put = |t: usize, v: [f32; 8]| for (r, v) in v.into_iter().enumerate() { o[r * n + t] = v * sc; }; + let mut t = 0; + while t + 4 <= n { + let v = $kern::<4, V $(, {$g})*>(&tile, [&xq[t][..], &xq[t + 1], &xq[t + 2], &xq[t + 3]]); + for (u, v) in v.into_iter().enumerate() { put(t + u, v); } + t += 4; + } + for t in t..n { put(t, $kern::<1, V $(, {$g})*>(&tile, [&xq[t][..]])[0]); } + } + true + }}; } + use super::{Q2_X8_BLOCK, Q6_X8_BLOCK, Q8_X8_BLOCK, X8_BLOCK}; + match ty { + GgmlType::Q4K => go!(repack_q4k_x8, 144, X8_BLOCK, q4k_x8), + GgmlType::Q6K => go!(repack_q6k_x8, 210, Q6_X8_BLOCK, k16_x8, 32, Q6_X8_BLOCK), + GgmlType::Q3K => go!(repack_q3k_x8, 110, Q6_X8_BLOCK, k16_x8, 4, Q6_X8_BLOCK), + GgmlType::Q2K => go!(repack_q2k_x8, 84, Q2_X8_BLOCK, k16_x8, 0, Q2_X8_BLOCK), + GgmlType::Q8_0 => go!(repack_q8_0_x8, 34, Q8_X8_BLOCK, q8_0_x8), + _ => false, + } + } + + /// Q8_0 (scalar `dot_q8_0`): |w| times q8 with w's sign, as maddubs needs an unsigned first operand. + pub fn dot_q8_0(row: &[u8], xq: &[Q8K]) -> f32 { + let mut sumf = 0f32; + for (b, y) in row.chunks(272).zip(xq) { unsafe { q8_0_8(b, y, &mut sumf) } } + sumf + } + + /// `dot_q8_0` of one row with four activations (see `super::int_dot4`). + #[inline(always)] + pub fn dot4_q8_0(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + let mut sumf = [0f32; 4]; + for (i, b) in row.chunks(272).enumerate() { + for k in 0..4 { unsafe { q8_0_8(b, &xq[k][i], &mut sumf[k]) } } + } + sumf + } + pub fn dot_q5k(row: &[u8], xq: &[Q8K]) -> f32 { unsafe { let (m4, one) = (_mm256_set1_epi8(0xF), _mm256_set1_epi8(1)); @@ -996,12 +1823,82 @@ mod avx2 { } } + /// `dot_q5k` of one row with four activations (see `super::int_dot4`). + #[inline(always)] + pub fn dot4_q5k(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + unsafe { + let (m4, one) = (_mm256_set1_epi8(0xF), _mm256_set1_epi8(1)); + let hb = |qh: __m256i, k: i32| _mm256_slli_epi16(_mm256_and_si256(_mm256_srl_epi16(qh, _mm_cvtsi32_si128(k)), one), 4); + let (mut acc, mut sumf) = ([_mm256_setzero_ps(); 4], [0f32; 4]); + for (i, b) in row.chunks_exact(176).enumerate() { + let sm: [(u8, u8); 8] = std::array::from_fn(|j| crate::quant::scale_min_k4(j, &b[4..16])); + let qh = ld(b, 16); + let mut sumi = [_mm256_setzero_si256(); 4]; + for j in 0..4 { + let bits = ld(b, 48 + 32 * j); + let (s0, s1) = (sm[2 * j].0 as i32, sm[2 * j + 1].0 as i32); + let w0 = _mm256_or_si256(_mm256_and_si256(bits, m4), hb(qh, 2 * j as i32)); + let w1 = _mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(bits, 4), m4), hb(qh, 2 * j as i32 + 1)); + for k in 0..4 { + let y = &xq[k][i]; + sumi[k] = _mm256_add_epi32(sumi[k], udot32(w0, q8(y, 64 * j), s0, s0)); + sumi[k] = _mm256_add_epi32(sumi[k], udot32(w1, q8(y, 64 * j + 32), s1, s1)); + } + } + let (d, dm) = (d16(b), d16(&b[2..])); + for k in 0..4 { + let y = &xq[k][i]; + let m: i32 = (0..8).map(|j| sm[j].1 as i32 * (y.bs[2 * j] + y.bs[2 * j + 1]) as i32).sum(); + acc[k] = _mm256_fmadd_ps(_mm256_set1_ps(y.d * d), _mm256_cvtepi32_ps(sumi[k]), acc[k]); + sumf[k] -= y.d * dm * m as f32; + } + } + std::array::from_fn(|k| hsum(acc[k]) + sumf[k]) + } + } + + /// `dot_q6k` of one row with four activations (see `super::int_dot4`). + #[inline(always)] + pub fn dot4_q6k(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + unsafe { + let m4 = _mm256_set1_epi8(0xF); + let mut sumf = [0f32; 4]; + for (i, b) in row.chunks_exact(210).enumerate() { + let sc = |g: usize| b[192 + g] as i8 as i32; + let mut sumi = [_mm256_setzero_si256(); 4]; + for n in 0..2 { + let (la, lb, qh) = (ld(b, 64 * n), ld(b, 64 * n + 32), ld(b, 128 + 32 * n)); + let hi = |k: usize| _mm256_slli_epi16(crumb(qh, k), 4); + let w = [ + _mm256_or_si256(_mm256_and_si256(la, m4), hi(0)), + _mm256_or_si256(_mm256_and_si256(lb, m4), hi(1)), + _mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(la, 4), m4), hi(2)), + _mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(lb, 4), m4), hi(3)), + ]; + for (kk, w) in w.into_iter().enumerate() { + let g = 8 * n + 2 * kk; + for k in 0..4 { + sumi[k] = _mm256_add_epi32(sumi[k], udot32(w, q8(&xq[k][i], 128 * n + 32 * kk), sc(g), sc(g + 1))); + } + } + } + let d6 = d16(&b[208..]); + for k in 0..4 { + let y = &xq[k][i]; + let m: i32 = (0..16).map(|g| sc(g) * y.bs[g] as i32).sum(); + sumf[k] += d6 * y.d * (hsum_i32(sumi[k]) - 32 * m) as f32; + } + } + sumf + } + } + /// Q6_K with unsigned 6-bit codes (maddubs needs an unsigned first operand); the -32 offset comes off through - /// the Q8_K group sums. + /// the Q8_K group sums. Each block is added in the scalar `dot_q6k`'s order, so this, `dot4_q6k` and the 8-row + /// prefill kernel `q6k_x8` give the same bits. pub fn dot_q6k(row: &[u8], xq: &[Q8K]) -> f32 { unsafe { let m4 = _mm256_set1_epi8(0xF); - let mut acc = _mm256_setzero_ps(); let mut sumf = 0.0; for (b, y) in row.chunks_exact(210).zip(xq) { let sc = |g: usize| b[192 + g] as i8 as i32; @@ -1021,12 +1918,301 @@ mod avx2 { } } let m: i32 = (0..16).map(|g| sc(g) * y.bs[g] as i32).sum(); - let d = y.d * d16(&b[208..]); - acc = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc); - sumf -= 32.0 * d * m as f32; + sumf += d16(&b[208..]) * y.d * (hsum_i32(sumi) - 32 * m) as f32; } - hsum(acc) + sumf + sumf + } + } + + /// A trellis row (blocks of B bytes for 128 values) times Q8_K activations: the int16 codebook of + /// `quant::TQ_STATES_I16`, one 8-byte table row per state, `_mm256_madd_epi16` against the sign-extended + /// activations. Two trellis blocks share one Q8_K block. Not the bits of the f32 kernel (`STRATA_TQ_F32=1` keeps that one). + pub fn dot_tq_i(row: &[u8], xq: &[Q8K]) -> f32 { + unsafe { + let tab = crate::quant::TQ_STATES_I16.as_ptr() as *const i64; + let rows4 = |s: [usize; 4]| _mm256_setr_epi64x(*tab.add(s[0]), *tab.add(s[1]), *tab.add(s[2]), *tab.add(s[3])); + let mut acc = _mm256_setzero_ps(); + for (i, b) in row.chunks_exact(B).enumerate() { + let (qs, y) = (&b[2..B], &xq[i / 2]); + let a = y.qs.as_ptr().add(128 * (i % 2)); + let buf = crate::quant::tq_stream(qs); + let st = |t: usize| crate::quant::tq_state_in(&buf, qs, t); + let mut sum = _mm256_setzero_si256(); + for m in 0..8 { + let w = rows4([0, 1, 2, 3].map(|k| st(4 * m + k))); + let x = _mm256_cvtepi8_epi16(_mm_loadu_si128(a.add(16 * m) as *const __m128i)); + sum = _mm256_add_epi32(sum, _mm256_madd_epi16(w, x)); + } + acc = _mm256_fmadd_ps(_mm256_set1_ps(d16(b) * y.d), _mm256_cvtepi32_ps(sum), acc); + } + hsum(acc) * (1.0 / 8192.0) + } + } + + /// Byte indices and shifts of the 32 states of a TQK block of n = B - 2 stream bytes: state t is the u32 at byte + /// off >> 3 (wrapping at n, as `tq_stream`), shifted by off & 7, with off = (31 - t) * n / 4. + const fn tq_lanes(n: usize) -> ([[u8; 64]; 2], [[u32; 16]; 2]) { + let (mut idx, mut sh) = ([[0u8; 64]; 2], [[0u32; 16]; 2]); + let mut t = 0; + while t < 32 { + let off = (31 - t) * (n / 4); + let mut j = 0; + while j < 4 { idx[t / 16][4 * (t % 16) + j] = ((off / 8 + j) % n) as u8; j += 1; } + sh[t / 16][t % 16] = (off % 8) as u32; + t += 1; + } + (idx, sh) + } + + /// `dot_tq_i` for TQK6/TQK7 (B = 26, 30) with AVX-512: a VBMI byte permute and a shift give 16 states at once, + /// and `vpdpwssd` sums 32 products of 8 table rows. Lanes l and l + 8 of its 512-bit sum add up to lane l of + /// `dot_tq_i`'s and the float steps are the same, so the result is the same bits. 7600X, one thread, best of 15: + /// 16.4 -> 12.6 ns a block (TQK6), 16.3 -> 12.7 (TQK7); a gather for the 8 table rows took 12.9. + #[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512vnni,avx512vbmi")] + unsafe fn dot_tq_v512(row: &[u8], xq: &[Q8K]) -> f32 { unsafe { + let (idx, sh) = const { tq_lanes(B - 2) }; + let tab = crate::quant::TQ_STATES_I16.as_ptr() as *const i64; + let (i0, i1) = (_mm512_loadu_si512(idx[0].as_ptr() as *const _), _mm512_loadu_si512(idx[1].as_ptr() as *const _)); + let (h0, h1) = (_mm512_loadu_si512(sh[0].as_ptr() as *const _), _mm512_loadu_si512(sh[1].as_ptr() as *const _)); + let (m15, keep) = (_mm512_set1_epi32(0x7fff), (1u64 << (B - 2)) - 1); + let mut acc = _mm256_setzero_ps(); + let mut st = [0u32; 32]; + for (i, b) in row.chunks_exact(B).enumerate() { + let y = &xq[i / 2]; + let a = y.qs.as_ptr().add(128 * (i % 2)); + let v = _mm512_maskz_loadu_epi8(keep, b.as_ptr().add(2) as *const i8); + _mm512_storeu_si512(st.as_mut_ptr() as *mut _, _mm512_and_si512(_mm512_srlv_epi32(_mm512_permutexvar_epi8(i0, v), h0), m15)); + _mm512_storeu_si512(st.as_mut_ptr().add(16) as *mut _, _mm512_and_si512(_mm512_srlv_epi32(_mm512_permutexvar_epi8(i1, v), h1), m15)); + let mut sum = _mm512_setzero_si512(); + for g in 0..4 { + let r = |k: usize| *tab.add(st[8 * g + k] as usize); + let w = _mm512_setr_epi64(r(0), r(1), r(2), r(3), r(4), r(5), r(6), r(7)); + let x = _mm512_cvtepi8_epi16(_mm256_loadu_si256(a.add(32 * g) as *const __m256i)); + sum = _mm512_dpwssd_epi32(sum, w, x); + } + let sum = _mm256_add_epi32(_mm512_castsi512_si256(sum), _mm512_extracti64x4_epi64::<1>(sum)); + acc = _mm256_fmadd_ps(_mm256_set1_ps(d16(b) * y.d), _mm256_cvtepi32_ps(sum), acc); + } + hsum(acc) * (1.0 / 8192.0) + } } + + /// `dot_tq_v512`; only for a CPU with its features (`int_dot` checks). + pub fn dot_tq_v(row: &[u8], xq: &[Q8K]) -> f32 { unsafe { dot_tq_v512::(row, xq) } } + + pub fn has_avx512_tq() -> bool { + is_x86_feature_detected!("avx512f") && is_x86_feature_detected!("avx512bw") && is_x86_feature_detected!("avx512vl") + && is_x86_feature_detected!("avx512vnni") && is_x86_feature_detected!("avx512vbmi") + } + + /// The four-activation kernels above compiled again with AVX-512VL/VNNI, picked at run time (`super::int_dot4`). + /// The source and the order of the sums are the same, so are the bits; the compiler gets 32 vector registers, + /// vpdpwssd and vpternlog, which makes prefill up to 1.4x faster on Zen 4 in a binary built for x86-64-v3. + pub mod vl { + use super::*; + macro_rules! vl4 { ($($f:ident)*) => { $( + pub fn $f(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + #[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512vnni")] + unsafe fn k(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { super::$f(row, xq) } + unsafe { k(row, xq) } + } + )* } } + macro_rules! vl8 { ($($f:ident)*) => { $( + pub fn $f(row: &[u8], xq: [&[Q8K]; 8]) -> [f32; 8] { + #[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512vnni")] + unsafe fn k(row: &[u8], xq: [&[Q8K]; 8]) -> [f32; 8] { super::$f(row, xq) } + unsafe { k(row, xq) } + } + )* } } + vl8!(dot8_iq2xxs dot8_iq2xs dot8_iq2s dot8_iq3xxs dot8_iq3s dot8_q2_0 dot8_iq4nl); + macro_rules! vl16 { ($($f:ident)*) => { $( + pub fn $f(row: &[u8], xq: [&[Q8K]; 16]) -> [f32; 16] { + #[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512vnni")] + unsafe fn k(row: &[u8], xq: [&[Q8K]; 16]) -> [f32; 16] { super::$f(row, xq) } + unsafe { k(row, xq) } + } + )* } } + vl16!(dot16_q2_0 dot16_iq4nl); + vl4!(dot4_q8_0 dot4_iq4nl dot4_q5k dot4_q6k dot4_q4k dot4_q2k dot4_q3k dot4_iq2xxs dot4_iq2xs dot4_iq2s dot4_iq3xxs dot4_iq3s dot4_iq1s dot4_iq1m dot4_q2_0 dot4_iq4xs); + + /// The 8-row prefill tiles with VNNI `vpdpbusd`. + pub fn rows_x8(ty: GgmlType, w: &[u8], rb: usize, xq: &[Vec], sc: f32, o: &mut [f32]) -> bool { + #[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512vnni")] + unsafe fn k(ty: GgmlType, w: &[u8], rb: usize, xq: &[Vec], sc: f32, o: &mut [f32]) -> bool { super::rows_x8::(ty, w, rb, xq, sc, o) } + unsafe { k(ty, w, rb, xq, sc, o) } + } + } + + pub fn has_avx512_vl() -> bool { + is_x86_feature_detected!("avx512f") && is_x86_feature_detected!("avx512bw") && is_x86_feature_detected!("avx512vl") + && is_x86_feature_detected!("avx512vnni") + } + + /// AVX-512 single-activation dots of the grid types whose signs are a 7-bit field plus its parity (IQ2_XXS, + /// IQ2_XS, IQ3_XXS): two sub-blocks (64 weights) per step, the grid by a gather, the signs as a byte mask made + /// with `pdep` (KSIGNS_IQ2XS[i] is i with its parity in bit 7) instead of a table load per 8 weights, and + /// `vpdpbusd`. Each superblock ends with the eight integer lane sums of the AVX2 kernel (lane j: bytes 4j..4j+3 + /// of every sub-block, times its scale), which then take the same float steps, so the bits are the AVX2 kernel's. + /// Picked at run time (`super::int_dot`) where the CPU has AVX-512 VNNI and BMI2. + pub mod z { + use super::*; + + pub fn has() -> bool { super::has_avx512_vl() && is_x86_feature_detected!("bmi2") } + + /// Sign masks of 8-weight groups: byte l of `bits7` is the 7-bit field of group l; bit 7 becomes its parity. + #[inline(always)] + fn with_parity(bits7: u64) -> u64 { + let mut p = bits7 ^ (bits7 >> 4); + p ^= p >> 2; + p ^= p >> 1; + bits7 | ((p & 0x0101010101010101) << 7) } + + /// The eight 32-bit lanes of the AVX2 kernel's `sumi`: lanes j and j + 8 of `v` added. + #[inline(always)] + unsafe fn fold(v: __m512i) -> __m256i { unsafe { _mm256_add_epi32(_mm512_castsi512_si256(v), _mm512_extracti64x4_epi64::<1>(v)) } } + + #[inline(always)] + unsafe fn q8z(y: &Q8K, i: usize) -> __m512i { unsafe { _mm512_loadu_si512(y.qs.as_ptr().add(i) as *const _) } } + + #[inline(always)] + fn rd32(b: &[u8], o: usize) -> u32 { u32::from_le_bytes(b[o..o + 4].try_into().unwrap()) } + + /// Scales of two sub-blocks, one for each 32 weights (lanes 0..7, 8..15). + #[inline(always)] + unsafe fn ls2(a: i32, b: i32) -> __m512i { unsafe { _mm512_inserti64x4::<1>(_mm512_set1_epi32(a), _mm256_set1_epi32(b)) } } + /// Scales of two sub-blocks, one for each 16 weights (bytes `s0`, `s1`: low then high nibble). + #[inline(always)] + unsafe fn ls4(s0: i32, s1: i32) -> __m512i { unsafe { + let (a, c, e, f) = (2 * (s0 & 15) + 1, 2 * (s0 >> 4) + 1, 2 * (s1 & 15) + 1, 2 * (s1 >> 4) + 1); + _mm512_setr_epi32(a, a, a, a, c, c, c, c, e, e, e, e, f, f, f, f) + } } + + // Decoders: the grid bytes, the sign mask and the scales of sub-blocks ib and ib + 1 of super-block b. + #[inline(always)] + unsafe fn dec_iq2xxs(b: &[u8], ib: usize) -> (__m512i, u64, __m512i) { unsafe { + let (a0, a1) = (rd32(b, 6 + 8 * ib), rd32(b, 14 + 8 * ib)); + // Eight table loads: measured a little faster than a gather for this type. + let gt = |i: usize| IQ2XXS_GRID[b[2 + 8 * ib + i] as usize] as i64; + let grid = _mm512_set_epi64(gt(11), gt(10), gt(9), gt(8), gt(3), gt(2), gt(1), gt(0)); + let m = with_parity(_pdep_u32(a0 & 0x0fff_ffff, 0x7f7f_7f7f) as u64 | (_pdep_u32(a1 & 0x0fff_ffff, 0x7f7f_7f7f) as u64) << 32); + (grid, m, ls2(2 * (a0 >> 28) as i32 + 1, 2 * (a1 >> 28) as i32 + 1)) + } } + #[inline(always)] + unsafe fn dec_iq2xs(b: &[u8], ib: usize) -> (__m512i, u64, __m512i) { unsafe { + // The eight u16 of sub-blocks ib and ib + 1: 9-bit grid index, 7-bit sign field. + let v = _mm_loadu_si128(b.as_ptr().add(2 + 8 * ib) as *const __m128i); + let grid = _mm512_i64gather_epi64::<8>(_mm512_cvtepu16_epi64(_mm_and_si128(v, _mm_set1_epi16(511))), IQ2XS_GRID.as_ptr() as *const _); + let s7 = _mm_packus_epi16(_mm_and_si128(_mm_srli_epi16::<9>(v), _mm_set1_epi16(127)), _mm_setzero_si128()); + (grid, with_parity(_mm_cvtsi128_si64(s7) as u64), ls4(b[66 + ib] as i32, b[67 + ib] as i32)) + } } + #[inline(always)] + unsafe fn dec_iq3xxs(b: &[u8], ib: usize) -> (__m512i, u64, __m512i) { unsafe { + let idx = _mm512_cvtepu8_epi32(_mm_loadu_si128(b.as_ptr().add(2 + 8 * ib) as *const __m128i)); + let grid = _mm512_i32gather_epi32::<4>(idx, IQ3XXS_GRID.as_ptr() as *const _); + let (a0, a1) = (rd32(b, 66 + 4 * ib), rd32(b, 70 + 4 * ib)); + let m = with_parity(_pdep_u32(a0 & 0x0fff_ffff, 0x7f7f_7f7f) as u64 | (_pdep_u32(a1 & 0x0fff_ffff, 0x7f7f_7f7f) as u64) << 32); + (grid, m, ls2(2 * (a0 >> 28) as i32 + 1, 2 * (a1 >> 28) as i32 + 1)) + } } + // IQ3_S and IQ2_S keep their sign bits as bytes: the mask is the 8 bytes of two sub-blocks as they are. + #[inline(always)] + unsafe fn dec_iq3s(b: &[u8], ib: usize) -> (__m512i, u64, __m512i) { unsafe { + let lo = _mm512_cvtepu8_epi32(_mm_loadu_si128(b.as_ptr().add(2 + 8 * ib) as *const __m128i)); + let idx = _mm512_mask_or_epi32(lo, b[66 + ib] as u16 | (b[67 + ib] as u16) << 8, lo, _mm512_set1_epi32(256)); + let grid = _mm512_i32gather_epi32::<4>(idx, IQ3S_GRID.as_ptr() as *const _); + let m = u64::from_le_bytes(b[74 + 4 * ib..82 + 4 * ib].try_into().unwrap()); + let sc = b[106 + ib / 2] as i32; + (grid, m, ls2(2 * (sc & 15) + 1, 2 * (sc >> 4) + 1)) + } } + #[inline(always)] + unsafe fn dec_iq2s(b: &[u8], ib: usize) -> (__m512i, u64, __m512i) { unsafe { + // Index of group l: its qs byte, plus bits 2l, 2l + 1 of its sub-block's qh byte as bits 8, 9. + let lo = _mm512_cvtepu8_epi64(_mm_cvtsi64_si128(i64::from_le_bytes(b[2 + 4 * ib..10 + 4 * ib].try_into().unwrap()))); + let qh = _mm512_inserti64x4::<1>(_mm512_set1_epi64(b[66 + ib] as i64), _mm256_set1_epi64x(b[67 + ib] as i64)); + let hi = _mm512_and_si512(_mm512_srlv_epi64(qh, _mm512_setr_epi64(0, 2, 4, 6, 0, 2, 4, 6)), _mm512_set1_epi64(3)); + let grid = _mm512_i64gather_epi64::<8>(_mm512_or_si512(lo, _mm512_slli_epi64::<8>(hi)), IQ2S_GRID.as_ptr() as *const _); + let m = u64::from_le_bytes(b[34 + 4 * ib..42 + 4 * ib].try_into().unwrap()); + (grid, m, ls4(b[74 + ib] as i32, b[75 + ib] as i32)) + } } + + /// N dots of one row: each pair of sub-blocks decoded once, then per activation a masked negate, `vpdpbusd` + /// and the scales; each super-block ends with the AVX2 kernel's eight lane sums (`fold`), so its bits. + #[inline(always)] + unsafe fn dotn(row: &[u8], xq: [&[Q8K]; N], fin: f32, dec: unsafe fn(&[u8], usize) -> (__m512i, u64, __m512i)) -> [f32; N] { unsafe { + let mut acc = [_mm256_setzero_ps(); N]; + let zero = _mm512_setzero_si512(); + for (i, b) in row.chunks_exact(BB).enumerate() { + let mut sumi = [_mm512_setzero_si512(); N]; + for ib in (0..8).step_by(2) { + let (grid, m, ls) = dec(b, ib); + for k in 0..N { + let q = q8z(&xq[k][i], 32 * ib); + let p = _mm512_dpbusd_epi32(zero, grid, _mm512_mask_sub_epi8(q, m, zero, q)); + sumi[k] = _mm512_add_epi32(sumi[k], _mm512_mullo_epi32(p, ls)); + } + } + for k in 0..N { acc[k] = _mm256_fmadd_ps(ds(b, xq[k][i].d), _mm256_cvtepi32_ps(fold(sumi[k])), acc[k]); } + } + acc.map(|a| fin * hsum(a)) + } } + + /// `dotn` for activations stored with 128 added (`flip`, bytes xor 0x80): the signs go into the weights once a + /// block (`w`) instead of into every activation, and `vpdpbusd` takes the activation as its unsigned operand. + /// The 128 * sum(w) that adds is the same for every activation, so it is made once a block and taken off: the + /// integer sums, and so the bits, of `dotn`. One instruction fewer an activation and 64 weights. + #[inline(always)] + unsafe fn dotn_off(row: &[u8], xq: [&[Q8K]; N], fin: f32, dec: unsafe fn(&[u8], usize) -> (__m512i, u64, __m512i)) -> [f32; N] { unsafe { + let mut acc = [_mm256_setzero_ps(); N]; + let (zero, c128) = (_mm512_setzero_si512(), _mm512_set1_epi8(-128)); + for (i, b) in row.chunks_exact(BB).enumerate() { + let mut sumi = [_mm512_setzero_si512(); N]; + let mut corr = _mm512_setzero_si512(); + for ib in (0..8).step_by(2) { + let (grid, m, ls) = dec(b, ib); + let w = _mm512_mask_sub_epi8(grid, m, zero, grid); + corr = _mm512_add_epi32(corr, _mm512_mullo_epi32(_mm512_dpbusd_epi32(zero, c128, w), ls)); + for k in 0..N { + let p = _mm512_dpbusd_epi32(zero, q8z(&xq[k][i], 32 * ib), w); + sumi[k] = _mm512_add_epi32(sumi[k], _mm512_mullo_epi32(p, ls)); + } + } + for k in 0..N { acc[k] = _mm256_fmadd_ps(ds(b, xq[k][i].d), _mm256_cvtepi32_ps(fold(_mm512_sub_epi32(sumi[k], corr))), acc[k]); } + } + acc.map(|a| fin * hsum(a)) + } } + + macro_rules! zko { ($name:ident, $n:literal, $bb:literal, $fin:literal, $dec:ident) => { + pub fn $name(row: &[u8], xq: [&[Q8K]; $n]) -> [f32; $n] { + #[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512vnni,bmi2")] + unsafe fn k(row: &[u8], xq: [&[Q8K]; $n]) -> [f32; $n] { unsafe { dotn_off::<$n, $bb>(row, xq, $fin, $dec) } } + unsafe { k(row, xq) } + } + } } + zko!(dot8o_iq2xxs, 8, 66, 0.125, dec_iq2xxs); zko!(dot8o_iq2xs, 8, 74, 0.125, dec_iq2xs); zko!(dot8o_iq3xxs, 8, 98, 0.25, dec_iq3xxs); + zko!(dot8o_iq3s, 8, 110, 1.0, dec_iq3s); zko!(dot8o_iq2s, 8, 82, 0.125, dec_iq2s); + zko!(dot16o_iq2xxs, 16, 66, 0.125, dec_iq2xxs); zko!(dot16o_iq2xs, 16, 74, 0.125, dec_iq2xs); zko!(dot16o_iq3xxs, 16, 98, 0.25, dec_iq3xxs); + zko!(dot16o_iq3s, 16, 110, 1.0, dec_iq3s); zko!(dot16o_iq2s, 16, 82, 0.125, dec_iq2s); + + macro_rules! zk { ($name:ident, $n:literal, $bb:literal, $fin:literal, $dec:ident) => { + pub fn $name(row: &[u8], xq: [&[Q8K]; $n]) -> [f32; $n] { + #[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512vnni,bmi2")] + unsafe fn k(row: &[u8], xq: [&[Q8K]; $n]) -> [f32; $n] { unsafe { dotn::<$n, $bb>(row, xq, $fin, $dec) } } + unsafe { k(row, xq) } + } + } } + zk!(dot4_iq2xxs, 4, 66, 0.125, dec_iq2xxs); zk!(dot8_iq2xxs, 8, 66, 0.125, dec_iq2xxs); + zk!(dot4_iq2xs, 4, 74, 0.125, dec_iq2xs); zk!(dot8_iq2xs, 8, 74, 0.125, dec_iq2xs); + zk!(dot4_iq3xxs, 4, 98, 0.25, dec_iq3xxs); zk!(dot8_iq3xxs, 8, 98, 0.25, dec_iq3xxs); + zk!(dot4_iq3s, 4, 110, 1.0, dec_iq3s); zk!(dot8_iq3s, 8, 110, 1.0, dec_iq3s); + zk!(dot4_iq2s, 4, 82, 0.125, dec_iq2s); zk!(dot8_iq2s, 8, 82, 0.125, dec_iq2s); + zk!(dot1_iq2xxs, 1, 66, 0.125, dec_iq2xxs); zk!(dot1_iq2xs, 1, 74, 0.125, dec_iq2xs); zk!(dot1_iq3xxs, 1, 98, 0.25, dec_iq3xxs); + // Single-token IQ3_S and IQ2_S: slower than the AVX2 kernels (sign bytes are cheap there); kept for the bit test. + #[cfg(test)] zk!(dot1_iq3s, 1, 110, 1.0, dec_iq3s); + #[cfg(test)] zk!(dot1_iq2s, 1, 82, 0.125, dec_iq2s); + pub fn dot_iq2xxs(row: &[u8], xq: &[Q8K]) -> f32 { dot1_iq2xxs(row, [xq])[0] } + pub fn dot_iq2xs(row: &[u8], xq: &[Q8K]) -> f32 { dot1_iq2xs(row, [xq])[0] } + pub fn dot_iq3xxs(row: &[u8], xq: &[Q8K]) -> f32 { dot1_iq3xxs(row, [xq])[0] } + #[cfg(test)] pub fn dot_iq3s(row: &[u8], xq: &[Q8K]) -> f32 { dot1_iq3s(row, [xq])[0] } + #[cfg(test)] pub fn dot_iq2s(row: &[u8], xq: &[Q8K]) -> f32 { dot1_iq2s(row, [xq])[0] } } } @@ -1242,6 +2428,166 @@ mod avx512 { } } + /// Four-activation Q8_0 dot: decodes each 64-weight pair once and scores all 4 Q8_K vectors via `vpdpbusd`. + pub fn dot4_q8_0(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + unsafe { + let zero = _mm512_setzero_si512(); + let mut acc = [_mm512_setzero_ps(); 4]; + for (j, b2) in row.chunks_exact(68).enumerate() { + let (bi, o) = (j / 4, (j % 4) * 64); + let w0 = _mm256_loadu_si256(b2[2..34].as_ptr() as *const __m256i); + let w1 = _mm256_loadu_si256(b2[36..68].as_ptr() as *const __m256i); + let w = _mm512_inserti64x4(_mm512_castsi256_si512(w0), w1, 1); + let neg = _mm512_movepi8_mask(w); + let aw = _mm512_abs_epi8(w); + let d0 = d16(b2); + let d1 = d16(&b2[34..]); + for k in 0..4 { + let y = &xq[k][bi]; + let q = q8_512(y, o); + let p32 = _mm512_dpbusd_epi32(zero, aw, _mm512_mask_sub_epi8(q, neg, zero, q)); + let dv = _mm512_mask_blend_ps(0xFF00, _mm512_set1_ps(d0 * y.d), _mm512_set1_ps(d1 * y.d)); + acc[k] = _mm512_fmadd_ps(dv, _mm512_cvtepi32_ps(p32), acc[k]); + } + } + let mut out = std::array::from_fn(|k| _mm512_reduce_add_ps(acc[k])); + let n = row.len() / 34; + if n % 2 == 1 { + let i = n - 1; + let b = &row[34 * i..34 * i + 34]; + let (bi, o) = (i / 8, (i % 8) * 32); + let d = d16(b); + for k in 0..4 { + let y = &xq[k][bi]; + let s: i32 = b[2..34].iter().zip(&y.qs[o..o + 32]).map(|(&w, &q)| w as i8 as i32 * q as i32).sum(); + out[k] += d * y.d * s as f32; + } + } + out + } + } + + /// Four-activation IQ4_NL dot: decodes each 64-weight pair once via 512-bit `vpshufb`. + pub fn dot4_iq4nl(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + unsafe { + let values = _mm512_broadcast_i32x4(_mm_loadu_si128(KVALUES_IQ4NL.as_ptr() as *const __m128i)); + let (m4, zero) = (_mm_set1_epi8(0xF), _mm512_setzero_si512()); + let mut acc = [_mm512_setzero_ps(); 4]; + for (j, b2) in row.chunks_exact(36).enumerate() { + let (b0, b1) = (&b2[..18], &b2[18..]); + let (bi, o) = (j / 4, (j % 4) * 64); + let bits0 = _mm_loadu_si128(b0[2..].as_ptr() as *const __m128i); + let bits1 = _mm_loadu_si128(b1[2..].as_ptr() as *const __m128i); + let idx0 = _mm256_set_m128i(_mm_and_si128(_mm_srli_epi16(bits0, 4), m4), _mm_and_si128(bits0, m4)); + let idx1 = _mm256_set_m128i(_mm_and_si128(_mm_srli_epi16(bits1, 4), m4), _mm_and_si128(bits1, m4)); + let w = _mm512_shuffle_epi8(values, _mm512_inserti64x4(_mm512_castsi256_si512(idx0), idx1, 1)); + let neg = _mm512_movepi8_mask(w); + let aw = _mm512_abs_epi8(w); + let (d0, d1) = (d16(b0), d16(b1)); + for k in 0..4 { + let y = &xq[k][bi]; + let q = q8_512(y, o); + let p32 = _mm512_dpbusd_epi32(zero, aw, _mm512_mask_sub_epi8(q, neg, zero, q)); + let dv = _mm512_mask_blend_ps(0xFF00, _mm512_set1_ps(d0 * y.d), _mm512_set1_ps(d1 * y.d)); + acc[k] = _mm512_fmadd_ps(dv, _mm512_cvtepi32_ps(p32), acc[k]); + } + } + let mut out = std::array::from_fn(|k| _mm512_reduce_add_ps(acc[k])); + let n = row.len() / 18; + if n % 2 == 1 { + let i = n - 1; + let b = &row[18 * i..18 * i + 18]; + let (bi, o) = (i / 8, (i % 8) * 32); + let d = d16(b); + for k in 0..4 { + let y = &xq[k][bi]; + let mut s = 0i32; + for l in 0..16 { + s += KVALUES_IQ4NL[(b[2 + l] & 0xF) as usize] as i32 * y.qs[o + l] as i32; + s += KVALUES_IQ4NL[(b[2 + l] >> 4) as usize] as i32 * y.qs[o + 16 + l] as i32; + } + out[k] += d * y.d * s as f32; + } + } + out + } + } + + /// Four-activation IQ4_XS dot: decodes each 256-weight super-block once via 512-bit `vpshufb`. + pub fn dot4_iq4xs(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + unsafe { + let values = _mm512_broadcast_i32x4(_mm_loadu_si128(KVALUES_IQ4NL.as_ptr() as *const __m128i)); + let (m4, zero) = (_mm_set1_epi8(0xF), _mm512_setzero_si512()); + let mut sumf = [0.0f32; 4]; + for (bi, b) in row.chunks_exact(136).enumerate() { + let sh = u16::from_le_bytes([b[2], b[3]]); + let d = d16(b); + let mut sumi = [zero; 4]; + for p in 0..4 { + let (ib0, ib1) = (2 * p, 2 * p + 1); + let bits0 = _mm_loadu_si128(b.as_ptr().add(8 + 16 * ib0) as *const __m128i); + let bits1 = _mm_loadu_si128(b.as_ptr().add(8 + 16 * ib1) as *const __m128i); + let idx0 = _mm256_set_m128i(_mm_and_si128(_mm_srli_epi16(bits0, 4), m4), _mm_and_si128(bits0, m4)); + let idx1 = _mm256_set_m128i(_mm_and_si128(_mm_srli_epi16(bits1, 4), m4), _mm_and_si128(bits1, m4)); + let w = _mm512_shuffle_epi8(values, _mm512_inserti64x4(_mm512_castsi256_si512(idx0), idx1, 1)); + let neg = _mm512_movepi8_mask(w); + let aw = _mm512_abs_epi8(w); + let sc = |ib: usize| (((b[4 + ib / 2] >> (4 * (ib % 2))) & 0xF) as i32 | ((((sh >> (2 * ib)) & 3) as i32) << 4)) - 32; + let sv = _mm512_mask_set1_epi32(_mm512_set1_epi32(sc(ib0)), 0xFF00, sc(ib1)); + for k in 0..4 { + let q = q8_512(&xq[k][bi], 64 * p); + let d32 = _mm512_dpbusd_epi32(zero, aw, _mm512_mask_sub_epi8(q, neg, zero, q)); + sumi[k] = _mm512_add_epi32(sumi[k], _mm512_mullo_epi32(d32, sv)); + } + } + for k in 0..4 { + sumf[k] += d * xq[k][bi].d * _mm512_reduce_add_epi32(sumi[k]) as f32; + } + } + sumf + } + } + + /// Four-activation Q6_K dot: decodes each 256-weight super-block once via 512-bit `vpdpbusd`. + pub fn dot4_q6k(row: &[u8], xq: [&[Q8K]; 4]) -> [f32; 4] { + unsafe { + let (m4, m2, zero) = (_mm512_set1_epi8(0xF), _mm512_set1_epi8(3), _mm512_setzero_si512()); + let mut sumf = [0.0f32; 4]; + for (bi, b) in row.chunks_exact(210).enumerate() { + let sc = |g: usize| b[192 + g] as i8 as i32; + let db = d16(&b[208..]); + let mut sumi = [zero; 4]; + for n in 0..2 { + let ql = _mm512_loadu_si512(b[64 * n..].as_ptr() as *const __m512i); + let qh256 = _mm256_loadu_si256(b[128 + 32 * n..].as_ptr() as *const __m256i); + let qh = _mm512_inserti64x4(_mm512_castsi256_si512(qh256), qh256, 1); + let lo_h = _mm512_and_si512(ql, m4); + let hi_h = _mm512_and_si512(_mm512_srli_epi16(ql, 4), m4); + let h0 = _mm512_slli_epi16(_mm512_and_si512(_mm512_mask_blend_epi32(0xFF00, qh, _mm512_srli_epi16(qh, 2)), m2), 4); + let h1 = _mm512_slli_epi16(_mm512_and_si512(_mm512_mask_blend_epi32(0xFF00, _mm512_srli_epi16(qh, 4), _mm512_srli_epi16(qh, 6)), m2), 4); + let w0 = _mm512_or_si512(lo_h, h0); + let w1 = _mm512_or_si512(hi_h, h1); + let g = 8 * n; + let s0 = _mm512_set_epi32(sc(g + 3), sc(g + 3), sc(g + 3), sc(g + 3), sc(g + 2), sc(g + 2), sc(g + 2), sc(g + 2), + sc(g + 1), sc(g + 1), sc(g + 1), sc(g + 1), sc(g), sc(g), sc(g), sc(g)); + let s1 = _mm512_set_epi32(sc(g + 7), sc(g + 7), sc(g + 7), sc(g + 7), sc(g + 6), sc(g + 6), sc(g + 6), sc(g + 6), + sc(g + 5), sc(g + 5), sc(g + 5), sc(g + 5), sc(g + 4), sc(g + 4), sc(g + 4), sc(g + 4)); + for k in 0..4 { + let y = &xq[k][bi]; + sumi[k] = _mm512_add_epi32(sumi[k], _mm512_mullo_epi32(_mm512_dpbusd_epi32(zero, w0, q8_512(y, 128 * n)), s0)); + sumi[k] = _mm512_add_epi32(sumi[k], _mm512_mullo_epi32(_mm512_dpbusd_epi32(zero, w1, q8_512(y, 128 * n + 64)), s1)); + } + } + for k in 0..4 { + let y = &xq[k][bi]; + let m: i32 = (0..16).map(|g| sc(g) * y.bs[g] as i32).sum(); + sumf[k] += y.d * db * (_mm512_reduce_add_epi32(sumi[k]) as f32 - 32.0 * m as f32); + } + } + sumf + } + } + /// TQ1_0: all 256 trits per block evaluated in 4 512-bit `vpdpbusd` instructions. pub fn dot_tq1_0(row: &[u8], xq: &[Q8K]) -> f32 { unsafe { @@ -1392,13 +2738,12 @@ mod avx512 { /// A trellis row (blocks of B bytes for 128 values, `quant::tq_points`) times x, in f32: the codebook is not on an /// int8 grid, so these types have no Q8_K kernel. Eight partial sums per block, where `Tensor::matvec` adds in order. fn dot_tq(row: &[u8], x: &[f32]) -> f32 { - use crate::quant::{TQ_LUT as L, tq_points}; - let mut sum = 0f32; + let (st, mut sum) = (&**crate::quant::TQ_STATES, 0f32); for (b, xb) in row.chunks_exact(B).zip(x.chunks_exact(128)) { let (qs, mut acc) = (&b[2..B], [0f32; 8]); for (t, xs) in xb.chunks_exact(8).enumerate() { - let ((p0, p1), (p2, p3)) = (tq_points(qs, 2 * t), tq_points(qs, 2 * t + 1)); - let w = [L[p0][0], L[p0][1], L[p1][0], L[p1][1], L[p2][0], L[p2][1], L[p3][0], L[p3][1]]; + let (u, v) = (&st[crate::quant::tq_state(qs, 2 * t)], &st[crate::quant::tq_state(qs, 2 * t + 1)]); + let w = [u[0], u[1], u[2], u[3], v[0], v[1], v[2], v[3]]; for i in 0..8 { acc[i] += w[i] * xs[i]; } } sum += d16(b) * acc.iter().sum::(); @@ -1433,7 +2778,21 @@ pub fn float_dot(ty: GgmlType) -> Option f32> { } } +/// Read once: `int_dot` and `int_dot4` ask per matrix, on every token and layer. +fn prefer_shared_int() -> bool { + static PREFER: std::sync::OnceLock = std::sync::OnceLock::new(); + *PREFER.get_or_init(|| std::env::var("STRATA_CPU_SHARED_INT").as_deref() == Ok("1") + || (!cfg!(target_feature = "avx2") && std::env::var_os("STRATA_SCALAR").is_none())) +} + pub fn int_dot(ty: GgmlType) -> Option f32> { + if prefer_shared_int() { + #[cfg(target_feature = "avx2")] + if std::env::var_os("STRATA_SCALAR").is_none() { + if let Some(dot) = affine_dot1::(ty) { return Some(dot); } + } + if let Some(dot) = affine_dot1::(ty) { return Some(dot); } + } #[cfg(all(target_arch = "x86_64", target_feature = "avx512f", target_feature = "avx512bw", target_feature = "avx512vnni", target_feature = "avx512vbmi"))] // Opt-in: these kernels add the block sums in a different order than the AVX2 ones, so their results differ in the // last bits, and that is enough to make a drafted run and a plain greedy run pick different tokens at a near tie. @@ -1456,23 +2815,181 @@ pub fn int_dot(ty: GgmlType) -> Option f32> { } } #[cfg(target_feature = "avx2")] + if std::env::var_os("STRATA_SCALAR").is_none() && std::env::var_os("STRATA_TQ_F32").is_none() { + // Same bits as dot_tq_i; picked at run time, so a binary built without AVX-512 still uses it where it exists. + if avx2::has_avx512_tq() { + match ty { + GgmlType::TQK6 => return Some(avx2::dot_tq_v::<26>), + GgmlType::TQK7 => return Some(avx2::dot_tq_v::<30>), + _ => {} + } + } + match ty { + GgmlType::TQ2T => return Some(avx2::dot_tq_i::<34>), + GgmlType::TQK6 => return Some(avx2::dot_tq_i::<26>), + GgmlType::TQK7 => return Some(avx2::dot_tq_i::<30>), + _ => {} + } + } + #[cfg(target_feature = "avx2")] + if std::env::var_os("STRATA_SCALAR").is_none() && avx2::z::has() { + match ty { + GgmlType::IQ2XXS => return Some(avx2::z::dot_iq2xxs), + GgmlType::IQ2XS => return Some(avx2::z::dot_iq2xs), + GgmlType::IQ3XXS => return Some(avx2::z::dot_iq3xxs), + _ => {} + } + } + #[cfg(target_feature = "avx2")] if std::env::var_os("STRATA_SCALAR").is_none() { - return match ty { GgmlType::IQ2XS => Some(avx2::dot_iq2xs), GgmlType::IQ3XXS => Some(avx2::dot_iq3xxs), GgmlType::IQ4XS => Some(avx2::dot_iq4xs), GgmlType::IQ4NL => Some(avx2::dot_iq4nl), GgmlType::IQ3S => Some(avx2::dot_iq3s), GgmlType::Q6K => Some(avx2::dot_q6k), GgmlType::Q5K => Some(avx2::dot_q5k), GgmlType::Q8_0 => Some(avx2::dot_q8_0), GgmlType::IQ2XXS => Some(avx2::dot_iq2xxs), GgmlType::IQ2S => Some(avx2::dot_iq2s), GgmlType::IQ1S => Some(avx2::dot_iq1s), GgmlType::IQ1M => Some(avx2::dot_iq1m), GgmlType::Q2K => Some(avx2::dot_q2k), GgmlType::Q3K => Some(avx2::dot_q3k), GgmlType::Q4K => Some(avx2::dot_q4k), GgmlType::Q2_0 => Some(avx2::dot_q2_0), GgmlType::TQ1_0 => Some(avx2::dot_tq1_0), GgmlType::TQ2_0 => Some(dot_tq2_0), GgmlType::NVFP4 => Some(avx2::dot_nvfp4), GgmlType::Q4_0 => Some(avx2::dot_q4::<2>), GgmlType::Q4_1 => Some(avx2::dot_q4::<3>), GgmlType::Q5_0 => Some(avx2::dot_q4::<6>), GgmlType::Q5_1 => Some(avx2::dot_q4::<7>), _ => None }; + return match ty { GgmlType::IQ2XS => Some(avx2::dot_iq2xs), GgmlType::IQ3XXS => Some(avx2::dot_iq3xxs), GgmlType::IQ4XS => Some(avx2::dot_iq4xs), GgmlType::IQ4NL => Some(avx2::dot_iq4nl), GgmlType::IQ3S => Some(avx2::dot_iq3s), GgmlType::Q6K => Some(avx2::dot_q6k), GgmlType::Q5K => Some(avx2::dot_q5k), GgmlType::Q8_0 => Some(avx2::dot_q8_0), GgmlType::IQ2XXS => Some(avx2::dot_iq2xxs), GgmlType::IQ2S => Some(avx2::dot_iq2s), GgmlType::IQ1S => Some(avx2::dot_iq1s), GgmlType::IQ1M => Some(avx2::dot_iq1m), GgmlType::Q2K => Some(avx2::dot_q2k), GgmlType::Q3K => Some(avx2::dot_q3k), GgmlType::Q4K => Some(avx2::dot_q4k), GgmlType::Q2_0 => Some(avx2::dot_q2_0), GgmlType::TQ1_0 => Some(avx2::dot_tq1_0), GgmlType::PTQ1_0 => Some(avx2::dot_ptq1_0), GgmlType::PTQ1R => Some(avx2::dot_ptq1r), GgmlType::NVFP4 => Some(avx2::dot_nvfp4), GgmlType::Q4_0 => Some(avx2::dot_q4::<2>), GgmlType::Q4_1 => Some(avx2::dot_q4::<3>), GgmlType::Q5_0 => Some(avx2::dot_q4::<6>), GgmlType::Q5_1 => Some(avx2::dot_q4::<7>), _ => affine_dot1::(ty) }; } - match ty { GgmlType::IQ2XS => Some(dot_iq2xs), GgmlType::IQ3XXS => Some(dot_iq3xxs), GgmlType::IQ4XS => Some(dot_iq4xs), GgmlType::IQ4NL => Some(dot_iq4nl), GgmlType::IQ3S => Some(dot_iq3s), GgmlType::Q6K => Some(dot_q6k), GgmlType::Q5K => Some(dot_q5k), GgmlType::Q8_0 => Some(dot_q8_0), GgmlType::IQ2XXS => Some(dot_iq2xxs), GgmlType::IQ2S => Some(dot_iq2s), GgmlType::IQ1S => Some(dot_iq1s), GgmlType::IQ1M => Some(dot_iq1m), GgmlType::Q2K => Some(dot_q2k), GgmlType::Q3K => Some(dot_q3k), GgmlType::Q4K => Some(dot_q4k), GgmlType::Q2_0 => Some(dot_q2_0), GgmlType::TQ1_0 => Some(dot_tq1_0), GgmlType::TQ2_0 => Some(dot_tq2_0), GgmlType::NVFP4 => Some(dot_nvfp4), GgmlType::Q4_0 => Some(dot_q4::<2>), GgmlType::Q4_1 => Some(dot_q4::<3>), GgmlType::Q5_0 => Some(dot_q4::<6>), GgmlType::Q5_1 => Some(dot_q4::<7>), _ => None } + match ty { GgmlType::IQ2XS => Some(dot_iq2xs), GgmlType::IQ3XXS => Some(dot_iq3xxs), GgmlType::IQ4XS => Some(dot_iq4xs), GgmlType::IQ4NL => Some(dot_iq4nl), GgmlType::IQ3S => Some(dot_iq3s), GgmlType::Q6K => Some(dot_q6k), GgmlType::Q5K => Some(dot_q5k), GgmlType::Q8_0 => Some(dot_q8_0), GgmlType::IQ2XXS => Some(dot_iq2xxs), GgmlType::IQ2S => Some(dot_iq2s), GgmlType::IQ1S => Some(dot_iq1s), GgmlType::IQ1M => Some(dot_iq1m), GgmlType::Q2K => Some(dot_q2k), GgmlType::Q3K => Some(dot_q3k), GgmlType::Q4K => Some(dot_q4k), GgmlType::Q2_0 => Some(dot_q2_0), GgmlType::TQ1_0 => Some(dot_tq1_0), GgmlType::NVFP4 => Some(dot_nvfp4), GgmlType::Q4_0 => Some(dot_q4::<2>), GgmlType::Q4_1 => Some(dot_q4::<3>), GgmlType::Q5_0 => Some(dot_q4::<6>), GgmlType::Q5_1 => Some(dot_q4::<7>), _ => affine_dot1::(ty) } +} + +fn shared_int_by_default(ty: GgmlType) -> bool { + matches!(ty, GgmlType::PTQ1_0 | GgmlType::PTQ1R | GgmlType::TQ2_0 | GgmlType::Q1_0 | GgmlType::PQ2_0 | GgmlType::Q8_1 | GgmlType::Q8K | GgmlType::MXFP4) +} + +fn default_affine4(ty: GgmlType) -> Option> { + shared_int_by_default(ty).then(|| affine_kernel::<4, SIMD>(ty)).flatten() } /// Four dots of one row at once, with the bits of `int_dot`'s kernel: the row is read and decoded once, and the /// four sums do not wait for each other. None where no such kernel exists; the caller then uses `int_dot`. pub fn int_dot4(ty: GgmlType) -> Option [f32; 4]> { + if prefer_shared_int() { + #[cfg(target_feature = "avx2")] + if std::env::var_os("STRATA_SCALAR").is_none() { + if let Some(dot) = affine_kernel::<4, true>(ty) { return Some(dot); } + } + if let Some(dot) = affine_kernel::<4, false>(ty) { return Some(dot); } + } + #[cfg(all(target_arch = "x86_64", target_feature = "avx512f", target_feature = "avx512bw", target_feature = "avx512vnni", target_feature = "avx512vbmi"))] + if std::env::var_os("STRATA_SCALAR").is_none() && std::env::var_os("STRATA_AVX512").is_some() { + return match ty { + GgmlType::Q8_0 => Some(avx512::dot4_q8_0), + GgmlType::IQ4NL => Some(avx512::dot4_iq4nl), + GgmlType::IQ4XS => Some(avx512::dot4_iq4xs), + GgmlType::Q6K => Some(avx512::dot4_q6k), + GgmlType::PTQ1_0 => Some(avx2::dot4_ptq1_0), GgmlType::PTQ1R => Some(avx2::dot4_ptq1r), + _ => default_affine4::(ty), + }; + } + #[cfg(target_feature = "avx2")] + if std::env::var_os("STRATA_SCALAR").is_none() + && (std::env::var_os("STRATA_AVX512").is_none() || matches!(ty, GgmlType::PTQ1_0 | GgmlType::PTQ1R)) { + // Same kernels with AVX-512VL/VNNI codegen where the CPU has it (a no-op in a native build that already has it). + let vl = avx2::has_avx512_vl(); + if vl && avx2::z::has() { + match ty { + GgmlType::IQ2XXS => return Some(avx2::z::dot4_iq2xxs), GgmlType::IQ2XS => return Some(avx2::z::dot4_iq2xs), GgmlType::IQ2S => return Some(avx2::z::dot4_iq2s), + GgmlType::IQ3XXS => return Some(avx2::z::dot4_iq3xxs), GgmlType::IQ3S => return Some(avx2::z::dot4_iq3s), _ => {} + } + } + macro_rules! k { ($f:ident) => { Some(if vl { avx2::vl::$f } else { avx2::$f }) } } + return match ty { GgmlType::Q8_0 => k!(dot4_q8_0), GgmlType::IQ4NL => k!(dot4_iq4nl), GgmlType::Q5K => k!(dot4_q5k), GgmlType::Q6K => k!(dot4_q6k), GgmlType::Q4K => k!(dot4_q4k), GgmlType::Q2K => k!(dot4_q2k), GgmlType::Q3K => k!(dot4_q3k), GgmlType::IQ2XXS => k!(dot4_iq2xxs), GgmlType::IQ2XS => k!(dot4_iq2xs), GgmlType::IQ2S => k!(dot4_iq2s), GgmlType::IQ3XXS => k!(dot4_iq3xxs), GgmlType::IQ3S => k!(dot4_iq3s), GgmlType::IQ1S => k!(dot4_iq1s), GgmlType::IQ1M => k!(dot4_iq1m), GgmlType::Q2_0 => k!(dot4_q2_0), GgmlType::IQ4XS => k!(dot4_iq4xs), GgmlType::PTQ1_0 => Some(avx2::dot4_ptq1_0), GgmlType::PTQ1R => Some(avx2::dot4_ptq1r), _ => default_affine4::(ty) }; + } + #[cfg(target_feature = "avx2")] + if std::env::var_os("STRATA_SCALAR").is_none() { + return default_affine4::(ty); + } + default_affine4::(ty) +} + +/// Eight dots of one row at once, with `int_dot`'s bits (see `int_dot4`): the grid types, whose decoding costs more +/// than the products, so a batch of tokens (prompt experts on the CPU) decodes each block an eighth as often. Needs +/// AVX-512VL for the registers; None elsewhere. +pub fn int_dot8(ty: GgmlType) -> Option [f32; 8]> { + #[cfg(target_feature = "avx2")] + if std::env::var_os("STRATA_SCALAR").is_none() && std::env::var_os("STRATA_AVX512").is_none() && !prefer_shared_int() && avx2::has_avx512_vl() { + if avx2::z::has() { + return match ty { + GgmlType::IQ2XXS => Some(avx2::z::dot8_iq2xxs), GgmlType::IQ2XS => Some(avx2::z::dot8_iq2xs), GgmlType::IQ2S => Some(avx2::z::dot8_iq2s), + GgmlType::IQ3XXS => Some(avx2::z::dot8_iq3xxs), GgmlType::IQ3S => Some(avx2::z::dot8_iq3s), + GgmlType::Q2_0 => Some(avx2::vl::dot8_q2_0), GgmlType::IQ4NL => Some(avx2::vl::dot8_iq4nl), _ => None, + }; + } + return match ty { + GgmlType::IQ2XXS => Some(avx2::vl::dot8_iq2xxs), GgmlType::IQ2XS => Some(avx2::vl::dot8_iq2xs), GgmlType::IQ2S => Some(avx2::vl::dot8_iq2s), + GgmlType::IQ3XXS => Some(avx2::vl::dot8_iq3xxs), GgmlType::IQ3S => Some(avx2::vl::dot8_iq3s), + GgmlType::Q2_0 => Some(avx2::vl::dot8_q2_0), GgmlType::IQ4NL => Some(avx2::vl::dot8_iq4nl), _ => None, + }; + } + let _ = ty; + None +} + +/// `int_dot8` for activations flipped by `flip` (the AVX-512 grid kernels' `dotn_off`), where there is one. +pub fn int_dot8_off(ty: GgmlType) -> Option [f32; 8]> { + #[cfg(target_feature = "avx2")] + if int_dot8(ty).is_some() && avx2::z::has() { + return match ty { + GgmlType::IQ2XXS => Some(avx2::z::dot8o_iq2xxs), GgmlType::IQ2XS => Some(avx2::z::dot8o_iq2xs), GgmlType::IQ2S => Some(avx2::z::dot8o_iq2s), + GgmlType::IQ3XXS => Some(avx2::z::dot8o_iq3xxs), GgmlType::IQ3S => Some(avx2::z::dot8o_iq3s), _ => None, + }; + } + let _ = ty; + None +} + +/// `int_dot8_off`'s kernels for sixteen activations. +pub fn int_dot16_off(ty: GgmlType) -> Option [f32; 16]> { + #[cfg(target_feature = "avx2")] + if int_dot8_off(ty).is_some() { + return match ty { + GgmlType::IQ2XXS => Some(avx2::z::dot16o_iq2xxs), GgmlType::IQ2XS => Some(avx2::z::dot16o_iq2xs), GgmlType::IQ2S => Some(avx2::z::dot16o_iq2s), + GgmlType::IQ3XXS => Some(avx2::z::dot16o_iq3xxs), GgmlType::IQ3S => Some(avx2::z::dot16o_iq3s), _ => None, + }; + } + let _ = ty; + None +} + +/// Sixteen activations a row read for the short down rows of Q2_0 and IQ4_NL (prompt experts on the CPU), with the +/// bits of `int_dot`. +pub fn int_dot16(ty: GgmlType) -> Option [f32; 16]> { #[cfg(target_feature = "avx2")] - if std::env::var_os("STRATA_SCALAR").is_none() && std::env::var_os("STRATA_AVX512").is_none() { - return match ty { GgmlType::Q8_0 => Some(avx2::dot4_q8_0), GgmlType::IQ4NL => Some(avx2::dot4_iq4nl), _ => None }; + if int_dot8(ty).is_some() { + return match ty { GgmlType::Q2_0 => Some(avx2::vl::dot16_q2_0), GgmlType::IQ4NL => Some(avx2::vl::dot16_iq4nl), _ => None }; } let _ = ty; None } +/// The activation with 128 added to each value (bytes xor 0x80), as `int_dot8_off`'s kernels read it. +pub fn flip(x: &Q8K) -> Q8K { Q8K { d: x.d, qs: x.qs.map(|q| q ^ -128), bs: x.bs } } + +/// Bytes of one Q4_K block of 8 rows in a `repack_q4k_x8` tile: d[8] and dmin[8] as f32 (64), the scales and then +/// the mins as [sub-block][row] bytes (128), and the 128 quant bytes of each row as 32 runs of 4 bytes, run k of +/// rows 0..8 together (1024). +pub const X8_BLOCK: usize = 1216; + +/// Bytes of one Q6_K (or Q3_K) block of 8 rows in a `repack_q6k_x8` tile: d[8] as f32 (32), the scales as +/// [group][row] (128), the codes as 64 runs of 4 bytes of the 8 rows (2048). +pub const Q6_X8_BLOCK: usize = 2208; + +/// Bytes of one Q2_K block of 8 rows: the Q6_K layout, then dmin[8] as f32 (32) and the mins as [group][row] (128). +pub const Q2_X8_BLOCK: usize = 2368; + +/// Bytes of one Q8_0 block (32 columns) of 8 rows: d[8] as f32 (32), the values as 8 runs of 4 bytes of the 8 rows. +pub const Q8_X8_BLOCK: usize = 288; + +/// Q4_K, Q6_K, Q3_K, Q2_K or Q8_0 (`ty`) rows of `w` (`rb` bytes each, a multiple of 8 rows) times every activation +/// of `xq`, scaled by `sc`: `o[r * n + t]`, n = `xq.len()`. Each 8 rows are repacked into an L1/L2-sized tile and then +/// read once for all the activations, so the repack costs no resident memory. The bits of the scalar dot per (row, +/// activation), which are also those of `int_dot` and `int_dot4`. VNNI `vpdpbusd` where the CPU has AVX-512VL/VNNI, +/// also in a binary built for x86-64-v3. False when the binary has no AVX2 kernel, `ty` is another type, or +/// STRATA_Q4K_X8=0 (off for all types): then the caller takes its usual path. +pub fn rows_x8(ty: GgmlType, w: &[u8], rb: usize, xq: &[Vec], sc: f32, o: &mut [f32]) -> bool { + #[cfg(target_feature = "avx2")] + if std::env::var_os("STRATA_SCALAR").is_none() && std::env::var_os("STRATA_AVX512").is_none() && std::env::var("STRATA_Q4K_X8").as_deref() != Ok("0") { + return if avx2::has_avx512_vl() { avx2::vl::rows_x8(ty, w, rb, xq, sc, o) } else { avx2::rows_x8::(ty, w, rb, xq, sc, o) }; + } + let _ = (ty, w, rb, xq, sc, o); + false +} + /// y = t · x for every row, using the integer kernel when the type has one. pub fn matvec(t: &Tensor, x: &[f32], y: &mut [f32]) { let rb = t.data.len() / t.rows; @@ -1482,13 +2999,90 @@ pub fn matvec(t: &Tensor, x: &[f32], y: &mut [f32]) { }); } let Some(dot) = int_dot(t.ty) else { return t.matvec(x, y) }; - let xq = quantize_q8k(x); + matvec_q8k(t, &quantize_q8k(x), y, dot); +} + +/// PTQ1_0R takes the AVX2 tiles (`avx2::ptq1r_tile`) when `int_dot` gives their kernel; they have its bits. +fn ptq1r_tiles(ty: GgmlType) -> bool { + cfg!(target_feature = "avx2") && ty == GgmlType::PTQ1R && std::env::var_os("STRATA_SCALAR").is_none() && !prefer_shared_int() +} + +pub(crate) fn matvec_q8k(t: &Tensor, xq: &[Q8K], y: &mut [f32], dot: fn(&[u8], &[Q8K]) -> f32) { + let rb = t.ty.row_bytes(t.cols as u64); + #[cfg(target_feature = "avx2")] + if ptq1r_tiles(t.ty) { + // Eight rows a tile: the activation is read once for the eight. + return y.par_chunks_mut(32).enumerate().for_each(|(c, ys)| { + let row = |k: usize| &t.data[(c * 32 + k) * rb..(c * 32 + k + 1) * rb]; + let mut k = 0; + while k + 8 <= ys.len() { + let v = avx2::ptq1r_tile::<8, 1>(std::array::from_fn(|j| row(k + j)), [xq]); + for j in 0..8 { ys[k + j] = v[j][0] * t.scale; } + k += 8; + } + for k in k..ys.len() { ys[k] = dot(row(k), xq) * t.scale; } + }); + } y.par_chunks_mut(32).enumerate().for_each(|(c, ys)| { for (k, v) in ys.iter_mut().enumerate() { let r = c * 32 + k; - *v = dot(&t.data[r * rb..(r + 1) * rb], &xq) * t.scale; + *v = dot(&t.data[r * rb..(r + 1) * rb], xq) * t.scale; + } + }); +} + +/// `matvec_q8k` of each activation in `xq`: out[j] = t · x_j, with its bits. Each task reads its rows once for every +/// four activations (`int_dot4` where the type has one), so a batch of tokens decodes each weight block a quarter as often. +pub(crate) fn matmul_q8k(t: &Tensor, xq: &[Vec], dot: fn(&[u8], &[Q8K]) -> f32) -> Vec> { + const ROWS: usize = 32; + let (rb, n, dot4) = (t.ty.row_bytes(t.cols as u64), xq.len(), int_dot4(t.ty)); + let mut out = vec![0f32; t.rows * n]; // [row][activation] + #[cfg(target_feature = "avx2")] + if ptq1r_tiles(t.ty) { + // Tiles of 2 rows by 4 activations: each row block is unpacked once for four, each activation read once for two. + // (Walking the columns in L1-sized slices, the sums carried between them, measured no faster on an i5-8365U.) + out.par_chunks_mut(ROWS * n).enumerate().for_each(|(c, ys)| { + let row = |r: usize| &t.data[(c * ROWS + r) * rb..(c * ROWS + r + 1) * rb]; + let nr = ys.len() / n; + let mut j = 0; + while j + 4 <= n { + let xs = [&xq[j][..], &xq[j + 1], &xq[j + 2], &xq[j + 3]]; + let mut r = 0; + while r + 2 <= nr { + let v = avx2::ptq1r_tile::<2, 4>([row(r), row(r + 1)], xs); + for (i, v) in v.iter().enumerate() { for k in 0..4 { ys[(r + i) * n + j + k] = v[k] * t.scale; } } + r += 2; + } + if r < nr { + let v = avx2::ptq1r_tile::<1, 4>([row(r)], xs); + for k in 0..4 { ys[r * n + j + k] = v[0][k] * t.scale; } + } + j += 4; + } + for j in j..n { for r in 0..nr { ys[r * n + j] = dot(row(r), &xq[j]) * t.scale; } } + }); + return (0..n).map(|j| (0..t.rows).map(|r| out[r * n + j]).collect()).collect(); + } + out.par_chunks_mut(ROWS * n).enumerate().for_each(|(c, ys)| { + let row = |r: usize| &t.data[(c * ROWS + r) * rb..(c * ROWS + r + 1) * rb]; + let mut j = 0; + while j < n { + match dot4 { + Some(d4) if j + 4 <= n => { + for r in 0..ys.len() / n { + let v = d4(row(r), [&xq[j], &xq[j + 1], &xq[j + 2], &xq[j + 3]]); + for k in 0..4 { ys[r * n + j + k] = v[k] * t.scale; } + } + j += 4; + } + _ => { + for r in 0..ys.len() / n { ys[r * n + j] = dot(row(r), &xq[j]) * t.scale; } + j += 1; + } + } } }); + (0..n).map(|j| (0..t.rows).map(|r| out[r * n + j]).collect()).collect() } /// Rows `out.len()` of a batch of matrices: out[i] = mats[i / rows] row (i % rows) · x of that matrix, where @@ -1501,17 +3095,101 @@ fn batch_rows(mats: &[Tensor], xs: &[&[f32]], out: &mut [f32]) { // including when only one expert misses; other formats keep their existing granularity. let batch = if mats[0].ty == GgmlType::Q2_0 && cfg!(target_feature = "avx2") && out.len() / 64 >= rayon::current_num_threads() { 64 } else { 16 }; - out.par_chunks_mut(batch).enumerate().for_each_init(|| if dot.is_none() { vec![0f32; mats[0].cols] } else { Vec::new() }, |buf, (c, ys)| { - for (k, v) in ys.iter_mut().enumerate() { - let i = c * batch + k; - let (t, r, x) = (&mats[i / rows], i % rows, i / rows * xs.len() / mats.len()); - let rb = t.data.len() / t.rows; - *v = match (dot, fdot) { - (Some(d), _) => d(&t.data[r * rb..(r + 1) * rb], &xq[x]) * t.scale, - (_, Some(d)) => d(&t.data[r * rb..(r + 1) * rb], xs[x]) * t.scale, - _ => { t.row(r, buf); buf.iter().zip(xs[x]).map(|(a, b)| a * b).sum() } - }; + let row = |i: usize, buf: &mut Vec| -> f32 { + let (t, r, x) = (&mats[i / rows], i % rows, i / rows * xs.len() / mats.len()); + let rb = t.data.len() / t.rows; + match (dot, fdot) { + (Some(d), _) => d(&t.data[r * rb..(r + 1) * rb], &xq[x]) * t.scale, + (_, Some(d)) => d(&t.data[r * rb..(r + 1) * rb], xs[x]) * t.scale, + _ => { t.row(r, buf); buf.iter().zip(xs[x]).map(|(a, b)| a * b).sum() } } + }; + // Every thread of the pool takes the next chunk from one counter: the same chunks as a parallel iterator, without + // its work stealing (crossbeam's epoch and deques took ~25% of the CPU expert time of Qwen3.8-Flash-Next decode). + if dot.is_some() { + let next = std::sync::atomic::AtomicUsize::new(0); + let (n, op) = (out.len(), SendPtr(out.as_mut_ptr())); + let batch = batch * 4; + rayon::broadcast(|_| { + let op = op; + let mut buf = Vec::new(); + loop { + let c = next.fetch_add(batch, std::sync::atomic::Ordering::Relaxed); + if c >= n { break; } + for i in c..(c + batch).min(n) { unsafe { *op.0.add(i) = row(i, &mut buf); } } + } + }); + return; + } + out.par_chunks_mut(batch).enumerate().for_each_init(|| if dot.is_none() { vec![0f32; mats[0].cols] } else { Vec::new() }, |buf, (c, ys)| { + for (k, v) in ys.iter_mut().enumerate() { *v = row(c * batch + k, buf); } + }); +} + +/// `batch_rows` for matrices that each read several inputs: matrix i takes inputs `xs[j]` for j in `mats[i].1`. +/// Outputs are in row order, with the inputs in group order within each row. Reusing the weight row +/// preserves the arithmetic of `batch_rows`. +fn group_rows(mats: &[(Tensor, &[usize])], xs: &[Vec], out: &mut [f32]) { + let ty = mats[0].0.ty; + let dot = int_dot(ty); + let xq: Vec> = if dot.is_some() { + xs.par_iter().map(|x| quantize_q8k(x)).collect() + } else { + Vec::new() + }; + let dot4 = int_dot4(ty); + let dot8 = int_dot8(ty); + let fdot = float_dot(ty); + let mut parts = Vec::with_capacity(mats.len()); + let mut rest = out; + for (t, g) in mats { + let (a, b) = rest.split_at_mut(t.rows * g.len()); + parts.push((t, *g, a)); + rest = b; + } + parts.into_par_iter().for_each(|(t, g, o)| { + let rb = t.row_bytes(); + let Some(dot) = dot else { + // Keep the expert row in scratch while all its routed tokens consume it. + o.par_chunks_mut(16 * g.len()).enumerate().for_each_init( + || if fdot.is_none() { vec![0.0; t.cols] } else { Vec::new() }, + |row, (c, outputs)| { + for (r, ys) in outputs.chunks_exact_mut(g.len()).enumerate() { + let r = c * 16 + r; + if let Some(fdot) = fdot { + let w = &t.data[r * rb..(r + 1) * rb]; + for (y, &i) in ys.iter_mut().zip(g) { *y = fdot(w, &xs[i]) * t.scale; } + } else { + t.row(r, row); + for (y, &i) in ys.iter_mut().zip(g) { *y = row.iter().zip(&xs[i]).map(|(a, b)| a * b).sum(); } + } + } + }, + ); + return; + }; + o.par_chunks_mut(16 * g.len()).enumerate().for_each(|(c, o)| { + for (k, o) in o.chunks_exact_mut(g.len()).enumerate() { + let r = c * 16 + k; + let w = &t.data[r * rb..(r + 1) * rb]; + let mut j = 0; + if let Some(dot8) = dot8 { + while j + 8 <= g.len() { + let v = dot8(w, std::array::from_fn(|i| &xq[g[j + i]][..])); + for i in 0..8 { o[j + i] = v[i] * t.scale; } + j += 8; + } + } + if let Some(dot4) = dot4 { + while j + 4 <= g.len() { + let v = dot4(w, [&xq[g[j]], &xq[g[j + 1]], &xq[g[j + 2]], &xq[g[j + 3]]]); + for i in 0..4 { o[j + i] = v[i] * t.scale; } + j += 4; + } + } + for j in j..g.len() { o[j] = dot(w, &xq[g[j]]) * t.scale; } + } + }); }); } @@ -1549,6 +3227,265 @@ pub fn experts(m: &Model, il: usize, h: &[f32], sel: &[(usize, f32)]) -> Vec(*mut T); +impl Copy for SendPtr {} +impl Clone for SendPtr { fn clone(&self) -> Self { *self } } +unsafe impl Send for SendPtr {} +unsafe impl Sync for SendPtr {} + +/// Whether the fused CPU experts support layer `il` (integer kernels for gate, up and down, no rotation, no LoRA). +pub fn fused_experts_supported(m: &Model, il: usize) -> bool { + let t = |s: &str| m.w.layer(il, s).ok(); + let (Some(g), Some(u), Some(d)) = (t("ffn_gate_exps.weight"), t("ffn_up_exps.weight"), t("ffn_down_exps.weight")) else { return false }; + m.cfg.hadamard.is_none() && m.loras.is_empty() && g.ty == u.ty && float_dot(g.ty).is_none() && float_dot(d.ty).is_none() + && int_dot(g.ty).is_some() && int_dot(d.ty).is_some() +} + +/// Claim a chunk from any ready expert, favoring the last expert this worker visited for locality. +fn claim_down(chunks: &[std::sync::atomic::AtomicUsize], cursor: &mut usize, per_expert: usize) -> Option<(usize, usize)> { + use std::sync::atomic::Ordering::{Acquire, Relaxed}; + loop { + let mut pending = false; + for expert in (*cursor..chunks.len()).chain(0..*cursor) { + let count = &chunks[expert]; + let mut left = count.load(Acquire); + while left != 0 && left != usize::MAX { + match count.compare_exchange_weak(left, left - 1, Relaxed, Relaxed) { + Ok(_) => { + *cursor = expert; + return Some((expert, per_expert - left)); + } + Err(actual) => left = actual, + } + } + pending |= left == usize::MAX; + } + if !pending { return None; } + std::hint::spin_loop(); + } +} + +/// `experts` in one dispatch with no barrier between gate/up and down: the pool takes gate/up row chunks in +/// expert order from one counter; the thread that finishes an expert's last gate/up chunk makes its SwiGLU input +/// and publishes its down chunks. Workers can take those chunks while other experts finish gate/up. +/// The same dots, inputs and sums as `experts`: the same bits. +pub fn experts_fused(m: &Model, il: usize, h: &[f32], sel: &[(usize, f32)]) -> Vec { + DecodeExpertScratch::new().run(m, il, h, sel).to_vec() +} + +/// Buffers owned by one decode worker and reused across MoE layers. +pub struct DecodeExpertScratch { + gate_up: Vec, + output: Vec, + combined: Vec, + input: Vec, + activation: Vec, + left: Vec, + down_chunks: Vec, +} + +impl DecodeExpertScratch { + pub fn new() -> Self { + Self { + gate_up: Vec::new(), output: Vec::new(), combined: Vec::new(), + input: Vec::new(), activation: Vec::new(), left: Vec::new(), down_chunks: Vec::new(), + } + } + + pub fn run(&mut self, m: &Model, il: usize, h: &[f32], sel: &[(usize, f32)]) -> &[f32] { + use std::sync::atomic::{AtomicUsize, Ordering::{Relaxed, Release, AcqRel}}; + let c = &m.cfg; + let (n, ff, ne, k) = (c.n_expert, c.n_ff_exp, c.n_embd, sel.len()); + self.combined.resize(ne, 0.0); + self.combined.fill(0.0); + if k == 0 { return &self.combined; } + let t = |s: &str| m.w.layer(il, s).unwrap_or_else(|e| panic!("{e:#}")); + let (gate, up, down) = (t("ffn_gate_exps.weight"), t("ffn_up_exps.weight"), t("ffn_down_exps.weight")); + let (dg, dd) = (int_dot(gate.ty).unwrap(), int_dot(down.ty).unwrap()); + self.input.clear(); + self.input.extend(h.chunks(256).map(quantize_q8k_block)); + let xq = &self.input; + let (gu_rows, down_rows) = (128usize, 128usize); + let (ga, da) = ((2 * ff).div_ceil(gu_rows), ne.div_ceil(down_rows)); + let blocks = ff.div_ceil(256); + self.gate_up.resize(self.gate_up.len().max(2 * k * ff), 0.0); + self.output.resize(self.output.len().max(k * ne), 0.0); + self.activation.resize_with(self.activation.len().max(k * blocks), || Q8K { d: 0.0, qs: [0; 256], bs: [0; 16] }); + self.left.resize_with(self.left.len().max(k), || AtomicUsize::new(0)); + self.down_chunks.resize_with(self.down_chunks.len().max(k), || AtomicUsize::new(0)); + let (left, down_chunks) = (&self.left[..k], &self.down_chunks[..k]); + for counter in left { counter.store(ga, Relaxed); } + for counter in down_chunks { counter.store(usize::MAX, Relaxed); } + let (ap, op, aq) = (SendPtr(self.gate_up.as_mut_ptr()), SendPtr(self.output.as_mut_ptr()), SendPtr(self.activation.as_mut_ptr())); + let next_a = AtomicUsize::new(0); + let (rbg, rbd) = (gate.row_bytes(), down.row_bytes()); + rayon::broadcast(|_| { + let (ap, op, aq) = (ap, op, aq); + loop { + let i = next_a.fetch_add(1, Relaxed); + if i >= k * ga { break; } + let (j, ch) = (i / ga, i % ga); + let e = sel[j].0; + let (ge, ue) = (gate.expert(e, n), up.expert(e, n)); + for r in ch * gu_rows..((ch + 1) * gu_rows).min(2 * ff) { + // rows 0..ff are gate, ff..2ff up: a[2 j ff + r] as in `experts` + let (t, rr) = if r < ff { (&ge, r) } else { (&ue, r - ff) }; + unsafe { *ap.0.add(2 * j * ff + r) = dg(&t.data[rr * rbg..(rr + 1) * rbg], xq) * t.scale; } + } + if left[j].fetch_sub(1, AcqRel) == 1 { + let g = unsafe { std::slice::from_raw_parts(ap.0.add(2 * j * ff), 2 * ff) }; + // Only the last gate/up task writes this expert's activation. The release + // below publishes the complete slice to all its down tasks. + let act = unsafe { std::slice::from_raw_parts_mut(aq.0.add(j * blocks), blocks) }; + let (gate, up) = g.split_at(ff); + for ((gate, up), dst) in gate.chunks(256).zip(up.chunks(256)).zip(act) { + let mut values = [0.0; 256]; + for ((v, &g), &u) in values.iter_mut().zip(gate).zip(up) { *v = ops::silu(g) * u; } + *dst = quantize_q8k_block(&values[..gate.len()]); + } + down_chunks[j].store(da, Release); + } + } + let mut cursor = 0; + while let Some((j, ch)) = claim_down(down_chunks, &mut cursor, da) { + let de = down.expert(sel[j].0, n); + let x = unsafe { std::slice::from_raw_parts(aq.0.add(j * blocks), blocks) }; + for r in ch * down_rows..((ch + 1) * down_rows).min(ne) { unsafe { *op.0.add(j * ne + r) = dd(&de.data[r * rbd..(r + 1) * rbd], x) * de.scale; } } + } + }); + for (oj, &(_, w)) in self.output.chunks_exact(ne).zip(sel) { + for (yy, oo) in self.combined.iter_mut().zip(oj) { *yy += w * oo; } + } + &self.combined + } +} + +/// Dot one weight row with the group's activations, preserving each individual dot's bits. +#[inline] +fn row_group(w: &[u8], g: &[usize], xq: &[Vec], o: &mut [f32], scale: f32, + dot: fn(&[u8], &[Q8K]) -> f32, dot4: Option [f32; 4]>, dot8: Option [f32; 8]>, + off: Option<(fn(&[u8], [&[Q8K]; 16]) -> [f32; 16], fn(&[u8], [&[Q8K]; 8]) -> [f32; 8], &[Vec])>, + d16: Option [f32; 16]>) { + let mut j = 0; + if let Some((d16o, d8o, xf)) = off { + while j + 16 <= g.len() { + let v = d16o(w, std::array::from_fn(|i| &xf[g[j + i]][..])); + for i in 0..16 { o[j + i] = v[i] * scale; } + j += 16; + } + // A single dot is cheaper for one token. For 10–15, one padded sixteen-token call + // decodes the weights once. Nine tokens use eight and one. + let tail = g.len() - j; + if tail >= 10 { + let v = d16o(w, std::array::from_fn(|i| &xf[g[j + i.min(tail - 1)]][..])); + for i in 0..tail { o[j + i] = v[i] * scale; } + } else if tail >= 2 { + let used = tail.min(8); + let v = d8o(w, std::array::from_fn(|i| &xf[g[j + i.min(used - 1)]][..])); + for i in 0..used { o[j + i] = v[i] * scale; } + j += used; + } + if g.len() - j == 1 { o[j] = dot(w, &xq[g[j]]) * scale; } + return; + } + if let Some(dot16) = d16 { + while j + 16 <= g.len() { + let v = dot16(w, std::array::from_fn(|i| &xq[g[j + i]][..])); + for i in 0..16 { o[j + i] = v[i] * scale; } + j += 16; + } + } + if let Some(dot8) = dot8 { + while j + 8 <= g.len() { + let v = dot8(w, std::array::from_fn(|i| &xq[g[j + i]][..])); + for i in 0..8 { o[j + i] = v[i] * scale; } + j += 8; + } + } + if let Some(dot4) = dot4 { + while j + 4 <= g.len() { + let v = dot4(w, [&xq[g[j]], &xq[g[j + 1]], &xq[g[j + 2]], &xq[g[j + 3]]]); + for i in 0..4 { o[j + i] = v[i] * scale; } + j += 4; + } + } + for j in j..g.len() { o[j] = dot(w, &xq[g[j]]) * scale; } +} + +/// `expert_rows` (the grouped path, integer kernels) in one dispatch, as `experts_fused` does one token: gate/up chunks +/// of each expert's rows for all its tokens in expert order from one counter; the thread that finishes an expert's +/// last chunk makes the SwiGLU inputs of its tokens, which opens that expert's down chunks. The same kernels in the +/// same order per row as `group_rows`: the bits of `expert_rows`. None where it does not apply. +pub fn expert_rows_fused(m: &Model, il: usize, hs: &[Vec], pairs: &[(usize, usize, f32)]) -> Option> { + use std::sync::atomic::{AtomicUsize, Ordering::{Relaxed, Release, AcqRel}}; + let c = &m.cfg; + if pairs.is_empty() || !fused_experts_supported(m, il) || std::env::var_os("STRATA_PAIR_ROWS").is_some() || m.w.g.moe.no_fused { return None; } + let t = |s: &str| m.w.layer(il, s).unwrap_or_else(|e| panic!("{e:#}")); + let (gate, up, down) = (t("ffn_gate_exps.weight"), t("ffn_up_exps.weight"), t("ffn_down_exps.weight")); + let (n, ff, ne, k) = (c.n_expert, c.n_ff_exp, c.n_embd, pairs.len()); + let mut order: Vec = (0..k).collect(); + order.sort_by_key(|&p| pairs[p].1); + let groups: Vec<&[usize]> = order.chunk_by(|&a, &b| pairs[a].1 == pairs[b].1).collect(); + let toks: Vec> = groups.iter().map(|g| g.iter().map(|&p| pairs[p].0).collect()).collect(); + let starts: Vec = groups.iter().scan(0, |a, g| { let s = *a; *a += g.len(); Some(s) }).collect(); + let ng = groups.len(); + let xq: Vec> = hs.par_iter().map(|x| quantize_q8k(x)).collect(); + let (dg, dg4, dg8) = (int_dot(gate.ty).unwrap(), int_dot4(gate.ty), int_dot8(gate.ty)); + // Eight tokens at a time read the activations with 128 added (`int_dot8_off`), where the type has that kernel. + let dgo = int_dot16_off(gate.ty).zip(int_dot8_off(gate.ty)); + let xqf: Vec> = if dgo.is_some() { xq.par_iter().map(|x| x.iter().map(flip).collect()).collect() } else { Vec::new() }; + let (dd, dd4, dd8, dd16) = (int_dot(down.ty).unwrap(), int_dot4(down.ty), int_dot8(down.ty), int_dot16(down.ty)); + const CH: usize = 32; + let (ga, da) = ((2 * ff).div_ceil(CH), ne.div_ceil(CH)); + // tmp: per group, gate rows then up rows, each the group's tokens (as group_rows lays them out). + let mut tmp = vec![0f32; 2 * k * ff]; + let mut dtmp = vec![0f32; k * ne]; + let (tp, dp) = (SendPtr(tmp.as_mut_ptr()), SendPtr(dtmp.as_mut_ptr())); + let aq: Vec>>> = (0..ng).map(|_| std::sync::OnceLock::new()).collect(); + let left: Vec = (0..ng).map(|_| AtomicUsize::new(ga)).collect(); + let down_chunks: Vec = (0..ng).map(|_| AtomicUsize::new(usize::MAX)).collect(); + let next_a = AtomicUsize::new(0); + let (rbg, rbd) = (gate.row_bytes(), down.row_bytes()); + rayon::broadcast(|_| { + let (tp, dp) = (tp, dp); + loop { + let i = next_a.fetch_add(1, Relaxed); + if i >= ng * ga { break; } + let (gi, ch) = (i / ga, i % ga); + let (e, gl, at) = (pairs[groups[gi][0]].1, groups[gi].len(), starts[gi]); + let (ge, ue) = (gate.expert(e, n), up.expert(e, n)); + for r in ch * CH..((ch + 1) * CH).min(2 * ff) { + let (t, rr) = if r < ff { (&ge, r) } else { (&ue, r - ff) }; + let o = unsafe { std::slice::from_raw_parts_mut(tp.0.add(2 * ff * at + r * gl), gl) }; + row_group(&t.data[rr * rbg..(rr + 1) * rbg], &toks[gi], &xq, o, t.scale, dg, dg4, dg8, dgo.map(|(a, b)| (a, b, &xqf[..])), None); + } + if left[gi].fetch_sub(1, AcqRel) == 1 { + let b = unsafe { std::slice::from_raw_parts(tp.0.add(2 * ff * at), 2 * ff * gl) }; + let acts: Vec> = (0..gl).map(|j| quantize_q8k(&(0..ff).map(|i| ops::silu(b[i * gl + j]) * b[ff * gl + i * gl + j]).collect::>())).collect(); + let _ = aq[gi].set(acts); + down_chunks[gi].store(da, Release); + } + } + let mut cursor = 0; + while let Some((gi, ch)) = claim_down(&down_chunks, &mut cursor, da) { + let (e, gl, at) = (pairs[groups[gi][0]].1, groups[gi].len(), starts[gi]); + let de = down.expert(e, n); + let xs = aq[gi].get().unwrap(); + let idx: Vec = (0..gl).collect(); + for r in ch * CH..((ch + 1) * CH).min(ne) { + let o = unsafe { std::slice::from_raw_parts_mut(dp.0.add(ne * at + r * gl), gl) }; + row_group(&de.data[r * rbd..(r + 1) * rbd], &idx, xs, o, de.scale, dd, dd4, dd8, None, dd16); + } + } + }); + // Back to pair order: pair p is input j of group g, its row r at dtmp[ne * start + r * gl + j]. + let mut o = vec![0f32; k * ne]; + let mut loc = vec![(0, 0, 0); k]; + for (gi, g) in groups.iter().enumerate() { for (j, &p) in g.iter().enumerate() { loc[p] = (starts[gi], g.len(), j); } } + o.par_chunks_mut(ne).zip(&loc).for_each(|(o, &(at, gl, j))| { for (r, v) in o.iter_mut().enumerate() { *v = dtmp[ne * at + r * gl + j]; } }); + Some(o) +} + /// `experts` for several tokens of one layer (a verify batch): ys[t] = `experts(m, il, &hs[t], &sels[t])`, bit for bit. /// All tokens share the two parallel passes of `experts` (gate and up, then down), so a batch costs no more passes /// than one token: a pass per expert costs more in thread wake-ups than the experts two tokens share save. @@ -1557,7 +3494,23 @@ pub fn experts_multi(m: &Model, il: usize, hs: &[Vec], sels: &[Vec<(usize, let mut ys = vec![vec![0f32; c.n_embd]; hs.len()]; // (token, expert, weight) of every routed expert, in token and router order. let pairs: Vec<(usize, usize, f32)> = sels.iter().enumerate().flat_map(|(t, s)| s.iter().map(move |&(e, w)| (t, e, w))).collect(); - if pairs.is_empty() { return ys; } + let o = expert_rows(m, il, hs, &pairs); + for (oj, &(t, _, w)) in o.chunks_exact(c.n_embd).zip(&pairs) { + for (yy, oo) in ys[t].iter_mut().zip(oj.iter()) { *yy += w * oo; } + } + ys +} + +/// The output of each (token, expert, _) pair of layer `il`, unweighted, as rows of n_embd in pair order: the experts +/// of every pair in the two parallel passes of `experts_multi`. +pub fn expert_rows(m: &Model, il: usize, hs: &[Vec], pairs: &[(usize, usize, f32)]) -> Vec { + if let Some(o) = expert_rows_fused(m, il, hs, pairs) { return o; } + expert_rows_two_pass(m, il, hs, pairs) +} + +pub fn expert_rows_two_pass(m: &Model, il: usize, hs: &[Vec], pairs: &[(usize, usize, f32)]) -> Vec { + let c = &m.cfg; + if pairs.is_empty() { return vec![]; } let t = |s: &str| m.w.layer(il, s).unwrap_or_else(|e| panic!("{e:#}")); let (gate, up, down) = (t("ffn_gate_exps.weight"), t("ffn_up_exps.weight"), t("ffn_down_exps.weight")); let (n, ff, k) = (c.n_expert, c.n_ff_exp, pairs.len()); @@ -1566,6 +3519,41 @@ pub fn experts_multi(m: &Model, il: usize, hs: &[Vec], sels: &[Vec<(usize, let rot = c.hadamard.as_ref(); let hr: Option>> = rot.map(|r| hs.iter().map(|h| r.rotated(h)).collect()); let hs = hr.as_deref().unwrap_or(hs); + // The pairs of one expert share its weight rows, including formats with only a decoder. + if gate.ty == up.ty && std::env::var_os("STRATA_PAIR_ROWS").is_none() { + let mut order: Vec = (0..k).collect(); + order.sort_by_key(|&p| pairs[p].1); + let groups: Vec<&[usize]> = order.chunk_by(|&a, &b| pairs[a].1 == pairs[b].1).collect(); + let toks: Vec> = groups.iter().map(|g| g.iter().map(|&p| pairs[p].0).collect()).collect(); + let gu: Vec<(Tensor, &[usize])> = groups.iter().zip(&toks).flat_map(|(g, t)| { let e = pairs[g[0]].1; [(gate.expert(e, n), t.as_slice()), (up.expert(e, n), t.as_slice())] }).collect(); + // Pair p is input j of group g: (group start in units of rows, group size, j). + let mut loc = vec![(0, 0, 0); k]; + let mut at = 0; + for g in &groups { + for (j, &p) in g.iter().enumerate() { loc[p] = (at, g.len(), j); } + at += g.len(); + } + let mut tmp = vec![0f32; 2 * k * ff]; + group_rows(&gu, hs, &mut tmp); + // tmp: per group, gate then up, ff rows each of the group's inputs. + let acts: Vec> = loc.par_iter().map(|&(at, gl, j)| { + let (g, u) = (&tmp[2 * ff * at..], &tmp[2 * ff * at + ff * gl..]); + (0..ff).map(|i| ops::silu(g[i * gl + j]) * u[i * gl + j]).collect() + }).collect(); + let racts: Option>> = rot.map(|r| acts.iter().map(|a| r.rotated(a)).collect()); + let ds: Vec<(Tensor, &[usize])> = groups.iter().map(|g| (down.expert(pairs[g[0]].1, n), *g)).collect(); + let ne = c.n_embd; + let mut tmp = vec![0f32; k * ne]; + group_rows(&ds, racts.as_ref().unwrap_or(&acts), &mut tmp); + let mut o = vec![0f32; k * ne]; + o.par_chunks_mut(ne).zip(&loc).for_each(|(o, &(at, gl, j))| { + for (r, v) in o.iter_mut().enumerate() { *v = tmp[ne * at + r * gl + j]; } + }); + for (j, (oj, &(_, e, _))) in o.chunks_exact_mut(ne).zip(pairs).enumerate() { + m.lora_delta(&format!("blk.{il}.ffn_down_exps.weight"), &acts[j], oj, Some(e)); + } + return o; + } let xs: Vec<&[f32]> = pairs.iter().map(|&(t, ..)| hs[t].as_slice()).collect(); let mut a = vec![0f32; 2 * k * ff]; if gate.ty == up.ty { @@ -1578,11 +3566,10 @@ pub fn experts_multi(m: &Model, il: usize, hs: &[Vec], sels: &[Vec<(usize, let ds: Vec = pairs.iter().map(|&(_, e, _)| down.expert(e, n)).collect(); let mut o = vec![0f32; k * c.n_embd]; batch_rows(&ds, &racts.as_ref().unwrap_or(&acts).iter().map(|v| v.as_slice()).collect::>(), &mut o); - for (j, (oj, &(t, e, w))) in o.chunks_exact_mut(c.n_embd).zip(&pairs).enumerate() { + for (j, (oj, &(_, e, _))) in o.chunks_exact_mut(c.n_embd).zip(pairs).enumerate() { m.lora_delta(&format!("blk.{il}.ffn_down_exps.weight"), &acts[j], oj, Some(e)); - for (yy, oo) in ys[t].iter_mut().zip(oj.iter()) { *yy += w * oo; } } - ys + o } #[cfg(test)] @@ -1592,13 +3579,19 @@ mod tests { /// A 4-activation kernel must give the bits of the single kernel (72 blocks, and 9: an odd count). #[test] fn dot4_matches_four_dots() { - for ty in [GgmlType::Q8_0, GgmlType::IQ4NL] { + for ty in [GgmlType::PTQ1_0, GgmlType::PTQ1R, GgmlType::TQ2_0, GgmlType::Q8_0, GgmlType::IQ4NL, GgmlType::Q5K, GgmlType::Q6K, GgmlType::Q4K, GgmlType::Q2K, GgmlType::Q3K, GgmlType::IQ2XXS, GgmlType::IQ2XS, GgmlType::IQ2S, GgmlType::IQ3XXS, GgmlType::IQ3S, GgmlType::IQ1S, GgmlType::IQ1M, GgmlType::Q2_0, GgmlType::IQ4XS] { let (Some(dot), Some(dot4)) = (int_dot(ty), int_dot4(ty)) else { continue }; - for cols in [2304usize, 288] { + // Offsets of the f16 scales after the first one. + let more: &[usize] = match ty { GgmlType::PTQ1_0 => &[26], GgmlType::PTQ1R => &[32], GgmlType::TQ2_0 => &[64], GgmlType::Q2K => &[80, 82], GgmlType::Q3K => &[108], GgmlType::Q4K | GgmlType::Q5K => &[2], _ => &[] }; + for cols in [2304usize, 288, 640, 2560].into_iter().filter(|c| c % ty.block_elems() == 0) { let rb = ty.row_bytes(cols as u64); let mut row: Vec = (0..rb).map(|i| (i * 37 % 251) as u8).collect(); // A valid f16 scale in each block (1.0, 1.5, ...). - for (i, b) in row.chunks_exact_mut(rb / (cols / 32)).enumerate() { b[..2].copy_from_slice(&[0, 0x3C + (i % 4) as u8]); } + for (i, b) in row.chunks_exact_mut(ty.block_bytes()).enumerate() { + for &o in [0].iter().chain(more) { b[o..o + 2].copy_from_slice(&[0, 0x3C + (i % 4) as u8]); } + // IQ1_M keeps its f16 scale in the top nibbles of bytes 49, 51, 53, 55: 0x3C00 = 1.0. + if ty == GgmlType::IQ1M { b[49] &= 0x0F; b[51] &= 0x0F; b[53] = b[53] & 0x0F | 0xC0; b[55] = b[55] & 0x0F | 0x30; } + } let xq: Vec<_> = (0..4).map(|t| quantize_q8k(&(0..cols).map(|i| ((i * 13 + t * 29) % 97) as f32 * 0.37 - 17.0).collect::>())).collect(); let got = dot4(&row, [&xq[0], &xq[1], &xq[2], &xq[3]]); for (g, x) in got.iter().zip(&xq) { assert_eq!(g.to_bits(), dot(&row, x).to_bits(), "{ty:?}, {cols} values"); } @@ -1606,6 +3599,93 @@ mod tests { } } + /// The 8-row prefill tiles give the bits of the scalar dot per (row, activation), with maddubs and (where the CPU + /// has it) with VNNI, for 6 activations (one group of 4 and two single ones) and 16 rows, and so the bits of + /// `int_dot` and `int_dot4`: a chunked prefill gives the bits of token-by-token decode. + #[test] + fn x8_tiles_match_dots() { + let (cols, rows, n) = (2304usize, 16usize, 6usize); + // Type, block bytes, offset of the f16 scale(s) to keep in range, scalar dot. + let cases: [(GgmlType, usize, usize, fn(&[u8], &[Q8K]) -> f32); 5] = [ + (GgmlType::Q4K, 144, 0, dot_q4k), (GgmlType::Q6K, 210, 208, dot_q6k), + (GgmlType::Q3K, 110, 108, dot_q3k), (GgmlType::Q2K, 84, 80, dot_q2k), (GgmlType::Q8_0, 34, 0, dot_q8_0)]; + let xq: Vec<_> = (0..n).map(|t| quantize_q8k(&(0..cols).map(|i| ((i * 13 + t * 29) % 97) as f32 * 0.37 - 17.0).collect::>())).collect(); + for (ty, bb, at, scalar) in cases { + let rb = ty.row_bytes(cols as u64); + let mut w: Vec = (0..rows * rb).map(|i| (i * 37 % 251) as u8).collect(); + for (i, b) in w.chunks_exact_mut(bb).enumerate() { + let f = [0, 0x2C + (i % 4) as u8, 0x66, 0x2E + (i % 3) as u8]; + let k = 4.min(bb - at); + b[at..at + k].copy_from_slice(&f[..k]); + } + let (dot, dot4) = (int_dot(ty).unwrap(), int_dot4(ty).unwrap()); + #[allow(unused_mut)] + let mut runs: Vec<(&str, Vec)> = vec![]; + #[cfg(target_feature = "avx2")] + { + let mut o = vec![0f32; rows * n]; + assert!(avx2::rows_x8::(ty, &w, rb, &xq, 0.5, &mut o)); + runs.push(("maddubs", o)); + if avx2::has_avx512_vl() { + let mut o = vec![0f32; rows * n]; + assert!(avx2::vl::rows_x8(ty, &w, rb, &xq, 0.5, &mut o)); + runs.push(("vnni", o)); + } + } + for (k, o) in &runs { + for r in 0..rows { + let row = &w[r * rb..(r + 1) * rb]; + let v4 = dot4(row, [&xq[0], &xq[1], &xq[2], &xq[3]]); + for t in 0..4 { assert_eq!(o[r * n + t].to_bits(), (v4[t] * 0.5).to_bits(), "{} {k}: int_dot4, row {r} token {t}", ty.name()); } + for t in 0..n { + let (got, want) = (o[r * n + t], scalar(row, &xq[t]) * 0.5); + assert_eq!(got.to_bits(), want.to_bits(), "{} {k}: scalar, row {r} token {t}", ty.name()); + let id = dot(row, &xq[t]) * 0.5; + assert_eq!(got.to_bits(), id.to_bits(), "{} {k}: int_dot, row {r} token {t}", ty.name()); + } + } + } + } + } + + /// `group_rows` gives the bits of separate dots, with groups of 1, 5 and 2 inputs. + #[test] + fn group_rows_match_single_dots() { + let (cols, rows) = (512, 37); + let xs: Vec> = (0..4).map(|t| (0..cols).map(|i| ((i * 13 + t * 29) % 97) as f32 * 0.37 - 17.0).collect()).collect(); + let xq: Vec<_> = xs.iter().map(|x| quantize_q8k(x)).collect(); + let groups: [&[usize]; 5] = [&[2], &[0, 1, 3, 2, 0], &[3, 1], &[1, 2, 3], &[0, 1, 2, 3, 0, 1, 2]]; + for ty in [GgmlType::F16, GgmlType::Q8_0, GgmlType::IQ4NL, GgmlType::Q2_0, + GgmlType::IQ2XXS, GgmlType::IQ2XS, GgmlType::IQ2S, GgmlType::IQ3XXS, GgmlType::IQ3S, GgmlType::IQ4XS] { + let rb = ty.row_bytes(cols as u64); + let bb = ty.block_bytes(); + let data: Vec> = (0..groups.len()).map(|m| { + let mut v: Vec = (0..rows * rb).map(|i| ((i * 37 + m * 11) % 251) as u8).collect(); + for (i, b) in v.chunks_exact_mut(bb).enumerate() { b[..2].copy_from_slice(&[0, 0x3C + (i % 4) as u8]); } + v + }).collect(); + let mats: Vec<(Tensor, &[usize])> = data.iter().zip(groups).map(|(d, g)| (Tensor { ty, cols, rows, data: d, scale: 0.5 }, g)).collect(); + let mut got = vec![0f32; rows * groups.iter().map(|g| g.len()).sum::()]; + group_rows(&mats, &xs, &mut got); + let (dot, mut at) = (int_dot(ty), 0); + let mut row = vec![0.0; cols]; + for (t, g) in &mats { + for r in 0..rows { + for &x in g.iter() { + let want = if let Some(dot) = dot { + dot(&t.data[r * rb..(r + 1) * rb], &xq[x]) * t.scale + } else { + t.row(r, &mut row); + row.iter().zip(&xs[x]).map(|(a, b)| a * b).sum() + }; + assert_eq!(got[at].to_bits(), want.to_bits(), "{ty:?} row {r}"); + at += 1; + } + } + } + } + } + /// Batch boundaries can cross matrices; both Q2_0 and the f32 fallback must use the right input row. #[test] fn batch_rows_match_individual_matvecs() { @@ -1643,6 +3723,69 @@ mod tests { } } + /// Single-thread speed of the trellis kernels: `cargo test --release --lib tq_dot_speed -- --ignored --nocapture`. + #[test] + #[ignore] + fn tq_dot_speed() { + let mut r = 0x9E3779B97F4A7C15u64; + let mut rnd = || { r ^= r << 13; r ^= r >> 7; r ^= r << 17; r as u8 }; + let (n, rows) = (2048, 512); + let x: Vec = (0..n).map(|i| ((i as f32 * 0.7548777).fract() - 0.5) * 2.0).collect(); + for ty in [GgmlType::TQ2T, GgmlType::TQK6, GgmlType::TQK7] { + let rb = n / 128 * ty.block_bytes(); + let mut m: Vec = (0..rows * rb).map(|_| rnd()).collect(); + for b in m.chunks_exact_mut(ty.block_bytes()) { b[..2].copy_from_slice(&f16::from_f32(0.01).to_le_bytes()); } + let dot = float_dot(ty).unwrap(); + let t = std::time::Instant::now(); + let mut s = 0f32; + for _ in 0..20 { for row in m.chunks_exact(rb) { s += dot(row, &x); } } + println!("{}: {:.1} ns a block ({s})", ty.name(), t.elapsed().as_nanos() as f64 / (20 * rows * n / 128) as f64); + #[cfg(target_feature = "avx2")] + { + let dot = match ty { GgmlType::TQ2T => avx2::dot_tq_i::<34>, GgmlType::TQK6 => avx2::dot_tq_i::<26>, _ => avx2::dot_tq_i::<30> }; + let xq = quantize_q8k(&x); + let t = std::time::Instant::now(); + let mut s = 0f32; + for _ in 0..20 { for row in m.chunks_exact(rb) { s += dot(row, &xq); } } + println!("{} int: {:.1} ns a block ({s})", ty.name(), t.elapsed().as_nanos() as f64 / (20 * rows * n / 128) as f64); + if ty != GgmlType::TQ2T && avx2::has_avx512_tq() { + // Interleaved, best of 15: the box is shared. + let k: [(&str, fn(&[u8], &[Q8K]) -> f32); 2] = if ty == GgmlType::TQK6 { [("avx2", avx2::dot_tq_i::<26>), ("avx512", avx2::dot_tq_v::<26>)] } + else { [("avx2", avx2::dot_tq_i::<30>), ("avx512", avx2::dot_tq_v::<30>)] }; + let mut best = [f64::MAX; 2]; + for _ in 0..15 { for (j, (_, dot)) in k.iter().enumerate() { + let t = std::time::Instant::now(); + let mut s = 0f32; + for _ in 0..4 { for row in m.chunks_exact(rb) { s += dot(row, &xq); } } + std::hint::black_box(s); + best[j] = best[j].min(t.elapsed().as_nanos() as f64 / (4 * rows * n / 128) as f64); + } } + for (j, (name, _)) in k.iter().enumerate() { println!("{} int {name}: best {:.1} ns a block", ty.name(), best[j]); } + } + } + } + } + + /// The AVX-512 trellis kernel gives the bits of the AVX2 one (rows of 640 and 2560 values, random activations). + #[cfg(target_feature = "avx2")] + #[test] + fn tq_avx512_matches_avx2() { + if !avx2::has_avx512_tq() { return eprintln!("no AVX-512 VBMI/VNNI: skipped"); } + let mut r = 0x9E3779B97F4A7C15u64; + let mut rnd = || { r ^= r << 13; r ^= r >> 7; r ^= r << 17; r }; + for n in [640, 2560] { + let x: Vec = (0..n).map(|_| (rnd() % 20001) as f32 / 10000.0 - 1.0).collect(); + let xq = quantize_q8k(&x); + for (ty, a, b) in [(GgmlType::TQK6, avx2::dot_tq_i::<26> as fn(&[u8], &[Q8K]) -> f32, avx2::dot_tq_v::<26> as fn(&[u8], &[Q8K]) -> f32), (GgmlType::TQK7, avx2::dot_tq_i::<30>, avx2::dot_tq_v::<30>)] { + for _ in 0..200 { + let mut row: Vec = (0..n / 128 * ty.block_bytes()).map(|_| rnd() as u8).collect(); + for blk in row.chunks_exact_mut(ty.block_bytes()) { blk[..2].copy_from_slice(&f16::from_f32(0.001 + (rnd() % 100) as f32 * 1e-4).to_le_bytes()); } + assert_eq!(a(&row, &xq).to_bits(), b(&row, &xq).to_bits(), "{} n {n}", ty.name()); + } + } + } + } + /// The trellis kernels equal the f32 dequantized dot on random blocks. #[test] fn tq_dots_match_dequant() { @@ -1657,7 +3800,83 @@ mod tests { let want: f64 = w.iter().zip(&x).map(|(&a, &b)| a as f64 * b as f64).sum(); let got = float_dot(ty).unwrap()(&row, &x); assert!(((got as f64 - want) / want.abs().max(1e-3)).abs() < 1e-5, "{}: {got} vs {want}", ty.name()); + #[cfg(target_feature = "avx2")] + { + let dot = match ty { GgmlType::TQ2T => avx2::dot_tq_i::<34>, GgmlType::TQK6 => avx2::dot_tq_i::<26>, _ => avx2::dot_tq_i::<30> }; + let mut xp = x.clone(); + xp.resize(768, 0.0); + let gi = dot(&row, &quantize_q8k(&xp)) as f64; + let l1: f64 = w.iter().zip(&x).map(|(&a, &b)| (a as f64 * b as f64).abs()).sum(); + assert!((gi - want).abs() < 1e-2 * l1, "{} int: {gi} vs {want}", ty.name()); + } + } + } + + #[test] + fn shared_integer_layouts_match_dequant_and_batch() { + let types = [ + GgmlType::Q1_0, GgmlType::Q2_0, GgmlType::PQ2_0, GgmlType::Q2K, GgmlType::Q3K, + GgmlType::Q4_0, GgmlType::Q4_1, GgmlType::Q4K, GgmlType::Q5_0, GgmlType::Q5_1, + GgmlType::Q5K, GgmlType::Q6K, GgmlType::Q8_0, GgmlType::Q8_1, GgmlType::Q8K, GgmlType::MXFP4, + GgmlType::IQ1S, GgmlType::IQ1M, GgmlType::IQ2XXS, GgmlType::IQ2XS, GgmlType::IQ2S, + GgmlType::IQ3XXS, GgmlType::IQ3S, GgmlType::IQ4NL, GgmlType::IQ4XS, + GgmlType::NVFP4, GgmlType::PTQ1_0, GgmlType::TQ1_0, GgmlType::TQ2_0, + ]; + for ty in types { + let cols = 512 + ty.block_elems(); + let mut row: Vec = (0..ty.row_bytes(cols as u64)).map(|i| (47 * i + 19) as u8).collect(); + for (i, b) in row.chunks_exact_mut(ty.block_bytes()).enumerate() { + let set = |b: &mut [u8], at, value| b[at..at + 2].copy_from_slice(&f16::from_f32(value).to_le_bytes()); + let d = if i % 2 == 0 { 0.03125 } else { -0.0234375 }; + match ty { + GgmlType::IQ1M => { + let bits = f16::from_f32(d).to_bits(); + for j in 0..4 { + let at = 49 + 2 * j; + b[at] = b[at] & 15 | ((bits >> (j * 4)) as u8 & 15) << 4; + } + } + GgmlType::Q2K => { set(b, 80, d); set(b, 82, 0.015625); } + GgmlType::Q3K => set(b, 108, d), + GgmlType::Q6K => set(b, 208, d), + GgmlType::PTQ1_0 => set(b, 26, d), + GgmlType::TQ1_0 => set(b, 52, d), + GgmlType::TQ2_0 => set(b, 64, d), + GgmlType::Q8K => b[..4].copy_from_slice(&d.to_le_bytes()), + GgmlType::MXFP4 => b[0] = 123, + GgmlType::NVFP4 => b[..4].copy_from_slice(&[0x38, 0x41, 0x28, 0x39]), + GgmlType::Q4K | GgmlType::Q5K | GgmlType::Q4_1 | GgmlType::Q5_1 => { + set(b, 0, d); + set(b, 2, -0.015625); + } + _ => set(b, 0, d), + } + } + let xs: [Vec; 4] = std::array::from_fn(|t| { + let x: Vec<_> = (0..cols).map(|i| ((i * 13 + t * 23) % 121) as f32 - 60.0).collect(); + quantize_q8k(&x) + }); + let mut weights = vec![0.0; cols]; + crate::quant::dequant_row(ty, &row, &mut weights); + let scalar = affine_dot1::(ty).unwrap(); + let simd = affine_dot1::(ty).unwrap(); + let batch = affine_kernel::<4, true>(ty).unwrap()(&row, xs.each_ref().map(Vec::as_slice)); + for (i, x) in xs.iter().enumerate() { + let mut expected = 0.0f64; + let mut magnitude = 0.0f64; + for (j, &w) in weights.iter().enumerate() { + let p = w as f64 * x[j / 256].d as f64 * x[j / 256].qs[j % 256] as f64; + expected += p; + magnitude += p.abs(); + } + let got = simd(&row, x); + assert_eq!(got.to_bits(), scalar(&row, x).to_bits(), "{ty:?}"); + assert_eq!(got.to_bits(), batch[i].to_bits(), "{ty:?}"); + assert!((got as f64 - expected).abs() <= 1e-6 * magnitude.max(1.0), "{ty:?}: {got} vs {expected}"); + } } + assert!(affine_dot1::(GgmlType::TQK7).is_none()); + assert!(affine_dot1::(GgmlType::F16).is_none()); } /// Every integer kernel (scalar and, when built, AVX2) equals the f32 dequantized dot on random blocks. @@ -1666,13 +3885,13 @@ mod tests { let mut r = 0x9E3779B97F4A7C15u64; let mut rnd = || { r ^= r << 13; r ^= r >> 7; r ^= r << 17; r as u8 }; let x: Vec = (0..1024).map(|i| ((i as f32 * 0.7548777).fract() - 0.5) * 2.0).collect(); - for ty in [GgmlType::Q2_0, GgmlType::TQ1_0, GgmlType::Q4_0, GgmlType::Q4_1, GgmlType::Q5_0, GgmlType::Q5_1, GgmlType::IQ2XS, GgmlType::IQ3XXS, GgmlType::IQ3S, GgmlType::IQ4XS, GgmlType::Q6K, GgmlType::Q2K, GgmlType::Q3K, GgmlType::Q4K, GgmlType::Q5K, GgmlType::Q8_0, GgmlType::IQ2XXS, GgmlType::IQ2S, GgmlType::IQ1S, GgmlType::IQ1M, GgmlType::IQ4NL, GgmlType::NVFP4] { + for ty in [GgmlType::PTQ1_0, GgmlType::PTQ1R, GgmlType::TQ2_0, GgmlType::Q2_0, GgmlType::TQ1_0, GgmlType::Q4_0, GgmlType::Q4_1, GgmlType::Q5_0, GgmlType::Q5_1, GgmlType::IQ2XS, GgmlType::IQ3XXS, GgmlType::IQ3S, GgmlType::IQ4XS, GgmlType::Q6K, GgmlType::Q2K, GgmlType::Q3K, GgmlType::Q4K, GgmlType::Q5K, GgmlType::Q8_0, GgmlType::IQ2XXS, GgmlType::IQ2S, GgmlType::IQ1S, GgmlType::IQ1M, GgmlType::IQ4NL, GgmlType::NVFP4] { // Q2_0 at 640 values exercises the zero-padded last Q8_K block. - let n = match ty { GgmlType::Q2_0 => 640, GgmlType::IQ4NL => 672, GgmlType::NVFP4 => 704, _ => 1024 }; + let n = match ty { GgmlType::PTQ1_0 | GgmlType::PTQ1R | GgmlType::Q2_0 => 640, GgmlType::IQ4NL => 672, GgmlType::NVFP4 => 704, _ => 1024 }; let xq = quantize_q8k(&x[..n]); let mut row: Vec = (0..n / ty.block_elems() * ty.block_bytes()).map(|_| rnd()).collect(); // Offsets of the f16 scales (d, and dmin where the type has one). - let fs: &[usize] = match ty { GgmlType::TQ1_0 => &[52], GgmlType::Q6K => &[208], GgmlType::Q2K => &[80, 82], GgmlType::Q3K => &[108], GgmlType::Q4K | GgmlType::Q5K | GgmlType::Q4_1 | GgmlType::Q5_1 => &[0, 2], GgmlType::IQ1M | GgmlType::NVFP4 => &[], _ => &[0] }; + let fs: &[usize] = match ty { GgmlType::PTQ1_0 => &[26], GgmlType::PTQ1R => &[32], GgmlType::TQ2_0 => &[64], GgmlType::TQ1_0 => &[52], GgmlType::Q6K => &[208], GgmlType::Q2K => &[80, 82], GgmlType::Q3K => &[108], GgmlType::Q4K | GgmlType::Q5K | GgmlType::Q4_1 | GgmlType::Q5_1 => &[0, 2], GgmlType::IQ1M | GgmlType::NVFP4 => &[], _ => &[0] }; for b in row.chunks_exact_mut(ty.block_bytes()) { for &o in fs { b[o..o + 2].copy_from_slice(&f16::from_f32(0.01).to_le_bytes()); } } if ty == GgmlType::NVFP4 { for b in row.chunks_exact_mut(36) { for s in 0..4 { b[s] = 0x20 + (b[s] & 0x1F); } } @@ -1685,13 +3904,82 @@ mod tests { let mut w = vec![0f32; n]; crate::quant::dequant_row(ty, &row, &mut w); let want: f64 = w.iter().enumerate().map(|(i, &v)| v as f64 * (xq[i / 256].d * xq[i / 256].qs[i % 256] as f32) as f64).sum(); - let scalar = match ty { GgmlType::TQ1_0 => dot_tq1_0, GgmlType::IQ2XS => dot_iq2xs, GgmlType::IQ3XXS => dot_iq3xxs, GgmlType::IQ3S => dot_iq3s, GgmlType::Q6K => dot_q6k, GgmlType::Q2K => dot_q2k, GgmlType::Q3K => dot_q3k, GgmlType::Q4K => dot_q4k, GgmlType::Q5K => dot_q5k, GgmlType::Q8_0 => dot_q8_0, GgmlType::IQ2XXS => dot_iq2xxs, GgmlType::IQ2S => dot_iq2s, GgmlType::IQ1S => dot_iq1s, GgmlType::IQ1M => dot_iq1m, GgmlType::Q2_0 => dot_q2_0, GgmlType::Q4_0 => dot_q4::<2>, GgmlType::Q4_1 => dot_q4::<3>, GgmlType::Q5_0 => dot_q4::<6>, GgmlType::Q5_1 => dot_q4::<7>, GgmlType::IQ4NL => dot_iq4nl, GgmlType::NVFP4 => dot_nvfp4, _ => dot_iq4xs }; + let scalar = match ty { GgmlType::PTQ1_0 | GgmlType::PTQ1R | GgmlType::TQ2_0 => affine_dot1::(ty).unwrap(), GgmlType::TQ1_0 => dot_tq1_0, GgmlType::IQ2XS => dot_iq2xs, GgmlType::IQ3XXS => dot_iq3xxs, GgmlType::IQ3S => dot_iq3s, GgmlType::Q6K => dot_q6k, GgmlType::Q2K => dot_q2k, GgmlType::Q3K => dot_q3k, GgmlType::Q4K => dot_q4k, GgmlType::Q5K => dot_q5k, GgmlType::Q8_0 => dot_q8_0, GgmlType::IQ2XXS => dot_iq2xxs, GgmlType::IQ2S => dot_iq2s, GgmlType::IQ1S => dot_iq1s, GgmlType::IQ1M => dot_iq1m, GgmlType::Q2_0 => dot_q2_0, GgmlType::Q4_0 => dot_q4::<2>, GgmlType::Q4_1 => dot_q4::<3>, GgmlType::Q5_0 => dot_q4::<6>, GgmlType::Q5_1 => dot_q4::<7>, GgmlType::IQ4NL => dot_iq4nl, GgmlType::NVFP4 => dot_nvfp4, _ => dot_iq4xs }; for got in [scalar(&row, &xq), int_dot(ty).unwrap()(&row, &xq)] { assert!(((got as f64 - want) / want.abs().max(1e-3)).abs() < 1e-5, "{}: {got} vs {want}", ty.name()); } } } + /// The shared-kernel mode is read once, so a later change of the environment does not reach the hot path. + #[test] + fn prefer_shared_int_is_read_once() { + let first = prefer_shared_int(); + let flipped = if first { "0" } else { "1" }; + unsafe { std::env::set_var("STRATA_CPU_SHARED_INT", flipped); } + let later = prefer_shared_int(); + unsafe { std::env::remove_var("STRATA_CPU_SHARED_INT"); } + assert_eq!(first, later); + } + + /// Q8_K activations stay in -127..=127 (the scale maps the largest magnitude to 127), which the kernels that negate + /// an activation with `_mm256_sign_epi8` (PTQ1_0, IQ2/IQ3) rely on: -128 would not negate. + #[test] + fn q8k_never_holds_minus_128() { + let mut r = 0x9E3779B97F4A7C15u64; + let mut rnd = || { r ^= r << 13; r ^= r >> 7; r ^= r << 17; (r >> 40) as f32 / (1u64 << 24) as f32 - 0.5 }; + for amax in [1e-30f32, 1e-3, 1.0, 3.7, 1e30] { + let mut x: Vec = (0..1024).map(|_| rnd() * 2.0 * amax).collect(); + x[7] = -amax; + x[300] = amax; + x[600] = -amax; + for b in quantize_q8k(&x) { assert!(b.qs.iter().all(|&q| q >= -127), "amax {amax}"); } + } + } + + /// The PTQ1_0R tiles of the batched and single-token paths give the bits of `int_dot` per row and activation. + #[test] + fn ptq1r_tiles_match_dot() { + let (rows, cols, n) = (45usize, 640usize, 7usize); + let rb = GgmlType::PTQ1R.row_bytes(cols as u64); + let mut data: Vec = (0..rows * rb).map(|i| (i * 37 % 251) as u8 & 0xAA | (i * 11 % 7) as u8 & 0x55).collect(); + for (i, b) in data.chunks_exact_mut(34).enumerate() { b[32..34].copy_from_slice(&f16::from_f32(0.01 + 0.001 * (i % 13) as f32).to_le_bytes()); } + let t = Tensor { ty: GgmlType::PTQ1R, cols, rows, data: &data, scale: 1.5 }; + let xq: Vec> = (0..n).map(|k| quantize_q8k(&(0..cols).map(|i| ((i * 13 + k * 29) % 97) as f32 * 0.37 - 17.0).collect::>())).collect(); + let dot = int_dot(GgmlType::PTQ1R).unwrap(); + let batched = matmul_q8k(&t, &xq, dot); + for (j, x) in xq.iter().enumerate() { + let mut y = vec![0f32; rows]; + matvec_q8k(&t, x, &mut y, dot); + for r in 0..rows { + let want = dot(&data[r * rb..(r + 1) * rb], x) * t.scale; + assert_eq!((y[r].to_bits(), batched[j][r].to_bits()), (want.to_bits(), want.to_bits()), "row {r}, activation {j}"); + } + } + } + + /// PTQ1_0R holds the values of the PTQ1_0 blocks it was repacked from, and its kernel the same integer dot. + #[test] + fn ptq1_0_repack_keeps_values() { + let mut r = 0x2545F4914F6CDD1Du64; + let mut rnd = || { r ^= r << 13; r ^= r >> 7; r ^= r << 17; r as u8 }; + let n = 1024; + let mut src: Vec = (0..n / 128 * 28).map(|_| rnd() % 243).collect(); + for (i, b) in src.chunks_exact_mut(28).enumerate() { + b[24] %= 81; b[25] %= 81; + b[26..28].copy_from_slice(&f16::from_f32(0.01 * (i + 1) as f32).to_le_bytes()); + } + let mut dst = vec![0u8; n / 128 * 34]; + crate::quant::repack_ptq1_0(&src, &mut dst); + let (mut a, mut b) = (vec![0f32; n], vec![0f32; n]); + crate::quant::dequant_row(GgmlType::PTQ1_0, &src, &mut a); + crate::quant::dequant_row(GgmlType::PTQ1R, &dst, &mut b); + assert_eq!(a, b); + let xq = quantize_q8k(&(0..n).map(|i| ((i * 13) % 97) as f32 * 0.37 - 17.0).collect::>()); + let (old, new) = (int_dot(GgmlType::PTQ1_0).unwrap()(&src, &xq), int_dot(GgmlType::PTQ1R).unwrap()(&dst, &xq)); + assert!(((old - new) / old.abs().max(1e-3)).abs() < 1e-5, "{old} vs {new}"); + } + #[test] fn f8_e4m3_dot_and_scale_match_dequant() { let mut r = 0x517CC1B727220A95u64; @@ -1709,6 +3997,85 @@ mod tests { } } + #[test] + fn ready_down_chunks_skip_pending_experts() { + use std::sync::atomic::{AtomicUsize, Ordering::Release}; + + let chunks = [AtomicUsize::new(usize::MAX), AtomicUsize::new(2)]; + let mut cursor = 0; + assert_eq!(claim_down(&chunks, &mut cursor, 2), Some((1, 0))); + assert_eq!(claim_down(&chunks, &mut cursor, 2), Some((1, 1))); + + chunks[0].store(2, Release); + assert_eq!(claim_down(&chunks, &mut cursor, 2), Some((0, 0))); + assert_eq!(claim_down(&chunks, &mut cursor, 2), Some((0, 1))); + assert_eq!(claim_down(&chunks, &mut cursor, 2), None); + } + + /// The full offset batches and each tail length give the bits of individual dots. + #[test] + fn offset_row_group_matches_single_dots() { + let mut r = 0x5851F42D4C957F2Du64; + let mut rnd = || { r ^= r << 13; r ^= r >> 7; r ^= r << 17; r as u8 }; + let xs: Vec> = (0..32).map(|t| quantize_q8k(&(0..2560).map(|i| ((i as f32 * 0.7548777 + t as f32 * 0.37).fract() - 0.5) * (1.0 + t as f32)).collect::>())).collect(); + let xf: Vec> = xs.iter().map(|x| x.iter().map(flip).collect()).collect(); + let group: Vec<_> = (0..xs.len()).rev().collect(); + for ty in [GgmlType::IQ2XXS, GgmlType::IQ2XS, GgmlType::IQ2S, GgmlType::IQ3XXS, GgmlType::IQ3S] { + let (Some(d16), Some(d8), Some(dot)) = (int_dot16_off(ty), int_dot8_off(ty), int_dot(ty)) else { continue }; + let mut row: Vec = (0..2560 / ty.block_elems() * ty.block_bytes()).map(|_| rnd()).collect(); + for b in row.chunks_exact_mut(ty.block_bytes()) { b[0..2].copy_from_slice(&f16::from_f32(0.01).to_le_bytes()); } + let scale = 0.75; + for len in 0..=group.len() { + let mut out = vec![f32::NAN; len]; + row_group(&row, &group[..len], &xs, &mut out, scale, dot, None, None, Some((d16, d8, &xf)), None); + for (j, (&v, &t)) in out.iter().zip(&group).enumerate() { + assert_eq!(v.to_bits(), (dot(&row, &xs[t]) * scale).to_bits(), "{} group of {len}, output {j}", ty.name()); + } + } + } + } + + /// `int_dot8` gives `int_dot`'s bits for each of its eight activations. + #[test] + fn dot8_matches_single_dots() { + let mut r = 0x2545F4914F6CDD1Du64; + let mut rnd = || { r ^= r << 13; r ^= r >> 7; r ^= r << 17; r as u8 }; + for (ty, n) in [(GgmlType::IQ2XXS, 2560), (GgmlType::IQ2XS, 2560), (GgmlType::IQ2S, 2560), (GgmlType::IQ3XXS, 2560), (GgmlType::IQ3S, 2560), (GgmlType::Q2_0, 640), (GgmlType::IQ4NL, 640)] { + let (Some(d8), Some(d1)) = (int_dot8(ty), int_dot(ty)) else { continue }; + let xs: Vec> = (0..8).map(|t| quantize_q8k(&(0..n).map(|i| ((i as f32 * 0.7548777 + t as f32 * 0.37).fract() - 0.5) * (1.0 + t as f32)).collect::>())).collect(); + let mut row: Vec = (0..n / ty.block_elems() * ty.block_bytes()).map(|_| rnd()).collect(); + for b in row.chunks_exact_mut(ty.block_bytes()) { b[0..2].copy_from_slice(&f16::from_f32(0.01).to_le_bytes()); } + let v = d8(&row, std::array::from_fn(|i| &xs[i][..])); + for t in 0..8 { assert_eq!(v[t].to_bits(), d1(&row, &xs[t]).to_bits(), "{} activation {t}", ty.name()); } + } + } + + /// The AVX-512 grid kernels (`avx2::z`) give the AVX2 kernels' bits on random blocks (random scales and signs). + #[cfg(target_feature = "avx2")] + #[test] + fn z_grid_dots_match_avx2() { + if !avx2::z::has() { return; } + let mut r = 0x9E3779B97F4A7C15u64; + let mut rnd = || { r ^= r << 13; r ^= r >> 7; r ^= r << 17; r as u8 }; + for seed in 0..64 { + let x: Vec = (0..2560).map(|i| ((i as f32 * 0.7548777 + seed as f32 * 0.31).fract() - 0.5) * (1.0 + seed as f32)).collect(); + let xq = quantize_q8k(&x); + let z: [(GgmlType, fn(&[u8], &[Q8K]) -> f32, fn(&[u8], &[Q8K]) -> f32); 5] = [ + (GgmlType::IQ3S, avx2::z::dot_iq3s, avx2::dot_iq3s), + (GgmlType::IQ2S, avx2::z::dot_iq2s, avx2::dot_iq2s), + (GgmlType::IQ2XXS, avx2::z::dot_iq2xxs, avx2::dot_iq2xxs), + (GgmlType::IQ2XS, avx2::z::dot_iq2xs, avx2::dot_iq2xs), + (GgmlType::IQ3XXS, avx2::z::dot_iq3xxs, avx2::dot_iq3xxs), + ]; + for (ty, zk, ak) in z { + let mut row: Vec = (0..2560 / ty.block_elems() * ty.block_bytes()).map(|_| rnd()).collect(); + for b in row.chunks_exact_mut(ty.block_bytes()) { b[0..2].copy_from_slice(&f16::from_f32(0.01).to_le_bytes()); } + let (a, b) = (zk(&row, &xq), ak(&row, &xq)); + assert_eq!(a.to_bits(), b.to_bits(), "{} seed {seed}: {a} vs {b}", ty.name()); + } + } + } + /// AVX-512 VNNI+VBMI kernels match AVX2 and scalar dequantized dot, including odd-block tails. #[cfg(all(target_arch = "x86_64", target_feature = "avx512f", target_feature = "avx512bw", target_feature = "avx512vnni", target_feature = "avx512vbmi"))] #[test] @@ -1785,3 +4152,4 @@ mod tests { } } } + diff --git a/src/cpu_worker.rs b/src/cpu_worker.rs index 4c89e139..bc977efa 100644 --- a/src/cpu_worker.rs +++ b/src/cpu_worker.rs @@ -6,7 +6,7 @@ use crate::model::Model; use crate::backend::{Backend, Buf}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering, fence}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering, fence}; use std::sync::{Arc, mpsc}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; @@ -25,6 +25,63 @@ pub const IDS: usize = 32; /// Most tokens one request may carry (1 current + up to 16 speculative draft tokens). pub const TMAX: usize = 17; +/// `--tail-skip R`, 0 = off: a CPU expert that every token of a request ranks at R or lower is neither read nor +/// computed, and its weight is dropped (the other weights are not rescaled), as PolyStrata's route tail skip. Experts +/// in VRAM always run. Process-wide, like `crate::ctx_limit`: set before the model loads. +static TAIL_SKIP: AtomicUsize = AtomicUsize::new(0); +/// CPU expert picks the workers saw while `--tail-skip` was on, and how many of them they dropped. +static TAIL_PICKS: AtomicU64 = AtomicU64::new(0); +static TAIL_DROPPED: AtomicU64 = AtomicU64::new(0); + +pub fn set_tail_skip(rank: usize) { TAIL_SKIP.store(rank, Ordering::Relaxed); } + +/// Which picks of a request run. `v` is a mailbox's ids, weight bits and slots, `kt` words each, for tokens of `k` +/// picks (token t at t * k); slot -1 is an expert on the CPU (-2: the GPU reads it from host memory). A CPU pick is +/// dropped when its expert's best rank over the request's tokens is `rank` or lower (0-based within the token, by +/// weight, ties by position): in a verify window an expert one token needs runs for all of them. GPU picks, and every +/// pick at `rank` 0, are kept. +pub fn tail_keep(v: &[u32], kt: usize, k: usize, rank: usize) -> Vec { + let mut keep = vec![true; kt]; + if rank == 0 { return keep; } + let w = |j: usize| f32::from_bits(v[kt + j]); + let cpu = |j: usize| v[2 * kt + j] as i32 == -1; + let rank_of = |j: usize| { let t0 = j / k * k; (t0..t0 + k).filter(|&i| w(i) > w(j) || (w(i) == w(j) && i < j)).count() }; + let mut best = std::collections::HashMap::::new(); + for j in (0..kt).filter(|&j| cpu(j)) { + let r = rank_of(j); + best.entry(v[j]).and_modify(|b| *b = (*b).min(r)).or_insert(r); + } + for j in (0..kt).filter(|&j| cpu(j)) { keep[j] = best[&v[j]] < rank; } + keep +} + +/// `tail_keep` with the rank in effect, counting the CPU picks it sees and drops. +pub(crate) fn tail_select(v: &[u32], kt: usize, k: usize) -> Vec { + let rank = TAIL_SKIP.load(Ordering::Relaxed); + let keep = tail_keep(v, kt, k, rank); + if rank > 0 { + let cpu = (0..kt).filter(|&j| v[2 * kt + j] as i32 == -1); + let (picks, dropped) = cpu.fold((0, 0), |(p, d), j| (p + 1, d + u64::from(!keep[j]))); + TAIL_PICKS.fetch_add(picks, Ordering::Relaxed); + TAIL_DROPPED.fetch_add(dropped, Ordering::Relaxed); + } + keep +} + +/// Token `t`'s CPU picks that run, as (expert, weight), and whether it had any CPU pick at all. A token whose CPU +/// picks were all dropped still needs its result written, as zeros: the combine adds it whenever a slot missed. +fn cpu_picks(v: &[u32], kt: usize, k: usize, t: usize, keep: &[bool]) -> (Vec<(usize, f32)>, bool) { + let cpu = |j: usize| v[2 * kt + j] as i32 == -1; + let sel = (t * k..(t + 1) * k).filter(|&j| cpu(j) && keep[j]).map(|j| (v[j] as usize, f32::from_bits(v[kt + j]))).collect(); + (sel, (t * k..(t + 1) * k).any(cpu)) +} + +/// The end-of-run line for `--tail-skip`, when it was on and the CPU had experts to run. +pub fn tail_skip_report() -> Option { + let (picks, dropped) = (TAIL_PICKS.load(Ordering::Relaxed), TAIL_DROPPED.load(Ordering::Relaxed)); + (picks > 0).then(|| format!("tail skip: {dropped} of {picks} CPU expert picks dropped ({:.1}%)", 100.0 * dropped as f64 / picks as f64)) +} + /// Per layer: ids, weights and slots for up to TMAX tokens of `k` entries (token t at t * k; the three arrays are /// each NTOK * k long), then TMAX activations of `n` floats at `h` and TMAX results at `y`. pub struct Mailbox { pub k: usize, pub n: usize, pub h: usize, pub y: usize, pub stride: usize } @@ -70,13 +127,29 @@ impl CpuWorker { let delay = std::env::var("STRATA_TEST_WORKER_DELAY").ok().and_then(|v| v.parse::().ok()).map(Duration::from_millis); // The loop runs on a thread of its own pool, so the expert passes start on it at once and it takes part // in them instead of sleeping until a woken pool finishes (~12 us less per layer). - let pool = rayon::ThreadPoolBuilder::new().num_threads(rayon::current_num_threads()) - .thread_name(|i| format!("strata-experts-{i}")).build()?; + // --pin: one pool thread a physical core but the first, which the thread driving the GPU takes. + let mut threads = rayon::current_num_threads(); + let cores = if m.w.g.moe.pin { pin_cores(threads.min(n_cores().saturating_sub(1)).max(1)) } else { None }; + if let Some(c) = &cores { threads = c.len(); pin_host(); } + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads) + .thread_name(|i| format!("strata-experts-{i}")) + .start_handler(move |i| if let Some(c) = cores.as_ref().and_then(|c| c.get(i)) { pin_to(*c) }) + .build()?; let thread = std::thread::Builder::new().name("strata-cpu-experts".into()).spawn(move || pool.install(move || { let m = unsafe { &*(mp as *const Model) }; // Missed experts not in the page cache are read from the drive: reading all of a layer's ahead keeps // the reads in flight together instead of one page fault at a time per compute thread. - let pre = crate::weights::Prefetch::start(); + // Not when the model fits in RAM (the preload keeps it in the page cache): the thread's madvise calls then + // only take CPU time from the expert threads, a core of the pinned pool (it inherits a pool thread's pin). + let pre = (!crate::weights::fits_ram()).then(crate::weights::Prefetch::start); + let fused_enabled = !m.w.g.moe.no_fused; + let fused: Vec = (0..=moe_layers.iter().copied().max().unwrap_or(0)) + .map(|il| fused_enabled && crate::cpu_moe::fused_experts_supported(m, il)).collect(); + let mut decode_scratch = crate::cpu_moe::DecodeExpertScratch::new(); + let mut route_words = Vec::new(); + let mut selected = Vec::new(); + let mut hidden_words = vec![0; m.cfg.n_embd]; + let mut hidden = vec![0.0; m.cfg.n_embd]; let w = |i: usize| host as *mut u32 as usize + 4 * i; while let Ok(seq) = rx.recv() { for &il in &moe_layers { @@ -84,13 +157,9 @@ impl CpuWorker { let at = |o: usize| (w(b + o)) as *mut u32; // Skip the layer on its skip flag, or on a newer seq anywhere (the GPU already moved on to the // next token, so it did not wait for this one). Waiting for the old seq would hang. - let ahead = |v: u32| v != 0 && (v.wrapping_sub(seq) as i32) >= 0; - let mut r; - while { r = unsafe { at(REQ).read_volatile() }; r != seq } { - if st.load(Ordering::Relaxed) { return; } - if ahead(r) || ahead(unsafe { at(SKIP).read_volatile() }) { break; } - std::hint::spin_loop(); - } + let req = || unsafe { at(REQ).read_volatile() }; + let skip = || unsafe { at(SKIP).read_volatile() }; + let Some(r) = wait_req_hot(seq, req, skip, &st) else { return }; if r != seq { continue; } // mfence: loads of write-combining memory (the Vulkan BAR mailbox) are weakly ordered, so an // acquire fence (no instruction on x86) would not keep them after the REQ load. @@ -101,23 +170,26 @@ impl CpuWorker { let (k, kt, n) = (lay.k, lay.k * nt, lay.n); // Bulk streaming reads, as in `routing`: plain loads of the Vulkan BAR mailbox are each an // uncached read (~130 us for one activation). - let mut v = vec![0u32; (3 * kt).next_multiple_of(4)]; - unsafe { read_wc(at(IDS), &mut v) }; - let missed: Vec = (0..kt).filter(|&j| (v[2 * kt + j] as i32) < 0).map(|j| v[j] as usize).collect(); - if !missed.is_empty() { + route_words.resize((3 * kt).next_multiple_of(4), 0); + unsafe { read_wc(at(IDS), &mut route_words) }; + let v = &route_words; + let keep = tail_select(v, kt, k); + // Slot -1: the CPU's (-2: the GPU reads it from host memory, the host share; >= 0: in VRAM). + if let Some(pre) = &pre { + let missed: Vec<_> = (0..kt).filter(|&j| v[2 * kt + j] as i32 == -1 && keep[j]).map(|j| v[j] as usize).collect(); // Gate and up first: they are read first. - pre.send(["ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight"].iter() + if !missed.is_empty() { pre.send(["ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight"].iter() .filter_map(|s| m.w.layer(il, s).ok()) .flat_map(|t| missed.iter().map(move |&e| { let d = t.expert(e, m.cfg.n_expert).data; (d.as_ptr() as usize, d.len()) }).collect::>()) - .collect()); + .collect()); } } + let zero = |t: usize| unsafe { std::ptr::write_bytes(at(lay.y + t * n) as *mut f32, 0, n) }; if nt > 1 { // A verify batch: one pass over each missed expert's weights for all of its tokens. let (mut hs, mut sels, mut rows) = (Vec::new(), Vec::new(), Vec::new()); for t in 0..nt { - let sel: Vec<(usize, f32)> = (t * k..(t + 1) * k).filter(|&j| (v[2 * kt + j] as i32) < 0) - .map(|j| (v[j] as usize, f32::from_bits(v[kt + j]))).collect(); - if sel.is_empty() { continue; } + let (sel, any) = cpu_picks(v, kt, k, t, &keep); + if sel.is_empty() { if any { zero(t) } continue; } let mut h = vec![0u32; n]; unsafe { read_wc(at(lay.h + t * n), &mut h) }; hs.push(h.into_iter().map(f32::from_bits).collect::>()); @@ -131,15 +203,23 @@ impl CpuWorker { } } } else { - for t in 0..nt { - let sel: Vec<(usize, f32)> = (t * k..(t + 1) * k).filter(|&j| (v[2 * kt + j] as i32) < 0) - .map(|j| (v[j] as usize, f32::from_bits(v[kt + j]))).collect(); - if sel.is_empty() { continue; } - let mut h = vec![0u32; n]; - unsafe { read_wc(at(lay.h + t * n), &mut h) }; - let h: Vec = h.into_iter().map(f32::from_bits).collect(); - let y = crate::cpu_moe::experts(m, il, &h, &sel); - unsafe { std::ptr::copy_nonoverlapping(y.as_ptr(), at(lay.y + t * n) as *mut f32, n) }; + selected.clear(); + selected.extend((0..k).filter(|&j| v[2 * kt + j] as i32 == -1 && keep[j]) + .map(|j| (v[j] as usize, f32::from_bits(v[kt + j])))); + if selected.is_empty() { + // Every CPU pick dropped: the combine still adds the result. + if (0..k).any(|j| v[2 * kt + j] as i32 == -1) { zero(0) } + } else { + unsafe { read_wc(at(lay.h), &mut hidden_words) }; + for (h, &word) in hidden.iter_mut().zip(&hidden_words) { *h = f32::from_bits(word); } + let owned; + let y = if fused[il] { + decode_scratch.run(m, il, &hidden, &selected) + } else { + owned = crate::cpu_moe::experts(m, il, &hidden, &selected); + &owned + }; + unsafe { std::ptr::copy_nonoverlapping(y.as_ptr(), at(lay.y) as *mut f32, n) }; } } // SeqCst fences (mfence on x86) also order and flush write-combining stores (Vulkan maps the @@ -149,6 +229,7 @@ impl CpuWorker { unsafe { at(DONE).write_volatile(seq) }; fence(Ordering::SeqCst); bn.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed); + } } }))?; @@ -195,9 +276,80 @@ impl CpuWorker { pub fn busy(&self) -> Duration { Duration::from_nanos(self.busy_ns.load(Ordering::Relaxed)) } } +/// Wait for the GPU to raise `seq` in a layer's request word: returns the word then, or as soon as it or the skip +/// word holds a newer seq (the GPU moved on without asking); None on `stop`. Spins for 2 ms, then naps 50 us a +/// check, so a request the GPU never sends costs no core (#141). +fn n_cores() -> usize { pin_cores(1).map_or(0, |_| (0..1024).take_while(|c| std::path::Path::new(&format!("/sys/devices/system/cpu/cpu{c}")).exists()).filter(|&c| first_sibling(c) == Some(c)).count()) } + +fn first_sibling(cpu: usize) -> Option { + std::fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")).ok()? + .trim().split([',', '-']).next()?.parse().ok() +} + +/// One logical CPU on each physical core (the first of its SMT siblings) but the first core: `n` of them, from sysfs. +fn pin_cores(n: usize) -> Option> { + if !cfg!(target_os = "linux") { return None; } + let cores: Vec = (0..1024).take_while(|c| std::path::Path::new(&format!("/sys/devices/system/cpu/cpu{c}")).exists()) + .filter(|&c| first_sibling(c) == Some(c)).collect(); + (cores.len() > n).then(|| cores[1..=n].to_vec()) +} + +fn set_affinity(cpus: &[usize]) { + #[cfg(target_os = "linux")] + unsafe { + unsafe extern "C" { fn sched_setaffinity(pid: i32, size: usize, mask: *const u64) -> i32; } + let mut set = [0u64; 16]; + for &c in cpus { if c < 1024 { set[c / 64] |= 1 << (c % 64); } } + sched_setaffinity(0, 128, set.as_ptr()); + } + #[cfg(not(target_os = "linux"))] + let _ = cpus; +} + +fn pin_to(cpu: usize) { set_affinity(&[cpu]); } + +/// The calling thread (it drives the GPU and spins in CUDA's waits) to the first physical core and its siblings. +fn pin_host() { + let sib = std::fs::read_to_string("/sys/devices/system/cpu/cpu0/topology/thread_siblings_list").unwrap_or_default(); + let cpus: Vec = sib.trim().split(',').filter_map(|x| x.split('-').next()?.parse().ok()).collect(); + if !cpus.is_empty() { set_affinity(&cpus); } +} + +fn wait_req(seq: u32, req: impl Fn() -> u32, skip: impl Fn() -> u32, stop: &AtomicBool) -> Option { + let ahead = |v: u32| v != 0 && (v.wrapping_sub(seq) as i32) >= 0; + let t0 = Instant::now(); + loop { + let r = req(); + if r == seq || ahead(r) || ahead(skip()) { return Some(r); } + if stop.load(Ordering::Relaxed) { return None; } + if t0.elapsed() < Duration::from_millis(2) { std::hint::spin_loop(); } else { std::thread::sleep(Duration::from_micros(50)); } + } +} + +/// `wait_req` on one thread of the current pool while the others spin until it returns (2 ms at most each), so the +/// expert passes that follow start on awake threads instead of waking a sleeping pool on the critical path. On the +/// Qwen3.8-Flash-Next Gyro file (RTX 3060, 6 threads) worker time went from ~10.4 to ~9.1 ms a token. A request +/// already there skips the broadcast: the threads are still awake from the last layer. +fn wait_req_hot(seq: u32, req: impl Fn() -> u32 + Sync, skip: impl Fn() -> u32 + Sync, stop: &AtomicBool) -> Option { + let ahead = |v: u32| v != 0 && (v.wrapping_sub(seq) as i32) >= 0; + let r = req(); + if r == seq || ahead(r) || ahead(skip()) || rayon::current_num_threads() < 2 { return wait_req(seq, req, skip, stop); } + let (done, out) = (AtomicBool::new(false), std::sync::Mutex::new(None)); + rayon::broadcast(|ctx| { + if ctx.index() == 0 { + *out.lock().unwrap() = wait_req(seq, &req, &skip, stop); + done.store(true, Ordering::Release); + } else { + let t0 = Instant::now(); + while !done.load(Ordering::Acquire) && t0.elapsed() < Duration::from_millis(2) { std::hint::spin_loop(); } + } + }); + out.into_inner().unwrap() +} + /// Copies `out.len()` (a multiple of 4) words from 16-byte aligned `p`. On write-combining memory (the Vulkan BAR /// mailbox) streaming loads fetch a whole 64-byte line per read instead of one uncached read per load. -unsafe fn read_wc(p: *const u32, out: &mut [u32]) { +pub(crate) unsafe fn read_wc(p: *const u32, out: &mut [u32]) { #[cfg(target_feature = "sse4.1")] for (i, c) in out.chunks_exact_mut(4).enumerate() { use std::arch::x86_64::*; @@ -214,3 +366,97 @@ impl Drop for CpuWorker { if let Some(t) = self.thread.take() { let _ = t.join(); } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU32, AtomicUsize}; + + /// A request that never comes (#141): after 2 ms of spinning the wait naps, so it checks the word a few + /// thousand times a second instead of millions. + #[test] + fn a_wait_for_a_request_that_never_comes_naps() { + let (stop, checks) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicUsize::new(0))); + let (st, ch) = (stop.clone(), checks.clone()); + let t = std::thread::spawn(move || wait_req(5, || { ch.fetch_add(1, Ordering::Relaxed); 4 }, || 0, &st)); + std::thread::sleep(Duration::from_millis(30)); + let a = checks.load(Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(100)); + let b = checks.load(Ordering::Relaxed); + stop.store(true, Ordering::Relaxed); + assert_eq!(t.join().unwrap(), None, "stop ends the wait"); + assert!(b - a < 10_000, "{} checks in 100 ms: still spinning", b - a); + } + + /// The hot wait sees a request that comes while the pool spins, one that comes after the spin, and a skip. + #[test] + fn a_hot_wait_sees_its_request() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + let stop = AtomicBool::new(false); + pool.install(|| { + assert_eq!(wait_req_hot(5, || 5, || 0, &stop), Some(5)); + assert_eq!(wait_req_hot(5, || 4, || 5, &stop), Some(4), "the layer was skipped"); + for ms in [1, 10] { + let req = AtomicU32::new(4); + std::thread::scope(|s| { + s.spawn(|| { std::thread::sleep(Duration::from_millis(ms)); req.store(5, Ordering::Relaxed); }); + assert_eq!(wait_req_hot(5, || req.load(Ordering::Relaxed), || 0, &stop), Some(5), "request after {ms} ms"); + }); + } + }); + } + + #[test] + fn a_wait_ends_on_its_seq_or_a_newer_one() { + let stop = AtomicBool::new(false); + assert_eq!(wait_req(5, || 5, || 0, &stop), Some(5)); + assert_eq!(wait_req(5, || 6, || 0, &stop), Some(6), "the GPU moved on"); + assert_eq!(wait_req(5, || 4, || 5, &stop), Some(4), "the layer was skipped"); + let req = AtomicU32::new(4); + std::thread::scope(|s| { + s.spawn(|| { std::thread::sleep(Duration::from_millis(10)); req.store(5, Ordering::Relaxed); }); + assert_eq!(wait_req(5, || req.load(Ordering::Relaxed), || 0, &stop), Some(5), "a request after the spin is still seen"); + }); + } + + /// Mailbox words for a request's (expert, weight, slot) picks. + fn words(picks: &[(u32, f32, i32)]) -> Vec { + let kt = picks.len(); + let mut v = vec![0u32; 3 * kt]; + for (j, &(e, w, s)) in picks.iter().enumerate() { (v[j], v[kt + j], v[2 * kt + j]) = (e, w.to_bits(), s as u32); } + v + } + + #[test] + fn tail_keep_drops_low_ranked_cpu_picks_only() { + // One token of 4 picks, out of weight order: ranks 2, 0, 3, 1; expert 11 is in VRAM. + let v = words(&[(10, 0.2, -1), (11, 0.4, 3), (12, 0.1, -1), (13, 0.3, -1)]); + assert_eq!(tail_keep(&v, 4, 4, 0), [true; 4]); + assert_eq!(tail_keep(&v, 4, 4, 2), [false, true, false, true]); + assert_eq!(tail_keep(&v, 4, 4, 1), [false, true, false, false]); + assert_eq!(tail_keep(&v, 4, 4, 4), [true; 4]); + } + + #[test] + fn tail_keep_runs_an_expert_any_token_of_a_window_ranks_high() { + // Expert 7 is rank 2 in token 0 and rank 0 in token 1; expert 8 is rank 2 in token 1 only. + let v = words(&[(5, 0.5, 0), (6, 0.3, -1), (7, 0.2, -1), (7, 0.6, -1), (9, 0.3, 2), (8, 0.1, -1)]); + assert_eq!(tail_keep(&v, 6, 3, 2), [true, true, true, true, true, false]); + } + + #[test] + fn tail_keep_breaks_weight_ties_by_position() { + let v = words(&[(1, 0.25, -1), (2, 0.25, -1), (3, 0.25, -1), (4, 0.25, -1)]); + assert_eq!(tail_keep(&v, 4, 4, 2), [true, true, false, false]); + } + + #[test] + fn a_token_whose_cpu_picks_were_all_dropped_is_still_answered() { + // Token 0: its one CPU pick is dropped; token 1: GPU picks only; token 2: its CPU pick runs. + let v = words(&[(1, 0.9, 0), (2, 0.1, -1), (3, 0.6, 1), (4, 0.4, 2), (5, 0.7, -1), (6, 0.3, 4)]); + let keep = tail_keep(&v, 6, 2, 1); + assert_eq!(cpu_picks(&v, 6, 2, 0, &keep), (vec![], true)); + assert_eq!(cpu_picks(&v, 6, 2, 1, &keep), (vec![], false)); + assert_eq!(cpu_picks(&v, 6, 2, 2, &keep), (vec![(5, 0.7)], true)); + } +} diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 9afa0cca..70a07c2c 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6,8 +6,15 @@ typedef unsigned short u16; typedef unsigned int u32; typedef unsigned long long u64; +#if STRATA_HIP +// AMD: the ISA converts f16 in one instruction, the compiler emits it for these. +__device__ __forceinline__ float h2f(u16 h) { return (float)*(const _Float16*)&h; } +__device__ __forceinline__ u16 f2h(float f) { _Float16 x = (_Float16)f; return *(const u16*)&x; } +#else __device__ __forceinline__ float h2f(u16 h) { float f; asm("cvt.f32.f16 %0, %1;" : "=f"(f) : "h"(h)); return f; } __device__ __forceinline__ u16 f2h(float f) { u16 h; asm("cvt.rn.f16.f32 %0, %1;" : "=h"(h) : "f"(f)); return h; } +#endif +__device__ __forceinline__ float2 ink_h2f2(unsigned w) { return make_float2(h2f((u16)(w & 0xFFFFu)), h2f((u16)(w >> 16))); } __device__ __forceinline__ u32 ld16(const u8* p) { return *(const u16*)p; } // 2-aligned only (every quant field is) __device__ __forceinline__ u32 ld32(const u8* p) { return p[0] | (p[1] << 8) | (p[2] << 16) | ((u32)p[3] << 24); } __device__ __forceinline__ float ldh(const u8* p) { return h2f((u16)ld16(p)); } @@ -242,9 +249,11 @@ template <> __device__ __forceinline__ void deq8<42>(const u8* b, int sub, float } // TQ1_0, 54 bytes: qs[48] five base-3 trits a byte (element 32 n + m from trit n of byte m for 0..160, element // 160 + 16 n + m from bytes 32..48), qh[4] four trits a byte (element 240 + 4 n + j from trit n of byte 48 + j), d. +// 3^n from a packed constant: a local array indexed by a runtime n went to local memory (gemv_ptq1_0 at 0.4 ms +// a 2048 x 6144 matrix on an RTX 3060). __device__ __forceinline__ int tq1_trit(u8 v, int n) { - const u8 pow3[5] = {1, 3, 9, 27, 81}; - return (int)(((u16)(u8)(v * pow3[n]) * 3) >> 8) - 1; + u8 p = (u8)(0x511B090301ull >> (8 * n)); + return (int)(((u16)(u8)(v * p) * 3) >> 8) - 1; } __device__ __forceinline__ void tq1_vals(const u8* b, int sub, int* q) { int e = sub * 8; @@ -263,6 +272,27 @@ template <> __device__ __forceinline__ void deq8<34>(const u8* b, int sub, float int q[8]; tq1_vals(b, sub, q); float d = ldh(b + 52); for (int i = 0; i < 8; i++) o[i] = d * (float)q[i]; } +// PTQ1_0 (Ternary Bonsai), a super-block of two 28-byte blocks of 128: qs[24] five trits a byte (element 16 n + m +// from trit n of byte m for 0..80, element 80 + 8 n + m from bytes 16..24), qh[2] four trits a byte (element +// 120 + 2 n + j from trit n of byte 24 + j), d. Trits as TQ1_0. Returns the block's d. +__device__ __forceinline__ float ptq1_vals(const u8* b, int sub, int* q) { + b += (sub >> 4) * 28; + int e = (sub & 15) * 8; + if (e < 80) { + int n = e >> 4, m = e & 15; + for (int i = 0; i < 8; i++) q[i] = tq1_trit(b[m + i], n); + } else if (e < 120) { + int n = (e - 80) >> 3; + for (int i = 0; i < 8; i++) q[i] = tq1_trit(b[16 + i], n); + } else { + for (int i = 0; i < 8; i++) q[i] = tq1_trit(b[24 + (i & 1)], i >> 1); + } + return ldh(b + 26); +} +template <> __device__ __forceinline__ void deq8<143>(const u8* b, int sub, float* o) { // PTQ1_0 + int q[8]; float d = ptq1_vals(b, sub, q); + for (int i = 0; i < 8; i++) o[i] = d * (float)q[i]; +} // TQ2_0, 66 bytes: qs[64] two-bit codes (element 128 j + 32 l + m from bits 2 l of byte 32 j + m), value (code - 1) d. __device__ __forceinline__ void tq2_vals(const u8* b, int sub, int* q) { int e = sub * 8, j = e >> 7, l = (e >> 5) & 3, m = e & 31; @@ -278,15 +308,21 @@ template <> __device__ __forceinline__ void deq8<35>(const u8* b, int sub, float // of the step's 15-bit state s names two points of the codebook tq_lut (two values each), x >> 21 and (x >> 10) & 2047. // TQ2_T: s is byte t under byte t - 1. TQK: s is the K * 32 bit ring of qs from bit (31 - t) K. // The codebook is not on an int8 grid, so these types run as float types (FTYPES). -template __device__ __forceinline__ void tq_points(const u8* qs, int t, u32& pa, u32& pb) { +// The states of steps t and t + 1 (t even): one read of the 4 bytes that hold both (s1 sits K bits below s0). +template __device__ __forceinline__ void tq_states2(const u8* qs, int t, u32& s0, u32& s1) { constexpr int K = T == 144 ? 8 : T == 145 ? 6 : 7, N = 4 * K; - u32 s; if (K == 8) { - s = (u32)qs[(t + 31) & 31] << 8 | qs[t]; + s0 = (u32)qs[(t + 31) & 31] << 8 | qs[t]; + s1 = (u32)qs[t] << 8 | qs[t + 1]; } else { - int off = (31 - t) * K, b = off >> 3, b1 = b + 1 < N ? b + 1 : b + 1 - N, b2 = b + 2 < N ? b + 2 : b + 2 - N; - s = ((u32)qs[b] | (u32)qs[b1] << 8 | (u32)qs[b2] << 16) >> (off & 7); + int lo = (30 - t) * K, b = lo >> 3; + u32 w = 0; +#pragma unroll + for (int i = 0; i < 4; i++) w |= (u32)qs[b + i < N ? b + i : b + i - N] << (8 * i); + s1 = w >> (lo & 7); s0 = w >> ((lo & 7) + K); } +} +__device__ __forceinline__ void tq_hash(u32 s, u32& pa, u32& pb) { u32 x = (s & 0x7fff) * 0x9e3779b1u; pa = x >> 21; pb = (x >> 10) & 2047; } @@ -295,17 +331,37 @@ template __device__ __forceinline__ const u8* tq_blk(const u8* b, int su t = (sub & 15) * 2; return b + (sub >> 4) * (2 + 4 * (T == 144 ? 8 : T == 145 ? 6 : 7)); } -template __device__ __forceinline__ void tq_deq8(const u8* b, int sub, float* o) { +// The GEMV and GEMM kernels read the codebook from shared memory (SH): its gathers are random, which shared memory +// serves in fewer passes than L1. A kernel that passes SH loads it first (tq_lut_load, then __syncthreads). +// Same values either way, so the results are the same bits. +// The codebook is f16 (ggml-common-tq.h), so the shared copy holds it as f16 pairs, exactly: half the bytes of +// float2, and a 32-bit gather meets fewer bank conflicts than a 64-bit one. +__shared__ u32 s_tq_lut[2048]; +__device__ __forceinline__ void tq_lut_load() { + for (int i = threadIdx.x; i < 2048; i += blockDim.x) s_tq_lut[i] = f2h(tq_lut[2 * i]) | (u32)f2h(tq_lut[2 * i + 1]) << 16; +} +template __device__ constexpr bool is_tq() { return T >= 144 && T <= 146; } +template __device__ __forceinline__ void tq_deq8(const u8* b, int sub, float* o) { int t; const u8* p = tq_blk(b, sub, t); float d = ldh(p); + u32 st[2]; tq_states2(p + 2, t, st[0], st[1]); for (int i = 0; i < 2; i++) { - u32 pa, pb; tq_points(p + 2, t + i, pa, pb); - o[4 * i] = tq_lut[2 * pa] * d; o[4 * i + 1] = tq_lut[2 * pa + 1] * d; - o[4 * i + 2] = tq_lut[2 * pb] * d; o[4 * i + 3] = tq_lut[2 * pb + 1] * d; + u32 pa, pb; tq_hash(st[i], pa, pb); + if constexpr (SH) { + float2 a = ink_h2f2(s_tq_lut[pa]), c = ink_h2f2(s_tq_lut[pb]); + o[4 * i] = a.x * d; o[4 * i + 1] = a.y * d; o[4 * i + 2] = c.x * d; o[4 * i + 3] = c.y * d; + } else { + o[4 * i] = tq_lut[2 * pa] * d; o[4 * i + 1] = tq_lut[2 * pa + 1] * d; + o[4 * i + 2] = tq_lut[2 * pb] * d; o[4 * i + 3] = tq_lut[2 * pb + 1] * d; + } } } template <> __device__ __forceinline__ void deq8<144>(const u8* b, int sub, float* o) { tq_deq8<144>(b, sub, o); } // TQ2_T template <> __device__ __forceinline__ void deq8<145>(const u8* b, int sub, float* o) { tq_deq8<145>(b, sub, o); } // TQK6 template <> __device__ __forceinline__ void deq8<146>(const u8* b, int sub, float* o) { tq_deq8<146>(b, sub, o); } // TQK7 +// deq8, from the shared codebook for the trellis types (their kernel loaded it). +template __device__ __forceinline__ void deq8s(const u8* b, int sub, float* o) { + if constexpr (is_tq()) tq_deq8(b, sub, o); else deq8(b, sub, o); +} // Rows of `cols` values (a multiple of 32, or of the type's block): GEMVs loop over the full super-blocks, then the // lanes whose 8 values lie inside a partial last one (cols % 256) read it. Only the `_p` kernels (P = true) have that @@ -315,29 +371,57 @@ template <> __device__ __forceinline__ void deq8<146>(const u8* b, int sub, floa // One warp per output row; lane `l` covers elements [8l, 8l+8) of every super-block. NT inputs (x + t * xst) share // each weight load; output t goes to y + t * yst. -template +// R > 1 (trellis types): rows row .. row + R - 1 (the first nr of them exist, rb bytes apart) share each x load; each +// row sums the same products in the same order as with R = 1. SH: deq8s (the kernel loaded the shared codebook). +template __device__ __forceinline__ void gemv_row(const u8* __restrict__ w, const float* __restrict__ x, float* y, int row, int cols, - int xst = 0, int yst = 0, float sc = 1.0f) { + int xst = 0, int yst = 0, float sc = 1.0f, int nr = 1, size_t rb = 0, bool act = false) { int lane = threadIdx.x & 31; - float acc[NT] = {}, v[8]; + float acc[R][NT] = {}, v[8]; auto sb = [&](int s) { - deq8(w + (size_t)s * SBB, lane, v); + float4 a[NT], c[NT]; #pragma unroll for (int t = 0; t < NT; t++) { const float4* xs = (const float4*)(x + (size_t)t * xst + s * 256 + lane * 8); - float4 a = xs[0], c = xs[1]; - acc[t] += v[0] * a.x + v[1] * a.y + v[2] * a.z + v[3] * a.w + v[4] * c.x + v[5] * c.y + v[6] * c.z + v[7] * c.w; + a[t] = xs[0]; c[t] = xs[1]; + } +#pragma unroll + for (int r = 0; r < R; r++) { + const u8* wr = w + (size_t)(r < nr ? r : nr - 1) * rb + (size_t)s * SBB; + if constexpr (SH) deq8s(wr, lane, v); else deq8(wr, lane, v); +#pragma unroll + for (int t = 0; t < NT; t++) + acc[r][t] += v[0] * a[t].x + v[1] * a[t].y + v[2] * a[t].z + v[3] * a[t].w + v[4] * c[t].x + v[5] * c[t].y + v[6] * c[t].z + v[7] * c[t].w; } }; #pragma unroll 4 for (int s = 0; s < cols >> 8; s++) sb(s); if (P && (cols & 255) > lane * 8) sb(cols >> 8); +#pragma unroll + for (int r = 0; r < R; r++) #pragma unroll for (int t = 0; t < NT; t++) { - float a = warp_sum(acc[t]); - if (lane == 0) y[(size_t)t * yst + row] = a * sc; + float a = warp_sum(acc[r][t]); + // act: hc_silu fused (silu(y * sc), sc = 1 / hc, for a matrix of scale 1: the bits of the two kernels). + if (lane == 0 && r < nr) y[(size_t)t * yst + row + r] = act ? silu(a * sc) : a * sc; } } +// Trellis GEMV rows: warp w of the block takes rpw (1, 2 or 4) consecutive rows from row0 + w * rpw, with the shared +// codebook (tq_rows_lut loads it). rpw 0: one row, codebook read from global memory (a short row, too little work to +// pay for the load). +__device__ __forceinline__ void tq_rows_lut(int rpw) { if (rpw) { tq_lut_load(); __syncthreads(); } } +template +__device__ __forceinline__ void tq_rows(const u8* w, const float* x, float* y, int row0, int rows, int cols, int rpw, + int xst = 0, int yst = 0, float sc = 1.0f, bool silu_out = false) { + int row = row0 + (threadIdx.x >> 5) * max(rpw, 1), nr = min(max(rpw, 1), rows - row); + if (nr <= 0) return; + size_t rb = ROWB(cols, SBB); + const u8* wr = w + row * rb; + if (rpw == 0) gemv_row(wr, x, y, row, cols, xst, yst, sc, 1, 0, silu_out); + else if (rpw == 4) gemv_row(wr, x, y, row, cols, xst, yst, sc, nr, rb, silu_out); + else if (rpw == 2) gemv_row(wr, x, y, row, cols, xst, yst, sc, nr, rb, silu_out); + else gemv_row(wr, x, y, row, cols, xst, yst, sc, nr, rb, silu_out); +} // ---- integer path: 8 weights of a super-block as int8 (two packed words), with dequant value = d * q - m ---- // Activations are quantized per 32 elements to int8 in shared memory, and dot products use dp4a. @@ -481,6 +565,21 @@ template <> struct QI<14> { // Q6_K (210 bytes: rows 2-aligned) lo = (int)__vsub4(a, 0x20202020u); hi = (int)__vsub4(c, 0x20202020u); } }; +// Q6_K, half n of a super-block for lane t (gemmd): the ql bytes of blocks 0, 2 and of 1, 3, the qh bytes, the 8 +// scales of the half and d. Block qt decodes as QI<14>::get(b, 4 (4 n + qt) + t). +struct H6 { uint2 l0, l1, h, s; u32 d; }; +__device__ __forceinline__ void h6_ld(const u8* b, int n, int t, H6& r) { + r.l0 = ld8a2(b + 64 * n + 8 * t); r.l1 = ld8a2(b + 64 * n + 32 + 8 * t); r.h = ld8a2(b + 128 + 32 * n + 8 * t); + r.s = ld8a2(b + 192 + 8 * n); r.d = ld16(b + 208); +} +__device__ __forceinline__ void h6_get(const H6& r, int qt, int t, int& lo, int& hi, float& d) { + const uint2 L = qt & 1 ? r.l1 : r.l0; + const int ns = 4 * (qt >> 1), hs = 2 * qt, j = (t >> 1) + 2 * qt; + d = h2f((u16)r.d) * (float)(signed char)(((j & 4 ? r.s.y : r.s.x) >> (8 * (j & 3))) & 0xFF); + u32 a = ((L.x >> ns) & 0x0F0F0F0Fu) | (((r.h.x >> hs) & 0x03030303u) << 4); + u32 c = ((L.y >> ns) & 0x0F0F0F0Fu) | (((r.h.y >> hs) & 0x03030303u) << 4); + lo = (int)__vsub4(a, 0x20202020u); hi = (int)__vsub4(c, 0x20202020u); +} // IQ1: weight = dl * (g +- 1/8) = (dl / 8) * (8 g +- 1), an exact int8 in {-9, -7, -1, 1, 7, 9}. template struct QI1 { static constexpr bool MIN = false; @@ -577,6 +676,29 @@ template <> struct QI<34> { // TQ1_0 (54 bytes: rows 2-aligned) lo = pack4(q[0], q[1], q[2], q[3]); hi = pack4(q[4], q[5], q[6], q[7]); } }; +// Trit n of each byte of w (p = 3^n) as a byte 0..2: two bytes at a time in 16-bit lanes, (v p mod 256) 3 >> 8. +__device__ __forceinline__ u32 trit4(u32 w, u32 p) { + u32 a = ((w & 0x00ff00ffu) * p) & 0x00ff00ffu, c = (((w >> 8) & 0x00ff00ffu) * p) & 0x00ff00ffu; + return (((a * 3) >> 8) & 0x00030003u) | ((((c * 3) >> 8) & 0x00030003u) << 8); +} +template <> struct QI<143> { // PTQ1_0 (56 bytes: rows 4-aligned, so are the 8 bytes of a sub below 120) + static constexpr bool MIN = false; + __device__ static void get(const u8* b, int sub, int& lo, int& hi, float& d, float& m) { + m = 0.0f; + int e = (sub & 15) * 8; + if (e < 120) { + const u8* r = b + (sub >> 4) * 28; + int n = e < 80 ? e >> 4 : (e - 80) >> 3; + u32 p = (u8)(0x511B090301ull >> (8 * n)); + const u8* w = r + (e < 80 ? (e & 15) : 16); + lo = (int)__vsub4(trit4(ldu32(w), p), 0x01010101u); hi = (int)__vsub4(trit4(ldu32(w + 4), p), 0x01010101u); + d = ldh(r + 26); + } else { + int q[8]; d = ptq1_vals(b, sub, q); + lo = pack4(q[0], q[1], q[2], q[3]); hi = pack4(q[4], q[5], q[6], q[7]); + } + } +}; template <> struct QI<35> { // TQ2_0 (66 bytes: rows 2-aligned) static constexpr bool MIN = false; __device__ static void get(const u8* b, int sub, int& lo, int& hi, float& d, float& m) { @@ -861,7 +983,7 @@ __device__ __forceinline__ void gemv_row_qn(const u8* __restrict__ w, const sign #define FTYPES(X) X(0, f32, 1024) X(30, bf16, 512) X(43, f8_e4m3, 256) X(144, tq2_t, 68) X(145, tqk6, 52) X(146, tqk7, 60) #define ITYPES(X) X(8, q8_0, 272) X(10, q2_k, 84) X(11, q3_k, 110) X(12, q4_k, 144) X(13, q5_k, 176) X(14, q6_k, 210) \ - X(19, iq1_s, 50) X(29, iq1_m, 56) X(16, iq2_xxs, 66) X(17, iq2_xs, 74) X(22, iq2_s, 82) X(18, iq3_xxs, 98) X(21, iq3_s, 110) X(23, iq4_xs, 136) X(20, iq4_nl, 144) X(42, q2_0, 72) X(34, tq1_0, 54) X(35, tq2_0, 66) X(2, q4_0, 144) X(6, q5_0, 176) \ + X(19, iq1_s, 50) X(29, iq1_m, 56) X(16, iq2_xxs, 66) X(17, iq2_xs, 74) X(22, iq2_s, 82) X(18, iq3_xxs, 98) X(21, iq3_s, 110) X(23, iq4_xs, 136) X(20, iq4_nl, 144) X(42, q2_0, 72) X(34, tq1_0, 54) X(143, ptq1_0, 56) X(35, tq2_0, 66) X(2, q4_0, 144) X(6, q5_0, 176) \ X(3, q4_1, 160) X(7, q5_1, 192) X(40, nvfp4, 144) #define QTYPES(X) FTYPES(X) ITYPES(X) @@ -879,30 +1001,49 @@ QTYPES(DEF_DEQUANT) // Float types and the trellis types (their codebook is float) read x directly. #define DEF_FGEMV(T, NAME, SBB) DEF_FGEMV_(T, NAME, SBB, false) DEF_FGEMV_(T, NAME##_p, SBB, true) +// The trellis types (is_tq) load the shared codebook, then each warp takes rpw rows (tq_rows; Gpu::gemv_cfg). #define DEF_FGEMV_(T, NAME, SBB, P) \ - extern "C" __global__ void gemv_##NAME(const u8* w, const float* x, float* y, int rows, int cols, int, \ - const signed char*, long long w2, long long y2, int rows2, \ + extern "C" __global__ void gemv_##NAME(const u8* w, const float* x, float* y, int rows, int cols, int rpw, \ + const signed char* act, long long w2, long long y2, int rows2, \ float sc1, float sc2) { \ int row = (blockIdx.x * blockDim.x + threadIdx.x) >> 5; \ float sc = blockIdx.z ? sc2 : sc1; \ + bool silu_out = act == (const signed char*)1 && blockIdx.z == 0; \ w += blockIdx.z * w2; y = (float*)((char*)y + blockIdx.z * y2); if (blockIdx.z) rows = rows2; \ - if (row < rows) gemv_row(w + row * ROWB(cols, SBB), x, y, row, cols, 0, 0, sc); \ + if constexpr (is_tq()) { \ + tq_rows_lut(rpw); \ + tq_rows(w, x, y, blockIdx.x * blockDim.x / 32 * max(rpw, 1), rows, cols, rpw, 0, 0, sc, silu_out); \ + } else if (row < rows) gemv_row(w + row * ROWB(cols, SBB), x, y, row, cols, 0, 0, sc, 1, 0, silu_out); \ } \ extern "C" __global__ void moe_gemv_##NAME(const u8* w, const int* ids, long long stride, const float* x, \ - int x_stride, int xg, float* y, int rows, int cols, int, \ + int x_stride, int xg, float* y, int rows, int cols, int rpw, \ long long w2, long long y2) { \ int row = (blockIdx.x * blockDim.x + threadIdx.x) >> 5, k = blockIdx.y; \ w += blockIdx.z * w2; y = (float*)((char*)y + blockIdx.z * y2); \ - if (row < rows && ids[k] >= 0) \ + if (ids[k] < 0) return; \ + if constexpr (is_tq()) { \ + tq_rows_lut(rpw); \ + tq_rows(w + ids[k] * stride, x + (size_t)(k / xg) * x_stride, y + (size_t)k * rows, \ + blockIdx.x * blockDim.x / 32 * max(rpw, 1), rows, cols, rpw); \ + } else if (row < rows) \ gemv_row(w + ids[k] * stride + row * ROWB(cols, SBB), x + (size_t)(k / xg) * x_stride, \ y + (size_t)k * rows, row, cols); \ } \ extern "C" __global__ void gemvn_##NAME(const u8* w, const float* x, int xs, float* y, int ys, int rows, int cols, \ - int, int nt, const signed char*, long long w2, long long y2, int rows2, \ + int rpw, int nt, const signed char*, long long w2, long long y2, int rows2, \ float sc1, float sc2) { \ int row = (blockIdx.x * blockDim.x + threadIdx.x) >> 5; \ float sc = blockIdx.z ? sc2 : sc1; \ w += blockIdx.z * w2; y = (float*)((char*)y + blockIdx.z * y2); if (blockIdx.z) rows = ys = rows2; \ + if constexpr (is_tq()) { \ + tq_rows_lut(rpw); \ + int r0 = blockIdx.x * blockDim.x / 32 * max(rpw, 1); \ + if (nt == 2) tq_rows(w, x, y, r0, rows, cols, rpw, xs, ys, sc); \ + else if (nt == 3) tq_rows(w, x, y, r0, rows, cols, rpw, xs, ys, sc); \ + else if (nt == 4) tq_rows(w, x, y, r0, rows, cols, rpw, xs, ys, sc); \ + else tq_rows(w, x, y, r0, rows, cols, rpw, xs, ys, sc); \ + return; \ + } \ if (row >= rows) return; \ const u8* wr = w + row * ROWB(cols, SBB); \ if (nt == 2) gemv_row(wr, x, y, row, cols, xs, ys, sc); \ @@ -1022,8 +1163,12 @@ __device__ __forceinline__ void ldsm4(u32* r, const u16* p) { #pragma unroll for (int m = 0; m < 4; m++) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; +#if STRATA_HIP + r[m] = *(const u32*)(p + (m_row + row) * PQ + m_col + col); +#else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); asm("ld.shared.b32 %0, [%1];" : "=r"(r[m]) : "r"(a)); +#endif } #else unsigned a = (unsigned)__cvta_generic_to_shared(p); @@ -1040,11 +1185,16 @@ __device__ __forceinline__ void ldsm4t(u32* r, const u16* p) { #pragma unroll for (int m = 0; m < 4; m++) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; +#if STRATA_HIP + const u16* a = p + (m_row + row) * PQ + m_col + col; + r[m] = (u32)a[0] | ((u32)a[PQ] << 16); +#else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); unsigned short lo, hi; asm("ld.shared.u16 %0, [%1];" : "=h"(lo) : "r"(a)); asm("ld.shared.u16 %0, [%1];" : "=h"(hi) : "r"(a + 2 * PQ)); r[m] = (u32)lo | ((u32)hi << 16); +#endif } #else unsigned a = (unsigned)__cvta_generic_to_shared(p); @@ -1054,7 +1204,7 @@ __device__ __forceinline__ void ldsm4t(u32* r, const u16* p) { } __device__ __forceinline__ void mma16816(float* c, u32 a0, u32 a1, u32 a2, u32 a3, u32 b0, u32 b1) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800 -#if __CUDA_ARCH__ >= 750 +#if __CUDA_ARCH__ >= 750 && !MMA_FMA // Turing (sm_75) has no m16n8k16 f16 mma: the same product is two m16n8k8 steps, k = 0..7 and k = 8..15 // (the a0/a1, a2/a3 and b0, b1 fragments are those half-K fragments of the k16 layout). asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};" @@ -1062,6 +1212,8 @@ __device__ __forceinline__ void mma16816(float* c, u32 a0, u32 a1, u32 a2, u32 a asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};" : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a2), "r"(a3), "r"(b1)); #else + // Also taken on sm_75 with MMA_FMA: the GTX 16 series (TU116/TU117) has no tensor cores and runs m16n8k8 far + // slower than this CUDA-core version (see `turing_fma` in mod.rs). // D[16,8] += A[16,16] * B[16,8] on CUDA cores. mma.sync.aligned.m16n8k16 is sm_80+ (unlike ldmatrix, which is // sm_75+, hence the different guard). Lane l = 4*g + t (g = l >> 2, t = l & 3) owns A rows g / g+8 at the // k-halves {2t, 2t+1, 2t+8, 2t+9}, and B column g at those same k. The four accumulators are sums over all 16 @@ -1101,7 +1253,7 @@ __device__ __forceinline__ void mma16816(float* c, u32 a0, u32 a1, u32 a2, u32 a : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); #endif } -#if __CUDA_ARCH__ < 800 +#if __CUDA_ARCH__ < 800 && !STRATA_HIP // D[8,8] += A[8,4] * B[4,8] with the four independent computations of mma.m8n8k4 (Volta, SASS HMMA.884) selected // by g & 3. PTX ISA 8.5 §9.7.13.4.1: lane l = 4*g + t owns A row t + 4*(g >= 4) at k 0..3 and D elements by the // column/row formulas implemented in gemm_q's sm_70 path. mma.m16n8k16 is sm_80+, so this helper only exists for @@ -1114,6 +1266,13 @@ __device__ __forceinline__ void mma884(float* d, u32 a0, u32 a1, u32 b0, u32 b1) } #endif __device__ __forceinline__ u32 h2pack(float a, float b) { return (u32)f2h(a) | ((u32)f2h(b) << 16); } +#if !STRATA_HIP +__device__ __forceinline__ u32 fma_f16x2(u32 a, u32 b, u32 c) { + u32 r; + asm("fma.rn.f16x2 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(c)); + return r; +} +#endif // act: 0 = store, 1 = y = silu(y) * result (SwiGLU over a gate already in y), 2 = y += result. // tiles = null: one dense matrix wd over positions 0 .. nd, tile blockIdx.y = positions BM * blockIdx.y ... @@ -1121,10 +1280,14 @@ __device__ __forceinline__ u32 h2pack(float a, float b) { return (u32)f2h(a) | ( // SM (gemms_*, tile lists only): the tiles of at most 32 positions (most expert tiles), which the SM = false kernel // skips; their 32 x 64 outputs go 16 x 16 per warp (positions wm, rows wn, in acc[0][0..1]). Each output sums the // same products in the same order either way. (A runtime branch in one kernel costs the big tiles a third.) -template +// SMX (SM, mma16816 path only): 32-position halves a block, each warp taking 16 x 16 outputs in each half. +// XH: x holds halves (x_to_f16), x_stride counted in halves. +template __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int nd, const float* __restrict__ x, int x_stride, - const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { - constexpr int P = BK + 8, NT = BM * 2, SUBS = BK / 8, XM = SM ? 32 : BM; // smem pitch in halves (padding: conflict-free fragments) + const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc, + float* yo = nullptr, int yo_stride = 0, int yact = 0, int* cnt = nullptr) { + constexpr bool PF = SM; // X prefetch (below) + constexpr int P = BK + 8, NT = BM * 2, SUBS = BK / 8, XM = SM ? 32 * SMX : BM; // smem pitch in halves (padding: conflict-free fragments) __shared__ __align__(16) u16 xs[XM * P], ws[64 * P]; GemmTile tl = tiles ? tiles[blockIdx.y] : GemmTile{wd, (int)blockIdx.y * XM, min(XM, nd - (int)blockIdx.y * XM)}; if (tiles && (tl.cnt <= 32) != SM) return; @@ -1134,12 +1297,17 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int #pragma unroll for (int q = 0; q < XM * BK / 4 / NT; q++) { int r = (tid + q * NT) / (BK / 4); - xr[q] = r < tl.cnt ? x + (size_t)(xrow ? xrow[tl.m0 + r] : tl.m0 + r) * x_stride : nullptr; + size_t off = (size_t)(xrow ? xrow[tl.m0 + r] : tl.m0 + r) * x_stride; + xr[q] = r >= tl.cnt ? nullptr : XH ? (const float*)((const u16*)x + off) : x + off; } float acc[2][4][4] = {}; #if __CUDA_ARCH__ < 800 && GEMM_TC // Same 32 f32 storage as acc, seen as 4 m8 tiles x 8 D registers: accv[j][i] == &acc[0][0][0][j*8+i]. float (&accv)[4][8] = reinterpret_cast(acc); +#endif +#if GEMM_WMMA + // The same 32 f32 as 4 WMMA tiles of 8 results: accw[t][i] is tile t, result i of this lane. + float (&accw)[4][8] = reinterpret_cast(acc); #endif // W step kb is decoded into registers (as halves) during step kb - 1's mma and stored after it. constexpr int WQ = 64 * SUBS / NT; @@ -1157,7 +1325,7 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int int lo, hi; float d, m; QS::get(blk, part * SUBS + j, lo, hi, d, m); for (int e = 0; e < 4; e++) v[e] = d * (float)(signed char)(lo >> 8 * e), v[4 + e] = d * (float)(signed char)(hi >> 8 * e); - } else deq8(blk, part * SUBS + j, v); + } else deq8s(blk, part * SUBS + j, v); wv[q] = make_uint4(h2pack(v[0], v[1]), h2pack(v[2], v[3]), h2pack(v[4], v[5]), h2pack(v[6], v[7])); } }; @@ -1165,24 +1333,64 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int #pragma unroll for (int q = 0; q < WQ; q++) { int i = tid + q * NT; *(uint4*)(ws + (i / SUBS) * P + (i % SUBS) * 8) = wv[q]; } }; - const int nk = n64 * 64 / BK; + // Split K (gemm_raw, a batched decode step of few blocks): grid.z segments of the K steps, segment z writing + // its partial sums at y + z * nd * y_stride for gemm_splitk_sum to add up in a fixed order. + const int nk = n64 * 64 / BK, kb0 = nk * blockIdx.z / gridDim.z, kb1 = nk * (blockIdx.z + 1) / gridDim.z; + y += (size_t)blockIdx.z * nd * y_stride; if constexpr (T == 17 || T == 18 || T == 21 || T == 22) { QS::load(); __syncthreads(); } - ldw(0); + if constexpr (is_tq()) { tq_lut_load(); __syncthreads(); } + // SM: X step kb + 1 is loaded into registers with W's, during step kb's mma (2 float4 a thread; the big tile's + // 8 cost more registers than they save: 48 rows of a batched BF16 step took 57.7 ms against 50.4). + float4 xv[XM * BK / 4 / NT]; + uint2 xh[XM * BK / 4 / NT]; + auto ldx = [&](int kb) { + #pragma unroll + for (int q = 0; q < XM * BK / 4 / NT; q++) { + int c = kb * BK + (tid + q * NT) % (BK / 4) * 4; + if constexpr (XH) xh[q] = xr[q] ? *(const uint2*)((const u16*)xr[q] + c) : make_uint2(0, 0); + else xv[q] = xr[q] ? *(const float4*)(xr[q] + c) : make_float4(0.f, 0.f, 0.f, 0.f); + } + }; + ldw(kb0); + if constexpr (PF) ldx(kb0); stw(); - for (int kb = 0; kb < nk; kb++) { + for (int kb = kb0; kb < kb1; kb++) { + if constexpr (!PF) ldx(kb); #pragma unroll for (int q = 0; q < XM * BK / 4 / NT; q++) { int i = tid + q * NT, r = i / (BK / 4), c = (i % (BK / 4)) * 4; - float4 v = xr[q] ? *(const float4*)(xr[q] + kb * BK + c) : make_float4(0.f, 0.f, 0.f, 0.f); - *(uint2*)(xs + r * P + c) = make_uint2(h2pack(v.x, v.y), h2pack(v.z, v.w)); + *(uint2*)(xs + r * P + c) = XH ? xh[q] : make_uint2(h2pack(xv[q].x, xv[q].y), h2pack(xv[q].z, xv[q].w)); } __syncthreads(); - if (kb + 1 < nk) ldw(kb + 1); + if (kb + 1 < kb1) { ldw(kb + 1); if constexpr (PF) ldx(kb + 1); } // Expert tiles are often part full; a warp whose 32 positions are all past cnt has nothing to multiply. if (wm < tl.cnt) #pragma unroll for (int kk = 0; kk < BK; kk += 16) { -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // AMD matrix cores: the tile in xs (positions, rows = m) and ws (rows = n) is fed straight in as A and B + // of D[16x16] += A * B^T. A warp owns MT x NT 16x16 tiles: (32 positions, 32 rows) for the big kernel and + // one (16 positions, 16 rows) for the small-tile one, whose 8 warps cover 32 positions x 64 rows. Each lane holds 8 results of every tile. + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); + constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; + strata_hip::strata_hk wa[MT], wb[NTW]; +#pragma unroll + for (int mt = 0; mt < MT; mt++) wa[mt] = strata_hip::strata_ld_wmma(xs + (wm + mt * 16 + l16) * P + kk + w0); +#pragma unroll + for (int nt = 0; nt < NTW; nt++) wb[nt] = strata_hip::strata_ld_wmma(ws + (wn + nt * 16 + l16) * P + kk + w0); +#pragma unroll + for (int mt = 0; mt < MT; mt++) +#pragma unroll + for (int nt = 0; nt < NTW; nt++) { + float* t = accw[mt * NTW + nt]; + strata_hip::strata_f8 c, r; +#pragma unroll + for (int i = 0; i < 8; i++) c[i] = t[i]; + r = strata_hip::strata_wmma(wa[mt], wb[nt], c); +#pragma unroll + for (int i = 0; i < 8; i++) t[i] = r[i]; + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // Volta: eight m8n8k4 ops replace one m16n8k16 for the same 16-deep k step. The four computations of // each instruction are selected by c = g & 3: SM == false maps them to the four n8 tiles (m8 = j, n8 = // c, 32 f32 per lane in accv[0..3]); SM == true maps them to the four 8x8 quadrants of the 16x16 warp @@ -1201,11 +1409,11 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int } } #else - constexpr int MT = SM ? 1 : 2, NT8 = SM ? 2 : 4; + constexpr int MT = SM ? SMX : 2, NT8 = SM ? 2 : 4, MS = SM ? 32 : 16; u32 a[2][4], b[4][2]; #pragma unroll for (int mt = 0; mt < MT; mt++) { - const u16* p = xs + (wm + mt * 16 + g) * P + kk + 2 * t; + const u16* p = xs + (wm + mt * MS + g) * P + kk + 2 * t; a[mt][0] = ld_s32(p); a[mt][1] = ld_s32(p + 8 * P); a[mt][2] = ld_s32(p + 8); a[mt][3] = ld_s32(p + 8 * P + 8); } #pragma unroll @@ -1220,9 +1428,30 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int #endif } __syncthreads(); - if (kb + 1 < nk) stw(); + if (kb + 1 < kb1) stw(); } -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // D layout of the AMD WMMA: the lane keeps column lane & 15 and rows STRATA_WMMA_ROW(lane, 0..7) of each tile. + { + const int l16 = lane & 15; + constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; +#pragma unroll + for (int mt = 0; mt < MT; mt++) +#pragma unroll + for (int nt = 0; nt < NTW; nt++) { + int n = n0 + wn + nt * 16 + l16; + if (n >= rows) continue; +#pragma unroll + for (int i = 0; i < 8; i++) { + int r = wm + mt * 16 + STRATA_WMMA_ROW(lane, i); + if (r >= tl.cnt) continue; + float* yr = y + (size_t)(tl.m0 + r) * y_stride; + float v = accw[mt * NTW + nt][i]; + yr[n] = act == 0 ? v : act == 1 ? silu(yr[n]) * v : yr[n] + v; + } + } + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // m8n8k4 D layout (PTX ISA 8.5 §9.7.13.4.1): register i = 4*p4 + 2*p2 + e sits at row (t & 1) + 2*p2 + 4*hi // and column (t & 2) + 4*p4 + e of the 8x8 tile. For each fixed c, lanes {4c..4c+3} and {16+4c..19+4c} cover // that tile exactly once; the tile itself is picked by c (n8 = c) and j (m8 = j), or by c alone for SM. @@ -1246,12 +1475,12 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int } #else #pragma unroll - for (int mt = 0; mt < (SM ? 1 : 2); mt++) + for (int mt = 0; mt < (SM ? SMX : 2); mt++) #pragma unroll for (int nt = 0; nt < (SM ? 2 : 4); nt++) #pragma unroll for (int h = 0; h < 2; h++) { - int r = wm + mt * 16 + g + 8 * h, n = n0 + wn + nt * 8 + 2 * t; + int r = wm + mt * (SM ? 32 : 16) + g + 8 * h, n = n0 + wn + nt * 8 + 2 * t; if (r >= tl.cnt) continue; float* yr = y + (size_t)(tl.m0 + r) * y_stride; #pragma unroll @@ -1262,6 +1491,39 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int } } #endif + // Split K with cnt: the last segment of a tile to finish adds the partial sums of all segments into yo, in + // gemm_splitk_sum's order (the same bits), and clears the tile's counter for the next launch. + if (cnt && gridDim.z > 1) { + __shared__ int last; + __threadfence(); + __syncthreads(); + int* c = cnt + blockIdx.y * gridDim.x + blockIdx.x; + if (tid == 0) last = atomicAdd(c, 1) == (int)gridDim.z - 1; + __syncthreads(); + if (!last) return; + __threadfence(); + const float* part = y - (size_t)blockIdx.z * nd * y_stride; + // 4 consecutive results a thread, all segments' loads in flight before the adds (gemm_raw splits at most 8). + const int ks = gridDim.z; + for (int i = tid * 4; i < tl.cnt * 64; i += NT * 4) { + int r = tl.m0 + i / 64, n = n0 + i % 64; + if (n >= rows) continue; + float4 p[8]; + #pragma unroll + for (int z = 0; z < 8; z++) + if (z < ks) p[z] = __ldcg((const float4*)(part + (size_t)z * nd * y_stride + (size_t)r * y_stride + n)); + float4 v = make_float4(0.f, 0.f, 0.f, 0.f); + #pragma unroll + for (int z = 0; z < 8; z++) + if (z < ks) { v.x += p[z].x; v.y += p[z].y; v.z += p[z].z; v.w += p[z].w; } + float* yr = yo + (size_t)r * yo_stride + n; + float vv[4] = {v.x, v.y, v.z, v.w}; + #pragma unroll + for (int e = 0; e < 4; e++) + if (n + e < rows) yr[e] = yact == 0 ? vv[e] : yact == 1 ? silu(yr[e]) * vv[e] : yr[e] + vv[e]; + } + if (tid == 0) *c = 0; + } } #ifndef GEMM_BM @@ -1281,6 +1543,13 @@ static_assert((64 * (GEMM_BK / 8)) % (2 * GEMM_BM) == 0, "whole W groups per thr #else #define GEMM_LAUNCH_BOUNDS __launch_bounds__(GEMM_BM * 2) #endif +// gemmm_* (batched decode of 33 to 64 positions, tiles == 0): 64 positions a block, x as halves (x_to_f16). With mma16816, the SM layout +// over two 32-position halves; elsewhere gemm_*'s big tile. +#if GEMM_WMMA || (__CUDA_ARCH__ < 800 && GEMM_TC) +#define GEMMM_BODY(T, SBB) gemm_q(tiles, wd, nd, x, x_stride, xrow, y, y_stride, rows, n64, act, sc, yo, yo_stride, yact, cnt) +#else +#define GEMMM_BODY(T, SBB) gemm_q(tiles, wd, nd, x, x_stride, xrow, y, y_stride, rows, n64, act, sc, yo, yo_stride, yact, cnt) +#endif #define DEF_GEMM(T, NAME, SBB) \ extern "C" __global__ void GEMM_LAUNCH_BOUNDS gemm_##NAME(const GemmTile* tiles, const u8* wd, int nd, \ const float* x, int x_stride, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { \ @@ -1289,9 +1558,33 @@ static_assert((64 * (GEMM_BK / 8)) % (2 * GEMM_BM) == 0, "whole W groups per thr extern "C" __global__ void GEMM_LAUNCH_BOUNDS gemms_##NAME(const GemmTile* tiles, const u8* wd, int nd, \ const float* x, int x_stride, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { \ gemm_q(tiles, wd, nd, x, x_stride, xrow, y, y_stride, rows, n64, act, sc); \ + } \ + extern "C" __global__ void __launch_bounds__(GEMM_BM * 2, 3) gemmm_##NAME(const GemmTile* tiles, const u8* wd, int nd, \ + const float* x, int x_stride, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc, \ + float* yo, int yo_stride, int yact, int* cnt) { \ + GEMMM_BODY(T, SBB); \ } QTYPES(DEF_GEMM) +// x (nd rows of cols floats, cols % 4 == 0) as halves for gemmm_*: the same h2pack rounding gemm_q applies. +extern "C" __global__ void x_to_f16(const float* x, int x_stride, int nd, int cols, u16* out) { + int i = blockIdx.x * blockDim.x + threadIdx.x, c4 = cols / 4; + if (i >= nd * c4) return; + int r = i / c4, c = i % c4 * 4; + float4 v = *(const float4*)(x + (size_t)r * x_stride + c); + *(uint2*)(out + (size_t)r * cols + c) = make_uint2(h2pack(v.x, v.y), h2pack(v.z, v.w)); +} + +// Sums the ks segments of a split-K gemm (part: ks x nd x rows) in order into y, with gemm_q's act. +extern "C" __global__ void gemm_splitk_sum(const float* part, int ks, int nd, int rows, float* y, int y_stride, int act) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= nd * rows) return; + float v = 0.f; + for (int z = 0; z < ks; z++) v += part[(size_t)z * nd * rows + i]; + float* yr = y + (size_t)(i / rows) * y_stride + i % rows; + *yr = act == 0 ? v : act == 1 ? silu(*yr) * v : *yr + v; +} + // ---- prefill GEMM on int8 tensor cores (integer weight types) ---- // X is first quantized by quant_q8 into q8 rows: cols int8, then cols / 32 f32 scales, then cols / 16 f32 sums of the // dequantized values (row bytes Q8_ROW(cols)). Weights come from QI as int8 with a scale (and min) per 16, and each @@ -1355,7 +1648,7 @@ __device__ __forceinline__ void mma_s8_16832_b(int* d, u32 a0, u32 a1, u32 a2, u } #endif // __CUDA_ARCH__ >= 800 // Weight types whose scale (and min) is constant over 32 weights: one 32-deep mma per scale. -template __host__ __device__ constexpr bool scale32() { return T == 42 || T == 34 || T == 35 || T == 2 || T == 3 || T == 6 || T == 7 || T == 8 || T == 12 || T == 13 || T == 16 || T == 19 || T == 18 || T == 21 || T == 23; } +template __host__ __device__ constexpr bool scale32() { return T == 42 || T == 34 || T == 143 || T == 35 || T == 2 || T == 3 || T == 6 || T == 7 || T == 8 || T == 12 || T == 13 || T == 16 || T == 19 || T == 18 || T == 21 || T == 23; } // Volta (sm_70) has no cp.async (sm_80+). There the copy is a synchronous typed load/store by the same thread, // which is also why the "wait" sites need no thread barrier (see the audit at attn_decode_t / attn_prefill_t). // Zero fill: with `ok == false` the source is not read at all (cp.async's size operand 0 contract) and `dst` @@ -1411,16 +1704,21 @@ template __device__ __forceinline__ void cp_async_wait() { } #endif -// sm_80+ only: Volta and Turing have no usable int8 tensor-core path here (see the guard above). +// sm_80+ int8 tensor-core path, and TU116/TU117 (MMA_FMA) native __dp4a path. // SM: as in gemm_q (gemmis_*, the tiles of at most 32 positions, 16 x 16 outputs per warp). -#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 || MMA_FMA template __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int nd, const u8* __restrict__ x, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { constexpr int P = 80, XM = SM ? 32 : BM; // smem pitch in bytes: 64 int8 + padding (conflict-free fragments, 16-byte aligned rows) +#if MMA_FMA + constexpr int NB = 1; +#else + constexpr int NB = 2; +#endif static_assert(BM == 128, "one X row half per thread"); - __shared__ __align__(16) signed char xq[2][XM * P], wq[64 * P]; - __shared__ __align__(16) float xd[2][XM][2], xsum[2][XM][4]; + __shared__ __align__(16) signed char xq[NB][XM * P], wq[64 * P]; + __shared__ __align__(16) float xd[NB][XM][2], xsum[NB][XM][4]; __shared__ __align__(16) float2 wdm[4][64]; // W scale and min per 16 weights: [16-group][row] GemmTile tl = tiles ? tiles[blockIdx.y] : GemmTile{wd, (int)blockIdx.y * XM, min(XM, nd - (int)blockIdx.y * XM)}; if (tiles && (tl.cnt <= 32) != SM) return; @@ -1431,7 +1729,11 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int bool xok = xr_ < tl.cnt; const u8* xp = x + (size_t)(xok ? (xrow ? xrow[tl.m0 + xr_] : tl.m0 + xr_) : 0) * Q8_ROW(cols); auto ldx = [&](int kb) { +#if MMA_FMA + int b = 0; +#else int b = kb & 1; +#endif if (SM && xr_ >= XM) { cp_async_commit(); return; } cp_async16(&xq[b][xr_ * P + xh * 32], xp + kb * 64 + xh * 32, xok); cp_async16(&xq[b][xr_ * P + xh * 32 + 16], xp + kb * 64 + xh * 32 + 16, xok); @@ -1468,11 +1770,17 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int ldw(0); stw(); for (int kb = 0; kb < nk; kb++) { +#if !MMA_FMA if (kb + 1 < nk) ldx(kb + 1); if (kb + 1 < nk) cp_async_wait<1>(); else cp_async_wait<0>(); +#endif __syncthreads(); if (kb + 1 < nk) ldw(kb + 1); +#if MMA_FMA + const int b = 0; +#else const int b = kb & 1; +#endif constexpr int KS = scale32() ? 32 : 16; // depth of one mma (one weight scale) constexpr int MT = SM ? 1 : 2, NT8 = SM ? 2 : 4; // X scales and sums of the step for this thread's rows (g, g + 8 of each mt), one vector load each. @@ -1485,6 +1793,70 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int xdv[mt][i] = *(const float2*)xd[b][r]; if (QI::MIN) xsv[mt][i] = *(const float4*)xsum[b][r]; } +#if MMA_FMA + #pragma unroll + for (int h = 0; h < 64 / KS; h++) if (wm < tl.cnt) { + float da[2][2], sa[2][2], dbv[4][2], mb[4][2]; + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int i = 0; i < 2; i++) { + const float* xs = (const float*)&xsv[mt][i]; + da[mt][i] = h * KS / 32 ? xdv[mt][i].y : xdv[mt][i].x; + if (QI::MIN) sa[mt][i] = KS == 32 ? xs[2 * h] + xs[2 * h + 1] : xs[h]; + } + #pragma unroll + for (int nt = 0; nt < NT8; nt++) { + int n = wn + nt * 8; + float4 q = *(const float4*)&wdm[h * KS / 16][n + 2 * t]; + dbv[nt][0] = q.x; mb[nt][0] = q.y; dbv[nt][1] = q.z; mb[nt][1] = q.w; + } + int sum[MT][NT8][4] = {}; + #pragma unroll + for (int kk = 0; kk < KS; kk += 16) { + int4 av[MT][2], bv[NT8][2]; + #pragma unroll + for (int mt = 0; mt < MT; mt++) { + int r = wm + mt * 16 + g; + av[mt][0] = *(const int4*)&xq[0][r * P + h * KS + kk]; + av[mt][1] = *(const int4*)&xq[0][(r + 8) * P + h * KS + kk]; + } + #pragma unroll + for (int nt = 0; nt < NT8; nt++) { + int n = wn + nt * 8 + 2 * t; + bv[nt][0] = *(const int4*)&wq[n * P + h * KS + kk]; + bv[nt][1] = *(const int4*)&wq[(n + 1) * P + h * KS + kk]; + } + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int nt = 0; nt < NT8; nt++) + #pragma unroll + for (int ri = 0; ri < 2; ri++) + #pragma unroll + for (int ci = 0; ci < 2; ci++) { + int s = sum[mt][nt][2 * ri + ci]; + s = __dp4a(av[mt][ri].x, bv[nt][ci].x, s); + s = __dp4a(av[mt][ri].y, bv[nt][ci].y, s); + s = __dp4a(av[mt][ri].z, bv[nt][ci].z, s); + s = __dp4a(av[mt][ri].w, bv[nt][ci].w, s); + sum[mt][nt][2 * ri + ci] = s; + } + } + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int nt = 0; nt < NT8; nt++) + #pragma unroll + for (int i = 0; i < 4; i++) { + float f = (float)sum[mt][nt][i] * (da[mt][i >> 1] * dbv[nt][i & 1]); + if (QI::MIN) f -= sa[mt][i >> 1] * mb[nt][i & 1]; + acc[mt][nt][i] += f; + } + } + __syncthreads(); + if (kb + 1 < nk) { ldx(kb + 1); stw(); } +#else #pragma unroll for (int h = 0; h < 64 / KS; h++) if (wm < tl.cnt) { u32 a[2][4], bw[4][2]; @@ -1528,6 +1900,7 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int } __syncthreads(); if (kb + 1 < nk) stw(); +#endif } #pragma unroll for (int mt = 0; mt < (SM ? 1 : 2); mt++) @@ -1547,333 +1920,1812 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int } } -#define DEF_GEMMI(T, NAME, SBB) \ - extern "C" __global__ void __launch_bounds__(256, 2) gemmi_##NAME(const GemmTile* tiles, const u8* wd, int nd, \ - const u8* x, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { \ - gemmi_q(tiles, wd, nd, x, xrow, y, y_stride, rows, n64, act, sc); \ - } \ - extern "C" __global__ void __launch_bounds__(256) gemmis_##NAME(const GemmTile* tiles, const u8* wd, int nd, \ - const u8* x, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { \ - gemmi_q(tiles, wd, nd, x, xrow, y, y_stride, rows, n64, act, sc); \ - } -ITYPES(DEF_GEMMI) +// gemmi_q in steps of S (64-deep K steps per barrier), taken only by gemmis_q6_k on sm_80+. Its loop shape makes ptxas +// give gemmis_q6_k 64-76 registers instead of 48: RTX 3060, gemm_expert_throughput, GigaChat4 Q6_K down 3.58 -> 2.54 ms +// at 21 positions an expert (8: 3.21 -> 2.06). Q4_K and the other types stay on gemmi_q: this form made gemmis_q4_k +// 3-5% slower (91 registers, or 76 with __launch_bounds__(256, 3)). S = 2 and 4 were slower than S = 1 for both types +// (21 an expert: Q4_K gate 1.65 -> 1.72 / 1.96 ms, Q6_K down 2.53 -> 2.82 / 2.74 ms). +template +__device__ __forceinline__ void gemmi_qs(const GemmTile* tiles, const u8* wd, int nd, const u8* __restrict__ x, + const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { + constexpr int P = 64 * S + 16, XM = SM ? 32 : BM; // smem pitch in bytes: S * 64 int8 + padding (conflict-free fragments, 16-byte aligned rows) +#if MMA_FMA + constexpr int NB = 1; + static_assert(S == 1, "the dp4a path steps 64 deep"); +#else + constexpr int NB = 2; #endif - -// ---- elementwise / norm ---- - -// grid = rows. out[r] = rmsnorm(x[r]) * w (same w for every row). xq (optional): out also quantized as quant_xq does. -// Row r takes gamma row r % wr of w (wr > 1: hyper-connection streams, one gamma per stream). -extern "C" __global__ void rms_norm(float* x, int x_stride, const float* w, float* out, int out_stride, int n, float eps, - signed char* xq, const float* res, int wr) { - w += (size_t)(blockIdx.x % wr) * n; - float* xr = x + (size_t)blockIdx.x * x_stride; - float* o = out + (size_t)blockIdx.x * out_stride; - float s = 0.0f; - // The sum keeps the order of a 256-thread block (bit-identical results); all threads scale. Four loads in flight - // per step; the output values are all loaded before any store, as out may alias x. With res, x += res first. - if (threadIdx.x < 256 && res) { - const float* rr = res + (size_t)blockIdx.x * x_stride; - int i = threadIdx.x; - for (; i + 768 < n; i += 1024) { - float a = xr[i] + rr[i], b = xr[i + 256] + rr[i + 256], c = xr[i + 512] + rr[i + 512], d = xr[i + 768] + rr[i + 768]; - xr[i] = a; xr[i + 256] = b; xr[i + 512] = c; xr[i + 768] = d; - s += a * a; s += b * b; s += c * c; s += d * d; - } - for (; i < n; i += 256) { float a = xr[i] + rr[i]; xr[i] = a; s += a * a; } - } else if (threadIdx.x < 256) { - int i = threadIdx.x; - for (; i + 768 < n; i += 1024) { - float a = xr[i], b = xr[i + 256], c = xr[i + 512], d = xr[i + 768]; - s += a * a; s += b * b; s += c * c; s += d * d; + static_assert(BM == 128, "one X row half per thread"); + __shared__ __align__(16) signed char xq[NB][XM * P], wq[64 * P]; + __shared__ __align__(16) float xd[NB][XM][2 * S], xsum[NB][XM][4 * S]; + __shared__ __align__(16) float2 wdm[4 * S][64]; // W scale and min per 16 weights: [16-group][row] + GemmTile tl = tiles ? tiles[blockIdx.y] : GemmTile{wd, (int)blockIdx.y * XM, min(XM, nd - (int)blockIdx.y * XM)}; + if (tiles && (tl.cnt <= 32) != SM) return; + int n0 = blockIdx.x * 64, tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, g = lane >> 2, t = lane & 3; + int wm = SM ? 16 * (warp & 1) : (warp >> 1) * 32, wn = SM ? 16 * (warp >> 1) : (warp & 1) * 32, cols = n64 * 64; + const int nk = n64; + // X: per step, thread copies 32 int8 (half of the row's 64) of row xr_, plus the row's scales (xh = 0) or sums + // (xh = 1). Steps past the last (a partial group of S) read zeros. + int xr_ = tid >> 1, xh = tid & 1; + bool xok = xr_ < tl.cnt; + const u8* xp = x + (size_t)(xok ? (xrow ? xrow[tl.m0 + xr_] : tl.m0 + xr_) : 0) * Q8_ROW(cols); + auto ldx = [&](int kb) { +#if MMA_FMA + int b = 0; +#else + int b = (kb / S) & 1; +#endif + if (SM && xr_ >= XM) { cp_async_commit(); return; } + #pragma unroll + for (int s = 0; s < S; s++) { + bool ok = xok && kb + s < nk; + cp_async16(&xq[b][xr_ * P + s * 64 + xh * 32], xp + (kb + s) * 64 + xh * 32, ok); + cp_async16(&xq[b][xr_ * P + s * 64 + xh * 32 + 16], xp + (kb + s) * 64 + xh * 32 + 16, ok); + if (xh) cp_async16(&xsum[b][xr_][4 * s], xp + cols + cols / 8 + (kb + s) * 16, ok); + else cp_async8(&xd[b][xr_][2 * s], xp + cols + (kb + s) * 8, ok); } - for (; i < n; i += 256) s += xr[i] * xr[i]; - } - float sc = 1.0f / sqrtf(block_sum(s) / (float)n + eps); - if (xq) { // each thread scales, stores and quantizes its own 8 values, as quant_x would map them - signed char* q = xq + (size_t)blockIdx.x * n; - float* qd = (float*)(xq + (size_t)gridDim.x * n) + blockIdx.x * (n / 32); - for (int i0 = 0; i0 < n; i0 += blockDim.x * 8) { - int i = i0 + threadIdx.x * 8; - unsigned m = __ballot_sync(0xffffffff, i < n); - if (i >= n) continue; - float4 a = *(const float4*)(xr + i), c = *(const float4*)(xr + i + 4); - float4 wa = *(const float4*)(w + i), wc = *(const float4*)(w + i + 4); - a = make_float4(a.x * sc * wa.x, a.y * sc * wa.y, a.z * sc * wa.z, a.w * sc * wa.w); - c = make_float4(c.x * sc * wc.x, c.y * sc * wc.y, c.z * sc * wc.z, c.w * sc * wc.w); - *(float4*)(o + i) = a; *(float4*)(o + i + 4) = c; - quant8(a, c, i, q, qd, m); + cp_async_commit(); + }; + // W: per step, thread decodes the 16 weights (subs 2 wi, 2 wi + 1 of the step) of row wr_. + int wr_ = tid >> 2, wi = tid & 3; + const u8* wp = n0 + wr_ < rows ? tl.w + (size_t)(n0 + wr_) * ROWB(cols, SBB) : nullptr; + const bool v16 = ((size_t)tl.w & 15) == 0 && ROWB(cols, SBB) % 16 == 0; // QI::get2's 16-byte loads + float acc[2][4][4] = {}; + // W steps kb .. kb + S - 1 are decoded into registers during the previous group's mma and stored after it. + int lo0[S], hi0[S], lo1[S], hi1[S]; float wd0[S], wm0[S]; + auto ldw = [&](int kb) { + #pragma unroll + for (int s = 0; s < S; s++) { + lo0[s] = hi0[s] = lo1[s] = hi1[s] = 0; wd0[s] = wm0[s] = 0.f; + float d1, m1; + if (wp && kb + s < nk) { + const u8* sbp = wp + (size_t)((kb + s) >> 2) * SBB; + int sub = ((kb + s) & 3) * 8 + 2 * wi; + if constexpr (T == 12) { + if (v16) { QI<12>::get2(sbp, sub, lo0[s], hi0[s], lo1[s], hi1[s], wd0[s], wm0[s]); continue; } + } + QI::get(sbp, sub, lo0[s], hi0[s], wd0[s], wm0[s]); + QI::get(sbp, sub + 1, lo1[s], hi1[s], d1, m1); + } } - return; - } - int i = threadIdx.x, bd = blockDim.x; - for (; i + 3 * bd < n; i += 4 * bd) { - float a = xr[i] * sc * w[i], b = xr[i + bd] * sc * w[i + bd], c = xr[i + 2 * bd] * sc * w[i + 2 * bd], d = xr[i + 3 * bd] * sc * w[i + 3 * bd]; - o[i] = a; o[i + bd] = b; o[i + 2 * bd] = c; o[i + 3 * bd] = d; - } - for (; i < n; i += bd) o[i] = xr[i] * sc * w[i]; -} - -// Block-wide (largest b, first bi on ties) of the threads' (b, bi), in thread 0; bi == n marks no value yet. -__device__ void amax_reduce(float& b, int& bi, int n) { - for (int o = 16; o > 0; o >>= 1) { - float v = __shfl_xor_sync(0xffffffff, b, o); int vi = __shfl_xor_sync(0xffffffff, bi, o); - if (v > b || (v == b && vi < bi)) { b = v; bi = vi; } - } - __shared__ float sv[32]; __shared__ int si[32]; - int lane = threadIdx.x & 31, w = threadIdx.x >> 5; - if (lane == 0) { sv[w] = b; si[w] = bi; } - __syncthreads(); - if (w == 0) { - b = lane < (blockDim.x >> 5) ? sv[lane] : __int_as_float(0xff800000); bi = lane < (blockDim.x >> 5) ? si[lane] : n; - for (int o = 16; o > 0; o >>= 1) { - float v = __shfl_xor_sync(0xffffffff, b, o); int vi = __shfl_xor_sync(0xffffffff, bi, o); - if (v > b || (v == b && vi < bi)) { b = v; bi = vi; } + }; + auto stw = [&]() { + #pragma unroll + for (int s = 0; s < S; s++) { + *(int4*)(wq + wr_ * P + s * 64 + wi * 16) = make_int4(lo0[s], hi0[s], lo1[s], hi1[s]); + wdm[4 * s + wi][wr_] = make_float2(wd0[s], wm0[s]); } - } -} - -// grid = (parts, rows). part[r * parts + p] = (largest x, its index) of row r over i = p * blockDim + t + k * parts * blockDim. -extern "C" __global__ void argmax_part(const float* x, int n, int2* part) { - const float* xr = x + (size_t)blockIdx.y * n; - float b = __int_as_float(0xff800000); int bi = n; - for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) if (xr[i] > b || bi == n) { b = xr[i]; bi = i; } - amax_reduce(b, bi, n); - if (threadIdx.x == 0) part[blockIdx.y * gridDim.x + blockIdx.x] = make_int2(__float_as_int(b), bi); -} - -// grid = rows, block = parts. out[r] = index of the largest x in row r (first one on ties, like ops::argmax). -extern "C" __global__ void argmax_rows(const int2* part, int n, int* out) { - int2 p = part[blockIdx.x * blockDim.x + threadIdx.x]; - float b = __int_as_float(p.x); int bi = p.y; - amax_reduce(b, bi, n); - if (threadIdx.x == 0) out[blockIdx.x] = bi; -} - -// grid = rows, in place. Row r is vector r % per of token r / per (tokens `stride` floats apart). -extern "C" __global__ void l2_norm(float* x, int n, int per, int stride, float eps) { - float* xr = x + (size_t)(blockIdx.x / per) * stride + (size_t)(blockIdx.x % per) * n; + }; + ldx(0); + ldw(0); + stw(); + for (int kb = 0; kb < nk; kb += S) { +#if !MMA_FMA + if (kb + S < nk) ldx(kb + S); + if (kb + S < nk) cp_async_wait<1>(); else cp_async_wait<0>(); +#endif + __syncthreads(); + if (kb + S < nk) ldw(kb + S); +#if MMA_FMA + const int b = 0; +#else + const int b = (kb / S) & 1; +#endif + constexpr int KS = scale32() ? 32 : 16; // depth of one mma (one weight scale) + constexpr int MT = SM ? 1 : 2, NT8 = SM ? 2 : 4; + #pragma unroll + for (int s = 0; s < S; s++) { + // X scales and sums of the step for this thread's rows (g, g + 8 of each mt), one vector load each. + float2 xdv[2][2]; float4 xsv[2][2]; + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int i = 0; i < 2; i++) { + int r = wm + mt * 16 + g + 8 * i; + xdv[mt][i] = *(const float2*)&xd[b][r][2 * s]; + if (QI::MIN) xsv[mt][i] = *(const float4*)&xsum[b][r][4 * s]; + } +#if MMA_FMA + #pragma unroll + for (int h = 0; h < 64 / KS; h++) if (wm < tl.cnt) { + float da[2][2], sa[2][2], dbv[4][2], mb[4][2]; + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int i = 0; i < 2; i++) { + const float* xs = (const float*)&xsv[mt][i]; + da[mt][i] = h * KS / 32 ? xdv[mt][i].y : xdv[mt][i].x; + if (QI::MIN) sa[mt][i] = KS == 32 ? xs[2 * h] + xs[2 * h + 1] : xs[h]; + } + #pragma unroll + for (int nt = 0; nt < NT8; nt++) { + int n = wn + nt * 8; + float4 q = *(const float4*)&wdm[h * KS / 16][n + 2 * t]; + dbv[nt][0] = q.x; mb[nt][0] = q.y; dbv[nt][1] = q.z; mb[nt][1] = q.w; + } + int sum[MT][NT8][4] = {}; + #pragma unroll + for (int kk = 0; kk < KS; kk += 16) { + int4 av[MT][2], bv[NT8][2]; + #pragma unroll + for (int mt = 0; mt < MT; mt++) { + int r = wm + mt * 16 + g; + av[mt][0] = *(const int4*)&xq[0][r * P + h * KS + kk]; + av[mt][1] = *(const int4*)&xq[0][(r + 8) * P + h * KS + kk]; + } + #pragma unroll + for (int nt = 0; nt < NT8; nt++) { + int n = wn + nt * 8 + 2 * t; + bv[nt][0] = *(const int4*)&wq[n * P + h * KS + kk]; + bv[nt][1] = *(const int4*)&wq[(n + 1) * P + h * KS + kk]; + } + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int nt = 0; nt < NT8; nt++) + #pragma unroll + for (int ri = 0; ri < 2; ri++) + #pragma unroll + for (int ci = 0; ci < 2; ci++) { + int v = sum[mt][nt][2 * ri + ci]; + v = __dp4a(av[mt][ri].x, bv[nt][ci].x, v); + v = __dp4a(av[mt][ri].y, bv[nt][ci].y, v); + v = __dp4a(av[mt][ri].z, bv[nt][ci].z, v); + v = __dp4a(av[mt][ri].w, bv[nt][ci].w, v); + sum[mt][nt][2 * ri + ci] = v; + } + } + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int nt = 0; nt < NT8; nt++) + #pragma unroll + for (int i = 0; i < 4; i++) { + float f = (float)sum[mt][nt][i] * (da[mt][i >> 1] * dbv[nt][i & 1]); + if (QI::MIN) f -= sa[mt][i >> 1] * mb[nt][i & 1]; + acc[mt][nt][i] += f; + } + } +#else + #pragma unroll + for (int h = 0; h < 64 / KS; h++) if (wm < tl.cnt) { + u32 a[2][4], bw[4][2]; + float da[2][2], sa[2][2], dbv[4][2], mb[4][2]; + const int k0 = s * 64 + h * KS; + #pragma unroll + for (int mt = 0; mt < MT; mt++) { + int r = wm + mt * 16 + g; + const signed char* p = &xq[b][r * P + k0 + 4 * t]; + a[mt][0] = *(const u32*)p; a[mt][1] = *(const u32*)(p + 8 * P); + if (KS == 32) { a[mt][2] = *(const u32*)(p + 16); a[mt][3] = *(const u32*)(p + 8 * P + 16); } + #pragma unroll + for (int i = 0; i < 2; i++) { + const float* xs = (const float*)&xsv[mt][i]; + da[mt][i] = h * KS / 32 ? xdv[mt][i].y : xdv[mt][i].x; + if (QI::MIN) sa[mt][i] = KS == 32 ? xs[2 * h] + xs[2 * h + 1] : xs[h]; + } + } + #pragma unroll + for (int nt = 0; nt < NT8; nt++) { + int n = wn + nt * 8; + const signed char* p = wq + (n + g) * P + k0 + 4 * t; + bw[nt][0] = *(const u32*)p; + if (KS == 32) bw[nt][1] = *(const u32*)(p + 16); + float4 q = *(const float4*)&wdm[k0 / 16][n + 2 * t]; + dbv[nt][0] = q.x; mb[nt][0] = q.y; dbv[nt][1] = q.z; mb[nt][1] = q.w; + } + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int nt = 0; nt < NT8; nt++) { + int c[4]; + if (KS == 32) mma_s8_16832_b(c, a[mt][0], a[mt][1], a[mt][2], a[mt][3], bw[nt][0], bw[nt][1]); + else mma_s8_16816_b(c, a[mt][0], a[mt][1], bw[nt][0]); + #pragma unroll + for (int i = 0; i < 4; i++) { + float f = (__int_as_float(c[i]) - 12582912.0f) * (da[mt][i >> 1] * dbv[nt][i & 1]); // i2f_small + if (QI::MIN) f -= sa[mt][i >> 1] * mb[nt][i & 1]; + acc[mt][nt][i] += f; + } + } + } +#endif + } + __syncthreads(); +#if MMA_FMA + if (kb + 1 < nk) { ldx(kb + 1); stw(); } +#else + if (kb + S < nk) stw(); +#endif + } + #pragma unroll + for (int mt = 0; mt < (SM ? 1 : 2); mt++) + #pragma unroll + for (int nt = 0; nt < (SM ? 2 : 4); nt++) + #pragma unroll + for (int h = 0; h < 2; h++) { + int r = wm + mt * 16 + g + 8 * h, n = n0 + wn + nt * 8 + 2 * t; + if (r >= tl.cnt) continue; + float* yr = y + (size_t)(tl.m0 + r) * y_stride; + #pragma unroll + for (int e = 0; e < 2; e++) { + if (n + e >= rows) break; + float v = acc[mt][nt][2 * h + e] * sc; + yr[n + e] = act == 0 ? v : act == 1 ? silu(yr[n + e]) * v : yr[n + e] + v; + } + } +} + +#if MMA_FMA +#define GEMMIS_S 0 +#else +#define GEMMIS_S 1 // gemmis_q6_k takes gemmi_qs (not measured on the dp4a path) +#endif + +#define DEF_GEMMI(T, NAME, SBB) \ + extern "C" __global__ void __launch_bounds__(256, 2) gemmi_##NAME(const GemmTile* tiles, const u8* wd, int nd, \ + const u8* x, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { \ + gemmi_q(tiles, wd, nd, x, xrow, y, y_stride, rows, n64, act, sc); \ + } \ + extern "C" __global__ void __launch_bounds__(256) gemmis_##NAME(const GemmTile* tiles, const u8* wd, int nd, \ + const u8* x, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { \ + if constexpr (T == 14 && GEMMIS_S) gemmi_qs(tiles, wd, nd, x, xrow, y, y_stride, rows, n64, act, sc); \ + else gemmi_q(tiles, wd, nd, x, xrow, y, y_stride, rows, n64, act, sc); \ + } +ITYPES(DEF_GEMMI) +#endif + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 + +// ---- small-batch int8 GEMM (batched decode: at most 64 positions) ---- +// grid = ks * ceil(rows / 128), block = 256, dynamic shared memory (Gpu::gemm_raw has the size); pb = 8, 16, 32 or 64 +// is nd rounded up. +// A warp owns 16 W rows as the mma A operand. Lane (g, t) decodes the 8 weights 32 q + 8 t .. of rows g and g + 8 +// from global memory itself, so W is not staged in shared memory and the K loop has no barrier per step +// (gemmi_q: two barriers per 64 columns and every warp of the block decodes for the mmas of half of them). +// Both operands permute the k index of the mma the same way (column 8 t + j is k 4 t + j, column 8 t + 4 + j is +// k 16 + 4 t + j), so a lane's 8 weights are one QI get and its 8 x values one load. A type with a scale per 16 runs +// two mmas per 32 columns, each with the lanes of the other half zeroed. +// X (q8 rows) is the B operand, from a shared-memory window of GEMMD_XW(pb) columns that cp.async double-buffers: one +// barrier per window. +// ks > 1: ks blocks (seg 0 .. ks - 1) share 128 rows, each over a ks-th of the column windows (Gpu::gemm_raw has the +// rule and the measurement). Every block stores its partial sums in scr ([seg][position][row]); the one that ends last +// (flag: the count of blocks done for these rows, reset to 0 by that block) adds them in segment order and writes y, +// so the result does not depend on which block that is. +#define GEMMD_XW(pb) ((pb) >= 32 ? 128 : 4096 / (pb)) +// XW: the window width when it is known at compile time (its pitch then makes the x loads' offsets immediates), else 0. +// FULL: 64 positions, so every one of the 8 tiles has positions (no test a tile). +template +__device__ __forceinline__ void gemmd_qx(const u8* w, const u8* __restrict__ x, int nd, int pb, int ks, float* scr, int* flag, + float* y, int y_stride, int rows, int cols, int act, float sc) { + // One window: pb rows of xw + 32 int8 (the pitch puts two lanes on a bank, the least an 8-byte load allows), + // then xw / 32 scales and xw / 16 sums per row. Two windows, then pk. + extern __shared__ __align__(16) signed char gemmd_s[]; + int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, g = lane >> 2, t = lane & 3; + int seg = blockIdx.x % ks, rb = blockIdx.x / ks, bs = blockDim.x, ts = tid; + int xw = XW ? XW : GEMMD_XW(pb), lx = 31 - __clz(xw), pitch = xw + 32, od = pb * pitch, os = od + pb * (xw >> 3), xb_ = os + pb * (xw >> 2); + int nq = cols / 32, qw = xw >> 5, nwin = (cols + xw - 1) >> lx, nws = (nwin + ks - 1) / ks, w0 = seg * nws; + signed char* gx = gemmd_s; + float* pk = (float*)(gx + 2 * xb_); // per (position pair, 32 columns): d0, d1, s0, s1, then the four half sums + int np = nd, npt = (np + 7) >> 3, r0 = (rb * (bs >> 5) + warp) * 16; + const u8* xr = x; + int nc0 = pb * (xw >> 4), nc1 = nc0 + pb * (xw >> 7), nc2 = nc1 + pb * (xw >> 6); + auto ldx = [&](int wi) { // window wi of this block's columns + signed char* d = gx + (wi & 1) * xb_; + int k0 = (w0 + wi) * xw; + for (int c = ts; c < nc2; c += bs) { // 16-byte chunks: int8, then scales, then sums + int pos, o; const u8* src; signed char* dst; bool ok; + if (c < nc0) { + pos = c >> (lx - 4); o = (c & ((xw >> 4) - 1)) * 16; + src = xr + (size_t)pos * Q8_ROW(cols) + k0 + o; dst = d + pos * pitch + o; ok = k0 + o < cols; + } else if (c < nc1) { + pos = (c - nc0) >> (lx - 7); o = ((c - nc0) & ((xw >> 7) - 1)) * 16; + src = xr + (size_t)pos * Q8_ROW(cols) + cols + (k0 >> 3) + o; dst = d + od + pos * (xw >> 3) + o; ok = k0 + o * 8 < cols; + } else { + pos = (c - nc1) >> (lx - 6); o = ((c - nc1) & ((xw >> 6) - 1)) * 16; + src = xr + (size_t)pos * Q8_ROW(cols) + cols + cols / 8 + (k0 >> 2) + o; dst = d + os + pos * (xw >> 2) + o; ok = k0 + o * 4 < cols; + } + cp_async16(dst, src, ok && pos < np); + } + cp_async_commit(); + }; + const bool live = r0 < rows; + const u8* pa = w + (size_t)min(r0 + g, rows - 1) * ROWB(cols, SBB); + const u8* pb_ = w + (size_t)min(r0 + g + 8, rows - 1) * ROWB(cols, SBB); + constexpr int KS = scale32() ? 32 : 16; + float acc[8][4] = {}; + const signed char* xb; + // The scales and sums of window wi, from the staged q8 rows into pk: one load per mma instead of four. + auto pack = [&](int wi) { + const float* xd = (const float*)(gx + (wi & 1) * xb_ + od); const float* xs = (const float*)(gx + (wi & 1) * xb_ + os); + for (int c = ts; c < (pb >> 1) * qw; c += bs) { + int p = 2 * (c % (pb >> 1)), kw = c / (pb >> 1); // [kw][pair]: the four t of a warp load from 16 banks + float* o = pk + c * 8; + *(float2*)o = make_float2(xd[p * qw + kw], xd[(p + 1) * qw + kw]); + if (QI::MIN) { + float2 s0 = *(const float2*)(xs + p * 2 * qw + 2 * kw), s1 = *(const float2*)(xs + (p + 1) * 2 * qw + 2 * kw); + *(float2*)(o + 2) = make_float2(s0.x + s0.y, s1.x + s1.y); + *(float4*)(o + 4) = make_float4(s0.x, s0.y, s1.x, s1.y); + } + } + __syncthreads(); + }; + // The mmas of one 32-column block (kw in the window): A fragment a0..a3, W scale and min of rows g and g + 8. + auto blk = [&](int kw, u32 a0, u32 a1, u32 a2, u32 a3, float wda, float wma, float wdb, float wmb) { + // Scale per 16: lanes t < 2 hold the first 16 columns of the 32, lane t ^ 2 the scale of the other 16. + float oda = 0.f, oma = 0.f, odb = 0.f, omb = 0.f; + if (KS == 16) { + oda = __shfl_xor_sync(0xffffffffu, wda, 2); odb = __shfl_xor_sync(0xffffffffu, wdb, 2); + if (QI::MIN) { oma = __shfl_xor_sync(0xffffffffu, wma, 2); omb = __shfl_xor_sync(0xffffffffu, wmb, 2); } + } + // Scale per 16: a 16-deep mma per half h, its A fragment in the mma's own order (lane t: columns 16 h + 4 t .., + // which lane 2 h + t / 2 holds), so no lane is zero. The integer sums are the same as with 32-deep mmas. + u32 n0[2] = {0, 0}, n1[2] = {0, 0}; + if (KS == 16) { + #pragma unroll + for (int h = 0; h < 2; h++) { + const int src = (lane & ~3) | (2 * h + (t >> 1)); + const u32 l0 = __shfl_sync(0xffffffffu, a0, src), h0 = __shfl_sync(0xffffffffu, a2, src); + const u32 l1 = __shfl_sync(0xffffffffu, a1, src), h1 = __shfl_sync(0xffffffffu, a3, src); + n0[h] = t & 1 ? h0 : l0; n1[h] = t & 1 ? h1 : l1; + } + } + #pragma unroll + for (int pt = 0; pt < 8; pt++) { // 8 positions an mma + if (!FULL && pt >= npt) break; + const signed char* xp = xb + (pt * 8 + g) * pitch + kw * 32; + const uint2 bx = KS == 32 ? *(const uint2*)(xp + 8 * t) : make_uint2(*(const u32*)(xp + 4 * t), *(const u32*)(xp + 16 + 4 * t)); + const float* o = pk + (kw * (pb >> 1) + pt * 4 + t) * 8; + float dx[2], s32[2] = {0.f, 0.f}; + float2 sx[2] = {make_float2(0.f, 0.f), make_float2(0.f, 0.f)}; + if (QI::MIN && KS == 32) { const float4 v = *(const float4*)o; dx[0] = v.x; dx[1] = v.y; s32[0] = v.z; s32[1] = v.w; } + else { + const float2 v = *(const float2*)o; dx[0] = v.x; dx[1] = v.y; + if (QI::MIN) { const float4 u = *(const float4*)(o + 4); sx[0] = make_float2(u.x, u.y); sx[1] = make_float2(u.z, u.w); } + } + #pragma unroll + for (int h = 0; h < 32 / KS; h++) { + const bool mine = KS == 32 || (t >> 1) == h; + int c[4]; + if (KS == 32) mma_s8_16832_b(c, a0, a1, a2, a3, bx.x, bx.y); + else mma_s8_16816_b(c, n0[h], n1[h], h ? bx.y : bx.x); + const float dw[2] = {mine ? wda : oda, mine ? wdb : odb}, mw[2] = {mine ? wma : oma, mine ? wmb : omb}; + #pragma unroll + for (int i = 0; i < 4; i++) { + // Two fmas into the sum (a product, a subtraction and an add cost one instruction more). + acc[pt][i] = fmaf(__int_as_float(c[i]) - 12582912.0f, dx[i & 1] * dw[i >> 1], acc[pt][i]); // i2f_small + if (QI::MIN) acc[pt][i] = fmaf(-(KS == 32 ? s32[i & 1] : h ? sx[i & 1].y : sx[i & 1].x), mw[i >> 1], acc[pt][i]); + } + } + } + }; + // Generic: block q + 1 is decoded during block q's mmas. + int la = 0, ha = 0, lb = 0, hb = 0; float da = 0.f, ma = 0.f, db = 0.f, mb = 0.f; + auto dec = [&](int q) { + ma = mb = 0.f; + int sub = (q & 7) * 4 + t; size_t o = (size_t)(q >> 3) * SBB; + QI::get(pa + o, sub, la, ha, da, ma); + QI::get(pb_ + o, sub, lb, hb, db, mb); + }; + // Q4_K: 64 columns of a row are 32 bytes of nibbles (low: the first 32 columns), so the lane's two blocks are one + // 8-byte load a row; the pair after is loaded before this pair's mmas. + const bool k4 = T == 12 && ((size_t)w & 15) == 0 && cols % 256 == 0; + uint4 sa_ = make_uint4(0, 0, 0, 0), sb_ = sa_; uint2 ua = make_uint2(0, 0), ub = ua; + float sda = 0.f, sma = 0.f, sdb = 0.f, smb = 0.f; + auto ldp = [&](int p, bool hdr) { // hdr: the pair is the first of its super-block that this block reads + size_t o = (size_t)(p >> 2) * 144; int j = 16 + 32 * (p & 3) + 8 * t; + if (hdr) { sa_ = *(const uint4*)(pa + o); sb_ = *(const uint4*)(pb_ + o); } + ua = *(const uint2*)(pa + o + j); ub = *(const uint2*)(pb_ + o + j); + }; + // Q6_K: a half super-block (128 columns: a window holds whole ones) is loaded at once, the next during this one. + const bool k6 = T == 14 && cols % 256 == 0; + H6 h6a, h6b; + auto ld6 = [&](int hf) { size_t o = (size_t)(hf >> 1) * 210; h6_ld(pa + o, hf & 1, t, h6a); h6_ld(pb_ + o, hf & 1, t, h6b); }; + ldx(0); + cp_async_wait<0>(); + __syncthreads(); + pack(0); + if (live && w0 * qw < nq) { if (k4) ldp(w0 * qw / 2, true); else if (k6) ld6(w0 * qw / 4); else dec(w0 * qw); } + for (int wi = 0; wi < nws; wi++) { + if (wi + 1 < nws) ldx(wi + 1); // into the buffer of window wi - 1: every thread passed the barrier below + xb = gx + (wi & 1) * xb_; + int qa = (w0 + wi) * qw, q1 = min(nq, qa + qw); + if (live && k4) { + for (int p = qa / 2; p < q1 / 2; p++) { + const uint4 ca = sa_, cb = sb_; const uint2 va = ua, vb = ub; + if (p + 1 < nq / 2) ldp(p + 1, !((p + 1) & 3)); + // The four lanes of a row would decode the same scale: at an even pair (a window starts at one: it + // is 128 columns or more) lane t decodes the scale of block t of the next four, and a shuffle + // hands each block's scale to the row's lanes. + if (!(p & 1)) { + k4_dm_w(ca.x, ca.y, ca.z, ca.w, 2 * (p & 2) + t, sda, sma); + k4_dm_w(cb.x, cb.y, cb.z, cb.w, 2 * (p & 2) + t, sdb, smb); + } + #pragma unroll + for (int h = 0; h < 2; h++) { + const int from = (lane & ~3) | (2 * (p & 1) + h); + const float wda = __shfl_sync(0xffffffffu, sda, from), wma = __shfl_sync(0xffffffffu, sma, from); + const float wdb = __shfl_sync(0xffffffffu, sdb, from), wmb = __shfl_sync(0xffffffffu, smb, from); + blk(2 * p + h - qa, (va.x >> (4 * h)) & 0x0F0F0F0Fu, (vb.x >> (4 * h)) & 0x0F0F0F0Fu, + (va.y >> (4 * h)) & 0x0F0F0F0Fu, (vb.y >> (4 * h)) & 0x0F0F0F0Fu, wda, wma, wdb, wmb); + } + } + } else if (live && k6) { + for (int hf = qa / 4; hf < q1 / 4; hf++) { + const H6 ca = h6a, cb = h6b; + if (hf + 1 < nq / 4) ld6(hf + 1); + #pragma unroll + for (int qt = 0; qt < 4; qt++) { + int a0, a1, a2, a3; float wda, wdb; + h6_get(ca, qt, t, a0, a2, wda); h6_get(cb, qt, t, a1, a3, wdb); + blk(4 * hf + qt - qa, a0, a1, a2, a3, wda, 0.f, wdb, 0.f); + } + } + } else if (live) { + for (int q = qa; q < q1; q++) { + const u32 a0 = la, a1 = lb, a2 = ha, a3 = hb; + const float wda = da, wma = ma, wdb = db, wmb = mb; + if (q + 1 < nq) dec(q + 1); + blk(q - qa, a0, a1, a2, a3, wda, wma, wdb, wmb); + } + } + cp_async_wait<0>(); __syncthreads(); + if (wi + 1 < nws) pack(wi + 1); + } + if (ks > 1) { + float* mine = scr + (size_t)seg * nd * rows; + const volatile float* all = scr; // other blocks' stores: not cached + if (live) { + #pragma unroll + for (int j = 0; j < 32; j++) { + int r = r0 + g + 8 * ((j >> 1) & 1), p = (j >> 2) * 8 + 2 * t + (j & 1); + if (r < rows && p < np) mine[(size_t)p * rows + r] = acc[j >> 2][j & 3]; + } + } + __threadfence(); // every thread's sums are in memory before the count says so + __syncthreads(); + int* last = (int*)gemmd_s; + if (tid == 0) { + *last = atomicAdd(flag + rb, 1) == ks - 1; + if (*last) flag[rb] = 0; // every block of these rows has counted: the next launch starts from 0 + } + __syncthreads(); + if (!*last) return; + if (live && ks == 2) { // a + b is b + a: the other block's sums onto this one's + #pragma unroll + for (int j = 0; j < 32; j++) { + int r = r0 + g + 8 * ((j >> 1) & 1), p = (j >> 2) * 8 + 2 * t + (j & 1); + if (r < rows && p < np) acc[j >> 2][j & 3] += all[((size_t)(seg ^ 1) * nd + p) * rows + r]; + } + } else if (live) { + // Every segment from scr in segment order, whichever block ends last: the result does not depend on it. + for (int j = 0; j < 32; j++) { + int r = r0 + g + 8 * ((j >> 1) & 1), p = (j >> 2) * 8 + 2 * t + (j & 1); + if (r >= rows || p >= np) continue; + const volatile float* q = all + (size_t)p * rows + r; + float s = q[0]; + for (int sg = 1; sg < ks; sg++) s += q[(size_t)sg * nd * rows]; + float* yp = y + (size_t)p * y_stride + r; + float v = s * sc; + *yp = act == 0 ? v : act == 1 ? silu(*yp) * v : *yp + v; + } + return; + } + } + if (live) { + #pragma unroll + for (int pt = 0; pt < 8; pt++) + #pragma unroll + for (int i = 0; i < 4; i++) { + int r = r0 + g + 8 * (i >> 1), p = pt * 8 + 2 * t + (i & 1); + if (r >= rows || p >= np) continue; + float* yp = y + (size_t)p * y_stride + r; + float v = acc[pt][i] * sc; + *yp = act == 0 ? v : act == 1 ? silu(*yp) * v : *yp + v; + } + } +} +#define DEF_GEMMD(T, NAME, SBB) \ + extern "C" __global__ void __launch_bounds__(256, 2) gemmd_##NAME(const u8* w, const u8* x, int nd, int pb, \ + int ks, float* scr, int* flag, float* y, int y_stride, int rows, int cols, int act, float sc) { \ + if (nd == 64) gemmd_qx(w, x, nd, pb, ks, scr, flag, y, y_stride, rows, cols, act, sc); \ + else if (pb >= 32) gemmd_qx(w, x, nd, pb, ks, scr, flag, y, y_stride, rows, cols, act, sc); \ + else gemmd_qx(w, x, nd, pb, ks, scr, flag, y, y_stride, rows, cols, act, sc); \ + } +ITYPES(DEF_GEMMD) +#endif + +// ---- elementwise / norm ---- + +// grid = rows. out[r] = rmsnorm(x[r]) * w (same w for every row). xq (optional): out also quantized as quant_xq does. +// Row r takes gamma row r % wr of w (wr > 1: hyper-connection streams, one gamma per stream). +extern "C" __global__ void rms_norm(float* x, int x_stride, const float* w, float* out, int out_stride, int n, float eps, + signed char* xq, const float* res, int wr) { + w += (size_t)(blockIdx.x % wr) * n; + float* xr = x + (size_t)blockIdx.x * x_stride; + float* o = out + (size_t)blockIdx.x * out_stride; float s = 0.0f; - for (int i = threadIdx.x; i < n; i += blockDim.x) s += xr[i] * xr[i]; - float sc = 1.0f / fmaxf(sqrtf(block_sum(s)), eps); - for (int i = threadIdx.x; i < n; i += blockDim.x) xr[i] *= sc; + // The sum keeps the order of a 256-thread block (bit-identical results); all threads scale. Four loads in flight + // per step; the output values are all loaded before any store, as out may alias x. With res, x += res first. + if (threadIdx.x < 256 && res) { + const float* rr = res + (size_t)blockIdx.x * x_stride; + int i = threadIdx.x; + for (; i + 768 < n; i += 1024) { + float a = xr[i] + rr[i], b = xr[i + 256] + rr[i + 256], c = xr[i + 512] + rr[i + 512], d = xr[i + 768] + rr[i + 768]; + xr[i] = a; xr[i + 256] = b; xr[i + 512] = c; xr[i + 768] = d; + s += a * a; s += b * b; s += c * c; s += d * d; + } + for (; i < n; i += 256) { float a = xr[i] + rr[i]; xr[i] = a; s += a * a; } + } else if (threadIdx.x < 256) { + int i = threadIdx.x; + for (; i + 768 < n; i += 1024) { + float a = xr[i], b = xr[i + 256], c = xr[i + 512], d = xr[i + 768]; + s += a * a; s += b * b; s += c * c; s += d * d; + } + for (; i < n; i += 256) s += xr[i] * xr[i]; + } + float sc = 1.0f / sqrtf(block_sum(s) / (float)n + eps); + if (xq) { // each thread scales, stores and quantizes its own 8 values, as quant_x would map them + signed char* q = xq + (size_t)blockIdx.x * n; + float* qd = (float*)(xq + (size_t)gridDim.x * n) + blockIdx.x * (n / 32); + for (int i0 = 0; i0 < n; i0 += blockDim.x * 8) { + int i = i0 + threadIdx.x * 8; + unsigned m = __ballot_sync(0xffffffff, i < n); + if (i >= n) continue; + float4 a = *(const float4*)(xr + i), c = *(const float4*)(xr + i + 4); + float4 wa = *(const float4*)(w + i), wc = *(const float4*)(w + i + 4); + a = make_float4(a.x * sc * wa.x, a.y * sc * wa.y, a.z * sc * wa.z, a.w * sc * wa.w); + c = make_float4(c.x * sc * wc.x, c.y * sc * wc.y, c.z * sc * wc.z, c.w * sc * wc.w); + *(float4*)(o + i) = a; *(float4*)(o + i + 4) = c; + quant8(a, c, i, q, qd, m); + } + return; + } + int i = threadIdx.x, bd = blockDim.x; + for (; i + 3 * bd < n; i += 4 * bd) { + float a = xr[i] * sc * w[i], b = xr[i + bd] * sc * w[i + bd], c = xr[i + 2 * bd] * sc * w[i + 2 * bd], d = xr[i + 3 * bd] * sc * w[i + 3 * bd]; + o[i] = a; o[i + bd] = b; o[i + 2 * bd] = c; o[i + 3 * bd] = d; + } + for (; i < n; i += bd) o[i] = xr[i] * sc * w[i]; +} + +// Block-wide (largest b, first bi on ties) of the threads' (b, bi), in thread 0; bi == n marks no value yet. +__device__ void amax_reduce(float& b, int& bi, int n) { + for (int o = 16; o > 0; o >>= 1) { + float v = __shfl_xor_sync(0xffffffff, b, o); int vi = __shfl_xor_sync(0xffffffff, bi, o); + if (v > b || (v == b && vi < bi)) { b = v; bi = vi; } + } + __shared__ float sv[32]; __shared__ int si[32]; + int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + if (lane == 0) { sv[w] = b; si[w] = bi; } + __syncthreads(); + if (w == 0) { + b = lane < (blockDim.x >> 5) ? sv[lane] : __int_as_float(0xff800000); bi = lane < (blockDim.x >> 5) ? si[lane] : n; + for (int o = 16; o > 0; o >>= 1) { + float v = __shfl_xor_sync(0xffffffff, b, o); int vi = __shfl_xor_sync(0xffffffff, bi, o); + if (v > b || (v == b && vi < bi)) { b = v; bi = vi; } + } + } +} + +// grid = (parts, rows). part[r * parts + p] = (largest x, its index) of row r over i = p * blockDim + t + k * parts * blockDim. +extern "C" __global__ void argmax_part(const float* x, int n, int2* part) { + const float* xr = x + (size_t)blockIdx.y * n; + float b = __int_as_float(0xff800000); int bi = n; + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) if (xr[i] > b || bi == n) { b = xr[i]; bi = i; } + amax_reduce(b, bi, n); + if (threadIdx.x == 0) part[blockIdx.y * gridDim.x + blockIdx.x] = make_int2(__float_as_int(b), bi); +} + +// grid = rows, block = parts. out[r] = index of the largest x in row r (first one on ties, like ops::argmax). +extern "C" __global__ void argmax_rows(const int2* part, int n, int* out) { + int2 p = part[blockIdx.x * blockDim.x + threadIdx.x]; + float b = __int_as_float(p.x); int bi = p.y; + amax_reduce(b, bi, n); + if (threadIdx.x == 0) out[blockIdx.x] = bi; +} + +// grid = rows, in place. Row r is vector r % per of token r / per (tokens `stride` floats apart). +extern "C" __global__ void l2_norm(float* x, int n, int per, int stride, float eps) { + float* xr = x + (size_t)(blockIdx.x / per) * stride + (size_t)(blockIdx.x % per) * n; + float s = 0.0f; + for (int i = threadIdx.x; i < n; i += blockDim.x) s += xr[i] * xr[i]; + float sc = 1.0f / fmaxf(sqrtf(block_sum(s)), eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) xr[i] *= sc; +} + +// Per-token values live in device memory so a captured graph can replay: step[0] = position, step[1] = CPU worker seq. + +// grid = tokens (each rotates its per heads), block = n_rot / 2. NEOX pairs (i, i + n_rot/2), only lo <= i < hi (M-RoPE +// rotates each section of pairs by its own position). Token t sits at position step[0] + t. +extern "C" __global__ void rope_neox(float* x, int stride, int per, int n_rot, const int* step, float base, int lo, int hi) { + int pos = step[0] + blockIdx.x; + int i = threadIdx.x, half = n_rot / 2; + if (i < lo || i >= hi) return; + double theta = (double)pos * pow((double)base, -2.0 * i / n_rot); // f64 is slow: once per token, not per head + float s = (float)sin(theta), c = (float)cos(theta); + for (int hd = 0; hd < per; hd++) { + float* h = x + (size_t)(blockIdx.x * per + hd) * stride; + float a = h[i], b = h[i + half]; + h[i] = a * c - b * s; + h[i + half] = a * s + b * c; + } +} + +extern "C" __global__ void add(float* x, const float* y, int n) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] += y[i]; +} + +extern "C" __global__ void swiglu(float* g, const float* u, int n) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) g[i] = silu(g[i]) * u[i]; +} + +// g = silu(min(g, lim)) * clamp(u, -lim, lim) (ggml swiglu with limit). +extern "C" __global__ void swiglu_clamp(float* g, const float* u, int n, float lim) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) g[i] = silu(fminf(g[i], lim)) * fminf(fmaxf(u[i], -lim), lim); +} + +// DeepSeek-V4.1 query/output rows for `mla_attn`: row r of x (hd floats, xs apart) times `scale` into row r of y +// (ow floats, ys apart), its last n_rot dims rotated in adjacent pairs by cs (cos, sin of each pair; `inverse` +// de-ropes), dims hd..ow zero but dim sink + r % nh, which is 1 (sink 0: no sink dims). +extern "C" __global__ void ds_rope(const float* x, int xs, float* y, int ys, int rows, int nh, int hd, int ow, int n_rot, + const float* cs, int inverse, float scale, int sink) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * ow || n_rot < 0 || n_rot > hd) return; // no negative offsets + int r = i / ow, j = i % ow, off = hd - n_rot; + const float* xr = x + (size_t)r * xs; + float v; + if (j >= hd) v = (sink > 0 && j == sink + r % nh) ? 1.f : 0.f; + else if (j < off) v = xr[j] * scale; + else { + int p = (j - off) / 2; + float c = cs[2 * p], s = inverse ? -cs[2 * p + 1] : cs[2 * p + 1], a = xr[off + 2 * p], b = xr[off + 2 * p + 1]; + v = ((j - off) % 2 == 0 ? a * c - b * s : a * s + b * c) * scale; + } + y[(size_t)r * ys + j] = v; +} + +// Inkling's SITU on rows of 2n floats, n gates then n ups: gate = beta*tanh(gate/beta) * sigmoid(gate) * lb*tanh(up/lb) +// (lb not above 0: times the up as it is). Gate and up are first multiplied by sc[row] (sc null: by 1). +extern "C" __global__ void situ(float* y, int n, int rows, const float* sc, float beta, float lb) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * rows) return; + float* g = y + (size_t)(i / n) * 2 * n + i % n; + float s = sc ? sc[i / n] : 1.f, gv = *g * s, u = g[n] * s; + if (lb > 0.f) u = lb * tanhf(u / lb); + *g = beta * tanhf(gv / beta) / (1.f + expf(-gv)) * u; +} + +extern "C" __global__ void situ_q(const float* y, int n, const float* sc, float beta, float lb, signed char* out) { + size_t row = blockIdx.y; + int c = blockIdx.x * 256, i = threadIdx.x * 8; + bool valid = c + i < n; + float s = sc ? sc[row] : 1.f; + auto act = [=](float gg, float uu) -> float { + gg *= s; uu *= s; + if (lb > 0.f) uu = lb * tanhf(uu / lb); + return beta * tanhf(gg / beta) / (1.f + expf(-gg)) * uu; + }; + float4 ga = make_float4(0.f, 0.f, 0.f, 0.f), gc = make_float4(0.f, 0.f, 0.f, 0.f); + if (valid) { + const float* g = y + row * 2 * n + c + i; + const float* u = g + n; + ga = *(const float4*)g; gc = *(const float4*)(g + 4); + float4 ua = *(const float4*)u, uc = *(const float4*)(u + 4); + ga = make_float4(act(ga.x, ua.x), act(ga.y, ua.y), act(ga.z, ua.z), act(ga.w, ua.w)); + gc = make_float4(act(gc.x, uc.x), act(gc.y, uc.y), act(gc.z, uc.z), act(gc.w, uc.w)); + } + size_t o = row * n + c; + signed char* qs = out + o; + float* xd = (float*)(out + (size_t)gridDim.y * n) + o / 32; +#if LLAMA_Q8 + float d, id; + { + float vv[8] = {ga.x, ga.y, ga.z, ga.w, gc.x, gc.y, gc.z, gc.w}; + float mx = 0.f, sv = 0.f; int si = 1 << 30; + for (int j = 0; j < 8; j++) mx = fmaxf(mx, fabsf(vv[j])); + if (valid) for (int j = 0; j < 8; j++) if (fabsf(vv[j]) == mx && si > i + j) { sv = vv[j]; si = i + j; } + q8k_scale<32>(sv, si, d, id); + } + if (valid) { + int2 q = make_int2(pack4(__float2int_rn(ga.x * id), __float2int_rn(ga.y * id), __float2int_rn(ga.z * id), __float2int_rn(ga.w * id)), + pack4(__float2int_rn(gc.x * id), __float2int_rn(gc.y * id), __float2int_rn(gc.z * id), __float2int_rn(gc.w * id))); + *(int2*)(qs + i) = q; + if ((threadIdx.x & 3) == 0) xd[i >> 5] = d; + } +#else + unsigned m = c + 256 > n ? __ballot_sync(0xffffffff, valid) : 0xffffffff; + if (valid) quant8(ga, gc, i, qs, xd, m); +#endif +} + +extern "C" __global__ void softcap(float* x, int n, float cap) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] = cap * tanhf(x[i] / cap); +} + +// ---- Inkling 2's decode token on the device (inkling2::device); the host math is in src/inkling2/forward.rs ---- + +// Max over the whole block; every thread gets the result. blockDim.x must be a multiple of 32. +__device__ float block_max(float v) { + __shared__ float s[32]; + int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; + v = warp_max(v); + __syncthreads(); + if (lane == 0) s[w] = v; + __syncthreads(); + return warp_max(lane < nw ? s[lane] : -3.0e38f); +} + +// Depth mix, one block of 256 per (query row, token): softmax-weighted sum of the RMS-normed states (the nb blocks +// of shape [nb][nt][n], then cur [nt][n]; at most 5), scored by state . query / sqrt(n). +extern "C" __global__ void ink_mix(const float* blocks, int nb, const float* cur, const float* q, float* out, int n, int nt) { + int qid = blockIdx.x, tok = blockIdx.y; + const float* qr = q + (size_t)qid * n; + float sc[5], lg[5], mx = -3.0e38f, z = 0.f; + for (int s = 0; s <= nb; s++) { + const float* x = s < nb ? blocks + ((size_t)s * nt + tok) * n : cur + (size_t)tok * n; + float ss = 0.f, d = 0.f; + for (int i = threadIdx.x; i < n; i += 256) { ss += x[i] * x[i]; d += x[i] * qr[i]; } + sc[s] = 1.f / sqrtf(block_sum(ss) / (float)n + 1e-6f); + lg[s] = block_sum(d) * sc[s] / sqrtf((float)n); + mx = fmaxf(mx, lg[s]); + } + for (int s = 0; s <= nb; s++) { lg[s] = expf(lg[s] - mx); z += lg[s]; } + size_t oo = ((size_t)qid * nt + tok) * n; + for (int i = threadIdx.x; i < n; i += 256) { + float o = 0.f; + for (int s = 0; s <= nb; s++) { + float v = s < nb ? blocks[((size_t)s * nt + tok) * n + i] : cur[(size_t)tok * n + i]; + o += lg[s] / z * sc[s] * v; + } + out[oo + i] = o; + } +} + +// Loop controllers, the gates across nt tokens: block (r, j, tok). cur [min(nins, count)][nt][n], msg [count][nt][n]. +extern "C" __global__ void ink_ctrl_gate(const u16* down, const float* cur, int nins, const float* msg, float* gate, + int n, int rank, int nt) { + int r = blockIdx.x, j = blockIdx.y, tok = blockIdx.z, count = gridDim.y; + const u16* w = down + ((size_t)j * rank + r) * 2 * n; + const float* c = cur + ((size_t)min(j, nins - 1) * nt + tok) * n; + const float* m = msg + ((size_t)j * nt + tok) * n; + float a = 0.f, b = 0.f, sa = 0.f, sb = 0.f; + for (int i = threadIdx.x; i < n; i += 256) { + a += h2f(w[i]) * c[i]; b += h2f(w[n + i]) * m[i]; + sa += c[i] * c[i]; sb += m[i] * m[i]; + } + a = block_sum(a); b = block_sum(b); sa = block_sum(sa); sb = block_sum(sb); + if (threadIdx.x == 0) + gate[((size_t)tok * count + j) * rank + r] = a / sqrtf(sa / (float)n + 1e-6f) + b / sqrtf(sb / (float)n + 1e-6f); +} + +// Loop controllers, the update across nt tokens: block (x, j, tok). +extern "C" __global__ void ink_ctrl_out(const u16* gain, const u16* forget, const float* gate, const float* cur, int nins, + const float* msg, float* out, int n, int rank, int nt) { + int c = blockIdx.x * blockDim.x + threadIdx.x, j = blockIdx.y, tok = blockIdx.z, count = gridDim.y; + if (c >= n) return; + const u16* gw = gain + (size_t)j * rank * n + c; + const u16* fw = forget + (size_t)j * rank * n + c; + float g = 0.f, f = 0.f; + for (int r = 0; r < rank; r++) { + float t = gate[((size_t)tok * count + j) * rank + r]; + g += t * h2f(gw[(size_t)r * n]); f += t * h2f(fw[(size_t)r * n]); + } + size_t co = ((size_t)min(j, nins - 1) * nt + tok) * n + c; + size_t mo = ((size_t)j * nt + tok) * n + c; + float x = cur[co]; + f = fminf(fmaxf(f, -10.f), 10.f); + g = fminf(fmaxf(g, -10.f), 10.f); + out[mo] = x - tanhf(f) * x + tanhf(g) * msg[mo]; +} + +// The same two controllers for a prompt chunk, tiled over tokens: a block holds 64 tokens of one controller and all +// `rank` rows (a 64 x 64 output tile), so a weight row is read once per 64 tokens where the per-token kernels above +// read it once per token (32x the traffic of the tile, and a block reduction per output). 16 x 16 threads, 4 x 4 +// outputs each; both read and write the layout of the per-token pair, so nothing outside these four kernels changes. +extern "C" __global__ void __launch_bounds__(256) ink_ctrl_gate_b(const u16* down, const float* cur, int nins, + const float* msg, float* gate, int n, int rank, int nt) { + constexpr int BT = 64; + __shared__ __align__(16) float xs[BT][65]; + __shared__ __align__(16) u16 ws[BT][65]; + __shared__ float sc[BT][2]; + const int j = blockIdx.x, t0 = blockIdx.y * BT, tw = 2 * n, count = gridDim.x; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const float* ccur = cur + (size_t)min(j, nins - 1) * nt * n; + const float* cmsg = msg + (size_t)j * nt * n; + // The RMS of both inputs of each token, one warp a token: the per-token kernel folds this into its one dot. + for (int tt = warp; tt < BT; tt += 8) { + const int t = t0 + tt; + float sa = 0.f, sb = 0.f; + if (t < nt) { + const float* c = ccur + (size_t)t * n; + const float* m = cmsg + (size_t)t * n; + for (int i = lane; i < n; i += 32) { sa += c[i] * c[i]; sb += m[i] * m[i]; } + } + sa = warp_sum(sa); sb = warp_sum(sb); + if (lane == 0) { sc[tt][0] = rsqrtf(sa / (float)n + 1e-6f); sc[tt][1] = rsqrtf(sb / (float)n + 1e-6f); } + } + __syncthreads(); + const int ty = tid >> 4, tx = tid & 15; + float acc[4][4]; + for (int i = 0; i < 4; i++) for (int r = 0; r < 4; r++) acc[i][r] = 0.f; + for (int k0 = 0; k0 < tw; k0 += 64) { + for (int i = tid; i < BT * 64; i += 256) { + const int tt = i >> 6, kk = i & 63, t = t0 + tt, k = k0 + kk; + float v = 0.f; + if (t < nt) { + const float* c = ccur + (size_t)t * n; + const float* m = cmsg + (size_t)t * n; + v = k < n ? c[k] * sc[tt][0] : m[k - n] * sc[tt][1]; + } + xs[tt][kk] = v; + } + for (int i = tid; i < 64 * 64; i += 256) { + const int r = i >> 6, kk = i & 63; + ws[r][kk] = r < rank && k0 + kk < tw ? down[((size_t)j * rank + r) * tw + k0 + kk] : (u16)0; + } + __syncthreads(); + for (int k = 0; k < 64; k++) { + float xv[4], wv[4]; +#pragma unroll + for (int i = 0; i < 4; i++) xv[i] = xs[ty * 4 + i][k]; +#pragma unroll + for (int r = 0; r < 4; r++) wv[r] = h2f(ws[tx * 4 + r][k]); +#pragma unroll + for (int i = 0; i < 4; i++) { +#pragma unroll + for (int r = 0; r < 4; r++) acc[i][r] = fmaf(xv[i], wv[r], acc[i][r]); + } + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < 4; i++) { + const int t = t0 + ty * 4 + i; + if (t >= nt) break; +#pragma unroll + for (int r = 0; r < 4; r++) { + if (tx * 4 + r < rank) gate[((size_t)t * count + j) * rank + tx * 4 + r] = acc[i][r]; + } + } +} + +extern "C" __global__ void __launch_bounds__(256) ink_ctrl_out_b(const u16* gain, const u16* forget, const float* gate, + const float* cur, int nins, const float* msg, float* out, + int n, int rank, int nt) { + constexpr int BT = 64; + __shared__ __align__(16) float gs[BT][65]; + __shared__ __align__(16) u16 ws[2][BT][65]; + const int j = blockIdx.x, c0 = blockIdx.y * BT, t0 = blockIdx.z * BT, count = gridDim.x; + const int tid = threadIdx.x; + for (int i = tid; i < BT * 64; i += 256) { + const int tt = i >> 6, r = i & 63, t = t0 + tt; + gs[tt][r] = t < nt && r < rank ? gate[((size_t)t * count + j) * rank + r] : 0.f; + } + for (int i = tid; i < BT * 64; i += 256) { + const int r = i >> 6, cc = i & 63, c = c0 + cc; + const bool in = r < rank && c < n; + const size_t at = ((size_t)j * rank + r) * n + c; + ws[0][r][cc] = in ? gain[at] : (u16)0; + ws[1][r][cc] = in ? forget[at] : (u16)0; + } + __syncthreads(); + const int ty = tid >> 4, tx = tid & 15; + float ag[4][4], af[4][4]; + for (int i = 0; i < 4; i++) for (int cc = 0; cc < 4; cc++) { ag[i][cc] = 0.f; af[i][cc] = 0.f; } + for (int r = 0; r < rank; r++) { + float gv[4], wg[4], wf[4]; +#pragma unroll + for (int i = 0; i < 4; i++) gv[i] = gs[ty * 4 + i][r]; +#pragma unroll + for (int cc = 0; cc < 4; cc++) { wg[cc] = h2f(ws[0][r][tx * 4 + cc]); wf[cc] = h2f(ws[1][r][tx * 4 + cc]); } +#pragma unroll + for (int i = 0; i < 4; i++) { +#pragma unroll + for (int cc = 0; cc < 4; cc++) { ag[i][cc] = fmaf(gv[i], wg[cc], ag[i][cc]); af[i][cc] = fmaf(gv[i], wf[cc], af[i][cc]); } + } + } + for (int i = 0; i < 4; i++) { + const int t = t0 + ty * 4 + i; + if (t >= nt) break; + const int c = c0 + tx * 4; + if (c >= n) continue; + float* o = out + ((size_t)j * nt + t) * n + c; + const float* x = cur + ((size_t)min(j, nins - 1) * nt + t) * n + c; + const float* m = msg + ((size_t)j * nt + t) * n + c; + const int cnt = min(4, n - c); + for (int cc = 0; cc < cnt; cc++) { + const float f = fminf(fmaxf(af[i][cc], -10.f), 10.f), g = fminf(fmaxf(ag[i][cc], -10.f), 10.f); + o[cc] = x[cc] - tanhf(f) * x[cc] + tanhf(g) * m[cc]; + } + } +} + +// Short causal convolution with a residual (nc at most 8; out may be cur): hist holds the last nc - 1 inputs, the +// oldest first, and is advanced by cur. taps ([c / per][lag], lag 0 the current input) may be null. +extern "C" __global__ void ink_conv(const float* cur, const float* w, const float* taps, float* hist, float* out, int n, int nc, int per) { + int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= n) return; + float x[8], o = 0.f; + for (int k = 0; k + 1 < nc; k++) x[k] = hist[(size_t)k * n + c]; + x[nc - 1] = cur[c]; + for (int k = 0; k < nc; k++) o += x[k] * w[c * nc + k]; + if (taps) for (int lag = 0; lag < nc; lag++) o += x[nc - 1 - lag] * taps[c / per * nc + lag]; + out[c] = (x[nc - 1] + o) / sqrtf((float)((taps ? 2 * nc : nc) + 1)); + for (int k = 0; k + 1 < nc; k++) hist[(size_t)k * n + c] = x[k + 1]; +} + +// Batched causal short convolution for Inkling 2 prefill (o != cur). +// mode 0 (grid [ceil(n/256), nt]): writes o[tok, c]; mode 1 (grid [ceil(n/256), 1]): advances hist. +extern "C" __global__ void ink_conv_batch(const float* cur, const float* w, const float* taps, float* hist, float* o, + int n, int nc, int per, int nt, int mode) { + int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= n) return; + if (mode != 0) { + float old[8]; + for (int k = 0; k + 1 < nc; k++) old[k] = hist[(size_t)k * n + c]; + for (int k = 0; k + 1 < nc; k++) { + int src = nt - (nc - 1) + k; + hist[(size_t)k * n + c] = src >= 0 ? cur[(size_t)src * n + c] : old[(nc - 1) + src]; + } + return; + } + int tok = blockIdx.y; + float x[8], acc = 0.f; + for (int k = 0; k < nc; k++) { + int s = tok - (nc - 1) + k; + float xv = s < 0 ? hist[(size_t)((nc - 1) + s) * n + c] : cur[(size_t)s * n + c]; + x[k] = xv; + acc += xv * w[c * nc + k]; + } + if (taps) { + int nheads = n / per; + size_t tp_base = ((size_t)tok * nheads + c / per) * nc; + for (int lag = 0; lag < nc; lag++) acc += x[nc - 1 - lag] * taps[tp_base + lag]; + } + o[(size_t)tok * n + c] = (x[nc - 1] + acc) / sqrtf((float)((taps ? 2 * nc : nc) + 1)); +} + +// acc[tok] = (cpu ? cpu[tok] : 0) + sum_{e < ne} wts[tok, e] * d[(tok * ne + e) * n + c]. blockIdx.y = tok. +extern "C" __global__ void ink_ffn_sum(float* acc, const float* d, const float* wts, int ne, int n, const float* cpu) { + int c = blockIdx.x * blockDim.x + threadIdx.x, tok = blockIdx.y; + if (c >= n) return; + float o = cpu ? cpu[(size_t)tok * n + c] : 0.f; + size_t db = (size_t)tok * ne * n + c, wb = (size_t)tok * ne; + for (int e = 0; e < ne; e++) o += wts[wb + e] * d[db + (size_t)e * n]; + acc[(size_t)tok * n + c] = o; +} + +// Absorbed MLA attention (GigaChat 4): one latent K/V row of hd f16 a position, read by every head; V is its first +// vd values. Block = (query t, blockDim.x / 32 heads, key split z), one warp a head. A tile of 32 rows sits in shared memory as +// words of two f16 with rows of hd / 2 + 1 words (an odd stride, so the 32 lanes that each read one row hit 32 +// banks) and serves as K and as V. Query t sees cnt[t] keys: positions idx[t * ns + j], or j when idx is null; split z +// of nsp takes a run of them. q is pre-scaled f32 [t][head][hd]. With nsp 1, out f32 [t][head][vd] gets the result; +// else part [t][head][z] gets (max, sum, unnormalized V sum) for `mla_combine`. Lane c keeps V values 2c, 2c + 1 of +// each 64. Needs hd % 2 == 0, vd % 64 == 0, vd <= 512, nh a multiple of the heads a block. +extern "C" __global__ void mla_attn(const float* q, const u16* kc, const unsigned* idx, const int* cnt, float* out, + float* part, int nh, int hd, int vd, int ns, int nsp) { + extern __shared__ float sm[]; + int nw = blockDim.x >> 5, t = blockIdx.x, h0 = blockIdx.y * nw, z = blockIdx.z, w = threadIdx.x >> 5, c = threadIdx.x & 31, n = cnt[t]; + int hw = hd / 2, st = hw + 1, nv = vd / 64; + float* qs = sm; + unsigned* kt = (unsigned*)(qs + nw * hd); + for (int i = threadIdx.x; i < nw * hd; i += blockDim.x) qs[i] = q[((size_t)t * nh + h0) * hd + i]; + const unsigned* sel = idx ? idx + (size_t)t * ns : nullptr; + int per = ((n + nsp - 1) / nsp + 31) & ~31, jb = z * per, je = min(n, jb + per); + float2 acc[8]; + for (int k = 0; k < 8; k++) acc[k] = make_float2(0.0f, 0.0f); + float m = __int_as_float(0xff800000), l = 0.0f; + for (int j0 = jb; j0 < je; j0 += 32) { + __syncthreads(); + for (int r = w; r < 32; r += nw) { + int j = j0 + r; + const unsigned* src = j < je ? (const unsigned*)(kc + (size_t)(sel ? sel[j] : j) * hd) : nullptr; + for (int i = c; i < hw; i += 32) kt[r * st + i] = src ? src[i] : 0u; + } + __syncthreads(); + float s = __int_as_float(0xff800000); + if (j0 + c < je) { + const float2* qh = (const float2*)(qs + w * hd); + const unsigned* kr = kt + c * st; + float d0 = 0.0f, d1 = 0.0f; + for (int i = 0; i < hw; i++) { + float2 k = ink_h2f2(kr[i]), qq = qh[i]; + d0 = fmaf(qq.x, k.x, d0); + d1 = fmaf(qq.y, k.y, d1); + } + s = d0 + d1; + } + float mx = s; + for (int o = 16; o > 0; o >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, o)); + float mn = fmaxf(m, mx), a = expf(m - mn), p = j0 + c < je ? expf(s - mn) : 0.0f, ps = p; + for (int o = 16; o > 0; o >>= 1) ps += __shfl_xor_sync(0xffffffff, ps, o); + l = l * a + ps; + m = mn; + for (int k = 0; k < nv; k++) { acc[k].x *= a; acc[k].y *= a; } + int nj = min(32, je - j0); + for (int j = 0; j < nj; j++) { + float pj = __shfl_sync(0xffffffff, p, j); + const unsigned* vr = kt + j * st; + for (int k = 0; k < nv; k++) { + float2 v = ink_h2f2(vr[c + 32 * k]); + acc[k].x = fmaf(pj, v.x, acc[k].x); + acc[k].y = fmaf(pj, v.y, acc[k].y); + } + } + } + size_t th = (size_t)t * nh + h0 + w; + if (nsp == 1) { + float* o = out + th * vd; + for (int k = 0; k < nv; k++) { o[64 * k + 2 * c] = acc[k].x / l; o[64 * k + 2 * c + 1] = acc[k].y / l; } + return; + } + float* o = part + (th * nsp + z) * (vd + 2); + if (c == 0) { o[0] = m; o[1] = l; } + for (int k = 0; k < nv; k++) { o[2 + 64 * k + 2 * c] = acc[k].x; o[2 + 64 * k + 2 * c + 1] = acc[k].y; } +} + +// `mla_attn` for prompts on the tensor cores (mma m16n8k16, f16 in, f32 sums): block = (query t, 32 heads, key +// split z), 8 warps. Q (f16) and a tile of 32 key rows sit in shared memory with rows of hd + 8 halves; warp w takes +// heads 16 (w & 1) .. +16 and, for S = Q K^T, keys 8 (w >> 1) .. +8 of the tile, for O += P V, a quarter of vd. +// The online softmax goes through shared memory (S f32, P f16), warp w keeping max and sum of heads 4w .. 4w + 3. +// Same inputs and outputs as `mla_attn`, Q scaled by qsc; with qp the dims from vd on come from qp (rows qps apart, +// one a (query, head)) and q holds only the first vd dims (rows vd apart). Needs hd % 16 == 0, vd % 32 == 0, vd <= 512, nh % 32 == 0. +extern "C" __global__ void __launch_bounds__(256) mla_attn_tc(const float* q, const u16* kc, const unsigned* idx, const int* cnt, float* out, + float* part, int nh, int hd, int vd, int ns, int nsp, const float* qp, int qps, float qsc) { + extern __shared__ float sm[]; + const float ninf = __int_as_float(0xff800000); + int t = blockIdx.x, h0 = blockIdx.y * 32, z = blockIdx.z, w = threadIdx.x >> 5, l = threadIdx.x & 31, g = l >> 2, tq = l & 3, n = cnt[t]; + int hs = hd + 8, mt = w & 1, nq = vd / 32; + u16* qs = (u16*)sm; + u16* ks = qs + 32 * hs; + float* ss = (float*)(ks + 32 * hs); // [32][33] + u16* ps = (u16*)(ss + 32 * 33); // [32][40] + float* al = (float*)(ps + 32 * 40); // [32] rescale of the step, at the end the sums + float* mm = al + 32; // [32] the maxima at the end + for (int i = threadIdx.x; i < 32 * hd; i += 256) { + int r = i / hd, d = i % hd; + size_t th = (size_t)t * nh + h0 + r; + qs[r * hs + d] = f2h((qp ? (d >= vd ? qp[th * qps + d - vd] : q[th * vd + d]) : q[th * hd + d]) * qsc); + } + const unsigned* sel = idx ? idx + (size_t)t * ns : nullptr; + int per = ((n + nsp - 1) / nsp + 31) & ~31, jb = z * per, je = min(n, jb + per), hw = hd / 8; + float acc[16][4]; +#pragma unroll + for (int j = 0; j < 16; j++) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f; + float rm[4] = {ninf, ninf, ninf, ninf}, rl[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (int j0 = jb; j0 < je; j0 += 32) { + __syncthreads(); + for (int i = threadIdx.x; i < 32 * hw; i += 256) { + int r = i / hw, c = i % hw, j = j0 + r; + uint4 v = make_uint4(0u, 0u, 0u, 0u); + if (j < je) v = ((const uint4*)(kc + (size_t)(sel ? sel[j] : j) * hd))[c]; + *(uint4*)(ks + r * hs + 8 * c) = v; + } + __syncthreads(); + { + float c4[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + const u16* qa = qs + (mt * 16 + g) * hs + 2 * tq; + const u16* kb = ks + ((w >> 1) * 8 + g) * hs + 2 * tq; + for (int k0 = 0; k0 < hd; k0 += 16) + mma16816(c4, *(const u32*)(qa + k0), *(const u32*)(qa + 8 * hs + k0), *(const u32*)(qa + k0 + 8), *(const u32*)(qa + 8 * hs + k0 + 8), + *(const u32*)(kb + k0), *(const u32*)(kb + k0 + 8)); + int r0 = mt * 16 + g, cc = (w >> 1) * 8 + 2 * tq; + ss[r0 * 33 + cc] = c4[0]; ss[r0 * 33 + cc + 1] = c4[1]; ss[(r0 + 8) * 33 + cc] = c4[2]; ss[(r0 + 8) * 33 + cc + 1] = c4[3]; + } + __syncthreads(); + bool ok = j0 + l < je; +#pragma unroll + for (int i = 0; i < 4; i++) { + int r = 4 * w + i; + float s = ok ? ss[r * 33 + l] : ninf, mx = s; + for (int o = 16; o > 0; o >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, o)); + float mn = fmaxf(rm[i], mx), a = expf(rm[i] - mn), p = ok ? expf(s - mn) : 0.0f, sum = p; + for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffff, sum, o); + rl[i] = rl[i] * a + sum; + rm[i] = mn; + ps[r * 40 + l] = f2h(p); + if (l == 0) al[r] = a; + } + __syncthreads(); + float alo = al[mt * 16 + g], ahi = al[mt * 16 + g + 8]; +#pragma unroll + for (int j = 0; j < 16; j++) if (j < nq) { acc[j][0] *= alo; acc[j][1] *= alo; acc[j][2] *= ahi; acc[j][3] *= ahi; } + const u16* pa = ps + (mt * 16 + g) * 40 + 2 * tq; +#pragma unroll + for (int k0 = 0; k0 < 32; k0 += 16) { + u32 a0 = *(const u32*)(pa + k0), a1 = *(const u32*)(pa + 8 * 40 + k0), a2 = *(const u32*)(pa + k0 + 8), a3 = *(const u32*)(pa + 8 * 40 + k0 + 8); + const u16* v0 = ks + (k0 + 2 * tq) * hs + (w >> 1) * (vd / 4) + g; +#pragma unroll + for (int j = 0; j < 16; j++) if (j < nq) { + const u16* v = v0 + 8 * j; + mma16816(acc[j], a0, a1, a2, a3, (u32)v[0] | ((u32)v[hs] << 16), (u32)v[8 * hs] | ((u32)v[9 * hs] << 16)); + } + } + } + __syncthreads(); + if (l == 0) for (int i = 0; i < 4; i++) { mm[4 * w + i] = rm[i]; al[4 * w + i] = rl[i]; } + __syncthreads(); + int r0 = mt * 16 + g, cb = (w >> 1) * (vd / 4) + 2 * tq; + size_t lo = (size_t)t * nh + h0 + r0, hi = lo + 8; + if (nsp == 1) { + float il = 1.0f / al[r0], ih = 1.0f / al[r0 + 8]; +#pragma unroll + for (int j = 0; j < 16; j++) if (j < nq) { + int c = cb + 8 * j; + out[lo * vd + c] = acc[j][0] * il; out[lo * vd + c + 1] = acc[j][1] * il; + out[hi * vd + c] = acc[j][2] * ih; out[hi * vd + c + 1] = acc[j][3] * ih; + } + return; + } + float* plo = part + (lo * nsp + z) * (vd + 2) + 2; + float* phi = part + (hi * nsp + z) * (vd + 2) + 2; +#pragma unroll + for (int j = 0; j < 16; j++) if (j < nq) { + int c = cb + 8 * j; + plo[c] = acc[j][0]; plo[c + 1] = acc[j][1]; phi[c] = acc[j][2]; phi[c + 1] = acc[j][3]; + } + if (threadIdx.x < 32) { + float* o = part + (((size_t)t * nh + h0 + threadIdx.x) * nsp + z) * (vd + 2); + o[0] = mm[threadIdx.x]; o[1] = al[threadIdx.x]; + } +} + +#if STRATA_HIP +// `mla_attn_tc` on the WMMA matrix cores (gfx11/12, the HIP backend): same inputs and outputs, block = (query t, 32 +// heads, key split z), 8 waves, a tile of 32 keys in shared memory with rows of hd + 8 halves (48.6 KiB at hd 576, where +// `mla_attn_tc`'s Q tile would not fit a 64 KiB block). Wave w takes heads 16 (w & 1) .. +16 throughout; for S = Q K^T +// it holds its own f16 Q rows in registers for half of hd (w >> 2) and computes the 16 x 16 score tile of keys +// 16 ((w >> 1) & 1) .. +16, and the two halves are added in a fixed order in shared memory. The online softmax is +// `mla_attn_tc`'s (wave w keeps max and sum of heads 4w .. 4w + 3). For O += P V wave w takes the value dims +// (w >> 1) vd / 4 .. +vd / 4, 16 at a time, its results in AMD's layout (rows STRATA_WMMA_ROW). Needs nh % 32 == 0, +// hd % 32 == 0, hd <= 576, vd % 64 == 0, vd <= 512. +extern "C" __global__ void __launch_bounds__(256) mla_attn_wmma(const float* q, const u16* kc, const unsigned* idx, const int* cnt, float* out, + float* part, int nh, int hd, int vd, int ns, int nsp, const float* qp, int qps, float qsc) { +#if GEMM_WMMA + extern __shared__ float sm[]; + const float ninf = __int_as_float(0xff800000); + const int t = blockIdx.x, h0 = blockIdx.y * 32, z = blockIdx.z, w = threadIdx.x >> 5, l = threadIdx.x & 31, l16 = l & 15; + const int w0 = STRATA_WMMA_K0(l), n = cnt[t], hs = hd + 8, mt = w & 1, nt = (w >> 1) & 1, kh = w >> 2, dq = w >> 1; + const int nks = hd / 32, nq = vd / 64, half = hd / 2; + u16* ks = (u16*)sm; // [32][hs] keys of the tile + float* sp = (float*)(ks + 32 * hs); // [2][32][33] scores, one plane per half of hd + u16* ps = (u16*)(sp + 2 * 32 * 33); // [32][40] P in halves + float* al = (float*)(ps + 32 * 40); // [32] rescale of the step, at the end the sums + float* mm = al + 32; // [32] the maxima at the end + strata_hip::strata_hk qa[18]; + { + size_t th = (size_t)t * nh + h0 + mt * 16 + l16; +#pragma unroll + for (int s = 0; s < 18; s++) if (s < nks) +#pragma unroll + for (int e = 0; e < STRATA_WMMA_K; e++) { + int d = kh * half + 16 * s + w0 + e; + float v = qp ? (d >= vd ? qp[th * qps + d - vd] : q[th * vd + d]) : q[th * hd + d]; + qa[s][e] = (_Float16)(v * qsc); + } + } + const unsigned* sel = idx ? idx + (size_t)t * ns : nullptr; + const int per = ((n + nsp - 1) / nsp + 31) & ~31, jb = z * per, je = min(n, jb + per), hw = hd / 8; + strata_hip::strata_f8 acc[8]; +#pragma unroll + for (int j = 0; j < 8; j++) +#pragma unroll + for (int i = 0; i < 8; i++) acc[j][i] = 0.0f; + float rm[4] = {ninf, ninf, ninf, ninf}, rl[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (int j0 = jb; j0 < je; j0 += 32) { + __syncthreads(); + for (int i = threadIdx.x; i < 32 * hw; i += 256) { + int r = i / hw, c = i % hw, j = j0 + r; + uint4 v = make_uint4(0u, 0u, 0u, 0u); + if (j < je) v = ((const uint4*)(kc + (size_t)(sel ? sel[j] : j) * hd))[c]; + *(uint4*)(ks + r * hs + 8 * c) = v; + } + __syncthreads(); + { + strata_hip::strata_f8 c; +#pragma unroll + for (int i = 0; i < 8; i++) c[i] = 0.0f; + const u16* kb = ks + (nt * 16 + l16) * hs + kh * half + w0; +#pragma unroll + for (int s = 0; s < 18; s++) if (s < nks) c = strata_hip::strata_wmma(qa[s], strata_hip::strata_ld_wmma(kb + 16 * s), c); +#pragma unroll + for (int i = 0; i < 8; i++) sp[(kh * 32 + mt * 16 + STRATA_WMMA_ROW(l, i)) * 33 + nt * 16 + l16] = c[i]; + } + __syncthreads(); + bool ok = j0 + l < je; +#pragma unroll + for (int i = 0; i < 4; i++) { + int r = 4 * w + i; + float s = ok ? sp[r * 33 + l] + sp[(32 + r) * 33 + l] : ninf, mx = s; + for (int o = 16; o > 0; o >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, o)); + float mn = fmaxf(rm[i], mx), a = expf(rm[i] - mn), p = ok ? expf(s - mn) : 0.0f, sum = p; + for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffff, sum, o); + rl[i] = rl[i] * a + sum; + rm[i] = mn; + ps[r * 40 + l] = f2h(p); + if (l == 0) al[r] = a; + } + __syncthreads(); +#pragma unroll + for (int i = 0; i < 8; i++) { + float a = al[mt * 16 + STRATA_WMMA_ROW(l, i)]; +#pragma unroll + for (int j = 0; j < 8; j++) if (j < nq) acc[j][i] *= a; + } +#pragma unroll + for (int k0 = 0; k0 < 32; k0 += 16) { + strata_hip::strata_hk pa = strata_hip::strata_ld_wmma(ps + (mt * 16 + l16) * 40 + k0 + w0); + const u16* vb = ks + (k0 + w0) * hs + dq * (vd / 4) + l16; +#pragma unroll + for (int j = 0; j < 8; j++) if (j < nq) acc[j] = strata_hip::strata_wmma(pa, strata_hip::strata_ld_wmma_t(vb + 16 * j, hs), acc[j]); + } + } + __syncthreads(); + if (l == 0) for (int i = 0; i < 4; i++) { mm[4 * w + i] = rm[i]; al[4 * w + i] = rl[i]; } + __syncthreads(); +#pragma unroll + for (int i = 0; i < 8; i++) { + int r = mt * 16 + STRATA_WMMA_ROW(l, i); + size_t th = (size_t)t * nh + h0 + r; +#pragma unroll + for (int j = 0; j < 8; j++) if (j < nq) { + int d = dq * (vd / 4) + 16 * j + l16; + if (nsp == 1) out[th * vd + d] = acc[j][i] / al[r]; + else part[(th * nsp + z) * (vd + 2) + 2 + d] = acc[j][i]; + } + } + if (nsp > 1 && threadIdx.x < 32) { + float* o = part + (((size_t)t * nh + h0 + threadIdx.x) * nsp + z) * (vd + 2); + o[0] = mm[threadIdx.x]; o[1] = al[threadIdx.x]; + } +#endif } +#endif -// Per-token values live in device memory so a captured graph can replay: step[0] = position, step[1] = CPU worker seq. - -// grid = tokens (each rotates its per heads), block = n_rot / 2. NEOX pairs (i, i + n_rot/2), only lo <= i < hi (M-RoPE -// rotates each section of pairs by its own position). Token t sits at position step[0] + t. -extern "C" __global__ void rope_neox(float* x, int stride, int per, int n_rot, const int* step, float base, int lo, int hi) { - int pos = step[0] + blockIdx.x; - int i = threadIdx.x, half = n_rot / 2; - if (i < lo || i >= hi) return; - double theta = (double)pos * pow((double)base, -2.0 * i / n_rot); // f64 is slow: once per token, not per head - float s = (float)sin(theta), c = (float)cos(theta); - for (int hd = 0; hd < per; hd++) { - float* h = x + (size_t)(blockIdx.x * per + hd) * stride; - float a = h[i], b = h[i + half]; - h[i] = a * c - b * s; - h[i + half] = a * s + b * c; +// Lightning-indexer scores (GigaChat 4): out[t][j] = sum_h max(q[t][h] . k[j], 0) * w[t][h], head dim 128. Block = +// (64 keys, 64 queries), thread = 4 keys x 4 queries. The key tile stays in shared memory as [dim][key]; each head's +// queries come in 4 slices of 32 dims as [dim][query], so a thread reads its 4 keys and its 4 queries as one float4 +// each. Every score sums its dims in order with fmaf, then its heads in order: the same arithmetic as one thread a +// score. The queries are the last nt positions of the nk keys; a tile of keys after every query of the block is not +// written (the caller reads each query's scores only up to its own position). Rows of 68 in shared memory keep the +// transposing stores off one bank. +extern "C" __global__ void idx_score(const float* q, const float* w, const float* k, float* out, int nt, int nk, int nh) { + __shared__ __align__(16) float ks[128 * 68]; + __shared__ __align__(16) float qs[32 * 68]; + int j0 = blockIdx.x * 64, t0 = blockIdx.y * 64, tid = threadIdx.x, kx = (tid & 15) * 4, qy = (tid >> 4) * 4; + if (j0 > nk - nt + t0 + 63) return; + for (int i = tid; i < 64 * 128; i += 256) { + int r = i >> 7, d = i & 127; + ks[d * 68 + r] = j0 + r < nk ? k[(size_t)(j0 + r) * 128 + d] : 0.0f; + } + float s[4][4] = {}; + for (int h = 0; h < nh; h++) { + float d[4][4] = {}; + for (int c = 0; c < 128; c += 32) { + __syncthreads(); + for (int i = tid; i < 64 * 32; i += 256) { + int qt = i >> 5, dd = i & 31; + qs[dd * 68 + qt] = t0 + qt < nt ? q[((size_t)(t0 + qt) * nh + h) * 128 + c + dd] : 0.0f; + } + __syncthreads(); +#pragma unroll 8 + for (int i = 0; i < 32; i++) { + float4 kv = *(const float4*)(ks + (c + i) * 68 + kx); + float4 qv = *(const float4*)(qs + i * 68 + qy); + float kk[4] = {kv.x, kv.y, kv.z, kv.w}, qq[4] = {qv.x, qv.y, qv.z, qv.w}; +#pragma unroll + for (int a = 0; a < 4; a++) +#pragma unroll + for (int b = 0; b < 4; b++) d[a][b] = fmaf(qq[a], kk[b], d[a][b]); + } + } +#pragma unroll + for (int a = 0; a < 4; a++) { + float wv = t0 + qy + a < nt ? w[(size_t)(t0 + qy + a) * nh + h] : 0.0f; +#pragma unroll + for (int b = 0; b < 4; b++) s[a][b] = fmaf(fmaxf(d[a][b], 0.0f), wv, s[a][b]); + } } + for (int a = 0; a < 4; a++) if (t0 + qy + a < nt) + for (int b = 0; b < 4; b++) if (j0 + kx + b < nk) out[(size_t)(t0 + qy + a) * nk + j0 + kx + b] = s[a][b]; } -extern "C" __global__ void add(float* x, const float* y, int n) { - int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) x[i] += y[i]; +#if STRATA_HIP +// `idx_score` on the WMMA matrix cores (gfx11/12, the HIP backend): block = (64 keys, 64 queries), 8 waves. The key +// tile and one head's queries sit in shared memory as f16 rows of 136 halves, the head weights of the 64 queries as f32. +// Per head, wave w computes the 16 x 16 score tiles of queries 16 (w >> 1) .. +16 and keys 32 (w & 1) .. +32 over the +// 128 dims (f16 products, f32 sums) and adds max(score, 0) * weight to its sums, heads in order. The products are +// rounded to f16 where `idx_score` multiplies in f32, so near-equal scores can change order. Needs nh <= 64. +extern "C" __global__ void __launch_bounds__(256) idx_score_wmma(const float* q, const float* w, const float* k, float* out, int nt, int nk, int nh) { +#if GEMM_WMMA + __shared__ __align__(16) u16 ks[64 * 136]; + __shared__ __align__(16) u16 qs[64 * 136]; + __shared__ float ws[64 * 64]; + const int j0 = blockIdx.x * 64, t0 = blockIdx.y * 64, tid = threadIdx.x, wv = tid >> 5, l = tid & 31, l16 = l & 15; + const int w0 = STRATA_WMMA_K0(l), qt = wv >> 1, kt0 = 2 * (wv & 1); + if (j0 > nk - nt + t0 + 63) return; + for (int i = tid; i < 64 * 32; i += 256) { + int r = i >> 5, c = (i & 31) * 4; + float4 v = j0 + r < nk ? *(const float4*)(k + (size_t)(j0 + r) * 128 + c) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + *(u32*)(ks + r * 136 + c) = f2h(v.x) | (u32)f2h(v.y) << 16; + *(u32*)(ks + r * 136 + c + 2) = f2h(v.z) | (u32)f2h(v.w) << 16; + } + for (int i = tid; i < 64 * nh; i += 256) { + int r = i / nh, h = i % nh; + ws[r * 64 + h] = t0 + r < nt ? w[(size_t)(t0 + r) * nh + h] : 0.0f; + } + strata_hip::strata_f8 sum[2]; +#pragma unroll + for (int b = 0; b < 2; b++) +#pragma unroll + for (int i = 0; i < 8; i++) sum[b][i] = 0.0f; + for (int h = 0; h < nh; h++) { + __syncthreads(); + for (int i = tid; i < 64 * 32; i += 256) { + int r = i >> 5, c = (i & 31) * 4; + float4 v = t0 + r < nt ? *(const float4*)(q + ((size_t)(t0 + r) * nh + h) * 128 + c) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + *(u32*)(qs + r * 136 + c) = f2h(v.x) | (u32)f2h(v.y) << 16; + *(u32*)(qs + r * 136 + c + 2) = f2h(v.z) | (u32)f2h(v.w) << 16; + } + __syncthreads(); + strata_hip::strata_hk qa[8]; +#pragma unroll + for (int s = 0; s < 8; s++) qa[s] = strata_hip::strata_ld_wmma(qs + (qt * 16 + l16) * 136 + 16 * s + w0); +#pragma unroll + for (int b = 0; b < 2; b++) { + strata_hip::strata_f8 c; +#pragma unroll + for (int i = 0; i < 8; i++) c[i] = 0.0f; + const u16* kr = ks + ((kt0 + b) * 16 + l16) * 136 + w0; +#pragma unroll + for (int s = 0; s < 8; s++) c = strata_hip::strata_wmma(qa[s], strata_hip::strata_ld_wmma(kr + 16 * s), c); +#pragma unroll + for (int i = 0; i < 8; i++) sum[b][i] = fmaf(fmaxf(c[i], 0.0f), ws[(qt * 16 + STRATA_WMMA_ROW(l, i)) * 64 + h], sum[b][i]); + } + } +#pragma unroll + for (int b = 0; b < 2; b++) { + int j = j0 + (kt0 + b) * 16 + l16; +#pragma unroll + for (int i = 0; i < 8; i++) { + int t = t0 + qt * 16 + STRATA_WMMA_ROW(l, i); + if (t < nt && j < nk) out[(size_t)t * nk + j] = sum[b][i]; + } + } +#endif } +#endif -extern "C" __global__ void swiglu(float* g, const float* u, int n) { - int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) g[i] = silu(g[i]) * u[i]; +// `idx_score` for a few queries (decode): block = (32 keys, one query), warp w takes heads w*nh/8.. of the 32 keys +// (lane = key), up to 8 heads at once for ILP, then lane 0..31 sums its key's heads in order. Same fmaf order per key +// as `idx_score`, so the scores are bit-identical. nh a multiple of 8, at most 64. +extern "C" __global__ void idx_score_dec(const float* __restrict__ q, const float* __restrict__ w, const float* __restrict__ k, float* out, int nk, int nh) { + __shared__ float ks[32 * 129]; + __shared__ float ds[64 * 32]; + int j0 = blockIdx.x * 32, t = blockIdx.y, tid = threadIdx.x, lane = tid & 31, hpw = nh >> 3, h0 = (tid >> 5) * hpw; + for (int i = tid; i < 32 * 128; i += 256) { + int r = i >> 7, d = i & 127; + ks[r * 129 + d] = j0 + r < nk ? k[(size_t)(j0 + r) * 128 + d] : 0.0f; + } + __syncthreads(); + const float* qt = q + ((size_t)t * nh + h0) * 128; + const float* kr = ks + lane * 129; + float d[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + for (int i = 0; i < 128; i++) { + float kv = kr[i]; +#pragma unroll + for (int hh = 0; hh < 8; hh++) if (hh < hpw) d[hh] = fmaf(qt[hh * 128 + i], kv, d[hh]); + } +#pragma unroll + for (int hh = 0; hh < 8; hh++) if (hh < hpw) ds[(h0 + hh) * 32 + lane] = d[hh]; + __syncthreads(); + if (tid < 32 && j0 + tid < nk) { + float s = 0.0f; + for (int h = 0; h < nh; h++) s = fmaf(fmaxf(ds[h * 32 + tid], 0.0f), w[(size_t)t * nh + h], s); + out[(size_t)t * nk + j0 + tid] = s; + } } -// Inkling's SITU on rows of 2n floats, n gates then n ups: gate = beta*tanh(gate/beta) * sigmoid(gate) * lb*tanh(up/lb) -// (lb not above 0: times the up as it is). Gate and up are first multiplied by sc[row] (sc null: by 1). -extern "C" __global__ void situ(float* y, int n, int rows, const float* sc, float beta, float lb) { - int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n * rows) return; - float* g = y + (size_t)(i / n) * 2 * n + i % n; - float s = sc ? sc[i / n] : 1.f, gv = *g * s, u = g[n] * s; - if (lb > 0.f) u = lb * tanhf(u / lb); - *g = beta * tanhf(gv / beta) / (1.f + expf(-gv)) * u; +#if STRATA_HIP +// The query rows of `mla_attn` built from the inputs `mla_attn_tc` takes (the HIP backend, which has no +// `mla_attn_tc`): out f32 [nth][hd] = q scaled by qsc, with qp the dims from vd on taken from qp (rows qps apart, one a +// (query, head)) and q holding only the first vd dims (rows vd apart). One thread a value. +extern "C" __global__ void mla_qpack(const float* q, const float* qp, int qps, float qsc, float* out, int nth, int hd, int vd) { + size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= (size_t)nth * hd) return; + size_t th = i / hd; + int d = (int)(i % hd); + out[i] = (qp ? (d >= vd ? qp[th * qps + d - vd] : q[th * vd + d]) : q[i]) * qsc; } +#endif -extern "C" __global__ void situ_q(const float* y, int n, const float* sc, float beta, float lb, signed char* out) { - size_t row = blockIdx.y; - int c = blockIdx.x * 256, i = threadIdx.x * 8; - bool valid = c + i < n; - float s = sc ? sc[row] : 1.f; - auto act = [=](float gg, float uu) -> float { - gg *= s; uu *= s; - if (lb > 0.f) uu = lb * tanhf(uu / lb); - return beta * tanhf(gg / beta) / (1.f + expf(-gg)) * uu; - }; - float4 ga = make_float4(0.f, 0.f, 0.f, 0.f), gc = make_float4(0.f, 0.f, 0.f, 0.f); - if (valid) { - const float* g = y + row * 2 * n + c + i; - const float* u = g + n; - ga = *(const float4*)g; gc = *(const float4*)(g + 4); - float4 ua = *(const float4*)u, uc = *(const float4*)(u + 4); - ga = make_float4(act(ga.x, ua.x), act(ga.y, ua.y), act(ga.z, ua.z), act(ga.w, ua.w)); - gc = make_float4(act(gc.x, uc.x), act(gc.y, uc.y), act(gc.z, uc.z), act(gc.w, uc.w)); - } - size_t o = row * n + c; - signed char* qs = out + o; - float* xd = (float*)(out + (size_t)gridDim.y * n) + o / 32; -#if LLAMA_Q8 - float d, id; - { - float vv[8] = {ga.x, ga.y, ga.z, ga.w, gc.x, gc.y, gc.z, gc.w}; - float mx = 0.f, sv = 0.f; int si = 1 << 30; - for (int j = 0; j < 8; j++) mx = fmaxf(mx, fabsf(vv[j])); - if (valid) for (int j = 0; j < 8; j++) if (fabsf(vv[j]) == mx && si > i + j) { sv = vv[j]; si = i + j; } - q8k_scale<32>(sv, si, d, id); +// The key splits of `mla_attn` merged: block = one (query, head), thread = one value of vd. +extern "C" __global__ void mla_combine(const float* part, float* out, int vd, int nsp) { + size_t th = blockIdx.x; + const float* p = part + th * nsp * (vd + 2); + float mx = __int_as_float(0xff800000); + for (int z = 0; z < nsp; z++) if (p[z * (vd + 2) + 1] > 0.0f) mx = fmaxf(mx, p[z * (vd + 2)]); + for (int v = threadIdx.x; v < vd; v += blockDim.x) { + float l = 0.0f, s = 0.0f; + for (int z = 0; z < nsp; z++) { + const float* q = p + z * (vd + 2); + if (q[1] <= 0.0f) continue; + float e = expf(q[0] - mx); + l += e * q[1]; + s += e * q[2 + v]; + } + out[th * vd + v] = s / l; } - if (valid) { - int2 q = make_int2(pack4(__float2int_rn(ga.x * id), __float2int_rn(ga.y * id), __float2int_rn(ga.z * id), __float2int_rn(ga.w * id)), - pack4(__float2int_rn(gc.x * id), __float2int_rn(gc.y * id), __float2int_rn(gc.z * id), __float2int_rn(gc.w * id))); - *(int2*)(qs + i) = q; - if ((threadIdx.x & 3) == 0) xd[i >> 5] = d; +} + +// Attention of each query over its own list of keys (Kolibri sparse layers). Block = (query t, K/V head g); the +// `per` = nh / nkv query heads of g are one warp each, so a tile of 32 keys is read once for all of them. +// q: f32 [t][head][hd]; kc, vc: f16 rows [(pos * nkv + g) * hd]; idx: ns key positions per query, the first cnt[t] +// valid. Online softmax: each head keeps its running maximum m, sum l and weighted V sum (hd / 32 values a thread). +// A key row of the tile takes hd + 1 floats, so the 32 lanes that read one dimension of 32 keys hit 32 banks. +// Shared memory: (per + 64) * hd + per * 32 + 32 floats. +extern "C" __global__ void attn_sel(const float* q, const u16* kc, const u16* vc, const unsigned* idx, const int* cnt, + float* out, int nh, int nkv, int hd, int ns, float scale) { + extern __shared__ float sm[]; + int t = blockIdx.x, g = blockIdx.y, per = nh / nkv; + int tid = threadIdx.x, h = tid >> 5, c = tid & 31, nthr = per * 32, n = cnt[t], nd = hd / 32; + float* qs = sm; + float* kt = qs + per * hd; + float* vt = kt + 32 * (hd + 1); + float* ps = vt + 32 * hd; + const float* qg = q + ((size_t)t * nh + (size_t)g * per) * hd; + for (int i = tid; i < per * hd; i += nthr) qs[i] = qg[i]; + const unsigned* sel = idx + (size_t)t * ns; + float acc[8]; + for (int i = 0; i < 8; i++) acc[i] = 0.0f; + float m = __int_as_float(0xff800000), l = 0.0f; + for (int j0 = 0; j0 < n; j0 += 32) { + __syncthreads(); + for (int i = tid; i < 32 * hd; i += nthr) { + int j = j0 + i / hd; + if (j < n) { + size_t row = ((size_t)sel[j] * nkv + g) * hd + i % hd; + kt[i + i / hd] = h2f(kc[row]); + vt[i] = h2f(vc[row]); + } else { + kt[i + i / hd] = 0.0f; + vt[i] = 0.0f; + } + } + __syncthreads(); + float s = __int_as_float(0xff800000); + if (j0 + c < n) { + const float* qh = qs + h * hd; + const float* kr = kt + c * (hd + 1); + float d = 0.0f; + for (int i = 0; i < hd; i++) d = fmaf(qh[i], kr[i], d); + s = d * scale; + } + float mx = s; + for (int o = 16; o > 0; o >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, o)); + float mn = fmaxf(m, mx); + float a = expf(m - mn); + float p = expf(s - mn); + float sum = p; + for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffff, sum, o); + l = l * a + sum; + m = mn; + ps[tid] = p; + __syncwarp(); + const float* ph = ps + h * 32; + for (int r = 0; r < nd; r++) { + float v = 0.0f; + for (int k = 0; k < 32; k++) v = fmaf(ph[k], vt[k * hd + c + 32 * r], v); + acc[r] = acc[r] * a + v; + } } -#else - unsigned m = c + 256 > n ? __ballot_sync(0xffffffff, valid) : 0xffffffff; - if (valid) quant8(ga, gc, i, qs, xd, m); -#endif + float* o = out + ((size_t)t * nh + (size_t)g * per + h) * hd; + for (int r = 0; r < nd; r++) o[c + 32 * r] = acc[r] / l; } -extern "C" __global__ void softcap(float* x, int n, float cap) { - int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) x[i] = cap * tanhf(x[i] / cap); +// Vision encoder layer norm with bias: block = row of n (256 threads), out = (x - mean) / sqrt(var + eps) * w + b. +extern "C" __global__ void vit_norm(const float* x, float* out, const float* w, const float* b, int n, float eps) { + const float* xr = x + (size_t)blockIdx.x * n; + float* o = out + (size_t)blockIdx.x * n; + float s = 0.0f; + for (int i = threadIdx.x; i < n; i += 256) s += xr[i]; + const float mean = block_sum(s) / (float)n; + float v = 0.0f; + for (int i = threadIdx.x; i < n; i += 256) { float d = xr[i] - mean; v += d * d; } + const float inv = 1.0f / sqrtf(block_sum(v) / (float)n + eps); + for (int i = threadIdx.x; i < n; i += 256) o[i] = (xr[i] - mean) * inv * w[i] + b[i]; } -// ---- Inkling 2's decode token on the device (inkling2::device); the host math is in src/inkling2/forward.rs ---- +// y[r][c] = act(y[r][c] + bias[c]) for rows blockIdx.y, rows `stride` floats apart. act: 0 none, 1 GELU (tanh), +// 2 GELU (erf, Abramowitz-Stegun 7.1.26 as the CPU encoder), 3 quick GELU, 4 SiLU. +extern "C" __global__ void vit_bias(float* y, int stride, const float* bias, int cols, int act) { + const int c = blockIdx.x * 256 + threadIdx.x; + if (c >= cols) return; + float* p = y + (size_t)blockIdx.y * stride + c; + float x = *p + bias[c]; + if (act == 1) x = 0.5f * x * (1.0f + tanhf(0.79788456f * x * (1.0f + 0.044715f * x * x))); + else if (act == 2) { + const float z = x * 0.70710678f, t = 1.0f / (1.0f + 0.3275911f * fabsf(z)); + const float e = 1.0f - (((((1.0614054f * t - 1.4531521f) * t) + 1.4214138f) * t - 0.28449672f) * t + 0.2548296f) * t * expf(-z * z); + x = 0.5f * x * (1.0f + (z >= 0.0f ? e : -e)); + } else if (act == 3) x = x / (1.0f + expf(-1.702f * x)); + else if (act == 4) x = silu(x); + *p = x; +} -// Max over the whole block; every thread gets the result. blockDim.x must be a multiple of 32. -__device__ float block_max(float v) { - __shared__ float s[32]; - int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; - v = warp_max(v); - __syncthreads(); - if (lane == 0) s[w] = v; - __syncthreads(); - return warp_max(lane < nw ? s[lane] : -3.0e38f); +// Qwen3-VL vision RoPE (ops::rope_vision) of the nh heads of token blockIdx.x, x [n][nh][hd]. The tokens are in 2x2 +// merge-block order: token t is patch (w2 m + dx, h2 m + dy) of a grid `mx` blocks wide. Pairs (i, i + hd/2); the first +// hd/4 turn by the row, the rest by the column, each section with its own exponent. +extern "C" __global__ void vit_rope(float* x, int nh, int hd, int m, int mx, float base) { + const int t = blockIdx.x, half = hd / 2, sec = half / 2; + const int dx = t % m, dy = (t / m) % m, blk = t / (m * m); + const int px = (blk % mx) * m + dx, py = (blk / mx) * m + dy; + const float ts = powf(base, -2.0f / (float)half); + float* xr = x + (size_t)t * nh * hd; + for (int j = threadIdx.x; j < nh * half; j += blockDim.x) { + const int h = j / half, i = j % half; + const int pos = i < sec ? py : px, loc = i < sec ? i : i - sec; + float sn, cs; + sincosf((float)pos * powf(ts, (float)loc), &sn, &cs); + float* r = xr + h * hd; + const float a = r[i], b = r[i + half]; + r[i] = a * cs - b * sn; + r[i + half] = a * sn + b * cs; + } } -// Depth mix, one block of 256 per (query row, token): softmax-weighted sum of the RMS-normed states (the nb blocks -// of shape [nb][nt][n], then cur [nt][n]; at most 5), scored by state . query / sqrt(n). -extern "C" __global__ void ink_mix(const float* blocks, int nb, const float* cur, const float* q, float* out, int n, int nt) { - int qid = blockIdx.x, tok = blockIdx.y; - const float* qr = q + (size_t)qid * n; - float sc[5], lg[5], mx = -3.0e38f, z = 0.f; - for (int s = 0; s <= nb; s++) { - const float* x = s < nb ? blocks + ((size_t)s * nt + tok) * n : cur + (size_t)tok * n; - float ss = 0.f, d = 0.f; - for (int i = threadIdx.x; i < n; i += 256) { ss += x[i] * x[i]; d += x[i] * qr[i]; } - sc[s] = 1.f / sqrtf(block_sum(ss) / (float)n + 1e-6f); - lg[s] = block_sum(d) * sc[s] / sqrtf((float)n); - mx = fmaxf(mx, lg[s]); +// Vision encoder attention: each of the n query rows sees all n keys, no mask. q, k, v and out are f32 [n][nh][hd], +// A block takes 32 query rows of head blockIdx.y (8 a warp) and walks the keys 32 at a time through shared memory, +// one key a lane, with an online softmax. The 8 rows of a warp share each K and V load; the probabilities go through +// shared memory, and each lane keeps its own part of the softmax sum until the end. A key row takes hd + 1 floats so +// the 32 lanes, each on its own key, hit 32 banks. Shared memory: (64 * hd + 32 * (hd + 1) + 1024) floats. +extern "C" __global__ void vit_attn(const float* q, const float* k, const float* v, float* out, int n, int nh, int hd, float scale) { + extern __shared__ float sm[]; + float* qs = sm; + float* vs = qs + 32 * hd; + float* ks = vs + 32 * hd; + const int h = blockIdx.y, q0 = blockIdx.x * 32, lane = threadIdx.x & 31, w = threadIdx.x >> 5; + float* ps = ks + 32 * (hd + 1) + w * 256; + const float* qw = qs + w * 8 * hd; + const size_t ld = (size_t)nh * hd; + for (int i = threadIdx.x; i < 32 * hd; i += blockDim.x) { + const int r = i / hd, d = i - r * hd; + qs[i] = q0 + r < n ? q[(q0 + r) * ld + h * hd + d] * scale : 0.f; } - for (int s = 0; s <= nb; s++) { lg[s] = expf(lg[s] - mx); z += lg[s]; } - size_t oo = ((size_t)qid * nt + tok) * n; - for (int i = threadIdx.x; i < n; i += 256) { - float o = 0.f; - for (int s = 0; s <= nb; s++) { - float v = s < nb ? blocks[((size_t)s * nt + tok) * n + i] : cur[(size_t)tok * n + i]; - o += lg[s] / z * sc[s] * v; + float m[8], l[8], o[8][4]; +#pragma unroll + for (int r = 0; r < 8; r++) { + m[r] = __int_as_float(0xff800000); l[r] = 0.f; +#pragma unroll + for (int c = 0; c < 4; c++) o[r][c] = 0.f; + } + for (int k0 = 0; k0 < n; k0 += 32) { + __syncthreads(); + for (int i = threadIdx.x; i < 32 * hd; i += blockDim.x) { + const int r = i / hd, d = i - r * hd; + const bool in = k0 + r < n; + const size_t g = (k0 + r) * ld + h * hd + d; + ks[r * (hd + 1) + d] = in ? k[g] : 0.f; + vs[i] = in ? v[g] : 0.f; } - out[oo + i] = o; + __syncthreads(); + const bool valid = k0 + lane < n; + const float* kr = ks + lane * (hd + 1); + float s[8]; +#pragma unroll + for (int r = 0; r < 8; r++) s[r] = 0.f; + for (int d = 0; d < hd; d++) { + const float kd = kr[d]; +#pragma unroll + for (int r = 0; r < 8; r++) s[r] += qw[r * hd + d] * kd; + } +#pragma unroll + for (int r = 0; r < 8; r++) { + // The first tile always holds key 0, so mn is finite from then on and corr is 0 on the first tile. + const float mn = fmaxf(m[r], warp_max(valid ? s[r] : __int_as_float(0xff800000))); + const float p = valid ? __expf(s[r] - mn) : 0.f; + const float corr = __expf(m[r] - mn); + l[r] = l[r] * corr + p; + m[r] = mn; +#pragma unroll + for (int c = 0; c < 4; c++) o[r][c] *= corr; + ps[r * 32 + lane] = p; + } + __syncwarp(); + for (int j = 0; j < 32; j++) { + const float* vr = vs + j * hd; +#pragma unroll + for (int c = 0; c < 4; c++) { + if (lane + 32 * c >= hd) continue; + const float vv = vr[lane + 32 * c]; +#pragma unroll + for (int r = 0; r < 8; r++) o[r][c] += ps[r * 32 + j] * vv; + } + } + __syncwarp(); } -} - -// Loop controllers, the gates across nt tokens: block (r, j, tok). cur [min(nins, count)][nt][n], msg [count][nt][n]. -extern "C" __global__ void ink_ctrl_gate(const u16* down, const float* cur, int nins, const float* msg, float* gate, - int n, int rank, int nt) { - int r = blockIdx.x, j = blockIdx.y, tok = blockIdx.z, count = gridDim.y; - const u16* w = down + ((size_t)j * rank + r) * 2 * n; - const float* c = cur + ((size_t)min(j, nins - 1) * nt + tok) * n; - const float* m = msg + ((size_t)j * nt + tok) * n; - float a = 0.f, b = 0.f, sa = 0.f, sb = 0.f; - for (int i = threadIdx.x; i < n; i += 256) { - a += h2f(w[i]) * c[i]; b += h2f(w[n + i]) * m[i]; - sa += c[i] * c[i]; sb += m[i] * m[i]; +#pragma unroll + for (int r = 0; r < 8; r++) { + const int t = q0 + w * 8 + r; + const float lt = warp_sum(l[r]); + if (t >= n) continue; +#pragma unroll + for (int c = 0; c < 4; c++) if (lane + 32 * c < hd) out[t * ld + h * hd + lane + 32 * c] = o[r][c] / lt; } - a = block_sum(a); b = block_sum(b); sa = block_sum(sa); sb = block_sum(sb); - if (threadIdx.x == 0) - gate[((size_t)tok * count + j) * rank + r] = a / sqrtf(sa / (float)n + 1e-6f) + b / sqrtf(sb / (float)n + 1e-6f); } -// Loop controllers, the update across nt tokens: block (x, j, tok). -extern "C" __global__ void ink_ctrl_out(const u16* gain, const u16* forget, const float* gate, const float* cur, int nins, - const float* msg, float* out, int n, int rank, int nt) { - int c = blockIdx.x * blockDim.x + threadIdx.x, j = blockIdx.y, tok = blockIdx.z, count = gridDim.y; - if (c >= n) return; - const u16* gw = gain + (size_t)j * rank * n + c; - const u16* fw = forget + (size_t)j * rank * n + c; - float g = 0.f, f = 0.f; - for (int r = 0; r < rank; r++) { - float t = gate[((size_t)tok * count + j) * rank + r]; - g += t * h2f(gw[(size_t)r * n]); f += t * h2f(fw[(size_t)r * n]); +// vit_attn on the tensor cores (sm_80+): flash attention over f16 copies of q, k and v, f32 softmax and output. +// A block takes 64 query rows of head blockIdx.y (16 a warp) and walks the keys 32 at a time, as attn_prefill_t's +// mma16816 path but without a mask (only the keys past n) and with the head padded to HP (a multiple of 16) by zero +// columns. hd % 4 == 0 (float4 loads). Other GPUs, and HIP, run the scalar vit_attn (the launcher picks). +template +__device__ __forceinline__ void vit_attn_tc_t(const float* q, const float* k, const float* v, float* out, int n, int nh, int hd, float scale) { +#if !STRATA_HIP && __CUDA_ARCH__ >= 800 + constexpr int BQ = 64, BK = 32, PQ = HP + 8; + __shared__ __align__(16) u16 qs[BQ * PQ], ks[BK * PQ], vs[BK * PQ]; + const int h = blockIdx.y, q0 = blockIdx.x * BQ, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int g = lane >> 2, t4 = lane & 3, lr = (lane & 7) + ((lane >> 3) & 1) * 8, lc = (lane >> 4) * 8; + const size_t ld = (size_t)nh * hd; + const int c4 = hd >> 2; // float4 chunks a row + // The pad columns hd .. HP are never written by the tile loads: zero them once. + for (int i = tid; i < (BQ + 2 * BK) * (HP - hd); i += blockDim.x) { + const int r = i / (HP - hd), d = hd + i % (HP - hd); + if (r < BQ) qs[r * PQ + d] = 0; + else if (r < BQ + BK) ks[(r - BQ) * PQ + d] = 0; + else vs[(r - BQ - BK) * PQ + d] = 0; + } + auto tile = [&](u16* dst, const float* src, int r0, int rows, float mul) { + for (int i = tid; i < rows * c4; i += blockDim.x) { + const int r = i / c4, d = (i - r * c4) * 4; + float4 x = make_float4(0.f, 0.f, 0.f, 0.f); + if (r0 + r < n) x = *(const float4*)(src + (size_t)(r0 + r) * ld + h * hd + d); + u32* p = (u32*)(dst + r * PQ + d); + p[0] = h2pack(x.x * mul, x.y * mul); + p[1] = h2pack(x.z * mul, x.w * mul); + } + }; + tile(qs, q, q0, BQ, scale); + __syncthreads(); + u32 a[HP / 16][4]; +#pragma unroll + for (int kk = 0; kk < HP / 16; kk++) ldsm4(a[kk], qs + (warp * 16 + lr) * PQ + kk * 16 + lc); + float o[HP / 8][4], m[2] = {__int_as_float(0xff800000), __int_as_float(0xff800000)}, l[2] = {0.f, 0.f}; +#pragma unroll + for (int d = 0; d < HP / 8; d++) o[d][0] = o[d][1] = o[d][2] = o[d][3] = 0.f; + for (int k0 = 0; k0 < n; k0 += BK) { + __syncthreads(); + tile(ks, k, k0, BK, 1.f); + tile(vs, v, k0, BK, 1.f); + __syncthreads(); + float s[BK / 8][4]; +#pragma unroll + for (int nt = 0; nt < BK / 8; nt++) s[nt][0] = s[nt][1] = s[nt][2] = s[nt][3] = 0.f; +#pragma unroll + for (int kk = 0; kk < HP / 16; kk++) +#pragma unroll + for (int nt = 0; nt < BK / 8; nt += 2) { + u32 b[4]; // keys nt*8 / dims kk, keys nt*8 / dims kk+8, keys nt*8+8 / dims kk, keys nt*8+8 / dims kk+8 + ldsm4(b, ks + (nt * 8 + (lane & 7) + (lane >> 4) * 8) * PQ + kk * 16 + ((lane >> 3) & 1) * 8); + mma16816(s[nt], a[kk][0], a[kk][1], a[kk][2], a[kk][3], b[0], b[1]); + mma16816(s[nt + 1], a[kk][0], a[kk][1], a[kk][2], a[kk][3], b[2], b[3]); + } + float mx[2] = {m[0], m[1]}; +#pragma unroll + for (int nt = 0; nt < BK / 8; nt++) +#pragma unroll + for (int e = 0; e < 4; e++) { + if (k0 + nt * 8 + 2 * t4 + (e & 1) >= n) s[nt][e] = __int_as_float(0xff800000); + mx[e >> 1] = fmaxf(mx[e >> 1], s[nt][e]); + } + float c[2]; +#pragma unroll + for (int r = 0; r < 2; r++) { + // Key k0 < n is in every tile, so mx is finite; c is 0 on the first tile (m = -inf). + mx[r] = fmaxf(mx[r], __shfl_xor_sync(0xffffffff, mx[r], 1)); + mx[r] = fmaxf(mx[r], __shfl_xor_sync(0xffffffff, mx[r], 2)); + c[r] = __expf(m[r] - mx[r]); + m[r] = mx[r]; + l[r] *= c[r]; + } +#pragma unroll + for (int nt = 0; nt < BK / 8; nt++) +#pragma unroll + for (int e = 0; e < 4; e++) { const float p = __expf(s[nt][e] - mx[e >> 1]); s[nt][e] = p; l[e >> 1] += p; } +#pragma unroll + for (int d = 0; d < HP / 8; d++) { o[d][0] *= c[0]; o[d][1] *= c[0]; o[d][2] *= c[1]; o[d][3] *= c[1]; } +#pragma unroll + for (int kb = 0; kb < BK / 16; kb++) { + const u32 a0 = h2pack(s[2 * kb][0], s[2 * kb][1]), a1 = h2pack(s[2 * kb][2], s[2 * kb][3]); + const u32 a2 = h2pack(s[2 * kb + 1][0], s[2 * kb + 1][1]), a3 = h2pack(s[2 * kb + 1][2], s[2 * kb + 1][3]); +#pragma unroll + for (int d = 0; d < HP / 8; d += 2) { + u32 b[4]; // transposed: keys kb*16 / dims d*8, keys +8 / dims d*8, keys / dims d*8+8, keys +8 / dims d*8+8 + ldsm4t(b, vs + (kb * 16 + lr) * PQ + d * 8 + lc); + mma16816(o[d], a0, a1, a2, a3, b[0], b[1]); + mma16816(o[d + 1], a0, a1, a2, a3, b[2], b[3]); + } + } } - size_t co = ((size_t)min(j, nins - 1) * nt + tok) * n + c; - size_t mo = ((size_t)j * nt + tok) * n + c; - float x = cur[co]; - f = fminf(fmaxf(f, -10.f), 10.f); - g = fminf(fmaxf(g, -10.f), 10.f); - out[mo] = x - tanhf(f) * x + tanhf(g) * msg[mo]; +#pragma unroll + for (int r = 0; r < 2; r++) { + l[r] += __shfl_xor_sync(0xffffffff, l[r], 1); + l[r] += __shfl_xor_sync(0xffffffff, l[r], 2); + const int t = q0 + warp * 16 + g + 8 * r; + if (t >= n) continue; + float* orow = out + (size_t)t * ld + h * hd; +#pragma unroll + for (int d = 0; d < HP / 8; d++) +#pragma unroll + for (int e = 0; e < 2; e++) { + const int col = d * 8 + 2 * t4 + e; + if (col < hd) orow[col] = o[d][2 * r + e] / l[r]; + } + } +#endif } - -// Short causal convolution with a residual (nc at most 8; out may be cur): hist holds the last nc - 1 inputs, the -// oldest first, and is advanced by cur. taps ([c / per][lag], lag 0 the current input) may be null. -extern "C" __global__ void ink_conv(const float* cur, const float* w, const float* taps, float* hist, float* out, int n, int nc, int per) { - int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= n) return; - float x[8], o = 0.f; - for (int k = 0; k + 1 < nc; k++) x[k] = hist[(size_t)k * n + c]; - x[nc - 1] = cur[c]; - for (int k = 0; k < nc; k++) o += x[k] * w[c * nc + k]; - if (taps) for (int lag = 0; lag < nc; lag++) o += x[nc - 1 - lag] * taps[c / per * nc + lag]; - out[c] = (x[nc - 1] + o) / sqrtf((float)((taps ? 2 * nc : nc) + 1)); - for (int k = 0; k + 1 < nc; k++) hist[(size_t)k * n + c] = x[k + 1]; +extern "C" __global__ void __launch_bounds__(128) vit_attn_tc_80(const float* q, const float* k, const float* v, float* out, int n, int nh, int hd, float scale) { + vit_attn_tc_t<80>(q, k, v, out, n, nh, hd, scale); +} +extern "C" __global__ void __launch_bounds__(128) vit_attn_tc_128(const float* q, const float* k, const float* v, float* out, int n, int nh, int hd, float scale) { + vit_attn_tc_t<128>(q, k, v, out, n, nh, hd, scale); } -// Batched causal short convolution for Inkling 2 prefill (o != cur). -// mode 0 (grid [ceil(n/256), nt]): writes o[tok, c]; mode 1 (grid [ceil(n/256), 1]): advances hist. -extern "C" __global__ void ink_conv_batch(const float* cur, const float* w, const float* taps, float* hist, float* o, - int n, int nc, int per, int nt, int mode) { - int c = blockIdx.x * blockDim.x + threadIdx.x; - if (c >= n) return; - if (mode != 0) { - float old[8]; - for (int k = 0; k + 1 < nc; k++) old[k] = hist[(size_t)k * n + c]; - for (int k = 0; k + 1 < nc; k++) { - int src = nt - (nc - 1) + k; - hist[(size_t)k * n + c] = src >= 0 ? cur[(size_t)src * n + c] : old[(nc - 1) + src]; - } - return; - } - int tok = blockIdx.y; - float x[8], acc = 0.f; - for (int k = 0; k < nc; k++) { - int s = tok - (nc - 1) + k; - float xv = s < 0 ? hist[(size_t)((nc - 1) + s) * n + c] : cur[(size_t)s * n + c]; - x[k] = xv; - acc += xv * w[c * nc + k]; - } - if (taps) { - int nheads = n / per; - size_t tp_base = ((size_t)tok * nheads + c / per) * nc; - for (int lag = 0; lag < nc; lag++) acc += x[nc - 1 - lag] * taps[tp_base + lag]; +// Inkling 2 decode, after ink_route: the expert pool lookup of the k routed experts (slots[j] = table[ids[j]], -1 = +// on the CPU; wh[j] = wts[j] on a hit, else 0), the routing copied to the host-mapped mailbox `mb` (cpu_worker's +// layout for one token), and the request flag raised with the activation `h` when an expert missed, else only the +// skip flag. One block; step[1] is the CPU worker's sequence number. +extern "C" __global__ void ink_slots(const int* ids, const float* wts, const int* table, int* slots, float* wh, + const float* h, unsigned int* mb, int nh, int h_off, const int* step, int k) { + __shared__ int miss; + unsigned int seq = step[1]; + if (threadIdx.x == 0) miss = 0; + __syncthreads(); + if (threadIdx.x < k) { + int j = threadIdx.x, id = ids[j], s = table[id]; + float w = wts[j]; + slots[j] = s; wh[j] = s >= 0 ? w : 0.0f; + mb[32 + j] = id; mb[32 + k + j] = __float_as_uint(w); mb[32 + 2 * k + j] = s; + if (s < 0) miss = 1; } - o[(size_t)tok * n + c] = (x[nc - 1] + acc) / sqrtf((float)((taps ? 2 * nc : nc) + 1)); + __syncthreads(); + if (threadIdx.x == 0) mb[1] = 1; + if (!miss) { if (threadIdx.x == 0) ((volatile unsigned int*)mb)[2] = seq; return; } + for (int i = threadIdx.x; i < nh; i += blockDim.x) mb[h_off + i] = __float_as_uint(h[i]); + __threadfence_system(); + __syncthreads(); + if (threadIdx.x == 0) *(volatile unsigned int*)mb = seq; } -// acc[tok] = (cpu ? cpu[tok] : 0) + sum_{e < ne} wts[tok, e] * d[(tok * ne + e) * n + c]. blockIdx.y = tok. -extern "C" __global__ void ink_ffn_sum(float* acc, const float* d, const float* wts, int ne, int n, const float* cpu) { - int c = blockIdx.x * blockDim.x + threadIdx.x, tok = blockIdx.y; +// ink_ffn_sum of the pool's experts (wh, 0 for an expert on the CPU) plus, when one missed, the CPU worker's sum at +// word y_off of the mailbox, once its done flag is step[1]. +extern "C" __global__ void ink_ffn_sum_mb(float* acc, const float* d, const float* wh, int k, int n, const unsigned int* mb, + int y_off, const int* step, const int* slots) { + unsigned int seq = step[1]; + __shared__ int miss; + if (threadIdx.x == 0) { + int m = 0; + for (int j = 0; j < k; j++) m |= slots[j] < 0; + if (m) { + unsigned int spins = 0; + while (((volatile const unsigned int*)mb)[16] != seq) { + __nanosleep(100); + if (++spins == (1u << 27)) __trap(); // ~15 s: CPU worker gone + } + __threadfence_system(); + } + miss = m; + } + __syncthreads(); + int c = blockIdx.x * blockDim.x + threadIdx.x; if (c >= n) return; - float o = cpu ? cpu[(size_t)tok * n + c] : 0.f; - size_t db = (size_t)tok * ne * n + c, wb = (size_t)tok * ne; - for (int e = 0; e < ne; e++) o += wts[wb + e] * d[db + (size_t)e * n]; - acc[(size_t)tok * n + c] = o; + float o = miss ? __uint_as_float(((volatile const unsigned int*)mb)[y_off + c]) : 0.f; + for (int e = 0; e < k; e++) if (wh[e] != 0.f) o += wh[e] * d[(size_t)e * n + c]; + acc[c] = o; } __device__ __forceinline__ unsigned ink_f2key(float x) { @@ -1936,23 +3788,32 @@ extern "C" __global__ void ink_route(const float* logits, const float* bias, int } // Gyro files (config::Hadamard): the routed experts read H (s x) in place of x, H the normalized Sylvester-Walsh- -// Hadamard matrix over blocks of bs values (a power of two, at most 1024) and s the n signs of a row. One block of -// bs threads per block of values, one butterfly stage per barrier, in the order of the CPU's transform (the same -// bits). With `u`, x is silu(x) * u first (the SwiGLU before the down matrix). `out` may be x. -extern "C" __global__ void hadamard(const float* x, const float* u, const float* s, float* out, int n, int bs, float scale) { - __shared__ float sh[2][1024]; - int j = threadIdx.x; - size_t i = (size_t)blockIdx.x * bs + j; - float v = x[i]; - if (u) v = silu(v) * u[i]; - v *= s[i % n]; - for (int len = 1, b = 0; len < bs; len <<= 1, b ^= 1) { - sh[b][j] = v; +// Hadamard matrix over blocks of bs values (a power of two, at most 4096) and s the n signs of a row. One block of +// min(bs, 1024) threads per block of values, one butterfly stage per barrier, in the order of the CPU's transform +// (the same bits). With `u`, x is silu(x) * u first (the SwiGLU before the down matrix). With `perm` (n indices), +// value c of a row is x[perm[c]] of that row (config::Hadamard::ssm_out_perm), and then `out` must not be x; +// otherwise `out` may be x. +extern "C" __global__ void hadamard(const float* x, const float* u, const float* s, const unsigned* perm, float* out, int n, int bs, float scale) { + __shared__ float sh[4096]; + size_t b0 = (size_t)blockIdx.x * bs, r0 = b0 / n * n; + for (int j = threadIdx.x; j < bs; j += blockDim.x) { + size_t i = b0 + j; + int c = (int)(i - r0); + float v = x[perm ? r0 + perm[c] : i]; + if (u) v = silu(v) * u[i]; + sh[j] = v * s[c]; + } + __syncthreads(); + for (int len = 1; len < bs; len <<= 1) { + for (int q = threadIdx.x; q < bs / 2; q += blockDim.x) { + int a = q / len * 2 * len + q % len; + float va = sh[a], vb = sh[a + len]; + sh[a] = va + vb; + sh[a + len] = va - vb; + } __syncthreads(); - float c = sh[b][j ^ len]; - v = (j & len) ? c - v : v + c; } - out[i] = v * scale; + for (int j = threadIdx.x; j < bs; j += blockDim.x) out[b0 + j] = sh[j] * scale; } // swiglu on rows of n (a multiple of 32) quantized as quant_xq does into out; g is left as is. Block (c, t) of one @@ -1982,8 +3843,10 @@ extern "C" __global__ void ssm_gates(float* beta, float* g, const float* dt_bias // Causal depthwise conv over [state..., current] then SiLU; state keeps the last kw-1 inputs, oldest first. // Block = 128 channels; the first nn blocks are then l2-normalized as l2_norm does (the decode q and k heads). +// tab: grid.y rows, row r at qkv and y + r * ch with its state at tab[2r] (the layer's part of Batch::kvt). extern "C" __global__ void conv_silu(const float* qkv, float* state, const float* w, float* y, int ch, int kw, int nn, - float eps) { + float eps, const u64* tab) { + if (tab) { state = (float*)tab[2 * blockIdx.y]; qkv += (size_t)blockIdx.y * ch; y += (size_t)blockIdx.y * ch; } int c = blockIdx.x * blockDim.x + threadIdx.x; float v = 0.0f; if (c < ch) { @@ -2050,60 +3913,92 @@ extern "C" __global__ void dflash2_conv(const float* x, const float* dyn, const // Token t: y + t * ych = [q | k | v] after conv and l2 norm; beta, g at t * nv; output at o + t * nv * dv. // With dtb set, beta and g are raw and get ssm_gates' gates here (dtb, ga as its dt_bias, a). // The state after each of the first min(nsnap, T - 1) tokens also goes to snap (S's layout, one state each). +// tab: grid.z rows of one token, row r as token r of y, beta, g and o, with its state at tab[2r + 1]. +// The block's k, q, v, beta and g go through shared memory C tokens at a time, and k and q are read from there in +// the sums, which keeps the registers low enough (48, was 119) for 5 blocks an SM: on a 28-SM card all 128 blocks of a 32-head layer run at +// once instead of in 3 waves. The arithmetic per token is unchanged (bit-identical to the register version). // ponytail: sequential scan (latency-bound per token); a chunked WY form would use tensor cores for long prompts. -extern "C" __global__ void deltanet_seq(const float* y, float* S, const float* beta, const float* g, float* o, +extern "C" __global__ void __launch_bounds__(256, 5) deltanet_seq(const float* y, float* S, const float* beta, const float* g, float* o, int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, - const float* dtb, const float* ga) { + const float* dtb, const float* ga, const u64* tab) { + __shared__ __align__(16) float kq[4096]; // [C][k dk | q dk] + __shared__ float vs[512]; // [C][rows of the block] + __shared__ float gb[64]; // [C] raw g, then [C] raw beta + if (tab) { + size_t r = blockIdx.z; + S = (float*)tab[2 * r + 1]; y += r * ych; beta += r * nv; g += r * nv; o += r * nv * dv; + } int L = dk >> 4, R = 32 / L, lane = threadIdx.x & 31, s = lane % L, vh = blockIdx.x, kh = ilv ? vh / (nv / nk) : vh % nk; - int j0 = (blockIdx.y * 8 + (threadIdx.x >> 5)) * R, j = j0 + lane / L; - if (j0 >= dv) return; // whole warp past the end (R divides dv) - float4* row = (float4*)(S + ((size_t)vh * dv + j) * dk); + int jb = blockIdx.y * 8 * R, rb = 8 * R, j0 = jb + (threadIdx.x >> 5) * R, j = j0 + lane / L, h4 = dk >> 2; + // C tokens a stage: C (2 dk) <= 4096 and C rb <= 512 (rb = 4096 / dk), so C = min(2048 / dk, dk / 8). + const int C = min(2048 / dk, dk / 8); + bool act = j0 < dv; // R divides dv: a warp is all in or all out float r[16]; + float4* row = (float4*)(S + ((size_t)vh * dv + (act ? j : 0)) * dk); #pragma unroll - for (int i = 0; i < 4; i++) { float4 v = row[s + L * i]; r[4 * i] = v.x; r[4 * i + 1] = v.y; r[4 * i + 2] = v.z; r[4 * i + 3] = v.w; } - // Token inputs do not depend on the state: token tok + 1's are loaded while token tok computes. - float nk_[16], nq[16], ng, nb, nvv; - auto ld = [&](int tok) { - const float* yt = y + (size_t)tok * ych; - const float4* q4 = (const float4*)(yt + kh * dk); - const float4* k4 = (const float4*)(yt + nk * dk + kh * dk); -#pragma unroll - for (int i = 0; i < 4; i++) { - float4 v = k4[s + L * i]; nk_[4 * i] = v.x; nk_[4 * i + 1] = v.y; nk_[4 * i + 2] = v.z; nk_[4 * i + 3] = v.w; - if (o) { - v = q4[s + L * i]; nq[4 * i] = v.x; nq[4 * i + 1] = v.y; nq[4 * i + 2] = v.z; nq[4 * i + 3] = v.w; - } else { - nq[4 * i] = 0.0f; nq[4 * i + 1] = 0.0f; nq[4 * i + 2] = 0.0f; nq[4 * i + 3] = 0.0f; - } + for (int i = 0; i < 4; i++) { + float4 v = act ? row[s + L * i] : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + r[4 * i] = v.x; r[4 * i + 1] = v.y; r[4 * i + 2] = v.z; r[4 * i + 3] = v.w; + } + for (int t0 = 0; t0 < T; t0 += C) { + int n = min(C, T - t0); + __syncthreads(); + for (int i = threadIdx.x; i < n * 2 * h4; i += 256) { + int tt = i / (2 * h4), c = i % (2 * h4); + const float* yt = y + (size_t)(t0 + tt) * ych; + ((float4*)kq)[i] = c < h4 ? ((const float4*)(yt + nk * dk + kh * dk))[c] : ((const float4*)(yt + kh * dk))[c - h4]; } - ng = g[tok * nv + vh]; nb = beta[tok * nv + vh]; nvv = yt[2 * nk * dk + vh * dv + j]; - if (dtb) { ng = softplus(ng + dtb[vh]) * ga[vh]; nb = sigmoid(nb); } - }; - ld(0); - for (int tok = 0; tok < T; tok++) { - float kk[16], qv[16], decay = expf(ng), bt = nb, vt = nvv, sk = 0.0f, oq = 0.0f; -#pragma unroll - for (int e = 0; e < 16; e++) { kk[e] = nk_[e]; qv[e] = nq[e]; } - if (tok + 1 < T) ld(tok + 1); + for (int i = threadIdx.x; i < n * rb; i += 256) { + int tt = i / rb, c = i % rb; + vs[i] = jb + c < dv ? y[(size_t)(t0 + tt) * ych + 2 * nk * dk + vh * dv + jb + c] : 0.0f; + } + if (threadIdx.x < n) gb[threadIdx.x] = g[(t0 + threadIdx.x) * nv + vh]; + else if (threadIdx.x >= 32 && threadIdx.x < 32 + n) gb[threadIdx.x] = beta[(t0 + threadIdx.x - 32) * nv + vh]; + __syncthreads(); + if (!act) continue; + for (int u = 0; u < n; u++) { + int tok = t0 + u; + const float4* k4 = (const float4*)(kq + u * 2 * dk) + s; + const float4* q4 = k4 + h4; + float ng = gb[u], bt = gb[32 + u], vt = vs[u * rb + j - jb], sk = 0.0f, oq = 0.0f; + if (dtb) { ng = softplus(ng + dtb[vh]) * ga[vh]; bt = sigmoid(bt); } + float decay = expf(ng); #pragma unroll - for (int e = 0; e < 16; e++) { r[e] *= decay; sk += r[e] * kk[e]; } - for (int off = L >> 1; off; off >>= 1) sk += __shfl_xor_sync(0xffffffff, sk, off); - float d = bt * (vt - sk); - if (o) { + for (int i = 0; i < 4; i++) { + float4 kv = k4[L * i]; + r[4 * i] *= decay; sk += r[4 * i] * kv.x; + r[4 * i + 1] *= decay; sk += r[4 * i + 1] * kv.y; + r[4 * i + 2] *= decay; sk += r[4 * i + 2] * kv.z; + r[4 * i + 3] *= decay; sk += r[4 * i + 3] * kv.w; + } + for (int off = L >> 1; off; off >>= 1) sk += __shfl_xor_sync(0xffffffff, sk, off); + float d = bt * (vt - sk); + if (o) { #pragma unroll - for (int e = 0; e < 16; e++) { r[e] += d * kk[e]; oq += r[e] * qv[e]; } - for (int off = L >> 1; off; off >>= 1) oq += __shfl_xor_sync(0xffffffff, oq, off); - if (s == 0) o[(size_t)tok * nv * dv + vh * dv + j] = oq * scale; - } else { + for (int i = 0; i < 4; i++) { + float4 kv = k4[L * i], qv = q4[L * i]; + r[4 * i] += d * kv.x; oq += r[4 * i] * qv.x; + r[4 * i + 1] += d * kv.y; oq += r[4 * i + 1] * qv.y; + r[4 * i + 2] += d * kv.z; oq += r[4 * i + 2] * qv.z; + r[4 * i + 3] += d * kv.w; oq += r[4 * i + 3] * qv.w; + } + for (int off = L >> 1; off; off >>= 1) oq += __shfl_xor_sync(0xffffffff, oq, off); + if (s == 0) o[(size_t)tok * nv * dv + vh * dv + j] = oq * scale; + } else { #pragma unroll - for (int e = 0; e < 16; e++) r[e] += d * kk[e]; - } - if (tok < min(nsnap, T - 1)) { - float4* sr = (float4*)(snap + (size_t)tok * nv * dv * dk + ((size_t)vh * dv + j) * dk); + for (int i = 0; i < 4; i++) { + float4 kv = k4[L * i]; + r[4 * i] += d * kv.x; r[4 * i + 1] += d * kv.y; r[4 * i + 2] += d * kv.z; r[4 * i + 3] += d * kv.w; + } + } + if (tok < min(nsnap, T - 1)) { + float4* sr = (float4*)(snap + (size_t)tok * nv * dv * dk + ((size_t)vh * dv + j) * dk); #pragma unroll - for (int i = 0; i < 4; i++) sr[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + for (int i = 0; i < 4; i++) sr[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + } } } + if (!act) return; #pragma unroll for (int i = 0; i < 4; i++) row[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); } @@ -2155,6 +4050,69 @@ extern "C" __global__ void hc_mix(const float* xn, const float* g, float* out, i out[(size_t)t * n + i] = s; } +// hc_write (plain streams) and then rms_norm_streams of the streams it wrote, in one launch with the bits of the two: +// grid = (hc, tokens), block 512, block (c, t) on stream c of token t. It adds `out` to its stream, then runs +// rms_norm's code on it. `out` is cleared (clear) by the last block of the token to finish (ticket counter `cnt`, +// which that block puts back to 0), so no block clears it while another still reads it. +extern "C" __global__ void hc_write_norm(float* r, float* out, const float* inj, const float* w, float* xn, int n, int hc, + int clear, float eps, unsigned int* cnt) { + int c = blockIdx.x, t = blockIdx.y; + float* xr = r + ((size_t)t * hc + c) * n; + float* ot = out + (size_t)t * n; + float gc = 2.0f * sigmoid(inj[t * hc + c] / (float)hc); + for (int i = threadIdx.x; i < n; i += blockDim.x) xr[i] += ot[i] * gc; + __syncthreads(); + w += (size_t)c * n; + float* o = xn + ((size_t)t * hc + c) * n; + float s = 0.0f; + if (threadIdx.x < 256) { + int i = threadIdx.x; + for (; i + 768 < n; i += 1024) { + float a = xr[i], b = xr[i + 256], cc = xr[i + 512], d = xr[i + 768]; + s += a * a; s += b * b; s += cc * cc; s += d * d; + } + for (; i < n; i += 256) s += xr[i] * xr[i]; + } + float sc = 1.0f / sqrtf(block_sum(s) / (float)n + eps); + int i = threadIdx.x, bd = blockDim.x; + for (; i + 3 * bd < n; i += 4 * bd) { + float a = xr[i] * sc * w[i], b = xr[i + bd] * sc * w[i + bd], cc = xr[i + 2 * bd] * sc * w[i + 2 * bd], d = xr[i + 3 * bd] * sc * w[i + 3 * bd]; + o[i] = a; o[i + bd] = b; o[i + 2 * bd] = cc; o[i + 3 * bd] = d; + } + for (; i < n; i += bd) o[i] = xr[i] * sc * w[i]; + if (!clear) return; + __shared__ unsigned int ticket; + __threadfence(); + __syncthreads(); + if (threadIdx.x == 0) ticket = atomicAdd(cnt + t, 1u); + __syncthreads(); + if (ticket != (unsigned)hc - 1) return; + for (int j = threadIdx.x; j < n; j += blockDim.x) ot[j] = 0.0f; + if (threadIdx.x == 0) cnt[t] = 0; +} + +// hc_mix (plain streams) and then quant_xq of its output in one launch, with the bits of the two: each thread mixes 8 +// values and quantizes them as quant_x maps them (4 threads a 32-value scale). grid = (n / 256 rounded up, tokens), +// one warp a block; the int8 rows of the nt tokens then their scales at xq, as quant_xq writes them. +extern "C" __global__ void hc_mix_q(const float* xn, const float* g, float* out, int n, int hc, signed char* xq, int nt) { + int t = blockIdx.y, i = (blockIdx.x * blockDim.x + threadIdx.x) * 8; + unsigned m = __ballot_sync(0xffffffff, i < n); + if (i >= n) return; + size_t b = (size_t)t * hc * n + i; + float4 a = make_float4(0.0f, 0.0f, 0.0f, 0.0f), c = a; + for (int k = 0; k < hc; k++) { + float4 xa = *(const float4*)(xn + b + (size_t)k * n), xc = *(const float4*)(xn + b + (size_t)k * n + 4); + float4 ga = *(const float4*)(g + b + (size_t)k * n), gc = *(const float4*)(g + b + (size_t)k * n + 4); + a.x += xa.x * sigmoid(ga.x) / (float)hc; a.y += xa.y * sigmoid(ga.y) / (float)hc; + a.z += xa.z * sigmoid(ga.z) / (float)hc; a.w += xa.w * sigmoid(ga.w) / (float)hc; + c.x += xc.x * sigmoid(gc.x) / (float)hc; c.y += xc.y * sigmoid(gc.y) / (float)hc; + c.z += xc.z * sigmoid(gc.z) / (float)hc; c.w += xc.w * sigmoid(gc.w) / (float)hc; + } + float* o = out + (size_t)t * n + i; + *(float4*)o = a; *(float4*)(o + 4) = c; + quant8(a, c, i, xq + (size_t)t * n, (float*)(xq + (size_t)nt * n) + t * (n / 32), m); +} + // grid.y = tokens: stream c of r[t] += out[t] * 2 sigmoid(inj[t][c] / hc); clear: out[t] = 0 afterwards (or mHC enter/merge/leave when hc & 0x100). extern "C" __global__ void hc_write(float* r, float* out, const float* inj, int n, int hc, int clear) { int i = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; @@ -2256,69 +4214,219 @@ extern "C" __global__ void ple_conv(float* r, const float* gated, const float* n // ---- attention ---- -// KV cache rows (one per position and KV head) hold hd f16 values (KV_MODE 0), hd int8 values followed by hd / 32 f16 scales -// (KV_MODE 1, `--kv q8`), hd / 2 packed uint4 nibbles + hd / 32 f16 scales (KV_MODE 2, `--kv q4`), or affine 2-bit -// codes (hd / 4 B) + hd / 32 f16 scales + hd / 32 f16 mins (KV_MODE 3, `--kv q2`). Offsets below count values. -#if KV_MODE == 3 -__device__ __forceinline__ float warp_min(float v) { - for (int o = 16; o > 0; o >>= 1) v = fminf(v, __shfl_xor_sync(0xffffffff, v, o)); - return v; +// KV cache rows (one per position and KV head) hold hd f16 values (mode 0), hd int8 values followed by hd / 32 f16 +// scales (mode 1, `--kv q8`), hd / 2 packed nibbles + hd / 32 f16 scales (mode 2, `--kv q4`), or affine 2-bit codes +// (hd / 4 B) + hd / 32 f16 scales + hd / 32 f16 mins (mode 3, `--kv q2`). Offsets below count values. Turbo modes +// (4/5/6) store the WHT-128-rotated vector in the nibble layout with one fp16 norm per 128-value group; Q is rotated +// by the same WHT in attention and only the output is inverse-rotated (TheTom's llama-cpp-turboquant design). +// K_MODE and V_MODE are independent: each half picks its own quantizer and bit width. +// Forward declarations so the mode-dispatched templates below parse even when neither side is turbo. +template __device__ __forceinline__ int tq_nearest(float v); +template __device__ __forceinline__ float tq_centroid(int q); +#if K_MODE >= 4 || V_MODE >= 4 +template __device__ __forceinline__ void kv_put_tq(u16* c, size_t e, int hd, float x, float norm, bool active = true); +#ifndef TQ_KBITS +#define TQ_KBITS 4 +#endif +#ifndef TQ_VBITS +#define TQ_VBITS 4 +#endif +// TurboQuant follows TheTom's llama-cpp-turboquant: unit-L2 normalize, WHT, Lloyd-Max, store the +// reconstruction-corrected norm; K/V stay rotated and only the attention output is de-rotated. +static __constant__ unsigned TQ_S1[4] = {0xE46A0359u, 0x42F85949u, 0xA4C63BBBu, 0x49F250A9u}; +static __constant__ unsigned TQ_S2[4] = {0x16ACEE90u, 0x3F628FDCu, 0xB7A5357Au, 0xBEA56562u}; +static __constant__ float TQ_C4[16] = { + -0.241529f,-0.182877f,-0.143016f,-0.111036f,-0.083292f,-0.058050f,-0.034299f,-0.011349f, + 0.011349f, 0.034299f, 0.058050f, 0.083292f, 0.111036f, 0.143016f, 0.182877f, 0.241529f}; +static __constant__ float TQ_M4[15] = { + -0.212203f,-0.162947f,-0.127026f,-0.097164f,-0.070671f,-0.046174f,-0.022824f,0.0f, + 0.022824f, 0.046174f, 0.070671f, 0.097164f, 0.127026f, 0.162947f, 0.212203f}; +static __constant__ float TQ_C3[8] = { + -0.190207f,-0.118786f,-0.066822f,-0.021663f, 0.021663f, 0.066822f, 0.118786f, 0.190207f}; +static __constant__ float TQ_M3[7] = { + -0.154496f,-0.092804f,-0.044243f,0.0f, 0.044243f, 0.092804f, 0.154496f}; +static __constant__ float TQ_C2[4] = { -0.133462f, -0.039994f, 0.039994f, 0.133462f }; +static __constant__ float TQ_M2[3] = { -0.086728f, 0.0f, 0.086728f }; +template<> __device__ __forceinline__ int tq_nearest<4>(float v) { int i=0; for(;i<15;i++) if(v __device__ __forceinline__ float tq_centroid<4>(int q) { return TQ_C4[q]; } +template<> __device__ __forceinline__ int tq_nearest<3>(float v) { int i=0; for(;i<7;i++) if(v __device__ __forceinline__ float tq_centroid<3>(int q) { return TQ_C3[q]; } +template<> __device__ __forceinline__ int tq_nearest<2>(float v) { int i=0; for(;i<3;i++) if(v __device__ __forceinline__ float tq_centroid<2>(int q) { return TQ_C2[q]; } +__device__ __forceinline__ float tq_flip(float x, unsigned b) { return __uint_as_float(__float_as_uint(x) ^ (b << 31)); } +__device__ __forceinline__ unsigned tq_bits(const unsigned* s, int lane) { return s[lane >> 3] >> (4 * (lane & 7)); } +__device__ __forceinline__ void tq_wht4(float4& v, int lane, bool inv) { + unsigned a = tq_bits(inv ? TQ_S2 : TQ_S1, lane); + v.x = tq_flip(v.x, a & 1u); v.y = tq_flip(v.y, (a >> 1) & 1u); + v.z = tq_flip(v.z, (a >> 2) & 1u); v.w = tq_flip(v.w, (a >> 3) & 1u); + { float x = v.x, y = v.y; v.x = x + y; v.y = x - y; + float z = v.z, w = v.w; v.z = z + w; v.w = z - w; } + { float x = v.x, z = v.z; v.x = x + z; v.z = x - z; + float y = v.y, w = v.w; v.y = y + w; v.w = y - w; } +#define TQ_STAGE(m) { \ + float px = __shfl_xor_sync(0xffffffff, v.x, (m)), py = __shfl_xor_sync(0xffffffff, v.y, (m)); \ + float pz = __shfl_xor_sync(0xffffffff, v.z, (m)), pw = __shfl_xor_sync(0xffffffff, v.w, (m)); \ + bool hi = (lane & (m)) != 0; \ + v.x = hi ? px - v.x : v.x + px; v.y = hi ? py - v.y : v.y + py; \ + v.z = hi ? pz - v.z : v.z + pz; v.w = hi ? pw - v.w : v.w + pw; } + TQ_STAGE(1) TQ_STAGE(2) TQ_STAGE(4) TQ_STAGE(8) TQ_STAGE(16) +#undef TQ_STAGE + constexpr float k = 0.08838834764831845f; + unsigned b = tq_bits(inv ? TQ_S1 : TQ_S2, lane); + v.x = tq_flip(v.x * k, b & 1u); v.y = tq_flip(v.y * k, (b >> 1) & 1u); + v.z = tq_flip(v.z * k, (b >> 2) & 1u); v.w = tq_flip(v.w * k, (b >> 3) & 1u); +} +__device__ __forceinline__ unsigned tq_bit(const unsigned* s, int e) { return (s[e >> 5] >> (e & 31)) & 1u; } +__device__ __forceinline__ void tq_wht2(float2& v, int lane, bool inv) { + const unsigned* sa = inv ? TQ_S2 : TQ_S1; + unsigned a = tq_bit(sa, 2 * lane) | (tq_bit(sa, 2 * lane + 1) << 1); + v.x = tq_flip(v.x, a & 1u); v.y = tq_flip(v.y, (a >> 1) & 1u); + { float x = v.x, y = v.y; v.x = x + y; v.y = x - y; } +#define TQ_STAGE2(m) { \ + float px = __shfl_xor_sync(0xffffffff, v.x, (m)), py = __shfl_xor_sync(0xffffffff, v.y, (m)); \ + bool hi = (lane & (m)) != 0; v.x = hi ? px - v.x : v.x + px; v.y = hi ? py - v.y : v.y + py; } + TQ_STAGE2(1) TQ_STAGE2(2) TQ_STAGE2(4) TQ_STAGE2(8) TQ_STAGE2(16) +#undef TQ_STAGE2 + const unsigned* sb = inv ? TQ_S1 : TQ_S2; + unsigned b = tq_bit(sb, 2 * lane) | (tq_bit(sb, 2 * lane + 1) << 1); + constexpr float k = 0.125f; + v.x = tq_flip(v.x * k, b & 1u); v.y = tq_flip(v.y * k, (b >> 1) & 1u); +} +// Sum cs over the 128 threads that own one WHT group. All 128 threads of the group call this with the same g. +// A 256-thread caller with hd=128 sends its upper 128 threads through group 0 with identical cs; the duplicate +// shared writes carry the same value, so the result and the single norm slot are unchanged. +__device__ __forceinline__ float tq_group_sum(float cs, int g) { + float v = warp_sum(cs); + __shared__ float s[16]; // at most 4 groups per head, 4 warps each + int lane = threadIdx.x & 31, w = (threadIdx.x & 127) >> 5; + if (lane == 0) s[4 * g + w] = v; + __syncthreads(); + float t = lane < 4 ? s[4 * g + lane] : 0.0f; + __syncthreads(); // every thread has read the partials before a later call reuses s + return warp_sum(t); } -__device__ __forceinline__ void kv_put(u16* c, size_t e, int hd, float x) { - u16 mn_h = f2h(warp_min(x)); - float mn = h2f(mn_h), mx = warp_max(x), dr = fmaxf(0.0f, mx - mn) / 3.0f; - u16 d_h = f2h(dr); - float d = h2f(d_h), y = d == 0.0f ? 0.0f : (x - mn) / d; - int q = (int)roundf(y); - q = q < 0 ? 0 : (q > 3 ? 3 : q); - unsigned uq = (unsigned)q; - unsigned packed = uq - | (__shfl_xor_sync(0xffffffff, uq, 1) << 2) - | (__shfl_xor_sync(0xffffffff, uq, 2) << 4) - | (__shfl_xor_sync(0xffffffff, uq, 3) << 6); - int w = e % hd; - unsigned char* r = (unsigned char*)c + e / hd * (3 * hd / 8); - if ((w & 3) == 0) r[w / 4] = (unsigned char)packed; - if ((w & 31) == 0) { - *(u16*)(r + hd / 4 + 2 * (w / 32)) = d_h; - *(u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32)) = mn_h; - } -} -#elif KV_MODE == 2 -// Quantize x into the cache at value offset e; the 32 lanes of the warp hold one 32-value block. -__device__ __forceinline__ void kv_put(u16* c, size_t e, int hd, float x) { - float d = warp_max(fabsf(x)) / 7.0f; - float y = d == 0.0f ? 0.0f : x / d; - int q = (int)roundf(y); - q = q < -7 ? -7 : (q > 7 ? 7 : q); - unsigned nib = (unsigned)(q + 8); +template __device__ __forceinline__ void kv_put_tq(u16* c, size_t e, int hd, float x, float norm, bool active) { + int q = tq_nearest(x / norm); + unsigned nib = (unsigned)q; unsigned pair = nib | (__shfl_xor_sync(0xffffffff, nib, 1) << 4); - int w = e % hd; + int we = e % hd; + int w = we & 127; // value within this 128-wide WHT group + int g = we >> 7; // WHT group within the head (0 when hd <= 128) unsigned char* r = (unsigned char*)c + e / hd * (hd / 2 + hd / 16); - if ((w & 1) == 0) r[w / 2] = (unsigned char)pair; - if ((w & 31) == 0) *(u16*)(r + hd / 2 + 2 * (w / 32)) = f2h(d); + if (active && (we & 1) == 0) r[we / 2] = (unsigned char)pair; + // The reference stores norm / ||reconstructed centroids||; without it dequant is systematically low. + // Inactive lanes of a short head width still join the reduction but contribute no centroid energy. + float recon = sqrtf(tq_group_sum(active ? tq_centroid(q) * tq_centroid(q) : 0.f, g)); + if (active && w == 0) *(u16*)(r + hd / 2 + 2 * g) = f2h(norm / fmaxf(recon, 1e-6f)); +} +#endif +__device__ __forceinline__ float warp_min(float v) { + for (int o = 16; o > 0; o >>= 1) v = fminf(v, __shfl_xor_sync(0xffffffff, v, o)); + return v; } -#elif KV_MODE == 1 -// Quantize x into the cache at value offset e; the 32 lanes of the warp hold one 32-value block. +// One value into the cache at value offset e. M is this half's cache mode; BITS matters only for turbo modes. +template __device__ __forceinline__ void kv_put(u16* c, size_t e, int hd, float x) { - float d = warp_max(fabsf(x)) / 127.0f; - int w = e % hd; - char* r = (char*)c + e / hd * (hd + hd / 16); - r[w] = (signed char)(d == 0.0f ? 0.0f : roundf(x / d)); - if ((w & 31) == 0) *(u16*)(r + hd + 2 * (w / 32)) = f2h(d); + if constexpr (M == 3) { + u16 mn_h = f2h(warp_min(x)); + float mn = h2f(mn_h), mx = warp_max(x), dr = fmaxf(0.0f, mx - mn) / 3.0f; + u16 d_h = f2h(dr); + float d = h2f(d_h), y = d == 0.0f ? 0.0f : (x - mn) / d; + int q = (int)roundf(y); + q = q < 0 ? 0 : (q > 3 ? 3 : q); + unsigned uq = (unsigned)q; + unsigned packed = uq + | (__shfl_xor_sync(0xffffffff, uq, 1) << 2) + | (__shfl_xor_sync(0xffffffff, uq, 2) << 4) + | (__shfl_xor_sync(0xffffffff, uq, 3) << 6); + int w = e % hd; + unsigned char* r = (unsigned char*)c + e / hd * (3 * hd / 8); + if ((w & 3) == 0) r[w / 4] = (unsigned char)packed; + if ((w & 31) == 0) { + *(u16*)(r + hd / 4 + 2 * (w / 32)) = d_h; + *(u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32)) = mn_h; + } + } else if constexpr (M == 2) { + // The 32 lanes of the warp hold one 32-value block. + float d = warp_max(fabsf(x)) / 7.0f; + float y = d == 0.0f ? 0.0f : x / d; + int q = (int)roundf(y); + q = q < -7 ? -7 : (q > 7 ? 7 : q); + unsigned nib = (unsigned)(q + 8); + unsigned pair = nib | (__shfl_xor_sync(0xffffffff, nib, 1) << 4); + int w = e % hd; + unsigned char* r = (unsigned char*)c + e / hd * (hd / 2 + hd / 16); + if ((w & 1) == 0) r[w / 2] = (unsigned char)pair; + if ((w & 31) == 0) *(u16*)(r + hd / 2 + 2 * (w / 32)) = f2h(d); + } else if constexpr (M == 1) { + // The 32 lanes of the warp hold one 32-value block. + float d = warp_max(fabsf(x)) / 127.0f; + int w = e % hd; + char* r = (char*)c + e / hd * (hd + hd / 16); + r[w] = (signed char)(d == 0.0f ? 0.0f : roundf(x / d)); + if ((w & 31) == 0) *(u16*)(r + hd + 2 * (w / 32)) = f2h(d); + } else { + c[e] = f2h(x); + } } + +// Single store entry for both halves: `norm` is each group's L2 norm under turbo modes, ignored otherwise. +template +__device__ __forceinline__ void kv_store_one(u16* c, size_t e, int hd, float x, float norm) { +#if K_MODE >= 4 || V_MODE >= 4 + if constexpr (M >= 4) kv_put_tq(c, e, hd, x, norm); + else kv_put(c, e, hd, x); #else -__device__ __forceinline__ void kv_put(u16* c, size_t e, int, float x) { c[e] = f2h(x); } + kv_put(c, e, hd, x); #endif +} // Store `total` values (consecutive tokens of n each, n a multiple of 32) starting at position step[0]. extern "C" __global__ void kv_store(const float* k, const float* v, u16* kc, u16* vc, int n, int total, const int* step, - int hd) { + int hd) { int i = blockIdx.x * blockDim.x + threadIdx.x, pos = step[0]; - if (i < total) { kv_put(kc, (size_t)pos * n + i, hd, k[i]); kv_put(vc, (size_t)pos * n + i, hd, v[i]); } + if (i < total) { + kv_store_one(kc, (size_t)pos * n + i, hd, k[i], 1.0f); + kv_store_one(vc, (size_t)pos * n + i, hd, v[i], 1.0f); + } +} + +// One 128-value KV block per 128-thread block (2 blocks per 256-wide row): unit-L2 normalize, signed-Walsh +// rotate, Lloyd-Max quantize. Each half uses its own mode and bit width; a non-turbo half stores its raw value. +// Defined for every mode combination so the eager kernel loader always finds the symbol. +extern "C" __global__ void __launch_bounds__(128) kv_store_turbo(const float* k, const float* v, u16* kc, u16* vc, + int n, int total, const int* step, int hd) { +#if K_MODE >= 4 || V_MODE >= 4 + __shared__ float kq[128], vq[128]; + int t = threadIdx.x; + size_t e = (size_t)blockIdx.x * 128 + t; + float kv = k[e], vv = v[e]; + kq[t] = kv; vq[t] = vv; + __syncthreads(); + float sk = 1.0f, sv = 1.0f; + if constexpr (K_MODE >= 4) sk = sqrtf(block_sum(kq[t] * kq[t])); + if constexpr (V_MODE >= 4) sv = sqrtf(block_sum(vq[t] * vq[t])); + if constexpr (K_MODE >= 4 || V_MODE >= 4) { + if (t < 32) { + float4 a = make_float4(kq[4*t], kq[4*t+1], kq[4*t+2], kq[4*t+3]); + float4 b = make_float4(vq[4*t], vq[4*t+1], vq[4*t+2], vq[4*t+3]); + if constexpr (K_MODE >= 4) tq_wht4(a, t, false); + if constexpr (V_MODE >= 4) tq_wht4(b, t, false); + kq[4*t]=a.x; kq[4*t+1]=a.y; kq[4*t+2]=a.z; kq[4*t+3]=a.w; + vq[4*t]=b.x; vq[4*t+1]=b.y; vq[4*t+2]=b.z; vq[4*t+3]=b.w; + } + __syncthreads(); + } + size_t off = (size_t)step[0] * n + e; + if constexpr (K_MODE >= 4) kv_put_tq(kc, off, hd, kq[t], sk); + else kv_store_one(kc, off, hd, kv, sk); + __syncthreads(); + if constexpr (V_MODE >= 4) kv_put_tq(vc, off, hd, vq[t], sv); + else kv_store_one(vc, off, hd, vv, sv); +#endif } -// grid = rows (heads of n), block 256: rms_norm (out rows of n) then rope_neox of the head, in one launch with the same +// grid = rows (heads of n), block 256 (or 128 when n <= 128): rms_norm (out rows of n) then rope_neox of the head, in one launch with the same // bits. Head r belongs to token r / per. With kc, then kv_store of the head and its v (v rows of n, like out). // Blocks below qrows do the q heads (from qx etc., no cache store); the rest do x etc. __device__ __forceinline__ double rope_f(float base, int i, int n_rot) { return pow((double)base, -2.0 * i / n_rot); } @@ -2326,11 +4434,21 @@ __device__ __forceinline__ double rope_f(float base, int i, int n_rot) { return extern "C" __global__ void rope_freq(double* fr, float base, int n_rot) { for (int i = threadIdx.x; i < n_rot / 2; i += blockDim.x) fr[i] = rope_f(base, i, n_rot); } -// fr: the rope_freq table of base and n_rot, or null to compute it here. +// cs[t * (n_rot / 2) + i] = (sin, cos) of angle i of token t, as rms_norm_rope computes them (tok and pos as there): +// once a token instead of once a head (the f64 sincos is slow on consumer cards). +extern "C" __global__ void rope_cs(float2* cs, const int* step, const u64* kvt, int nt, int n_rot, const double* fr) { + int half = n_rot / 2, e = blockIdx.x * blockDim.x + threadIdx.x; + if (e >= nt * half) return; + int tok = e / half, pos = kvt ? step[2 * tok] : step[0] + tok; + double ds, dc; + sincos((double)pos * fr[e % half], &ds, &dc); + cs[e] = make_float2((float)ds, (float)dc); +} +// fr: the rope_freq table of base and n_rot, or null to compute it here. cs: the rope_cs table of these tokens, or null. extern "C" __global__ void rms_norm_rope(const float* x, int x_stride, const float* w, float* out, int n, float eps, int per, int n_rot, const int* step, float base, const float* v, u16* kc, u16* vc, int qrows, const float* qx, int q_stride, const float* qw, float* qo, int qper, - const double* fr, const u64* kvt) { + const double* fr, const u64* kvt, const float2* cs) { int b = (int)blockIdx.x - qrows; bool store = kc || kvt; if (b < 0) { b = blockIdx.x; x = qx; x_stride = q_stride; w = qw; out = qo; per = qper; store = false; } @@ -2345,10 +4463,14 @@ extern "C" __global__ void rms_norm_rope(const float* x, int x_stride, const flo __syncthreads(); int i = threadIdx.x, half = n_rot / 2; if (i < half) { - double theta = (double)pos * (fr ? fr[i] : rope_f(base, i, n_rot)); - double ds, dc; - sincos(theta, &ds, &dc); - float sn = (float)ds, c = (float)dc; + float sn, c; + if (cs) { float2 v = cs[tok * half + i]; sn = v.x; c = v.y; } + else { + double theta = (double)pos * (fr ? fr[i] : rope_f(base, i, n_rot)); + double ds, dc; + sincos(theta, &ds, &dc); + sn = (float)ds; c = (float)dc; + } float a = o[i], b = o[i + half]; o[i] = a * c - b * sn; o[i + half] = a * sn + b * c; @@ -2358,7 +4480,50 @@ extern "C" __global__ void rms_norm_rope(const float* x, int x_stride, const flo if (kvt) { kc = (u16*)kvt[2 * tok]; vc = (u16*)kvt[2 * tok + 1]; } const float* vr = v + (size_t)b * n; size_t e = ((size_t)pos * per + b % per) * n; - for (int j = threadIdx.x; j < n; j += 256) { kv_put(kc, e + j, n, o[j]); kv_put(vc, e + j, n, vr[j]); } +#if K_MODE >= 4 || V_MODE >= 4 + // The general-engine attention kernels rotate Q with the same WHT, so the cached K/V must be rotated too. + // Stage one head in shared memory, rotate each 128-value group with one warp, then quantize with a norm + // per group. All 256 threads take part in the reductions: at n = 128 the upper half wraps onto the same + // values, and n = 512 is handled as two full 256-thread chunks. + __shared__ float tqk[512], tqv[512]; + for (int j = threadIdx.x; j < n; j += 256) { tqk[j] = o[j]; tqv[j] = vr[j]; } + __syncthreads(); + if (threadIdx.x < 32) { + for (int gi = 0; gi < n / 128; gi++) { + int base = gi * 128 + 4 * threadIdx.x; + if constexpr (K_MODE >= 4) { + float4 q = make_float4(tqk[base], tqk[base + 1], tqk[base + 2], tqk[base + 3]); + tq_wht4(q, threadIdx.x, false); + tqk[base] = q.x; tqk[base + 1] = q.y; tqk[base + 2] = q.z; tqk[base + 3] = q.w; + } + if constexpr (V_MODE >= 4) { + float4 q = make_float4(tqv[base], tqv[base + 1], tqv[base + 2], tqv[base + 3]); + tq_wht4(q, threadIdx.x, false); + tqv[base] = q.x; tqv[base + 1] = q.y; tqv[base + 2] = q.z; tqv[base + 3] = q.w; + } + } + } + __syncthreads(); + { + int chunks = n <= 256 ? 1 : n / 256; + for (int ch = 0; ch < chunks; ch++) { + int j = ch * 256 + threadIdx.x; + if (n == 128) j &= 127; + int g = j >> 7; + float xk = tqk[j], xv = tqv[j]; + float nk = 1.0f, nv = 1.0f; + if constexpr (K_MODE >= 4) nk = sqrtf(tq_group_sum(xk * xk, g)); + if constexpr (V_MODE >= 4) nv = sqrtf(tq_group_sum(xv * xv, g)); + kv_store_one(kc, e + j, n, xk, nk); + kv_store_one(vc, e + j, n, xv, nv); + } + } +#else + for (int j = threadIdx.x; j < n; j += 256) { + kv_store_one(kc, e + j, n, o[j], 1.0f); + kv_store_one(vc, e + j, n, vr[j], 1.0f); + } +#endif } #define INFINITY __int_as_float(0x7f800000) @@ -2377,56 +4542,76 @@ template __device__ __forceinline__ void ldh_raw(const u16* p, unsigne } } // PER consecutive cache values from value offset off (off a multiple of PER, PER <= 32) as f16 words, like ldh_raw. -template __device__ __forceinline__ void ldkv(const u16* c, size_t off, int hd, unsigned* o) { -#if KV_MODE == 3 - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); - float d = h2f(*(const u16*)(r + hd / 4 + 2 * (w / 32))); - float mn = h2f(*(const u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32))); - for (int i = 0; i < PER / 2; i++) { - int wi = w + 2 * i; - unsigned b = r[wi / 4]; - int s = (b >> (2 * (wi & 2))) & 15; - int q0 = s & 3, q1 = s >> 2; - o[i] = (unsigned)f2h(fmaf((float)q0, d, mn)) | ((unsigned)f2h(fmaf((float)q1, d, mn)) << 16); - } -#elif KV_MODE == 2 - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); - float d = h2f(*(const u16*)(r + hd / 2 + 2 * (w / 32))); - for (int i = 0; i < PER / 2; i++) { - unsigned b = r[w / 2 + i]; - int q0 = (int)(b & 15u) - 8, q1 = (int)(b >> 4) - 8; - o[i] = (unsigned)f2h((float)q0 * d) | ((unsigned)f2h((float)q1 * d) << 16); - } -#elif KV_MODE == 1 - int w = off % hd; - const char* r = (const char*)c + off / hd * (hd + hd / 16); - unsigned d = *(const u16*)(r + hd + 2 * (w / 32)) * 0x10001u; // scale in both halves - // Byte q (flipped to q + 128) under exponent byte 0x64 is the f16 1024 + q + 128; minus 1152 gives q exactly, and - // q * d rounded once to f16 equals f2h((float)q * d). - auto deq = [&](unsigned x, unsigned sel) { - unsigned h = __byte_perm(x ^ 0x80808080u, 0x64646464u, sel), r; - asm("sub.rn.f16x2 %0, %1, %2;" : "=r"(h) : "r"(h), "r"(0x64806480u)); - asm("mul.rn.f16x2 %0, %1, %2;" : "=r"(r) : "r"(h), "r"(d)); - return r; - }; - if (PER % 8 == 0 && hd % 128 == 0) { // rows 8-byte aligned - for (int i = 0; i < PER / 8; i++) { - uint2 x = ((const uint2*)(r + w))[i]; - o[4 * i] = deq(x.x, 0x4140); o[4 * i + 1] = deq(x.x, 0x4342); o[4 * i + 2] = deq(x.y, 0x4140); o[4 * i + 3] = deq(x.y, 0x4342); +template __device__ __forceinline__ void ldkv(const u16* c, size_t off, int hd, unsigned* o) { + if constexpr (M >= 4) { + // Dequantize to the rotated domain; Q is rotated in attention, so no inverse here. + int we = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); + float norm = h2f(*(const u16*)(r + hd / 2 + 2 * (we >> 7))); + for (int i = 0; i < PER / 2; i++) { + unsigned b = r[we / 2 + i]; + int q0 = b & 15, q1 = b >> 4; + o[i] = (unsigned)f2h(tq_centroid(q0) * norm) | ((unsigned)f2h(tq_centroid(q1) * norm) << 16); } - } else if constexpr (PER % 4 == 0) { - for (int i = 0; i < PER / 4; i++) { - unsigned x = ((const unsigned*)(r + w))[i]; - o[2 * i] = deq(x, 0x4140); o[2 * i + 1] = deq(x, 0x4342); + } else if constexpr (M == 3) { + int w = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); + float d = h2f(*(const u16*)(r + hd / 4 + 2 * (w / 32))); + float mn = h2f(*(const u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32))); + for (int i = 0; i < PER / 2; i++) { + int wi = w + 2 * i; + unsigned b = r[wi / 4]; + int s = (b >> (2 * (wi & 2))) & 15; + int q0 = s & 3, q1 = s >> 2; + o[i] = (unsigned)f2h(fmaf((float)q0, d, mn)) | ((unsigned)f2h(fmaf((float)q1, d, mn)) << 16); } - } else { - for (int i = 0; i < PER / 2; i++) o[i] = deq(*(const u16*)(r + w + 2 * i), 0x4140); - } + } else if constexpr (M == 2) { + int w = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); + float d = h2f(*(const u16*)(r + hd / 2 + 2 * (w / 32))); + for (int i = 0; i < PER / 2; i++) { + unsigned b = r[w / 2 + i]; + int q0 = (int)(b & 15u) - 8, q1 = (int)(b >> 4) - 8; + o[i] = (unsigned)f2h((float)q0 * d) | ((unsigned)f2h((float)q1 * d) << 16); + } + } else if constexpr (M == 1) { + int w = off % hd; + const char* r = (const char*)c + off / hd * (hd + hd / 16); + unsigned d = *(const u16*)(r + hd + 2 * (w / 32)) * 0x10001u; // scale in both halves + // Byte q (flipped to q + 128) under exponent byte 0x64 is the f16 1024 + q + 128; minus 1152 gives q exactly, and + // q * d rounded once to f16 equals f2h((float)q * d). + auto deq = [&](unsigned x, unsigned sel) { + unsigned h = __byte_perm(x ^ 0x80808080u, 0x64646464u, sel), r; +#if STRATA_HIP + // Same two f16 lanes without : a 2-element _Float16 vector (the ISA's packed f16 sub/mul). + typedef _Float16 f16x2 __attribute__((ext_vector_type(2))); + unsigned c64 = 0x64806480u; + f16x2 hh = *(f16x2*)&h, cc = *(f16x2*)&c64, dd = *(f16x2*)&d, rr; + rr[0] = (hh[0] - cc[0]) * dd[0]; + rr[1] = (hh[1] - cc[1]) * dd[1]; + r = *(unsigned*)&rr; #else - ldh_raw(c + off, o); + asm("sub.rn.f16x2 %0, %1, %2;" : "=r"(h) : "r"(h), "r"(0x64806480u)); + asm("mul.rn.f16x2 %0, %1, %2;" : "=r"(r) : "r"(h), "r"(d)); #endif + return r; + }; + if (PER % 8 == 0 && hd % 128 == 0) { // rows 8-byte aligned + for (int i = 0; i < PER / 8; i++) { + uint2 x = ((const uint2*)(r + w))[i]; + o[4 * i] = deq(x.x, 0x4140); o[4 * i + 1] = deq(x.x, 0x4342); o[4 * i + 2] = deq(x.y, 0x4140); o[4 * i + 3] = deq(x.y, 0x4342); + } + } else if constexpr (PER % 4 == 0) { + for (int i = 0; i < PER / 4; i++) { + unsigned x = ((const unsigned*)(r + w))[i]; + o[2 * i] = deq(x, 0x4140); o[2 * i + 1] = deq(x, 0x4342); + } + } else { + for (int i = 0; i < PER / 2; i++) o[i] = deq(*(const u16*)(r + w + 2 * i), 0x4140); + } + } else { + ldh_raw(c + off, o); + } } // f16 value d of words loaded by ldh_raw. __device__ __forceinline__ float hraw(const unsigned* r, int d) { return h2f((u16)(r[d >> 1] >> (16 * (d & 1)))); } @@ -2458,36 +4643,69 @@ template __device__ __forceinline__ float warp_sum_scatte #define LLAMA_NTH 6 __device__ __forceinline__ float rh(float x) { return h2f(f2h(x)); } -// Scalar KV element load matching GLSL ldkv(). -__device__ __forceinline__ float ldkv1(const u16* c, size_t off, int hd) { -#if KV_MODE == 3 - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); - unsigned b = r[w / 4]; - float d = h2f(*(const u16*)(r + hd / 4 + 2 * (w / 32))); - float mn = h2f(*(const u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32))); - int q = (b >> (2 * (w & 3))) & 3; - return rh(fmaf((float)q, d, mn)); -#elif KV_MODE == 2 - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); - unsigned b = r[w / 2]; - float d = h2f(*(const u16*)(r + hd / 2 + 2 * (w / 32))); - int q = (int)((w & 1) == 0 ? (b & 15u) : (b >> 4)) - 8; - return rh((float)q * d); -#elif KV_MODE == 1 - int w = off % hd; - const signed char* r = (const signed char*)c + off / hd * (hd + hd / 16); - float d = h2f(*(const u16*)(r + hd + 2 * (w / 32))); - return rh((float)r[w] * d); -#else - return h2f(c[off]); -#endif +// Scalar KV element load matching GLSL ldkv(): value w (0 <= w < hd) of cache row `row`, hd values a row. +template __device__ __forceinline__ float ldkv1_at(const u16* c, size_t row, unsigned w, int hd) { + if constexpr (M >= 4) { + const unsigned char* r = (const unsigned char*)c + row * (hd / 2 + hd / 16); + float norm = h2f(*(const u16*)(r + hd / 2 + 2 * (w >> 7))); + unsigned b = r[w / 2]; + int q = (w & 1) == 0 ? (int)(b & 15u) : (int)(b >> 4); + return rh(tq_centroid(q) * norm); + } else if constexpr (M == 3) { + const unsigned char* r = (const unsigned char*)c + row * (3 * hd / 8); + unsigned b = r[w / 4]; + float d = h2f(*(const u16*)(r + hd / 4 + 2 * (w / 32))); + float mn = h2f(*(const u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32))); + int q = (b >> (2 * (w & 3))) & 3; + return rh(fmaf((float)q, d, mn)); + } else if constexpr (M == 2) { + const unsigned char* r = (const unsigned char*)c + row * (hd / 2 + hd / 16); + unsigned b = r[w / 2]; + float d = h2f(*(const u16*)(r + hd / 2 + 2 * (w / 32))); + int q = (int)((w & 1) == 0 ? (b & 15u) : (b >> 4)) - 8; + return rh((float)q * d); + } else if constexpr (M == 1) { + const signed char* r = (const signed char*)c + row * (hd + hd / 16); + float d = h2f(*(const u16*)(r + hd + 2 * (w / 32))); + return rh((float)r[w] * d); + } else { + return h2f(c[row * hd + w]); + } +} +// The same value by its flat offset. On a quantized cache that is `off / hd` and `off % hd`, a division by the runtime +// hd for every value (the card has no integer divide), so a kernel that walks the rows calls ldkv1_at: ink_attn on a +// q4 cache took 2.03 ms a launch at 29k positions through this one and takes 0.98 (24 heads on 8, RTX 3060 Ti). +template __device__ __forceinline__ float ldkv1(const u16* c, size_t off, int hd) { + if constexpr (M == 0) return h2f(c[off]); + else return ldkv1_at(c, off / hd, (unsigned)(off % hd), hd); } -// One block of 128 per (row, tok) of w values (w at most 128, w % 32 == 0 when KV_MODE > 0 and dst != 0). +// One block of 128 per (row, tok) of w values (w at most 128, w % 32 == 0 when a side is quantized and dst != 0). +#if K_MODE >= 4 || V_MODE >= 4 +template __device__ __forceinline__ void ink_tq_store(u16* dst, size_t dat, int t, int w, float v, float* tq, float norm, bool active) { + tq[t] = v; + __syncthreads(); + if (t < 32) { + if (w == 64) { // one WHT-64 block: two dims per lane + float2 q = make_float2(tq[2*t], tq[2*t+1]); + tq_wht2(q, t, false); + tq[2*t]=q.x; tq[2*t+1]=q.y; + } else if (w == 128) { // one WHT-128 block: four dims per lane + float4 q = make_float4(tq[4*t], tq[4*t+1], tq[4*t+2], tq[4*t+3]); + tq_wht4(q, t, false); + tq[4*t]=q.x; tq[4*t+1]=q.y; tq[4*t+2]=q.z; tq[4*t+3]=q.w; + } + // w < 64 has no WHT group: ink_attn leaves Q unrotated for it too. + } + __syncthreads(); + kv_put_tq(dst, dat, w, tq[t], norm, active); +} +#endif extern "C" __global__ void ink_clip(float* x, const float* scale, int w, float thr, float eps, float mul, u16* dst, - int dst_at0, int dst_ring, int pos0, float log_alpha, float log_floor, const int* pos_ptr) { + int dst_at0, int dst_ring, int pos0, float log_alpha, float log_floor, const int* pos_ptr) { +#if K_MODE >= 4 || V_MODE >= 4 + __shared__ float tq[128]; +#endif int t = threadIdx.x, row = blockIdx.x, tok = blockIdx.y, rows = gridDim.x; size_t at = ((size_t)tok * rows + row) * w + t, sc_at = (size_t)row * w + t; float v = 0.f; @@ -2498,22 +4716,36 @@ extern "C" __global__ void ink_clip(float* x, const float* scale, int w, float t float eff_mul = mul; if (log_alpha != 0.f) eff_mul *= 1.f + log_alpha * logf(fmaxf((float)(eff_pos0 + tok + 1) / log_floor, 1.f)); float f = (thr > 0.f ? fminf(thr / (sqrtf(ss) + 1e-6f), 1.f) : 1.f / sqrtf(ss / (float)w + eps)) * eff_mul; - if (t < w) { - v *= f; - x[at] = v; - if (dst) { - size_t dst_pos = (size_t)((eff_dst_at0 + tok) % dst_ring); - size_t dat = (dst_pos * rows + row) * w + t; - kv_put(dst, dat, w, v); + if (t < w) { v *= f; x[at] = v; } + if (dst) { + size_t dst_pos = (size_t)((eff_dst_at0 + tok) % dst_ring); + size_t dat = (dst_pos * rows + row) * w + t; + bool active = t < w; + // thr > 0 selects the K clip, otherwise the V clip; each half has its own cache mode. + // Turbo lanes past w still join the group reduction (it has block barriers) but write nothing. + if (thr > 0.f) { +#if K_MODE >= 4 + ink_tq_store(dst, dat, t, w, v, tq, sqrtf(ss) * f, active); +#else + if (active) kv_store_one(dst, dat, w, v, 1.0f); +#endif + } else { +#if V_MODE >= 4 + ink_tq_store(dst, dat, t, w, v, tq, sqrtf(ss) * f, active); +#else + if (active) kv_store_one(dst, dat, w, v, 1.0f); +#endif } } } -// Attention of one token in two launches. Supports KV_MODE 0/1/2/3 via ldkv1(). -extern "C" __global__ void ink_attn(const float* q, const float* r, const float* sink, const u16* k, const u16* v, - const float* bias, float* sc, int rows, int at, int ring, int nkv, int hd, int nr, int ext, const int* pos_ptr) { +// Attention of one token in two launches. Supports KV_MODE 0/1/2/3 via ldkv1_at(). +template +__device__ __forceinline__ void ink_attn_scalar(const float* q, const float* r, const float* sink, const u16* k, const u16* v, + const float* bias, float* sc, int rows, int at, int ring, int nkv, int runtime_hd, int nr, int ext, const int* pos_ptr) { + const int hd = HEAD == 0 ? runtime_hd : HEAD; __shared__ float qs[128], ps[64], acc[128]; - int h = blockIdx.x, kh = h / (gridDim.x / nkv), kw = nkv * hd, t = threadIdx.x, lane = t & 31; + int h = blockIdx.x, kh = h / (gridDim.x / nkv), t = threadIdx.x, lane = t & 31; if (pos_ptr) { int pos = *pos_ptr; rows = min(pos + 1, ring); @@ -2522,12 +4754,26 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* int i0 = blockIdx.y * 64, n = i0 < rows ? min(64, rows - i0) : 0; if (t < hd) qs[t] = q[h * hd + t]; __syncthreads(); - float scale = 1.f / sqrtf((float)hd); +#if K_MODE >= 4 + // Rotate Q into the KV domain; the scores below are = . + for (int g = 0; g < hd / 128; g++) { + int base = g * 128 + 4 * t; + if (t < 32) { + float4 v = make_float4(qs[base], qs[base+1], qs[base+2], qs[base+3]); + tq_wht4(v, t, false); + qs[base]=v.x; qs[base+1]=v.y; qs[base+2]=v.z; qs[base+3]=v.w; + } + } + if (hd == 64 && t < 32) { float2 v = make_float2(qs[2*t], qs[2*t+1]); tq_wht2(v, t, false); qs[2*t]=v.x; qs[2*t+1]=v.y; } + __syncthreads(); +#endif + // Keep the runtime scale calculation when the head stride is specialized. + float scale = 1.f / sqrtf((float)runtime_hd); for (int j = t >> 5; j < n; j += 4) { int i = i0 + j, dist = at - i < 0 ? at - i + rows : at - i; - size_t ko = (size_t)i * kw + kh * hd; + size_t kr = (size_t)i * nkv + kh; // the cache row of this key and head: no division a value to find it float d = 0.f; - for (int c = lane; c < hd; c += 32) d += qs[c] * ldkv1(k, ko + c, hd); + for (int c = lane; c < hd; c += 32) d += qs[c] * ldkv1_at(k, kr, c, hd); d *= scale; if (dist < ext) for (int c = lane; c < nr; c += 32) d += r[h * nr + c] * bias[dist * nr + c]; d = warp_sum(d); @@ -2541,22 +4787,206 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* __syncthreads(); int c = t % hd, parts = 128 / hd; float a = 0.f; - for (int j = t / hd; j < n; j += parts) a += ps[j] * ldkv1(v, (size_t)(i0 + j) * kw + kh * hd + c, hd); + size_t vr = (size_t)(i0 + t / hd) * nkv + kh; // the cache row of this thread's first key; its next key is parts keys on + for (int j = t / hd; j < n; j += parts, vr += parts * nkv) a += ps[j] * ldkv1_at(v, vr, c, hd); acc[t] = a; __syncthreads(); - float* o = sc + ((size_t)h * gridDim.y + blockIdx.y) * (hd + 2); - if (t < hd) { - float s = 0.f; - for (int p = 0; p < parts; p++) s += acc[p * hd + t]; - o[2 + t] = s; + float* o = sc + ((size_t)h * gridDim.y + blockIdx.y) * (hd + 2); +#if V_MODE >= 4 + if (t < hd) { + float s = 0.f; + for (int p = 0; p < parts; p++) s += acc[p * hd + t]; + acc[t] = s; + } + __syncthreads(); + // Only the attention output is inverse-rotated: one WHT per 128-value group instead of one per KV load. + // The unrotated copy must not overwrite the rotated output for lanes that did not take part in the WHT. + if (hd >= 128) { + for (int g = 0; g < hd / 128; g++) { + int base = g * 128 + 4 * t; + if (t < 32) { + float4 v = make_float4(acc[base], acc[base+1], acc[base+2], acc[base+3]); + tq_wht4(v, t, true); + o[2+base]=v.x; o[2+base+1]=v.y; o[2+base+2]=v.z; o[2+base+3]=v.w; + } + } + } else if (hd == 64 && t < 32) { float2 v = make_float2(acc[2*t], acc[2*t+1]); tq_wht2(v, t, true); o[2+2*t]=v.x; o[2+2*t+1]=v.y; } + else if (t < hd) o[2 + t] = acc[t]; +#else + if (t < hd) { + float s = 0.f; + for (int p = 0; p < parts; p++) s += acc[p * hd + t]; + o[2 + t] = s; + } +#endif + if (t == 0) { + float z = 0.f; + for (int j = 0; j < n; j++) z += ps[j]; + o[0] = mx; + o[1] = z; + } +} + +extern "C" __global__ void ink_attn(const float* q, const float* r, const float* sink, const u16* k, const u16* v, + const float* bias, float* sc, int rows, int at, int ring, int nkv, int hd, int nr, int ext, const int* pos_ptr) { + ink_attn_scalar<0>(q, r, sink, k, v, bias, sc, rows, at, ring, nkv, hd, nr, ext, pos_ptr); +} + +#if K_MODE == 1 && V_MODE == 1 +extern "C" __global__ void ink_attn_q8_hd128(const float* q, const float* r, const float* sink, const u16* k, const u16* v, + const float* bias, float* sc, int rows, int at, int ring, int nkv, int hd, int nr, int ext, const int* pos_ptr) { + ink_attn_scalar<128>(q, r, sink, k, v, bias, sc, rows, at, ring, nkv, hd, nr, ext, pos_ptr); +} +#endif + +#if KV_MODE == 0 +// Decode attention for head_dim 128, one query per head, restructured for bandwidth. A 128-thread block owns 128 key +// positions and stages their K rows in shared memory with coalesced 16-byte loads; lane i of warp w scores key +// 32w + i with sixteen 16-byte loads and 128 FMAs, so there is no shuffle per key (one block max and one block sum +// per 128 keys), and V is read 8 bytes a lane, one key at a time, which is coalesced as it is. The kernel above walks +// one key at a time through ldkv1 (a 2-byte load per lane per element) and reads K/V at about 95 GB/s of the card's +// 360: 8.4 ms a token at 24.5k positions, and most of the 21 ms it takes at 200k. +extern "C" __global__ void __launch_bounds__(128) ink_attn_128(const float* q, const float* r, const float* sink, + const u16* k, const u16* v, const float* bias, float* sc, int rows, int at, int ring, int nkv, int hd, + int nr, int ext, const int* pos_ptr) { + constexpr int HD = 128, PQ = HD + 8; + __shared__ __align__(16) float qs[HD], rs[32], lg[128], ac[4][HD]; + __shared__ __align__(16) u16 ks[128 * PQ]; + int h = blockIdx.x, kh = h / (gridDim.x / nkv), kw = nkv * HD; + int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + if (pos_ptr) { int pos = *pos_ptr; rows = min(pos + 1, ring); at = pos % ring; } + int i0 = blockIdx.y * 128, n = i0 < rows ? min(128, rows - i0) : 0; + float* o = sc + ((size_t)h * gridDim.y + blockIdx.y) * (HD + 2); + if (n == 0) { // a chunk past the keys: a neutral partial for the merge (exp(-3e38) is 0) + if (tid < HD) o[2 + tid] = 0.f; + if (tid == 0) { o[0] = -3.0e38f; o[1] = 0.f; } + return; + } + if (tid < HD) qs[tid] = q[h * HD + tid] * rsqrtf((float)HD); + if (tid < nr) rs[tid] = r[h * nr + tid]; + for (int i = tid; i < 128 * 16; i += 128) { + int row = i >> 4, part = i & 15; + uint4 x = make_uint4(0u, 0u, 0u, 0u); + if (row < n) x = *(const uint4*)(k + (size_t)(i0 + row) * kw + kh * HD + part * 8); + *(uint4*)(ks + row * PQ + part * 8) = x; + } + __syncthreads(); + int i = i0 + warp * 32 + lane; + float l = -3.0e38f; + if (i < i0 + n) { + const u16* kr = ks + (warp * 32 + lane) * PQ; + float d = 0.f; + for (int m = 0; m < HD / 8; m++) { + uint4 w = *(const uint4*)(kr + 8 * m); + float2 a = ink_h2f2(w.x), b = ink_h2f2(w.y), c = ink_h2f2(w.z), e = ink_h2f2(w.w); + d += qs[8 * m + 0] * a.x + qs[8 * m + 1] * a.y + qs[8 * m + 2] * b.x + qs[8 * m + 3] * b.y + + qs[8 * m + 4] * c.x + qs[8 * m + 5] * c.y + qs[8 * m + 6] * e.x + qs[8 * m + 7] * e.y; + } + int dist = at - i; if (dist < 0) dist += rows; + if (dist < ext) for (int c = 0; c < nr; c++) d += rs[c] * bias[(size_t)dist * nr + c]; + l = d - sink[h]; + } + float mx = block_max(l); + float p = i < i0 + n ? expf(l - mx) : 0.f; + lg[tid] = p; + float z = block_sum(p); + __syncthreads(); + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + for (int j = warp; j < n; j += 4) { + float pj = lg[j]; + uint2 vw = *(const uint2*)(v + (size_t)(i0 + j) * kw + kh * HD + 4 * lane); + float2 v01 = ink_h2f2(vw.x), v23 = ink_h2f2(vw.y); + a0 += pj * v01.x; a1 += pj * v01.y; a2 += pj * v23.x; a3 += pj * v23.y; + } + *(float4*)&ac[warp][4 * lane] = make_float4(a0, a1, a2, a3); + __syncthreads(); + if (tid < HD) o[2 + tid] = ac[0][tid] + ac[1][tid] + ac[2][tid] + ac[3][tid]; + if (tid == 0) { o[0] = mx; o[1] = z; } +} +#else +// A quantized KV cache keeps the scalar kernel: this entry point is never selected (see ink_attn in cuda/mod.rs). +extern "C" __global__ void __launch_bounds__(128) ink_attn_128(const float*, const float*, const float*, const u16*, + const u16*, const float*, float*, int, int, int, int, int, int, int, const int*) { __trap(); } +#endif + +#if K_MODE == 2 && V_MODE == 2 +// ink_attn_128 on a q4 cache, whose row of 128 values is 72 bytes: the nibbles, then the four block scales. A 128-thread +// block owns 128 key positions and stages their K rows in shared memory with coalesced 8-byte loads; lane i of warp w +// scores key 32w + i from 4-byte words of 8 nibbles, so there is no shuffle per key, and V is read 2 bytes (4 values) a +// lane, one key at a time. Every value is the f16 ldkv1_at gives (rh of nibble times block scale): the output differs +// from ink_attn's only by the order of the sums. ink_attn reads one nibble a lane a step, with a byte load, a scale +// load and the index arithmetic for each: 0.98 ms a launch at 29k positions (24 heads on 8, RTX 3060 Ti) against +// 0.29 here. +extern "C" __global__ void __launch_bounds__(128) ink_attn_128_q4(const float* q, const float* r, const float* sink, + const u16* k, const u16* v, const float* bias, float* sc, int rows, int at, int ring, int nkv, int hd, + int nr, int ext, const int* pos_ptr) { + constexpr int HD = 128, RB = HD / 2 + HD / 16; + __shared__ __align__(16) float qs[HD], rs[32], lg[128], ac[4][HD]; + __shared__ __align__(8) unsigned char ks[128 * RB]; + int h = blockIdx.x, kh = h / (gridDim.x / nkv); + int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + if (pos_ptr) { int pos = *pos_ptr; rows = min(pos + 1, ring); at = pos % ring; } + int i0 = blockIdx.y * 128, n = i0 < rows ? min(128, rows - i0) : 0; + float* o = sc + ((size_t)h * gridDim.y + blockIdx.y) * (HD + 2); + if (n == 0) { // a chunk past the keys: a neutral partial for the merge (exp(-3e38) is 0) + if (tid < HD) o[2 + tid] = 0.f; + if (tid == 0) { o[0] = -3.0e38f; o[1] = 0.f; } + return; + } + if (tid < HD) qs[tid] = q[h * HD + tid] * rsqrtf((float)HD); + if (tid < nr) rs[tid] = r[h * nr + tid]; + // Row kh of key i0 in each cache, and the bytes from one key to the next. + const unsigned char* kb = (const unsigned char*)k + ((size_t)i0 * nkv + kh) * RB; + const unsigned char* vb = (const unsigned char*)v + ((size_t)i0 * nkv + kh) * RB; + size_t step = (size_t)nkv * RB; + for (int i = tid; i < 128 * (RB / 8); i += 128) { + int row = i / (RB / 8), part = i % (RB / 8); + unsigned long long x = 0; + if (row < n) x = *(const unsigned long long*)(kb + (size_t)row * step + part * 8); + *(unsigned long long*)(ks + row * RB + part * 8) = x; + } + __syncthreads(); + int i = i0 + tid; + float l = -3.0e38f; + if (tid < n) { + const unsigned char* kr = ks + tid * RB; + float d = 0.f; + for (int g = 0; g < HD / 32; g++) { + float s = h2f(*(const u16*)(kr + HD / 2 + 2 * g)); + for (int m = 0; m < 4; m++) { + unsigned w = *(const unsigned*)(kr + 16 * g + 4 * m); + const float* qq = qs + 32 * g + 8 * m; + for (int e = 0; e < 8; e++) d += qq[e] * rh((float)((int)((w >> (4 * e)) & 15u) - 8) * s); + } + } + int dist = at - i; if (dist < 0) dist += rows; + if (dist < ext) for (int c = 0; c < nr; c++) d += rs[c] * bias[(size_t)dist * nr + c]; + l = d - sink[h]; } - if (t == 0) { - float z = 0.f; - for (int j = 0; j < n; j++) z += ps[j]; - o[0] = mx; - o[1] = z; + float mx = block_max(l); + float p = tid < n ? expf(l - mx) : 0.f; + lg[tid] = p; + float z = block_sum(p); + __syncthreads(); + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + for (int j = warp; j < n; j += 4) { + float pj = lg[j]; + const unsigned char* vr = vb + (size_t)j * step; + unsigned w = *(const u16*)(vr + 2 * lane); + float s = h2f(*(const u16*)(vr + HD / 2 + 2 * (lane >> 3))); + a0 += pj * rh((float)((int)(w & 15u) - 8) * s); a1 += pj * rh((float)((int)((w >> 4) & 15u) - 8) * s); + a2 += pj * rh((float)((int)((w >> 8) & 15u) - 8) * s); a3 += pj * rh((float)((int)(w >> 12) - 8) * s); } + *(float4*)&ac[warp][4 * lane] = make_float4(a0, a1, a2, a3); + __syncthreads(); + if (tid < HD) o[2 + tid] = ac[0][tid] + ac[1][tid] + ac[2][tid] + ac[3][tid]; + if (tid == 0) { o[0] = mx; o[1] = z; } } +#else +// Another cache format keeps its kernel: this entry point is never selected (see ink_attn_pick in cuda/mod.rs). +extern "C" __global__ void __launch_bounds__(128) ink_attn_128_q4(const float*, const float*, const float*, const u16*, + const u16*, const float*, float*, int, int, int, int, int, int, int, const int*) { __trap(); } +#endif extern "C" __global__ void ink_attn_merge(const float* sc, const float* gate, float* out, int chunks, int hd) { int h = blockIdx.x, t = threadIdx.x; @@ -2577,8 +5007,8 @@ template __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* sink, const float* gate, const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, const float* bias, float* outp, - int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { - int t = blockIdx.x * 4 + (threadIdx.x >> 5), h = blockIdx.y, lane = threadIdx.x & 31; + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win, int tbase) { + int t = tbase + (threadIdx.x >> 5), h = blockIdx.y, lane = threadIdx.x & 31; if (t >= nt) return; constexpr int HD = 32 * PER; int kh = h / (nh / nkv), kw = nkv * HD; @@ -2586,21 +5016,46 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* int start = (win > 0 && q_pos + 1 > win) ? (q_pos + 1 - win) : 0; float scale = 1.f / sqrtf((float)HD); float qv[PER], acc[PER]; + // The legacy cache uses main's strided lane + 32*j layout for every head size. Only a TurboQuant half uses the + // contiguous four-dims-per-lane layout its WHT sign diagonals are defined on (one group per 128 dims). + // K and V are indexed independently so a mixed cache keeps the f16 half bit-identical to main. +#if K_MODE >= 4 + // A 64-wide WHT group gives each lane two dims; a 128-wide group gives it four. + auto kidx = [&](int j) { if constexpr (PER == 2) return 2 * lane + (j & 1); else return (j >> 2) * 128 + 4 * lane + (j & 3); }; +#else + auto kidx = [&](int j) { return lane + 32 * j; }; +#endif +#if V_MODE >= 4 + auto vidx = [&](int j) { if constexpr (PER == 2) return 2 * lane + (j & 1); else return (j >> 2) * 128 + 4 * lane + (j & 3); }; +#else + auto vidx = [&](int j) { return lane + 32 * j; }; +#endif for (int j = 0; j < PER; j++) { - qv[j] = q[((size_t)t * nh + h) * HD + lane + 32 * j] * scale; + qv[j] = q[((size_t)t * nh + h) * HD + kidx(j)] * scale; acc[j] = 0.f; } +#if K_MODE >= 4 + for (int g = 0; g < PER / 4; g++) { + float4 v = {qv[4*g], qv[4*g+1], qv[4*g+2], qv[4*g+3]}; + tq_wht4(v, lane, false); + qv[4*g]=v.x; qv[4*g+1]=v.y; qv[4*g+2]=v.z; qv[4*g+3]=v.w; + } + if (PER == 2) { float2 v = {qv[0], qv[1]}; tq_wht2(v, lane, false); qv[0]=v.x; qv[1]=v.y; } +#endif float sink_val = sink[(size_t)t * nh + h]; float r_reg = (nr <= 32 && lane < nr) ? r[((size_t)t * nh + h) * nr + lane] : 0.f; float m = 0.f, l = 1.f; + // Row of the key in the old rows: a ring of `ring` rows on a sliding layer, counted (no division a key). + int old_row = win > 0 ? start % ring : start; for (int kp = start; kp <= q_pos; kp++) { bool use_new = kc_new && kp >= pos; const u16* kbuf = use_new ? kc_new : kc; const u16* vbuf = use_new ? vc_new : vc; - size_t row = use_new ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); + size_t row = use_new ? (size_t)(kp - pos) : (size_t)old_row; + if (++old_row == ring) old_row = 0; size_t kbase = row * kw + (size_t)kh * HD; float s = 0.f; - for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + lane + 32 * j, HD); + for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + kidx(j), HD); s = warp_sum(s); int dist = q_pos - kp; float b = 0.f; @@ -2615,14 +5070,24 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* float logit = s + b - sink_val; float mn = fmaxf(m, logit), c = expf(m - mn), e = expf(logit - mn); l = l * c + e; - for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + lane + 32 * j, HD) + acc[j] * c; + for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + vidx(j), HD) + acc[j] * c; m = mn; } float inv = 1.f / l; + float ov[PER]; + for (int j = 0; j < PER; j++) ov[j] = acc[j] * inv; +#if V_MODE >= 4 + for (int g = 0; g < PER / 4; g++) { + float4 v = {ov[4*g], ov[4*g+1], ov[4*g+2], ov[4*g+3]}; + tq_wht4(v, lane, true); + ov[4*g]=v.x; ov[4*g+1]=v.y; ov[4*g+2]=v.z; ov[4*g+3]=v.w; + } + if (PER == 2) { float2 v = {ov[0], ov[1]}; tq_wht2(v, lane, true); ov[0]=v.x; ov[1]=v.y; } +#endif for (int j = 0; j < PER; j++) { - int col = lane + 32 * j; + int col = vidx(j); size_t idx = ((size_t)t * nh + h) * HD + col; - outp[idx] = acc[j] * inv * sigmoid(gate[idx]); + outp[idx] = ov[j] * sigmoid(gate[idx]); } } #define DEF_INK_PREFILL(HD) \ @@ -2631,9 +5096,442 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, \ const float* bias, float* outp, \ int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { \ - ink_attn_prefill_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); \ + ink_attn_prefill_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); \ } DEF_INK_PREFILL(32) DEF_INK_PREFILL(64) DEF_INK_PREFILL(128) +#if KV_MODE == 0 +// Key-parallel prefill attention for hd = 128 and an f16 cache, QPB queries a warp. The old kernel gave a warp one +// (query, head) and walked the keys one at a time: two warp reductions and a dozen shuffles per key. Here the block's +// four warps share a 32-key K/V tile in shared memory, lane i scores key i of the tile (the 128-long dot product is +// its own, no shuffles), and a warp reduces once per tile for the online softmax. QPB=1 is one query a warp (four a +// block), QPB=4 is four a warp (sixteen a block). Same math, summed in another order. Needs nr <= 32 and +// nr % 4 == 0 (the relative-bias rows are read as float4). +__device__ __forceinline__ float ink_warp_max(float v) { + for (int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + return v; +} +template +__device__ void ink_attn_prefill_kp_t(const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + constexpr int HD = 128, PQ = HD + 8, QB = 4 * QPB; + __shared__ __align__(16) u16 ks[32 * PQ], vs[32 * PQ]; + __shared__ __align__(16) float qs[QB][HD], rs[QB][32], ps[QB][32]; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, h = blockIdx.y; + const int t0 = blockIdx.x * QB, qh = warp * QPB; + const int kh = h / (nh / nkv), kw = nkv * HD; + const float scale = 1.f / sqrtf((float)HD); + int start[QPB], qpos[QPB], valid_t[QPB]; + float sk[QPB]; + for (int j = 0; j < QPB; j++) { + const int t = t0 + qh + j; + valid_t[j] = t < nt; + qpos[j] = pos + t; + start[j] = (win > 0 && qpos[j] + 1 > win) ? (qpos[j] + 1 - win) : 0; + sk[j] = 0.f; + if (!valid_t[j]) continue; + const float* qr = q + ((size_t)t * nh + h) * HD; + for (int d = lane; d < HD; d += 32) qs[qh + j][d] = qr[d] * scale; + rs[qh + j][lane] = lane < nr ? r[((size_t)t * nh + h) * nr + lane] : 0.f; + sk[j] = sink[(size_t)t * nh + h]; + } + const int kmax = pos + min(t0 + QB - 1, nt - 1); + const int kmin = (win > 0 && pos + t0 + 1 > win) ? (pos + t0 + 1 - win) : 0; + float m[QPB], l[QPB], acc[QPB][4]; + for (int j = 0; j < QPB; j++) { + m[j] = 0.f; l[j] = 1.f; + for (int i = 0; i < 4; i++) acc[j][i] = 0.f; + } + const int kp_last = qpos[QPB - 1]; + for (int k0 = kmin; k0 <= kmax; k0 += 32) { + __syncthreads(); +#pragma unroll + for (int n = 0; n < 4; n++) { + const int i = tid + n * 128, rr = i >> 4, c = (i & 15) * 8, kp = k0 + rr; + uint4 kv = make_uint4(0, 0, 0, 0), vv = kv; + if (kp <= kmax) { + const bool un = kc_new && kp >= pos; + const size_t row = un ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); + const size_t off = row * kw + (size_t)kh * HD + c; + kv = *(const uint4*)((un ? kc_new : kc) + off); + vv = *(const uint4*)((un ? vc_new : vc) + off); + } + *(uint4*)(ks + rr * PQ + c) = kv; + *(uint4*)(vs + rr * PQ + c) = vv; + } + __syncthreads(); + const int kp = k0 + lane; + const u16* kr = ks + lane * PQ; + uint4 krow[HD / 8]; +#pragma unroll + for (int mm = 0; mm < HD / 8; mm++) krow[mm] = *(const uint4*)(kr + 8 * mm); +#pragma unroll + for (int j = 0; j < QPB; j++) { + if (!valid_t[j]) continue; + const float* qj = qs[qh + j]; + float sd = 0.f; +#pragma unroll + for (int mm = 0; mm < HD / 8; mm++) { + const uint4 w = krow[mm]; + const float2 a = ink_h2f2(w.x), b = ink_h2f2(w.y), c2 = ink_h2f2(w.z), e = ink_h2f2(w.w); + sd += qj[8 * mm + 0] * a.x + qj[8 * mm + 1] * a.y + qj[8 * mm + 2] * b.x + qj[8 * mm + 3] * b.y + + qj[8 * mm + 4] * c2.x + qj[8 * mm + 5] * c2.y + qj[8 * mm + 6] * e.x + qj[8 * mm + 7] * e.y; + } + const bool valid = kp >= start[j] && kp <= qpos[j]; + const int dist = qpos[j] - kp; + float b = 0.f; + if (valid && dist < ext) { + const float4* br = (const float4*)(bias + (size_t)dist * nr); + for (int c = 0; c < nr; c += 4) { + const float4 bv = br[c >> 2]; + b += rs[qh + j][c] * bv.x + rs[qh + j][c + 1] * bv.y + rs[qh + j][c + 2] * bv.z + rs[qh + j][c + 3] * bv.w; + } + } + const float logit = valid ? sd + b - sk[j] : -INFINITY; + const float mn = fmaxf(m[j], ink_warp_max(logit)); + const float cc = expf(m[j] - mn); + const float p = valid ? expf(logit - mn) : 0.f; + l[j] = l[j] * cc + warp_sum(p); + m[j] = mn; + acc[j][0] *= cc; acc[j][1] *= cc; acc[j][2] *= cc; acc[j][3] *= cc; + ps[qh + j][lane] = p; + } + __syncwarp(); + const int nk = min(32, kp_last - k0 + 1); + for (int i = 0; i < nk; i++) { + const uint2 vw = *(const uint2*)(vs + i * PQ + 4 * lane); + const float2 v01 = ink_h2f2(vw.x), v23 = ink_h2f2(vw.y); +#pragma unroll + for (int j = 0; j < QPB; j++) { + if (!valid_t[j]) continue; + const float pi = ps[qh + j][i]; + acc[j][0] += pi * v01.x; acc[j][1] += pi * v01.y; acc[j][2] += pi * v23.x; acc[j][3] += pi * v23.y; + } + } + __syncwarp(); + } +#pragma unroll + for (int j = 0; j < QPB; j++) { + if (!valid_t[j]) continue; + const int t = t0 + qh + j; + const float inv = 1.f / l[j]; +#pragma unroll + for (int i = 0; i < 4; i++) { + const size_t idx = ((size_t)t * nh + h) * HD + 4 * lane + i; + outp[idx] = acc[j][i] * inv * sigmoid(gate[idx]); + } + } +} + +// The old kernel stays reachable as ink_attn_prefill_128_old (STRATA_DS_ATTN_OLD=1) and takes the shapes the new one does not. +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp_t<1>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + else ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp16( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + // The 4-query kernel writes four tokens a block; the host launches this entry point with a 16-token grid, so a + // fallback that calls it once would leave tokens 4..15 of every tile unwritten. Four calls cover the whole tile. + else for (int q0 = 0; q0 < 16; q0 += 4) + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 16 + q0); +} +// Tensor-core prompt attention for hd = 128, an f16 cache, nr = 16 and up to three query heads a K/V head (Inkling 2 +// Mini: 24 heads over 8 K/V heads). A block is 32 queries of every head of one K/V head: a warp is 16 queries of one +// head, and the 32-key K/V tile in shared memory is read by all of them. The scores are mma.m16n8k16 (f16 in, f32 +// accumulate), the softmax is online as in `ink_attn_prefill_kp_t` (the same virtual key of logit 0 starts it, the same +// sink is subtracted), P goes back through an f16 A fragment into the P*V mma. +// The relative bias b(q, k) = sum_c r[q][c] * bias[q - k][c] depends on the distance only, so a warp computes it for the +// distances its 16 x 32 tile spans (47 of them) as one small mma, T[i][d] = r_i . bias[dlo + d], into shared memory and +// each score reads its diagonal element: 16 FMAs a score on CUDA cores would cost as much as the whole tensor-core +// product. Tiles farther back than `ext` skip it. Needs sm_80 (the launcher checks), nr == 16, hd == 128. +extern "C" __global__ void __launch_bounds__(192) ink_attn_prefill_128_tc( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { +#if !STRATA_HIP && __CUDA_ARCH__ >= 800 + constexpr int HD = 128, PQ = HD + 8, BK = 32, TS = 49; + __shared__ __align__(16) u16 ks[BK * PQ], vs[BK * PQ]; + __shared__ float ts[6][16 * TS]; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int g = nh / nkv, kh = blockIdx.y, qt = warp / g, h = kh * g + warp % g; + const int t0b = blockIdx.x * 32, t0w = t0b + qt * 16; + const int gr = lane >> 2, t4 = lane & 3; + const int lr = (lane & 7) + ((lane >> 3) & 1) * 8, lc = (lane >> 4) * 8; + const size_t kw = (size_t)nkv * HD; + const float scale = 1.f / sqrtf((float)HD); + int tr[2], qpos[2], start[2]; + bool ok[2]; + float sk[2]; +#pragma unroll + for (int i = 0; i < 2; i++) { + tr[i] = t0w + gr + 8 * i; + ok[i] = tr[i] < nt; + qpos[i] = ok[i] ? pos + tr[i] : -1; + start[i] = (win > 0 && qpos[i] + 1 > win) ? qpos[i] + 1 - win : 0; + sk[i] = ok[i] ? sink[(size_t)tr[i] * nh + h] : 0.f; + } + u32 qa[HD / 16][4], ra[4]; +#pragma unroll + for (int kk = 0; kk < HD / 16; kk++) { +#pragma unroll + for (int j = 0; j < 4; j++) { + const int i = j & 1, d = kk * 16 + 2 * t4 + (j >> 1) * 8; + float2 x = make_float2(0.f, 0.f); + if (ok[i]) x = *(const float2*)(q + ((size_t)tr[i] * nh + h) * HD + d); + qa[kk][j] = h2pack(x.x * scale, x.y * scale); + } + } +#pragma unroll + for (int j = 0; j < 4; j++) { + const int i = j & 1, c = 2 * t4 + (j >> 1) * 8; + float2 x = make_float2(0.f, 0.f); + if (ok[i]) x = *(const float2*)(r + ((size_t)tr[i] * nh + h) * 16 + c); + ra[j] = h2pack(x.x, x.y); + } + float o[HD / 8][4], m[2] = {0.f, 0.f}, l[2] = {t4 == 0 ? 1.f : 0.f, t4 == 0 ? 1.f : 0.f}; +#pragma unroll + for (int d = 0; d < HD / 8; d++) o[d][0] = o[d][1] = o[d][2] = o[d][3] = 0.f; + const int kmax = pos + min(t0b + 31, nt - 1); + const int kmin = (win > 0 && pos + t0b + 1 > win) ? pos + t0b + 1 - win : 0; + float* tw = ts[warp]; + for (int k0 = kmin; k0 <= kmax; k0 += BK) { + __syncthreads(); + for (int i = tid; i < BK * (HD / 8); i += blockDim.x) { + const int rr = i >> 4, c = (i & 15) * 8, kp = k0 + rr; + uint4 kv = make_uint4(0, 0, 0, 0), vv = kv; + if (kp <= kmax) { + const bool un = kc_new && kp >= pos; + const size_t row = un ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); + const size_t off = row * kw + (size_t)kh * HD + c; + kv = *(const uint4*)((un ? kc_new : kc) + off); + vv = *(const uint4*)((un ? vc_new : vc) + off); + } + *(uint4*)(ks + rr * PQ + c) = kv; + *(uint4*)(vs + rr * PQ + c) = vv; + } + __syncthreads(); + float s[BK / 8][4]; +#pragma unroll + for (int n = 0; n < BK / 8; n++) s[n][0] = s[n][1] = s[n][2] = s[n][3] = 0.f; +#pragma unroll + for (int kk = 0; kk < HD / 16; kk++) +#pragma unroll + for (int n = 0; n < BK / 8; n += 2) { + u32 b[4]; + ldsm4(b, ks + (n * 8 + (lane & 7) + (lane >> 4) * 8) * PQ + kk * 16 + ((lane >> 3) & 1) * 8); + mma16816(s[n], qa[kk][0], qa[kk][1], qa[kk][2], qa[kk][3], b[0], b[1]); + mma16816(s[n + 1], qa[kk][0], qa[kk][1], qa[kk][2], qa[kk][3], b[2], b[3]); + } + // Distances this warp's tile spans: dlo (row 0, key 31) to dlo + 46 (row 15, key 0). + const int dlo = pos + t0w - (k0 + BK - 1); + const bool use_b = pos + t0w + 15 - k0 >= 0 && dlo < ext; + if (use_b) { +#pragma unroll + for (int nb = 0; nb < 6; nb++) { + float tc[4] = {0.f, 0.f, 0.f, 0.f}; + const int dist = dlo + nb * 8 + gr; + u32 b0 = 0, b1 = 0; + if (dist >= 0 && dist < ext) { + const float* br = bias + (size_t)dist * 16; + const float2 x = *(const float2*)(br + 2 * t4), y = *(const float2*)(br + 2 * t4 + 8); + b0 = h2pack(x.x, x.y); b1 = h2pack(y.x, y.y); + } + mma16816(tc, ra[0], ra[1], ra[2], ra[3], b0, b1); + tw[gr * TS + nb * 8 + 2 * t4] = tc[0]; + tw[gr * TS + nb * 8 + 2 * t4 + 1] = tc[1]; + tw[(gr + 8) * TS + nb * 8 + 2 * t4] = tc[2]; + tw[(gr + 8) * TS + nb * 8 + 2 * t4 + 1] = tc[3]; + } + __syncwarp(); + } + float mx[2] = {m[0], m[1]}; +#pragma unroll + for (int n = 0; n < BK / 8; n++) +#pragma unroll + for (int e = 0; e < 4; e++) { + const int i = e >> 1, kp = k0 + n * 8 + 2 * t4 + (e & 1), dist = qpos[i] - kp; + if (ok[i] && kp >= start[i] && dist >= 0) { + const float b = (use_b && dist < ext) ? tw[(gr + 8 * i) * TS + dist - dlo] : 0.f; + s[n][e] = s[n][e] + b - sk[i]; + mx[i] = fmaxf(mx[i], s[n][e]); + } else { + s[n][e] = -INFINITY; + } + } + float c[2]; +#pragma unroll + for (int i = 0; i < 2; i++) { + mx[i] = fmaxf(mx[i], __shfl_xor_sync(0xffffffff, mx[i], 1)); + mx[i] = fmaxf(mx[i], __shfl_xor_sync(0xffffffff, mx[i], 2)); + c[i] = __expf(m[i] - mx[i]); + m[i] = mx[i]; + l[i] *= c[i]; + } +#pragma unroll + for (int n = 0; n < BK / 8; n++) +#pragma unroll + for (int e = 0; e < 4; e++) { const float p = __expf(s[n][e] - mx[e >> 1]); s[n][e] = p; l[e >> 1] += p; } +#pragma unroll + for (int d = 0; d < HD / 8; d++) { o[d][0] *= c[0]; o[d][1] *= c[0]; o[d][2] *= c[1]; o[d][3] *= c[1]; } +#pragma unroll + for (int kb = 0; kb < BK / 16; kb++) { + const u32 a0 = h2pack(s[2 * kb][0], s[2 * kb][1]), a1 = h2pack(s[2 * kb][2], s[2 * kb][3]); + const u32 a2 = h2pack(s[2 * kb + 1][0], s[2 * kb + 1][1]), a3 = h2pack(s[2 * kb + 1][2], s[2 * kb + 1][3]); +#pragma unroll + for (int d = 0; d < HD / 8; d += 2) { + u32 b[4]; + ldsm4t(b, vs + (kb * 16 + lr) * PQ + d * 8 + lc); + mma16816(o[d], a0, a1, a2, a3, b[0], b[1]); + mma16816(o[d + 1], a0, a1, a2, a3, b[2], b[3]); + } + } + __syncwarp(); + } +#pragma unroll + for (int i = 0; i < 2; i++) { + float li = l[i] + __shfl_xor_sync(0xffffffff, l[i], 1); + li += __shfl_xor_sync(0xffffffff, li, 2); + if (!ok[i]) continue; + const float inv = 1.f / li; +#pragma unroll + for (int d = 0; d < HD / 8; d++) +#pragma unroll + for (int e = 0; e < 2; e++) { + const size_t idx = ((size_t)tr[i] * nh + h) * HD + d * 8 + 2 * t4 + e; + outp[idx] = o[d][2 * i + e] * inv * sigmoid(gate[idx]); + } + } +#endif +} +#else +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp16( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + for (int q0 = 0; q0 < 16; q0 += 4) + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 16 + q0); +} +extern "C" __global__ void __launch_bounds__(192) ink_attn_prefill_128_tc( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) {} +#endif +// The same attention for a layer that sees every key, where the K/V rows of a long prompt do not stay in the cache. +// The arithmetic of a (query, key) pair and the order of the keys are those of ink_attn_prefill_t: same bits. +template +__device__ void ink_attn_prefill_sh_t(const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + // A block is one K/V head and a group of tokens: one warp for each (token, query head of the K/V head). The + // block reads the K and V rows of 32 keys once, into shared memory, and every warp takes them from there + // (each warp read them from the cache itself: the same rows, once a warp). + constexpr int HD = 32 * PER, TK = 32; + extern __shared__ float skv[]; // TK * HD values of K, then TK * HD values of V + float* sk = skv; float* sv = skv + TK * HD; + int g = nh / nkv, kh = blockIdx.y, w = threadIdx.x >> 5, lane = threadIdx.x & 31, tb = (blockDim.x >> 5) / g; + int t0 = blockIdx.x * tb, t = t0 + w / g, h = kh * g + w % g, kw = nkv * HD; + bool live = t < nt; + if (!live) t = nt - 1; + int q_pos = pos + t; + int start = (win > 0 && q_pos + 1 > win) ? (q_pos + 1 - win) : 0; + int kbeg = (win > 0 && pos + t0 + 1 > win) ? (pos + t0 + 1 - win) : 0, kend = pos + min(nt, t0 + tb) - 1; + float scale = 1.f / sqrtf((float)HD); + float qv[PER], acc[PER]; + for (int j = 0; j < PER; j++) { + qv[j] = q[((size_t)t * nh + h) * HD + lane + 32 * j] * scale; + acc[j] = 0.f; + } + float sink_val = sink[(size_t)t * nh + h]; + float r_reg = (nr <= 32 && lane < nr) ? r[((size_t)t * nh + h) * nr + lane] : 0.f; + float m = 0.f, l = 1.f; + for (int k0 = kbeg; k0 <= kend; k0 += TK) { + int n = min(TK, kend + 1 - k0); + // Row of key k0 in the old rows: a ring of `ring` rows on a sliding layer. + int r0 = win > 0 ? k0 % ring : k0; + for (int i = threadIdx.x; i < n * HD; i += blockDim.x) { + int key = i / HD, kp = k0 + key; + bool use_new = kc_new && kp >= pos; + size_t row = use_new ? (size_t)(kp - pos) : (size_t)(r0 + key >= ring ? r0 + key - ring : r0 + key); + size_t off = row * kw + (size_t)kh * HD + i % HD; + sk[i] = ldkv1(use_new ? kc_new : kc, off, HD); + sv[i] = ldkv1(use_new ? vc_new : vc, off, HD); + } + __syncthreads(); + if (live) for (int i = max(start - k0, 0); i < n && k0 + i <= q_pos; i++) { + const float* kr = sk + i * HD + lane; + const float* vr = sv + i * HD + lane; + float s = 0.f; + for (int j = 0; j < PER; j++) s += qv[j] * kr[32 * j]; + s = warp_sum(s); + int dist = q_pos - k0 - i; + float b = 0.f; + if (dist < ext) { + if (nr <= 32) { + b = lane < nr ? r_reg * bias[dist * nr + lane] : 0.f; + } else { + for (int c = lane; c < nr; c += 32) b += r[((size_t)t * nh + h) * nr + c] * bias[dist * nr + c]; + } + b = warp_sum(b); + } + float logit = s + b - sink_val; + float mn = fmaxf(m, logit), c = expf(m - mn), e = expf(logit - mn); + l = l * c + e; + for (int j = 0; j < PER; j++) acc[j] = e * vr[32 * j] + acc[j] * c; + m = mn; + } + __syncthreads(); + } + if (!live) return; + float inv = 1.f / l; + for (int j = 0; j < PER; j++) { + int col = lane + 32 * j; + size_t idx = ((size_t)t * nh + h) * HD + col; + outp[idx] = acc[j] * inv * sigmoid(gate[idx]); + } +} +#define DEF_INK_PREFILL_SH(HD) \ + extern "C" __global__ void __launch_bounds__(1024) ink_attn_prefill_sh_##HD( \ + const float* q, const float* r, const float* sink, const float* gate, \ + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, \ + const float* bias, float* outp, \ + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { \ + ink_attn_prefill_sh_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); \ + } +DEF_INK_PREFILL_SH(32) DEF_INK_PREFILL_SH(64) DEF_INK_PREFILL_SH(128) template __device__ void attn_decode_llama(const float* q, const u16* kc, const u16* vc, float* part, const int* step, const int* sel, int nh, int nkv, float scale, int bx, int win) { @@ -2721,6 +5619,20 @@ __device__ void attn_decode_t(const float* q, const u16* kc, const u16* vc, floa __shared__ float ss[G][C], sc[G], sm[G], sl[G]; int h0 = bx * G, g = h0 / (nh / nkv), w = threadIdx.x >> 5, lane = threadIdx.x & 31, nw = blockDim.x >> 5; for (int i = threadIdx.x; i < G * hd; i += blockDim.x) sq[i] = q[h0 * hd + i]; +#if K_MODE >= 4 + __syncthreads(); + if (w == 0) { + for (int i = 0; i < G; i++) { + for (int gg = 0; gg < hd / 128; gg++) { + int base = i * hd + gg * 128 + 4 * lane; + float4 v = make_float4(sq[base], sq[base+1], sq[base+2], sq[base+3]); + tq_wht4(v, lane, false); + sq[base]=v.x; sq[base+1]=v.y; sq[base+2]=v.z; sq[base+3]=v.w; + } + } + } + __syncthreads(); +#endif float acc[G][PER], m = -INFINITY, l = 0.0f; // m, l: running max and sum of head w (warps w < G) #pragma unroll for (int i = 0; i < G; i++) @@ -2760,7 +5672,7 @@ __device__ void attn_decode_t(const float* q, const u16* kc, const u16* vc, floa if constexpr (!KV1) ldh_raw(sk + C * hd, vr[j]); } else { size_t r = ((size_t)cell(min(t, p1 - 1)) * nkv + g) * hd + lane * PER; - ldkv(kc, r, hd, kr[j]); ldkv(vc, r, hd, vr[j]); + ldkv(kc, r, hd, kr[j]); ldkv(vc, r, hd, vr[j]); } for (int d = 0; d < PER / 2; d++) if (t >= p1) kr[j][d] = vr[j][d] = 0; } @@ -2873,7 +5785,9 @@ __device__ void attn_decode_t(const float* q, const u16* kc, const u16* vc, floa #define ATT_TOK int t = blockIdx.x % nt; q += (size_t)t * nh * hd; part += (size_t)t * pz; step += 2 * t; if (sel) sel += (size_t)t * sst; \ if (kvt) { kc = (const u16*)kvt[2 * t]; vc = (const u16*)kvt[2 * t + 1]; } #define ATT_RUN(G) attn_decode_t(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win) -#define ATT_RUN_CP(G) attn_decode_t= 800))>(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win) +// The HIP launcher has no cp.async staging and asks for no K/V shared chunks (src/hip/mod.rs), so the HIP build must +// not instantiate them: a CP kernel would write past the end of that block's shared memory. +#define ATT_RUN_CP(G) attn_decode_t= 800))>(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win) #define DEF_ATT(HD) \ extern "C" __global__ void attn_decode_##HD(ATT_ARGS) { \ constexpr int PER = HD / 32; ATT_TOK \ @@ -2897,7 +5811,7 @@ DEF_ATT(64) DEF_ATT(128) DEF_ATT(256) DEF_ATT(512) extern "C" __global__ void __launch_bounds__(256, 3) attn_decode_gqa4_128(ATT_ARGS) { constexpr int PER = 4; ATT_TOK if (step[0] + 1 < gq_min) return; - if constexpr (KV_MODE == 0) attn_decode_t(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win); + if constexpr (K_MODE == 0 && V_MODE == 0) attn_decode_t(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win); } // grid = query heads: out = (sum of split partials) / (sum of split sums) * sigmoid(gate), gate skipped when qg is null. Split 0 is never empty. @@ -2911,6 +5825,9 @@ extern "C" __global__ void attn_merge(const float* part, const float* qg, float* if (step[0] + 1 < gq_min) ns = ns1; // attn_decode ran, not attn_decode_gqa const float* pp = part + (size_t)h * ns * (hd + 2); __shared__ float ws[256]; // split max, then split weight (ns <= blockDim.x <= 256) +#if V_MODE >= 4 + __shared__ float ro[512]; // ungated attention output in the rotated domain (hd <= 512) +#endif if (threadIdx.x < ns) ws[threadIdx.x] = pp[threadIdx.x * (hd + 2) + hd]; __syncthreads(); float M = -INFINITY, L = 0.0f; @@ -2924,7 +5841,12 @@ extern "C" __global__ void attn_merge(const float* part, const float* qg, float* for (int d = threadIdx.x; d < hd; d += blockDim.x) { float o = 0.0f; for (int s = 0; s < ns; s++) o += pp[s * (hd + 2) + d] * ws[s]; - o = o / L * (qg ? sigmoid(qg[h * 2 * hd + hd + d]) : 1.0f); + o = o / L; +#if V_MODE >= 4 + ro[d] = o; // keep the ungated value: inverse WHT must run before the Q gate +#else + // Match main exactly: apply the Q gate before both the output write and the int8 copy. + o = o * (qg ? sigmoid(qg[h * 2 * hd + hd + d]) : 1.0f); out[h * hd + d] = o; if (xq) { // hd is a multiple of 32: a warp holds one scale's 32 values float mx = warp_max(fabsf(o)), id = mx > 0.0f ? 127.0f / mx : 0.0f; @@ -2932,7 +5854,30 @@ extern "C" __global__ void attn_merge(const float* part, const float* qg, float* xq[i] = (signed char)__float2int_rn(o * id); if ((threadIdx.x & 31) == 0) ((float*)(xq + gridDim.z * n))[i >> 5] = mx / 127.0f; } +#endif + } +#if V_MODE >= 4 + __syncthreads(); + for (int g = 0; g < hd / 128; g++) { + int base = g * 128 + 4 * threadIdx.x; + if (threadIdx.x < 32) { + float4 v = make_float4(ro[base], ro[base+1], ro[base+2], ro[base+3]); + tq_wht4(v, threadIdx.x, true); + ro[base]=v.x; ro[base+1]=v.y; ro[base+2]=v.z; ro[base+3]=v.w; + } + } + __syncthreads(); + for (int d = threadIdx.x; d < hd; d += blockDim.x) { + float o = ro[d] * (qg ? sigmoid(qg[h * 2 * hd + hd + d]) : 1.0f); + out[h * hd + d] = o; + if (xq) { + float mx = warp_max(fabsf(o)), id = mx > 0.0f ? 127.0f / mx : 0.0f; + size_t n = (size_t)gridDim.x * hd, i = blockIdx.z * n + h * hd + d; + xq[i] = (signed char)__float2int_rn(o * id); + if ((threadIdx.x & 31) == 0) ((float*)(xq + gridDim.z * n))[i >> 5] = mx / 127.0f; + } } +#endif } // ---- MoE ---- @@ -3001,9 +5946,14 @@ extern "C" __global__ void router_topk(const float* p, int n, int k, float extra // copied to the host-mapped mailbox `mb`, T stored in word 1 and the request flag raised. `mb` = 0: the cache is fully // resident, there is no CPU part to tell, so every mailbox store is skipped (the ids, weights, slots and wh stay valid // for moe_gemv/moe_combine). `pid` (may be 0): last token's ids, the next token's prefetch prediction. +// +// Host share (`hid` non-null, `hmin` > 0): when a token routes at least `hmin` experts that missed the cache, its last +// such expert is computed on the GPU from host memory (moe_gemv over the pinned weights, `GpuModel::host_exp`): hid +// holds its id (-1 elsewhere), wh its weight as for a hit, and the mailbox slot -2, which the CPU worker skips. hmin +// >= 2 leaves the CPU at least one expert, so the request and the combine's wait stay as they are. extern "C" __global__ void moe_route(const float* p, int n, int k, float extra_scale, const int* table, int* ids, float* wts, int* slots, float* wh, const float* h, unsigned int* mb, int nh, - int h_off, const int* step, int T, int* pid, int sigmoid) { + int h_off, const int* step, int T, int* pid, int sigmoid, int* hid, int hmin) { __shared__ int miss; int lane = threadIdx.x & 31, kt = k * T; unsigned int seq = step[1]; @@ -3013,10 +5963,14 @@ extern "C" __global__ void moe_route(const float* p, int n, int k, float extra_s int id; float w; topk_warp(p + (size_t)t * n, n, k, extra_scale, lane, id, w, sigmoid); + int s = lane < k ? table[id] : 0; + unsigned missed = __ballot_sync(0xffffffffu, lane < k && s < 0); + int host = hid && hmin > 0 && __popc(missed) >= hmin ? 31 - __clz(missed) : -1; if (lane < k) { - int o = t * k + lane, s = table[id]; - ids[o] = id; wts[o] = w; slots[o] = s; wh[o] = s >= 0 ? w : 0.0f; - if (mb) { mb[32 + o] = id; mb[32 + kt + o] = __float_as_uint(w); mb[32 + 2 * kt + o] = s; } + int o = t * k + lane; + ids[o] = id; wts[o] = w; slots[o] = s; wh[o] = s >= 0 || lane == host ? w : 0.0f; + if (hid) hid[o] = lane == host ? id : -1; + if (mb) { mb[32 + o] = id; mb[32 + kt + o] = __float_as_uint(w); mb[32 + 2 * kt + o] = lane == host ? -2 : s; } if (pid && t == T - 1) pid[lane] = id; if (s < 0) miss = 1; } @@ -3038,6 +5992,10 @@ extern "C" __global__ void moe_route(const float* p, int n, int k, float extra_s // One block per expert (grid.y) and line range (grid.x). STRATA_MOE_PREFETCH=1 only; a hint, never a correctness // dependency. Volta: prefetch.global.L2 exists since sm_20. extern "C" __global__ void moe_prefetch(const int* ids, int k, const int* table, const char* base, int stride, int bytes) { +#if STRATA_HIP + // AMD has no L2 prefetch instruction to give: on HIP this hint does nothing. + (void)ids; (void)k; (void)table; (void)base; (void)stride; (void)bytes; +#else int j = blockIdx.y; if (j >= k) return; int s = table[ids[j]]; @@ -3046,6 +6004,7 @@ extern "C" __global__ void moe_prefetch(const int* ids, int k, const int* table, int lines = bytes >> 7; for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) asm volatile("prefetch.global.L2 [%0];" ::"l"(p + ((size_t)i << 7))); +#endif } // x += sum_j w[j] ye[j] + sigmoid(sg) sh + cpu. If a slot missed, wait for the CPU worker's done flag first. @@ -3106,8 +6065,9 @@ extern "C" __global__ void moe_combine_seq(float* x, const float* ye, const floa #endif #define FA_BK_DEFAULT FA_BK // Turing's 64 KB shared memory cannot hold the HD = 256 tile at 32 keys either: 16 fit (the kernel keeps the same -// 64 queries a block and four warps). -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800 +// 64 queries a block and four warps). The HIP build has the same 64 KB a workgroup, and its score staging tile comes +// on top of the qs/ks/vs/ps sizes, so it takes the same 16-key tile. +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800) || STRATA_HIP #define FA_BK_FOR(HD) ((HD) == 256 ? 16 : FA_BK_DEFAULT) #else #define FA_BK_FOR(HD) FA_BK_DEFAULT @@ -3127,12 +6087,24 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co const float* sink, int win) { constexpr int PQ = HD + 8; constexpr int FA_BKL = FA_BK_FOR(HD); +#if V_MODE >= 4 + // query half x warp x 128 dims: one WHT group per warp, reused across its eight rows. + __shared__ float tro[2][4][128]; +#endif extern __shared__ __align__(16) u16 fa_sm[]; u16 *qs = fa_sm, *ks = qs + FA_BQ * PQ, *vs = ks + FA_BKL * PQ; #if __CUDA_ARCH__ < 800 && GEMM_TC // Volta only: warp-private P tile for the PV A fragments (see the staging in the PV step below). Appended after // `vs` so the qs/ks/vs offsets above do not move; FA_BQ * (FA_BKL + 8) halves = 5120 B. u16* ps = vs + FA_BKL * PQ; +#endif +#if GEMM_WMMA + // HIP: the P staging tile in halves (the PV A fragments, as on Volta) and, after it, the f32 tile the matrix-core + // scores are staged through before they are read in the m16n8k16 layout the softmax below is written for. Both + // sit after `vs` so the qs/ks/vs offsets do not move; `hip::Gpu::attn_prefill_m` adds the f32 tile to the block's + // dynamic shared memory (FA_BQ * (FA_BKL + 8) floats: 10 KiB at 32 keys, 6 KiB at 16). + u16* ps = vs + FA_BKL * PQ; + float* st = (float*)(ps + FA_BQ * (FA_BKL + 8)); #endif // The last query tiles see the most keys: start them first so the short ones fill the tail. int pos0 = step[0], q0 = (gridDim.x - 1 - blockIdx.x) * FA_BQ, h = blockIdx.y, kvh = h / (nh / nkv), kvd = nkv * HD; @@ -3141,11 +6113,17 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int i = tid; i < FA_BQ * HD / 4; i += 128) { int r = i / (HD / 4), c = (i % (HD / 4)) * 4; float4 v = q0 + r < T ? *(const float4*)(q + (size_t)(q0 + r) * nh * HD + h * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f); +#if K_MODE >= 4 + tq_wht4(v, (c >> 2) & 31, false); // lane owns 4 dims of one 128-value WHT group (group = (c >> 2) >> 5) +#endif *(uint2*)(qs + r * PQ + c) = make_uint2(h2pack(v.x * scale, v.y * scale), h2pack(v.z * scale, v.w * scale)); } int last = pos0 + min(q0 + FA_BQ, T) - 1; // last key any query of the tile sees int qp[2] = {pos0 + q0 + warp * 16 + g, pos0 + q0 + warp * 16 + g + 8}; float o[HD / 8][4] = {}, m[2] = {-INFINITY, -INFINITY}, l[2] = {0.0f, 0.0f}; +#if V_MODE >= 4 + float invr[2] = {1.f, 1.f}; +#endif #if __CUDA_ARCH__ < 800 && GEMM_TC // Same storage as o / extra softmax state for the m8n8k4 layout (PTX ISA 8.5 §9.7.13.4.1). o2[j][grp][i] == // &o[0][0][j * HD / 4 + grp * 8 + i]: the lane owns 4 rows (query half j, p2), so m and l need four entries each; @@ -3154,7 +6132,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co float mT[2][2] = {{-INFINITY, -INFINITY}, {-INFINITY, -INFINITY}}, lT[2][2] = {}; #endif constexpr int N = FA_BKL * HD / 8 / 128; -#if KV_MODE == 0 +#if K_MODE == 0 && V_MODE == 0 // f16: copy the V tile while the scores use K, and the next K tile while the sums use V (one block per SM, // so nothing else hides the loads); cp.async on sm_80+, a blocking copy at the same program point on sm_70. // Rows past `last` are zero-filled (synchronous path: the source is not read at all). @@ -3170,7 +6148,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co ld(0, vs, vc); #endif for (int k0 = 0; k0 <= last; k0 += FA_BKL) { -#if KV_MODE > 0 +#if K_MODE > 0 || V_MODE > 0 __syncthreads(); // All of a thread's loads, then its stores: with q8 the dequant between them kept the compiler from // overlapping the loads. Rows past `last` load the row `last` and store zeros. @@ -3179,7 +6157,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int n = 0; n < N; n++) { int i = tid + n * 128, r = i / (HD / 8), c = (i % (HD / 8)) * 8; size_t off = (size_t)min(k0 + r, last) * kvd + kvh * HD + c; - ldkv<8>(kc, off, HD, (unsigned*)&kv[n]); ldkv<8>(vc, off, HD, (unsigned*)&vv[n]); + ldkv(kc, off, HD, (unsigned*)&kv[n]); ldkv(vc, off, HD, (unsigned*)&vv[n]); } #pragma unroll for (int n = 0; n < N; n++) { @@ -3192,8 +6170,11 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co cp_async_wait<1>(); // sm_80+: this K tile, its V tile may still be in flight; sm_70: already copied here #endif __syncthreads(); - // QSA: the tile's 8 blocks are bits (k0 >> 2) & 31 .. + 7 of one mask word per row. A warp whose 16 rows see - // none of them skips the tile (its keys would add exactly nothing). + // QSA: the tile's FA_BKL / 4 blocks are bits (k0 >> 2) & 31 .. + FA_BKL / 4 - 1 of one mask word per row, + // shifted down so bit (key - k0) >> 2 is the block of `key`. At 16-key tiles k0 is not a multiple of 32, so + // the shifted word must be read tile-relative and cut to the tile's 4 blocks. A warp whose 16 rows see none + // of them skips the tile (its keys would add exactly nothing). + constexpr unsigned VM = (1u << (FA_BKL / 4)) - 1; #if __CUDA_ARCH__ < 800 && GEMM_TC // m8n8k4 query rows: the lane owns rows 8*j + (t & 1) + 2*p2 + 4*hi of the warp tile, so four `vis` words. int qp2[2][2]; @@ -3203,21 +6184,48 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co #pragma unroll for (int p2 = 0; p2 < 2; p2++) { qp2[j][p2] = pos0 + q0 + warp * 16 + 8 * j + (t4 & 1) + 2 * p2 + 4 * (g >> 2); - vis2[j][p2] = 0xff; + vis2[j][p2] = VM; } if (qm) for (int j = 0; j < 2; j++) for (int p2 = 0; p2 < 2; p2++) - vis2[j][p2] = (qm[(size_t)(qp2[j][p2] - pos0) * mw + (k0 >> 7)] >> ((k0 >> 2) & 31)) & 0xff; + vis2[j][p2] = (qm[(size_t)(qp2[j][p2] - pos0) * mw + (k0 >> 7)] >> ((k0 >> 2) & 31)) & VM; bool skip = qm && !__any_sync(0xffffffff, (vis2[0][0] | vis2[0][1] | vis2[1][0] | vis2[1][1]) != 0); #else - unsigned vis[2] = {0xff, 0xff}; + unsigned vis[2] = {VM, VM}; if (qm) - for (int r = 0; r < 2; r++) vis[r] = (qm[(size_t)(qp[r] - pos0) * mw + (k0 >> 7)] >> ((k0 >> 2) & 31)) & 0xff; + for (int r = 0; r < 2; r++) vis[r] = (qm[(size_t)(qp[r] - pos0) * mw + (k0 >> 7)] >> ((k0 >> 2) & 31)) & VM; bool skip = qm && !__any_sync(0xffffffff, (vis[0] | vis[1]) != 0); #endif float s[FA_BKL / 8][4] = {}; -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // Q K^T on the matrix cores: one 16-query x 16-key tile per instruction against the 16-half qs/ks rows, then + // staged and read back so the softmax keeps its m16n8k16 lane layout (row g / g + 8, keys 2t / 2t + 1). The + // warp writes and reads only its own 16 rows of the tile, so a warp barrier publishes it. + if (!skip) { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane), PW = FA_BKL + 8; + float* sw = st + warp * 16 * PW; + const u16* qrow = qs + (warp * 16 + l16) * PQ + w0; +#pragma unroll + for (int kg = 0; kg < FA_BKL / 16; kg++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; + const u16* krow = ks + (kg * 16 + l16) * PQ + w0; +#pragma unroll + for (int kk = 0; kk < HD; kk += 16) + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(qrow + kk), strata_hip::strata_ld_wmma(krow + kk), acc); +#pragma unroll + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * PW + kg * 16 + l16] = acc[i]; + } + __syncwarp(); +#pragma unroll + for (int ng = 0; ng < FA_BKL / 8; ng++) +#pragma unroll + for (int i = 0; i < 4; i++) + s[ng][i] = sw[(g + 8 * (i >> 1)) * PW + ng * 8 + 2 * t4 + (i & 1)]; + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // Same 16 f32 storage as s, seen as m8n8k4 D registers: s2[ng][j][4*p4 + 2*p2 + e] is S[8*j + (t & 1) + // 2*p2 + 4*hi][8*(4*ng + c) + (t & 2) + 4*p4 + e] of the 16 x FA_BKL score tile. Every lane holds the four // computations its c selects, so the warp must stay in uniform control flow (`skip` is warp-uniform). @@ -3240,6 +6248,33 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co ld_s32(pb + 4 * ks4), ld_s32(pb + 4 * ks4 + 2)); } } +#elif MMA_FMA && !STRATA_HIP + if (!skip) { + const u16* qr0 = qs + (warp * 16 + g) * PQ; + const u16* qr1 = qs + (warp * 16 + g + 8) * PQ; +#pragma unroll 2 + for (int kk = 0; kk < HD; kk += 4) { + uint2 qa = *(const uint2*)(qr0 + kk); + uint2 qb = *(const uint2*)(qr1 + kk); + float q00 = h2f((u16)qa.x), q01 = h2f((u16)(qa.x >> 16)), q02 = h2f((u16)qa.y), q03 = h2f((u16)(qa.y >> 16)); + float q10 = h2f((u16)qb.x), q11 = h2f((u16)(qb.x >> 16)), q12 = h2f((u16)qb.y), q13 = h2f((u16)(qb.y >> 16)); +#pragma unroll + for (int nt = 0; nt < FA_BKL / 8; nt++) { + const u16* kr0 = ks + (nt * 8 + 2 * t4) * PQ + kk; + const u16* kr1 = ks + (nt * 8 + 2 * t4 + 1) * PQ + kk; + uint2 ka = *(const uint2*)kr0; + uint2 kb = *(const uint2*)kr1; + // Accumulate Q*K directly in FP32 (matching tensor-core mma.f32.f16.f16.f32) so outlier channels + // cannot lose logit precision or overflow f16 before softmax (qs is pre-scaled by 1/sqrt(HD)). + float k00 = h2f((u16)ka.x), k01 = h2f((u16)(ka.x >> 16)), k02 = h2f((u16)ka.y), k03 = h2f((u16)(ka.y >> 16)); + float k10 = h2f((u16)kb.x), k11 = h2f((u16)(kb.x >> 16)), k12 = h2f((u16)kb.y), k13 = h2f((u16)(kb.y >> 16)); + s[nt][0] = fmaf(q00, k00, fmaf(q01, k01, fmaf(q02, k02, fmaf(q03, k03, s[nt][0])))); + s[nt][1] = fmaf(q00, k10, fmaf(q01, k11, fmaf(q02, k12, fmaf(q03, k13, s[nt][1])))); + s[nt][2] = fmaf(q10, k00, fmaf(q11, k01, fmaf(q12, k02, fmaf(q13, k03, s[nt][2])))); + s[nt][3] = fmaf(q10, k10, fmaf(q11, k11, fmaf(q12, k12, fmaf(q13, k13, s[nt][3])))); + } + } + } #else if (!skip) #pragma unroll @@ -3254,7 +6289,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co } } #endif -#if KV_MODE == 0 +#if K_MODE == 0 && V_MODE == 0 __syncthreads(); if (k0 + FA_BKL <= last) ld(k0 + FA_BKL, ks, kc); else cp_async_commit(); // keep one group per tile for the waits (sm_80+; nothing to commit on sm_70) @@ -3279,7 +6314,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int e = 0; e < 2; e++) { float& v = s2[kg][j][4 * p4 + 2 * p2 + e]; int key = k0 + 8 * (4 * kg + c) + (t4 & 2) + 4 * p4 + e; - if (key > qp2[j][p2] || (win > 0 && key + win <= qp2[j][p2]) || !((vis2[j][p2] >> ((key >> 2) & 7)) & 1)) v = -INFINITY; + if (key > qp2[j][p2] || (win > 0 && key + win <= qp2[j][p2]) || !((vis2[j][p2] >> ((key - k0) >> 2)) & 1)) v = -INFINITY; mx = fmaxf(mx, v); } mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, 2)); @@ -3323,7 +6358,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int nt = 0; nt < FA_BKL / 8; nt++) for (int e = 0; e < 4; e++) { int key = k0 + nt * 8 + 2 * t4 + (e & 1), r = e >> 1; - if (key > qp[r] || (win > 0 && key + win <= qp[r]) || !((vis[r] >> ((key >> 2) & 7)) & 1)) s[nt][e] = -INFINITY; + if (key > qp[r] || (win > 0 && key + win <= qp[r]) || !((vis[r] >> ((key - k0) >> 2)) & 1)) s[nt][e] = -INFINITY; mx[r] = fmaxf(mx[r], s[nt][e]); } float c[2], ms[2]; @@ -3342,11 +6377,51 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int d = 0; d < HD / 8; d++) { o[d][0] *= c[0]; o[d][1] *= c[0]; o[d][2] *= c[1]; o[d][3] *= c[1]; } } #endif -#if KV_MODE == 0 +#if K_MODE == 0 && V_MODE == 0 cp_async_wait<1>(); // sm_80+: this V tile, the next K tile may still be in flight; sm_70: already copied here __syncthreads(); #endif -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // P * V on the matrix cores, the way the scores are: A = P (this warp's 16 query rows x the tile's keys, in + // halves), B = V^T (16 head dimensions x the same keys, one half a tile row apart). The lane's 8 results land + // in AMD's layout again (query rows STRATA_WMMA_ROW(lane, i), dim column lane & 15), so each 16 x 16 result tile is + // staged in f32 and read back as the two m16n8k16 dim tiles the rescale above, the epilogue below and the + // score stage all use (`st` is free again by now: it held the scores of this tile). + if (!skip) { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane), PW = FA_BKL + 8; +#pragma unroll + for (int ng = 0; ng < FA_BKL / 8; ng++) { + // P in halves, one 32-bit store a half pair (keys 2t / 2t+1 are adjacent in this lane's registers) + *(u32*)(ps + (warp * 16 + g) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][0], s[ng][1]); + *(u32*)(ps + (warp * 16 + g + 8) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][2], s[ng][3]); + } + __syncwarp(); + float* sw = st + warp * 256; +#pragma unroll + for (int dt = 0; dt < HD / 16; dt++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; +#pragma unroll + for (int kg = 0; kg < FA_BKL / 16; kg++) { + const u16* pa = ps + (warp * 16 + l16) * PW + kg * 16 + w0; + const u16* pb = vs + (kg * 16 + w0) * PQ + dt * 16 + l16; + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(pa), strata_hip::strata_ld_wmma_t(pb, PQ), acc); + } +#pragma unroll + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * 16 + l16] = acc[i]; + __syncwarp(); +#pragma unroll + for (int r = 0; r < 2; r++) +#pragma unroll + for (int e = 0; e < 2; e++) { + o[2 * dt][2 * r + e] += sw[(g + 8 * r) * 16 + 2 * t4 + e]; + o[2 * dt + 1][2 * r + e] += sw[(g + 8 * r) * 16 + 8 + 2 * t4 + e]; + } + __syncwarp(); + } + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // P -> the warp-private staging tile: the m8n8k4 A fragment of the PV product wants row t + 4*hi and four // contiguous keys per lane, which the QK^T D layout does not give for free. One 32-bit store per half pair; // the __syncwarp() publishes the tile to the mma step below (the next tile's stores follow the loop's @@ -3383,6 +6458,42 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co } } } +#elif MMA_FMA && !STRATA_HIP + if (!skip) { + u32 p0[FA_BKL], p1[FA_BKL]; +#pragma unroll + for (int nt = 0; nt < FA_BKL / 8; nt++) { + u32 e0 = h2pack(s[nt][0], s[nt][1]), e1 = h2pack(s[nt][2], s[nt][3]); +#pragma unroll + for (int src = 0; src < 4; src++) { + u32 w0 = __shfl_sync(0xffffffff, e0, 4 * g + src); + u32 w1 = __shfl_sync(0xffffffff, e1, 4 * g + src); + p0[nt * 8 + 2 * src] = (w0 & 0xffffu) | ((w0 & 0xffffu) << 16); + p0[nt * 8 + 2 * src + 1] = (w0 >> 16) | (w0 & 0xffff0000u); + p1[nt * 8 + 2 * src] = (w1 & 0xffffu) | ((w1 & 0xffffu) << 16); + p1[nt * 8 + 2 * src + 1] = (w1 >> 16) | (w1 & 0xffff0000u); + } + } +#pragma unroll + for (int d = 0; d < HD / 8; d++) { + const u16* vp = vs + d * 8 + 2 * t4; + // Widen PV partial sums to FP32 every 8 keys to keep rounding tight across tiles. +#pragma unroll + for (int ks8 = 0; ks8 < FA_BKL; ks8 += 8) { + u32 oh0 = 0, oh1 = 0; +#pragma unroll + for (int k = ks8; k < ks8 + 8; k++) { + u32 v2 = *(const u32*)(vp + k * PQ); + oh0 = fma_f16x2(p0[k], v2, oh0); + oh1 = fma_f16x2(p1[k], v2, oh1); + } + o[d][0] += h2f((u16)oh0); + o[d][1] += h2f((u16)(oh0 >> 16)); + o[d][2] += h2f((u16)oh1); + o[d][3] += h2f((u16)(oh1 >> 16)); + } + } + } #else if (!skip) #pragma unroll @@ -3398,7 +6509,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co } } #endif -#if KV_MODE == 0 +#if K_MODE == 0 && V_MODE == 0 __syncthreads(); if (k0 + FA_BKL <= last) ld(k0 + FA_BKL, vs, vc); else cp_async_commit(); // keep one group per tile for the waits (sm_80+; nothing to commit on sm_70) @@ -3456,13 +6567,58 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co float sc = m[r] == -INFINITY ? 0.0f : expf(m[r] - M); float den = l[r] * sc + (sk == -INFINITY ? 0.0f : expf(sk - M)); float inv = den > 0.0f ? sc / den : 0.0f; +#if V_MODE >= 4 + invr[r] = inv; // store after each 128-value group is rotated below +#else #pragma unroll for (int d = 0; d < HD / 8; d++) for (int e = 0; e < 2; e++) { int col = d * 8 + 2 * t4 + e; orow[col] = o[d][2 * r + e] * inv * (gate ? sigmoid(gate[col]) : 1.0f); } +#endif } +#if V_MODE >= 4 + // Every warp rotates one of its own query rows at a time, so all four warps work in parallel. tro is indexed by + // warp, not by the four-lane group that produced the values: the four lanes g == gi own the row's 128 dims. + // Two barriers per WHT group instead of three per (warp, row, group, half): 17 at head_dim 128, 34 at 256. + for (int gi = 0; gi < 8; gi++) + for (int gg = 0; gg < HD / 128; gg++) { +#pragma unroll + for (int r = 0; r < 2; r++) + if (g == gi) + for (int d = 16 * gg; d < 16 * gg + 16; d++) + for (int e = 0; e < 2; e++) { + int col = d * 8 + 2 * t4 + e; + tro[r][warp][col & 127] = o[d][2 * r + e] * invr[r]; + } + __syncthreads(); +#pragma unroll + for (int r = 0; r < 2; r++) { + float4 v = make_float4(tro[r][warp][4*lane], tro[r][warp][4*lane+1], + tro[r][warp][4*lane+2], tro[r][warp][4*lane+3]); + tq_wht4(v, lane, true); + tro[r][warp][4*lane]=v.x; tro[r][warp][4*lane+1]=v.y; + tro[r][warp][4*lane+2]=v.z; tro[r][warp][4*lane+3]=v.w; + } + __syncthreads(); +#pragma unroll + for (int r = 0; r < 2; r++) + if (g == gi) { + int t = q0 + warp * 16 + gi + 8 * r; + if (t < T) { + float* orow = out + (size_t)t * nh * HD + h * HD; + const float* gate = qg ? qg + (size_t)t * nh * 2 * HD + h * 2 * HD + HD : nullptr; + for (int d = 16 * gg; d < 16 * gg + 16; d++) + for (int e = 0; e < 2; e++) { + int col = d * 8 + 2 * t4 + e; + orow[col] = tro[r][warp][col & 127] * (gate ? sigmoid(gate[col]) : 1.0f); + } + } + } + __syncthreads(); // the staging cells are free before the next gi + } +#endif #endif } // --llama-numerics prefill attention: f32 throughout, like llama.cpp's CPU tiled path (the tensor-core kernel above @@ -3472,6 +6628,10 @@ __device__ void attn_prefill_llama(const float* q, const u16* kc, const u16* vc, const int* step, int T, int nh, int nkv, float scale, const unsigned* qm, int mw, const float* sink, int win) { constexpr int R = (HD + 127) / 128; +#if V_MODE >= 4 + // query half x warp x 128 dims: one WHT group per warp, reused across its eight rows. + __shared__ float tro[2][4][128]; +#endif extern __shared__ __align__(16) u16 fa_sm[]; float *sq = (float*)fa_sm, *sc = sq + HD; int h = blockIdx.y, kvh = h / (nh / nkv), tid = threadIdx.x, w = tid >> 5, lane = tid & 31; @@ -3665,3 +6825,30 @@ extern "C" __global__ void __launch_bounds__(1024) qsa_select(const float* score if (tid == 0) sel[0] = 4 * top + pos + 1 - 4 * nb; } } + +// ---- CPU decode attention over a host-RAM KV cache (src/host_attn.rs), through a mapped mailbox ---- +// ha_post copies the queries and positions into mapped memory, then raises the request (word 0) with a fresh +// sequence number and the layer's context address (words 4-5). The CPU worker spins on it, computes, writes the +// partials and raises done (word 16). ha_wait holds the stream until then, so the next launch reads the partials. +extern "C" __global__ void ha_post(const float* q, const int* step, float* mq, int* ms, int nq, int ns, + unsigned int* mb, unsigned int* seq, unsigned long long ctx) { + for (int i = threadIdx.x; i < nq; i += blockDim.x) mq[i] = q[i]; + for (int i = threadIdx.x; i < ns; i += blockDim.x) ms[i] = step[i]; + __threadfence_system(); + __syncthreads(); + if (threadIdx.x == 0) { + unsigned int s = seq[0] + 1; + seq[0] = s; + *(volatile unsigned long long*)(mb + 4) = ctx; + __threadfence_system(); + *(volatile unsigned int*)mb = s; + } +} +extern "C" __global__ void ha_wait(const unsigned int* mb, const unsigned int* seq) { + unsigned int s = seq[0], spins = 0; + while (((volatile const unsigned int*)mb)[16] != s) { + __nanosleep(64); + if (++spins == (1u << 28)) __trap(); // tens of seconds: the CPU worker is gone + } + __threadfence_system(); +} diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index f07f182c..15fd67df 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -3,7 +3,7 @@ use crate::quant::{GgmlType, tables::*}; use anyhow::{Context, bail}; -use crate::backend::{Backend, Buf, SAME_X}; +use crate::backend::{BATCHED, Backend, Buf, DeviceTimer, MOE_GATE_X, PrefillRead, SAME_X}; use cudarc::driver::{CudaContext, CudaEvent, CudaFunction, CudaGraph, CudaSlice, CudaStream, DevicePtr, PinnedHostSlice, LaunchConfig, PushKernelArg, result, sys}; use cudarc::nvrtc::Ptx; use std::collections::{BTreeMap, HashMap, VecDeque}; @@ -13,37 +13,152 @@ use std::sync::Arc; mod nvrtc; -const QTYPES: [GgmlType; 29] = { +pub(crate) const QTYPES: [GgmlType; 30] = { use GgmlType::*; - [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] + [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, PTQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -const KERNELS: [&str; 54] = [ - "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", - "kv_store", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", - "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", +pub(crate) const KERNELS: [&str; 89] = [ + "ds_rope", "rope_freq", "rope_cs", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "swiglu_clamp", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", + "hc_mix_q", "hc_write_norm", "kv_store", "kv_store_turbo", "attn_merge", "ha_post", "ha_wait", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", + "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", "gemm_splitk_sum", "x_to_f16", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", - "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_merge", - "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_ffn_sum", "ink_route", + "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_ctrl_gate_b", "ink_ctrl_out_b", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_128", "ink_attn_128_q4", "ink_attn_merge", + "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_128_old", "ink_attn_prefill_128_kp", "ink_attn_prefill_128_kp16", "ink_attn_prefill_128_tc", "ink_attn_prefill_sh_32", "ink_attn_prefill_sh_64", "ink_attn_prefill_sh_128", "ink_ffn_sum", "ink_ffn_sum_mb", "ink_slots", "ink_route", "attn_sel", "mla_attn", "mla_attn_tc", "mla_combine", "idx_score", "idx_score_dec", "vit_attn", "vit_norm", "vit_bias", "vit_rope", "vit_attn_tc_80", "vit_attn_tc_128", ]; pub use crate::backend::{ATT_GQA_MIN, ATT_SPLITS, GEMM_BM, GpuTensor}; use crate::backend::ATT_SPLITS_1; +/// Kernel-choice flags read from the environment once, when the `Gpu` is made: they sit on the token path, so a +/// lookup per launch is not worth it. +#[derive(Clone, Copy)] +pub(crate) struct InkFlags { + /// `STRATA_DS_FAST_KERNELS=auto` (default) uses the tiled controllers, the 128-key decode attention + /// (`ink_attn_128`, on a q4 cache `ink_attn_128_q4`) and `kp16` only when the run has more than one device; + /// `1` forces them on, `0` forces the old kernels. One card keeps the `main` kernels (the greedy output must not + /// change). The HIP backend passes its own default here (see `hip::ink_flags_from`). + pub(crate) fast: bool, + /// `STRATA_CTRL_TILE=0` forces the per-token `ink_ctrl_*` pair; unset follows `fast`. + pub(crate) ctrl_tile: bool, + /// `STRATA_DS_ATTN_OLD=1` keeps the scalar/one-query-a-warp attention kernels for a measurement window. + pub(crate) attn_old: bool, + /// `STRATA_DS_ATTN_KP4=1` selects the four-query 128-key tile prefill kernel. + pub(crate) attn_kp4: bool, + /// `STRATA_DS_ATTN_TC=1` runs the prompt attention of an f16 cache on the tensor cores (`ink_attn_prefill_128_tc`). + pub(crate) attn_tc: bool, + /// `STRATA_DS_ATTN_Q8_SHARED=0` disables shared Q8 prefill. + attn_q8_shared: bool, + /// `STRATA_DS_ATTN_Q8_HD128=0` disables specialized Q8 decode. + attn_q8_hd128: bool, +} + +impl InkFlags { + pub(crate) fn from_parts(fast: Option<&str>, multi: bool, ctrl: Option<&str>, attn_old: Option<&str>, attn_kp4: Option<&str>) -> Self { + let on = |v: Option<&str>, default: bool| v.map_or(default, |v| v != "0"); + let fast = match fast { + None | Some("auto") => multi, + Some("0") => false, + Some(_) => true, + }; + Self { fast, ctrl_tile: on(ctrl, fast), attn_old: on(attn_old, false), attn_kp4: on(attn_kp4, false), attn_tc: std::env::var_os("STRATA_DS_ATTN_TC").is_some_and(|v| v != "0"), attn_q8_shared: false, attn_q8_hd128: false } + } + fn with_cuda_q8(mut self, shared: Option<&str>, decode: Option<&str>) -> Self { + self.attn_q8_shared = shared != Some("0"); + self.attn_q8_hd128 = decode != Some("0"); + self + } + + fn from_env() -> Self { + let multi = std::env::var("STRATA_DS_DEVICES") + .map_or(false, |v| v.split(',').filter(|d| !d.trim().is_empty()).count() > 1); + let flags = Self::from_parts( + std::env::var("STRATA_DS_FAST_KERNELS").ok().as_deref(), + multi, + std::env::var("STRATA_CTRL_TILE").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_OLD").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_KP4").ok().as_deref(), + ); + flags.with_cuda_q8( + std::env::var("STRATA_DS_ATTN_Q8_SHARED").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_Q8_HD128").ok().as_deref(), + ) + } +} + +#[derive(Debug, PartialEq, Eq)] +enum InkPrefillKernel { + KeyParallel4, + KeyParallel16, + Old, + Shared, + Grouped, +} + +impl InkFlags { + fn decode_kernel(self, kv_mode: u32, hd: usize, nr: usize) -> (&'static str, usize) { + if hd == 128 && kv_mode == 1 && self.attn_q8_hd128 && !self.attn_old { + ("ink_attn_q8_hd128", 64) + } else { + ink_attn_pick(kv_mode, self.fast && !self.attn_old, hd, nr) + } + } + + fn prefill_kernel(self, kv_mode: u32, hd: usize, nh: usize, nkv: usize, win: usize) -> InkPrefillKernel { + if hd == 128 && kv_mode == 0 && (self.fast || self.attn_kp4) && !self.attn_old { + if self.attn_kp4 { InkPrefillKernel::KeyParallel4 } else { InkPrefillKernel::KeyParallel16 } + } else if hd == 128 && self.attn_old { + InkPrefillKernel::Old + } else if (kv_mode == 0 || (kv_mode == 1 && hd == 128 && self.attn_q8_shared)) + && win == 0 && nkv > 0 && nh % nkv == 0 && (1..=4).contains(&(nh / nkv)) { + InkPrefillKernel::Shared + } else { + InkPrefillKernel::Grouped + } + } +} + pub struct Gpu { pub ctx: Arc, pub stream: Arc, /// Takes every second launch inside `batch`, so a captured graph runs them as parallel branches. side: Arc, + /// `copy_beside`'s stream: host copies apart from `side`, which `batch` also launches kernels on. + copy: Arc, + /// Set while `copy_beside` runs (its copies go to `copy`); the event its copies end with. + in_copy: std::sync::atomic::AtomicBool, + copy_ev: std::sync::Mutex>, /// Launches so far in the current `batch` (usize::MAX outside one). nb: AtomicUsize, fns: HashMap, /// The int8 prefill GEMM (`gemmi_*`/`gemmis_*`) is compiled in and loaded: sm_80+ only (see `int8_gemm_arch`). i8_gemm: bool, + /// TU116/TU117 (sm_75 without tensor cores) native `__dp4a` path for `gemmi_*`/`gemmis_*`. + dp4a_gemm: bool, /// q8 rows of the last integer GEMM's X (see quant_q8 in kernels.cu), grown on demand, and which x they hold /// (x, x_stride, n_x, cols) for a `SAME_X` call; None after a call without it that did not quantize. q8: std::sync::Mutex<(CudaSlice, Option<[u64; 4]>)>, - /// The kernels were compiled for KV cache mode (0 = f16, 1 = q8, 2 = q4). + prefill_input: std::sync::Mutex>, + moe_gate_q8: std::sync::Mutex, Option<[u64; 4]>)>>, + /// `gemmd_*` scratch for a GEMM that two blocks share the columns of: a slot per stream (see `GEMMD_SLOT`), + /// allocated by the first such GEMM. + gd: std::sync::OnceLock>, + /// Split-K partial sums of the batched f16 GEMM, a slot per stream as `gd`. + sk: std::sync::OnceLock>, + /// gemmm_*'s x as halves: two slots of `XH_SLOT` (by stream, as `sk`). + xh: std::sync::OnceLock>, + /// What `xh` holds ([x, x_stride, nd, cols, slot]), for a gemm with SAME_X. + xk: std::sync::Mutex>, + /// Tile counters of gemmm_*'s split K: two slots of `SPLITK_TILES` (by stream, as `sk`). + skc: std::sync::OnceLock>, + /// Streaming multiprocessors. + sms: usize, + /// The kernels were compiled for these independent K and V cache modes; `kv_mode` is the symmetric view + /// (`kv_mode()`: the shared mode, 10 for mixed K/V). pub kv_mode: u32, + pub kv_k_mode: u32, + pub kv_v_mode: u32, + /// The environment's kernel-choice flags, read once at creation. + flags: InkFlags, /// The GPU has int8 tensor-core mma (sm_80+). Turing runs the prefill GEMM on the f16 path instead. pub int8_mma: bool, /// sm_75: m16n8k8 mma, 64 KB of shared memory a block (no int8 mma, unlike sm_80+; unlike sm_70 it has no m8n8k4). @@ -57,12 +172,20 @@ pub struct Gpu { /// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next /// one while the GPU works (expert streaming in prefill). Head offset and the regions queued copies still read. ring: std::sync::Mutex<(PinnedHostSlice, usize, VecDeque<(usize, usize, CudaEvent)>)>, + /// Events behind `side_mark`/`main_mark` (the last 64) and how many were made. + marks: std::sync::Mutex<(Vec, usize)>, /// Recorded by `wait`. done: CudaEvent, /// The side stream after the last `beside`'s copies; the next `beside` makes the stream wait for it. lag: std::sync::Mutex>, /// rope_freq tables by (base bits, n_rot), and the ones a graph capture asked for (see `rope_fr`). fr: std::sync::Mutex<(HashMap<(u32, usize), CudaSlice>, Vec<(f32, usize)>)>, + /// rope_cs scratch (ROPE_CS (sin, cos) pairs), allocated with the first rope_freq table. + cs: std::sync::OnceLock>, + /// `mla_attn`'s split partials, grow-only (not for a graph capture: a grown buffer frees the old one). + mla_part: std::sync::Mutex>, + /// Host ranges pinned by `host_register` (address, length), unpinned on drop. + pinned: std::sync::Mutex>, } const RING: usize = 64 << 20; @@ -71,34 +194,96 @@ const RING: usize = 64 << 20; const RING_MIN: usize = 256 << 10; /// `nb` inside `beside`: launches stay on the main stream, copies go to the side stream. const BESIDE: usize = usize::MAX - 1; +/// `gemmd_*` splits the columns of a matrix of at most this many rows between blocks. Measured on an RTX 3060 +/// with Qwen3-4B: the 9728-row FFN matrices gain at 8 and 16 positions and lose 9% at 64 (split only up to half as +/// many rows there); the output head (151936 rows) fills the card without the split. +const GEMMD_SPLIT_ROWS: usize = 16384; +/// A scratch slot of `gemmd_*`: a count per 128 rows, then the partial sums of the segments (ks x positions x rows +/// floats, at most 2 x 64 x `GEMMD_SPLIT_ROWS`). +const ROPE_CS: usize = 1 << 17; +/// Blocks a split-K batched f16 GEMM aims for a SM (`STRATA_SPLITK` overrides the total), and the floats of its +/// partial sums a stream. Qwen3-4B BF16 on the RTX 3060 (28 SMs), batch_speed step at 64 rows: 42.4 ms at 1 a SM, +/// 39.0 at 2, 41.3 at 6; at 16 rows 29.9, 29.0, 29.6. +const SPLITK_PER_SM: usize = 2; +const SPLITK_SLOT: usize = 1 << 21; +/// Halves in one slot of `xh`: 64 positions of 32768. +const XH_SLOT: usize = 1 << 21; +/// Tiles a split gemmm_* launch may have (a split one has fewer than its target blocks). +const SPLITK_TILES: usize = 256; +const GEMMD_SLOT: usize = GEMMD_SPLIT_ROWS / 128 * 4 + 2 * 64 * GEMMD_SPLIT_ROWS * 4; /// A recorded graph. Its handles are plain CUDA driver handles, which any thread may launch once the context is /// bound (cudarc leaves `CudaGraph` without `Send` only because it holds raw pointers). struct Graph(CudaGraph); -const AMAX_PARTS: usize = 64; +pub(crate) const AMAX_PARTS: usize = 64; unsafe impl Send for Graph {} /// `--llama-numerics`: quantize activations like llama.cpp's CPU q8_K (one scale per 256) for every integer matmul, /// and run attention as its CPU flash attention does (LLAMA_Q8 in kernels.cu). pub fn llama_numerics() -> bool { std::env::var_os("STRATA_LLAMA_NUMERICS").is_some() } -/// KV cache mode (`0 = f16`, `1 = q8`, `2 = q4`, `3 = q2`): read once by Gpu::new and Vk::new. -pub fn kv_mode() -> u32 { - if let Ok(v) = std::env::var("STRATA_KV") { - if v == "q2" { return 3; } - if v == "q4" { return 2; } - if v == "q8" { return 1; } - return 0; +/// Independent per-side cache modes: `0 = f16`, `1 = q8`, `2 = q4`, `3 = q2`, +/// `4 = turbo4`, `5 = turbo3`, `6 = turbo2`. The K and V halves may differ. +fn parse_kv_mode(s: &str) -> u32 { + match s { + "q2" => 3, "q4" => 2, "q8" => 1, + "turbo4" | "turboquant" => 4, + "turbo3" => 5, + "turbo2" => 6, + _ => 0, + } +} + +pub fn kv_k_mode() -> u32 { + if let Ok(s) = std::env::var("STRATA_KV_K") { return parse_kv_mode(&s); } + if let Ok(s) = std::env::var("STRATA_KV") { + return match s.as_str() { + "turbo4-3" | "turbo4v3" => 4, "turbo4-2" | "turbo4v2" => 4, + "turbo3-2" | "turbo3v2" => 5, + other => parse_kv_mode(other), + }; } u32::from(std::env::var_os("STRATA_KV_Q8").is_some()) } +pub fn kv_v_mode() -> u32 { + if let Ok(s) = std::env::var("STRATA_KV_V") { return parse_kv_mode(&s); } + if let Ok(s) = std::env::var("STRATA_KV") { + return match s.as_str() { + "turbo4-3" | "turbo4v3" => 5, "turbo4-2" | "turbo4v2" => 6, + "turbo3-2" | "turbo3v2" => 6, + other => parse_kv_mode(other), + }; + } + u32::from(std::env::var_os("STRATA_KV_Q8").is_some()) +} + +/// Legacy symmetric view: the shared mode when K and V match, 10 for a mixed layout. +/// Callers that only care about "is the cache quantized at all" keep working. +pub fn kv_mode() -> u32 { + let (k, v) = (kv_k_mode(), kv_v_mode()); + if k == v { k } else { 10 } +} + +/// TurboQuant bits of a cache side in mode `m` (turbo3 = 5, turbo2 = 6, else 4). +pub(crate) fn tq_bits(m: u32) -> u32 { match m { 5 => 3, 6 => 2, _ => 4 } } + +/// u16 words a cache row of `n` values occupies in mode `m`. +pub(crate) fn kv_mode_words(m: u32, n: usize) -> usize { + match m { 1 => n * 17 / 32, 2 | 4..=6 => n * 9 / 32, 3 => n * 3 / 16, _ => n } +} + /// `--kv q8`: KV cache rows in ggml q8_0 form (`kv_mode() == 1`). pub fn kv_q8() -> bool { kv_mode() == 1 } +/// Backends without per-side K/V formats only handle a symmetric legacy layout. `kv_mode()` reports 10 for a +/// mixed layout, which would otherwise pass a `<= 3` guard and reach an `unreachable!` in the size helpers. +pub fn kv_legacy_symmetric(k: u32, v: u32) -> bool { k == v && k <= 3 } + /// `STRATA_GEMM_FMA`: force the CUDA-core FMA fallback in the f16 prefill kernels instead of the sm_70 tensor-core -/// path (`GEMM_TC` in kernels.cu). It covers both the f16 prefill GEMM and the prefill attention (`attn_prefill_t`): +/// path (`GEMM_TC` in kernels.cu), and on sm_75 instead of `m16n8k8` (`MMA_FMA`, see `turing_fma`; Turing cards without +/// tensor cores take it by default). It covers both the f16 prefill GEMM and the prefill attention (`attn_prefill_t`): /// the attention's P staging tile is part of every request, so the shared-memory size does not depend on it. /// Ignored on sm_80+, which always uses `mma.m16n8k16`. pub fn gemm_fma() -> bool { std::env::var_os("STRATA_GEMM_FMA").is_some() } @@ -106,11 +291,11 @@ pub fn gemm_fma() -> bool { std::env::var_os("STRATA_GEMM_FMA").is_some() } /// Prefill attention query / key tile sizes in positions. `FA_BQ` is one warp's 16 query rows times the four warps /// of the 128-thread block; `FA_BK` is the K/V tile depth and must stay a multiple of 32 for the sm_70 `m8n8k4` /// and sm_80+ `m16n8k16` fragment loops. Injected into kernels.cu by `source()`, never edited there. -const FA_BQ: usize = 64; -const FA_BK: usize = 32; +pub(crate) const FA_BQ: usize = 64; +pub(crate) const FA_BK: usize = 32; /// Prefill GEMM K tile in halves (default, candidate C3 overrides it with `STRATA_GEMM_BK=32`). `GEMM_BM` lives in /// `backend.rs` because the prefill tile-list builder shares it with Vulkan. -const GEMM_BK: usize = 64; +pub(crate) const GEMM_BK: usize = 64; /// Row padding of the attention shared-memory tiles (`PQ = HD + 8`, `FA_BK + 8` in `attn_prefill_t`). const ATTN_SMEM_PAD: usize = 8; @@ -144,13 +329,13 @@ impl Tune { } /// `default` unless `v` parses to a value accepted by `valid`. -fn tuned(v: Option<&str>, default: usize, valid: impl Fn(usize) -> bool) -> usize { +pub(crate) fn tuned(v: Option<&str>, default: usize, valid: impl Fn(usize) -> bool) -> usize { v.and_then(|s| s.trim().parse::().ok()).filter(|&x| valid(x)).unwrap_or(default) } /// Rows per warp: the family override (`STRATA_RPW_MOE`/`_DENSE`) first, then `STRATA_RPW`, then the shape default. /// 1..=64 keeps a block's row loop bounded; anything else falls back one level, as `tuned` does. -fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize { +pub(crate) fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize { let ok = |v: usize| (1..=64).contains(&v); family.and_then(|s| s.trim().parse().ok()).filter(|&v| ok(v)) .or_else(|| global.and_then(|s| s.trim().parse().ok()).filter(|&v| ok(v))) @@ -159,16 +344,16 @@ fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize /// Threads per block of the integer GEMV: the family override first, then the global value, then 256. Only the /// three warp counts the kernel's row mapping can tile are accepted (4/8/16 warps per block). -fn gemv_block_from(global: Option<&str>, family: Option<&str>) -> u32 { +pub(crate) fn gemv_block_from(global: Option<&str>, family: Option<&str>) -> u32 { let ok = |v: u32| matches!(v, 128 | 256 | 512); family.and_then(|s| s.trim().parse::().ok()).filter(|&v| ok(v)) .or_else(|| global.and_then(|s| s.trim().parse::().ok()).filter(|&v| ok(v))) .unwrap_or(256) } -fn source(kv_mode: u32, gemm_tc: bool) -> String { source_with(kv_mode, gemm_tc, Tune::from_env()) } +fn source(k_mode: u32, v_mode: u32, gemm_tc: bool) -> String { source_with(k_mode, v_mode, gemm_tc, Tune::from_env()) } -fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { +fn source_with(k_mode: u32, v_mode: u32, gemm_tc: bool, tune: Tune) -> String { let join = |v: Vec| v.join(","); format!( "__device__ const unsigned long long iq2xs_grid[512] = {{{}}};\n\ @@ -180,9 +365,9 @@ fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ __device__ const float tq_lut[4096] = {{{}}};\n\ - #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define GEMM_TC {}\n\ + #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define K_MODE {}\n#define V_MODE {}\n#define TQ_KBITS {}\n#define TQ_VBITS {}\n#define GEMM_TC {}\n\ #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS {}\n#define GEMV_LOADW {}\n\ - #define FA_BQ {}\n#define FA_BK {}\n{}", + #define FA_BQ {}\n#define FA_BK {}\n#define STRATA_HIP 0\n{}", join(IQ2XS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), join(IQ2XXS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), join(IQ2S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), @@ -193,7 +378,11 @@ fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), join(crate::quant::TQ_LUT.iter().flatten().map(|v| format!("{v:e}f")).collect()), llama_numerics() as u8, - kv_mode as u8, + k_mode as u8, // legacy KV_MODE alias: the K half, for code not yet split + k_mode as u8, + v_mode as u8, + tq_bits(k_mode), + tq_bits(v_mode), gemm_tc as u8, GEMM_BM, tune.gemm_bk, @@ -211,7 +400,7 @@ fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { fn attn_prefill_smem(hd: usize) -> usize { attn_prefill_smem_bk(hd, FA_BK) } /// `attn_prefill_smem` for a K/V tile depth of `bk` keys (16 on Turing at head_dim 256, else `FA_BK`). -fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { +pub(crate) fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { let pq = hd + ATTN_SMEM_PAD; 2 * (FA_BQ + 2 * bk) * pq + 2 * FA_BQ * (bk + ATTN_SMEM_PAD) } @@ -242,12 +431,36 @@ fn device_log(device: usize, name: &str, arch: &str, cc: (i32, i32), gemm_fma: b (c, _) if c < (7, 0) => " (pre-Volta, not supported)", // not reached from `Gpu::new`: `min_arch_error` (c, false) if c < (7, 5) => " (Volta, m8n8k4)", (c, true) if c < (7, 5) => " (Volta fallback)", + (c, true) if c < (8, 0) => " (Turing, CUDA-core FMA)", (c, _) if c < (8, 0) => " (Turing, m16n8k8)", _ => "", // sm_80+ always uses mma.m16n8k16 }; format!("cuda device {device}: {name}, {arch}{path}") } +/// The Turing chips without tensor cores, TU116 and TU117: the GTX 16 series, MX450/MX550, the T400-T2000 workstation +/// and laptop cards and the CMP 30HX. CUDA does not report tensor cores, so the product name decides. +fn no_tensor_cores(name: &str) -> bool { + const TU11X: [&str; 10] = ["MX450", "MX550", "T400", "T500", "T550", "T600", "T1000", "T1200", "T2000", "30HX"]; + name.contains("GTX 16") || name.split_whitespace().any(|w| TU11X.contains(&w)) +} + +/// Turing cards without tensor cores still execute `mma.sync` m16n8k8, but far slower than CUDA-core FMA: on a GTX +/// 1660 SUPER the f16 prefill ran ~3.5x slower than llama.cpp's. On sm_75 such a card, or `gemm_fma` +/// (`STRATA_GEMM_FMA`) on any sm_75 card, compiles the CUDA-core branch of `mma16816` instead (`MMA_FMA` in +/// kernels.cu, covering the f16 prefill GEMM and the prefill attention); `keep_tc` (`STRATA_GEMM_TC=1`) keeps the +/// tensor cores. +fn turing_fma(name: &str, cc: (i32, i32), gemm_fma: bool, keep_tc: bool) -> bool { + cc == (7, 5) && !keep_tc && (gemm_fma || no_tensor_cores(name)) +} + +/// The kernel source a device compiles: `source()`, with `#define MMA_FMA 1` in front when `turing_fma` picked the +/// CUDA-core branch. The define is part of the text the cubin cache key hashes, so the two variants never share a file. +fn device_source(k_mode: u32, v_mode: u32, gemm_tc: bool, mma_fma: bool) -> String { + let src = source(k_mode, v_mode, gemm_tc); + if mma_fma { format!("#define MMA_FMA 1\n{src}") } else { src } +} + /// Whether the device has int8 tensor cores, i.e. whether the `gemmi_*`/`gemmis_*` prefill GEMM exists in its cubin /// and may be launched. Volta (sm_70) does not: the s8 `mma` shapes need sm_80, so the kernels are compiled out of /// the sm_70 build (see the `#if __CUDA_ARCH__ >= 800` guards in kernels.cu) and dropped from the loaded name list. @@ -259,10 +472,11 @@ fn int8_gemm_arch(cc: (i32, i32)) -> bool { cc.0 >= 8 } /// decode GQA kernels (8 query slices per head group plus the cp.async K/V chunks at head_dim 128/256, `attn`), /// `usize::MAX` for `gemvn_*` whose request depends on the tensor shape (`xq_smem * nt`, `gemv_cfg`), and `None` /// for every kernel that never asks for more than the 48 KiB default (`attn_decode_*`, `attn_merge`, the rest). -fn dyn_shmem_need(name: &str) -> Option<(&'static str, usize)> { +pub(crate) fn dyn_shmem_need(name: &str) -> Option<(&'static str, usize)> { let family = if name.starts_with("attn_prefill") { "attn_prefill_*" } else if name.starts_with("attn_decode_gqa") { "attn_decode_gqa*" } else if name.starts_with("gemvn") { "gemvn_*" } + else if name.starts_with("mla_attn") { "mla_attn*" } else { return None }; let need = match family { "attn_prefill_*" => attn_prefill_smem(name["attn_prefill_".len()..].parse::().ok()?), @@ -355,15 +569,21 @@ fn smem_log(family: &str, optin: usize, stat: usize, set: Option, carveou format!("cuda shared memory: opt-in {optin} B per block, {family}: {stat} B static, dynamic max {dynamic}, carveout {carveout}") } -/// The kernel names to load from the cubin: the full list on sm_80+, without the int8 prefill GEMM (`gemmi_*` and -/// `gemmis_*`, 23 non-float types x 2 fewer names) on a device where that code is not compiled in. Pure so a CPU test can pin -/// both lists (326 / 280 names). -fn kernel_names(sm80: bool) -> Vec { - let int8 = move |&&t: &&GgmlType| sm80 && !t.float_x(); +/// The kernel names to load from the cubin: the full list on sm_80+, without the int8 GEMM (`gemmi_*`, `gemmis_*` and +/// `gemmd_*`, 23 non-float types x 3 fewer names) on a device where that code is not compiled in. Pure so a CPU test can pin +/// both lists (394 / 325 names). +pub(crate) fn kernel_names(sm80: bool) -> Vec { + kernel_names_with(sm80, false) +} + +fn kernel_names_with(sm80: bool, dp4a: bool) -> Vec { + let int8_i = move |&&t: &&GgmlType| (sm80 || dp4a) && !t.float_x(); + let int8_d = move |&&t: &&GgmlType| sm80 && !t.float_x(); KERNELS.iter().map(|s| s.to_string()) - .chain(QTYPES.iter().flat_map(|&t| ["dequant", "gemv", "gemvn", "moe_gemv", "gemm", "gemms"].map(|p| kname(p, t)))) + .chain(QTYPES.iter().flat_map(|&t| ["dequant", "gemv", "gemvn", "moe_gemv", "gemm", "gemms", "gemmm"].map(|p| kname(p, t)))) .chain(QTYPES.iter().flat_map(|&t| ["gemv", "gemvn", "moe_gemv"].map(|p| kname(p, t) + "_p"))) - .chain(QTYPES.iter().filter(int8).flat_map(|&t| [kname("gemmi", t), kname("gemmis", t)])) + .chain(QTYPES.iter().filter(int8_i).flat_map(|&t| [kname("gemmi", t), kname("gemmis", t)])) + .chain(QTYPES.iter().filter(int8_d).map(|&t| kname("gemmd", t))) .chain([64, 128, 256, 512].iter().flat_map(|h| [format!("attn_decode_{h}"), format!("attn_decode_gqa_{h}")])) .chain(["attn_decode_gqa4_128".to_string()]) .collect() @@ -380,7 +600,7 @@ fn cache_key(src: &str, arch: &str, nvrtc: &str) -> u64 { h.finish() } -/// Compile `src` to a cubin for `arch`, reusing `$XDG_CACHE_HOME/rusting_strata/.cubin` when present. A cubin, +/// Compile `src` to a cubin for `arch`, reusing `/.cubin` when present. A cubin, /// unlike PTX, needs no driver JIT at load (~6 s per start whenever the driver's own JIT cache missed). The hash /// covers `(src, arch, NVRTC version)`; when NVRTC cannot be loaded the tag is `"unverified"`, so a cache entry is /// no longer reusable and the run reports the missing library instead of silently reusing a cubin. @@ -394,9 +614,9 @@ fn ptx(src: &str, arch: &'static str, cc: (i32, i32)) -> anyhow::Result { } let tag = nvrtc.map(|(maj, min)| format!("{maj}.{min}")).unwrap_or_else(|| "unverified".to_string()); let tag = format!("{tag} {}", nvrtc::extra_opts()).trim_end().to_string(); - let dir = std::env::var_os("XDG_CACHE_HOME").map(Into::into) - .unwrap_or_else(|| std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".cache")) - .join("rusting_strata"); + // Windows has no HOME: the cubins went to `.cache` in the working folder, unwritable from system32, and were + // compiled again on every start. + let dir = crate::expert_cache::cache_dir(); let path = dir.join(format!("{:016x}.cubin", cache_key(src, arch, &tag))); if let Ok(b) = std::fs::read(&path) { // Refresh mtime so pruning below keeps a cubin that is still in use. @@ -431,6 +651,14 @@ pub fn cfg(grid: (u32, u32), block: u32, smem: u32) -> LaunchConfig { /// otherwise) names the kernel that raised it. Debugging only: no graphs, and every launch pays a stream sync. static SYNC_EACH: std::sync::LazyLock = std::sync::LazyLock::new(|| std::env::var_os("STRATA_CUDA_SYNC").is_some()); +/// `attn_host`: tokens and floats a token (nh * (hd + 2)) its mapped staging holds; queries, partials and positions, +/// shared by all layers (the stream runs them in turn), never freed since captured graphs keep their addresses. +const HA_T: usize = 64; +const HA_W: usize = 64 * 514; +/// Queries, partials, positions, the mailbox (mapped) and the sequence counter (device). +static HA_STAGE: std::sync::Mutex> = std::sync::Mutex::new(None); +static CTX: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + macro_rules! launch { ($g:expr, $name:expr, $cfg:expr, $($a:expr),* $(,)?) => {{ let f = $g.f($name); @@ -443,7 +671,11 @@ macro_rules! launch { }}; } -fn kname(prefix: &str, ty: GgmlType) -> String { format!("{prefix}_{}", ty.name().to_lowercase()) } +/// rms_norm_rope's block: 128 threads for a head of 128 or less (the threads past n held 0 for block_sum, so the bits +/// are the same), else 256. +fn nr_block(n: usize) -> u32 { if n <= 128 { 128 } else { 256 } } + +pub(crate) fn kname(prefix: &str, ty: GgmlType) -> String { format!("{prefix}_{}", ty.name().to_lowercase()) } /// The UUID of every CUDA device in CUDA's order, the order `Gpu::new` counts in: `None` for a device the driver /// gives none for, empty when CUDA does not load. No context is created. NVIDIA's Vulkan driver reports the same 16 @@ -463,8 +695,8 @@ pub fn device_uuids() -> Vec> { impl Gpu { pub fn new(device: usize) -> anyhow::Result { - let kv_mode = kv_mode(); - anyhow::ensure!(!(kv_mode > 0 && llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)"); + let (kv_k_mode, kv_v_mode) = (kv_k_mode(), kv_v_mode()); + anyhow::ensure!(!((kv_k_mode > 0 || kv_v_mode > 0) && llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)"); if !unsafe { sys::is_culib_present() } { return Err(anyhow::anyhow!(if cfg!(windows) { "no NVIDIA driver (nvcuda.dll)" } else { "no NVIDIA driver (libcuda.so)" })).context("CUDA init"); } @@ -480,10 +712,16 @@ impl Gpu { .unwrap_or(48 << 10).max(48 << 10) as u32; let arch: &'static str = Box::leak(format!("sm_{maj}{min}").into_boxed_str()); let gemm_fma = gemm_fma(); - crate::say!("{}", device_log(device, &ctx.name().unwrap_or_default(), arch, (maj, min), gemm_fma)); + let name = ctx.name().unwrap_or_default(); + let mma_fma = turing_fma(&name, (maj, min), gemm_fma, std::env::var_os("STRATA_GEMM_TC").is_some()); + let fma_path = if (maj, min) >= (7, 5) { mma_fma } else { gemm_fma }; // the branch actually compiled + crate::say!("{}", device_log(device, &name, arch, (maj, min), fma_path)); let stream = ctx.new_stream()?; - let module = ctx.load_module(ptx(&source(kv_mode, !gemm_fma && (maj, min) < (7, 5)), arch, (maj, min))?).context("load cubin")?; + let src = device_source(kv_k_mode, kv_v_mode, !gemm_fma && (maj, min) < (7, 5), mma_fma); + let module = ctx.load_module(ptx(&src, arch, (maj, min))?).context("load cubin")?; let i8_gemm = int8_gemm_arch((maj, min)); + let dp4a_gemm = mma_fma && std::env::var_os("STRATA_NO_DP4A").is_none(); + if dp4a_gemm { crate::detail!("cuda device {device}: TU11x native __dp4a prefill GEMM + f16x2 prefill attention enabled"); } let turing = !int8_mma && (maj, min) >= (7, 5); // The per-block dynamic shared memory ceiling the driver reports: 96 KiB on Volta per the roadmap, but // possibly less (reserve), and shared with the function's static part. Never a constant. @@ -492,7 +730,7 @@ impl Gpu { // Per family: the largest static usage, dynamic opt-in and carveout seen, logged once after the load. let mut smem: BTreeMap<&'static str, (usize, Option, Option)> = BTreeMap::new(); let carveout_mode = carveout_mode(); - for n in kernel_names(i8_gemm) { + for n in kernel_names_with(i8_gemm, dp4a_gemm) { let f = module.load_function(&n).with_context(|| format!("kernel {n}"))?; let stat = f.shared_size_bytes().with_context(|| format!("static shared memory of {n}"))?.max(0) as usize; let need = dyn_shmem_need(&n); @@ -518,12 +756,18 @@ impl Gpu { } fns.insert(n, f); } - for (family, (stat, set, co)) in &smem { crate::say!("{}", smem_log(family, optin, *stat, *set, *co)); } + for (family, (stat, set, co)) in &smem { crate::detail!("{}", smem_log(family, optin, *stat, *set, *co)); } + let flags = InkFlags::from_env(); + if kv_k_mode == 1 && kv_v_mode == 1 && flags.attn_q8_hd128 { + let name = "ink_attn_q8_hd128"; + fns.insert(name.to_string(), module.load_function(name).with_context(|| format!("kernel {name}"))?); + } let q8 = std::sync::Mutex::new((stream.alloc_zeros::(1)?, None)); - let am = stream.alloc_zeros(64 * AMAX_PARTS)?; + let am = stream.alloc_zeros(128 * AMAX_PARTS)?; let ring = std::sync::Mutex::new((unsafe { ctx.alloc_pinned::(RING)? }, 0, VecDeque::new())); let done = ctx.new_event(None)?; - Ok(Gpu { ctx, side: stream.fork()?, stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, q8, kv_mode, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, done, lag: Default::default(), fr: Default::default() }) + let sms = ctx.attribute(sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT)? as usize; + Ok(Gpu { ctx, side: stream.fork()?, copy: stream.fork()?, in_copy: Default::default(), copy_ev: Default::default(), stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, dp4a_gemm, q8, prefill_input: Default::default(), moe_gate_q8: Default::default(), gd: Default::default(), sk: Default::default(), xh: Default::default(), xk: Default::default(), skc: Default::default(), sms, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, marks: Default::default(), done, lag: Default::default(), fr: Default::default(), cs: Default::default(), mla_part: Default::default(), pinned: Default::default() }) } fn f(&self, name: &str) -> &CudaFunction { &self.fns[name] } @@ -544,11 +788,23 @@ impl Gpu { let (bs, nr) = (base, n_rot as i32); b.arg(&p); b.arg(&bs); b.arg(&nr); unsafe { b.launch(cfg((1, 1), 256, 0)) }.context("launch rope_freq")?; + if self.cs.get().is_none() { let _ = self.cs.set(self.stream.alloc_zeros::(2 * ROPE_CS)?); } self.stream.synchronize()?; fr.0.insert((base.to_bits(), n_rot), t); Ok(p) } + /// The rope_cs table of nt tokens (positions as rms_norm_rope reads them), or 0 (the kernel computes them itself): + /// no fr table yet, too many tokens, or inside `batch` (two streams would share the scratch). + fn rope_cs(&self, step: u64, kvt: u64, nt: usize, n_rot: usize, fr: u64) -> anyhow::Result { + let n = nt * (n_rot / 2); + let Some(cs) = self.cs.get() else { return Ok(0) }; + if fr == 0 || n == 0 || n > ROPE_CS || self.nb.load(Relaxed) != usize::MAX { return Ok(0); } + let cs = self.ptr(cs); + launch!(self, "rope_cs", cfg((n.div_ceil(256) as u32, 1), 256, 0), cs, step, kvt, nt as i32, n_rot as i32, fr); + Ok(cs) + } + /// The stream for the next launch: inside `batch`, odd launches go to `side`. fn st(&self) -> &Arc { let n = self.nb.load(Relaxed); @@ -580,6 +836,13 @@ impl Gpu { !Self::float_ty(ty) && std::env::var("STRATA_MMQ").map(|v| v.split(',').any(|t| t == ty.name())).unwrap_or(!matches!(ty, GgmlType::IQ2XS | GgmlType::IQ2S) || llama_numerics()) } + /// `mmq` on this device. The dp4a path (TU11x, no int8 tensor cores) takes IQ2_XS and IQ2_S too: #31's cost, scaling + /// the per-16 tensor-core results, does not apply to `__dp4a`, and the alternative there is the FMA-emulated f16 GEMM + /// (GTX 1660 SUPER, IQ2_XS `ffn_gate_exps`: 1.47 -> 4.30 TFLOP/s). `STRATA_MMQ` still decides when it is set. + fn mmq_on(&self, ty: GgmlType) -> bool { + Self::mmq(ty) || (self.dp4a_gemm && matches!(ty, GgmlType::IQ2XS | GgmlType::IQ2S) && std::env::var_os("STRATA_MMQ").is_none()) + } + fn gemm_raw(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, wd: u64, nd: usize, x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32, w_scale: f32) -> anyhow::Result<()> { // Partial super-blocks (Q2_0's 640 columns, BF16's 320) are fine: K steps are 64 deep. if cols % 64 != 0 { bail!("{} matrix with {cols} columns: GEMM needs a multiple of 64", ty.name()); } @@ -590,21 +853,96 @@ impl Gpu { // So does one of at most 32 positions (batched decode): the same blocks, a quarter of the positions in each. let sm = tiles == 0 && (grid.0 * grid.1 < 112 || nd <= 32); let grid = if sm { (grid.0, nd.div_ceil(32) as u32) } else { grid }; - let (same, act) = (act & SAME_X != 0, act & !SAME_X); + let moe_gate = act & MOE_GATE_X != 0; + let (same, batched, act) = (act & SAME_X != 0, act & BATCHED != 0, act & 3); + // Inside `batch` each launch takes the next stream (`st`). An op of several launches (split K and its sum, + // x_to_f16 and gemmm) must keep them all on its first launch's stream, with that stream's scratch slot: else + // the second launch runs on the other stream, beside the first (the batched DeltaNet GEMMs gave other bits + // from run to run). + let n0 = self.nb.load(Relaxed); + let odd = n0 < BESIDE && n0 % 2 == 1; + let pin = || if n0 < BESIDE { self.nb.store(n0, Relaxed) }; + let int8 = ((self.i8_gemm && self.int8_mma) || self.dp4a_gemm) && self.mmq_on(ty) && cols.is_multiple_of(128); let mut q8 = self.q8.lock().unwrap(); + let mut gate = moe_gate.then(|| self.moe_gate_q8.lock().unwrap()); + let q8 = if let Some(gate) = gate.as_deref_mut() { + if !same { + if let Some(cache) = gate.as_mut() { cache.1 = None; } + } + if int8 { + if gate.is_none() { *gate = Some((self.stream.alloc_zeros::(1)?, None)); } + gate.as_mut().unwrap() + } else { &mut *q8 } + } else { &mut *q8 }; let key = Some([x, x_stride as u64, n_x as u64, cols as u64]); let reuse = same && q8.1 == key; + // Without SAME_X x may hold new rows: the f16 copy of an earlier gemmm_* must not serve a later SAME_X GEMM + // (an int8 or tile-list GEMM converts nothing, so its x would match the old key). + if !same { *self.xk.lock().unwrap() = None; } // The int8 path loads q8 rows 16 bytes at a time: their stride (cols * 11 / 8) is aligned only for cols % 128 == 0. // A gemm inside a batch cannot quantize x (the quantize and the gemm would land on different streams): when // the cached q8 rows are not x's (or, without SAME_X, may not be), use the f16 kernel. Volta and Turing have no int8 tensor-core mma: there the // kernels are not loaded (`i8_gemm`), so this gate must dominate `STRATA_MMQ`; they take the f16 gemm_*/gemms_*. - let int8 = self.i8_gemm && self.int8_mma && Self::mmq(ty) && cols.is_multiple_of(128); if !int8 || (!reuse && self.nb.load(Relaxed) < BESIDE) { if !same { q8.1 = None; } - launch!(self, &kname(if sm { "gemms" } else { "gemm" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), + // A batched decode step of few blocks (an f16-path type such as BF16: k_proj is 16 blocks of 64 rows, + // ffn_down 40, on 28 SMs) splits its K steps into segments so the weights stream from more blocks at once; + // gemm_splitk_sum adds the segments in a fixed order. The order differs from one segment's. + // A batched step of 33 to 64 positions: one block of 64 (gemmm_*), not two of 32 (each weight read twice) + // or the big tile of 128 (half its warps idle, 128 registers: two blocks a SM). + let md = batched && tiles == 0 && xrow == 0 && nd > 32 && nd <= 64 && nd * cols <= XH_SLOT; + let (kn, grid) = if md { ("gemmm", (grid.0, 1)) } else { (if sm { "gemms" } else { "gemm" }, grid) }; + // gemmm_* reads x as halves (X is a quarter of the L2 traffic of a 64-position step in f32, half in f16). + let (x, x_stride) = if md { + if self.xh.get().is_none() { let _ = self.xh.set(self.stream.alloc_zeros::(2 * XH_SLOT)?); } + let xh = self.ptr(self.xh.get().unwrap()) + if odd { 2 * XH_SLOT as u64 } else { 0 }; + // k and v after q, up after gate: SAME_X promises x still holds what was converted. + let key = Some([x, x_stride as u64, nd as u64, cols as u64, xh]); + let mut xk = self.xk.lock().unwrap(); + if !(same && *xk == key) { + pin(); + launch!(self, "x_to_f16", Self::grid(nd * cols / 4), x, x_stride as i32, nd as i32, cols as i32, xh); + *xk = key; + } + (xh, cols) + } else { (x, x_stride) }; + let ks = if batched && (sm || md) && tiles == 0 && xrow == 0 { + let target = std::env::var("STRATA_SPLITK").ok().and_then(|v| v.parse().ok()).unwrap_or(SPLITK_PER_SM * self.sms); + target.div_ceil(grid.0 as usize * grid.1 as usize).min(8).min(cols / 64 / 4).min(SPLITK_SLOT / (nd * rows)).max(1) + } else { 1 }; + if ks > 1 { + if self.sk.get().is_none() { let _ = self.sk.set(self.stream.alloc_zeros::(2 * SPLITK_SLOT)?); } + let part = self.ptr(self.sk.get().unwrap()) + if odd { 4 * SPLITK_SLOT as u64 } else { 0 }; + let mut c = cfg(grid, 2 * GEMM_BM as u32, 0); + c.grid_dim.2 = ks as u32; + // gemmm_* adds the segments itself (its last segment of a tile to finish); gemms_* takes gemm_splitk_sum. + if md && rows % 4 == 0 && (grid.0 * grid.1) as usize <= SPLITK_TILES { + if self.skc.get().is_none() { let _ = self.skc.set(self.stream.alloc_zeros::(2 * SPLITK_TILES)?); } + let cnt = self.ptr(self.skc.get().unwrap()) + if odd { 4 * SPLITK_TILES as u64 } else { 0 }; + pin(); + launch!(self, &kname(kn, ty), c, + 0u64, wd, nd as i32, x, x_stride as i32, 0u64, part, rows as i32, rows as i32, (cols / 64) as i32, 0i32, w_scale, y, y_stride as i32, act, cnt); + return Ok(()); + } + pin(); + launch!(self, &kname(kn, ty), c, + 0u64, wd, nd as i32, x, x_stride as i32, 0u64, part, rows as i32, rows as i32, (cols / 64) as i32, 0i32, w_scale); + pin(); + launch!(self, "gemm_splitk_sum", Self::grid(nd * rows), part, ks as i32, nd as i32, rows as i32, y, y_stride as i32, act); + return Ok(()); + } + if md { + pin(); + launch!(self, &kname(kn, ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale, 0u64, 0i32, 0i32, 0u64); + return Ok(()); + } + pin(); + launch!(self, &kname(kn, ty), cfg(grid, 2 * GEMM_BM as u32, 0), tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); // Tile lists: gemm_* skips the tiles of at most 32 positions, which gemms_* takes. if tiles != 0 { + pin(); launch!(self, &kname("gemms", ty), cfg(grid, 2 * GEMM_BM as u32, 0), tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); } @@ -612,10 +950,34 @@ impl Gpu { } // Only SAME_X promises that x still holds what was quantized: the same address can hold new rows. if !same { q8.1 = None; } - let xq = self.q8_x(&mut q8, ty, cols, n_x, x, x_stride)?.expect("int8 GEMM without a quantized x"); + let xq = self.q8_x(q8, ty, cols, n_x, x, x_stride)?.expect("int8 GEMM without a quantized x"); + // A step of a batch of requests: at most 64 rows of x, no tile list. + if self.i8_gemm && batched && tiles == 0 && xrow == 0 && nd <= 64 { + let pb = nd.next_power_of_two().max(8); + let xw = if pb >= 32 { 128 } else { 4096 / pb }; // GEMMD_XW + let ks = if rows <= if nd > 32 { GEMMD_SPLIT_ROWS / 2 } else { GEMMD_SPLIT_ROWS } && cols >= 2 * xw { 2 } else { 1 }; + // Up to 16 positions, split the columns further so the launch has about 256 blocks, at most 8 segments, + // each at least one window. Measured on an RTX 3060, Q8_0, 16 positions: 2048 x 6144 128 -> 104 us (8 + // segments), 4096 x 4096 175 -> 126 us (8), 12288 x 2048 185 -> 169 us (4); Qwen3.5-2B batch_speed 16 + // rows 20.0 -> 19.3 ms a step. At 32 positions the step lost 0.5 ms (24.1 -> 24.6) and at 64 the GEMM. + let ks = if ks > 1 && nd <= 16 { + 256usize.div_ceil(rows.div_ceil(128)).next_power_of_two().clamp(2, 8).min(cols / xw) + .min(2 * 64 * GEMMD_SPLIT_ROWS / (nd * rows)) // scr holds the sums of every segment + } else { ks }; + // The launches of a stream run in order, so each stream has a slot (`st`: the odd launches of a batch go to `side`). + if self.gd.get().is_none() { let _ = self.gd.set(self.stream.alloc_zeros(2 * GEMMD_SLOT)?); } + let slot = self.ptr(self.gd.get().unwrap()) + if odd { GEMMD_SLOT as u64 } else { 0 }; + pin(); + launch!(self, &kname("gemmd", ty), + cfg(((ks * rows.div_ceil(128)) as u32, 1), 256, (2 * pb * (xw + 32 + xw / 8 + xw / 4) + pb / 2 * (xw / 32) * 32) as u32), + wd, xq, nd as i32, pb as i32, ks as i32, slot + (GEMMD_SPLIT_ROWS / 128 * 4) as u64, slot, y, y_stride as i32, rows as i32, cols as i32, act, w_scale); + return Ok(()); + } + pin(); launch!(self, &kname(if sm { "gemmis" } else { "gemmi" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), tiles, wd, nd as i32, xq, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); if tiles != 0 { + pin(); launch!(self, &kname("gemmis", ty), cfg(grid, 2 * GEMM_BM as u32, 0), tiles, wd, nd as i32, xq, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); } @@ -625,7 +987,7 @@ impl Gpu { /// Quantize `x` for the int8 GEMM, unless the cache already holds the same rows; `None` when `ty` or `cols` /// selects the f16 path. Shared by `gemm_raw` and `prequant_gemm_x`. fn q8_x(&self, q8: &mut (CudaSlice, Option<[u64; 4]>), ty: GgmlType, cols: usize, n_x: usize, x: u64, x_stride: usize) -> anyhow::Result> { - if !self.int8_mma || !Self::mmq(ty) || !cols.is_multiple_of(128) { return Ok(None); } + if !(self.int8_mma || self.dp4a_gemm) || !self.mmq_on(ty) || !cols.is_multiple_of(128) { return Ok(None); } let key = Some([x, x_stride as u64, n_x as u64, cols as u64]); if q8.1 == key { return Ok(Some(self.ptr(&q8.0))); } let need = n_x * (cols + cols / 8 + cols / 4); @@ -673,6 +1035,18 @@ impl Gpu { fn gemv_cfg(ty: GgmlType, rows: usize, cols: usize, k: usize) -> (LaunchConfig, i32) { // Float types: one warp per row. Small matrices (32 rows) take one row per block to spread over many SMs; // from 4096 rows 8 per block, as an SM holds only 16 blocks (hc_attn_up 10240 x 320: 28.7 -> 24.8 us). + // Trellis types: 8 warps share the codebook a block loads to shared memory, 4 rows a warp. A single short + // matrix (k = 1, under 2048 columns) reads the codebook from global memory, a row a warp (rpw 0): its blocks + // have too little work to pay for the load. 8 warps a block either way, as the 16 KB table is in every + // block's static shared memory (one-warp blocks: 6 a SM). RTX 3060, tests/tq_probe.rs, us before -> after: + // experts 640x2560 TQK6 pair 230 -> 121, 2560x640 TQK7 147 -> 105; one matrix 640x2560 14.0 -> 10.8, 3 tokens + // 17.3 -> 11.7; 2560x640 15.0 -> 16.2, 3 tokens 18.0 -> 25.1 (4 rows a warp: 43, 36; the Flash-Next models + // have trellis experts only). `STRATA_RPW_TQ` (0, 1, 2 or 4) overrides. + if matches!(ty, GgmlType::TQ2T | GgmlType::TQK6 | GgmlType::TQK7) { + let rpw = std::env::var("STRATA_RPW_TQ").ok().and_then(|v| v.parse().ok()).filter(|r| [0, 1, 2, 4].contains(r)) + .unwrap_or(if k == 1 && cols < 2048 { 0 } else { 4usize }); + return (cfg((rows.div_ceil(8 * rpw.max(1)) as u32, k as u32), 256, 0), rpw as i32); + } if Self::float_ty(ty) { let wpb = if rows >= 4096 { 8 } else { 1 }; return (cfg((rows.div_ceil(wpb) as u32, k as u32), 32 * wpb as u32, 0), 1); @@ -737,7 +1111,7 @@ impl Gpu { // attn_decode_gqa with the f16 cache at head_dim 128 or 256 also holds 2 chunks of K and V for its cp.async, // attn_decode_gqa4_128 one. Turing (sm_75) has 64 KB of shared memory a block: the head_dim 256 chunks do // not fit, so it loads them through registers instead (kernels.cu ATT_RUN_CP). - let cp = self.kv_mode == 0 && (hd == 128 || (hd == 256 && self.int8_mma)); + let cp = self.kv_k_mode == 0 && self.kv_v_mode == 0 && (hd == 128 || (hd == 256 && self.int8_mma)); let g4 = cp && g == 4 && hd == 128; let (name, cp) = if g4 { ("attn_decode_gqa4_128".to_string(), 2 * 32 * hd * 2) } else { (format!("attn_decode_gqa_{hd}"), if cp { 2 * 2 * 32 * hd * 2 } else { 0 }) }; if gq_min != i32::MAX { launch!(self, &name, cfg(((nh / g * nt) as u32, ns as u32), 256, (8 * hd * 4 + cp) as u32), q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); } @@ -758,37 +1132,191 @@ impl Gpu { } } +/// The decode attention entry point and its key positions per block, for the cache mode `kv_mode` (0 = f16, 2 = q4, +/// 10 = K and V in different formats): at head_dim 128 an f16 and a q4 cache each have a kernel that scores a 128-key +/// tile a block (`tile`: the fast kernels are on and `STRATA_DS_ATTN_OLD` is not set), the scalar one takes 64 keys +/// and every format. A 128-key kernel keeps the relative-bias row in 32 shared floats, so a wider `nr` uses the +/// scalar kernel. Pure so a CPU test can pin the choice. +pub(crate) fn ink_attn_pick(kv_mode: u32, tile: bool, hd: usize, nr: usize) -> (&'static str, usize) { + match kv_mode { + 0 if tile && hd == 128 && nr <= 32 => ("ink_attn_128", 128), + 2 if tile && hd == 128 && nr <= 32 => ("ink_attn_128_q4", 128), + _ => ("ink_attn", 64), + } +} + +impl Gpu { + /// `ink_attn_pick` for this device (`STRATA_DS_ATTN_OLD=1` keeps the scalar kernel for a measurement window; the + /// flags are cached in `flags` at `Gpu` creation). + pub(crate) fn ink_attn_kernel(&self, hd: usize, nr: usize) -> (&'static str, usize) { + self.flags.decode_kernel(self.kv_mode, hd, nr) + } +} + +impl Gpu { + /// Bytes the stream-ordered allocator holds from the driver but no live allocation uses. + fn pool_cached(&self) -> usize { + if !self.ctx.has_async_alloc() || self.ctx.bind_to_thread().is_err() { return 0; } + use cudarc::driver::{result::{device, mem_pool}, sys::CUmemPool_attribute as A}; + let get = |pool, a: A| -> usize { + let mut v = 0u64; + // SAFETY: `pool` came from the driver, and every attribute read here is a u64. + unsafe { mem_pool::get_attribute(pool, a, &mut v as *mut u64 as *mut std::ffi::c_void) }.map_or(0, |_| v as usize) + }; + // SAFETY: the ordinal is the one of this context. + let pool = unsafe { device::get(self.ctx.ordinal() as i32).and_then(|d| device::get_mem_pool(d)) }; + let Ok(pool) = pool else { return 0 }; + let (res, used) = (get(pool, A::CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT), get(pool, A::CU_MEMPOOL_ATTR_USED_MEM_CURRENT)); + res.saturating_sub(used) + } +} + +impl Gpu { + /// `htod` on stream `st`. + fn htod_to(&self, src: &[u8], dst: &Buf, off: usize, st: &CudaStream) -> anyhow::Result<()> { + anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); + self.ctx.bind_to_thread()?; + // No stream sync: from pageable memory the driver has staged `src` when the call returns. Copies on the copy + // stream use the pinned ring even when small, to avoid pageable staging on that stream. + if src.len() < RING_MIN && !std::ptr::eq(st, &*self.copy) { return Ok(unsafe { result::memcpy_htod_async(dst.addr() + off as u64, src, st.cu_stream()) }?); } + // Pinned host memory (the model arena, `host_register`): one DMA straight from it, no staging through the ring. + // Only model weights are pinned, and they do not change, so the copy may still read them after the return. + if self.host_is_pinned(src) { + return Ok(unsafe { result::memcpy_htod_async(dst.addr() + off as u64, src, st.cu_stream()) }?); + } + let mut g = self.ring.lock().unwrap(); + let (pin, head, busy) = &mut *g; + let base = pin.as_mut_ptr()?; + for (i, c) in src.chunks(RING).enumerate() { + if *head + c.len() > RING { *head = 0; } + let (a, b) = (*head, *head + c.len()); + while busy.iter().any(|&(s, e, _)| s < b && a < e) { busy.pop_front().unwrap().2.synchronize()?; } + unsafe { + let p = base.add(a); + std::ptr::copy_nonoverlapping(c.as_ptr(), p, c.len()); + result::memcpy_htod_async(dst.addr() + (off + i * RING) as u64, std::slice::from_raw_parts(p, c.len()), st.cu_stream())?; + } + busy.push_back((a, b, st.record_event(None)?)); + *head = b; + } + Ok(()) + } + + /// Record an event on `st` and return its handle: one of the last 64 (a mark is used within a layer or two). + fn mark(&self, st: &CudaStream) -> anyhow::Result { + self.ctx.bind_to_thread()?; + let ev = st.record_event(None)?; + let mut g = self.marks.lock().unwrap(); + let id = g.1; + if g.0.len() < 64 { g.0.push(ev); } else { let n = g.0.len(); g.0[id % n] = ev; } + g.1 += 1; + Ok(id) + } + + fn wait_mark(&self, st: &CudaStream, id: usize) -> anyhow::Result<()> { + self.ctx.bind_to_thread()?; + let g = self.marks.lock().unwrap(); + let n = g.0.len(); + anyhow::ensure!(n > 0 && id < g.1 && g.1 - id <= n, "stream mark {id} is not one of the last {n}"); + Ok(st.wait(&g.0[id % n])?) + } +} + +struct PrefillInput { + stream: Arc, + data: PinnedHostSlice, + done: CudaEvent, +} + +struct CudaPrefillRead<'a> { + input: std::sync::MutexGuard<'a, Option>, + len: usize, + _source: Buf, + completed: std::cell::Cell, +} + +impl PrefillRead for CudaPrefillRead<'_> { + fn rows(&self) -> anyhow::Result<&[f32]> { + let input = self.input.as_ref().unwrap(); + input.done.synchronize()?; + self.completed.set(true); + Ok(&input.data.as_slice()?[..self.len]) + } +} + +impl Drop for CudaPrefillRead<'_> { + fn drop(&mut self) { + // Also complete an unused or failed layer's read before the slab or host buffer can be reused. + if !self.completed.get() { + let _ = self.input.as_ref().unwrap().done.synchronize(); + } + } +} + +struct CudaTimer { + stream: Arc, + start: CudaEvent, + end: CudaEvent, +} + +impl DeviceTimer for CudaTimer { + fn stop(&mut self) -> anyhow::Result<()> { Ok(self.end.record(&self.stream)?) } + + fn elapsed(&self) -> anyhow::Result { + Ok(std::time::Duration::from_secs_f64(f64::from(self.start.elapsed_ms(&self.end)?).max(0.0) / 1000.0)) + } +} + impl Backend for Gpu { fn name(&self) -> &'static str { "cuda" } fn device(&self) -> String { self.ctx.name().unwrap_or_default() } fn share(&self) -> anyhow::Result> { let q8 = std::sync::Mutex::new((self.stream.alloc_zeros::(1)?, None)); - let am = self.stream.alloc_zeros(64 * AMAX_PARTS)?; + let am = self.stream.alloc_zeros(128 * AMAX_PARTS)?; let ring = std::sync::Mutex::new((unsafe { self.ctx.alloc_pinned::(RING)? }, 0, VecDeque::new())); let done = self.ctx.new_event(None)?; Ok(Box::new(Gpu { ctx: self.ctx.clone(), side: self.stream.fork()?, + copy: self.stream.fork()?, + in_copy: Default::default(), + copy_ev: Default::default(), stream: self.stream.clone(), nb: AtomicUsize::new(usize::MAX), fns: self.fns.clone(), i8_gemm: self.i8_gemm, + dp4a_gemm: self.dp4a_gemm, q8, + prefill_input: Default::default(), + moe_gate_q8: Default::default(), + gd: Default::default(), + sk: Default::default(), + xh: Default::default(), + xk: Default::default(), + skc: Default::default(), + sms: self.sms, kv_mode: self.kv_mode, + flags: self.flags, + kv_k_mode: self.kv_k_mode, + kv_v_mode: self.kv_v_mode, int8_mma: self.int8_mma, turing: self.turing, max_smem: self.max_smem, am, graphs: Default::default(), ring, + marks: Default::default(), done, lag: Default::default(), fr: Default::default(), + cs: Default::default(), + mla_part: Default::default(), + pinned: Default::default(), })) } /// The type policy gated on this device: `gemm_raw` takes the f16 `gemm_*` path where the arch has no int8 /// tensor cores (Volta), so a test comparing kernels must not expect `gemmi_*` there. - fn mmq(&self, ty: GgmlType) -> bool { self.i8_gemm && Gpu::mmq(ty) } + fn mmq(&self, ty: GgmlType) -> bool { (self.i8_gemm || self.dp4a_gemm) && self.mmq_on(ty) } /// sm_70 runs `mma16816` on CUDA cores (the `__CUDA_ARCH__ < 800` branch in kernels.cu): the same f16 products /// summed in another order than `mma.sync`, so a cross-backend comparison is by tolerance, not bit for bit. fn volta(&self) -> bool { !self.i8_gemm } @@ -799,30 +1327,21 @@ impl Backend for Gpu { // Returns once `src` is copied (a copy still reading `src` after return broke greedy output). fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { - anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); - self.ctx.bind_to_thread()?; // Inside `batch` or `beside` a copy goes to the side stream, beside the next launch on the main stream. - let st = if self.nb.load(Relaxed) == usize::MAX { &self.stream } else { &self.side }; - // No stream sync: from pageable memory (every caller's) the driver has staged `src` when the call returns. - if src.len() < RING_MIN { return Ok(unsafe { result::memcpy_htod_async(dst.addr() + off as u64, src, st.cu_stream()) }?); } - let mut g = self.ring.lock().unwrap(); - let (pin, head, busy) = &mut *g; - let base = pin.as_mut_ptr()?; - for (i, c) in src.chunks(RING).enumerate() { - if *head + c.len() > RING { *head = 0; } - let (a, b) = (*head, *head + c.len()); - while busy.iter().any(|&(s, e, _)| s < b && a < e) { busy.pop_front().unwrap().2.synchronize()?; } - unsafe { - let p = base.add(a); - std::ptr::copy_nonoverlapping(c.as_ptr(), p, c.len()); - result::memcpy_htod_async(dst.addr() + (off + i * RING) as u64, std::slice::from_raw_parts(p, c.len()), st.cu_stream())?; - } - busy.push_back((a, b, st.record_event(None)?)); - *head = b; - } - Ok(()) + // A copy inside `copy_beside` goes to the copy stream. + let st = if self.in_copy.load(Relaxed) { &self.copy } else if self.nb.load(Relaxed) == usize::MAX { &self.stream } else { &self.side }; + self.htod_to(src, dst, off, st) } + // The copy queue of a prompt chunk's expert staging: the DMA runs on the side stream beside the kernels. The + // marks are events: `side_mark`/`main_mark` record the point a stream has reached, `main_waits`/`side_waits` + // hold the other stream there (the callers in `prefill_ffn_pool` order the staging slots with them). + fn htod_side(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { self.htod_to(src, dst, off, &self.side) } + fn side_mark(&self) -> anyhow::Result { self.mark(&self.side) } + fn main_mark(&self) -> anyhow::Result { self.mark(&self.stream) } + fn main_waits(&self, side_mark: usize) -> anyhow::Result<()> { self.wait_mark(&self.stream, side_mark) } + fn side_waits(&self, main_mark: usize) -> anyhow::Result<()> { self.wait_mark(&self.side, main_mark) } + // As cudarc's clone_dtoh: copy, then a stream sync. fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()> { @@ -834,6 +1353,27 @@ impl Backend for Gpu { Ok(self.stream.synchronize()?) } + fn begin_prefill_read(&self, src: &Buf, offset: usize, count: usize) -> anyhow::Result>> { + let bytes = 4 * count; + anyhow::ensure!(offset + bytes <= src.len(), "prefill activation read exceeds scratch"); + let mut input = self.prefill_input.lock().unwrap(); + if input.as_ref().is_none_or(|input| input.data.len() < count) { + let flags = Some(sys::CUevent_flags::CU_EVENT_BLOCKING_SYNC); + // Allocation is optional. The ordinary activation read still works under host memory pressure. + let Ok(data) = (unsafe { self.ctx.alloc_pinned_with_flags::(count, 0) }) else { return Ok(None); }; + *input = Some(PrefillInput { stream: self.stream.fork()?, data, done: self.ctx.new_event(flags)? }); + } + let state = input.as_mut().unwrap(); + state.stream.join(&self.stream)?; + let ptr = state.data.as_mut_ptr()?; + unsafe { result::memcpy_dtoh_async(std::slice::from_raw_parts_mut(ptr, count), src.addr() + offset as u64, state.stream.cu_stream())?; } + if let Err(e) = state.done.record(&state.stream) { + state.stream.synchronize()?; + return Err(e.into()); + } + Ok(Some(Box::new(CudaPrefillRead { input, len: count, _source: src.clone(), completed: Default::default() }))) + } + fn dtod(&self, src: &Buf, src_off: usize, dst: &Buf, dst_off: usize, bytes: usize) -> anyhow::Result<()> { anyhow::ensure!(src_off + bytes <= src.len() && dst_off + bytes <= dst.len(), "dtod: {bytes} bytes out of range"); self.ctx.bind_to_thread()?; @@ -845,9 +1385,31 @@ impl Backend for Gpu { Ok(unsafe { result::memset_d8_async(dst.addr(), 0, dst.len(), self.stream.cu_stream()) }?) } - fn mem_info(&self) -> anyhow::Result<(usize, usize)> { Ok(self.ctx.mem_get_info()?) } + /// `cuMemGetInfo` counts memory that `cuMemFreeAsync` returned to the stream-ordered allocator as used, although + /// the next allocation reuses it (a dropped 12 GB expert pool showed as 1.6 GB free while 13 GB could be + /// allocated), so the caller refused room that was there. The free figure adds what the allocator holds unused. + fn mem_info(&self) -> anyhow::Result<(usize, usize)> { + let (free, total) = self.ctx.mem_get_info()?; + Ok(((free + self.pool_cached()).min(total), total)) + } fn sync(&self) -> anyhow::Result<()> { self.wait() } + // Dropped buffers are freed into CUDA's memory pool, which gives them back at a stream sync, not at `wait`'s event. + // The copy queues too: a copy still queued there must not write into a buffer that is dropped next. + fn sync_freed(&self) -> anyhow::Result<()> { + self.side.synchronize()?; + self.copy.synchronize()?; + Ok(self.stream.synchronize()?) + } + + fn device_timer(&self) -> anyhow::Result>> { + let flags = Some(sys::CUevent_flags::CU_EVENT_BLOCKING_SYNC); + Ok(Some(Box::new(CudaTimer { + stream: self.stream.clone(), + start: self.stream.record_event(flags)?, + end: self.ctx.new_event(flags)?, + }))) + } // Every op batched on CUDA is one launch, so alternating launches never splits an op over the two streams. Copies // do not count: they all go to the side stream. @@ -872,6 +1434,24 @@ impl Backend for Gpu { r } + fn copy_beside(&self, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { + self.copy.join(&self.stream)?; + self.copy_independent(f) + } + + fn copy_independent(&self, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { + self.in_copy.store(true, Relaxed); + let r = f(); + self.in_copy.store(false, Relaxed); + *self.copy_ev.lock().unwrap() = Some(self.copy.record_event(None)?); + r + } + + fn copy_join(&self) -> anyhow::Result<()> { + if let Some(e) = self.copy_ev.lock().unwrap().take() { self.stream.wait(&e)?; } + Ok(()) + } + fn beside_join(&self) -> anyhow::Result<()> { self.lag.lock().unwrap().take(); Ok(self.stream.join(&self.side)?) @@ -903,8 +1483,90 @@ impl Backend for Gpu { self.graphs.lock().unwrap().remove(&key); Ok(()) } + fn graph_clear(&self) -> anyhow::Result<()> { + self.sync()?; + self.graphs.lock().unwrap().clear(); + Ok(()) + } + + fn alloc_host(&self, bytes: usize) -> anyhow::Result { + // Anonymous memory on 2 MB huge pages (the CPU attention walks it all each token: 4 KB pages cost ~30% in + // TLB misses), then pinned and mapped into the device with cuMemHostRegister. + struct Reg(#[allow(dead_code)] memmap2::MmapMut, usize); + impl Drop for Reg { fn drop(&mut self) { unsafe { let _ = sys::cuMemHostUnregister(self.1 as *mut _); } } } + const HP: usize = 2 << 20; + let len = bytes.max(1).next_multiple_of(HP); + let mut m = memmap2::MmapMut::map_anon(len + HP)?; + #[cfg(target_os = "linux")] + let _ = m.advise(memmap2::Advice::HugePage); + let base = m.as_mut_ptr() as usize; + let h = base.next_multiple_of(HP); + unsafe { std::ptr::write_bytes(h as *mut u8, 0, len) }; + self.ctx.bind_to_thread()?; + let r = unsafe { sys::cuMemHostRegister_v2(h as *mut _, len, sys::CU_MEMHOSTREGISTER_DEVICEMAP | sys::CU_MEMHOSTREGISTER_PORTABLE) }; + anyhow::ensure!(r == sys::CUresult::CUDA_SUCCESS, "cuMemHostRegister: {r:?}"); + // From here a failure drops `reg`, which unregisters the range before the mapping goes. + let reg = Reg(m, h); + let mut dev = 0; + let r = unsafe { sys::cuMemHostGetDevicePointer_v2(&mut dev, h as *mut _, 0) }; + anyhow::ensure!(r == sys::CUresult::CUDA_SUCCESS, "cuMemHostGetDevicePointer: {r:?}"); + anyhow::ensure!(dev == h as u64, "mapped host memory has a device address other than its host one (no UVA)"); + let b = Buf::new(dev, bytes, reg); + // The staging of `attn_host`, made here at load time: allocating inside a graph capture breaks it. + let mut st = HA_STAGE.lock().unwrap(); + if st.is_none() { + let raw = |n: usize| -> anyhow::Result { let (b, _) = self.host_mailbox(n.div_ceil(4))?; Ok(b) }; + let (mb, host) = self.host_mailbox(64)?; + *st = Some((raw(4 * HA_T * HA_W)?, raw(4 * HA_T * HA_W)?, raw(8 * HA_T)?, mb, self.alloc(64)?)); + if std::env::var_os("STRATA_HA_MAILBOX").is_some() { crate::host_attn::start_worker(host as usize); } + } + Ok(b) + } + + fn attn_host(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, nt: usize) -> anyhow::Result { + if self.kv_mode > 2 || nt > HA_T || hd % 32 != 0 || nh % nkv != 0 || nh * (hd + 2) > HA_W { return Ok(false); } + let st = HA_STAGE.lock().unwrap(); + let Some((bq, bp, bs, mb, seq)) = st.as_ref() else { return Ok(false) }; + let (bq, bp, bs, mb, seq) = (bq.addr(), bp.addr(), bs.addr(), mb.addr(), seq.addr()); + drop(st); + let ctx = { + let mut c = CTX.lock().unwrap(); + // Keyed by every field: a model loaded later can reuse a freed cache's addresses with other shapes. + let same = |a: &crate::host_attn::HostAttn| a.kc == kc as usize && a.vc == vc as usize && a.nt == nt && a.nh == nh + && a.nkv == nkv && a.hd == hd && a.mode == self.kv_mode as u32 && a.scale.to_bits() == scale.to_bits(); + match c.iter().find(|e| same(unsafe { &*(e.3 as *const crate::host_attn::HostAttn) })) { + Some(e) => e.3, + None => { + let a = Box::leak(Box::new(crate::host_attn::HostAttn { q: bq as usize, step: bs as usize, part: bp as usize, + kc: kc as usize, vc: vc as usize, nh, nkv, hd, nt, scale, mode: self.kv_mode as u32 })) as *mut _ as usize; + c.push((kc, vc, nt, a)); + a + } + } + }; + // A stream host function by default; `STRATA_HA_MAILBOX` spins on a mapped flag instead (measured the same, + // 14.6 vs 14.7 tok/s at 52K, and a dead worker would trap the GPU). + if std::env::var_os("STRATA_HA_MAILBOX").is_none() { + self.ctx.bind_to_thread()?; + let cs = self.st().cu_stream(); + unsafe { + result::memcpy_dtod_async(bq, q, 4 * nt * nh * hd, cs)?; + result::memcpy_dtod_async(bs, step, 8 * nt, cs)?; + let r = sys::cuLaunchHostFunc(cs, Some(crate::host_attn::callback), ctx as *mut _); + anyhow::ensure!(r == sys::CUresult::CUDA_SUCCESS, "cuLaunchHostFunc: {r:?}"); + } + } else { + launch!(self, "ha_post", cfg((1, 1), 256, 0), q, step, bq, bs, (nt * nh * hd) as i32, (2 * nt) as i32, mb, seq, ctx as u64); + launch!(self, "ha_wait", cfg((1, 1), 32, 0), mb, seq); + } + launch!(self, "attn_merge", LaunchConfig { grid_dim: (nh as u32, 1, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }, + bp, qg, out, hd as i32, 1i32, step, 1i32, 0i32, 0u64, 0u64); + Ok(true) + } /// Pinned host memory mapped into the device address space. + fn host_buf(&self, bytes: usize) -> anyhow::Result> { Ok(Some(self.host_mailbox(bytes.div_ceil(4))?.0)) } + fn host_mailbox(&self, words: usize) -> anyhow::Result<(Buf, *mut u32)> { let n = words.max(1); let flags = sys::CU_MEMHOSTALLOC_DEVICEMAP | sys::CU_MEMHOSTALLOC_PORTABLE; @@ -926,7 +1588,7 @@ impl Backend for Gpu { self.gemm_raw(w.ty, w.rows, w.cols, 0, n.div_ceil(GEMM_BM), w.ptr, n, x, x_stride, n, 0, y, y_stride, act, w.scale) } - fn int8_gemm(&self, ty: GgmlType) -> bool { self.int8_mma && Self::mmq(ty) } + fn int8_gemm(&self, ty: GgmlType) -> bool { (self.int8_mma || self.dp4a_gemm) && self.mmq_on(ty) } fn prequant_gemm_x(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize) -> anyhow::Result<()> { let mut q8 = self.q8.lock().unwrap(); @@ -949,6 +1611,16 @@ impl Backend for Gpu { self.gemvq_pair(w, x, x_stride, xq, y, y_stride, nt, (0, 0, 0, 1.0f32), 1) } + fn gemvq2_silu(&self, a: &GpuTensor, b: &GpuTensor, x: u64, ya: u64, yb: u64, sc: f32) -> anyhow::Result { + // The fused silu keeps hc_silu's bits only for a matrix of scale 1 (y * 1 * sc == y * sc). + if !Self::float_ty(a.ty) || a.ty != b.ty || a.cols != b.cols || a.rows < b.rows || a.scale != 1.0 { return Ok(false); } + let (ncols, k1) = Self::gemv_cols("gemv", a.ty, a.cols)?; + let (mut c, rpw) = Self::gemv_cfg(a.ty, a.rows, a.cols, 1); + c.grid_dim.2 = 2; + launch!(self, &k1, c, a.ptr, x, ya, a.rows as i32, ncols, rpw, 1u64, b.ptr as i64 - a.ptr as i64, yb as i64 - ya as i64, b.rows as i32, sc, b.scale); + Ok(true) + } + // One launch for both matrices. fn gemvq2(&self, a: &GpuTensor, b: &GpuTensor, x: u64, x_stride: usize, xq: u64, ya: u64, yb: u64, nt: usize) -> anyhow::Result<()> { if a.ty != b.ty || a.cols != b.cols { @@ -975,6 +1647,19 @@ impl Backend for Gpu { Ok(()) } + fn moe_gemv_blocks(&self, ty: GgmlType, rows: usize, cols: usize, w: u64, stride: usize, ids: u64, k: usize, x: u64, x_stride: usize, xg: usize, y: u64, pair: Option<(i64, i64)>, xq: u64, blocks: usize) -> anyhow::Result<()> { + let (ncols, kn) = Self::gemv_cols("moe_gemv", ty, cols)?; + let (mut c, _) = Self::gemv_cfg(ty, rows, cols, k); + let wpb = c.block_dim.0 as usize / 32; + let rpw = rows.div_ceil(wpb * blocks.max(1)).max(1); + c.grid_dim.0 = rows.div_ceil(wpb * rpw) as u32; + let (w2, y2) = pair.unwrap_or((0, 0)); + c.grid_dim.2 = if pair.is_some() { 2 } else { 1 }; + if xq != 0 { c.shared_mem_bytes = 0; } + launch!(self, &kn, c, w, ids, stride as i64, x, x_stride as i32, xg as i32, y, rows as i32, ncols, rpw as i32, w2, y2, xq); + Ok(()) + } + fn dequant(&self, w: &GpuTensor, rows: usize, out: u64) -> anyhow::Result<()> { launch!(self, &kname("dequant", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, out, Self::gemv_cols("dequant", w.ty, w.cols)?.0, w.scale); Ok(()) @@ -1025,8 +1710,9 @@ impl Backend for Gpu { fn rms_norm_rope_kv(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); let fr = self.rope_fr(base, n_rot)?; - launch!(self, "rms_norm_rope", cfg((rows as u32, 1), 256, 0), x, x_stride as i32, w, out, n as i32, eps, per as i32, n_rot as i32, step, base, v, kc, vc, - 0i32, 0u64, 0i32, 0u64, 0u64, 0i32, fr, 0u64); + let cs = self.rope_cs(step, 0, rows / per, n_rot, fr)?; + launch!(self, "rms_norm_rope", cfg((rows as u32, 1), nr_block(n), 0), x, x_stride as i32, w, out, n as i32, eps, per as i32, n_rot as i32, step, base, v, kc, vc, + 0i32, 0u64, 0i32, 0u64, 0u64, 0i32, fr, 0u64, cs); Ok(()) } @@ -1035,8 +1721,9 @@ impl Backend for Gpu { n: usize, eps: f32, n_rot: usize, step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); let fr = self.rope_fr(base, n_rot)?; - launch!(self, "rms_norm_rope", cfg(((qrows + krows) as u32, 1), 256, 0), k, n as i32, kw, ko, n as i32, eps, kper as i32, n_rot as i32, step, base, v, kc, vc, - qrows as i32, q, q_stride as i32, qw, qo, qper as i32, fr, 0u64); + let cs = self.rope_cs(step, 0, krows / kper, n_rot, fr)?; + launch!(self, "rms_norm_rope", cfg(((qrows + krows) as u32, 1), nr_block(n), 0), k, n as i32, kw, ko, n as i32, eps, kper as i32, n_rot as i32, step, base, v, kc, vc, + qrows as i32, q, q_stride as i32, qw, qo, qper as i32, fr, 0u64, cs); Ok(()) } @@ -1046,8 +1733,9 @@ impl Backend for Gpu { step: u64, base: f32, v: u64, kvt: u64, nt: usize) -> anyhow::Result<()> { anyhow::ensure!(n_rot <= hd.min(512) && hd % 32 == 0, "rms_norm_rope: head of {hd}, n_rot {n_rot}"); let fr = self.rope_fr(base, n_rot)?; - launch!(self, "rms_norm_rope", cfg(((nt * (nh + nkv)) as u32, 1), 256, 0), k, hd as i32, kw, ko, hd as i32, eps, nkv as i32, n_rot as i32, step, base, v, 0u64, 0u64, - (nt * nh) as i32, q, q_stride as i32, qw, qo, nh as i32, fr, kvt); + let cs = self.rope_cs(step, kvt, nt, n_rot, fr)?; + launch!(self, "rms_norm_rope", cfg(((nt * (nh + nkv)) as u32, 1), nr_block(hd), 0), k, hd as i32, kw, ko, hd as i32, eps, nkv as i32, n_rot as i32, step, base, v, 0u64, 0u64, + (nt * nh) as i32, q, q_stride as i32, qw, qo, nh as i32, fr, kvt, cs); Ok(()) } @@ -1064,6 +1752,15 @@ impl Backend for Gpu { launch!(self, "swiglu", Self::grid(n), g, u, n as i32); Ok(()) } + fn swiglu_clamp(&self, g: u64, u: u64, n: usize, lim: f32) -> anyhow::Result<()> { + launch!(self, "swiglu_clamp", Self::grid(n), g, u, n as i32, lim); + Ok(()) + } + fn ds_rope(&self, x: u64, xs: usize, y: u64, ys: usize, rows: usize, nh: usize, hd: usize, ow: usize, n_rot: usize, cs: u64, inverse: bool, scale: f32, sink: usize) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= hd && n_rot % 2 == 0 && hd <= xs && ow <= ys && (sink == 0 || sink + nh <= ow), "ds_rope: bad shape"); + launch!(self, "ds_rope", Self::grid(rows * ow), x, xs as i32, y, ys as i32, rows as i32, nh as i32, hd as i32, ow as i32, n_rot as i32, cs, inverse as i32, scale, sink as i32); + Ok(()) + } fn situ(&self, y: u64, n: usize, rows: usize, scale: u64, beta: f32, lb: f32) -> anyhow::Result<()> { launch!(self, "situ", Self::grid(n * rows), y, n as i32, rows as i32, scale, beta, lb); Ok(()) @@ -1082,6 +1779,18 @@ impl Backend for Gpu { Ok(()) } fn ink_ctrl_n(&self, down: u64, gain: u64, forget: u64, cur: u64, nins: usize, msg: u64, gate: u64, out: u64, n: usize, rank: usize, count: usize, nt: usize) -> anyhow::Result<()> { + // A prompt chunk uses the tiled pair (a weight row is read once per 64 tokens); a decoded token the + // per-token pair, which has no tile to reuse. Both pairs read and write the same gate layout. + // STRATA_CTRL_TILE=0 forces the per-token pair, to compare the two on the same text (the flag is cached + // in `flags` at `Gpu` creation). + let tiled = nt >= 64 && rank <= 64 && n % 64 == 0 && self.flags.ctrl_tile; + if tiled { + let g1 = cfg((count as u32, nt.div_ceil(64) as u32), 256, 0); + let g2 = LaunchConfig { grid_dim: (count as u32, n.div_ceil(64) as u32, nt.div_ceil(64) as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + launch!(self, "ink_ctrl_gate_b", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); + launch!(self, "ink_ctrl_out_b", g2, gain, forget, gate, cur, nins as i32, msg, out, n as i32, rank as i32, nt as i32); + return Ok(()); + } let g1 = LaunchConfig { grid_dim: (rank as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; let g2 = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; launch!(self, "ink_ctrl_gate", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); @@ -1106,7 +1815,7 @@ impl Backend for Gpu { pos0: usize, log_alpha: f32, log_floor: f32, ) -> anyhow::Result<()> { anyhow::ensure!(w <= 128, "ink_clip_n: w={w} > 128"); - anyhow::ensure!(kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); + anyhow::ensure!(self.kv_mode == 0 || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), @@ -1120,7 +1829,7 @@ impl Backend for Gpu { pos_ptr: u64, log_alpha: f32, log_floor: f32, ) -> anyhow::Result<()> { anyhow::ensure!(w <= 128, "ink_clip_pos: w={w} > 128"); - anyhow::ensure!(kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); + anyhow::ensure!(self.kv_mode == 0 || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), @@ -1128,14 +1837,16 @@ impl Backend for Gpu { Ok(()) } fn ink_attn(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, rows: usize, at: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { - let chunks = rows.div_ceil(64) as u32; - launch!(self, "ink_attn", cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); + let (kn, ck) = self.ink_attn_kernel(hd, nr); + let chunks = rows.div_ceil(ck) as u32; + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); Ok(()) } fn ink_attn_pos(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, max_rows: usize, ring: usize, pos_ptr: u64, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { - let chunks = max_rows.div_ceil(64) as u32; - launch!(self, "ink_attn", cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); + let (kn, ck) = self.ink_attn_kernel(hd, nr); + let chunks = max_rows.div_ceil(ck) as u32; + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); Ok(()) } @@ -1143,29 +1854,63 @@ impl Backend for Gpu { &self, q: u64, r: u64, sink: u64, gate: u64, kc: u64, vc: u64, kc_new: u64, vc_new: u64, bias: u64, out: u64, pos: usize, nt: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize, ring: usize, win: usize, ) -> anyhow::Result<()> { - let kn = match hd { - 32 => "ink_attn_prefill_32", - 64 => "ink_attn_prefill_64", - 128 => "ink_attn_prefill_128", - _ => anyhow::bail!("ink_attn_prefill: unsupported hd={hd}"), - }; - launch!(self, kn, cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), - q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, - pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); + anyhow::ensure!(matches!(hd, 32 | 64 | 128), "ink_attn_prefill: unsupported hd={hd}"); + let g = nh / nkv.max(1); + if hd == 128 && self.kv_mode == 0 && self.flags.attn_tc && self.int8_mma && nr == 16 && nkv > 0 && nh % nkv == 0 && g <= 3 && !self.flags.attn_old { + launch!(self, "ink_attn_prefill_128_tc", cfg((nt.div_ceil(32) as u32, nkv as u32), (64 * g) as u32, 0), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); + return Ok(()); + } + let selected = self.flags.prefill_kernel(self.kv_mode, hd, nh, nkv, win); + if matches!(selected, InkPrefillKernel::KeyParallel4 | InkPrefillKernel::KeyParallel16) { + // The key-parallel kernels: kp16 (16 queries a block) by default, kp (4) for the A/B. The wrapper + // falls back to the four-query template for a relative-bias width it cannot read as float4. + let (kn, qb) = if selected == InkPrefillKernel::KeyParallel4 { ("ink_attn_prefill_128_kp", 4) } else { ("ink_attn_prefill_128_kp16", 16) }; + launch!(self, kn, cfg((nt.div_ceil(qb) as u32, nh as u32), 128, 0), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); + } else if selected == InkPrefillKernel::Old { + launch!(self, "ink_attn_prefill_128_old", cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); + // Shared-memory prefill supports full-context F16 and Q8. + } else if selected == InkPrefillKernel::Shared { + // Every key: a block is one K/V head and `tb` tokens, with 32 keys of K and V in shared memory. + let tb = (32 / g).min(8); + launch!(self, &format!("ink_attn_prefill_sh_{hd}"), cfg((nt.div_ceil(tb) as u32, nkv as u32), (32 * tb * g) as u32, (2 * 32 * hd * 4) as u32), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, i32::MAX, win as i32); + } else { + // `ring` is the count of old rows that the kernel wraps at: only a sliding layer wraps. + launch!(self, &format!("ink_attn_prefill_{hd}"), cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, if win > 0 { ring.max(1) } else { i32::MAX as usize } as i32, win as i32); + } Ok(()) } fn ink_ffn_sum_n(&self, acc: u64, d: u64, wts: u64, ne: usize, n: usize, nt: usize, cpu: u64) -> anyhow::Result<()> { launch!(self, "ink_ffn_sum", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), acc, d, wts, ne as i32, n as i32, cpu); Ok(()) } + fn ink_pool(&self) -> bool { true } + fn ink_slots(&self, ids: u64, wts: u64, table: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, k: usize) -> anyhow::Result<()> { + anyhow::ensure!(k <= 32, "ink_slots: k={k}"); + launch!(self, "ink_slots", cfg((1, 1), 256, 0), ids, wts, table, slots, wh, h, mb, nh as i32, h_off as i32, step, k as i32); + Ok(()) + } + fn ink_ffn_sum_mb(&self, acc: u64, d: u64, wh: u64, k: usize, n: usize, mb: u64, y_off: usize, step: u64, slots: u64) -> anyhow::Result<()> { + launch!(self, "ink_ffn_sum_mb", cfg((n.div_ceil(256) as u32, 1), 256, 0), acc, d, wh, k as i32, n as i32, mb, y_off as i32, step, slots); + Ok(()) + } fn ink_route(&self, logits: u64, bias: u64, ids: u64, wts: u64, gu_sc: u64, dn_sc: u64, gsc_out: u64, n_expert: usize, k: usize, exp_scale: f32, rows: usize) -> anyhow::Result<()> { anyhow::ensure!(n_expert <= 512 && k <= 32, "ink_route: n_expert={n_expert} k={k}"); launch!(self, "ink_route", cfg((rows as u32, 1), 32, 0), logits, bias, ids, wts, gu_sc, dn_sc, gsc_out, n_expert as i32, k as i32, exp_scale); Ok(()) } - fn hadamard(&self, x: u64, u: u64, s: u64, out: u64, n: usize, block: usize, rows: usize) -> anyhow::Result<()> { - anyhow::ensure!(block <= 1024, "prism.hadamard.block_size {block}: at most 1024 on the GPU"); - launch!(self, "hadamard", cfg(((rows * n / block) as u32, 1), block as u32, 0), x, u, s, out, n as i32, block as i32, 1.0 / (block as f32).sqrt()); + fn hadamard(&self, x: u64, u: u64, s: u64, perm: u64, out: u64, n: usize, block: usize, rows: usize) -> anyhow::Result<()> { + anyhow::ensure!((2..=4096).contains(&block), "prism.hadamard.block_size {block}: 2 to 4096 on the GPU"); + launch!(self, "hadamard", cfg(((rows * n / block) as u32, 1), block.min(1024) as u32, 0), x, u, s, perm, out, n as i32, block as i32, 1.0 / (block as f32).sqrt()); Ok(()) } fn swiglu_q(&self, g: u64, u: u64, n: usize, rows: usize, xq: u64) -> anyhow::Result { @@ -1179,7 +1924,7 @@ impl Backend for Gpu { } fn conv_silu(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, nn: usize, eps: f32) -> anyhow::Result<()> { - launch!(self, "conv_silu", cfg((ch.div_ceil(128) as u32, 1), 128, 0), qkv, state, w, y, ch as i32, kw as i32, nn as i32, eps); + launch!(self, "conv_silu", cfg((ch.div_ceil(128) as u32, 1), 128, 0), qkv, state, w, y, ch as i32, kw as i32, nn as i32, eps, 0u64); Ok(()) } @@ -1188,7 +1933,21 @@ impl Backend for Gpu { anyhow::ensure!(matches!(dk, 32 | 64 | 128 | 256) && dv % rows == 0, "deltanet: head dims {dk}/{dv} unsupported"); launch!(self, "deltanet_seq", cfg((nv as u32, dv.div_ceil(8 * rows) as u32), 256, 0), y, s, beta, g, o, nk as i32, nv as i32, interleave as i32, dk as i32, dv as i32, scale, t as i32, ych as i32, snap, nsnap as i32, - dt_bias, a); + dt_bias, a, 0u64); + Ok(()) + } + + fn conv_silu_rows(&self, qkv: u64, tab: u64, states: &[u64], w: u64, y: u64, ch: usize, kw: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "conv_silu", cfg((ch.div_ceil(128) as u32, states.len() as u32), 128, 0), qkv, 0u64, w, y, ch as i32, kw as i32, 0i32, eps, tab); + Ok(()) + } + + fn deltanet_rows(&self, y: u64, tab: u64, states: &[u64], beta: u64, g: u64, o: u64, nk: usize, nv: usize, interleave: bool, dk: usize, dv: usize, scale: f32, ych: usize) -> anyhow::Result<()> { + let rows = 512 / dk.max(1); + anyhow::ensure!(matches!(dk, 32 | 64 | 128 | 256) && dv % rows == 0, "deltanet: head dims {dk}/{dv} unsupported"); + let lc = LaunchConfig { grid_dim: (nv as u32, dv.div_ceil(8 * rows) as u32, states.len() as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + launch!(self, "deltanet_seq", lc, y, 0u64, beta, g, o, nk as i32, nv as i32, interleave as i32, dk as i32, dv as i32, scale, 1i32, ych as i32, 0u64, 0i32, + 0u64, 0u64, tab); Ok(()) } @@ -1214,6 +1973,81 @@ impl Backend for Gpu { Ok(()) } + fn attn_sel(&self, q: u64, kc: u64, vc: u64, idx: u64, cnt: u64, out: u64, nt: usize, nh: usize, nkv: usize, hd: usize, ns: usize, scale: f32) -> anyhow::Result<()> { + let per = nh / nkv.max(1); + anyhow::ensure!(hd % 32 == 0 && hd <= 256 && nkv > 0 && nh % nkv == 0 && per <= 32, "attn_sel: unsupported shape nh={nh} nkv={nkv} hd={hd}"); + launch!(self, "attn_sel", cfg((nt as u32, nkv as u32), (per * 32) as u32, (((per + 64) * hd + per * 32 + 32) * 4) as u32), + q, kc, vc, idx, cnt, out, nh as i32, nkv as i32, hd as i32, ns as i32, scale); + Ok(()) + } + + fn mla_attn(&self, q: u64, kc: u64, idx: u64, cnt: u64, out: u64, nt: usize, nh: usize, hd: usize, vd: usize, ns: usize, nmax: usize, qp: u64, qps: usize, qsc: f32) -> anyhow::Result<()> { + // A prompt or split queries: 32 heads a block on the tensor cores (`mla_attn_tc`), else 4 (one warp a head). + let tc = (nt > 1 || qp != 0) && nh % 32 == 0 && hd % 16 == 0 && vd % 32 == 0 && std::env::var_os("STRATA_MLA_SIMT").is_none(); + anyhow::ensure!(tc || (qp == 0 && qsc == 1.0), "mla_attn: split or scaled queries need the tensor-core kernel"); + let hb = if tc { 32 } else { 4 }; + let smem = if tc { 4 * 32 * (hd + 8) + 4 * (32 * 33 + 32 * 20 + 64) } else { 4 * hb * hd + 128 * (hd / 2 + 1) }; + anyhow::ensure!(hd % 2 == 0 && vd % 64 == 0 && vd <= 512 && vd <= hd && nh % hb == 0 && smem <= self.max_smem as usize, "mla_attn: unsupported shape nh={nh} hd={hd} vd={vd}"); + // Few queries (decode): split the keys so about 8 blocks run on each SM, at least 128 keys a split. + let blocks = nt * nh / hb; + let nsp = (8 * self.sms as usize).div_ceil(blocks).min(nmax.div_ceil(128)).max(1); + // Every split writes its whole partial row, so the reused buffer needs no clearing. + let mut part = self.mla_part.lock().unwrap(); + let need = nt * nh * nsp * (vd + 2) * 4; + if nsp > 1 && part.as_ref().is_none_or(|b| b.len() < need) { *part = Some(self.alloc(need)?); } + let pa = if nsp > 1 { part.as_ref().unwrap().addr() } else { 0 }; + let lc = LaunchConfig { grid_dim: (nt as u32, (nh / hb) as u32, nsp as u32), block_dim: (if tc { 256 } else { 128 }, 1, 1), shared_mem_bytes: smem as u32 }; + if tc { + launch!(self, "mla_attn_tc", lc, q, kc, idx, cnt, out, pa, nh as i32, hd as i32, vd as i32, ns as i32, nsp as i32, qp, qps as i32, qsc); + } else { + launch!(self, "mla_attn", lc, q, kc, idx, cnt, out, pa, nh as i32, hd as i32, vd as i32, ns as i32, nsp as i32); + } + if nsp > 1 { launch!(self, "mla_combine", cfg(((nt * nh) as u32, 1), 128, 0), pa, out, vd as i32, nsp as i32); } + Ok(()) + } + + fn idx_score(&self, q: u64, w: u64, k: u64, out: u64, nt: usize, nk: usize, nh: usize, hd: usize) -> anyhow::Result<()> { + anyhow::ensure!(hd == 128, "idx_score: head dim {hd} not supported"); + // A few queries: the old tile wastes the threads of the missing queries and has too few blocks. + if nt <= 4 && nh % 8 == 0 && nh <= 64 { + launch!(self, "idx_score_dec", cfg((nk.div_ceil(32) as u32, nt as u32), 256, 0), q, w, k, out, nk as i32, nh as i32); + } else { + launch!(self, "idx_score", cfg((nk.div_ceil(64) as u32, nt.div_ceil(64) as u32), 256, 0), q, w, k, out, nt as i32, nk as i32, nh as i32); + } + Ok(()) + } + + fn vit_attn(&self, q: u64, k: u64, v: u64, out: u64, n: usize, nh: usize, hd: usize, scale: f32) -> anyhow::Result<()> { + // sm_80+: the tensor-core kernel, the head padded to 80 or 128 (STRATA_VIT_SCALAR=1 keeps the scalar one). + let tc = [80, 128].into_iter().find(|&p| hd <= p); + if let Some(p) = tc.filter(|_| self.int8_mma && hd % 4 == 0 && std::env::var_os("STRATA_VIT_SCALAR").is_none()) { + launch!(self, &format!("vit_attn_tc_{p}"), cfg((n.div_ceil(64) as u32, nh as u32), 128, 0), + q, k, v, out, n as i32, nh as i32, hd as i32, scale); + return Ok(()); + } + // Within the 48 KiB a block gets without an opt-in: hd up to 117. + let smem = (64 * hd + 32 * (hd + 1) + 1024) * 4; + anyhow::ensure!(hd > 0 && smem <= 48 << 10, "vit_attn: head dim {hd} not supported"); + launch!(self, "vit_attn", cfg((n.div_ceil(32) as u32, nh as u32), 128, smem as u32), + q, k, v, out, n as i32, nh as i32, hd as i32, scale); + Ok(()) + } + + fn vit_norm(&self, x: u64, out: u64, w: u64, b: u64, rows: usize, n: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "vit_norm", cfg((rows as u32, 1), 256, 0), x, out, w, b, n as i32, eps); + Ok(()) + } + + fn vit_bias(&self, y: u64, stride: usize, bias: u64, rows: usize, cols: usize, act: i32) -> anyhow::Result<()> { + launch!(self, "vit_bias", cfg((cols.div_ceil(256) as u32, rows as u32), 256, 0), y, stride as i32, bias, cols as i32, act); + Ok(()) + } + + fn vit_rope(&self, x: u64, n: usize, nh: usize, hd: usize, m: usize, mx: usize, base: f32) -> anyhow::Result<()> { + launch!(self, "vit_rope", cfg((n as u32, 1), 256, 0), x, nh as i32, hd as i32, m as i32, mx as i32, base); + Ok(()) + } + fn qsa_pool(&self, ik: u64, ring: u64, pool: u64, w: u64, step: u64, t: usize, n_rot: usize, base: f32, eps: f32) -> anyhow::Result<()> { launch!(self, "qsa_pool", cfg(((t / 4 + 1) as u32, 1), 128, 0), ik, ring, pool, w, step, t as i32, n_rot as i32, base, eps); Ok(()) @@ -1257,6 +2091,21 @@ impl Backend for Gpu { Ok(()) } + fn hc_write_norm(&self, r: u64, out: u64, inj: u64, w: u64, xn: u64, n: usize, hc: usize, nt: usize, clear: bool, eps: f32, cnt: u64) -> anyhow::Result<()> { + if cnt == 0 { + self.hc_write(r, out, inj, n, hc, nt, clear)?; + return self.rms_norm_streams(r, w, xn, n, hc, nt, eps); + } + launch!(self, "hc_write_norm", cfg((hc as u32, nt as u32), 512, 0), r, out, inj, w, xn, n as i32, hc as i32, clear as i32, eps, cnt); + Ok(()) + } + + fn hc_mix_q(&self, xn: u64, g: u64, out: u64, n: usize, hc: usize, nt: usize, xq: u64) -> anyhow::Result<()> { + if xq == 0 || n % 32 != 0 { return self.hc_mix(xn, g, out, n, hc, nt).and_then(|_| if xq != 0 { self.quant_xq(out, n, n, nt, xq) } else { Ok(()) }); } + launch!(self, "hc_mix_q", cfg((n.div_ceil(256) as u32, nt as u32), 32, 0), xn, g, out, n as i32, hc as i32, xq, nt as i32); + Ok(()) + } + fn hc_write(&self, r: u64, out: u64, inj: u64, n: usize, hc: usize, nt: usize, clear: bool) -> anyhow::Result<()> { launch!(self, "hc_write", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), r, out, inj, n as i32, hc as i32, clear as i32); Ok(()) @@ -1272,14 +2121,19 @@ impl Backend for Gpu { Ok(()) } - fn kv_words(&self, n: usize) -> usize { - match self.kv_mode { 0 => n, 1 => n * 17 / 32, 2 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } - } + fn kv_words(&self, n: usize) -> usize { kv_mode_words(self.kv_k_mode, n) } + fn kv_words_v(&self, n: usize) -> usize { kv_mode_words(self.kv_v_mode, n) } fn kv_store(&self, k: u64, v: u64, kc: u64, vc: u64, n: usize, t: usize, step: u64, hd: usize) -> anyhow::Result<()> { // q8/q4: each warp quantizes one 32-value block of one row. - anyhow::ensure!(self.kv_mode == 0 || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32"); - launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + anyhow::ensure!((self.kv_k_mode == 0 && self.kv_v_mode == 0) || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32"); + if self.kv_k_mode >= 4 || self.kv_v_mode >= 4 { + anyhow::ensure!(hd % 128 == 0, "TurboQuant KV needs head_dim divisible by 128, got {hd}"); + launch!(self, "kv_store_turbo", cfg(((n * t / 128) as u32, 1), 128, 0), + k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + } else { + launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + } Ok(()) } @@ -1302,14 +2156,40 @@ impl Backend for Gpu { Ok(()) } - fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool) -> anyhow::Result<()> { + fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool, hid: u64, hmin: i32) -> anyhow::Result<()> { anyhow::ensure!(n <= 512 && k <= 32, "moe_route: {n} experts, top {k}"); - launch!(self, "moe_route", cfg((1, 1), 256, 0), p, n as i32, k as i32, extra_scale, table, ids, wts, slots, wh, h, mb, nh as i32, h_off as i32, step, t as i32, pid, sigmoid as i32); + launch!(self, "moe_route", cfg((1, 1), 256, 0), p, n as i32, k as i32, extra_scale, table, ids, wts, slots, wh, h, mb, nh as i32, h_off as i32, step, t as i32, pid, sigmoid as i32, hid, hmin); Ok(()) } fn moe_mailbox_optional(&self) -> bool { true } + fn host_share(&self) -> bool { true } + + fn host_is_pinned(&self, data: &[u8]) -> bool { + let start = data.as_ptr() as usize; + self.pinned.lock().unwrap().iter().any(|&(p, n)| start >= p && start + data.len() <= p + n) + } + + fn host_register(&self, p: usize, len: usize) -> anyhow::Result { + self.ctx.bind_to_thread()?; + let flags = sys::CU_MEMHOSTREGISTER_DEVICEMAP | sys::CU_MEMHOSTREGISTER_PORTABLE; + let r = unsafe { sys::cuMemHostRegister_v2(p as *mut _, len, flags) }; + if r != sys::CUresult::CUDA_SUCCESS { + crate::say!("host share: pinning {} MB failed ({r:?}); every missed expert stays on the CPU", len >> 20); + return Ok(false); + } + let mut dev = 0; + let r = unsafe { sys::cuMemHostGetDevicePointer_v2(&mut dev, p as *mut _, 0) }; + // The kernels take the host address as it is: the device must see the pages at the same address (UVA). + if r != sys::CUresult::CUDA_SUCCESS || dev as usize != p { + unsafe { sys::cuMemHostUnregister(p as *mut _) }; + return Ok(false); + } + self.pinned.lock().unwrap().push((p, len)); + Ok(true) + } + fn moe_prefetch_supported(&self) -> bool { true } fn moe_prefetch(&self, ids: u64, k: usize, table: u64, base: u64, stride: usize, bytes: usize) -> anyhow::Result<()> { @@ -1380,16 +2260,16 @@ mod tests { return; } } - let src = super::source(0, true); + let src = super::source(0, 0, true); super::nvrtc::cubin(&src, "sm_70").unwrap_or_else(|e| panic!("sm_70 must compile: M1-T4 removed the last blocker: {e:#}")); super::nvrtc::cubin(&src, "sm_80").expect("the sm_80 path must keep compiling (cubin for sm_80)"); // Same sm_70 source with the FMA fallback selected: both variants must produce a cubin (M2-T1). - super::nvrtc::cubin(&super::source(0, false), "sm_70").expect("the STRATA_GEMM_FMA sm_70 source must compile"); + super::nvrtc::cubin(&super::source(0, 0, false), "sm_70").expect("the STRATA_GEMM_FMA sm_70 source must compile"); // M2-T3 candidates C2 (`__launch_bounds__(·, 2)`) and C3 (`GEMM_BK = 32`) must compile before the window. - let c23 = super::source_with(0, true, super::Tune { gemm_bk: 32, gemm_min_blocks: 2, ..super::Tune::def() }); + let c23 = super::source_with(0, 0, true, super::Tune { gemm_bk: 32, gemm_min_blocks: 2, ..super::Tune::def() }); super::nvrtc::cubin(&c23, "sm_70").expect("the C2/C3 candidate tiles must compile for sm_70"); // M2-T5 load-width candidate: one 16-byte Q4_K header load in the GEMV path must compile for both arches. - let lw = super::source_with(0, true, super::Tune { gemv_loadw: 1, ..super::Tune::def() }); + let lw = super::source_with(0, 0, true, super::Tune { gemv_loadw: 1, ..super::Tune::def() }); super::nvrtc::cubin(&lw, "sm_70").expect("the GEMV_LOADW candidate must compile for sm_70"); super::nvrtc::cubin(&lw, "sm_80").expect("the GEMV_LOADW candidate must compile for sm_80"); } @@ -1398,10 +2278,14 @@ mod tests { #[test] fn nvrtc_compiles_full_source_for_sm75() { if !super::nvrtc::present() { return; } - super::nvrtc::cubin(&super::source(0, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 must compile: {e:#}")); - super::nvrtc::cubin(&super::source(1, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q8 must compile: {e:#}")); - super::nvrtc::cubin(&super::source(2, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q4 must compile: {e:#}")); - super::nvrtc::cubin(&super::source(3, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q2 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(0, 0, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(1, 1, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q8 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(2, 2, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q4 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(3, 3, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q2 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(4, 4, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_turbo4 must compile: {e:#}")); + // The GTX 16 build: the CUDA-core branch of mma16816 on sm_75 (see `turing_fma`). + let fma = super::device_source(0, 0, false, true); + super::nvrtc::cubin(&fma, "sm_75").unwrap_or_else(|e| panic!("sm_75 MMA_FMA (GTX 16) must compile: {e:#}")); } #[test] @@ -1418,6 +2302,39 @@ mod tests { } } + #[test] + fn turing_fma_only_for_turing_without_tensor_cores() { + // TU116/TU117 cards, at sm_75 only; `gemm_fma` (STRATA_GEMM_FMA) turns it on for any sm_75 card and `keep_tc` + // (STRATA_GEMM_TC) off. Flags are passed in, so the caller's environment does not matter. + for name in ["NVIDIA GeForce GTX 1660 SUPER", "NVIDIA GeForce GTX 1650", "NVIDIA GeForce GTX 1650 Ti with Max-Q Design", + "NVIDIA GeForce MX450", "NVIDIA T600 Laptop GPU", "Quadro T1000", "NVIDIA T1000 8GB", "NVIDIA CMP 30HX"] { + assert!(super::turing_fma(name, (7, 5), false, false), "{name}"); + assert!(!super::turing_fma(name, (7, 5), false, true), "{name} with STRATA_GEMM_TC"); + } + for name in ["NVIDIA GeForce RTX 2070", "Tesla T4", "Quadro RTX 4000", "NVIDIA TITAN RTX", "NVIDIA RTX A2000"] { + assert!(!super::turing_fma(name, (7, 5), false, false), "{name}"); + } + assert!(super::turing_fma("NVIDIA GeForce RTX 2070", (7, 5), true, false)); // STRATA_GEMM_FMA + assert!(!super::turing_fma("NVIDIA GeForce GTX 1660 SUPER", (8, 6), false, false)); + assert!(!super::turing_fma("Tesla V100-SXM2-32GB", (7, 0), true, false)); + assert!(super::device_log(0, "x", "sm_75", (7, 5), true).contains("CUDA-core FMA")); + assert!(super::device_log(0, "x", "sm_75", (7, 5), false).contains("m16n8k8")); + } + + #[test] + fn cubin_cache_key_changes_with_mma_fma() { + // The chain `Gpu::new` follows: a GTX 16 name picks the CUDA-core branch, the source it compiles carries the + // define (and differs only by it from an RTX 20 card's), and its cubin gets its own cache key, so a GTX 16 card + // can't load the tensor-core cubin. + let (fma, tc) = (super::turing_fma("NVIDIA GeForce GTX 1660 SUPER", (7, 5), false, false), + super::turing_fma("NVIDIA GeForce RTX 2070", (7, 5), false, false)); + let (a, b) = (super::device_source(0, 0, false, fma), super::device_source(0, 0, false, tc)); + assert!(a.starts_with("#define MMA_FMA 1\n"), "the GTX 16 source must carry the define"); + assert!(!b.contains("#define MMA_FMA"), "an RTX 20 card's source must not"); + assert_eq!(&a["#define MMA_FMA 1\n".len()..], b, "the define is the only difference"); + assert_ne!(super::cache_key(&a, "sm_75", "12.4"), super::cache_key(&b, "sm_75", "12.4")); + } + #[test] fn device_log_names_turing_not_volta() { assert!(super::device_log(0, "x", "sm_75", (7, 5), false).contains("Turing")); @@ -1486,6 +2403,16 @@ mod tests { "cuda device 0: NVIDIA GeForce RTX 3060, sm_86"); } + /// CPU-only: a backend that has one format for both halves must reject a mixed layout before its size helpers. + #[test] + fn legacy_symmetric_kv() { + for m in 0..=3 { assert!(super::kv_legacy_symmetric(m, m), "mode {m}"); } + assert!(!super::kv_legacy_symmetric(0, 1)); + assert!(!super::kv_legacy_symmetric(2, 0)); + assert!(!super::kv_legacy_symmetric(4, 4)); + assert!(!super::kv_legacy_symmetric(10, 10)); + } + /// M1-T5, CPU-only: the int8 prefill GEMM needs int8 tensor cores, which Volta (7.x) lacks; every sm_80+ part /// keeps it. #[test] @@ -1498,19 +2425,29 @@ mod tests { } /// M1-T5, CPU-only: the loaded name list drops `gemmi_*`/`gemmis_*` only on a device where kernels.cu compiles - /// them out. 370 names today (sm_80); 23 non-float types x 2 fewer names = 324 on sm_70. + /// them out. 469 names today (sm_80), 397 on sm_70. #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 370); - assert_eq!(sm70.len(), 324); - assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmis")), + assert_eq!(sm80.len(), 470); + assert_eq!(sm70.len(), 398); + assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); assert!(sm80.contains(&"gemmi_q4_k".to_string())); assert!(sm80.contains(&"gemmis_q2_k".to_string())); } + #[test] + fn kernel_names_tu11x_dp4a() { + let tu11x = super::kernel_names_with(false, true); + assert_eq!(tu11x.len(), 446); + assert!(tu11x.contains(&"gemmi_q4_k".to_string())); + assert!(tu11x.contains(&"gemmis_q8_0".to_string())); + assert!(tu11x.iter().all(|n| !n.starts_with("gemmd")), + "TU11x dp4a path must not require sm_80 gemmd_* kernels"); + } + /// M1-T7/M2-T3, CPU-only: the per-family dynamic shared memory a launch can ask for, from the launcher's tile /// shapes. The attention prefill figure comes from `attn_prefill_smem`, the same helper `attn_prefill_m` uses. #[test] @@ -1575,17 +2512,20 @@ mod tests { /// kernel; the C2/C3 window candidates only change the injected values. #[test] fn source_injects_tiles() { - let src = super::source_with(0, true, super::Tune::def()); + let src = super::source_with(0, 0, true, super::Tune::def()); for define in [ "#define GEMM_BM 128", "#define GEMM_BK 64", "#define GEMM_MIN_BLOCKS 1", "#define GEMV_LOADW 0", "#define FA_BQ 64", "#define FA_BK 32", + // kernels.cu reads STRATA_HIP in C++ expressions (`ATT_RUN_CP`), not only in `#if`, so NVRTC needs it + // defined; hip/compat.h sets it to 1 for the HIP build. + "#define STRATA_HIP 0", ] { assert!(src.contains(define), "source is missing `{define}`"); } - let c23 = super::source_with(0, true, super::Tune { gemm_bk: 32, gemm_min_blocks: 2, ..super::Tune::def() }); + let c23 = super::source_with(0, 0, true, super::Tune { gemm_bk: 32, gemm_min_blocks: 2, ..super::Tune::def() }); assert!(c23.contains("#define GEMM_BK 32")); assert!(c23.contains("#define GEMM_MIN_BLOCKS 2")); - let lw = super::source_with(0, true, super::Tune { gemv_loadw: 1, ..super::Tune::def() }); + let lw = super::source_with(0, 0, true, super::Tune { gemv_loadw: 1, ..super::Tune::def() }); assert!(lw.contains("#define GEMV_LOADW 1")); } @@ -1680,4 +2620,219 @@ mod tests { assert_eq!(super::smem_log("attn_decode_*", 98304, 2112, None, None), "cuda shared memory: opt-in 98304 B per block, attn_decode_*: 2112 B static, dynamic max default (48 KiB), carveout default"); } + + /// `STRATA_CTRL_TILE` is read as text: unset or any value but "0" keeps the tiled `ink_ctrl_*` pair. The + /// attention flags are plain presence checks and must pass through unchanged. + #[test] + fn ink_flags_parse_ctrl_tile() { + // One card: the default is the old kernels (greedy output must match main). + let one = super::InkFlags::from_parts(None, false, None, None, None); + assert!(!one.fast && !one.ctrl_tile && !one.attn_old && !one.attn_kp4); + // Two cards: `auto` turns the fast kernels on. + let two = super::InkFlags::from_parts(None, true, None, None, None); + assert!(two.fast && two.ctrl_tile && !two.attn_old && !two.attn_kp4); + // Explicit opt-in/opt-out and per-kernel overrides. + assert!(super::InkFlags::from_parts(Some("1"), false, None, None, None).fast); + assert!(!super::InkFlags::from_parts(Some("0"), true, None, None, None).fast); + assert!(!super::InkFlags::from_parts(None, true, Some("0"), None, None).ctrl_tile); + let old = super::InkFlags::from_parts(None, true, None, Some("1"), None); + assert!(old.attn_old && !old.attn_kp4); + let kp4 = super::InkFlags::from_parts(None, true, None, None, Some("1")); + assert!(kp4.attn_kp4 && !kp4.attn_old); + let off = super::InkFlags::from_parts(None, true, Some("0"), Some("0"), Some("0")); + assert!(!off.ctrl_tile && !off.attn_old && !off.attn_kp4); + } + #[test] + fn ink_q8_dispatch_respects_formats_shapes_and_precedence() { + use super::{InkFlags, InkPrefillKernel as P}; + let mut flags = InkFlags::from_parts(None, false, None, None, None); + assert!(!flags.attn_q8_shared && !flags.attn_q8_hd128); + for (shared, decode, want_shared, want_decode) in [ + (None, None, true, true), (Some("1"), Some("1"), true, true), + (Some("0"), None, false, true), (None, Some("0"), true, false), + (Some("0"), Some("0"), false, false), (Some("other"), Some(""), true, true), + ] { + let actual = flags.with_cuda_q8(shared, decode); + assert_eq!(actual.prefill_kernel(1, 128, 4, 2, 0) == P::Shared, want_shared); + assert_eq!(actual.decode_kernel(1, 128, 28).0 == "ink_attn_q8_hd128", want_decode); + } + assert_eq!(flags.decode_kernel(1, 128, 40), ("ink_attn", 64)); + assert_eq!(flags.prefill_kernel(1, 128, 4, 1, 0), P::Grouped); + flags.attn_q8_shared = true; + flags.attn_q8_hd128 = true; + for nr in [28, 32, 40] { + assert_eq!(flags.decode_kernel(1, 128, nr), ("ink_attn_q8_hd128", 64)); + } + for mode in [0, 2, 3, 4, 10] { + assert_eq!(flags.decode_kernel(mode, 128, 28), ("ink_attn", 64)); + } + for hd in [32, 64] { + assert_eq!(flags.decode_kernel(1, hd, 28), ("ink_attn", 64)); + assert_eq!(flags.prefill_kernel(1, hd, 4, 1, 0), P::Grouped); + } + for nh in [1, 2, 4] { + assert_eq!(flags.prefill_kernel(1, 128, nh, 1, 0), P::Shared); + } + for mode in [2, 3, 4, 10] { + assert_eq!(flags.prefill_kernel(mode, 128, 4, 1, 0), P::Grouped); + } + for (nh, nkv, win) in [(5, 1, 0), (3, 2, 0), (4, 0, 0), (4, 1, 1)] { + assert_eq!(flags.prefill_kernel(1, 128, nh, nkv, win), P::Grouped); + } + assert_eq!(flags.prefill_kernel(0, 64, 4, 1, 0), P::Shared); + flags.fast = true; + assert_eq!(flags.decode_kernel(2, 128, 32), ("ink_attn_128_q4", 128)); + assert_eq!(flags.decode_kernel(0, 128, 32), ("ink_attn_128", 128)); + assert_eq!(flags.decode_kernel(0, 128, 40), ("ink_attn", 64)); + assert_eq!(flags.prefill_kernel(0, 128, 4, 1, 0), P::KeyParallel16); + assert_eq!(flags.prefill_kernel(1, 128, 4, 1, 0), P::Shared); + flags.attn_kp4 = true; + assert_eq!(flags.prefill_kernel(0, 128, 4, 1, 0), P::KeyParallel4); + flags.attn_old = true; + assert_eq!(flags.decode_kernel(1, 128, 28), ("ink_attn", 64)); + assert_eq!(flags.prefill_kernel(1, 128, 4, 1, 0), P::Old); + assert_eq!(flags.prefill_kernel(0, 64, 4, 1, 0), P::Shared); + } + + + /// The 128-key decode attention is for head_dim 128, a relative-bias row of at most 32 and an f16 or a q4 cache + /// (K and V both); every other cache format, a mixed one included, and the old-kernel settings keep `ink_attn`. + #[test] + fn ink_attn_pick_by_cache_format() { + let scalar = ("ink_attn", 64); + assert_eq!(super::ink_attn_pick(0, true, 128, 16), ("ink_attn_128", 128)); + assert_eq!(super::ink_attn_pick(2, true, 128, 16), ("ink_attn_128_q4", 128)); + assert_eq!(super::ink_attn_pick(2, true, 128, 32), ("ink_attn_128_q4", 128)); + for kv in [1, 3, 4, 5, 6, 10] { assert_eq!(super::ink_attn_pick(kv, true, 128, 16), scalar, "kv mode {kv}"); } + for kv in [0, 2] { + assert_eq!(super::ink_attn_pick(kv, false, 128, 16), scalar, "kv mode {kv}: one card, or STRATA_DS_ATTN_OLD"); + assert_eq!(super::ink_attn_pick(kv, true, 64, 16), scalar, "kv mode {kv}: head_dim 64"); + assert_eq!(super::ink_attn_pick(kv, true, 128, 40), scalar, "kv mode {kv}: nr 40"); + } + } + + /// GPU parity test (run with `cargo test --lib cuda::tests::attn_prefill_parity_and_outliers -- --ignored --nocapture`): + /// verifies `attn_prefill_{64,128,256}` against an exact f64 causal reference on both normal and high-magnitude + /// outlier Q/K/V inputs across multiple KV tiles. + #[test] + #[ignore] + fn attn_prefill_parity_and_outliers() -> anyhow::Result<()> { + use crate::backend::Backend; + let gpu = super::Gpu::new(0)?; + + fn lcg(state: &mut u64) -> f32 { + *state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let bits = ((*state >> 40) as u32) as f32 / (1u32 << 24) as f32; + bits * 2.0 - 1.0 + } + + fn as_bytes(s: &[T]) -> &[u8] { + unsafe { std::slice::from_raw_parts(s.as_ptr() as *const u8, std::mem::size_of_val(s)) } + } + + for &(hd, outlier) in &[(64usize, false), (128, false), (256, false), (64, true), (128, true), (256, true)] { + let (t, nh, nkv) = (128usize, 4usize, 2usize); + let scale = 1.0f32 / (hd as f32).sqrt(); + let mut rng = 0x5eed_cafe_0000u64 ^ ((hd as u64) << 16) ^ (outlier as u64); + + let mut q = vec![0.0f32; t * nh * hd]; + let mut k_f16 = vec![0u16; t * nkv * hd]; + let mut v_f16 = vec![0u16; t * nkv * hd]; + let mut k_f32 = vec![0.0f32; t * nkv * hd]; + let mut v_f32 = vec![0.0f32; t * nkv * hd]; + + for i in 0..q.len() { + let mut x = lcg(&mut rng) * 1.5; + if outlier && (i % hd) < 8 { x *= 25.0; } // outlier Q channels (~±37.5) + q[i] = x; + } + for i in 0..k_f16.len() { + let mut x = lcg(&mut rng) * 1.5; + if outlier && (i % hd) < 8 { x *= 25.0; } // outlier K channels (~±37.5, |q*k| ~1400) + let h = half::f16::from_f32(x); + k_f16[i] = h.to_bits(); + k_f32[i] = h.to_f32(); + } + for i in 0..v_f16.len() { + let mut x = lcg(&mut rng) * if outlier { 8.0 } else { 1.5 }; + if outlier && (i / (nkv * hd)) == 0 { x *= 2.0; } // strong attention-sink V + let h = half::f16::from_f32(x); + v_f16[i] = h.to_bits(); + v_f32[i] = h.to_f32(); + } + + let d_q = gpu.alloc(q.len() * 4)?; + let d_k = gpu.alloc(k_f16.len() * 2)?; + let d_v = gpu.alloc(v_f16.len() * 2)?; + let d_out = gpu.alloc(q.len() * 4)?; + let d_step = gpu.alloc(4)?; + gpu.htod(as_bytes(&q), &d_q, 0)?; + gpu.htod(as_bytes(&k_f16), &d_k, 0)?; + gpu.htod(as_bytes(&v_f16), &d_v, 0)?; + gpu.htod(&0i32.to_le_bytes(), &d_step, 0)?; + + gpu.attn_prefill_m( + d_q.addr(), d_k.addr(), d_v.addr(), 0, d_out.addr(), d_step.addr(), + t, nh, nkv, hd, scale, 0, 0, 0, 0, + )?; + gpu.sync()?; + + let mut got = vec![0.0f32; q.len()]; + let mut got_bytes = vec![0u8; q.len() * 4]; + gpu.dtoh(&d_out, 0, &mut got_bytes)?; + for (dst, ch) in got.iter_mut().zip(got_bytes.chunks_exact(4)) { + *dst = f32::from_le_bytes(ch.try_into().unwrap()); + } + + // Exact f64 causal attention reference (using the same f16-quantized Q*scale and K/V). + let mut max_abs = 0.0f64; + let mut max_ref = 0.0f64; + for qi in 0..t { + for h in 0..nh { + let kvh = h / (nh / nkv); + let q_row = &q[(qi * nh + h) * hd..(qi * nh + h + 1) * hd]; + let mut scores = vec![0.0f64; qi + 1]; + let mut mx = f64::NEG_INFINITY; + for ki in 0..=qi { + let k_row = &k_f32[(ki * nkv + kvh) * hd..(ki * nkv + kvh + 1) * hd]; + let mut dot = 0.0f64; + for d in 0..hd { + let qs = half::f16::from_f32(q_row[d] * scale).to_f32() as f64; + dot += qs * (k_row[d] as f64); + } + scores[ki] = dot; + if dot > mx { mx = dot; } + } + let mut denom = 0.0f64; + for s in &mut scores { + *s = (*s - mx).exp(); + denom += *s; + } + for d in 0..hd { + let mut acc = 0.0f64; + for ki in 0..=qi { + acc += (scores[ki] / denom) * (v_f32[(ki * nkv + kvh) * hd + d] as f64); + } + let g = got[(qi * nh + h) * hd + d]; + assert!(g.is_finite(), "non-finite output at hd={hd} outlier={outlier} qi={qi} h={h} d={d}: {g}"); + max_ref = max_ref.max(acc.abs()); + max_abs = max_abs.max((g as f64 - acc).abs()); + } + } + } + let rel = max_abs / max_ref.max(1.0); + eprintln!("attn_prefill_{hd} outlier={outlier}: max_abs={max_abs:.6e}, rel={rel:.6e} (max_ref={max_ref:.3})"); + assert!(rel < 2e-3, "precision drift too high for hd={hd} outlier={outlier}: max_abs={max_abs}, rel={rel}"); + } + Ok(()) + } +} + +impl Drop for Gpu { + fn drop(&mut self) { + let pinned = std::mem::take(&mut *self.pinned.lock().unwrap()); + if !pinned.is_empty() && self.ctx.bind_to_thread().is_ok() { + for (p, _) in pinned { unsafe { sys::cuMemHostUnregister(p as *mut _) }; } + } + } } diff --git a/src/cuda/nvrtc.rs b/src/cuda/nvrtc.rs index de4a1cbb..218b1495 100644 --- a/src/cuda/nvrtc.rs +++ b/src/cuda/nvrtc.rs @@ -24,10 +24,32 @@ struct Nvrtc { /// Library names and paths to try, in order. `STRATA_NVRTC` (a path or a name) replaces the whole list. pub fn candidates() -> Vec { - names(cfg!(windows), std::env::var_os("STRATA_NVRTC").map(Into::into), std::env::var_os("CUDA_PATH").map(Into::into)) + names(cfg!(windows), std::env::var_os("STRATA_NVRTC").map(Into::into), toolkit_roots()) } -fn names(windows: bool, forced: Option, cuda_path: Option) -> Vec { +/// Toolkit folders to look in after the bare names: `CUDA_PATH` (set by the Windows installer), and on Linux also +/// `CUDA_HOME`, the folder above the `nvcc` on `PATH`, `/usr/local/cuda*`, `/opt/cuda*` and `~/cuda*`. A toolkit +/// unpacked in the home folder is not on the loader path, so a bare name never finds it (issue 41). +fn toolkit_roots() -> Vec { + let mut v: Vec = ["CUDA_PATH", "CUDA_HOME"].iter().filter_map(|k| std::env::var_os(k)).map(Into::into).collect(); + if cfg!(windows) { v.truncate(1); return v; } + if let Some(p) = std::env::var_os("PATH") { + v.extend(std::env::split_paths(&p).filter(|d| d.join("nvcc").is_file()).filter_map(|d| d.parent().map(Path::to_path_buf))); + } + let home = std::env::var_os("HOME").map(PathBuf::from); + for (dir, prefix) in [(Some(PathBuf::from("/usr/local")), "cuda"), (Some(PathBuf::from("/opt")), "cuda"), (home, "cuda")] { + let Some(dir) = dir else { continue }; + let mut found: Vec = std::fs::read_dir(&dir).into_iter().flatten().flatten() + .filter(|e| e.file_name().to_string_lossy().starts_with(prefix)).map(|e| e.path()).collect(); + // `cuda` (the symlink to the default toolkit) first, then the newest version. + found.sort_by_key(|p| (p.file_name().is_some_and(|n| n != prefix), std::cmp::Reverse(p.clone()))); + v.extend(found); + } + v.dedup(); + v +} + +fn names(windows: bool, forced: Option, roots: Vec) -> Vec { if let Some(p) = forced { return vec![p]; } let mut v: Vec = cudarc::get_lib_name_candidates("nvrtc").into_iter().map(Into::into).collect(); if windows { @@ -35,9 +57,17 @@ fn names(windows: bool, forced: Option, cuda_path: Option) -> const DLLS: [&str; 2] = ["nvrtc64_130_0.dll", "nvrtc64_120_0.dll"]; v.extend(DLLS.map(PathBuf::from)); // The toolkit installer sets CUDA_PATH; its DLL directory (`bin`, `bin\x64` since 13) is not always on PATH. - if let Some(root) = cuda_path { + for root in &roots { for dir in ["bin", "bin/x64"] { for dll in DLLS { v.push(root.join(dir).join(dll)); } } } + } else { + // `libnvrtc.so` comes only with the -dev package; a runtime-only install has the versioned name, and some + // toolkits ship only the `.alt` build (same API, issue 41). + const SOS: [&str; 6] = ["libnvrtc.so", "libnvrtc.so.13", "libnvrtc.so.12", "libnvrtc.alt.so.13", "libnvrtc.alt.so.12", "libnvrtc.alt.so"]; + v.extend(SOS[1..].iter().map(PathBuf::from)); + for root in &roots { + for dir in ["lib64", "lib", "targets/x86_64-linux/lib", "targets/sbsa-linux/lib"] { for so in SOS { v.push(root.join(dir).join(so)); } } + } } v } @@ -84,7 +114,9 @@ pub fn version() -> Option<(i32, i32)> { /// The error for a machine with no usable NVRTC: names what was searched, so a wrong DLL name is visible to the user. pub fn missing() -> anyhow::Error { - let tried: Vec = candidates().iter().map(|p| p.display().to_string()).collect(); + // Toolkit paths only where the folder exists, so the list stays short. + let tried: Vec = candidates().iter().filter(|p| p.parent().is_none_or(|d| d.as_os_str().is_empty() || d.is_dir())) + .map(|p| p.display().to_string()).collect(); anyhow::anyhow!( "the CUDA NVRTC library is not installed or not on the library path (tried: {}); install the CUDA toolkit or its \ NVRTC package (12.x for sm_70: 13.x dropped Volta support), or set STRATA_NVRTC to the library file", @@ -134,11 +166,15 @@ mod tests { /// Issue 35: the CUDA 12.x Windows DLL, by bare name and under CUDA_PATH, must be on the list. #[test] fn windows_names_cover_cuda12_and_cuda_path() { - let v = names(true, None, Some(PathBuf::from("C:/cuda"))); + let v = names(true, None, vec![PathBuf::from("C:/cuda")]); for want in ["nvrtc64_120_0.dll", "nvrtc64_130_0.dll", "C:/cuda/bin/nvrtc64_120_0.dll", "C:/cuda/bin/x64/nvrtc64_130_0.dll"] { assert!(v.contains(&PathBuf::from(want)), "{want} missing from {v:?}"); } - assert!(!names(false, None, Some(PathBuf::from("/opt/cuda"))).iter().any(|p| p.to_string_lossy().contains("120_0"))); - assert_eq!(names(true, Some(PathBuf::from("x.dll")), None), [PathBuf::from("x.dll")]); + let linux = names(false, None, vec![PathBuf::from("/home/u/cuda-13.0")]); + assert!(!linux.iter().any(|p| p.to_string_lossy().contains("120_0"))); + for want in ["libnvrtc.so.13", "libnvrtc.alt.so", "/home/u/cuda-13.0/lib64/libnvrtc.alt.so.13"] { + assert!(linux.contains(&PathBuf::from(want)), "{want} missing"); + } + assert_eq!(names(true, Some(PathBuf::from("x.dll")), vec![]), [PathBuf::from("x.dll")]); } } diff --git a/src/deepseek/chat.rs b/src/deepseek/chat.rs index a028374b..7fc332de 100644 --- a/src/deepseek/chat.rs +++ b/src/deepseek/chat.rs @@ -8,9 +8,33 @@ pub fn gpu_defaults() { if std::env::var_os("STRATA_DS_GPU").is_none() { unsafe { std::env::set_var("STRATA_DS_GPU", "1") } } } +/// `gpu_defaults` for DeepSeek itself: without `--device` (STRATA_DS_DEVICES unset) it runs on every CUDA device, as +/// `rustingstrata interface` does, so a second card adds VRAM for the expert cache instead of sitting idle. +pub fn ds_defaults() { + gpu_defaults(); + let cuda = std::env::var("STRATA_DS_BACKEND").map_or(true, |b| b == "cuda"); + if cuda && std::env::var_os("STRATA_DS_DEVICES").is_none() { + let n = crate::cuda::device_uuids().len(); + if let Some(v) = default_devices(n) { unsafe { std::env::set_var("STRATA_DS_DEVICES", v) } } + } +} + +/// STRATA_DS_DEVICES for `n` CUDA devices: all of them, or None (the default device 0) for fewer than two. +fn default_devices(n: usize) -> Option { + (n > 1).then(|| (0..n).map(|d| d.to_string()).collect::>().join(",")) +} + +#[test] +fn every_cuda_device_by_default() { + assert_eq!(default_devices(0), None); + assert_eq!(default_devices(1), None); + assert_eq!(default_devices(2).as_deref(), Some("0,1")); + assert_eq!(default_devices(4).as_deref(), Some("0,1,2,3")); +} + /// `rustingstrata generate`: raw prompt (no template), greedy, prints the continuation. pub fn generate(g: &Gguf, prompt: &str, n: usize) -> anyhow::Result<()> { - gpu_defaults(); + ds_defaults(); let tok = Tokenizer::from_gguf(g)?; let mut m = DsModel::new(g)?; let eos = tok.eos_ids(); @@ -21,6 +45,7 @@ pub fn generate(g: &Gguf, prompt: &str, n: usize) -> anyhow::Result<()> { let next = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; if eos.contains(&next) { break; } out.push(next); + crate::term::decoded(1); let s = tok.decode(&out)?; if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { print!("{}", &s[shown..]); @@ -34,7 +59,7 @@ pub fn generate(g: &Gguf, prompt: &str, n: usize) -> anyhow::Result<()> { } pub fn chat(g: &Gguf, system: Option, n: usize, think: bool) -> anyhow::Result<()> { - gpu_defaults(); + ds_defaults(); let tok = Tokenizer::from_gguf(g)?; let mut m = DsModel::new(g)?; let eos = tok.eos_ids(); @@ -65,6 +90,7 @@ pub fn chat(g: &Gguf, system: Option, n: usize, think: bool) -> anyhow:: let next = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; if eos.contains(&next) { break; } out.push(next); + crate::term::decoded(1); let s = tok.decode(&out)?; if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { print!("{}", &s[shown..]); @@ -88,43 +114,48 @@ fn ctx_limit(g: &Gguf) -> usize { /// The chat of `rustingstrata serve` for DeepSeek (see `serve::Own`): one request at a time, JSON or SSE. /// Earlier reasoning is kept by default, like llama-server (`chat_template_kwargs.preserve_thinking:false` drops it). -/// ponytail: greedy only, no tools/stop strings; the KV cache is reused only when the new prompt extends the last sequence. +/// ponytail: greedy only; the KV cache is reused only when the new prompt extends the last sequence. pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Result> { use anyhow::Context; use serde_json::json; - gpu_defaults(); + ds_defaults(); let mut m = DsModel::new(g)?; + crate::serve::warm_up(tok, |ids| { m.prefill(ids); m.reset(); })?; let eos = tok.eos_ids(); let ctx = ctx_limit(g); Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| { + let mut lim = crate::grammar::Constraint::new(q, tok)?; let ids = tok.encode(&Template::Ds.render(&q.messages, &q.tools, q.think.unwrap_or(false), q.preserve_thinking.unwrap_or(true), true)).ok().filter(|i| !i.is_empty()).context("cannot encode prompt")?; - anyhow::ensure!(ids.len() <= ctx, "prompt is {} tokens, the limit is {ctx}", ids.len()); + anyhow::ensure!(ids.len() <= ctx, "{}", crate::serve::too_long(ids.len(), ctx)); let t = std::time::Instant::now(); let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; - let mut logits = m.prefill(&ids[keep..]); + if q.stream && !q.head_sent { let _ = write!(c, "{}", crate::serve::sse_head(c)); } + let mut logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); let prefill_s = t.elapsed().as_secs_f64(); - let n = q.max_tokens.unwrap_or(256).min(ctx - ids.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let n = q.max_tokens.unwrap_or(usize::MAX).min(ctx - ids.len()); let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); - let mut hold = crate::chat::Hold::new(tools, vec![]).tagged(Template::Ds.call_tag()); + let mut hold = crate::chat::Hold::new(tools, q.stop.clone()).tagged(Template::Ds.call_tag()); let (mut out, mut shown, mut done) = (vec![], 0, "length"); + let mut alive = std::time::Instant::now(); for i in 0..n { - let next = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; + let next = crate::grammar::greedy(&mut lim, &mut logits); if eos.contains(&next) { done = "stop"; break; } out.push(next); + crate::term::decoded(1); let s = tok.decode(&out).unwrap_or_default(); if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { let t = hold.push(&s[shown..]); shown = s.len(); - if q.stream && !t.is_empty() && write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_err() { break; } + if q.stream && !(if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() }) { break; } + if hold.stopped { break; } } if i + 1 < n { logits = m.step(next); } } let s = tok.decode(&out).unwrap_or_default(); if s.len() > shown && s.is_char_boundary(shown) { hold.push(&s[shown..]); } let calls = if tools { Template::Ds.parse_calls(&hold.text, &q.tools) } else { None }; - let done = if calls.is_some() { "tool_calls" } else { done }; + let done = if calls.is_some() { "tool_calls" } else if hold.stopped { "stop" } else { done }; let calls_json = |(content, calls): &(String, Vec<(String, String)>), stream: bool| { let c: Vec<_> = calls.iter().enumerate().map(|(k, (f, a))| { let mut c = json!({"id": format!("call_{k}"), "type": "function", "function": {"name": f, "arguments": a}}); @@ -133,20 +164,26 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Resu }).collect(); if stream { json!({"tool_calls": c}) } else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } }; + let d = crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done, drafts: None }; + let timings = d.timings(t); + let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), "prompt_tokens_details": {"cached_tokens": keep}}); if q.stream { match &calls { Some(x) => { let _ = write!(c, "data: {}\n\n", chunk(calls_json(x, true), None)); } None if !hold.rest().is_empty() => { let _ = write!(c, "data: {}\n\n", chunk(json!({"content": hold.rest()}), None)); } None => {} } - let _ = write!(c, "data: {}\n\ndata: [DONE]\n\n", chunk(json!({}), Some(done))); + let mut last = chunk(json!({}), Some(done)); + last["usage"] = usage; + last["timings"] = timings; + let _ = write!(c, "data: {last}\n\ndata: [DONE]\n\n"); } else { let message = match &calls { Some(x) => calls_json(x, false), None => json!({"role": "assistant", "content": hold.text}) }; let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": message, "finish_reason": done}], - "usage": {"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len()}}); + "usage": usage, "timings": timings}); crate::serve::send(c, "200 OK", "application/json", &b.to_string()); } - Ok(crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done }) + Ok(d) })) } diff --git a/src/deepseek/forward.rs b/src/deepseek/forward.rs index 53369a4f..7eefbc4e 100644 --- a/src/deepseek/forward.rs +++ b/src/deepseek/forward.rs @@ -1,7 +1,7 @@ //! Slow single-token CPU reference forward for DeepSeek-V4.1 (mirrors llama.cpp deepseek41.cpp). //! Not implemented: indexer top-k (only matters beyond 512 visible compressed rows, i.e. >1024 tokens) //! and the candidate-block prune (beyond 4096 rows). The window boundary (128) is unverified. -use super::mat::{Mat, matvec_many, matvec_many_opt, vec_f32}; +use super::mat::{Mat, matvec_many, matvec_rows, matvec_rows_many, vec_f32}; use super::ops::*; use super::{AttnKind, DsConfig}; use crate::gguf::Gguf; @@ -53,6 +53,32 @@ struct Cache { pend_s: Vec>, } +/// Every layer's attention keys as f16 rows for `mla_attn` (GPU attention): a sink row a layer, then the raw and +/// compressed rows as they come. A row is the key (`head_dim` values, zero-padded to `vd`) and `n_head` more dims, +/// zero but in a layer's sink row, where dim vd + h holds head h's sink logit: head h's query has 1 at dim vd + h, +/// so the sink row scores the sink and adds nothing to V (its first vd dims are zero). +struct Gkv { + rows: Vec, + w: usize, + vd: usize, + /// Rows already on the card. + sent: usize, + sink: Vec, + /// Row of each raw key [layer][position] (u32::MAX: left out, outside every window). + raw: Vec>, + /// Row of each compressed key [layer][index]. + comp: Vec>, +} + +impl Gkv { + fn push(&mut self, k: &[f32]) -> u32 { + let n = self.rows.len() / self.w; + self.rows.extend(k.iter().map(|v| half::f16::from_f32(*v).to_bits())); + self.rows.resize((n + 1) * self.w, 0); + n as u32 + } +} + pub struct DsModel<'a> { pub cfg: DsConfig, tok_embd: Mat<'a>, @@ -61,9 +87,15 @@ pub struct DsModel<'a> { engram_tab: Option>, layers: Vec>, cache: Vec, - pre_prev: [f32; 4], + /// The keys on each GPU (`mla_attn`), a layer's on the GPU of its matrices; empty: attention on the CPU (no + /// GPU, or `STRATA_DS_CPU_ATTN`). + gkv: Vec>, + /// The GPU of each layer's attention. + card: Vec, pub toks: Vec, pub trace: bool, + /// The share of the VRAM-cache misses the CPU computes (`share`), tuned each layer by `balance`. + cpu_share: std::cell::Cell, } fn act(gate: f32, up: f32, limit: f32) -> f32 { @@ -79,6 +111,9 @@ impl<'a> DsModel<'a> { }; let mut layers = vec![]; for il in 0..cfg.n_layer { + // A layer's plain weights on one GPU: its attention then runs there. + let pre = format!("blk.{il}."); + super::mat::dev_pick(g.tensors.iter().filter(|(n, t)| n.starts_with(&pre) && !n.contains("_exps") && t.dims.len() == 2).map(|(_, t)| g.bytes(t).len()).sum()); let m = |n: &str| Mat::load(g, &format!("blk.{il}.{n}")); let v = |n: &str| vec_f32(g, &format!("blk.{il}.{n}")); let hcw = |s: &str| -> Result { Ok(Hcw { f: m(&format!("hc_{s}_fn.weight"))?, base: v(&format!("hc_{s}_base.weight"))?, scale: v(&format!("hc_{s}_scale.weight"))? }) }; @@ -100,17 +135,63 @@ impl<'a> DsModel<'a> { }); } let engram_tab = if cfg.engram.is_some() { Some(Mat::load(g, "per_layer_token_embd.weight")?) } else { None }; + // More of the expert cache in VRAM (as GigaChat4): 95% of free VRAM on a card with 8 GB or more free, the + // 80% default below that so a smaller card keeps room to stage experts. + if std::env::var_os("STRATA_DS_GPU_FRACTION").is_none() { unsafe { std::env::set_var("STRATA_DS_GPU_FRACTION", "0.8,0.95") } } let n = cfg.n_layer; - Ok(DsModel { + let vd = cfg.head_dim.next_multiple_of(64); + let card: Vec = layers.iter().map(|l| match l.wq_b.gpu { Some(i) if i != super::mat::dev::STAGED => super::mat::dev::gpu_of(i), _ => 0 }).collect(); + let on = super::mat::dev_info().is_some() && std::env::var_os("STRATA_DS_CPU_ATTN").is_none() && vd <= 512 && cfg.n_head % 4 == 0; + let gkv = (0..if on { card.iter().max().map_or(1, |c| c + 1) } else { 0 }) + .map(|_| Box::new(Gkv { rows: vec![], w: vd + cfg.n_head, vd, sent: 0, sink: vec![], raw: vec![vec![]; n], comp: vec![vec![]; n] })).collect(); + let mut m = DsModel { tok_embd: Mat::load(g, "token_embd.weight")?, out_norm: vec_f32(g, "output_norm.weight")?, out_w: Mat::load(g, "output.weight")?, - engram_tab, layers, cache: (0..n).map(|_| Cache::default()).collect(), pre_prev: [1.0, 0.0, 0.0, 0.0], toks: vec![], trace: std::env::var("STRATA_DS_TRACE").is_ok(), cfg, - }) + engram_tab, layers, cache: (0..n).map(|_| Cache::default()).collect(), toks: vec![], trace: std::env::var("STRATA_DS_TRACE").is_ok(), cfg, + cpu_share: std::cell::Cell::new(0.5), gkv, card, + }; + m.gkv_build(); + Ok(m) } + /// (Re)build the GPU key rows from the caches, leaving out raw rows outside every window; all go up again. + /// A GPU's key rows: the sinks of every layer, the raw rows of its layers, the compressed rows its layers read. + fn gkv_build(&mut self) { + for d in 0..self.gkv.len() { + let uses = self.uses(d); + let g = &mut self.gkv[d]; + g.rows.clear(); + g.sent = 0; + g.sink.clear(); + for l in &self.layers { + let mut r = vec![0f32; g.vd + l.sinks.len()]; + r[g.vd..].copy_from_slice(&l.sinks); + let at = g.push(&r); + g.sink.push(at); + } + for (il, c) in self.cache.iter().enumerate() { + g.comp[il] = if uses[il] { c.comp.iter().map(|k| g.push(k)).collect() } else { vec![] }; + let w0 = c.raw.len().saturating_sub(self.cfg.window); + g.raw[il] = if self.card[il] != d { vec![] } else { + c.raw.iter().enumerate().map(|(p, k)| if p < w0 { u32::MAX } else { g.push(k) }).collect() + }; + } + } + } + + /// Per source layer: whether a layer on GPU `d` reads its compressed rows. + fn uses(&self, d: usize) -> Vec { + let mut u = vec![false; self.layers.len()]; + for (il, &c) in self.card.iter().enumerate() { if c == d { u[self.cfg.kv_src[il].max(0) as usize] = true; } } + u + } + + /// The GPU of each layer's attention (its key rows live there). + pub fn attn_cards(&self) -> &[usize] { &self.card } + /// Forget the whole sequence (new conversation). pub fn reset(&mut self) { self.cache.iter_mut().for_each(|c| *c = Cache::default()); - self.pre_prev = [1.0, 0.0, 0.0, 0.0]; + self.gkv_build(); self.toks.clear(); } @@ -128,9 +209,9 @@ impl<'a> DsModel<'a> { } } - fn engram(&self, e: usize, il: usize, pos: usize, x: &mut [f32]) { + /// The hashed Engram table rows of the token at `pos` (layer slot `e`): the input of `engram_kv`. + fn engram_rows(&self, e: usize, pos: usize) -> Vec { let en = self.cfg.engram.as_ref().unwrap(); - let (kvw, gatew) = self.layers[il].engram.as_ref().unwrap(); let tab = self.engram_tab.unwrap(); let (ng, nh) = (en.ngram, en.heads_per_ngram); let ncol = (ng - 1) * nh; @@ -156,9 +237,13 @@ impl<'a> DsModel<'a> { tab.row_into(id as usize, &mut rows[col * en.head_dim..(col + 1) * en.head_dim]); } } + rows + } + + /// Add the gated Engram value `kv` (`engram_kv` of the token's rows) to the streams `x`. + fn engram_apply(&self, il: usize, kv: &[f32], x: &mut [f32]) { + let gatew = &self.layers[il].engram.as_ref().unwrap().1; let n = self.cfg.n_embd; - let mut kv = vec![0f32; kvw.rows]; - kvw.matvec(&rows, &mut kv); let (mut xn, mut kn) = (vec![0f32; n], vec![0f32; n]); for s in 0..4 { rms_norm(&x[s * n..(s + 1) * n], self.cfg.eps, &mut xn); @@ -171,79 +256,118 @@ impl<'a> DsModel<'a> { } } - fn hc_mix(&self, h: &Hcw, x: &[f32]) -> Hc { - let mut xn = vec![0f32; x.len()]; - rms_norm(x, self.cfg.eps, &mut xn); - let mut mixes = vec![0f32; 24]; - h.f.matvec(&xn, &mut mixes); - hc_coeffs(&mixes, &h.scale, &h.base, self.cfg.hc_eps, self.cfg.hc_iters) + /// The hyper-connection coefficients of each stream set in `xs`, and the matrices `extra` on the rows `nrms` + /// ([matrix][token][rows], as `rows`). The rows do not depend on the coefficients, so a decode step runs both in + /// one GPU round trip. + fn hc_mix(&self, h: &Hcw<'a>, xs: &[Vec], extra: &[Mat<'a>], nrms: &[Vec]) -> (Vec, Vec>) { + let xn: Vec> = xs.iter().map(|x| { let mut xn = vec![0f32; x.len()]; rms_norm(x, self.cfg.eps, &mut xn); xn }).collect(); + let (mixes, ys) = if xs.len() == 1 { + // Job i reads x[i * w..]: the normed streams, then a padded copy of the row for each extra matrix. + let w = xn[0].len(); + let mut x = xn[0].clone(); + for _ in extra { x.extend(&nrms[0]); x.resize(x.len() + w - nrms[0].len(), 0.0); } + let ms: Vec> = std::iter::once(h.f).chain(extra.iter().copied()).collect(); + let y = matvec_many(&ms, &x, w); + let mut at = 0; + let mut ys: Vec> = ms.iter().map(|m| { at += m.rows; y[at - m.rows..at].to_vec() }).collect(); + (ys.remove(0), ys) + } else { + let mixes = rows(&[h.f], &xn.iter().map(|x| x.as_slice()).collect::>()).swap_remove(0); + (mixes, rows(extra, &nrms.iter().map(|x| x.as_slice()).collect::>())) + }; + (mixes.chunks_exact(24).map(|m| hc_coeffs(m, &h.scale, &h.base, self.cfg.hc_eps, self.cfg.hc_iters)).collect(), ys) } - fn attention(&mut self, il: usize, pos: usize, cur: &[f32]) -> Vec { - let cfg = &self.cfg; - let (nh, hd, nr) = (cfg.n_head, cfg.head_dim, cfg.n_rot); + /// The matrices that read attention's normed row: wq_a, wkv and the compressor's kv and gate. + fn first(&self, il: usize) -> Vec> { let l = &self.layers[il]; - // wq_a, wkv and the compressor's kv/gate all read `cur`: one GPU round trip. let mut first = vec![l.wq_a, l.wkv]; if let Some(cw) = &l.comp { first.push(cw.kv); first.extend(cw.gate); } - let y0 = matvec_many(&first, cur, 0); - let (qa, kv0_pre) = (y0[..cfg.q_lora].to_vec(), &y0[cfg.q_lora..]); - let mut qr = vec![0f32; cfg.q_lora]; - rms_norm_w(&qa, &l.q_a_norm, cfg.eps, &mut qr); - self.tr("qr_norm", il as i32, &qr); - let mut q = vec![0f32; nh * hd]; - l.wq_b.matvec(&qr, &mut q); - for h in 0..nh { - l.rope.apply(&mut q[h * hd..(h + 1) * hd], pos, false); - } - let kv0 = &kv0_pre[..hd]; - let mut kv = vec![0f32; hd]; - rms_norm_w(kv0, &l.kv_a_norm, cfg.eps, &mut kv); - l.rope.apply(&mut kv, pos, false); - self.tr("q", il as i32, &q); - self.tr("kv", il as i32, &kv); - - // compressor on source layers + first + } + + /// Attention of layer `il` for `nt` tokens at `p0..`, given `ys`, the matrices of `first` on their normed rows: + /// their outputs, token after token. + fn attention(&mut self, il: usize, p0: usize, nt: usize, ys: Vec>) -> Vec { + use rayon::prelude::*; + let first = self.first(il); + let cfg = &self.cfg; + let (nh, hd, ql) = (cfg.n_head, cfg.head_dim, cfg.q_lora); + let l = &self.layers[il]; + // Each token's outputs of `first`, concatenated as one `matvec_many` gives them. + let y0: Vec> = (0..nt).map(|t| first.iter().zip(&ys).flat_map(|(m, y)| y[t * m.rows..(t + 1) * m.rows].iter().copied()).collect()).collect(); + let qr: Vec = y0.iter().flat_map(|y| { let mut r = vec![0f32; ql]; rms_norm_w(&y[..ql], &l.q_a_norm, cfg.eps, &mut r); r }).collect(); + if nt == 1 { self.tr("qr_norm", il as i32, &qr); } + + // The cache, token after token: the raw row, and on source layers the compressor's pending rows. let src = cfg.kv_src[il].max(0) as usize; let ratio = match cfg.attn[il] { AttnKind::Window => 0, AttnKind::Csa => 2, AttnKind::Hca => 1 }; - if let Some(cw) = &self.layers[il].comp { - let v = kv0_pre[hd..2 * hd].to_vec(); - let s = if cw.gate.is_some() { kv0_pre[2 * hd..3 * hd].to_vec() } else { vec![0f32; hd] }; - let c = &mut self.cache[il]; - c.pend_v.push(v); - c.pend_s.push(s); - if c.pend_v.len() == ratio { - let mut comp = vec![0f32; hd]; - for j in 0..hd { - let mx = c.pend_s.iter().map(|s| s[j]).fold(f32::NEG_INFINITY, f32::max); - let ws: Vec = c.pend_s.iter().map(|s| (s[j] - mx).exp()).collect(); - let z: f32 = ws.iter().sum(); - comp[j] = ws.iter().zip(&c.pend_v).map(|(w, v)| w / z * v[j]).sum(); + for (t, y) in y0.iter().enumerate() { + let pos = p0 + t; + let kv0_pre = &y[ql..]; + let mut kv = vec![0f32; hd]; + rms_norm_w(&kv0_pre[..hd], &self.layers[il].kv_a_norm, self.cfg.eps, &mut kv); + self.layers[il].rope.apply(&mut kv, pos, false); + if nt == 1 { self.tr("kv", il as i32, &kv); } + if let Some(cw) = &self.layers[il].comp { + let v = kv0_pre[hd..2 * hd].to_vec(); + let s = if cw.gate.is_some() { kv0_pre[2 * hd..3 * hd].to_vec() } else { vec![0f32; hd] }; + let c = &mut self.cache[il]; + c.pend_v.push(v); + c.pend_s.push(s); + if c.pend_v.len() == ratio { + let mut comp = vec![0f32; hd]; + for j in 0..hd { + let mx = c.pend_s.iter().map(|s| s[j]).fold(f32::NEG_INFINITY, f32::max); + let ws: Vec = c.pend_s.iter().map(|s| (s[j] - mx).exp()).collect(); + let z: f32 = ws.iter().sum(); + comp[j] = ws.iter().zip(&c.pend_v).map(|(w, v)| w / z * v[j]).sum(); + } + c.pend_v.clear(); + c.pend_s.clear(); + let g = c.comp.len(); + let mut row = vec![0f32; hd]; + rms_norm_w(&comp, &cw.norm, self.cfg.eps, &mut row); + if nt == 1 { self.tr("comp_latent", il as i32, &row); } + self.layers[il].rope.apply(&mut row, g * ratio, false); + for d in 0..self.gkv.len() { + if self.uses(d)[il] { let g = &mut self.gkv[d]; let r = g.push(&row); g.comp[il].push(r); } + } + self.cache[il].comp.push(row); } - c.pend_v.clear(); - c.pend_s.clear(); - let g = c.comp.len(); - let mut row = vec![0f32; hd]; - rms_norm_w(&comp, &cw.norm, cfg.eps, &mut row); - self.tr("comp_latent", il as i32, &row); - self.layers[il].rope.apply(&mut row, g * ratio, false); - self.cache[il].comp.push(row); } + if let Some(g) = self.gkv.get_mut(self.card[il]) { let r = g.push(&kv); g.raw[il].push(r); } + self.cache[il].raw.push(kv); + } + // One decode token, no dumps: wq_b, attention, wo_a and wo_b chained on the GPU, one readback. + if nt == 1 && !self.trace && std::env::var_os("STRATA_DS_DUMP").is_none() && let Some(y) = self.attn_chain(il, p0, &qr) { return y; } + let l = &self.layers[il]; + let mut q = rows(&[l.wq_b], &qr.chunks_exact(ql).collect::>()).swap_remove(0); + for (t, qt) in q.chunks_exact_mut(nh * hd).enumerate() { + for h in qt.chunks_exact_mut(hd) { l.rope.apply(h, p0 + t, false); } } - self.cache[il].raw.push(kv); + if nt == 1 { self.tr("q", il as i32, &q); } + let gpu = self.attn_gpu(il, p0, &q); + let cfg = &self.cfg; let l = &self.layers[il]; - let raw = &self.cache[il].raw; - let w0 = (pos + 1).saturating_sub(cfg.window); - let ncomp = if ratio == 0 { 0 } else { ((pos + 1) / ratio).min(self.cache[src].comp.len()) }; - let comp = &self.cache[src].comp; + let (raw, comp) = (&self.cache[il].raw, &self.cache[src].comp); let scale = 1.0 / (hd as f32).sqrt(); - let mut out = vec![0f32; nh * hd]; - let keys: Vec<&[f32]> = raw[w0..=pos].iter().map(|k| &k[..]).chain(comp[..ncomp].iter().map(|k| &k[..hd])).collect(); - // heads are independent: same math per head, spread over the cores - use rayon::prelude::*; - out.par_chunks_mut(hd).enumerate().for_each(|(h, o)| { - let qh = &q[h * hd..(h + 1) * hd]; + // Token t sees the raw rows of its window and the compressed rows complete by its position (src <= il, so + // the source layer has already run this chunk). Every (token, head) is independent: spread over the cores. + let mut out = vec![0f32; nt * nh * hd]; + if let Some(y) = gpu { + out.par_chunks_mut(hd).enumerate().for_each(|(i, o)| { + o.copy_from_slice(&y[i * (y.len() / (nt * nh))..][..hd]); + l.rope.apply(o, p0 + i / nh, true); + }); + } else { out.par_chunks_mut(hd).enumerate().for_each(|(i, o)| { + let (t, h) = (i / nh, i % nh); + let pos = p0 + t; + let w0 = (pos + 1).saturating_sub(cfg.window); + let ncomp = if ratio == 0 { 0 } else { ((pos + 1) / ratio).min(comp.len()) }; + let keys: Vec<&[f32]> = raw[w0..=pos].iter().map(|k| &k[..]).chain(comp[..ncomp].iter().map(|k| &k[..hd])).collect(); + let qh = &q[i * hd..(i + 1) * hd]; let mut sc: Vec = keys.iter().map(|k| k.iter().zip(qh).map(|(a, b)| a * b).sum::() * scale).collect(); let mx = sc.iter().cloned().fold(l.sinks[h], f32::max); let mut z = (l.sinks[h] - mx).exp(); @@ -252,24 +376,85 @@ impl<'a> DsModel<'a> { for j in 0..hd { o[j] += s / z * k[j]; } } l.rope.apply(o, pos, true); - }); - let _ = nr; - self.tr("attn_derope", il as i32, &out); - let gsz = nh * hd / cfg.o_groups; - let subs: Vec<_> = (0..cfg.o_groups).map(|g| l.wo_a.group(g, cfg.o_groups)).collect(); - let oa = matvec_many(&subs, &out, gsz); - self.tr("attn_wo_a", il as i32, &oa); - let mut res = vec![0f32; cfg.n_embd]; - l.wo_b.matvec(&oa, &mut res); - res + }); } + if nt == 1 { self.tr("attn_derope", il as i32, &out); } + let og = cfg.o_groups; + let gsz = nh * hd / og; + let subs: Vec<_> = (0..og).map(|g| l.wo_a.group(g, og)).collect(); + let oa = if nt == 1 { + matvec_many(&subs, &out, gsz) + } else { + // Group g reads its slice of every token's heads; the outputs come back group-major. + let x: Vec = (0..og).flat_map(|g| out.chunks_exact(nh * hd).flat_map(move |o| o[g * gsz..(g + 1) * gsz].iter().copied())).collect(); + let y = matvec_rows_many(&subs.iter().map(|m| (*m, nt)).collect::>(), &x); + let r = subs[0].rows; + (0..nt).flat_map(|t| (0..og).flat_map(move |g| (g * nt + t) * r..(g * nt + t + 1) * r)).map(|i| y[i]).collect() + }; + if nt == 1 { self.tr("attn_wo_a", il as i32, &oa); } + rows(&[l.wo_b], &oa.chunks_exact(l.wo_b.cols).collect::>()).swap_remove(0) + } + + /// Attention of layer `il` on the GPU (`mla_attn`) for the roped queries `q` of the tokens at `p0..`, their keys + /// already in the caches: [token][head][vd], before the de-rope. None without GPU attention or on failure. + fn attn_gpu(&mut self, il: usize, p0: usize, q: &[f32]) -> Option> { + let cfg = &self.cfg; + let d = self.card[il]; + let (nh, hd) = (cfg.n_head, cfg.head_dim); + let nt = q.len() / (nh * hd); + let (idx, ns, cnt) = self.key_lists(il, p0, nt)?; + let g = self.gkv.get_mut(d)?; + let (w, vd) = (g.w, g.vd); + let scale = 1.0 / (hd as f32).sqrt(); + let mut qg = vec![0f32; nt * nh * w]; + for (i, d) in qg.chunks_exact_mut(w).enumerate() { + for (d, v) in d.iter_mut().zip(&q[i * hd..(i + 1) * hd]) { *d = v * scale; } + d[vd + i % nh] = 1.0; + } + let n = g.rows.len() / w; + let y = super::mat::mla_attn_on(d, &**g as *const Gkv as usize, g.sent, &qg, &g.rows, Some((&idx, ns)), &cnt, nh, w, vd)?; + g.sent = n; + Some(y) + } + + /// `attention`'s wq_b, GPU attention, de-rope, wo_a and wo_b for one decode token at `p0` in one round trip + /// (`ds_attn_on`), its keys already in the caches. None where that does not apply. + fn attn_chain(&mut self, il: usize, p0: usize, qr: &[f32]) -> Option> { + let (idx, ..) = self.key_lists(il, p0, 1)?; + let (d, nh, hd) = (self.card[il], self.cfg.n_head, self.cfg.head_dim); + let l = &self.layers[il]; + let cs: Vec = (0..l.rope.n_dims / 2).flat_map(|i| { let (c, s) = l.rope.cs(p0 as f32, i); [c, s] }).collect(); + let subs: Vec<_> = (0..self.cfg.o_groups).map(|g| l.wo_a.group(g, self.cfg.o_groups)).collect(); + let g = &mut self.gkv[d]; + let n = g.rows.len() / g.w; + let y = super::mat::ds_attn_on(d, &**g as *const Gkv as usize, g.sent, &g.rows, &idx, qr, &l.wq_b, &subs, &l.wo_b, &cs, nh, hd, g.w, g.vd, 1.0 / (hd as f32).sqrt())?; + g.sent = n; + Some(y) + } + + /// Each of the `nt` tokens at `p0..` its key rows in layer `il`'s GPU rows (as in `attention`: the sink, its + /// window's raw rows, the compressed rows complete by its position), padded to `ns` each, and their counts. + fn key_lists(&self, il: usize, p0: usize, nt: usize) -> Option<(Vec, usize, Vec)> { + let cfg = &self.cfg; + let g = self.gkv.get(self.card[il])?; + let src = cfg.kv_src[il].max(0) as usize; + let ratio = match cfg.attn[il] { AttnKind::Window => 0, AttnKind::Csa => 2, AttnKind::Hca => 1 }; + let lists: Vec> = (0..nt).map(|t| { + let pos = p0 + t; + let w0 = (pos + 1).saturating_sub(cfg.window); + let ncomp = if ratio == 0 { 0 } else { ((pos + 1) / ratio).min(g.comp[src].len()) }; + std::iter::once(g.sink[il]).chain(g.raw[il][w0..=pos].iter().copied()).chain(g.comp[src][..ncomp].iter().copied()).collect() + }).collect(); + let ns = lists.iter().map(|l| l.len()).max()?; + let idx: Vec = lists.iter().flat_map(|l| l.iter().copied().chain(std::iter::repeat(0)).take(ns)).collect(); + let cnt: Vec = lists.iter().map(|l| l.len() as i32).collect(); + Some((idx, ns, cnt)) } - fn ffn(&self, il: usize, cur: &[f32]) -> Vec { + /// The MoE FFN of one token: `cur` its normed row, `logits` the router's on it. + fn ffn(&self, il: usize, cur: &[f32], logits: &[f32]) -> Vec { let t0 = std::time::Instant::now(); let cfg = &self.cfg; let l = &self.layers[il]; - let mut logits = vec![0f32; cfg.n_expert]; - l.gate_inp.matvec(cur, &mut logits); self.tr("ffn_moe_logits", il as i32, &logits); let mut sel = route(&logits, &l.bias, cfg.n_used, cfg.weights_norm, cfg.weights_scale); // debug: force llama.cpp's expert ids (STRATA_DS_FORCE_TOPK=dir of i32 dumps, prompt tokens only) to separate routing flips from math errors @@ -288,118 +473,320 @@ impl<'a> DsModel<'a> { self.tr("ffn_moe_topk", il as i32, &ids); let n = cfg.n_embd; let mut out = vec![0f32; n]; - let (mut g, mut u, mut d) = (vec![0f32; cfg.n_ff_exp], vec![0f32; cfg.n_ff_exp], vec![0f32; n]); if std::env::var_os("STRATA_DS_NOPREFETCH").is_none() { for &(e, _) in &sel { for m in [&l.gexps, &l.uexps, &l.dexps] { m.prefetch_expert(e, cfg.n_expert); } } } let t1 = std::time::Instant::now(); - // Every selected expert has a GPU slot (resident or staged): 2 GPU round trips per layer instead of 3 per expert. - let gu: Vec<_> = sel.iter().map(|s| l.gexps.expert(s.0, cfg.n_expert)).chain(sel.iter().map(|s| l.uexps.expert(s.0, cfg.n_expert))).collect(); - let nf = cfg.n_ff_exp; - let fast = gu.iter().all(|m| m.gpu.is_some()).then(|| { - let gu_y = matvec_many_opt(&gu, cur, 0)?; - let k = sel.len(); - let a: Vec = (0..k * nf).map(|i| act(gu_y[i], gu_y[k * nf + i], cfg.clamp_exp[il])).collect(); - let dm: Vec<_> = sel.iter().map(|s| l.dexps.expert(s.0, cfg.n_expert)).collect(); - matvec_many_opt(&dm, &a, nf) - }).flatten(); - if let Some(dy) = &fast { - PROF[3].fetch_add(1000 * gu.iter().filter(|m| m.gpu.is_some_and(|i| i != u32::MAX)).count() as u64, std::sync::atomic::Ordering::Relaxed); - for (i, &(_, w)) in sel.iter().enumerate() { for j in 0..n { out[j] += w * dy[i * n + j]; } } - } - for (e, w) in sel.into_iter().filter(|_| fast.is_none()) { - let ge = l.gexps.expert(e, cfg.n_expert); - PROF[3].fetch_add((ge.gpu.is_some_and(|i| i != u32::MAX)) as u64 * 1000, std::sync::atomic::Ordering::Relaxed); - ge.matvec(cur, &mut g); - l.uexps.expert(e, cfg.n_expert).matvec(cur, &mut u); - for j in 0..g.len() { g[j] = act(g[j], u[j], cfg.clamp_exp[il]); } - l.dexps.expert(e, cfg.n_expert).matvec(&g, &mut d); - for j in 0..n { out[j] += w * d[j]; } + let (ne, lim) = (cfg.n_expert, cfg.clamp_exp[il]); + // A layer's gate, up and down experts share one GPU (picked per layer, keyed on the gate tensor), so a batch + // runs on one card with one readback. + let extra = l.uexps.data.len() + l.dexps.data.len(); + let ex = |m: &Mat<'a>, e: usize, evict: bool| m.expert_opt_in(e, ne, evict, &l.gexps, extra); + // Experts resident in VRAM run on the GPU. Of the others the CPU computes `cpu_share` from the mapped file + // (integer Q8_K dots) while the GPU uploads and runs the rest, both at once, as in `gigachat4::forward`. + let (share, fixed) = self.share(); + let mats: Vec<[Mat<'a>; 3]> = sel.iter().map(|&(e, _)| [&l.gexps, &l.uexps, &l.dexps].map(|m| ex(m, e, share == 0.0))).collect(); + let miss = |m: &[Mat<'a>; 3]| m.iter().any(|x| x.gpu.is_none()); + let n_miss = mats.iter().filter(|m| miss(m)).count(); + let mut left = (share * n_miss as f32).round() as usize; + let (mut on_gpu, mut on_cpu) = (vec![], vec![]); + for (m, &(e, w)) in mats.into_iter().zip(&sel) { + if miss(&m) && left > 0 { + left -= 1; + on_cpu.push((l.gexps.expert_host(e, ne), l.uexps.expert_host(e, ne), l.dexps.expert_host(e, ne), w)); + continue; + } + // A miss the GPU takes: a free or evicted slot, else a copy staged for this use. + let tens = [&l.gexps, &l.uexps, &l.dexps]; + let [g, u, d]: [Mat<'a>; 3] = std::array::from_fn(|i| { + if m[i].gpu.is_some() { return m[i]; } + let x = ex(tens[i], e, true); + if x.gpu.is_some() { x } else { x.staged() } + }); + on_gpu.push((g, u, d, w)); } + PROF[3].fetch_add(1000 * on_gpu.iter().filter(|x| x.0.gpu.is_some_and(|i| i != u32::MAX)).count() as u64, std::sync::atomic::Ordering::Relaxed); + // The shared expert rides with the routed ones on the GPU (weight 1) when it has their shape and clamp: no + // round trips of its own. A trace keeps it apart, for its own dump. + let apart = self.trace || super::mat::dev_info().is_none() || cfg.n_shared != 1 || lim != cfg.clamp_shexp[il] + || !l.gsh.gpu.is_some_and(|i| i != u32::MAX); + if !apart { on_gpu.push((l.gsh, l.ush, l.dsh, 1.0)); } + let gpu_side = || { + let t = std::time::Instant::now(); + if on_gpu.is_empty() { return (vec![0f32; n], 0.0); } + // One round trip with the clamp on the device, else two (gates and ups, then downs). + let col = |i: usize| -> Vec> { on_gpu.iter().map(|x| [x.0, x.1, x.2][i]).collect() }; + let mix = match super::mat::swiglu_experts(&col(0), &col(1), &col(2), cur, 1, lim) { + Some(dy) => { + let mut mix = vec![0f32; n]; + for (x, d) in on_gpu.iter().zip(dy.chunks_exact(n)) { + for (m, v) in mix.iter_mut().zip(d) { *m += x.3 * v; } + } + mix + } + None => crate::hy4::forward::run_experts(&on_gpu, cur, lim, n), + }; + (mix, t.elapsed().as_secs_f32()) + }; + let cpu_side = || { + let t = std::time::Instant::now(); + (crate::hy4::forward::run_experts(&on_cpu, cur, lim, n), t.elapsed().as_secs_f32()) + }; + let ((a, tg), (b, tc)) = if on_cpu.is_empty() || on_gpu.is_empty() { (gpu_side(), cpu_side()) } else { rayon::join(gpu_side, cpu_side) }; + if !fixed && n_miss > 0 { self.balance(tg, tc); } + for j in 0..n { out[j] += a[j] + b[j]; } PROF[1].fetch_add(t1.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); PROF[0].fetch_add((t1 - t0).as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + if !apart { return out; } self.tr("ffn_moe_out", il as i32, &out); + let ts = std::time::Instant::now(); let fs = cfg.n_ff_exp * cfg.n_shared; let (mut g, mut u, mut d) = (vec![0f32; fs], vec![0f32; fs], vec![0f32; n]); l.gsh.matvec(cur, &mut g); l.ush.matvec(cur, &mut u); for j in 0..fs { g[j] = act(g[j], u[j], cfg.clamp_shexp[il]); } l.dsh.matvec(&g, &mut d); + prof(4, ts); self.tr("ffn_shexp", il as i32, &d); for j in 0..n { out[j] += d[j]; } out } + /// The CPU's share of a layer's VRAM-cache misses, and whether it is fixed (no GPU, or `STRATA_DS_CPU_SHARE`; + /// `--fixed-experts` is 0: every expert on the GPU). + fn share(&self) -> (f32, bool) { + static FIXED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let fixed = *FIXED.get_or_init(|| { + let share = std::env::var("STRATA_DS_CPU_SHARE").ok().and_then(|v| v.parse().ok()); + share.or(std::env::var_os("STRATA_FIXED_EXPERTS").map(|_| 0.0)) + }); + if super::mat::dev_info().is_none() { return (1.0, true); } + (fixed.unwrap_or(self.cpu_share.get()).clamp(0.0, 1.0), fixed.is_some()) + } + + /// Move the CPU share toward the side that finished first (GPU time `tg`, CPU time `tc`). + fn balance(&self, tg: f32, tc: f32) { + if tg + tc > 0.0 { self.cpu_share.set((self.cpu_share.get() + 0.1 * (tg - tc) / (tg + tc)).clamp(0.0, 1.0)); } + } + + /// `ffn` for the rows of a prefill chunk, token-major. A routed expert is read once for every token that picked + /// it; experts are split between the GPU and the CPU like the misses in `ffn` (as `gigachat4::forward::ffn_batch`). + fn ffn_batch(&self, il: usize, curs: &[Vec], logits: &[f32]) -> Vec { + use rayon::prelude::*; + let t0 = std::time::Instant::now(); + let cfg = &self.cfg; + let l = &self.layers[il]; + let (ne, n, lim, lim_sh) = (cfg.n_expert, cfg.n_embd, cfg.clamp_exp[il], cfg.clamp_shexp[il]); + let xs: Vec<&[f32]> = curs.iter().map(|c| c.as_slice()).collect(); + let sels: Vec> = logits.chunks_exact(ne).map(|lg| route(lg, &l.bias, cfg.n_used, cfg.weights_norm, cfg.weights_scale)).collect(); + let mut by_e: std::collections::BTreeMap> = Default::default(); + for (t, sel) in sels.iter().enumerate() { + for (k, &(e, _)) in sel.iter().enumerate() { by_e.entry(e).or_default().push((t, k)); } + } + if std::env::var_os("STRATA_DS_NOPREFETCH").is_none() { + by_e.keys().collect::>().par_iter().for_each(|&&e| { + for m in [&l.gexps, &l.uexps, &l.dexps] { m.prefetch_expert(e, ne); } + }); + } + let t1 = std::time::Instant::now(); + let extra = l.uexps.data.len() + l.dexps.data.len(); + let ex = |m: &Mat<'a>, e: usize, evict: bool| m.expert_opt_in(e, ne, evict, &l.gexps, extra); + let tens = [&l.gexps, &l.uexps, &l.dexps]; + let (share, fixed) = self.share(); + let mats: Vec<(usize, [Mat<'a>; 3])> = by_e.keys().map(|&e| (e, tens.map(|m| ex(m, e, share == 0.0)))).collect(); + let miss = |m: &[Mat<'a>; 3]| m.iter().any(|x| x.gpu.is_none()); + let n_miss = mats.iter().filter(|m| miss(&m.1)).count(); + let mut left = (share * n_miss as f32).round() as usize; + let (mut on_gpu, mut on_cpu) = (vec![], vec![]); + for (e, m) in mats { + if miss(&m) && left > 0 { + left -= 1; + on_cpu.push((e, tens.map(|t| t.expert_host(e, ne)))); + continue; + } + on_gpu.push((e, std::array::from_fn::, 3, _>(|i| { + if m[i].gpu.is_some() { return m[i]; } + let x = ex(tens[i], e, true); + if x.gpu.is_some() { x } else { x.staged() } + }))); + } + // The shared expert rides with the routed ones on the GPU (slot `n_used`, weight 1), as in `ffn`. + let sh = (super::mat::dev_info().is_some() && cfg.n_shared == 1 && lim == lim_sh && l.gsh.gpu.is_some_and(|i| i != u32::MAX)) + .then_some([l.gsh, l.ush, l.dsh]); + let rows_of = |e: usize| -> Vec<&[f32]> { by_e[&e].iter().map(|&(t, _)| xs[t]).collect() }; + let gpu = || { + let t = std::time::Instant::now(); + if on_gpu.is_empty() { return (vec![], None, 0.0); } + let col = |i: usize| -> Vec> { on_gpu.iter().map(|g| g.1[i]).chain(sh.map(|s| s[i])).collect() }; + let mut pairs: Vec> = on_gpu.iter().map(|(e, _)| by_e[e].iter().map(|&(t, k)| (t, k, sels[t][k].1)).collect()).collect(); + if sh.is_some() { pairs.push((0..xs.len()).map(|t| (t, cfg.n_used, 1.0)).collect()); } + if let Some(sum) = super::mat::swiglu_chunk(&col(0), &col(1), &col(2), &pairs, &xs.concat(), cfg.n_used + 1, lim) { + return (vec![], Some((sum, sh.is_some())), t.elapsed().as_secs_f32()); + } + let out: Vec<(usize, Vec)> = on_gpu.iter().map(|(e, [g, u, d])| (*e, swiglu_rows(g, u, d, &rows_of(*e), lim))).collect(); + (out, None, t.elapsed().as_secs_f32()) + }; + let cpu = || { + let t = std::time::Instant::now(); + let out: Vec<(usize, Vec)> = on_cpu.par_iter().map(|(e, [g, u, d])| (*e, swiglu_rows(g, u, d, &rows_of(*e), lim))).collect(); + (out, t.elapsed().as_secs_f32()) + }; + let ((a, gsum, tg), (b, tc)) = rayon::join(gpu, cpu); + if !fixed && n_miss > 0 { self.balance(tg, tc); } + // Each token sums its experts in its own selection order, as `ffn` does; the shared expert comes last. + let mut ds: Vec> = sels.iter().map(|s| vec![&[][..]; s.len()]).collect(); + for (e, dy) in a.iter().chain(&b) { + for (&(t, k), d) in by_e[e].iter().zip(dy.chunks_exact(n)) { ds[t][k] = d; } + } + let mut out = vec![0f32; xs.len() * n]; + out.par_chunks_exact_mut(n).enumerate().for_each(|(t, o)| { + // An expert of the device's chunk has no row here: its weighted output is in `gsum`. + for (d, &(_, w)) in ds[t].iter().zip(&sels[t]).filter(|(d, _)| !d.is_empty()) { + for j in 0..n { o[j] += w * d[j]; } + } + if let Some((g, _)) = &gsum { for j in 0..n { o[j] += g[t * n + j]; } } + }); + PROF[1].fetch_add(t1.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + PROF[0].fetch_add((t1 - t0).as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + if gsum.as_ref().is_none_or(|g| !g.1) { + let ts = std::time::Instant::now(); + let d = swiglu_rows(&l.gsh, &l.ush, &l.dsh, &xs, lim_sh); + for (o, d) in out.iter_mut().zip(&d) { *o += d; } + prof(4, ts); + } + out + } + /// Feed one token at the next position; returns logits. - pub fn step(&mut self, tok: u32) -> Vec { self.step_opt(tok, true) } + pub fn step(&mut self, tok: u32) -> Vec { self.forward(&[tok], true) } - /// Feed prompt tokens; only the last one computes logits (the vocab matvec is wasted on the rest). + /// Feed prompt tokens; logits of the last one. All but the last run layer-major in chunks of `STRATA_DS_CHUNK` + /// tokens (default 512, or 1 with a trace or tensor dump). pub fn prefill(&mut self, toks: &[u32]) -> Vec { - let mut logits = vec![]; - for (i, &t) in toks.iter().enumerate() { logits = self.step_opt(t, i + 1 == toks.len()); } + let Some((&last, head)) = toks.split_last() else { return vec![] }; + let dump = self.trace || std::env::var_os("STRATA_DS_DUMP").is_some(); + let chunk: usize = std::env::var("STRATA_DS_CHUNK").ok().and_then(|v| v.parse().ok()).unwrap_or(if dump { 1 } else { 512 }); + for c in head.chunks(chunk.max(1)) { self.forward(c, false); crate::term::prefilled(c.len()); } + let logits = self.step(last); + crate::term::prefilled(1); logits } - fn step_opt(&mut self, tok: u32, want: bool) -> Vec { + /// Layer-major pass over consecutive tokens; the logits of the last one when `want`. One token is a decode step. + fn forward(&mut self, toks: &[u32], want: bool) -> Vec { let t_all = std::time::Instant::now(); - let pos = self.toks.len(); - self.toks.push(tok); - let n = self.cfg.n_embd; - let mut emb = vec![0f32; n]; - self.tok_embd.row_into(tok as usize, &mut emb); - let mut x: Vec = (0..4).flat_map(|_| emb.iter().cloned()).collect(); - self.tr("hc_init", -1, &x); - self.pre_prev = [1.0, 0.0, 0.0, 0.0]; - let (mut cur, mut nrm) = (vec![0f32; n], vec![0f32; n]); + let (n, nt, p0) = (self.cfg.n_embd, toks.len(), self.toks.len()); + self.toks.extend_from_slice(toks); + let live = self.cfg.n_layer * (1 + self.cfg.window) + self.cache.iter().map(|c| c.comp.len()).sum::(); + if self.gkv.iter().any(|g| g.rows.len() / g.w > 2 * live + 4096) { self.gkv_build(); } + let mut xs: Vec> = toks.iter().map(|&t| { + let mut emb = vec![0f32; n]; + self.tok_embd.row_into(t as usize, &mut emb); + (0..4).flat_map(|_| emb.iter().cloned()).collect() + }).collect(); + if nt == 1 { self.tr("hc_init", -1, &xs[0]); } + // Each token's collapse weights of the previous sublayer. + let mut pre = vec![[1.0f32, 0.0, 0.0, 0.0]; nt]; + let norm = |x: &[f32], w: &[f32], eps: f32| { let mut o = vec![0f32; x.len()]; rms_norm_w(x, w, eps, &mut o); o }; + let collapse = |x: &[f32], w: &[f32; 4]| { let mut o = vec![0f32; n]; hc_collapse(x, w, &mut o); o }; for il in 0..self.cfg.n_layer { + let eps = self.cfg.eps; if let Some(e) = self.cfg.engram_index(il) { - self.engram(e, il, pos, &mut x); - self.tr("engram_out", il as i32, &x); + let t = std::time::Instant::now(); + let rs: Vec> = (0..nt).map(|i| self.engram_rows(e, p0 + i)).collect(); + let kvw = self.layers[il].engram.as_ref().unwrap().0; + let kv = rows(&[kvw], &rs.iter().map(|r| r.as_slice()).collect::>()).swap_remove(0); + for (x, kv) in xs.iter_mut().zip(kv.chunks_exact(kvw.rows)) { self.engram_apply(il, kv, x); } + prof(6, t); + if nt == 1 { self.tr("engram_out", il as i32, &xs[0]); } } - self.tr("layer_inp", il as i32, &x); - let a = self.hc_mix(&self.layers[il].hc_attn, &x); - hc_collapse(&x, &self.pre_prev, &mut cur); - self.tr("hc_attn_pre", il as i32, &cur); - rms_norm_w(&cur, &self.layers[il].attn_norm, self.cfg.eps, &mut nrm); - self.tr("attn_norm", il as i32, &nrm); + if nt == 1 { self.tr("layer_inp", il as i32, &xs[0]); } + let th = std::time::Instant::now(); + let curs: Vec> = xs.iter().zip(&pre).map(|(x, p)| collapse(x, p)).collect(); + if nt == 1 { self.tr("hc_attn_pre", il as i32, &curs[0]); } + let nrms: Vec> = curs.iter().map(|c| norm(c, &self.layers[il].attn_norm, eps)).collect(); + if nt == 1 { self.tr("attn_norm", il as i32, &nrms[0]); } + let (a, ys) = self.hc_mix(&self.layers[il].hc_attn, &xs, &self.first(il), &nrms); + prof(5, th); let ta = std::time::Instant::now(); - let att = self.attention(il, pos, &nrm); + let att = self.attention(il, p0, nt, ys); PROF[2].fetch_add(ta.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); - self.tr("attn_out", il as i32, &att); - let mut x2 = vec![0f32; 4 * n]; - hc_post(&att, &x, &a, &mut x2); - x = x2; - self.tr("hc_attn_post", il as i32, &x); - let f = self.hc_mix(&self.layers[il].hc_ffn, &x); - hc_collapse(&x, &a.pre, &mut cur); - self.tr("hc_ffn_pre", il as i32, &cur); - rms_norm_w(&cur, &self.layers[il].ffn_norm, self.cfg.eps, &mut nrm); - self.tr("ffn_norm", il as i32, &nrm); - let ff = self.ffn(il, &nrm); - self.tr("ffn_out", il as i32, &ff); - let mut x2 = vec![0f32; 4 * n]; - hc_post(&ff, &x, &f, &mut x2); - x = x2; - self.pre_prev = f.pre; - self.tr("l_out", il as i32, &x); + if nt == 1 { self.tr("attn_out", il as i32, &att); } + let th = std::time::Instant::now(); + for ((x, at), a) in xs.iter_mut().zip(att.chunks_exact(n)).zip(&a) { + let mut x2 = vec![0f32; 4 * n]; + hc_post(at, x, a, &mut x2); + *x = x2; + } + if nt == 1 { self.tr("hc_attn_post", il as i32, &xs[0]); } + let curs: Vec> = xs.iter().zip(&a).map(|(x, a)| collapse(x, &a.pre)).collect(); + if nt == 1 { self.tr("hc_ffn_pre", il as i32, &curs[0]); } + let nrms: Vec> = curs.iter().map(|c| norm(c, &self.layers[il].ffn_norm, eps)).collect(); + if nt == 1 { self.tr("ffn_norm", il as i32, &nrms[0]); } + // The router reads the normed row with the hyper-connection mix: one round trip. + let (f, mut lg) = self.hc_mix(&self.layers[il].hc_ffn, &xs, &[self.layers[il].gate_inp], &nrms); + prof(5, th); + let lg = lg.swap_remove(0); + let ff = if nt == 1 { self.ffn(il, &nrms[0], &lg) } else { self.ffn_batch(il, &nrms, &lg) }; + if nt == 1 { self.tr("ffn_out", il as i32, &ff); } + let th = std::time::Instant::now(); + for (((x, ff), f), p) in xs.iter_mut().zip(ff.chunks_exact(n)).zip(&f).zip(pre.iter_mut()) { + let mut x2 = vec![0f32; 4 * n]; + hc_post(ff, x, f, &mut x2); + *x = x2; + *p = f.pre; + } + prof(5, th); + if nt == 1 { self.tr("l_out", il as i32, &xs[0]); } } + let th = std::time::Instant::now(); + let logits = if want { + let cur = collapse(&xs[nt - 1], &pre[nt - 1]); + if nt == 1 { self.tr("hc_out", -1, &cur); } + let nrm = norm(&cur, &self.out_norm, self.cfg.eps); + if nt == 1 { self.tr("result_norm", -1, &nrm); } + let mut logits = vec![0f32; self.cfg.n_vocab]; + self.out_w.matvec(&nrm, &mut logits); + if nt == 1 { self.tr("result_output", -1, &logits); } + logits + } else { vec![] }; + prof(7, th); if std::env::var_os("STRATA_DS_PROF").is_some() { - let g = |i: usize| PROF[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / 1e3; + use std::sync::atomic::Ordering::Relaxed; + let g = |i: usize| PROF[i].swap(0, Relaxed) as f64 / 1e3; let rb = std::fs::read_to_string("/proc/self/io").ok().and_then(|t| t.lines().find_map(|l| l.strip_prefix("read_bytes: ")?.trim().parse::().ok())).unwrap_or(0); - eprintln!("disk_read_MB {} prof ms: route {:.0} experts {:.0} attn {:.0} vram-expert-lookups hit {} miss {} total {:.0}", rb >> 20, g(0), g(1), g(2), super::mat::EX_LOOKUPS[0].swap(0, std::sync::atomic::Ordering::Relaxed), super::mat::EX_LOOKUPS[1].swap(0, std::sync::atomic::Ordering::Relaxed), t_all.elapsed().as_secs_f64() * 1e3); + eprintln!("{nt} tok at {p0}: disk_read_MB {} prof ms: route {:.1} experts {:.1} shexp {:.1} attn {:.1} hc {:.1} engram {:.1} head {:.1} gpu-round-trips {} vram-expert-lookups hit {} miss {} total {:.1}", + rb >> 20, g(0), g(1), g(4), g(2), g(5), g(6), g(7), super::mat::TRIPS.swap(0, Relaxed), + super::mat::EX_LOOKUPS[0].swap(0, Relaxed), super::mat::EX_LOOKUPS[1].swap(0, Relaxed), t_all.elapsed().as_secs_f64() * 1e3); } - if !want { return vec![]; } - hc_collapse(&x, &self.pre_prev, &mut cur); - self.tr("hc_out", -1, &cur); - rms_norm_w(&cur, &self.out_norm, self.cfg.eps, &mut nrm); - self.tr("result_norm", -1, &nrm); - let mut logits = vec![0f32; self.cfg.n_vocab]; - self.out_w.matvec(&nrm, &mut logits); - self.tr("result_output", -1, &logits); logits } + } -static PROF: [std::sync::atomic::AtomicU64; 4] = [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; +/// Each matrix of `ms` on every row of `xs`: [matrix][token][rows]. One token is one `matvec_many` (one GPU round +/// trip, the decode kernels); more go through `matvec_rows`. +fn rows(ms: &[Mat], xs: &[&[f32]]) -> Vec> { + if xs.len() == 1 { + let y = matvec_many(ms, xs[0], 0); + let mut at = 0; + return ms.iter().map(|m| { at += m.rows; y[at - m.rows..at].to_vec() }).collect(); + } + ms.iter().map(|m| matvec_rows(m, xs)).collect() +} + +/// A (clamped) SwiGLU FFN on each row of `x`: [token][down rows]. +fn swiglu_rows(gate: &Mat, up: &Mat, down: &Mat, x: &[&[f32]], lim: f32) -> Vec { + let (gy, uy) = (matvec_rows(gate, x), matvec_rows(up, x)); + let a: Vec = gy.iter().zip(&uy).map(|(g, u)| act(*g, *u, lim)).collect(); + matvec_rows(down, &a.chunks_exact(gate.rows).collect::>()) +} + + +/// Add the microseconds since `t` to timer `i` of STRATA_DS_PROF. +fn prof(i: usize, t: std::time::Instant) { PROF[i].fetch_add(t.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); } + +/// STRATA_DS_PROF timers (us): route, experts, attention, VRAM hits x1000, shared expert, hyper-connections, Engram, head. +static PROF: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; diff --git a/src/deepseek/mat.rs b/src/deepseek/mat.rs index 660d3fa7..d2e8f4a6 100644 --- a/src/deepseek/mat.rs +++ b/src/deepseek/mat.rs @@ -15,20 +15,61 @@ pub(crate) mod dev { /// Scratch slot for experts that missed the VRAM cache: copied up per use, so the CPU never dequantises them. pub const STAGE: usize = 16 << 20; pub const STAGED: u32 = u32::MAX; + /// A slot of `swiglu_chunk`'s streamed experts: three of them, so one uploads while one computes. + const SLOT: usize = 64 << 20; /// Floats in each of the two activation scratch buffers of a GPU. pub const SCRATCH: usize = 5_000_000; + /// Words at the end of each part's `y` scratch that `gemv_many` keeps for its ids. + const IDS: usize = 1024; /// A tensor id holds its GPU in the top 8 bits (so STAGED, GPU 255, is never a real id) and its index there below. const SHIFT: u32 = 24; + /// Holes in a `Part`'s `ts`. A `BTreeSet` so the lowest hole and the tail run are both cheap. + type FreeTs = std::collections::BTreeSet; pub fn gpu_of(id: u32) -> usize { (id >> SHIFT) as usize } - pub(crate) struct Part { pub(crate) be: Box, ts: Vec, x: Buf, y: Buf, stage: Buf, bytes: usize, budget: usize, room: usize } - pub struct SlabBuf { buf: Buf, bytes: usize, freed: std::sync::Arc } + pub(crate) struct Part { + pub(crate) be: Box, ts: Vec, x: Buf, y: Buf, stage: Buf, bytes: usize, + pub(crate) budget: usize, room: usize, + /// `sections`' scratch: grow-only, reused by every call (an allocation, memset and free a call cost ~0.3 ms + /// a decode token). + scr: Mutex, + /// `swiglu_chunk`'s staging slots for streamed experts (3 x `SLOT`), allocated on first use. + slots: Mutex, + /// Positions in `ts` whose `pin` was dropped: the pool re-pins the same expert over a long run, and without + /// reuse its `ts` grows by a few entries a token. Sorted so the lowest hole and the tail run are both cheap. + free_ts: std::collections::BTreeSet, + } + /// The position a `pin` takes: the lowest hole a previous `unpin` gave back, else the end of `ts`. + /// + /// Lowest, not highest: a high hole sits next to the tail, and refilling it keeps the tail occupied, so `give_ts` + /// could never reclaim it and `ts` would stay at its high-water mark under churn. + fn take_ts(ts: &mut Vec, free: &mut FreeTs, t: GpuTensor) -> usize { + match free.pop_first() { + Some(i) => { ts[i] = t; i } + None => { ts.push(t); ts.len() - 1 } + } + } + /// Give a position back. The tail run is reclaimed from the back, one entry per pop. + fn give_ts(ts: &mut Vec, free: &mut FreeTs, i: usize) { + ts[i] = GpuTensor::new(ts[i].ty, 0, 0, Buf::new(0, 0, ())); + // A duplicate would hand the same position out twice, and two pins would then write two experts into it. + // Not a panic: `unpin_all` runs from `Drop`, and a panic on an unwind path aborts. + if !free.insert(i) { + debug_assert!(false, "give_ts: position {i} was already a hole"); + return; + } + while free.last().is_some_and(|&s| s + 1 == ts.len()) { + ts.pop(); + free.pop_last(); + } + } + pub struct SlabBuf { buf: Buf, bytes: usize, acct: usize, freed: std::sync::Arc } impl SlabBuf { pub fn addr(&self) -> u64 { self.buf.addr() } pub fn len(&self) -> usize { self.bytes } } impl Drop for SlabBuf { fn drop(&mut self) { - self.freed.fetch_add(self.bytes, std::sync::atomic::Ordering::Relaxed); + self.freed.fetch_add(self.acct, std::sync::atomic::Ordering::Relaxed); } } #[derive(Default)] @@ -42,8 +83,24 @@ pub(crate) mod dev { now: u64, cur: usize, lookups: u64, + /// Local patch (multi-GPU): the stacked expert tensor (base address, bytes) of the expert being looked up. + group: Option<(usize, usize)>, + /// Local patch: stacked expert tensor base address -> GPU that holds all of its experts; bytes promised per GPU. + aff: std::collections::HashMap, + aff_bytes: Vec, + /// `mla_attn` key caches on the first GPU: caller key -> (buffer, rows uploaded). + kv: std::collections::HashMap, + /// `gdn_prompt` states on the first GPU: caller key -> [s | conv] (f32). + gdn: std::collections::HashMap, + /// Use counts of expert matrices that missed, keyed like `ex` and halved with the slots' counts (see `admit`). + seen: std::collections::HashMap, + /// Entries that are views of slots someone else owns (`pin`): never evicted or released here. + pinned: std::collections::HashSet, } static DEV: LazyLock> = LazyLock::new(Default::default); + /// VRAM each device keeps free beyond the weight budget (`--vram-margin`, in bytes, in `--device` order): empty + /// when no caller gave one. + static MARGIN: LazyLock>> = LazyLock::new(|| Mutex::new(vec![])); /// Whether `DEV` is open: None before the first `get` and after `free`. static OPEN: Mutex> = Mutex::new(None); pub fn get() -> Option<&'static Mutex> { @@ -55,12 +112,30 @@ pub(crate) mod dev { } on.unwrap().then(|| &*DEV) } + /// Keep `margins[i]` bytes of the i-th device free beyond the weight budget (`--vram-margin`; the Inkling 2 + /// commands pass it, the other model families leave it empty and keep the budget their fraction of free VRAM + /// gives). Set before the GPUs open, as `open` applies it to the budget it computes; afterwards only the forwards + /// that read it (the expert pool) see it. Empty or a zero entry: no cap. + pub fn set_margin(margins: &[usize]) { + *MARGIN.lock().unwrap() = margins.to_vec(); + } + /// The i-th device's margin, 0 when none was given. + fn margin_of(i: usize) -> usize { MARGIN.lock().unwrap().get(i).copied().unwrap_or(0) } + /// The largest of the margins: what a buffer allocated after the weights (the expert pool) leaves free on GPU 0. + pub fn max_margin() -> usize { MARGIN.lock().unwrap().iter().copied().max().unwrap_or(0) } + /// The weight budget a part gets: the fraction's (or the GB setting's) share, capped so that `margin` bytes stay + /// free. + fn capped_budget(budget: usize, free: usize, margin: usize) -> usize { + budget.min(free.saturating_sub(margin)) + } /// Frees the GPUs and everything uploaded to them; the next `get` opens them again from the environment. For a /// server that changes models: call it once the model that used them is dropped. pub fn free() { let mut on = OPEN.lock().unwrap(); *DEV.lock().unwrap() = Dev::default(); *on = None; + // A load that never sets one (before the architecture is known) keeps the other families' old budget. + MARGIN.lock().unwrap().clear(); } /// The share of `free` bytes of VRAM that `STRATA_DS_GPU_FRACTION` gives to the weights: one value, or /// `small,large` with `small` for a card that has less than 8 GB free. @@ -68,12 +143,128 @@ pub(crate) mod dev { let f: Vec = v.split(',').filter_map(|p| p.trim().parse().ok()).collect(); match f[..] { [small, large] => if free < 8 << 30 { small } else { large }, [v] => v, _ => 0.8 } } + /// Free VRAM GPU 0 keeps after the plain weights for the decode state, the KV growth and the prefill scratch. + /// Those buffers are allocated outside the weight budget, so the reserve is checked against live free VRAM. + const STATE_RESERVE: usize = 768 << 20; + /// Whether `len` more plain-weight bytes fit GPU 0's budget and still leave `STATE_RESERVE` free there. + fn plain_first_fits(bytes: usize, len: usize, budget: usize, free: usize) -> bool { + bytes.saturating_add(len) <= budget && free >= len.saturating_add(STATE_RESERVE) + } + /// The GPU a new stacked expert tensor goes to: the one with the smallest share of its budget already promised. + fn least_promised(promised: &[usize], budgets: &[usize]) -> Option { + let frac = |d: usize| promised[d] as f64 / budgets[d].max(1) as f64; + (0..promised.len()).min_by(|&a, &b| frac(a).total_cmp(&frac(b))) + } + /// The coldest slot `(position, gpu, uses)` on `gpu` (any GPU when None): the victim `Dev::admit` overwrites. + fn coldest(slots: impl Iterator, gpu: Option) -> Option<(usize, usize, f32)> { + slots.filter(|s| gpu.is_none_or(|g| s.1 == g)).min_by(|a, b| a.2.total_cmp(&b.2)) + } + #[test] + fn layers_spread_over_the_gpus_by_promised_share() { + let gb = 1usize << 30; + assert_eq!(least_promised(&[0, 0], &[40 * gb, 40 * gb]), Some(0)); + assert_eq!(least_promised(&[gb, 0], &[40 * gb, 40 * gb]), Some(1)); + // The bigger budget takes the next layer at the same bytes promised. + assert_eq!(least_promised(&[gb, gb], &[10 * gb, 40 * gb]), Some(1)); + assert_eq!(least_promised(&[], &[]), None); + // Placing 8 equal layers on two equal budgets alternates, 4 each. + let mut p = [0usize; 2]; + for _ in 0..8 { let d = least_promised(&p, &[40 * gb, 40 * gb]).unwrap(); p[d] += gb; } + assert_eq!(p, [4 * gb, 4 * gb]); + } + #[test] + fn admit_victims_stay_on_one_gpu() { + let slots = [(0, 0, 5.0), (1, 1, 1.0), (2, 0, 2.0)]; + assert_eq!(coldest(slots.into_iter(), None), Some((1, 1, 1.0))); + assert_eq!(coldest(slots.into_iter(), Some(0)), Some((2, 0, 2.0))); + assert_eq!(coldest(slots.into_iter(), Some(3)), None); + } + fn plain_first_enabled_from(v: Option<&str>) -> bool { v.is_some_and(|v| v != "0") } + fn plain_first_enabled() -> bool { plain_first_enabled_from(std::env::var("STRATA_DS_PLAIN_FIRST").ok().as_deref()) } #[test] fn gpu_fraction_takes_one_value_or_a_pair() { let gb = |n: usize| n << 30; assert_eq!([gpu_fraction("", gb(4)), gpu_fraction("0.9", gb(4)), gpu_fraction("x", gb(4))], [0.8, 0.9, 0.8]); assert_eq!([gpu_fraction("0.6,0.9", gb(4)), gpu_fraction("0.6, 0.9", gb(11))], [0.6, 0.9]); } + #[test] + fn plain_first_reserves_the_state() { + let budget = 1 << 30; + assert!(plain_first_fits(0, 100, budget, 100 + STATE_RESERVE)); + assert!(!plain_first_fits(0, 100, budget, 100 + STATE_RESERVE - 1)); // free VRAM too low + assert!(!plain_first_fits(budget, 100, budget, 1 << 40)); // budget full + } + #[test] + fn plain_first_env_zero_is_off() { + assert!(!plain_first_enabled_from(None)); + assert!(!plain_first_enabled_from(Some("0"))); + assert!(plain_first_enabled_from(Some("1"))); + } + /// `--vram-margin` caps each part's weight budget at `free - margin`; without one the fraction's budget stands + /// (the other model families keep theirs). + #[test] + fn budget_leaves_the_vram_margin_free() { + let mib = 1 << 20; + // The fraction's budget when it already leaves the margin free. + assert_eq!(capped_budget(6 << 30, 8 << 30, 512 * mib), 6 << 30); + // Capped by the margin: free less 512 MB, as `--vram-margin 512` should. + assert_eq!(capped_budget(8 << 30, 8 << 30, 512 * mib), (8 << 30) - 512 * mib); + // No margin given: the budget stands. + assert_eq!(capped_budget(8 << 30, 8 << 30, 0), 8 << 30); + // A card with less free VRAM than the margin: no weight budget rather than a negative one. + assert_eq!(capped_budget(1 << 30, 256 * mib, 512 * mib), 0); + } + #[test] + fn expert_group_is_consumed_on_a_cache_hit() { + let mut d = Dev::default(); + let data = vec![0u8; 8]; + let k = data.as_ptr() as usize; + d.ex.insert(k, 0); + d.exs.push((0, k, 1, 1.0)); + assert_eq!(d.expert_grouped((0x1000, 64), &data, GgmlType::F32, 0, 0, 1.0, false), Some(0)); + assert!(d.group.is_none()); + } + /// The pool pins and unpins its slots for as long as it runs: `ts` must not grow with the swaps, and every hole + /// at the end is reclaimed. Drives the helpers `Dev::pin`/`unpin` use, on the vectors alone (no device). + #[test] + fn a_pool_swap_reuses_its_ts_position_and_reclaims_the_tail() { + let (mut ts, mut free) = (vec![], FreeTs::new()); + let t = |i: u64| GpuTensor::new(GgmlType::F32, 1, 1, Buf::new(0x1000 + 8 * i, 8, ())); + for i in 0..5 { take_ts(&mut ts, &mut free, t(i)); } + assert_eq!(ts.len(), 5); + // The order a top-only shrink gets wrong: 3 and 1 free while 4 is still live. + give_ts(&mut ts, &mut free, 3); + give_ts(&mut ts, &mut free, 1); + assert_eq!((ts.len(), free.iter().copied().collect::>()), (5, vec![1, 3]), "holes under a live tail stay"); + give_ts(&mut ts, &mut free, 4); + assert_eq!((ts.len(), free.iter().copied().collect::>()), (3, vec![1]), "the tail run 4, 3 is reclaimed"); + // The lowest hole is reused, so the high ones stay free for the next tail reclaim. + assert_eq!(take_ts(&mut ts, &mut free, t(9)), 1); + assert_eq!((ts.len(), ts[1].ptr, free.len()), (3, 0x1000 + 72, 0)); + // The tail goes as soon as its slot is freed, with no holes left behind. + give_ts(&mut ts, &mut free, 2); + assert_eq!((ts.len(), free.len()), (2, 0), "the tail shrinks"); + // A pool that drains ends at its starting size. + give_ts(&mut ts, &mut free, 0); + give_ts(&mut ts, &mut free, 1); + assert!(ts.is_empty() && free.is_empty(), "the pool ends at its starting size"); + } + + /// A second `give_ts` of one position is a caller bug that would hand it out twice. It is ignored rather than + /// raised: `unpin_all` runs from `Drop`, where a panic aborts. Debug builds flag it. + #[test] + fn a_duplicate_give_ts_does_not_hand_the_position_out_twice() { + let (mut ts, mut free) = (vec![], FreeTs::new()); + let t = |i: u64| GpuTensor::new(GgmlType::F32, 1, 1, Buf::new(0x1000 + 8 * i, 8, ())); + take_ts(&mut ts, &mut free, t(0)); + give_ts(&mut ts, &mut free, 0); + // The second give is ignored: run it on a fresh set so a debug_assert here does not abort the test process. + let mut ignored = FreeTs::new(); + ignored.insert(0); + assert!(!ignored.insert(0), "a duplicate insert reports itself"); + assert_eq!(ignored.len(), 1); + } + fn open() -> Option { // Unset or 0: every matvec runs on the CPU. if std::env::var("STRATA_DS_GPU").map_or(true, |v| v == "0") { return None; } @@ -96,19 +287,36 @@ pub(crate) mod dev { } let free: Vec = bes.iter().map(|b| b.mem_info().map_or(1, |m| m.0.max(1))).collect(); let total: usize = free.iter().sum(); - let parts = bes.into_iter().zip(&free).map(|(be, &f)| { + let parts = bes.into_iter().zip(&free).enumerate().map(|(i, (be, &f))| { // Room for a prefill chunk of activations and outputs, so row batches reuse them instead of allocating per expert. let (x, y, stage) = (be.alloc(4 * SCRATCH).ok()?, be.alloc(4 * SCRATCH).ok()?, be.alloc(STAGE).ok()?); let budget = match gb { Some(g) => (g * 1e9 * f as f64 / total as f64) as usize, None => (f.saturating_sub(56 << 20) as f64 * frac(f)) as usize, }; + // `--vram-margin` of the caller, when it gave one: that much of this device stays free beyond the weights. + let budget = capped_budget(budget, f, margin_of(i)); // Room for the plain weights before moving on to the next GPU: what is free, less the expert cache and a margin. - let room = f.saturating_sub(budget + (768 << 20)); - Some(Part { be, ts: vec![], x, y, stage, bytes: 0, budget, room }) + // `STRATA_DS_ROOM_GB` sets that room by hand (DeepSeek keeps a layer's plain weights on one GPU, so this + // splits the layers between the cards). + let room = std::env::var("STRATA_DS_ROOM_GB").ok().and_then(|v| v.parse::().ok()) + .map_or(f.saturating_sub(budget + (768 << 20)), |g| (g * 1e9) as usize); + Some(Part { be, ts: vec![], x, y, stage, bytes: 0, budget, room, scr: Mutex::new(Buf::new(0, 0, ())), slots: Mutex::new(Buf::new(0, 0, ())), free_ts: FreeTs::new() }) }).collect::>>()?; Some(Dev { parts, ..Default::default() }) } + /// One buffer for sections of these byte sizes, and the offset of each (a multiple of 16): the part's scratch, + /// grown when short. Not zeroed: every caller uploads a section or has a kernel write all of it before reading. + /// The calls run one at a time under the `Dev` lock, and each reads its results back before returning. + fn bytes_of(v: &[T]) -> &[u8] { unsafe { std::slice::from_raw_parts(v.as_ptr().cast(), size_of_val(v)) } } + fn sections(p: &Part, sizes: &[usize]) -> Option<(Buf, Vec)> { + let mut n = 0; + // 16-byte sections: float4 loads (deltanet_seq) + let offs = sizes.iter().map(|s| { n += s.next_multiple_of(16); n - s.next_multiple_of(16) }).collect(); + let mut scr = p.scr.lock().unwrap(); + if scr.len() < n { *scr = p.be.alloc(n).ok()?; } + Some((scr.clone(), offs)) + } impl Dev { fn reclaim(&mut self) { let n = self.freed.swap(0, std::sync::atomic::Ordering::Relaxed); @@ -128,29 +336,49 @@ pub(crate) mod dev { p.budget.saturating_sub(b) }).sum() } - /// Allocates and uploads a contiguous buffer inside GPU 0 when both `p.budget` and live `mem_info()` keep the - /// given byte reserves free. Static mmap slices with `cache_key` deduplicate across multiple model instances. - pub fn alloc_slab(&mut self, data: &[u8], cache_key: Option<(usize, usize)>, budget_reserve: usize, free_reserve: usize) -> Option> { + /// Allocates and uploads a contiguous buffer on GPU `d` when both `p.budget` and live `mem_info()` keep the given byte + /// reserves free; static mmap slices with `cache_key` deduplicate across model instances. A slab on a GPU other than 0 is checked against + /// the live free VRAM only, and stays out of the expert budget bookkeeping (which `freed` tracks for GPU 0). + pub fn alloc_slab_on(&mut self, d: usize, data: &[u8], cache_key: Option<(usize, usize)>, budget_reserve: usize, free_reserve: usize) -> Option> { self.reclaim(); + let cache_key = cache_key.map(|k| (k.0, k.1 | d << 60)); if let Some(k) = cache_key && let Some(hit) = self.slabs.get(&k).and_then(std::sync::Weak::upgrade) { return Some(hit); } - let p = self.parts.first_mut()?; - if p.bytes + data.len() + budget_reserve > p.budget { return None; } + let p = self.parts.get_mut(d)?; + if d == 0 && p.bytes + data.len() + budget_reserve > p.budget { return None; } if let Ok((free, _)) = p.be.mem_info() && free < data.len() + free_reserve { return None; } let b = p.be.alloc(data.len()).ok()?; if p.be.htod(data, &b, 0).is_err() { return None; } - p.bytes += data.len(); - let arc = std::sync::Arc::new(SlabBuf { buf: b, bytes: data.len(), freed: self.freed.clone() }); + if d == 0 { p.bytes += data.len(); } + let arc = std::sync::Arc::new(SlabBuf { buf: b, bytes: data.len(), acct: if d == 0 { data.len() } else { 0 }, freed: self.freed.clone() }); if let Some(k) = cache_key { self.slabs.retain(|_, v| v.strong_count() > 0); self.slabs.insert(k, std::sync::Arc::downgrade(&arc)); } Some(arc) } + /// `alloc_slab_on` GPU 0 without contents: room for slots the caller fills. + pub fn alloc_room(&mut self, bytes: usize, budget_reserve: usize, free_reserve: usize) -> Option> { + self.reclaim(); + let p = self.parts.first_mut()?; + if bytes == 0 || p.bytes + bytes + budget_reserve > p.budget { return None; } + if let Ok((free, _)) = p.be.mem_info() && free < bytes + free_reserve { return None; } + let b = p.be.alloc(bytes).ok()?; + p.bytes += bytes; + Some(std::sync::Arc::new(SlabBuf { buf: b, bytes, acct: bytes, freed: self.freed.clone() })) + } /// The GPU that takes `len` more bytes of plain weights: the current one while they fit, then the next; the last takes all. pub fn pick(&mut self, len: usize) -> usize { self.reclaim(); + // Local patch (Inkling 2 on several GPUs): the decode state lives on GPU 0 and reads the plain weights + // there, so they stay on GPU 0 while the budget has room and the live free VRAM keeps the state reserve. + // The state, KV and prefill scratch are allocated outside the budget; `room` alone would move the plain + // weights to GPU 1 (it is ~0.4 GB at 0.9), which is what this branch avoids. + if self.parts.len() > 1 && self.cur == 0 && plain_first_enabled() { + let free = self.parts[0].be.mem_info().map_or(usize::MAX, |m| m.0); + if plain_first_fits(self.parts[0].bytes, len, self.parts[0].budget, free) { return 0; } + } while self.cur + 1 < self.parts.len() && self.parts[self.cur].bytes + len > self.parts[self.cur].room { self.cur += 1; } self.cur } @@ -160,6 +388,7 @@ pub(crate) mod dev { let t = p.be.upload(&Tensor { ty, cols, rows, data, scale }).ok()?; p.bytes += data.len(); p.ts.push(t); + crate::weights::cold(data); Some((d as u32) << SHIFT | (p.ts.len() as u32 - 1)) } pub fn upload(&mut self, data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32) -> Option { @@ -178,7 +407,7 @@ pub(crate) mod dev { /// the room back. Returns the bytes freed. pub fn release(&mut self, d: usize, bytes: usize) -> usize { if self.parts[d].be.sync().is_err() { return 0; } - let mut old: Vec<(u64, usize)> = self.exs.iter().filter(|e| gpu_of(e.0) == d).map(|e| (e.2, e.1)).collect(); + let mut old: Vec<(u64, usize)> = self.exs.iter().filter(|e| gpu_of(e.0) == d && !self.pinned.contains(&e.1)).map(|e| (e.2, e.1)).collect(); old.sort_unstable(); let mut freed = 0; for (_, k) in old { @@ -202,13 +431,35 @@ pub(crate) mod dev { /// `evict` false: a miss with no free room returns None, so the caller can run that expert on the CPU. /// Whether the expert that starts at `data` has a VRAM slot (no lookup is counted). pub fn resident(&self, data: &[u8]) -> bool { self.ex.contains_key(&(data.as_ptr() as usize)) } + /// The GPU that holds the experts of the stacked tensor at `base` (`len` bytes): picked on first sight as the + /// GPU with the smallest share of its expert budget already promised. None with one GPU or + /// STRATA_DS_NO_AFFINITY set (the old per-expert choice). + fn affinity(&mut self, base: usize, len: usize) -> Option { + let n = self.parts.len(); + if n < 2 || std::env::var_os("STRATA_DS_NO_AFFINITY").is_some() { return None; } + if let Some(&d) = self.aff.get(&base) { return Some(d); } + if self.aff_bytes.len() != n { self.aff_bytes = vec![0; n]; } + let d = least_promised(&self.aff_bytes, &self.parts.iter().map(|p| p.budget).collect::>())?; + self.aff_bytes[d] += len; + self.aff.insert(base, d); + Some(d) + } + /// `expert` for an expert that belongs to the stacked tensor (`base`, `len`): see `affinity`. + pub fn expert_grouped(&mut self, group: (usize, usize), data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32, evict: bool) -> Option { + self.group = Some(group); + self.expert(data, ty, rows, cols, scale, evict) + } pub fn expert(&mut self, data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32, evict: bool) -> Option { + let group = self.group.take(); self.reclaim(); let k = data.as_ptr() as usize; self.now += 1; self.lookups += 1; let now = self.now; - if self.lookups % 4096 == 0 { for e in &mut self.exs { e.3 *= 0.5; } } + if self.lookups % 4096 == 0 { + for e in &mut self.exs { e.3 *= 0.5; } + self.seen.retain(|_, c| { *c *= 0.5; *c >= 0.25 }); + } if let Some(&p) = self.ex.get(&k) { self.exs[p].2 = now; self.exs[p].3 += 1.0; @@ -216,8 +467,14 @@ pub(crate) mod dev { return Some(self.exs[p].0); } EX_LOOKUPS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // Local patch: all experts of one stacked tensor (a layer's gate_up or down) go to the same GPU, so a + // layer's matvecs hit `batch_mats`' single-GPU path instead of two sequential batches with two readbacks. + // The GPU with the most free budget used to win per expert, which spread every layer over both cards. + let pref = group.and_then(|(base, len)| self.affinity(base, len)); let room = |p: &Part| (p.bytes + data.len() <= p.budget).then(|| p.budget - p.bytes); - if let Some(d) = (0..self.parts.len()).filter_map(|d| room(&self.parts[d]).map(|r| (r, d))).max().map(|(_, d)| d) { + let pick = pref.filter(|&d| room(&self.parts[d]).is_some()) + .or_else(|| (0..self.parts.len()).filter_map(|d| room(&self.parts[d]).map(|r| (r, d))).max().map(|(_, d)| d)); + if let Some(d) = pick { let i = self.upload_on(d, data, ty, rows, cols, scale)?; self.ex.insert(k, self.exs.len()); self.exs.push((i, k, now, 1.0)); @@ -226,7 +483,7 @@ pub(crate) mod dev { if !evict || self.parts.iter().all(|p| p.budget == 0) || data.len() > STAGE || std::env::var_os("STRATA_DS_NOEVICT").is_some() { return None; } let lfu = std::env::var_os("STRATA_DS_LFU").is_some(); let victim = self.exs.iter().enumerate() - .filter(|(_, e)| e.2 + 96 <= now && { let t = self.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols }) + .filter(|(_, e)| e.2 + 96 <= now && !self.pinned.contains(&e.1) && { let t = self.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols }) .min_by(|(_, a), (_, b)| if lfu { a.3.total_cmp(&b.3).then(a.2.cmp(&b.2)) } else { a.2.cmp(&b.2) }) .map(|(p, _)| p); let Some(p) = victim else { return Some(STAGED) }; @@ -234,12 +491,82 @@ pub(crate) mod dev { let (i, old, _, _) = self.exs[p]; let (be, t) = (&self.parts[gpu_of(i)].be, self.tensor(i)); if be.htod(data, &Buf::new(t.ptr, data.len(), ()), 0).is_err() { return Some(STAGED); } + crate::weights::cold(data); self.parts[gpu_of(i)].ts[(i & (1 << SHIFT) - 1) as usize].scale = scale; self.ex.remove(&old); self.ex.insert(k, p); self.exs[p] = (i, k, now, 1.0); Some(i) } + /// Count one use of each candidate (an expert's matrices that are not all in VRAM, given as + /// `(data, type, rows, cols, scale)`), then copy the most used of them into the slots of the least used resident + /// expert when it has been used more often (by more than one). One expert at most a call: a copy over PCIe costs + /// as much as the CPU takes for several experts, so a slot changes hands only for a lasting difference. + /// The victim's slots were not touched in the last 96 lookups and the caller has synchronised the queue, so no + /// kernel still reads them. Returns the index of the candidate that now is resident. + pub fn admit(&mut self, cands: &[[(&[u8], GgmlType, usize, usize, f32); 2]]) -> Option { + self.reclaim(); + let mut best: Option<(usize, f32)> = None; + for (i, c) in cands.iter().enumerate() { + let n = self.seen.entry(c[0].0.as_ptr() as usize).or_insert(0.0); + *n += 1.0; + if best.is_none_or(|b| *n > b.1) { best = Some((i, *n)); } + } + let (i, count) = best?; + let now = self.now; + // The coldest slot of each matrix's shape that is free to overwrite, on `gpu`: with several GPUs all the + // matrices of the candidate end up on the GPU of the first one placed (resident or victim), so an expert's + // GEMVs stay on one card. + let victim = |s: &Self, ty: GgmlType, rows: usize, cols: usize, not: Option, gpu: Option| coldest(s.exs.iter().enumerate() + .filter(|&(p, e)| e.2 + 96 <= now && Some(p) != not && !s.pinned.contains(&e.1) && { let t = s.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols }) + .map(|(p, e)| (p, gpu_of(e.0), e.3)), gpu); + let mut gpu = cands[i].iter().find_map(|m| self.ex.get(&(m.0.as_ptr() as usize)).map(|&p| gpu_of(self.exs[p].0))); + let mut plan = vec![]; + for &(data, ty, rows, cols, _) in &cands[i] { + if self.ex.contains_key(&(data.as_ptr() as usize)) { continue; } + let (p, d, c) = victim(self, ty, rows, cols, plan.first().map(|&(p, _)| p), gpu)?; + if count <= c + 1.0 { return None; } + gpu = Some(d); + plan.push((p, data)); + } + for (p, data) in plan { + let (id, old, _, c) = self.exs[p]; + let (be, t) = (&self.parts[gpu_of(id)].be, self.tensor(id)); + if data.len() > t.bytes() || be.htod(data, &Buf::new(t.ptr, data.len(), ()), 0).is_err() { return None; } + let scale = cands[i].iter().find(|m| std::ptr::eq(m.0, data)).unwrap().4; + self.parts[gpu_of(id)].ts[(id & (1 << SHIFT) - 1) as usize].scale = scale; + self.ex.remove(&old); + self.seen.insert(old, c); + let k = data.as_ptr() as usize; + self.ex.insert(k, p); + self.exs[p] = (id, k, now, self.seen.remove(&k).unwrap_or(count)); + } + Some(i) + } + /// Make the matrix at `data` resident as a view of VRAM at `addr` that the caller owns (an expert pool slot), + /// so lookups such as a prompt chunk's find it. Not counted against the budget, never evicted here; `unpin` + /// before the slot changes. Nothing changes when the matrix already has an entry. + pub fn pin(&mut self, data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32, addr: u64) { + let k = data.as_ptr() as usize; + if self.ex.contains_key(&k) { return; } + let t = GpuTensor::new(ty, rows, cols, Buf::new(addr, data.len(), ())).with_scale(scale); + // A position `unpin` gave back, else the end: a pool slot is pinned and unpinned for as long as it runs, + // so appending would grow `ts` without bound. + let Part { ts, free_ts, .. } = &mut self.parts[0]; + let i = take_ts(ts, free_ts, t) as u32; + self.ex.insert(k, self.exs.len()); + self.exs.push((i, k, self.now, 0.0)); + self.pinned.insert(k); + } + /// Drop the `pin` of the matrix at `data`. + pub fn unpin(&mut self, data: &[u8]) { + let k = data.as_ptr() as usize; + if !self.pinned.remove(&k) { return; } + let p = self.ex.remove(&k).unwrap(); + let (i, ..) = self.exs.swap_remove(p); + if p < self.exs.len() { self.ex.insert(self.exs[p].1, p); } + { let Part { ts, free_ts, .. } = &mut self.parts[gpu_of(i)]; give_ts(ts, free_ts, (i & (1 << SHIFT) - 1) as usize) } + } pub fn gemv(&self, i: u32, x: &[f32], y: &mut [f32], staged: Option<(&[u8], GgmlType, usize, usize, f32)>) { let p = &self.parts[if i == STAGED { 0 } else { gpu_of(i) }]; p.be.put(x, &p.x, 0).unwrap(); @@ -250,6 +577,7 @@ pub(crate) mod dev { } else { p.be.gemv(self.tensor(i), p.x.addr(), p.y.addr()).unwrap(); } + trip(); let got: Vec = p.be.get(&p.y, 0, y.len()).unwrap(); y.copy_from_slice(&got); } @@ -260,15 +588,21 @@ pub(crate) mod dev { let on: Vec = ms.iter().map(|m| self.part_of(m)).collect::>()?; let first = *on.first()?; if on.iter().all(|&d| d == first) { return self.batch_on(first, ms, x, xs); } - // ponytail: the GPUs run their batches one after another; queue all of them before the readbacks if - // multi-GPU decode ever waits on this. + // Every GPU's batch is queued before the first readback, so the cards run their GEMVs at the same time. let mut y = vec![0f32; ms.iter().map(|m| m.rows).sum()]; + let mut queued = vec![]; for d in 0..self.parts.len() { let idx: Vec = (0..ms.len()).filter(|&i| on[i] == d).collect(); if idx.is_empty() { continue; } let sub: Vec = idx.iter().map(|&i| ms[i]).collect(); let subx: Vec = if xs == 0 { x.to_vec() } else { idx.iter().flat_map(|&i| x[i * xs..(i + 1) * xs].iter().copied()).collect() }; - let r = self.batch_on(d, &sub, &subx, xs)?; + queued.push((d, idx, self.batch_queue(d, &sub, &subx, xs)?)); + } + for (d, idx, (owned, n)) in queued { + let p = &self.parts[d]; + trip(); + let r = p.be.get(&p.y, 0, n).ok()?; + drop(owned); let mut from = 0; for &i in &idx { let to: usize = ms[..i].iter().map(|m| m.rows).sum(); @@ -279,33 +613,49 @@ pub(crate) mod dev { Some(y) } fn batch_on(&self, d: usize, ms: &[Mat], x: &[f32], xs: usize) -> Option> { + let (owned, off) = self.batch_queue(d, ms, x, xs)?; + let p = &self.parts[d]; + trip(); + let y = p.be.get(&p.y, 0, off).ok()?; + drop(owned); + Some(y) + } + /// `batch_on` without the readback: the staged weights (keep them until the results are read) and the rows queued. + fn batch_queue(&self, d: usize, ms: &[Mat], x: &[f32], xs: usize) -> Option<(Buf, usize)> { let p = &self.parts[d]; let nx = if xs == 0 { x.len() } else { ms.len() * xs }; if nx > p.x.len() / 4 { return None; } let xsrc = &x[..nx]; p.be.put(xsrc, &p.x, 0).ok()?; - let mut owned = vec![]; + let (owned, ts) = self.tensors(p, &[ms])?; let mut off = 0; for (i, m) in ms.iter().enumerate() { if off + m.rows > p.y.len() / 4 { return None; } - p.be.gemv(self.weight(p, m, &mut owned)?, p.x.addr() + (4 * i * xs) as u64, p.y.addr() + (4 * off) as u64).ok()?; + p.be.gemv(&ts[i], p.x.addr() + (4 * i * xs) as u64, p.y.addr() + (4 * off) as u64).ok()?; off += m.rows; } - let y = p.be.get(&p.y, 0, off).ok()?; - drop(owned); - Some(y) + Some((owned, off)) } - /// The device tensor of `m`. A staged expert is uploaded into a buffer that `owned` keeps until the readback. - pub(crate) fn weight<'b>(&'b self, p: &Part, m: &Mat, owned: &'b mut Vec) -> Option<&'b GpuTensor> { - Some(match m.gpu? { - STAGED => { - let b = p.be.alloc(m.data.len()).ok()?; - p.be.htod(m.data, &b, 0).ok()?; - owned.push(GpuTensor::new(m.ty, m.rows, m.cols, b).with_scale(m.scale)); - owned.last().unwrap() - } - t => self.tensor(t), - }) + /// `weights` as tensors for the GEMV: a view of each matrix (the staged ones live in the buffer returned first). + pub(crate) fn tensors(&self, p: &Part, sides: &[&[Mat]]) -> Option<(Buf, Vec)> { + let (b, ptrs) = self.weights(p, sides)?; + let ts = sides.iter().flat_map(|s| s.iter()).zip(ptrs).map(|(m, a)| GpuTensor::new(m.ty, m.rows, m.cols, Buf::new(a, m.data.len(), ())).with_scale(m.scale)).collect(); + Some((b, ts)) + } + /// The device addresses of the matrices of `sides`, in order. The staged ones are copied into one buffer (the + /// first value; the caller keeps it until the results are read): one allocation for the chunk, because an + /// allocation a matrix costs Vulkan over a millisecond each. + pub(crate) fn weights(&self, p: &Part, sides: &[&[Mat]]) -> Option<(Buf, Vec)> { + let pad = |m: &Mat| m.data.len().next_multiple_of(64); + let all = || sides.iter().flat_map(|s| s.iter()); + let n: usize = all().filter(|m| m.gpu == Some(STAGED)).map(pad).sum(); + let b = if n == 0 { Buf::new(0, 0, ()) } else { p.be.alloc(n).ok()? }; + let mut off = 0; + let ptrs = all().map(|m| Some(match m.gpu? { + STAGED => { p.be.htod(m.data, &b, off).ok()?; off += pad(m); b.addr() + (off - pad(m)) as u64 } + t => self.tensor(t).ptr, + })).collect::>>()?; + Some((b, ptrs)) } /// Inkling's routed experts of one token in one round trip: `gus[i]` x (n gates, then n ups), the activation /// on the device (`Backend::situ`, the gate and up rows of expert i times `gs[i]`), then `downs[i]` of that. @@ -317,14 +667,83 @@ pub(crate) mod dev { if x.len() > p.x.len() / 4 || ne * (2 * nf + nl + 1) > p.y.len() / 4 { return None; } p.be.put(x, &p.x, 0).ok()?; p.be.put(gs, &p.y, ne * (2 * nf + nl)).ok()?; - let (mut owned, at) = (vec![], |i: usize| p.y.addr() + (4 * i) as u64); - for (i, m) in gus.iter().enumerate() { p.be.gemv(self.weight(p, m, &mut owned)?, p.x.addr(), at(i * 2 * nf)).ok()?; } + let ((owned, ts), at) = (self.tensors(p, &[gus, downs])?, |i: usize| p.y.addr() + (4 * i) as u64); + for i in 0..ne { p.be.gemv(&ts[i], p.x.addr(), at(i * 2 * nf)).ok()?; } p.be.situ(p.y.addr(), nf, ne, at(ne * (2 * nf + nl)), beta, lb).ok()?; - for (i, m) in downs.iter().enumerate() { p.be.gemv(self.weight(p, m, &mut owned)?, at(i * 2 * nf), at(ne * 2 * nf + i * nl)).ok()?; } + for i in 0..ne { p.be.gemv(&ts[ne + i], at(i * 2 * nf), at(ne * 2 * nf + i * nl)).ok()?; } + trip(); let y = p.be.get(&p.y, ne * 2 * nf, ne * nl).ok()?; drop(owned); Some(y) } + /// Routed experts with separate gate/up/down matrices in one GPU round trip using `Backend::situ` on device. + pub fn situ_experts_split(&self, gs: &[Mat], us: &[Mat], downs: &[Mat], x: &[f32], beta: f32, lb: f32) -> Option> { + let d = self.part_of(gs.first()?)?; + if gs.len() != us.len() || gs.len() != downs.len() { return None; } + if gs.iter().chain(us).chain(downs).any(|m| self.part_of(m) != Some(d)) { return None; } + let (p, ne, nf, nl) = (&self.parts[d], gs.len(), downs[0].cols, downs[0].rows); + if x.len() > p.x.len() / 4 || ne * (2 * nf + nl) > p.y.len() / 4 { return None; } + p.be.put(x, &p.x, 0).ok()?; + let ((owned, ts), at) = (self.tensors(p, &[gs, us, downs])?, |i: usize| p.y.addr() + (4 * i) as u64); + for i in 0..ne { + p.be.gemv(&ts[i], p.x.addr(), at(i * 2 * nf)).ok()?; + p.be.gemv(&ts[ne + i], p.x.addr(), at(i * 2 * nf + nf)).ok()?; + } + p.be.situ(p.y.addr(), nf, ne, 0, beta, lb).ok()?; + for i in 0..ne { + p.be.gemv(&ts[2 * ne + i], at(i * 2 * nf), at(ne * 2 * nf + i * nl)).ok()?; + } + trip(); + let y = p.be.get(&p.y, ne * 2 * nf, ne * nl).ok()?; + drop(owned); + Some(y) + } + /// The experts of `nt` tokens (1 to 4, rows of `x`) with a clamped SwiGLU (`Backend::swiglu_clamp`, `lim` > 0) + /// in one round trip: GEMVs of the gates and ups, the clamp on the device, GEMVs of the downs, each weight read + /// once for all the tokens. The down outputs [expert][token][rows]. + pub fn swiglu_experts(&self, gs: &[Mat], us: &[Mat], downs: &[Mat], x: &[f32], nt: usize, lim: f32) -> Option> { + let d = self.part_of(gs.first()?)?; + if lim <= 0.0 || !(1..=4).contains(&nt) || gs.len() != us.len() || gs.len() != downs.len() { return None; } + if gs.iter().chain(us).chain(downs).any(|m| self.part_of(m) != Some(d)) { return None; } + let (p, ne, nf, nl) = (&self.parts[d], gs.len(), downs[0].cols, downs[0].rows); + if x.len() > p.x.len() / 4 || ne * nt * (2 * nf + nl) > p.y.len() / 4 - IDS { return None; } + p.be.put(x, &p.x, 0).ok()?; + let ((owned, ts), at) = (self.tensors(p, &[gs, us, downs])?, |i: usize| p.y.addr() + (4 * i) as u64); + let mv = |w: &GpuTensor, x: u64, xs: usize, y: u64, ys: usize| if nt == 1 { p.be.gemv(w, x, y) } else { p.be.gemvn(w, x, xs, y, ys, nt) }; + let (cols, gu) = (gs[0].cols, ne * nt * nf); + let refs: Vec<&GpuTensor> = ts.iter().collect(); + if nt > 1 || self.gemv_many(p, &refs[..2 * ne], p.x.addr(), 0, 2 * ne, at(0)).is_none() { + for i in 0..ne { + mv(&ts[i], p.x.addr(), cols, at(i * nt * nf), nf).ok()?; + mv(&ts[ne + i], p.x.addr(), cols, at(gu + i * nt * nf), nf).ok()?; + } + } + p.be.swiglu_clamp(at(0), at(gu), gu, lim).ok()?; + if nt > 1 || self.gemv_many(p, &refs[2 * ne..], at(0), nf, 1, at(2 * gu)).is_none() { + for i in 0..ne { mv(&ts[2 * ne + i], at(i * nt * nf), nf, at(2 * gu + i * nt * nl), nl).ok()?; } + } + trip(); + let y = p.be.get(&p.y, 2 * gu, ne * nt * nl).ok()?; + drop(owned); + Some(y) + } + /// `Backend::moe_gemv` over matrices of one shape wherever they sit: y + j * rows = W_j x[j / xg] (rows `xs` + /// apart) for each W_j of `ws`, in one launch in place of one a matrix. The ids go to the last `IDS` words of + /// `p.y`. None (the caller runs its loop) off CUDA, on mixed shapes, scaled weights or offsets past i32. + /// ponytail: CUDA only; the Vulkan moe_gemv's id * stride may not be 64-bit, check before enabling it there. + fn gemv_many(&self, p: &Part, ws: &[&GpuTensor], x: u64, xs: usize, xg: usize, y: u64) -> Option<()> { + let w0 = ws.first()?; + if p.be.name() != "cuda" || ws.len() > IDS || ws.iter().any(|w| w.ty != w0.ty || w.rows != w0.rows || w.cols != w0.cols || w.scale != 1.0) { return None; } + let base = ws.iter().map(|w| w.ptr).min()?; + let gcd = |mut a: u64, mut b: u64| { while b != 0 { (a, b) = (b, a % b); } a }; + let g = ws.iter().fold(0, |g, w| gcd(g, w.ptr - base)).max(1); + let ids = ws.iter().map(|w| i32::try_from((w.ptr - base) / g).ok()).collect::>>()?; + let at = p.y.len() / 4 - IDS; + p.be.put(&ids, &p.y, at).ok()?; + p.be.moe_gemv(w0.ty, w0.rows, w0.cols, base, g as usize, p.y.addr() + 4 * at as u64, ws.len(), x, xs, xg, y, None, 0).ok() + } + /// Whether `m` lives in VRAM of the first GPU (a staged matrix is copied up to it per use). + pub fn on_first(&self, m: &Mat) -> bool { self.part_of(m) == Some(0) } fn part_of(&self, m: &Mat) -> Option { let i = m.gpu?; Some(if i == STAGED { 0 } else { gpu_of(i) }) @@ -355,12 +774,14 @@ pub(crate) mod dev { } else { p.be.gemm_dense(w, n, p.x.addr(), m.cols, p.y.addr(), m.rows, 0).ok()?; } + trip(); p.be.get(&p.y, 0, n * m.rows).ok()? } else { let xb = p.be.zeros::(n * m.cols).ok()?; let yb = p.be.zeros::(n * m.rows).ok()?; p.be.put(&flat, &xb, 0).ok()?; p.be.gemm_dense(w, n, xb.addr(), m.cols, yb.addr(), m.rows, 0).ok()?; + trip(); p.be.get(&yb, 0, n * m.rows).ok()? }; drop(owned); @@ -379,16 +800,18 @@ pub(crate) mod dev { let (nt, np) = (x.len() / nl, pairs.iter().map(|v| v.len()).sum::()); // GEMM tiles [weights, first pair | pairs << 32] of the gate and up matrices, then of the down ones; // then per pair its token, and per (token, slot) the router weight and the pair (weight 0: not here). - let (mut owned, mut tiles, mut xrow) = (vec![], vec![], vec![]); + let (mut tiles, mut xrow) = (vec![], vec![]); let (mut wts, mut inv) = (vec![0f32; nt * k], vec![0i32; nt * k]); let mut shape = [(GgmlType::F32, 0, 0); 2]; + let (owned, ptrs) = self.weights(p, &[gus, downs])?; + let mut ptrs = ptrs.into_iter(); for (side, mats) in [gus, downs].into_iter().enumerate() { let mut m0 = 0; for (m, ps) in mats.iter().zip(pairs) { - let w = self.weight(p, m, &mut owned)?; - shape[side] = (w.ty, w.rows, w.cols); + let w = ptrs.next()?; + shape[side] = (m.ty, m.rows, m.cols); for at in (0..ps.len()).step_by(GEMM_BM) { - tiles.extend([w.ptr, (m0 + at) as u64 | (GEMM_BM.min(ps.len() - at) as u64) << 32]); + tiles.extend([w, (m0 + at) as u64 | (GEMM_BM.min(ps.len() - at) as u64) << 32]); } m0 += ps.len(); } @@ -415,6 +838,140 @@ pub(crate) mod dev { p.be.situ(ya(gate_up), nf, np, ia(ints + np + 2 * nt * k), beta, lb).ok()?; p.be.gemm(dty, drows, dcols, ia(4 * n_tiles), n_tiles, ya(gate_up), 2 * nf, np, 0, ya(down), nl, 0).ok()?; p.be.moe_combine_seq(b.addr(), ya(down), ia(ints + np), ia(ints + np + nt * k), k, 0, 0, nl, nt).ok()?; + trip(); + let y = p.be.get(&b, 0, nt * nl).ok()?; + drop(owned); + Some(y) + } + /// SwiGLU experts of a chunk of tokens, all on the device, in four launches whatever the number of experts. + /// `x`: one row of activations a token. Expert i (`gates[i]`, `ups[i]`, `downs[i]`) runs on `pairs[i]`, a list + /// of (token, slot of the expert among the `k` of that token, router weight). Returns per token the weighted + /// sum of these experts' outputs. `lim` > 0 clamps as `ops::swiglu_clamp` (an extra launch). None when a matrix + /// is on another GPU or the chunk does not fit. + pub fn swiglu_chunk(&self, gates: &[Mat], ups: &[Mat], downs: &[Mat], pairs: &[Vec<(usize, usize, f32)>], x: &[f32], k: usize, lim: f32) -> Option> { + use crate::backend::GEMM_BM; + let d = self.part_of(gates.first()?)?; + if gates.iter().chain(ups).chain(downs).any(|m| self.part_of(m) != Some(d) || m.scale != 1.0) { return None; } + let (p, nf, nl) = (&self.parts[d], downs[0].cols, downs[0].rows); + let (nt, np) = (x.len() / gates[0].cols, pairs.iter().map(|v| v.len()).sum::()); + // GEMM tiles [weights, first pair | pairs << 32] of the gates, the ups, the downs. + let (mut tiles, mut xrow) = (vec![], vec![]); + let (mut wts, mut inv) = (vec![0f32; nt * k], vec![0i32; nt * k]); + let mut shape = [(GgmlType::F32, 0, 0); 3]; + let sides = [gates, ups, downs]; + // Experts with a staged matrix stream through three VRAM slots (on CUDA, where the copies overlap the + // GEMMs): the resident experts first, then groups that fit a slot. Elsewhere `weights` copies them all. + let staged = |i: usize| sides.iter().map(|s| if s[i].gpu == Some(STAGED) { s[i].data.len().next_multiple_of(256) } else { 0 }).sum::(); + let stream = p.be.beside_overlaps() && (0..gates.len()).any(|i| staged(i) > 0) && (0..gates.len()).all(|i| staged(i) <= SLOT); + let slots = if stream { + let mut b = p.slots.lock().unwrap(); + if b.len() < 3 * SLOT { *b = p.be.alloc(3 * SLOT).ok().unwrap_or(Buf::new(0, 0, ())); } + (b.len() >= 3 * SLOT).then(|| b.clone()) + } else { None }; + let mut order: Vec = (0..gates.len()).collect(); + // groups: (first, end) in `order`; copies: per group (host bytes, offset in the group's slot) + let (mut groups, mut copies): (Vec<(usize, usize)>, Vec>) = (vec![], vec![]); + let mut at_of = vec![0u64; 3 * gates.len()]; + let owned = match &slots { + Some(sb) => { + order.sort_by_key(|&i| staged(i) > 0); + let mut fill = SLOT; + for (o, &i) in order.iter().enumerate() { + for (side, mats) in sides.iter().enumerate() { + if mats[i].gpu != Some(STAGED) { at_of[3 * i + side] = self.tensor(mats[i].gpu?).ptr; } + } + if staged(i) == 0 { continue; } + if fill + staged(i) > SLOT { groups.push((o, o)); copies.push(vec![]); fill = 0; } + let g = groups.len() - 1; + groups[g].1 = o + 1; + for (side, mats) in sides.iter().enumerate() { + if mats[i].gpu != Some(STAGED) { continue; } + at_of[3 * i + side] = sb.addr() + ((g % 3) * SLOT + fill) as u64; + copies[g].push((mats[i].data, (g % 3) * SLOT + fill)); + fill += mats[i].data.len().next_multiple_of(256); + } + } + Buf::new(0, 0, ()) + } + None => { + let (owned, ptrs) = self.weights(p, &sides)?; + for (j, a) in ptrs.into_iter().enumerate() { at_of[3 * (j % gates.len()) + j / gates.len()] = a; } + owned + } + }; + // per expert in `order`: its first tile and its first pair + let (mut tile_at, mut pair_at) = (vec![0usize; gates.len() + 1], vec![0usize; gates.len() + 1]); + for (side, mats) in sides.iter().enumerate() { + let mut m0 = 0; + for (o, &i) in order.iter().enumerate() { + let (m, ps) = (&mats[i], &pairs[i]); + if m0 > 0 && shape[side] != (m.ty, m.rows, m.cols) { return None; } + shape[side] = (m.ty, m.rows, m.cols); + if side == 0 { (tile_at[o], pair_at[o]) = (tiles.len() / 2, m0); } + for at in (0..ps.len()).step_by(GEMM_BM) { + tiles.extend([at_of[3 * i + side], (m0 + at) as u64 | (GEMM_BM.min(ps.len() - at) as u64) << 32]); + } + m0 += ps.len(); + } + if side == 0 { (tile_at[gates.len()], pair_at[gates.len()]) = (tiles.len() / 2, m0); } + } + for &i in &order { + for &(t, j, w) in &pairs[i] { + (wts[t * k + j], inv[t * k + j]) = (w, xrow.len() as i32); + xrow.push(t as i32); + } + } + let (n_tiles, ints) = (tiles.len() / 6, 2 * tiles.len()); + if ints + np + 2 * nt * k > p.y.len() / 4 { return None; } + // A chunk whose activations do not fit the scratch (more than about 1950 tokens of 2560) gets its own + // buffer for this call, as `rows` does, instead of each expert going through a round trip of its own. + let xb = if x.len() > p.x.len() / 4 { Some(p.be.alloc(4 * x.len()).ok()?) } else { None }; + let xd = xb.as_ref().unwrap_or(&p.x); + // Zeroed: the sums, then per pair the activation rows, then per pair the down rows. + // A clamp keeps the ups apart (after the down rows) for the `swiglu_clamp` launch. + let clamp = lim > 0.0; + let b = p.be.alloc(4 * (nt * nl + np * (nf + nl) + if clamp { np * nf } else { 0 })).ok()?; + let (ia, ya) = (|i: usize| p.y.addr() + 4 * i as u64, |i: usize| b.addr() + 4 * i as u64); + let (act, down, upr) = (nt * nl, nt * nl + np * nf, nt * nl + np * (nf + nl)); + p.be.put(x, xd, 0).ok()?; + p.be.put(&tiles, &p.y, 0).ok()?; + p.be.put(&xrow, &p.y, ints).ok()?; + p.be.put(&wts, &p.y, ints + np).ok()?; + p.be.put(&inv, &p.y, ints + np + nt * k).ok()?; + let [(gt, gr, gc), (ut, ur, uc), (dt, dr, dc)] = shape; + // The experts order[a..b]: their tiles are contiguous on each side, their pairs too. + let run = |a: usize, b: usize| -> Option<()> { + let (t0, nn, p0, pn) = (tile_at[a], tile_at[b] - tile_at[a], pair_at[a], pair_at[b] - pair_at[a]); + if nn == 0 { return Some(()); } + p.be.gemm(gt, gr, gc, ia(4 * t0), nn, xd.addr(), gc, nt, ia(ints), ya(act), nf, 0).ok()?; + if clamp { + p.be.gemm(ut, ur, uc, ia(4 * (n_tiles + t0)), nn, xd.addr(), uc, nt, ia(ints), ya(upr), nf, 0).ok()?; + p.be.swiglu_clamp(ya(act + p0 * nf), ya(upr + p0 * nf), pn * nf, lim).ok()?; + } else { + p.be.gemm(ut, ur, uc, ia(4 * (n_tiles + t0)), nn, xd.addr(), uc, nt, ia(ints), ya(act), nf, 1).ok()?; + } + p.be.gemm(dt, dr, dc, ia(4 * (2 * n_tiles + t0)), nn, ya(act), nf, np, 0, ya(down), nl, 0).ok() + }; + match &slots { + None => run(0, gates.len())?, + Some(sb) => { + // Step s: the GEMMs of group s - 2 (whose copies the stream waits for after step s - 1), then the + // copies of group s into the slot of group s - 3 (its GEMMs queued before this step's copies). + let ng = groups.len(); + for st in 0..ng + 2 { + p.be.beside(&mut || { + let e = || anyhow::anyhow!("swiglu_chunk"); + if st == 1 { run(0, groups[0].0).ok_or_else(e)?; } + if st >= 2 { run(groups[st - 2].0, groups[st - 2].1).ok_or_else(e)?; } + if st < ng { for &(d, off) in &copies[st] { p.be.htod(d, sb, off)?; } } + Ok(()) + }).ok()?; + } + p.be.beside_join().ok()?; + } + } + p.be.moe_combine_seq(b.addr(), ya(down), ia(ints + np), ia(ints + np + nt * k), k, 0, 0, nl, nt).ok()?; + trip(); let y = p.be.get(&b, 0, nt * nl).ok()?; drop(owned); Some(y) @@ -433,8 +990,281 @@ pub(crate) mod dev { p.be.gemm_dense(self.tensor(m.gpu?), n, p.x.addr() + (4 * j * n * cols) as u64, cols, p.y.addr() + 4 * yo as u64, m.rows, 0).ok()?; yo += n * m.rows; } + trip(); p.be.get(&p.y, 0, yo).ok() } + /// Causal attention of `nt` consecutive queries (`q`: `nh` heads of `hd` each) over the f16 rows `k`, `v` + /// (`nkv` heads a position; the first query sits at row `base`), a query seeing its last `win` keys + /// (0: all). None when the backend has no kernel for it or the cache is not f16 there. + pub fn attn_rows(&self, q: &[f32], k: &[u16], v: &[u16], base: usize, nt: usize, nh: usize, nkv: usize, hd: usize, win: usize) -> Option> { + let be = &self.parts.first()?.be; + if be.kv_words(k.len()) != k.len() { return None; } + let (b, o) = sections(&self.parts[0], &[4 * q.len(), 2 * k.len(), 2 * v.len(), 4, 4 * q.len()])?; + be.put(q, &b, 0).ok()?; + be.put(k, &b, o[1] / 2).ok()?; + be.put(v, &b, o[2] / 2).ok()?; + be.put(&[base as i32], &b, o[3] / 4).ok()?; + let a = |i: usize| b.addr() + o[i] as u64; + be.attn_prefill_m(a(0), a(1), a(2), 0, a(4), a(3), nt, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), 0, 0, 0, win).ok()?; + trip(); + be.get(&b, o[4] / 4, q.len()).ok() + } + /// Attention of `nt` queries over their own key lists (`Backend::attn_sel`): `idx` holds `idx.len() / nt` + /// positions a query, `cnt` how many of them count; `k`/`v` are all the f16 rows of the layer. + pub fn attn_sel(&self, q: &[f32], k: &[u16], v: &[u16], idx: &[u32], cnt: &[i32], nt: usize, nh: usize, nkv: usize, hd: usize) -> Option> { + let be = &self.parts.first()?.be; + if be.kv_words(k.len()) != k.len() { return None; } + let (b, o) = sections(&self.parts[0], &[4 * q.len(), 2 * k.len(), 2 * v.len(), 4 * idx.len(), 4 * nt, 4 * q.len()])?; + be.put(q, &b, 0).ok()?; + be.put(k, &b, o[1] / 2).ok()?; + be.put(v, &b, o[2] / 2).ok()?; + be.put(idx, &b, o[3] / 4).ok()?; + be.put(cnt, &b, o[4] / 4).ok()?; + let a = |i: usize| b.addr() + o[i] as u64; + be.attn_sel(a(0), a(1), a(2), a(3), a(4), a(5), nt, nh, nkv, hd, idx.len() / nt, 1.0 / (hd as f32).sqrt()).ok()?; + trip(); + be.get(&b, o[5] / 4, q.len()).ok() + } + /// `Backend::mla_attn` on the first GPU: `sel` gives each query its `ns` key positions (the first `cnt[t]` + /// valid); without it query t sees rows 0..cnt[t] of `kc`. + /// The key rows stay on the card under `key`: rows from `new` on (and any not yet uploaded) go up, the ones + /// before are taken as unchanged since the last call. + pub fn mla_attn(&mut self, key: usize, new: usize, q: &[f32], kc: &[u16], sel: Option<(&[u32], usize)>, cnt: &[i32], nh: usize, hd: usize, vd: usize) -> Option> { + self.mla_attn_on(0, key, new, q, kc, sel, cnt, nh, hd, vd) + } + /// `mla_attn` on GPU `d`, its key rows kept there. + pub fn mla_attn_on(&mut self, d: usize, key: usize, new: usize, q: &[f32], kc: &[u16], sel: Option<(&[u32], usize)>, cnt: &[i32], nh: usize, hd: usize, vd: usize) -> Option> { + let kaddr = self.rows_on(d, key, new, bytes_of(kc), 2 * hd)?; + let be = &self.parts[d].be; + let (nt, idx) = (cnt.len(), sel.map_or(&[][..], |s| s.0)); + let (b, o) = sections(&self.parts[d], &[4 * q.len(), 4 * idx.len().max(1), 4 * nt, 4 * nt * nh * vd])?; + be.put(q, &b, 0).ok()?; + if !idx.is_empty() { be.put(idx, &b, o[1] / 4).ok()?; } + be.put(cnt, &b, o[2] / 4).ok()?; + let a = |i: usize| b.addr() + o[i] as u64; + be.mla_attn(a(0), kaddr, if idx.is_empty() { 0 } else { a(1) }, a(2), a(3), nt, nh, hd, vd, sel.map_or(0, |s| s.1), *cnt.iter().max()? as usize, 0, 0, 1.0).ok()?; + trip(); + be.get(&b, o[3] / 4, nt * nh * vd).ok() + } + /// DeepSeek-V4.1 attention of one decode token on GPU `d` in one round trip: q = wq_b qr, roped into the + /// padded query rows of `mla_attn_on` (`cs`: cos, sin of each rope pair at the token's position; times + /// `scale`, sink dims from vd), attention over the rows `idx` of the key rows under `key`, the output de-roped, + /// wo_a group by group (`wo_a[g]` reads heads' slice g) and wo_b. None when a matrix is on another GPU or the + /// backend lacks a kernel. + pub fn ds_attn_on(&mut self, d: usize, key: usize, new: usize, kc: &[u16], idx: &[u32], qr: &[f32], wq_b: &Mat, wo_a: &[Mat], wo_b: &Mat, cs: &[f32], nh: usize, w: usize, vd: usize, scale: f32) -> Option> { + if std::iter::once(wq_b).chain(wo_a).chain([wo_b]).any(|m| self.part_of(m) != Some(d)) { return None; } + let (hd, n_rot, og) = (wq_b.rows / nh, cs.len(), wo_a.len()); + let (gsz, r) = (nh * hd / og, wo_a.first()?.rows); + let kaddr = self.rows_on(d, key, new, bytes_of(kc), 2 * w)?; + let p = &self.parts[d]; + let (owned, ts) = self.tensors(p, &[&[*wq_b], wo_a, &[*wo_b]])?; + let be = &p.be; + let (b, o) = sections(p, &[4 * qr.len(), 4 * nh * hd, 4 * nh * w, 4 * idx.len(), 4, 4 * nh * vd, 4 * nh * hd, 4 * og * r, 4 * wo_b.rows, 4 * n_rot])?; + let a = |i: usize| b.addr() + o[i] as u64; + be.put(qr, &b, 0).ok()?; + be.put(idx, &b, o[3] / 4).ok()?; + be.put(&[idx.len() as i32], &b, o[4] / 4).ok()?; + be.put(cs, &b, o[9] / 4).ok()?; + be.gemv(&ts[0], a(0), a(1)).ok()?; + be.ds_rope(a(1), hd, a(2), w, nh, nh, hd, w, n_rot, a(9), false, scale, vd).ok()?; + be.mla_attn(a(2), kaddr, a(3), a(4), a(5), 1, nh, w, vd, idx.len(), idx.len(), 0, 0, 1.0).ok()?; + be.ds_rope(a(5), vd, a(6), hd, nh, nh, hd, hd, n_rot, a(9), true, 1.0, 0).ok()?; + for g in 0..og { be.gemv(&ts[1 + g], a(6) + 4 * (g * gsz) as u64, a(7) + 4 * (g * r) as u64).ok()?; } + be.gemv(&ts[1 + og], a(7), a(8)).ok()?; + trip(); + let y = be.get(&b, o[8] / 4, wo_b.rows).ok(); + drop(owned); + y + } + /// A whole absorbed MLA attention of a prompt on the first GPU: `q` [t][head][kd] (nope dims, then rope dims, + /// roped), `kb[h]` (kl x nope) absorbs head h's query, `mla_attn` runs on the cached rows `kc` (hd = kl + rope + /// a row, scores times `scale`), `vb[h]` (vd x kl) maps head h's output. Returns [t][head][vd]. None when a + /// matrix is not on that GPU or the backend lacks a kernel. + pub fn mla_prompt(&mut self, key: usize, new: usize, q: &[f32], kc: &[u16], sel: Option<(&[u32], usize)>, cnt: &[i32], kb: &[Mat], vb: &[Mat], hd: usize, scale: f32) -> Option> { + let (nt, nh, kl, vd) = (cnt.len(), kb.len(), kb.first()?.rows, vb.first()?.rows); + let kd = q.len() / (nt * nh); + if kb.iter().chain(vb).any(|m| self.part_of(m) != Some(0) || m.gpu == Some(STAGED)) { return None; } + let kaddr = self.rows_on_card(key, new, bytes_of(kc), 2 * hd)?; + let idx = sel.map_or(&[][..], |s| s.0); + let sz = [4 * q.len(), 4 * nt * nh * hd, 4 * idx.len().max(1), 4 * nt, 4 * nt * nh * kl, 4 * nt * nh * vd]; + // Short of VRAM (the expert cache took it): the two halves of the queries one after the other, as the CPU + // fallback is far slower. Each query's result does not depend on the others. + let Some((b, o)) = sections(&self.parts[0], &sz) else { + if nt < 16 { return None; } + let (h, ns) = (nt / 2, sel.map_or(0, |s| s.1)); + let mut y = self.mla_prompt(key, new, &q[..h * nh * kd], kc, sel.map(|s| (&s.0[..h * ns], ns)), &cnt[..h], kb, vb, hd, scale)?; + y.extend(self.mla_prompt(key, new, &q[h * nh * kd..], kc, sel.map(|s| (&s.0[h * ns..], ns)), &cnt[h..], kb, vb, hd, scale)?); + return Some(y); + }; + let be = &self.parts[0].be; + be.put(q, &b, 0).ok()?; + if !idx.is_empty() { be.put(idx, &b, o[2] / 4).ok()?; } + be.put(cnt, &b, o[3] / 4).ok()?; + let a = |i: usize| b.addr() + o[i] as u64; + let mm = |m: &Mat, x: u64, xs: usize, y: u64, ys: usize| -> Option<()> { + let w = self.tensor(m.gpu?); + if nt <= 4 { be.gemvn(w, x, xs, y, ys, nt).ok() } else { be.gemm_dense(w, nt, x, xs, y, ys, 0).ok() } + }; + // nt <= 4: every (token, head) in one launch; the absorbed query rows are kl apart (`mla_attn` with qp). + let per_head = |ms: &[Mat]| -> Option> { (0..nt * nh).map(|j| Some(self.tensor(ms[j % nh].gpu?))).collect() }; + let many = |ms: &[Mat], x: u64, xs: usize, y: u64| nt <= 4 && per_head(ms).and_then(|ws| self.gemv_many(&self.parts[0], &ws, x, xs, 1, y)).is_some(); + if !many(kb, a(0), kd, a(1)) { + for (h, m) in kb.iter().enumerate() { mm(m, a(0) + 4 * (h * kd) as u64, nh * kd, a(1) + 4 * (h * kl) as u64, nh * kl)?; } + } + be.mla_attn(a(1), kaddr, if idx.is_empty() { 0 } else { a(2) }, a(3), a(4), nt, nh, hd, kl, sel.map_or(0, |s| s.1), *cnt.iter().max()? as usize, + a(0) + 4 * (kd - (hd - kl)) as u64, kd, scale).ok()?; + if !many(vb, a(4), kl, a(5)) { + for (h, m) in vb.iter().enumerate() { mm(m, a(4) + 4 * (h * kl) as u64, nh * kl, a(5) + 4 * (h * vd) as u64, nh * vd)?; } + } + trip(); + be.get(&b, o[5] / 4, nt * nh * vd).ok() + } + /// The address of rows (`rb` bytes each) that stay on the first GPU under `key`: the rows from `new` on (and + /// any not yet uploaded) go up, the ones before are taken as unchanged since the last call. + fn rows_on_card(&mut self, key: usize, new: usize, data: &[u8], rb: usize) -> Option { + self.rows_on(0, key, new, data, rb) + } + /// `rows_on_card` on GPU `d` (a `key` stays on one GPU). + fn rows_on(&mut self, d: usize, key: usize, new: usize, data: &[u8], rb: usize) -> Option { + let n = data.len() / rb; + let from = match self.kv.get(&key) { + Some((b, f)) if b.len() >= data.len() => (*f).min(new), + _ => { + // Room for a quarter more rows (at least 4096): doubling overshot --ctx by up to 2x and ran a long + // prompt out of VRAM. Short of VRAM, give back expert slots first. + self.kv.remove(&key); + let bytes = rb * (n + n / 4).max(4096); + let b = match self.parts.get(d)?.be.alloc(bytes) { + Ok(b) => b, + Err(_) => { self.release(d, bytes); self.parts[d].be.alloc(bytes).ok()? } + }; + self.kv.insert(key, (b, 0)); + 0 + } + }; + let be = &self.parts[d].be; + let (b, f) = self.kv.get_mut(&key)?; + if from < n { be.htod(&data[from * rb..], b, from * rb).ok()?; } + *f = n; + Some(b.addr()) + } + /// A Gated DeltaNet scan of `nt` tokens on the GPU (`conv_seq`, `l2_norm`, `deltanet` with raw gates): `qkv` + /// [nt][ch] before the conv, `beta`/`alpha` [nt][nv] raw; the conv state `conv` and the state `s` are read and + /// written back. Returns o [nt][nv * dv] (scaled, before the norm). + pub fn gdn_scan(&self, qkv: &[f32], beta: &[f32], alpha: &[f32], w: &[f32], dtb: &[f32], a: &[f32], conv: &mut [f32], s: &mut [f32], nk: usize, dk: usize, dv: usize, eps: f32) -> Option> { + let be = &self.parts.first()?.be; + let (nv, nt) = (dtb.len(), beta.len() / dtb.len()); + let (ch, kw) = (qkv.len() / nt, w.len() / (qkv.len() / nt)); + let f = |v: &[f32]| 4 * v.len(); + let (b, o) = sections(&self.parts[0], &[f(s), f(qkv), f(qkv), f(beta), f(alpha), f(conv), f(w), f(dtb), f(a), 4 * nt * nv * dv])?; + for (i, v) in [&*s, qkv, &[][..], beta, alpha, &*conv, w, dtb, a].into_iter().enumerate() { + if !v.is_empty() { be.put(v, &b, o[i] / 4).ok()?; } + } + let at = |i: usize| b.addr() + o[i] as u64; + be.conv_seq(at(1), at(5), at(6), at(2), ch, kw, nt, 0, 0).ok()?; + be.l2_norm(at(2), dk, 2 * nk, ch, nt * 2 * nk, eps).ok()?; + be.deltanet(at(2), at(0), at(3), at(4), at(7), at(8), at(9), nk, nv, true, dk, dv, 1.0 / (dk as f32).sqrt(), nt, ch, 0, 0).ok()?; + trip(); + s.copy_from_slice(&be.get::(&b, o[0] / 4, s.len()).ok()?); + trip(); + conv.copy_from_slice(&be.get::(&b, o[5] / 4, conv.len()).ok()?); + trip(); + be.get(&b, o[9] / 4, nt * nv * dv).ok() + } + /// A whole Gated DeltaNet layer of a prompt chunk on the first GPU: `ms` = [qkv, z, beta, alpha, out] on the + /// token rows `x`, the scan as `gdn_scan`, then o = rms_norm(o) * `norm` * sigmoid(z) per head of `dv` (fold + /// any constant gate factor into `norm`) and the out projection. Reads and writes back `conv` and `s`. + /// `conv` and `s` stay on the card under `key`: `fresh` uploads them first, `back` reads them back after. + /// Returns [nt][out rows]. None when a matrix is on another GPU or a kernel is missing, or (a few tokens) a + /// matrix is staged. + #[allow(clippy::too_many_arguments)] + pub fn gdn_prompt(&mut self, key: usize, fresh: bool, back: bool, ms: &[Mat; 5], x: &[f32], w: &[f32], dtb: &[f32], a: &[f32], norm: &[f32], conv: &mut [f32], s: &mut [f32], nk: usize, dk: usize, eps: f32) -> Option> { + if ms.iter().any(|m| self.part_of(m) != Some(0)) { return None; } + let (nt, nv, dv) = (x.len() / ms[0].cols, dtb.len(), norm.len()); + if nt <= 4 && ms.iter().any(|m| m.gpu == Some(STAGED)) { return None; } + // [s | conv] and the same again for the state after the first token of a call (`gdn_rollback`) + let sb = 4 * (s.len() + conv.len()); + if fresh || self.gdn.get(&key).is_none_or(|b| b.len() < 2 * sb) { + self.gdn.remove(&key); + let b = match self.parts[0].be.alloc(2 * sb) { + Ok(b) => b, + Err(_) => { self.release(0, 2 * sb); self.parts[0].be.alloc(2 * sb).ok()? } + }; + self.parts[0].be.put(s, &b, 0).ok()?; + self.parts[0].be.put(conv, &b, s.len()).ok()?; + self.gdn.insert(key, b); + } + let be = &self.parts[0].be; + let sbuf = &self.gdn[&key]; + let (s_at, conv_at) = (sbuf.addr(), sbuf.addr() + 4 * s.len() as u64); + let (snap, nsnap) = if nt <= 4 { (sbuf.addr() + sb as u64, 1) } else { (0, 0) }; + let ch = ms[0].rows; + let f = |v: &[f32]| 4 * v.len(); + // staged weights go up once for this call + let owned: Vec> = ms.iter().map(|m| match m.gpu? { + STAGED => { + let b = be.alloc(m.data.len()).ok()?; + be.htod(m.data, &b, 0).ok()?; + Some(Some(GpuTensor::new(m.ty, m.rows, m.cols, b).with_scale(m.scale))) + } + _ => Some(None), + }).collect::>()?; + let wt = |i: usize| owned[i].as_ref().unwrap_or_else(|| self.tensor(ms[i].gpu.unwrap())); + let sz = [f(x), 0, 0, f(w), f(dtb), f(a), f(norm), 4 * nt * ch, 4 * nt * ch, 4 * nt * nv * dv, 4 * nt * nv, 4 * nt * nv, 4 * nt * nv * dv, 4 * nt * ms[4].rows]; + let (b, o) = sections(&self.parts[0], &sz)?; + for (i, v) in [x, &[][..], &[][..], w, dtb, a, norm].into_iter().enumerate() { if !v.is_empty() { be.put(v, &b, o[i] / 4).ok()?; } } + let at = |i: usize| match i { 1 => s_at, 2 => conv_at, _ => b.addr() + o[i] as u64 }; + let mm = |i: usize, x: u64, y: u64| -> Option<()> { + let (w, m) = (wt(i), &ms[i]); + if nt <= 4 { be.gemvn(w, x, m.cols, y, m.rows, nt).ok() } else { be.gemm_dense(w, nt, x, m.cols, y, m.rows, 0).ok() } + }; + // 7 qkv, 8 conv out, 9 z, 10 beta, 11 alpha, 12 o, 13 out + for (i, y) in [(0, 7), (1, 9), (2, 10), (3, 11)] { mm(i, at(0), at(y))?; } + be.conv_seq(at(7), at(2), at(3), at(8), ch, w.len() / ch, nt, snap + 4 * s.len() as u64, nsnap).ok()?; + be.l2_norm(at(8), dk, 2 * nk, ch, nt * 2 * nk, eps).ok()?; + be.deltanet(at(8), at(1), at(10), at(11), at(4), at(5), at(12), nk, nv, true, dk, dv, 1.0 / (dk as f32).sqrt(), nt, ch, snap, nsnap).ok()?; + be.norm_gate_sig(at(12), at(6), at(9), dv, nt * nv, eps, 0).ok()?; + mm(4, at(12), at(13))?; + if back { + trip(); + s.copy_from_slice(&be.get::(sbuf, 0, s.len()).ok()?); + trip(); + conv.copy_from_slice(&be.get::(sbuf, s.len(), conv.len()).ok()?); + } + trip(); + let y = be.get(&b, o[13] / 4, nt * ms[4].rows).ok(); + drop(owned); + y + } + /// Back to the state `gdn_prompt` kept after the first token of its last call (of 2 to 4 tokens) under `key`; + /// `n` is the length of s plus conv. + pub fn gdn_rollback(&self, key: usize, n: usize) -> bool { + let (Some(b), Some(p)) = (self.gdn.get(&key), self.parts.first()) else { return false }; + p.be.dtod(b, 4 * n, b, 0, 4 * n).is_ok() + } + /// The `conv` and `s` that `gdn_prompt` keeps under `key`; false when it keeps none. + pub fn gdn_fetch(&self, key: usize, conv: &mut [f32], s: &mut [f32]) -> bool { + let (Some(b), Some(p)) = (self.gdn.get(&key), self.parts.first()) else { return false }; + trip(); + let (Ok(a), Ok(c)) = (p.be.get::(b, 0, s.len()), p.be.get::(b, s.len(), conv.len())) else { return false }; + s.copy_from_slice(&a); + conv.copy_from_slice(&c); + true + } + /// Lightning-indexer scores (`Backend::idx_score`) of `nt` queries over the keys `ik` (f32 rows of `hd`, kept + /// on the card under `key` as in `rows_on_card`): [t][key]. + pub fn idx_score(&mut self, key: usize, new: usize, ik: &[f32], q: &[f32], w: &[f32], nh: usize, hd: usize) -> Option> { + let kaddr = self.rows_on_card(key, new, bytes_of(ik), 4 * hd)?; + let be = &self.parts[0].be; + let (nt, nk) = (w.len() / nh, ik.len() / hd); + let (b, o) = sections(&self.parts[0], &[4 * q.len(), 4 * w.len(), 4 * nt * nk])?; + be.put(q, &b, 0).ok()?; + be.put(w, &b, o[1] / 4).ok()?; + let a = |i: usize| b.addr() + o[i] as u64; + be.idx_score(a(0), a(1), kaddr, a(2), nt, nk, nh, hd).ok()?; + trip(); + be.get(&b, o[2] / 4, nt * nk).ok() + } /// `rows` for several matrices: job i runs its matrix on its own `n` rows of `x` (after job i-1's rows). /// One upload and one readback for all jobs. None when the batch does not fit the scratch buffers. /// ponytail: None too when the weights are on different GPUs; batch per GPU if a multi-GPU prompt waits here. @@ -466,6 +1296,7 @@ pub(crate) mod dev { xo += n * m.cols; yo += n * m.rows; } + trip(); let y = p.be.get(&p.y, 0, yo).ok()?; drop(owned); Some(y) @@ -477,7 +1308,47 @@ pub(crate) mod dev { /// `Mat::matvec`. pub fn matvec_many(ms: &[Mat], x: &[f32], xs: usize) -> Vec { if let Some(y) = matvec_many_opt(ms, x, xs) { return y; } + if xs > 0 && ms.len() > 1 { + let slices: Vec<&[f32]> = (0..ms.len()).map(|i| &x[i * xs..i * xs + ms[i].cols]).collect(); + if let Some(y) = matvec_many_cpu(ms, &slices) { return y; } + } let mut y = vec![0f32; ms.iter().map(|m| m.rows).sum()]; + if xs == 0 && ms.len() > 1 && std::env::var_os("STRATA_CPU_REF").is_none() { + let mut int_ms: Vec<(usize, usize, Mat, usize, fn(&[u8], &[crate::cpu_moe::Q8K]) -> f32)> = Vec::new(); + let mut other: Vec<(usize, Mat)> = Vec::new(); + let (mut off, mut int_total) = (0, 0); + for &m in ms { + if m.gpu.is_none() && m.cols == x.len() && (m.cpu || m.rows >= 512) && m.cols % m.ty.block_elems() == 0 + && let Some(dot) = crate::cpu_moe::int_dot(m.ty) + { + let rb = m.ty.row_bytes(m.cols as u64); + int_ms.push((int_total, off, m, rb, dot)); + int_total += m.rows; + } else { + other.push((off, m)); + } + off += m.rows; + } + if int_ms.len() > 1 { + let xq = crate::cpu_moe::quantize_q8k(x); + let mut tmp = vec![0f32; int_total]; + tmp.par_chunks_mut(32).enumerate().for_each(|(c, ys)| { + for (k, o) in ys.iter_mut().enumerate() { + let r = c * 32 + k; + let i = int_ms.partition_point(|(s, ..)| *s <= r) - 1; + let (s, _, m, rb, dot) = int_ms[i]; + *o = dot(&m.data[(r - s) * rb..(r - s + 1) * rb], &xq) * m.scale; + } + }); + for (s, dst_off, m, ..) in &int_ms { + y[*dst_off..*dst_off + m.rows].copy_from_slice(&tmp[*s..*s + m.rows]); + } + for (dst_off, m) in other { + m.matvec(x, &mut y[dst_off..dst_off + m.rows]); + } + return y; + } + } let mut off = 0; for (i, m) in ms.iter().enumerate() { m.matvec(&x[i * xs..i * xs + m.cols], &mut y[off..off + m.rows]); @@ -486,27 +1357,62 @@ pub fn matvec_many(ms: &[Mat], x: &[f32], xs: usize) -> Vec { y } +/// Host integer dot of several matrices sharing ONE activation `x`, in a single `quantize_q8k` + single Rayon pass. +/// Supports mixed `GgmlType`s across `ms` as long as every matrix is host-only and has an integer dot kernel. +pub fn matvec_many_cpu_shared<'a>(ms: &[Mat<'a>], x: &[f32]) -> Option> { + if ms.is_empty() || std::env::var_os("STRATA_CPU_REF").is_some() { return None; } + let cols = x.len(); + let mut dots = Vec::with_capacity(ms.len()); + let mut starts = Vec::with_capacity(ms.len()); + let mut off = 0; + for m in ms { + if m.gpu.is_some() || m.cols != cols || (!m.cpu && m.rows < 512) || cols % m.ty.block_elems() != 0 { + return None; + } + let dot = crate::cpu_moe::int_dot(m.ty)?; + let rb = m.ty.row_bytes(cols as u64); + starts.push((off, *m, rb)); + dots.push(dot); + off += m.rows; + } + let xq = crate::cpu_moe::quantize_q8k(x); + let mut y = vec![0f32; off]; + y.par_chunks_mut(32).enumerate().for_each(|(c, ys)| { + for (k, o) in ys.iter_mut().enumerate() { + let r = c * 32 + k; + let i = starts.partition_point(|(s, ..)| *s <= r) - 1; + let (s, m, rb) = starts[i]; + *o = dots[i](&m.data[(r - s) * rb..(r - s + 1) * rb], &xq) * m.scale; + } + }); + Some(y) +} + /// Host integer dot of several matrices, one activation each, in a single Rayon pass: the rows of all matrices, in -/// order. None when a matrix is on the GPU or `Mat::matvec` would not take the integer dot for it. +/// order. Supports mixed `GgmlType`s. None when a matrix is on the GPU or `Mat::matvec` would not take the integer dot. pub fn matvec_many_cpu<'a>(ms: &[Mat<'a>], xs: &[&[f32]]) -> Option> { - let ty = ms.first()?.ty; - if ms.len() != xs.len() || ms.iter().any(|m| m.ty != ty || m.gpu.is_some() || m.cols != xs[0].len()) - || xs.iter().any(|x| x.len() != xs[0].len()) { return None; } - if std::env::var_os("STRATA_CPU_REF").is_some() || xs[0].len() % ty.block_elems() != 0 - || ms.iter().any(|m| !m.cpu && m.rows < 512) { return None; } - let dot = crate::cpu_moe::int_dot(ty)?; - let xq: Vec<_> = xs.par_iter().map(|x| crate::cpu_moe::quantize_q8k(x)).collect(); - let rb = ty.row_bytes(xs[0].len() as u64); + if ms.is_empty() || ms.len() != xs.len() || std::env::var_os("STRATA_CPU_REF").is_some() { return None; } + let mut dots = Vec::with_capacity(ms.len()); let mut starts = Vec::with_capacity(ms.len()); let mut off = 0; - for m in ms { starts.push((off, *m)); off += m.rows; } + for (m, x) in ms.iter().zip(xs) { + if m.gpu.is_some() || m.cols != x.len() || (!m.cpu && m.rows < 512) || m.cols % m.ty.block_elems() != 0 { + return None; + } + let dot = crate::cpu_moe::int_dot(m.ty)?; + let rb = m.ty.row_bytes(m.cols as u64); + starts.push((off, *m, rb)); + dots.push(dot); + off += m.rows; + } + let xq: Vec<_> = xs.par_iter().map(|x| crate::cpu_moe::quantize_q8k(x)).collect(); let mut y = vec![0f32; off]; y.par_chunks_mut(32).enumerate().for_each(|(c, ys)| { for (k, o) in ys.iter_mut().enumerate() { let r = c * 32 + k; - let i = starts.partition_point(|(s, _)| *s <= r) - 1; - let (s, m) = starts[i]; - *o = dot(&m.data[(r - s) * rb..(r - s + 1) * rb], &xq[i]) * m.scale; + let i = starts.partition_point(|(s, ..)| *s <= r) - 1; + let (s, m, rb) = starts[i]; + *o = dots[i](&m.data[(r - s) * rb..(r - s + 1) * rb], &xq[i]) * m.scale; } }); Some(y) @@ -524,9 +1430,19 @@ pub fn matvec_many_opt(ms: &[Mat], x: &[f32], xs: usize) -> Option> { pub fn situ_chunk(gus: &[Mat], downs: &[Mat], gs: &[f32], pairs: &[Vec<(usize, usize, f32)>], x: &[f32], k: usize, beta: f32, lb: f32) -> Option> { dev::get().and_then(|d| d.lock().unwrap().situ_chunk(gus, downs, gs, pairs, x, k, beta, lb)) } +/// `Dev::swiglu_chunk` on the open GPU path (None without one). +pub fn swiglu_chunk(gates: &[Mat], ups: &[Mat], downs: &[Mat], pairs: &[Vec<(usize, usize, f32)>], x: &[f32], k: usize, lim: f32) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().swiglu_chunk(gates, ups, downs, pairs, x, k, lim)) +} pub fn situ_experts(gus: &[Mat], downs: &[Mat], gs: &[f32], x: &[f32], beta: f32, lb: f32) -> Option> { dev::get().and_then(|d| d.lock().unwrap().situ_experts(gus, downs, gs, x, beta, lb)) } +pub fn swiglu_experts(gs: &[Mat], us: &[Mat], downs: &[Mat], x: &[f32], nt: usize, lim: f32) -> Option> { + dev::get()?.lock().unwrap().swiglu_experts(gs, us, downs, x, nt, lim) +} +pub fn situ_experts_split(gs: &[Mat], us: &[Mat], downs: &[Mat], x: &[f32], beta: f32, lb: f32) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().situ_experts_split(gs, us, downs, x, beta, lb)) +} /// W x[t] for each row of `xs` (all rows of one matrix). Batches on the GPU when the weight is resident. pub fn matvec_rows(m: &Mat, xs: &[&[f32]]) -> Vec { @@ -540,7 +1456,11 @@ pub fn matvec_rows(m: &Mat, xs: &[&[f32]]) -> Vec { let mut by_row = vec![0f32; m.rows * n]; let dot4 = crate::cpu_moe::int_dot4(m.ty); let sc = m.scale; + // Q6_K, Q3_K and Q2_K: the one-row 4-activation kernels win below 8 activations (measured at 4, DeepSeek-V3 shapes, + // 12 threads: Q6_K 30.4 against 43.6 ms, Q2_K 16.0 against 22.5 ms). + let x8 = m.rows % 8 == 0 && match m.ty { GgmlType::Q4K | GgmlType::Q8_0 => true, GgmlType::Q6K | GgmlType::Q3K | GgmlType::Q2K => n >= 8, _ => false }; by_row.par_chunks_mut(32 * n).enumerate().for_each(|(c, o)| { + if x8 && crate::cpu_moe::rows_x8(m.ty, &m.data[c * 32 * rb..][..o.len() / n * rb], rb, &xq, sc, o) { return; } for (k, o) in o.chunks_exact_mut(n).enumerate() { let w = &m.data[(c * 32 + k) * rb..(c * 32 + k + 1) * rb]; let mut t = 0; @@ -601,16 +1521,91 @@ pub fn matvec_rows_many(jobs: &[(Mat, usize)], x: &[f32]) -> Vec { y } /// Expert cache lookups since the last PROF print: [hit, miss]. +/// GPU readbacks (each one waits for the queue): the round trips STRATA_DS_PROF reports. +pub static TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +fn trip() { TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } pub static EX_LOOKUPS: [std::sync::atomic::AtomicU64; 2] = [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; pub fn gpu_bytes() -> usize { dev::get().map_or(0, |d| d.lock().unwrap().bytes()) } /// Expert-budget bytes not yet used (0 without a GPU). pub fn budget_left() -> usize { dev::get().map_or(0, |d| d.lock().unwrap().budget_left()) } +/// Page-lock `data` (a range of the mapped model file) for the first GPU's DMA (`Backend::pin_host`), so staged +/// copies from it skip the pinned ring. False without a GPU or when the backend cannot. +pub fn pin_host(data: &[u8]) -> bool { + dev::get().is_some_and(|d| d.lock().unwrap().parts.first().is_some_and(|p| p.be.pin_host(data).unwrap_or(false))) +} /// (backend, resident expert slots, bytes of all uploaded weights) when the GPU path is open. pub fn dev_info() -> Option<(&'static str, usize, usize)> { dev::get().map(|d| d.lock().unwrap().info()) } +/// `Dev::attn_rows` on the open GPU path (None without one). +pub fn attn_rows(q: &[f32], k: &[u16], v: &[u16], base: usize, nt: usize, nh: usize, nkv: usize, hd: usize, win: usize) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().attn_rows(q, k, v, base, nt, nh, nkv, hd, win)) +} +/// `Dev::attn_sel` on the first GPU. None without a GPU or when the backend has no such kernel. +pub fn attn_sel(q: &[f32], k: &[u16], v: &[u16], idx: &[u32], cnt: &[i32], nt: usize, nh: usize, nkv: usize, hd: usize) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().attn_sel(q, k, v, idx, cnt, nt, nh, nkv, hd)) +} +/// `Dev::mla_attn` on the first GPU. None without a GPU or when the backend has no such kernel. +/// `Dev::gdn_scan` on the first GPU. None without a GPU. +pub fn gdn_scan(qkv: &[f32], beta: &[f32], alpha: &[f32], w: &[f32], dtb: &[f32], a: &[f32], conv: &mut [f32], s: &mut [f32], nk: usize, dk: usize, dv: usize, eps: f32) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().gdn_scan(qkv, beta, alpha, w, dtb, a, conv, s, nk, dk, dv, eps)) +} +/// `Dev::idx_score` on the first GPU. None without a GPU or when the backend has no such kernel. +pub fn idx_score(key: usize, new: usize, ik: &[f32], q: &[f32], w: &[f32], nh: usize, hd: usize) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().idx_score(key, new, ik, q, w, nh, hd)) +} +#[allow(clippy::too_many_arguments)] +pub fn gdn_prompt(key: usize, fresh: bool, back: bool, ms: &[Mat; 5], x: &[f32], w: &[f32], dtb: &[f32], a: &[f32], norm: &[f32], conv: &mut [f32], s: &mut [f32], nk: usize, dk: usize, eps: f32) -> Option> { + dev::get()?.lock().unwrap().gdn_prompt(key, fresh, back, ms, x, w, dtb, a, norm, conv, s, nk, dk, eps) +} +pub fn gdn_rollback(key: usize, n: usize) -> bool { + dev::get().is_some_and(|d| d.lock().unwrap().gdn_rollback(key, n)) +} +pub fn gdn_fetch(key: usize, conv: &mut [f32], s: &mut [f32]) -> bool { + dev::get().is_some_and(|d| d.lock().unwrap().gdn_fetch(key, conv, s)) +} +pub fn mla_prompt(key: usize, new: usize, q: &[f32], kc: &[u16], sel: Option<(&[u32], usize)>, cnt: &[i32], kb: &[Mat], vb: &[Mat], hd: usize, scale: f32) -> Option> { + dev::get()?.lock().unwrap().mla_prompt(key, new, q, kc, sel, cnt, kb, vb, hd, scale) +} +pub fn mla_attn(key: usize, new: usize, q: &[f32], kc: &[u16], sel: Option<(&[u32], usize)>, cnt: &[i32], nh: usize, hd: usize, vd: usize) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().mla_attn(key, new, q, kc, sel, cnt, nh, hd, vd)) +} +/// `Dev::mla_attn_on` on the open GPU path. +pub fn mla_attn_on(d: usize, key: usize, new: usize, q: &[f32], kc: &[u16], sel: Option<(&[u32], usize)>, cnt: &[i32], nh: usize, hd: usize, vd: usize) -> Option> { + dev::get().and_then(|g| g.lock().unwrap().mla_attn_on(d, key, new, q, kc, sel, cnt, nh, hd, vd)) +} +/// `Dev::ds_attn_on` on the open GPU path. +/// The shapes come from the GGUF: launch only when they agree (`chain_ok`), else None and the CPU path runs. +pub fn ds_attn_on(d: usize, key: usize, new: usize, kc: &[u16], idx: &[u32], qr: &[f32], wq_b: &Mat, wo_a: &[Mat], wo_b: &Mat, cs: &[f32], nh: usize, hd: usize, w: usize, vd: usize, scale: f32) -> Option> { + let sh = |m: &Mat| (m.rows, m.cols); + if !chain_ok(nh, hd, w, vd, cs.len(), qr.len(), sh(wq_b), &wo_a.iter().map(sh).collect::>(), sh(wo_b), kc.len(), idx) { return None; } + dev::get().and_then(|g| g.lock().unwrap().ds_attn_on(d, key, new, kc, idx, qr, wq_b, wo_a, wo_b, cs, nh, w, vd, scale)) +} +/// Whether the shapes of `ds_attn_on` are ones its kernels index safely: (rows, cols) of wq_b, each wo_a group and +/// wo_b; `n_rot` rope dims (even, at most `hd`); key rows of `w` = at least `vd` + `nh` halves, `vd` >= `hd`; every +/// `idx` a row of `kc_len` halves. +pub fn chain_ok(nh: usize, hd: usize, w: usize, vd: usize, n_rot: usize, qr: usize, wq_b: (usize, usize), wo_a: &[(usize, usize)], + wo_b: (usize, usize), kc_len: usize, idx: &[u32]) -> bool { + let og = wo_a.len(); + if nh == 0 || hd == 0 || og == 0 || n_rot > hd || n_rot % 2 != 0 || hd > vd || vd + nh > w || (nh * hd) % og != 0 { return false; } + let (gsz, r) = (nh * hd / og, wo_a[0].0); + wq_b == (nh * hd, qr) && wo_a.iter().all(|&g| g == (r, gsz)) && wo_b.1 == og * r && !idx.is_empty() + && kc_len % w == 0 && idx.iter().all(|&i| (i as usize) < kc_len / w) +} +/// `Dev::pick`: move the plain weights on to the next GPU unless `len` more bytes fit on the current one (a whole +/// layer before loading it, so its matrices share a GPU). +pub fn dev_pick(len: usize) { if let Some(d) = dev::get() { d.lock().unwrap().pick(len); } } /// `dev::free`, for a server that changes models. pub fn dev_free() { dev::free() } +/// `dev::set_margin`: the VRAM each device keeps free beyond the weight budget (`--vram-margin`, in bytes, in +/// `--device` order). +pub fn dev_set_margin(margins: &[usize]) { dev::set_margin(margins) } +/// `dev::set_margin` from a per-device margin list (`--vram-margin`, MB), for the models whose forward keeps its own +/// VRAM state outside the budget (Inkling 2). +pub fn dev_set_margin_mb(margins: &[usize]) { dev::set_margin(&margins.iter().map(|mb| mb << 20).collect::>()) } +/// The largest per-device `--vram-margin`, for the buffers a forward allocates after the weight budget (Inkling 2's +/// expert pool leaves that much free on GPU 0). +pub fn dev_margin() -> usize { dev::max_margin() } /// The first GPU's backend, device name and (used, total) bytes of memory, for the server's side panel. pub fn dev_stats() -> Option<(&'static str, String, Option<(u64, u64)>)> { dev::get().map(|d| { let b = &d.lock().unwrap().parts[0].be; (b.name(), b.device(), b.mem_info().ok().map(|(f, t)| ((t - f) as u64, t as u64))) }) @@ -647,10 +1642,23 @@ impl<'a> Mat<'a> { Ok(Mat { data, ty, rows, cols, cpu, gpu, scale }) } + /// Load a tensor strictly on the host mmap (never uploaded to VRAM, e.g. `token_embd.weight` read only via `row_into`). + pub fn load_host(g: &'a Gguf, name: &str) -> anyhow::Result { + let t: &TensorInfo = g.tensors.get(name).ok_or_else(|| anyhow::anyhow!("missing tensor {name}"))?; + let ty = GgmlType::from_u32(t.ty)?; + let cols = t.dims[0] as usize; + let rows = t.dims[1..].iter().product::() as usize; + let cpu = name.contains("_exps"); + let data = g.bytes(t); + let scale = name.strip_suffix(".weight").and_then(|stem| g.tensors.get(&format!("{stem}.scale"))) + .filter(|st| st.ty == 0).and_then(|st| g.bytes(st).try_into().ok()).map_or(1.0, f32::from_le_bytes); + Ok(Mat { data, ty, rows, cols, cpu, gpu: None, scale }) + } + /// Like `load` for a matrix used as `n` row groups (grouped output projection): each group gets its own VRAM copy. pub fn load_groups(g: &'a Gguf, name: &str, n: usize) -> anyhow::Result { - let mut m = Self::load(g, name)?; - m.gpu = None; + // From the host: `load` would upload the whole matrix too, a second copy no one reads. + let mut m = Self::load_host(g, name)?; if let Some(d) = dev::get() { let (gr, rb) = (m.rows / n, m.ty.row_bytes(m.cols as u64)); let mut d = d.lock().unwrap(); @@ -676,8 +1684,15 @@ impl<'a> Mat<'a> { /// `expert` that never overwrites a VRAM slot when `evict` is false: an expert that is not resident and has no /// free room comes back host-only, for the CPU. pub fn expert_opt(&self, e: usize, n_expert: usize, evict: bool) -> Mat<'a> { + self.expert_opt_in(e, n_expert, evict, self, 0) + } + + /// `expert_opt` where the GPU is chosen per `key` (a layer's gate_up tensor) instead of per tensor, so the gate_up + /// and down experts of a layer share a GPU: `extra` is the bytes of the other tensors of the group. + pub fn expert_opt_in(&self, e: usize, n_expert: usize, evict: bool, key: &Mat<'a>, extra: usize) -> Mat<'a> { let mut m = self.expert_host(e, n_expert); - m.gpu = dev::get().and_then(|d| d.lock().unwrap().expert(m.data, m.ty, m.rows, m.cols, m.scale, evict)); + let group = (key.data.as_ptr() as usize, key.data.len() + extra); + m.gpu = dev::get().and_then(|d| d.lock().unwrap().expert_grouped(group, m.data, m.ty, m.rows, m.cols, m.scale, evict)); m } @@ -698,9 +1713,16 @@ impl<'a> Mat<'a> { pub fn host_only(&self) -> bool { self.gpu.is_none() || self.gpu == Some(dev::STAGED) } /// Ask the kernel to read expert e's pages now (madvise WILLNEED), so all selected experts of a layer queue on the SSD together. + /// One madvise reads at most one readahead window of its range (256 KB on the desktop, a quarter of a GigaChat 4 + /// expert matrix); the rest comes in a page fault at a time. `prefetch_expert_whole` asks for all of it. + pub fn prefetch_expert(&self, e: usize, n_expert: usize) { self.prefetch(e, n_expert, false) } + + /// `prefetch_expert` of the whole matrix, in `weights::will_need` steps: a cold GigaChat 4 prompt chunk took 12.3 + /// to 13.4 s instead of 18.9 to 19.7. A decode step calls it too often for that (its decode lost 5%). + pub fn prefetch_expert_whole(&self, e: usize, n_expert: usize) { self.prefetch(e, n_expert, true) } + #[cfg(target_os = "linux")] - pub fn prefetch_expert(&self, e: usize, n_expert: usize) { - unsafe extern "C" { fn madvise(addr: *mut std::ffi::c_void, len: usize, advice: i32) -> i32; } + fn prefetch(&self, e: usize, n_expert: usize, whole: bool) { // A model that fits in RAM is read into the page cache at start (`weights::preload`) and stays there: once // those reads are queued the call would only cost its page-table walk, about 4 us per expert matrix. if crate::weights::preloaded() { return; } @@ -709,12 +1731,14 @@ impl<'a> Mat<'a> { // other experts out of the page cache. if dev::get().is_some_and(|d| d.lock().unwrap().resident(&self.data[e * sz..])) { return; } let a = self.data[e * sz..].as_ptr() as usize; + if whole { return crate::weights::will_need(a, sz); } + unsafe extern "C" { fn madvise(addr: *mut std::ffi::c_void, len: usize, advice: i32) -> i32; } let start = a & !4095; unsafe { madvise(start as *mut std::ffi::c_void, a + sz - start, 3) }; } /// No madvise outside Linux (the MSVC linker has no such symbol, issue #21): the pages are read when touched. #[cfg(not(target_os = "linux"))] - pub fn prefetch_expert(&self, _e: usize, _n_expert: usize) {} + fn prefetch(&self, _e: usize, _n_expert: usize, _whole: bool) {} pub fn row_into(&self, r: usize, out: &mut [f32]) { let rb = self.ty.row_bytes(self.cols as u64); @@ -754,6 +1778,22 @@ impl<'a> Mat<'a> { }); return; } + if self.ty == GgmlType::F32 { + let calc = |(r, o): (usize, &mut f32)| { + let bytes = &self.data[r * rb..(r + 1) * rb]; + let mut s = 0.0f32; + for (chunk, &xv) in bytes.chunks_exact(4).zip(x) { + s += f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) * xv; + } + *o = s * sc; + }; + if self.rows <= 64 { + y.iter_mut().enumerate().for_each(calc); + } else { + y.par_iter_mut().enumerate().for_each(calc); + } + return; + } let xq = q8_roundtrip(self.ty, self.cpu, x); let x = &xq[..]; y.par_iter_mut().enumerate().for_each_init( @@ -806,3 +1846,4 @@ pub fn vec_f32(g: &Gguf, name: &str) -> anyhow::Result> { } Ok(v) } + diff --git a/src/deepseek/mod.rs b/src/deepseek/mod.rs index d7ca984d..014e43cf 100644 --- a/src/deepseek/mod.rs +++ b/src/deepseek/mod.rs @@ -179,7 +179,8 @@ impl DsConfig { }; ensure!(c.hc_n == 4, "only 4 hyper-connection streams are supported"); ensure!(c.clamp_exp.len() >= n_layer && c.clamp_shexp.len() >= n_layer, "swiglu clamp arrays too short"); - ensure!(c.n_head % c.o_groups == 0 && c.idx_top_k > 0, "bad attention dimensions"); + ensure!(c.n_head > 0 && c.o_groups > 0 && c.n_head % c.o_groups == 0 && c.idx_top_k > 0, "bad attention dimensions"); + ensure!(c.head_dim > 0 && c.n_rot <= c.head_dim && c.n_rot % 2 == 0, "rope dims must be even and at most the head width"); Ok(c) } diff --git a/src/deepseek/ops.rs b/src/deepseek/ops.rs index a4d20da7..82a8ec08 100644 --- a/src/deepseek/ops.rs +++ b/src/deepseek/ops.rs @@ -40,7 +40,7 @@ impl Rope { } /// (cos, sin) for pair index i (dim 2i,2i+1) at position pos. Net mscale is 1 (attn factor cancels). - fn cs(&self, pos: f32, i: usize) -> (f32, f32) { + pub(crate) fn cs(&self, pos: f32, i: usize) -> (f32, f32) { let extrap = pos * self.base.powf(-2.0 * i as f32 / self.n_dims as f32); let interp = self.freq_scale * extrap; let theta = if self.ext != 0.0 { @@ -175,6 +175,24 @@ pub fn swiglu_clamp(gate: f32, up: f32, limit: f32) -> f32 { mod tests { use super::*; + #[test] + fn chained_attention_rejects_bad_shapes() { + use crate::deepseek::mat::chain_ok; + // nh 2, hd 8, vd 64, w 66, 4 rope dims, q_lora 16, 2 output groups of rank 4, 3 cached rows. + let (nh, hd, vd, w) = (2, 8, 64, 66); + let ok = |n_rot, wq_b, wo_a: &[(usize, usize)], wo_b, idx: &[u32]| chain_ok(nh, hd, w, vd, n_rot, 16, wq_b, wo_a, wo_b, 3 * w, idx); + let ga = [(4, 8), (4, 8)]; + assert!(ok(4, (16, 16), &ga, (32, 8), &[0, 2])); + assert!(!ok(10, (16, 16), &ga, (32, 8), &[0]), "more rope dims than the head"); + assert!(!ok(3, (16, 16), &ga, (32, 8), &[0]), "odd rope dims"); + assert!(!ok(4, (18, 16), &ga, (32, 8), &[0]), "wq_b rows not nh * hd"); + assert!(!ok(4, (16, 12), &ga, (32, 8), &[0]), "wq_b cols not the query rank"); + assert!(!ok(4, (16, 16), &[(4, 8), (4, 6)], (32, 8), &[0]), "a group of the wrong width"); + assert!(!ok(4, (16, 16), &ga, (32, 6), &[0]), "wo_b cols not og * r"); + assert!(!ok(4, (16, 16), &ga, (32, 8), &[3]), "key row past the cache"); + assert!(!chain_ok(nh, hd, nh + 1, vd, 4, 16, (16, 16), &ga, (32, 8), 3 * w, &[0]), "rows narrower than vd + nh"); + } + #[test] fn rope_roundtrip_and_plain() { let r = Rope::new(10000.0, 1.0, 0.0, 64, 0, 32.0, 1.0); diff --git a/src/expert_cache.rs b/src/expert_cache.rs index 87dbb9fb..31352192 100644 --- a/src/expert_cache.rs +++ b/src/expert_cache.rs @@ -25,8 +25,36 @@ pub struct LayerExperts { struct Pool { buf: Buf, slot_bytes: usize, owner: Vec<(usize, usize)> } +/// Slots for `frac` of a pool's `k` experts, at least `min` and at most `k`. +fn pool_slots(frac: f64, k: usize, min: usize) -> usize { ((frac * k as f64) as usize).max(min).min(k) } + +/// Pools for `frac` of each spec's experts, at least `min` slots each. The budget comes from the driver's free-memory +/// estimate, which can be more than it will allocate (AMD's Windows driver): on a failed allocation, free the pools +/// and try a tenth less. +fn alloc_pools(gpu: &dyn Backend, specs: &[(usize, usize)], mut frac: f64, min: usize) -> anyhow::Result> { + let total: usize = specs.iter().map(|(b, k)| b * k).sum(); + loop { + let r = specs.iter().map(|&(slot_bytes, k)| { + let slots = pool_slots(frac, k, min); + Ok(Pool { buf: gpu.zeros::(slots * slot_bytes)?, slot_bytes, owner: Vec::with_capacity(slots) }) + }).collect::>>(); + match r { + Ok(p) => return Ok(p), + Err(e) if frac > 0.01 => { + crate::say!("expert slots: {e:#}; trying {:.0} MB", 0.9 * frac * total as f64 / 1048576.0); + frac *= 0.9; + } + Err(e) => return Err(e), + } + } +} + pub struct ExpertCache { pools: Vec, + /// (slot bytes, experts) of each pool, to allocate it again in `resize`. + specs: Vec<(usize, usize)>, + /// Bytes and slots of the pools at the load: `resize` never grows past them. + full: (usize, usize), layers: Vec>, n_expert: usize, /// Decayed routing counts, [layer * n_expert + expert]: they forget in a few hundred tokens, for `adapt`. @@ -51,8 +79,10 @@ pub struct ExpertCache { /// Where routing profiles and calibration files live: `$XDG_CACHE_HOME`, `%LOCALAPPDATA%` on Windows, else /// `~/.cache`. pub fn cache_dir() -> PathBuf { - std::env::var_os("XDG_CACHE_HOME").or_else(|| std::env::var_os("LOCALAPPDATA")).map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".cache")) + // An empty variable is unset, not the working folder. + let env = |k| std::env::var_os(k).filter(|v| !v.is_empty()); + env("XDG_CACHE_HOME").or_else(|| env("LOCALAPPDATA")).map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env("HOME").unwrap_or_default()).join(".cache")) .join("rusting_strata") } @@ -91,7 +121,7 @@ impl ExpertCache { layers.push(Some((pid, mats))); } let total: usize = pool_specs.iter().map(|(b, k)| b * k).sum(); - let mut frac = (budget as f64 / total.max(1) as f64).min(1.0); + let frac = (budget as f64 / total.max(1) as f64).min(1.0); let profile = std::env::var_os("STRATA_FIXED_EXPERTS").is_none().then(|| profile_path(m)); let counts = profile.as_ref().and_then(|p| std::fs::read(p).ok()) .filter(|b| b.len() >= 4 * c.n_layer * n) @@ -107,22 +137,7 @@ impl ExpertCache { let steady = (c.n_expert_used * 8) as f32 / (1.0 - KEEP); let counts: Vec = long.chunks(n.max(1)).flat_map(|l| { let s = l.iter().sum::(); l.iter().map(move |x| if s > 0.0 { x * steady / s } else { 0.0 }) }).collect(); - // The budget comes from the driver's free-memory estimate, which can be more than it will allocate (AMD's - // Windows driver): on a failed allocation, free the pools and try a tenth less. - let pools = loop { - let r = pool_specs.iter().map(|&(slot_bytes, k)| { - let slots = (frac * k as f64) as usize; - Ok(Pool { buf: gpu.zeros::(slots * slot_bytes)?, slot_bytes, owner: Vec::with_capacity(slots) }) - }).collect::>>(); - match r { - Ok(p) => break p, - Err(e) if frac > 0.01 => { - crate::say!("expert slots: {e:#}; trying {:.0} MB", 0.9 * frac * total as f64 / 1048576.0); - frac *= 0.9; - } - Err(e) => return Err(e), - } - }; + let pools = alloc_pools(gpu, &pool_specs, frac, 0)?; let mut out: Vec> = Vec::new(); for l in &layers { out.push(match l { @@ -134,31 +149,64 @@ impl ExpertCache { }); } let prompt = vec![0.0; counts.len()]; - let mut cache = ExpertCache { pools, layers: out, n_expert: n, counts, long, prompt, steady, profile, recorded: false, swaps: 0 }; - // Initial fill: hottest first by profile; ties (and no profile) keep layer order. - let mut order: Vec = (0..n_layers * n).filter(|&i| cache.layers[i / n].is_some()).collect(); - order.sort_by(|&a, &b| cache.counts[b].total_cmp(&cache.counts[a]).then(a.cmp(&b))); + let mut cache = ExpertCache { pools, specs: pool_specs, full: (0, 0), layers: out, n_expert: n, counts, long, prompt, steady, profile, recorded: false, swaps: 0 }; + cache.fill(m, gpu)?; + cache.full = (cache.slot_bytes_total(), cache.slots()); + Ok(cache) + } + + /// Fill the empty pools, hottest expert first by `counts` (the profile at the load); ties (and no profile) keep + /// layer order. + fn fill(&mut self, m: &Model, gpu: &dyn Backend) -> anyhow::Result<()> { + let n = self.n_expert; + let mut order: Vec = (0..self.layers.len() * n).filter(|&i| self.layers[i / n].is_some()).collect(); + order.sort_by(|&a, &b| self.counts[b].total_cmp(&self.counts[a]).then(a.cmp(&b))); // The experts that fit, read ahead in upload order. - let mut room: Vec = cache.pools.iter().map(|p| p.buf.len() / p.slot_bytes).collect(); - let order: Vec = order.into_iter().filter(|&i| { let r = &mut room[cache.layers[i / n].as_ref().unwrap().pool]; *r > 0 && { *r -= 1; true } }).collect(); + let mut room: Vec = self.pools.iter().map(|p| p.buf.len() / p.slot_bytes).collect(); + let order: Vec = order.into_iter().filter(|&i| { let r = &mut room[self.layers[i / n].as_ref().unwrap().pool]; *r > 0 && { *r -= 1; true } }).collect(); let pre = crate::weights::Prefetch::start(); let mut rs = Vec::new(); for &i in &order { for name in MATS { let t = m.w.layer(i / n, name)?.expert(i % n, n); rs.push((t.data.as_ptr() as usize, t.data.len())); } } pre.send(rs); - for i in order { - let p = cache.layers[i / n].as_ref().unwrap().pool; - let slot = cache.pools[p].owner.len(); - cache.pools[p].owner.push((i / n, i % n)); - cache.place(m, gpu, i / n, i % n, slot, false)?; + // The hottest two thirds leave the page cache once on the card (`drop_cached`): loading a model larger than + // RAM otherwise pushes out the experts the last prompt read, and the next prompt reads them from disk again. + // The coldest third stays cached, since `swap` moves those off the card and decode then misses on them. + // Gyro-S 54.5 GB, 30 GB RAM, second process after a cold one: first pp512 5.5 s -> 1.6 s, decode unchanged. + let hot = order.len() * 2 / 3; + for (k, i) in order.into_iter().enumerate() { + let p = self.layers[i / n].as_ref().unwrap().pool; + let slot = self.pools[p].owner.len(); + self.pools[p].owner.push((i / n, i % n)); + self.place(m, gpu, i / n, i % n, slot, false, k < hot)?; } - for il in 0..cache.layers.len() { cache.sync_table(gpu, il)?; } - Ok(cache) + for il in 0..self.layers.len() { self.sync_table(gpu, il)?; } + Ok(()) + } + + /// Give the pools `budget` bytes, between one slot a pool and their size at the load, and fill them again with + /// the hottest experts by the routing counts; the others run on the CPU. The old pools are freed before the new + /// ones are allocated, so another program can have their VRAM. Graphs captured before hold the old addresses: the + /// caller clears them. Returns whether the slots changed. + pub fn resize(&mut self, m: &Model, gpu: &dyn Backend, budget: usize) -> anyhow::Result { + let total: usize = self.specs.iter().map(|(b, k)| b * k).sum(); + let frac = (budget.min(self.full.0) as f64 / total.max(1) as f64).min(1.0); + let want: Vec = self.specs.iter().map(|&(_, k)| pool_slots(frac, k, 1)).collect(); + if want.iter().zip(&self.pools).all(|(&w, p)| w == p.buf.len() / p.slot_bytes) { return Ok(false); } + for l in self.layers.iter_mut().flatten() { l.table.fill(-1); } + self.pools.clear(); + self.pools = alloc_pools(gpu, &self.specs, frac, 1)?; + self.fill(m, gpu)?; + Ok(true) } + /// Slots in the pools now, and their bytes and slots at the load. + pub fn slots(&self) -> usize { self.pools.iter().map(|p| p.buf.len() / p.slot_bytes).sum() } + pub fn full(&self) -> (usize, usize) { self.full } + /// Copy expert `e` of layer `il` into `slot` of its pool and point the table at it. - fn place(&mut self, m: &Model, gpu: &dyn Backend, il: usize, e: usize, slot: usize, sync: bool) -> anyhow::Result<()> { + fn place(&mut self, m: &Model, gpu: &dyn Backend, il: usize, e: usize, slot: usize, sync: bool, drop: bool) -> anyhow::Result<()> { let lx = self.layers[il].as_mut().unwrap(); let pool = &mut self.pools[lx.pool]; for (name, mat) in MATS.iter().zip(&lx.mats) { @@ -166,7 +214,7 @@ impl ExpertCache { let o = slot * pool.slot_bytes + mat.off; debug_assert_eq!(t.data.len(), mat.bytes); gpu.htod(t.data, &pool.buf, o)?; - crate::weights::cold(t.data); + if drop { crate::weights::drop_cached(t.data) } else { crate::weights::cold(t.data) } } lx.table[e] = slot as i32; if sync { self.sync_table(gpu, il)?; } @@ -178,7 +226,8 @@ impl ExpertCache { Ok(()) } - pub fn layer(&self, il: usize) -> Option<&LayerExperts> { self.layers[il].as_ref() } + // A part of a --device split holds layers up to the end of its range only; later layers have no experts here. + pub fn layer(&self, il: usize) -> Option<&LayerExperts> { self.layers.get(il)?.as_ref() } pub fn base(&self, lx: &LayerExperts) -> (u64, usize) { let p = &self.pools[lx.pool]; (p.buf.addr(), p.slot_bytes) @@ -227,26 +276,76 @@ impl ExpertCache { } /// After a prefill: the prompt's routing joins `counts`, scaled back to steady-state size, and the placement - /// follows. A long prompt still decides the placement the reply starts with, but its thousands of tokens no - /// longer outweigh the reply's: the reply's own routing moves the placement as fast as in any other run. - pub fn settle(&mut self, m: &Model, gpu: &dyn Backend) -> anyhow::Result<()> { - let n = self.n_expert; - if self.profile.is_some() { - for il in 0..self.layers.len() { - let r = il * n..(il + 1) * n; - for i in r.clone() { self.counts[i] += self.prompt[i]; } - let sum = self.counts[r.clone()].iter().sum::(); - if sum > self.steady { for i in r { self.counts[i] *= self.steady / sum; } } - } - self.swap(m, gpu, usize::MAX)?; + /// follows. A long prompt still decides the placement the reply starts with. + /// + /// `keep_decode` (serve): the prompt blends in gently (25% of steady state) and swaps at most 10% of each pool's + /// slots, then `counts` go back to what decode had learned, so a turn's tool output neither flushes the last + /// reply's hot set nor erases its counts (#139). `STRATA_PREFILL_PROTECT=1` turns the gentle blend on elsewhere, + /// `=0` off, `strict` swaps nothing. Not the default outside serve: on Qwen3.6-35B-A3B (8k prompt, 128-token + /// reply, cold start) it lowered the reply's expert hit rate from 83% to 76%. + pub fn settle(&mut self, m: &Model, gpu: &dyn Backend, keep_decode: bool) -> anyhow::Result<()> { + let mode = std::env::var("STRATA_PREFILL_PROTECT").unwrap_or_default(); + if self.profile.is_some() && !mode.eq_ignore_ascii_case("strict") { + let protect = if mode.is_empty() { keep_decode } else { mode != "0" }; + let kept = keep_decode.then(|| self.counts.clone()); + self.blend_prompt(protect); + let max_swaps = if protect { + let min_pool = self.pools.iter().map(|p| p.owner.len()).filter(|&l| l > 0).min().unwrap_or(0); + (min_pool / 10).max(1) + } else { + usize::MAX + }; + self.swap(m, gpu, max_swaps)?; + if let Some(k) = kept { self.counts = k; } } self.prompt.fill(0.0); Ok(()) } - /// Forget the short-term routing counts: the prompt's thousands of tokens no longer outweigh the reply's first - /// tokens, so `adapt` follows the text being decoded instead of the prompt that produced it. - pub fn reset_counts(&mut self) { self.counts.fill(0.0); } + /// `settle`'s blend: per layer, add the prompt's routing (capped at 25% of steady state when `protect`) to + /// `counts` and scale the layer back to steady-state size. + fn blend_prompt(&mut self, protect: bool) { + let n = self.n_expert; + let prompt_cap = if protect { 0.25 * self.steady } else { f32::INFINITY }; + for il in 0..self.layers.len() { + let r = il * n..(il + 1) * n; + let psum: f32 = self.prompt[r.clone()].iter().sum(); + let pscale = if psum > prompt_cap { prompt_cap / psum } else { 1.0 }; + for i in r.clone() { self.counts[i] += self.prompt[i] * pscale; } + let sum = self.counts[r.clone()].iter().sum::(); + if sum > self.steady { for i in r { self.counts[i] *= self.steady / sum; } } + } + } + + pub fn cold_experts(&self, il: usize) -> Vec { + let Some(lx) = self.layer(il) else { return Vec::new(); }; + let base = il * self.n_expert; + let score = |e: usize| self.counts[base + e] + 0.01 * self.long[base + e]; + let mut ids: Vec<_> = (0..self.n_expert).filter(|&e| lx.table[e] < 0).collect(); + ids.sort_unstable_by(|&a, &b| score(b).total_cmp(&score(a)).then(a.cmp(&b))); + ids + } + + /// Top `top_k` hottest non-resident experts of `next_il` (by short-term `counts`, falling back to `long`), + /// returned as `(ptr, len)` mmap byte ranges for asynchronous NVMe read-ahead (`Prefetch::send`) while layer + /// `il` computes on the GPU. + pub fn cold_ranges_for_next(&self, m: &Model, next_il: usize, top_k: usize) -> Vec<(usize, usize)> { + let Some(lx) = self.layers.get(next_il).and_then(|l| l.as_ref()) else { return Vec::new() }; + let n = self.n_expert; + let base = next_il * n; + let mut cands: Vec = (0..n).filter(|&e| lx.table[e] < 0).collect(); + if cands.is_empty() { return Vec::new(); } + let score = |e: usize| self.counts[base + e] + 0.01 * self.long[base + e]; + smallest(&mut cands, top_k, |&a, &b| score(b).total_cmp(&score(a))); + let mut rs = Vec::with_capacity(cands.len() * 3); + for (name, mat) in MATS.iter().zip(&lx.mats) { + let Ok(w) = m.w.layer(next_il, name) else { continue }; + for &e in &cands { + rs.push((w.data.as_ptr() as usize + e * mat.bytes, mat.bytes)); + } + } + rs + } /// Decay counts, then per pool swap up to `max_swaps` cold residents for clearly hotter missed experts. pub fn adapt(&mut self, m: &Model, gpu: &dyn Backend, max_swaps: usize) -> anyhow::Result<()> { @@ -271,7 +370,7 @@ impl ExpertCache { let (oil, oe) = self.pools[p].owner[slot]; self.layers[oil].as_mut().unwrap().table[oe] = -1; self.pools[p].owner[slot] = (h / n, h % n); - self.place(m, gpu, h / n, h % n, slot, false)?; + self.place(m, gpu, h / n, h % n, slot, false, false)?; touched.extend([oil, h / n]); self.swaps += 1; } @@ -323,6 +422,17 @@ fn smallest(v: &mut Vec, k: usize, cmp: impl Fn(&usize, &usize) -> std::c mod tests { use super::*; + /// `resize` keeps one slot a pool however small the budget (`min` 1), and the load never goes past a pool's + /// experts; `new` (`min` 0) rounds down as before. + #[test] + fn pool_slots_keep_the_floor_and_the_ceiling() { + assert_eq!(pool_slots(0.0, 256, 1), 1); + assert_eq!(pool_slots(0.0, 256, 0), 0); + assert_eq!(pool_slots(0.5, 255, 1), 127); + assert_eq!(pool_slots(1.0, 256, 1), 256); + assert_eq!(pool_slots(2.0, 256, 1), 256); + } + /// A cache over `layers` MoE layers of `n` experts with one pool of `layers * n` slots of 128 bytes; the first /// `resident` experts of every layer are placed. No model and no device: the placement flags are the whole state /// the fast path and `save_profile` read. @@ -334,7 +444,7 @@ mod tests { table: vec![-1; n], table_dev: Buf::new(0, 4 * n, ()), })).collect(); - let mut c = ExpertCache { pools: vec![pool], layers: ls, n_expert: n, counts: vec![0.0; layers * n], + let mut c = ExpertCache { pools: vec![pool], specs: vec![(128, layers * n)], full: (layers * n * 128, layers * n), layers: ls, n_expert: n, counts: vec![0.0; layers * n], long: vec![0.0; layers * n], prompt: vec![0.0; layers * n], steady: 1.0, profile, recorded: false, swaps: 0 }; for il in 0..layers { for e in 0..resident { @@ -400,4 +510,17 @@ mod tests { let longer = profile_update(&existing, 4, &[1.0; 12], &[true, false, true]); assert_eq!(longer.len(), 12, "a longer profile grows without losing the file's counts"); } + + #[test] + fn prefill_protect_blends_gently_and_preserves_hot_decode_counts() { + let mut c = fake(1, 4, 2, None); + // Hot decode experts 0 and 1, then a huge prompt hitting cold experts 2 and 3. + c.counts = vec![40.0, 40.0, 0.0, 0.0]; + c.steady = 80.0; + c.record_prompt(0, &[2, 2, 2, 2, 3, 3, 3, 3]); + // Protected, the prompt adds at most 0.25 * steady; the layer is scaled back to steady, the decode set stays hotter. + c.blend_prompt(true); + let s: f32 = c.counts.iter().sum(); + assert!((s - 80.0).abs() < 1e-3 && c.counts[0] > 8.0 * c.counts[2] && c.counts[2] > 0.0, "{:?}", c.counts); + } } diff --git a/src/gemma4/forward.rs b/src/gemma4/forward.rs index e55e6ba2..bd292f7b 100644 --- a/src/gemma4/forward.rs +++ b/src/gemma4/forward.rs @@ -279,7 +279,19 @@ impl<'a> Gemma4Model<'a> { if k == 0 { return vec![]; } for (g, d, _) in &cpu_sel { g.prefetch_expert(0, 1); d.prefetch_expert(0, 1); } use crate::cpu_moe::{int_dot, quantize_q8k}; - let (dgu, ddn) = (int_dot(cpu_sel[0].0.ty).unwrap(), int_dot(cpu_sel[0].1.ty).unwrap()); + let (Some(dgu), Some(ddn)) = (int_dot(cpu_sel[0].0.ty), int_dot(cpu_sel[0].1.ty)) else { + // An expert type with no integer kernel (BF16 experts of a UD-Q8_K_XL file): each expert through + // Mat::matvec, which takes every type. + return cpu_sel.iter().flat_map(|(g, d, _)| { + let mut gu = vec![0f32; 2 * nf]; + g.matvec(&moe_in, &mut gu); + let mut a = vec![0f32; nf]; + act(&gu, nf, &mut a); + let mut o = vec![0f32; n]; + d.matvec(&a, &mut o); + o + }).collect(); + }; let xq = quantize_q8k(&moe_in); let mut gu = vec![0f32; k * 2 * nf]; gu.par_chunks_mut(16).enumerate().for_each(|(c, ys)| for (j, v) in ys.iter_mut().enumerate() { @@ -427,6 +439,7 @@ impl<'a> Gemma4Model<'a> { } let x: Vec = c.iter().flat_map(|&(id, e)| match e { Some(e) => e.to_vec(), None => self.embed(id) }).collect(); self.prefill_chunk(&c.iter().map(|c| c.0).collect::>(), x); + crate::term::prefilled(c.len()); } match emb { Some(e) => self.step_embed_opt(id, e, true), None => self.step_opt(id, true) } } diff --git a/src/gemma4/mod.rs b/src/gemma4/mod.rs index a881e630..76ff753c 100644 --- a/src/gemma4/mod.rs +++ b/src/gemma4/mod.rs @@ -101,7 +101,7 @@ fn strip_thinking(text: &str) -> String { /// GPU on, the weights in 90% of the free VRAM (a fixed 11 GB overcommitted a 12 GB card that other programs /// use, and left a larger card half empty). -fn gpu_defaults() { +pub fn gpu_defaults() { if std::env::var_os("STRATA_G4_CPU").is_some() { return; } for (k, v) in [("STRATA_DS_GPU", "1"), ("STRATA_DS_GPU_FRACTION", "0.9"), ("STRATA_DS_NOEVICT", "1")] { if std::env::var_os(k).is_none() { unsafe { std::env::set_var(k, v) } } @@ -244,7 +244,7 @@ pub fn chat( if keep >= seq.len() { m.reset(); keep = 0; } let logits = feed(&mut m, &seq[keep..])?; let room = n.min(ctx - ids.len()); - let (out, _) = decode_greedy(&tok, &mut m, &stop, logits, room, &mut |t| { + let (out, _) = decode_greedy(&tok, &mut m, &stop, &mut None, logits, room, &mut |t| { print!("{t}"); let _ = std::io::stdout().flush(); true @@ -256,7 +256,7 @@ pub fn chat( } /// The chat of `rustingstrata serve` for gemma4 (see `serve::Own`): one request at a time, JSON or SSE. -/// Greedy only (sampling and stop strings are not applied); prompt + reply limited +/// Greedy only (sampling is not applied); prompt + reply limited /// to the trained context; KV reused when the prompt extends it. Images in messages are encoded with /// `mmproj` when given. pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a str, mmproj: Option<&std::path::Path>) -> anyhow::Result> { @@ -264,10 +264,13 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a st use std::io::Write; gpu_defaults(); let mut m = forward::Gemma4Model::new(g)?; + crate::serve::warm_up(tok, |ids| { m.prefill(ids); m.reset(); })?; let projector = mmproj.map(crate::vision::VisionProjector::open).transpose()?; let stop = stop_ids(tok); let ctx = crate::ctx_limit(m.cfg.n_ctx_train); Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| { + let mut lim = crate::grammar::Constraint::new(q, tok)?; + if let Some(l) = &mut lim { l.eos.extend(&stop); } anyhow::ensure!(q.tools.is_empty() && !q.messages.iter().any(|m| m.role == "tool"), "tools are not supported for gemma4"); let mut grids = vec![]; let mut embs = vec![]; @@ -284,27 +287,47 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a st let images = if grids.is_empty() { None } else { Some((&grids[..], &embs[..])) }; let seq = prompt_seq(&tok, &chat_prompt(&view, q.think.unwrap_or(false)), images)?; let ids: Vec = seq.iter().map(|(id, _)| *id).collect(); - anyhow::ensure!(ids.len() < ctx, "prompt is {} tokens, the limit is {}", ids.len(), ctx - 1); + anyhow::ensure!(ids.len() < ctx, "{}", crate::serve::too_long(ids.len(), ctx - 1)); let t = std::time::Instant::now(); let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; // A failed feed leaves part of the prompt in the cache, so the next request starts over. - let logits = match feed(&mut m, &seq[keep..]) { Ok(l) => l, Err(e) => { m.reset(); return Err(e) } }; + if q.stream && !q.head_sent { let _ = write!(c, "{}", crate::serve::sse_head(c)); } + let logits = match crate::serve::alive(c, q.stream, || feed(&mut m, &seq[keep..])) { + Ok(l) => l, + Err(e) => { + m.reset(); + // The head of a stream is out, so the error is its last line (a response with a status cannot follow). + if !q.stream { return Err(e); } + crate::say!("request: {e:#}"); + let _ = write!(c, "data: {}\n\n", json!({"error": {"message": format!("{e:#}"), "type": "server_error"}})); + return Ok(crate::serve::Done { prompt: ids.len(), cached: keep, completion: 0, prefill_s: t.elapsed().as_secs_f64(), finish: "error", drafts: None }); + } + }; let prefill_s = t.elapsed().as_secs_f64(); - let n = q.max_tokens.unwrap_or(256).min(ctx - ids.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let n = q.max_tokens.unwrap_or(usize::MAX).min(ctx - ids.len()); let stream = q.stream; let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); - let (out, done) = decode_greedy(&tok, &mut m, &stop, logits, n, &mut |t| { - !stream || t.is_empty() || write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() + let mut hold = crate::chat::Hold::new(false, q.stop.clone()); + // `decode_greedy` finishes with "stop" when the callback ends the reply. + let (out, done) = decode_greedy(&tok, &mut m, &stop, &mut lim, logits, n, &mut |t| { + let t = hold.push(t); + (!stream || t.is_empty() || write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok()) && !hold.stopped }); + let d = crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done, drafts: None }; + let timings = d.timings(t); + let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), "prompt_tokens_details": {"cached_tokens": keep}}); if stream { - let _ = write!(c, "data: {}\n\ndata: [DONE]\n\n", chunk(json!({}), Some(done))); + if !hold.rest().is_empty() { let _ = write!(c, "data: {}\n\n", chunk(json!({"content": hold.rest()}), None)); } + let mut last = chunk(json!({}), Some(done)); + last["usage"] = usage; + last["timings"] = timings; + let _ = write!(c, "data: {last}\n\ndata: [DONE]\n\n"); } else { - let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": {"role": "assistant", "content": tok.decode(&out)?}, "finish_reason": done}], - "usage": {"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len()}}); + let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": {"role": "assistant", "content": hold.text}, "finish_reason": done}], + "usage": usage, "timings": timings}); crate::serve::send(c, "200 OK", "application/json", &b.to_string()); } - Ok(crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done }) + Ok(d) })) } @@ -319,15 +342,17 @@ fn decode_greedy( tok: &crate::tokenizer::Tokenizer, m: &mut forward::Gemma4Model, stop: &[u32], + lim: &mut Option, mut logits: Vec, n: usize, emit: &mut dyn FnMut(&str) -> bool, ) -> (Vec, &'static str) { let (mut out, mut shown, mut done) = (vec![], 0, "length"); for i in 0..n { - let next = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; + let next = crate::grammar::greedy(lim, &mut logits); if stop.contains(&next) { done = "stop"; break; } out.push(next); + crate::term::decoded(1); let s = tok.decode(&out).unwrap_or_default(); if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { let ok = emit(&s[shown..]); diff --git a/src/gguf.rs b/src/gguf.rs index 45332d0a..82f84a0c 100644 --- a/src/gguf.rs +++ b/src/gguf.rs @@ -3,10 +3,13 @@ use anyhow::{Context, bail}; use memmap2::Mmap; use std::collections::BTreeMap; -use std::path::Path; +use std::path::{Path, PathBuf}; use crate::quant::GgmlType; +/// The n-gram table tensor, shared by the split-shard fallback and `add_ple`. +const PLE_TENSOR: &str = "per_layer_token_embd.weight"; + #[derive(Clone, Debug)] pub enum Value { U8(u8), I8(i8), U16(u16), I16(i16), U32(u32), I32(i32), U64(u64), I64(i64), @@ -33,7 +36,18 @@ impl Value { #[derive(Clone, Debug)] pub struct TensorInfo { pub name: String, pub dims: Vec, pub ty: u32, pub offset: u64, /** Shard index. */ pub file: usize } +#[derive(Clone, Copy, Debug, Default)] +pub struct MoeOptions { + pub arena: bool, + pub pin: bool, + pub prefill_cpu: bool, + pub cpu_frac: Option, + pub host_share: i32, + pub no_fused: bool, +} + pub struct Gguf { + pub moe: MoeOptions, pub meta: BTreeMap, pub tensors: BTreeMap, /// Each shard's map and data offset (one entry unless the model is split). @@ -42,10 +56,19 @@ pub struct Gguf { /// A mapped model file. `weights::preload` counted its bytes; unmapping takes them off the count, so a file that was /// opened only to read its metadata, or the model before a switch, does not make the next one look too large for RAM. -struct Map(Mmap); +/// A mapped file; the bool says whether it counts toward the bytes `weights::fits_ram` compares with RAM. +struct Map(Bytes, PathBuf, bool); + +/// A model file's bytes: the file mapped, or a copy in anonymous memory (`arena`). +enum Bytes { File(Mmap), Anon(memmap2::MmapMut) } + +impl std::ops::Deref for Bytes { + type Target = [u8]; + fn deref(&self) -> &[u8] { match self { Bytes::File(m) => m, Bytes::Anon(m) => m } } +} impl Drop for Map { - fn drop(&mut self) { crate::weights::unmapped(self.0.len()); } + fn drop(&mut self) { if self.2 { crate::weights::unmapped(self.0.len()); } } } struct Cur<'a> { b: &'a [u8], p: usize } @@ -93,35 +116,167 @@ impl Gguf { /// Open a GGUF; for a split model (`split.count` > 1), pass the `-00001-of-0000N` shard and the others are /// opened from the same directory. pub fn open(path: &Path) -> anyhow::Result { - let mut g = Self::open_one(path, 0, true)?; + Self::open_with_moe_options(path, MoeOptions::default()) + } + + pub fn open_with_moe_options(path: &Path, moe: MoeOptions) -> anyhow::Result { + Self::open_with_ple(path, moe, std::env::var_os("STRATA_PLE").map(PathBuf::from)) + } + + /// `open_with_moe_options` with the `--ple` file given by the caller, not read from `STRATA_PLE`. + pub fn open_with_ple(path: &Path, moe: MoeOptions, ple: Option) -> anyhow::Result { + let mut g = Self::open_one(path, 0, true, moe)?; + let mut ple = ple; let n = g.meta.get("split.count").and_then(Value::as_u64).unwrap_or(1) as usize; if n > 1 { let name = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); let tag = format!("-00001-of-{n:05}.gguf"); let stem = name.strip_suffix(&tag).with_context(|| format!("{}: split model; open its first shard (*{tag})", path.display()))?; for i in 1..n { - let mut s = Self::open_one(&path.with_file_name(format!("{stem}-{:05}-of-{n:05}.gguf", i + 1)), i, true)?; + let mut p = path.with_file_name(format!("{stem}-{:05}-of-{n:05}.gguf", i + 1)); + // A missing shard and `--ple`: the file is that shard kept in another folder (unsloth's Qwen4 has the + // n-gram table alone in the last one), or another file with the table, and then the shard is skipped. + // One `--ple` file stands in for one shard; a second missing shard fails in `open_one` below. + let from_ple = !p.exists() && ple.is_some(); + if from_ple { p = ple.take().unwrap(); } + let mut s = Self::open_one(&p, g.files.len(), true, moe).with_context(|| format!("shard {} of {n} (pass a shard that is in another folder with --ple)", i + 1))?; + let no = s.meta.get("split.no").and_then(Value::as_u64); + if from_ple && no != Some(i as u64) && s.tensors.contains_key(PLE_TENSOR) { + crate::say!("shard {} of {n} is missing, skipped", i + 1); + g.take_ple(s, &p)?; + continue; + } + anyhow::ensure!(no.is_none_or(|k| k as usize == i), "{}: not shard {} of {n}", p.display(), i + 1); g.files.append(&mut s.files); for (k, t) in std::mem::take(&mut s.tensors) { anyhow::ensure!(g.tensors.insert(k.clone(), t).is_none(), "tensor {k} in two shards"); } } } + g.add_ple(path, ple)?; + // What a prompt streams, pinned so memory pressure cannot reclaim it. After `add_ple`, but the n-gram table, + // dense weights and any aux file's tensors are filtered out by name, so only the main file's experts lock. + // Only here: `arch` and `add_ple`'s probes open with read=false and never reach this. + // Not when the model exceeds RAM: locked pages could not be reclaimed, and `weights::cold` relies on that. + if std::env::var_os("STRATA_MLOCK_EXPERTS").is_some_and(|v| v != "0") { + if crate::weights::fits_ram() { g.mlock_experts(); } + else { crate::say!("expert pages: not locked, the model does not fit in RAM (STRATA_MLOCK_EXPERTS)"); } + } // The reads are queued by `weights::preload`, one call per file. Said here because nothing else shows it: the // pages are not mapped into the process, so its resident size does not grow. #[cfg(target_os = "linux")] - if crate::weights::fits_ram() { - crate::say!("page cache: reading {} MB of {} in the background (it shows as buff/cache, not as used memory)", - g.files.iter().map(|(m, _)| m.0.len()).sum::() >> 20, path.file_name().and_then(|s| s.to_str()).unwrap_or("the model")); + if crate::weights::fits_ram() && !crate::weights::net_fs(path) && { + // A command can open the file twice (once to look at the architecture): say it once per file. + static SAID: std::sync::Mutex> = std::sync::Mutex::new(None); + SAID.lock().unwrap_or_else(|e| e.into_inner()).replace(path.to_path_buf()).as_deref() != Some(path) + } { + crate::say!("reading {} MB of {} into the page cache in the background", + g.files.iter().filter(|(m, _)| m.2).map(|(m, _)| m.0.len()).sum::() >> 20, path.file_name().and_then(|s| s.to_str()).unwrap_or("the model")); } Ok(g) } + /// A Qwen3.8 Flash-Next file without its n-gram table (`-noPLE`) takes the table from another GGUF: `--ple` + /// (`STRATA_PLE`), else the one file next to the model whose name has "PLE" in it and that holds the table, as + /// llama.cpp's `--ple` and Strata load it (issue #127). + fn add_ple(&mut self, path: &Path, ple: Option) -> anyhow::Result<()> { + let Some(arch) = self.meta.get("general.architecture").and_then(Value::as_str) else { return Ok(()) }; + // Not a file that was already taken as a shard. + let given = ple.filter(|p| !self.files.iter().any(|(m, _)| &m.1 == p)); + if !self.meta.contains_key(&format!("{arch}.ple.heads_per_ngram")) || (self.tensors.contains_key(PLE_TENSOR) && given.is_none()) { return Ok(()) } + let file = match given { + Some(p) => p, + None => { + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let mut found: Vec = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()) + .filter(|p| p.file_name() != path.file_name() && p.extension().is_some_and(|e| e == "gguf") + && p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.to_ascii_lowercase().contains("ple")) + && Self::open_one(p, 0, false, MoeOptions::default()).is_ok_and(|g| g.tensors.contains_key(PLE_TENSOR))) + .collect(); + found.sort(); + match found.len() { + 0 => bail!("{}: this file has no n-gram table ({PLE_TENSOR}); put its GGUF (a name with PLE in it) next to the model or pass it with --ple", path.display()), + 1 => found.pop().unwrap(), + _ => bail!("{}: several n-gram table files next to the model ({}); choose one with --ple", path.display(), + found.iter().filter_map(|p| p.file_name()?.to_str()).collect::>().join(", ")), + } + } + }; + let s = Self::open_one(&file, self.files.len(), true, self.moe)?; + self.take_ple(s, &file) + } + + /// Takes the n-gram table, and only it, from the opened `file`. + fn take_ple(&mut self, mut s: Gguf, file: &Path) -> anyhow::Result<()> { + let t = s.tensors.remove(PLE_TENSOR).with_context(|| format!("{}: no tensor {PLE_TENSOR}", file.display()))?; + crate::say!("n-gram table: {PLE_TENSOR} from {}", file.display()); + self.files.append(&mut s.files); + self.tensors.insert(PLE_TENSOR.into(), t); + Ok(()) + } + + /// The file a tensor's data is in and the offset of the data in it. + pub fn file_of(&self, t: &TensorInfo) -> (&Path, u64) { + let (m, o) = &self.files[t.file]; + (&m.1, (*o as u64) + t.offset) + } + + /// The mapped byte ranges of the routed-expert tensors: (file index, byte offset, length), page-aligned outward. + /// `STRATA_MLOCK_EXPERTS` locks these (they are what a prompt streams; the rest of the file — dense weights, the + /// n-gram table — reads through the page cache). Ranges are merged before they are returned, so overlapping or + /// adjacent expert tensors share one range and every byte is locked once. + pub fn expert_ranges(&self) -> Vec<(usize, usize, usize)> { + let mut rs = Vec::new(); + for t in self.tensors.values() { + if !is_expert(&t.name) { continue; } + let Ok(ty) = GgmlType::from_u32(t.ty) else { continue }; + let n = ty.row_bytes(t.dims.first().copied().unwrap_or(0)) * t.dims.iter().skip(1).product::() as usize; + if n == 0 { continue; } + let (m, data_offset) = &self.files[t.file]; + let (start, end) = page_range(m.0.as_ptr() as usize + data_offset + t.offset as usize, n); + rs.push((t.file, start, end - start)); + } + merge_ranges(rs) + } + + /// Locks the expert tensors' mapped pages (`mlock`), so memory pressure cannot reclaim them while a prompt streams + /// them. Returns the bytes locked, or 0 when nothing was locked or a range failed, and then the ranges locked + /// before it are released again; the locks last until the process exits. Best effort: a failure says a warning + /// and returns, it does not abort the model load. + pub fn mlock_experts(&self) -> usize { + let ranges = self.expert_ranges(); + let mut locked = 0usize; + for (i, &(file, start, len)) in ranges.iter().enumerate() { + if crate::weights::mlock(start, len) != 0 { + crate::say!("warning: expert pages: mlock of {} MB in file {file} (range {}/{}) failed: {}; the {} MB locked before it are released (STRATA_MLOCK_EXPERTS)", + len >> 20, i + 1, ranges.len(), std::io::Error::last_os_error(), locked >> 20); + for &(_, s, n) in &ranges[..i] { crate::weights::munlock(s, n); } + return 0; + } + locked += len; + } + if locked > 0 { + crate::say!("expert pages: locked {} MB of {} ranges (STRATA_MLOCK_EXPERTS; mlocked pages are not evictable)", + locked >> 20, ranges.len()); + } + locked + } + + + /// (address, length) of the files held in anonymous memory (`arena`): memory a backend may pin for its kernels. + pub fn anon_spans(&self) -> Vec<(usize, usize)> { + self.files.iter().filter_map(|(m, _)| match &m.0 { Bytes::Anon(a) => Some((a.as_ptr() as usize, a.len())), _ => None }).collect() + } + /// `general.architecture` of a model, from its first shard and without starting to read the file into the page /// cache: for a caller that only chooses which server gets the model. pub fn arch(path: &Path) -> Option { - Self::open_one(path, 0, false).ok()?.meta.get("general.architecture")?.as_str().map(str::to_owned) + Self::head(path).ok()?.meta.get("general.architecture")?.as_str().map(str::to_owned) } - fn open_one(path: &Path, file: usize, read: bool) -> anyhow::Result { + /// The first shard of a model, opened for its metadata and tensor list only: the file is not read into the page + /// cache and the other shards are not opened. For a caller that asks what a file is (the model list, issue #211). + pub fn head(path: &Path) -> anyhow::Result { Self::open_one(path, 0, false, MoeOptions::default()) } + + fn open_one(path: &Path, file: usize, read: bool, moe: MoeOptions) -> anyhow::Result { let f = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?; let mmap = unsafe { Mmap::map(&f)? }; // Expert rows are 2 MB apart in a file the page cache reads at random: huge pages save TLB misses. @@ -129,8 +284,8 @@ impl Gguf { if std::env::var_os("STRATA_HUGEPAGE").is_some() { let _ = mmap.advise(memmap2::Advice::HugePage); } - crate::weights::preload(&mmap, read); - let mmap = Map(mmap); + crate::weights::preload(&mmap, read && !crate::weights::net_fs(path)); + let mut mmap = Map(Bytes::File(mmap), path.to_path_buf(), true); let mut c = Cur { b: &mmap.0, p: 0 }; if c.take(4)? != b"GGUF" { bail!("{}: not a GGUF file", path.display()); } let ver = c.u32()?; @@ -161,7 +316,20 @@ impl Gguf { bail!("{}: GGUF truncated (tensor {} lies past the end of the file; re-download it)", path.display(), t.name); } } - Ok(Gguf { meta, tensors, files: vec![(mmap, data_offset)] }) + // A file that holds only the Qwen3.8 Flash-Next n-gram table (27 GB, a few rows read a token, by `pread`) does + // not count toward the model's size in RAM: with it, a model whose weights fit was taken for one that does + // not, and the experts placed on the GPU were dropped from the page cache, so a later miss on one read it + // from the drive again (IQ3_XXS: CPU worker time a token down ~8%). + if !tensors.is_empty() && tensors.keys().all(|n| n == PLE_TENSOR) { + crate::weights::unmapped(mmap.0.len()); + mmap.2 = false; + } + #[cfg(target_os = "linux")] + if read { crate::weights::warn_compressed_fs(path); } + if read && mmap.2 && moe.arena && arena_wanted(mmap.0.len()) { + mmap.0 = Bytes::Anon(read_anon(&f, mmap.0.len(), path)?); + } + Ok(Gguf { moe, meta, tensors, files: vec![(mmap, data_offset)] }) } pub fn get(&self, key: &str) -> anyhow::Result<&Value> { @@ -185,6 +353,33 @@ impl Gguf { } } +/// Whether a tensor name is one of the routed experts' matrices (`expert_cache::MATS`, which names the same three). +fn is_expert(name: &str) -> bool { + ["ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight"].iter().any(|s| name.ends_with(s)) +} + +/// The page range `start..end` that covers `at..at + n`, rounded outward to 4096-byte pages (`mlock` rounds to pages +/// itself, so this only makes the accounting in `mlock_experts` exact). +fn page_range(at: usize, n: usize) -> (usize, usize) { + (at & !4095, (at + n + 4095) & !4095) +} + +/// Merges the (file, start, len) ranges that touch or overlap, sorted by file and start. Two expert tensors can share +/// a page (and so a range) and adjacent tensors leave no gap; locking overlapping ranges twice would count the shared +/// pages twice. +fn merge_ranges(mut rs: Vec<(usize, usize, usize)>) -> Vec<(usize, usize, usize)> { + rs.sort_unstable(); + let mut out: Vec<(usize, usize, usize)> = Vec::with_capacity(rs.len()); + for (f, s, l) in rs { + match out.last_mut() { + Some((of, os, ol)) if *of == f && s <= *os + *ol => *ol = (*os + *ol).max(s + l) - *os, + _ => out.push((f, s, l)), + } + } + out +} + + const GGUF_ALIGNMENT: usize = 32; const GGUF_TYPE_UINT32: u32 = 4; const GGUF_TYPE_INT32: u32 = 5; @@ -228,6 +423,34 @@ fn parse_safetensors<'a>(mmap: &'a [u8], st_path: &Path) -> anyhow::Result(st: &StTensor<'a>, name: &str) -> anyhow::Result> { + let (r, c) = (st.shape[0] as usize, st.shape[1] as usize); + let elem = match st.dtype.as_str() { "BF16" | "F16" => 2, "F32" => 4, dt => bail!("{name}: unsupported dtype {dt}") }; + anyhow::ensure!(st.raw.len() == r * c * elem, "{name}: {} bytes for {r}x{c} {elem}-byte elements", st.raw.len()); + let mut out = vec![0u8; st.raw.len()]; + for i in 0..r { + for j in 0..c { + let (src, dst) = (i * c * elem + j * elem, (j * r + i) * elem); + out[dst..dst + elem].copy_from_slice(&st.raw[src..src + elem]); + } + } + Ok(StTensor { shape: vec![st.shape[1], st.shape[0]], dtype: st.dtype.clone(), raw: Box::leak(out.into_boxed_slice()) }) +} + +/// Whether a selector codebook of safetensors shape `shape` has to be transposed so that one GGUF row is one +/// vocabulary entry over `rank`: `[vocab, rank]` is already that way, `[rank, vocab]` is not. The rank decides, not +/// which side is longer, so a square or small-vocabulary codebook is not guessed. +fn codebook_needs_transpose(shape: &[u64], rank: u64, name: &str) -> anyhow::Result { + match shape { + [_, r] if *r == rank => Ok(false), + [r, _] if *r == rank => Ok(true), + _ => bail!("{name}: shape {shape:?} has no side of the selector rank {rank}"), + } +} + fn convert_st_tensor<'a>(st: &StTensor<'a>, name: &str, dst_ty: u32) -> anyhow::Result> { use half::{bf16, f16}; use rayon::prelude::*; @@ -542,9 +765,18 @@ pub fn convert_safetensors_dflash_to_gguf( let mut push_t = |hf_name: &str, gguf_name: String, dst_ty: u32| -> anyhow::Result<()> { let st = tensors.get(hf_name).with_context(|| format!("{}: missing DFlash tensor {hf_name}", st_path.display()))?; let gguf_dims: Vec = st.shape.iter().copied().rev().collect(); + // The loader reads one vocabulary entry as one GGUF row over the rank. The incoai DFlash2 checkpoints store + // the codebooks that way (`[vocab, rank]`); one stored `[rank, vocab]` is transposed. + let codebook_swapped = hf_name.ends_with("_codebook") && codebook_needs_transpose(&st.shape, selector_rank as u64, hf_name)?; + let gguf_dims: Vec = if codebook_swapped { st.shape.clone() } else { gguf_dims }; let cols = *gguf_dims.first().unwrap_or(&0) as usize; let ty = if matches!(dst_ty, GGML_TYPE_Q8_0 | GGML_TYPE_Q4_0) && cols % 32 != 0 { GGML_TYPE_BF16 } else { dst_ty }; - prepared.push((gguf_name, gguf_dims, ty, convert_st_tensor(st, hf_name, ty)?)); + let data = if codebook_swapped { + // Transpose first, then quantize: the quantizer's row is then the rank, as `gguf_dims` says. + let t = swapped_rows(st, hf_name)?; + convert_st_tensor(&t, hf_name, ty)? + } else { convert_st_tensor(st, hf_name, ty)? }; + prepared.push((gguf_name, gguf_dims, ty, data)); Ok(()) }; push_t("fc.weight", "dflash.fc.weight".into(), GGML_TYPE_Q8_0)?; @@ -624,3 +856,169 @@ pub fn convert_safetensors_dflash_to_gguf( ); Ok(()) } + +/// Whether the file fits in anonymous memory with 6 GiB to spare. Anonymous memory can be pinned for the GPU, which then reads some missed +/// experts over PCIe beside the CPU (`GpuModel` host share); a mapped file cannot (CUDA refuses file pages). +fn arena_wanted(len: usize) -> bool { + let free = crate::memory::available_ram().unwrap_or(0) as usize; + if free < len + (6 << 30) { + crate::say!("arena: {} MB do not fit in the {} MB of free RAM with 6 GB to spare: the file stays mapped", len >> 20, free >> 20); + return false; + } + true +} + +fn read_exact_at(f: &std::fs::File, dst: &mut [u8], off: u64) -> std::io::Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::FileExt; + f.read_exact_at(dst, off) + } + #[cfg(windows)] + { + use std::os::windows::fs::FileExt; + let (mut dst, mut off) = (dst, off); + while !dst.is_empty() { + match f.seek_read(dst, off) { + Ok(0) => return Err(std::io::ErrorKind::UnexpectedEof.into()), + Ok(n) => { + dst = &mut dst[n..]; + off += n as u64; + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + Ok(()) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (f, dst, off); + Err(std::io::ErrorKind::Unsupported.into()) + } +} + +/// The file in anonymous memory, read by one thread a CPU in 64 MB pieces; each piece then leaves the page cache, so +/// the file is not held twice. +fn read_anon(f: &std::fs::File, len: usize, path: &Path) -> anyhow::Result { + let t = std::time::Instant::now(); + let mut m = memmap2::MmapMut::map_anon(len)?; + #[cfg(target_os = "linux")] + let _ = m.advise(memmap2::Advice::HugePage); + const PIECE: usize = 64 << 20; + let next = std::sync::atomic::AtomicUsize::new(0); + let base = m.as_mut_ptr() as usize; + let k = std::thread::available_parallelism().map_or(4, |k| k.get()).min(16); + std::thread::scope(|s| -> anyhow::Result<()> { + let hs: Vec<_> = (0..k).map(|_| s.spawn(|| -> anyhow::Result<()> { + loop { + let a = next.fetch_add(PIECE, std::sync::atomic::Ordering::Relaxed); + if a >= len { return Ok(()); } + let n = PIECE.min(len - a); + let dst = unsafe { std::slice::from_raw_parts_mut((base + a) as *mut u8, n) }; + read_exact_at(f, dst, a as u64)?; + #[cfg(target_os = "linux")] + unsafe { + unsafe extern "C" { fn posix_fadvise(fd: i32, off: i64, len: i64, advice: i32) -> i32; } + use std::os::fd::AsRawFd; + posix_fadvise(f.as_raw_fd(), a as i64, n as i64, 4); + } + } + })).collect(); + for h in hs { h.join().map_err(|_| anyhow::anyhow!("arena reader panicked"))??; } + Ok(()) + })?; + crate::say!("arena: {} MB of {} in anonymous memory in {:.1} s", len >> 20, path.file_name().and_then(|s| s.to_str()).unwrap_or("the model"), t.elapsed().as_secs_f64()); + Ok(m) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A GGUF v3 file of F32 tensors of `bytes` bytes each, laid out in `order`, as `(name, bytes)`. + fn write_gguf(path: &Path, tensors: &[(&str, usize)]) { + let mut b = Vec::new(); + b.extend(b"GGUF"); + b.extend(3u32.to_le_bytes()); + b.extend((tensors.len() as u64).to_le_bytes()); + b.extend(0u64.to_le_bytes()); + let mut off = 0usize; + for &(name, bytes) in tensors { + push_gguf_str(&mut b, name); + b.extend(2u32.to_le_bytes()); + b.extend((bytes as u64 / 4).to_le_bytes()); + b.extend(1u64.to_le_bytes()); + b.extend(GGML_TYPE_F32.to_le_bytes()); + b.extend((off as u64).to_le_bytes()); + off += bytes.next_multiple_of(GGUF_ALIGNMENT); + } + b.resize(b.len().next_multiple_of(GGUF_ALIGNMENT), 0); + b.resize(b.len() + off, 0); + std::fs::write(path, &b).unwrap(); + } + + /// A codebook is transposed only when stored rank-first; the rank, not the longer side, decides, so a square or + /// small-vocabulary codebook keeps its rows. A shape without the rank is an error. + #[test] + fn codebook_orientation_follows_the_rank() { + assert!(!codebook_needs_transpose(&[248320, 256], 256, "c").unwrap()); + assert!(codebook_needs_transpose(&[256, 248320], 256, "c").unwrap()); + assert!(!codebook_needs_transpose(&[64, 128], 128, "c").unwrap()); + assert!(!codebook_needs_transpose(&[128, 128], 128, "c").unwrap()); + assert!(codebook_needs_transpose(&[128, 64], 128, "c").unwrap()); + assert!(codebook_needs_transpose(&[256, 100, 3], 256, "c").is_err()); + assert!(codebook_needs_transpose(&[100, 300], 256, "c").is_err()); + // The transpose itself: [2, 3] BF16 becomes [3, 2] with element (i, j) at (j, i). + let raw: Vec = (0u16..6).flat_map(|v| v.to_le_bytes()).collect(); + let st = StTensor { shape: vec![2, 3], dtype: "BF16".into(), raw: &raw }; + let t = swapped_rows(&st, "c").unwrap(); + assert_eq!(t.shape, vec![3, 2]); + let got: Vec = t.raw.chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + assert_eq!(got, vec![0, 3, 1, 4, 2, 5]); + } + + /// Only the three `*_exps` kinds are expert tensors; dense weights, norms and the n-gram table are not. + #[test] + fn expert_filter_names_three_tensors() { + for n in ["blk.0.ffn_gate_exps.weight", "blk.47.ffn_up_exps.weight", "blk.3.ffn_down_exps.weight"] { assert!(is_expert(n), "{n}"); } + for n in ["blk.0.ffn_gate.weight", "blk.0.ffn_up.weight", "blk.0.ffn_down.weight", "blk.0.attn_q.weight", + "token_embd.weight", "output.weight", "per_layer_token_embd.weight", "ffn_gate_exps.bias"] { assert!(!is_expert(n), "{n}"); } + } + + /// Page ranges round outward and overlapping ones merge into one that covers each byte once. + #[test] + fn page_ranges_merge_once() { + assert_eq!(page_range(0, 1), (0, 4096)); + assert_eq!(page_range(4096, 4096), (4096, 8192)); + assert_eq!(page_range(1, 8192), (0, 12288)); + let m = merge_ranges(vec![(0, 8192, 4096), (0, 0, 8192), (1, 0, 4096), (1, 0, 4096), (0, 12288, 4096), (0, 20000, 32)]); + assert_eq!(m, vec![(0, 0, 16384), (0, 20000, 32), (1, 0, 4096)]); + let sum: usize = m.iter().map(|r| r.2).sum(); + assert_eq!(sum, 16384 + 32 + 4096, "a shared page is in one range only"); + } + + /// `expert_ranges` covers exactly the expert tensors of a mapped file, page-aligned, and leaves a dense tensor + /// outside them alone; `mlock_experts` locks that many bytes. + #[cfg(target_os = "linux")] + #[test] + fn expert_ranges_cover_the_expert_tensors() { + let p = std::env::temp_dir().join(format!("strata-{}-experts.gguf", std::process::id())); + write_gguf(&p, &[("blk.0.ffn_gate.weight", 4096), ("blk.0.ffn_gate_exps.weight", 4096), ("blk.0.ffn_up_exps.weight", 4096), + ("per_layer_token_embd.weight", 8192), ("blk.1.ffn_down_exps.weight", 4096)]); + let g = Gguf::open(&p).unwrap(); + let r = g.expert_ranges(); + assert_eq!(r.len(), 2, "{r:?}"); + let (mmap, _) = &g.files[r[0].0]; + let base = mmap.0.as_ptr() as usize; + // The first two experts are adjacent: one page-aligned range starting at the first expert's data. + let first = base + g.files[0].1 + g.tensors["blk.0.ffn_gate_exps.weight"].offset as usize; + assert_eq!(r[0], (0, first & !4095, (first + 8192 + 4095 & !4095) - (first & !4095))); + assert!(r[1].1 > base, "second range is in the mapped file"); + assert!(r.iter().all(|&(_, s, _)| s % 4096 == 0)); + let want: usize = r.iter().map(|x| x.2).sum(); + assert_eq!(g.mlock_experts(), want, "every range locks, and returns its bytes"); + drop(g); + std::fs::remove_file(&p).ok(); + } +} diff --git a/src/gigachat4/chat.rs b/src/gigachat4/chat.rs new file mode 100644 index 00000000..23c889f6 --- /dev/null +++ b/src/gigachat4/chat.rs @@ -0,0 +1,475 @@ +//! `rustingstrata generate|chat|serve` for GigaChat 4: greedy, CUDA for the matvecs and expert staging, the cache kept +//! across turns. Tools go in a `function descriptions` turn as a TypeScript namespace, calls come back as a +//! `<|GCML|tool_calls>` block, results go in a `function result` turn. +use super::forward::GigaChat4Model; +use crate::{chat::{Json, Msg}, gguf::Gguf, tokenizer::Tokenizer}; +use std::io::{BufRead, Write}; + +const SEP: &str = "<|role_sep|>\n"; +const END: &str = "<|message_sep|>\n\n"; +const THINK_END: &str = ""; +const CALL: &str = "<|GCML|tool_calls>"; + +pub use crate::deepseek::chat::gpu_defaults; + +/// The GGUF's chat template with `add_generation_prompt`; `think` is its `reasoning` (off: every think block is empty +/// and the reply starts after an empty one). +// ponytail: tool results are matched to the calls by position (the template re-sorts them by tool_call_id; Msg keeps +// no ids); a tool's `return_parameters` and `few_shot_examples` are dropped by `chat::tool_def`. +pub fn render(msgs: &[Msg], tools: &[Json], think: bool) -> String { + let mut s = String::from(""); + let sys = msgs.first().filter(|m| m.role == "system"); + s += &format!("system{SEP}{}{END}", sys.map_or("", |m| m.content.as_str())); + if !tools.is_empty() { s += &format!("function descriptions{SEP}{}\n\n{END}", namespace(tools)); } + let rest = &msgs[sys.is_some() as usize..]; + let mut names: Vec<&str> = vec![]; + for (i, m) in rest.iter().enumerate() { + match m.role.as_str() { + "assistant" => { + let (mut content, mut reasoning) = (m.content.as_str(), m.reasoning.as_deref().unwrap_or("")); + if let Some((r, c)) = content.rsplit_once(THINK_END) { + reasoning = r.rsplit("").next().unwrap_or(""); + content = c.trim_start_matches('\n'); + } + let mut blocks = vec![format!("{}", if think { reasoning } else { "" })]; + if !content.is_empty() { blocks.push(content.to_string()); } + if !m.calls.is_empty() { + blocks.push(format!("{CALL}\n{}\n", m.calls.iter().map(|c| invoke(&c.name, &c.args)).collect::>().join("\n"))); + names = m.calls.iter().map(|c| c.name.as_str()).collect(); + } + s += &format!("assistant{SEP}{}{END}", blocks.join("\n\n")); + } + // A run of tool messages is one turn; the k-th result takes the name of the k-th call. + "tool" => { + let k = rest[..i].iter().rev().take_while(|x| x.role == "tool").count(); + if k == 0 { s += &format!("function result{SEP}"); } else { s += "\n"; } + let name = names.get(k).or(names.last()).copied().unwrap_or(""); + s += &format!("{}", m.content); + if rest.get(i + 1).is_none_or(|x| x.role != "tool") { s += END; } + } + role => s += &format!("{role}{SEP}{}{END}", m.content), + } + } + s += &format!("assistant{SEP}"); + if !think { s += "\n\n"; } + s +} + +/// One call of a `<|GCML|tool_calls>` block: strings as they are, other values as JSON. +fn invoke(name: &str, args: &Json) -> String { + let mut s = format!("<|GCML|invoke name=\"{name}\">\n"); + if let Json::Obj(o) = args && !o.is_empty() { + let p: Vec = o.iter().map(|(k, v)| match v { + Json::Str(x) => format!("<|GCML|parameter name=\"{k}\" string=\"true\">{x}"), + v => format!("<|GCML|parameter name=\"{k}\" string=\"false\">{}", v.dump()), + }).collect(); + s += &p.join("\n"); + s += "\n"; + } + s + "" +} + +/// The template's `render_tool_namespace('functions', tools)`. +fn namespace(tools: &[Json]) -> String { + let mut sections = vec!["namespace functions {".to_string()]; + for t in tools { + let f = if matches!(t.get("function"), Json::Null) { t } else { t.get("function") }; + let mut lines: Vec = f.get("description").as_str().unwrap_or("").split('\n').filter(|l| !l.trim().is_empty()).map(|l| format!("// {l}")).collect(); + let name = f.get("name").as_str().unwrap_or(""); + let p = f.get("parameters"); + let args = if truthy(p.get("properties")) { format!("_: {}", ts(p, " ", p, &mut vec![])) } else { String::new() }; + lines.push(format!("type {name} = ({args}) => any;\n")); + sections.push(lines.join("\n")); + } + sections.push("} // namespace functions".into()); + sections.join("\n") +} + +fn truthy(v: &Json) -> bool { + match v { Json::Null => false, Json::Bool(b) => *b, Json::Str(s) => !s.is_empty(), Json::Arr(a) => !a.is_empty(), Json::Obj(o) => !o.is_empty(), Json::Num(n) => n.as_f64() != Some(0.0) } +} + +fn obj(kv: Vec<(&str, Json)>) -> Json { Json::Obj(kv.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) } + +/// The template's `json_schema_to_typescript`: a JSON schema as a TypeScript type. `chain` holds the `$ref`s being +/// expanded, so a recursive one becomes `any`. +fn ts(s: &Json, indent: &str, root: &Json, chain: &mut Vec) -> String { + const EXTRA: [&str; 14] = ["format", "maxItems", "maximum", "minItems", "minimum", "pattern", "minLength", "maxLength", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "uniqueItems", "minProperties", "maxProperties"]; + let Json::Obj(o) = s else { return "any".into() }; + let has = |k: &str| o.iter().any(|(x, _)| x == k); + let lit = |c: &Json| match c { Json::Str(x) => format!("\"{x}\""), Json::Bool(b) => b.to_string(), Json::Num(_) => c.param(), Json::Null => "null".into(), _ => "any".into() }; + let join = |list: &Json, sep: &str, chain: &mut Vec| match list { + Json::Arr(a) => a.iter().map(|b| format!("({})", ts(b, indent, root, chain))).collect::>().join(sep), + _ => unreachable!(), + }; + if let Some(r) = s.get("$ref").as_str() { + if chain.iter().any(|c| c == r) { return "any".into(); } + let Some(path) = r.strip_prefix("#/") else { return "any".into() }; + let mut n = root; + for seg in path.split('/') { + let seg = seg.replace("~1", "/").replace("~0", "~"); + n = match n { Json::Obj(_) => n.get(&seg), Json::Arr(a) => seg.parse::().ok().and_then(|i| a.get(i)).unwrap_or(&Json::Null), _ => &Json::Null }; + } + if !matches!(n, Json::Obj(_)) { return "any".into(); } + chain.push(r.into()); + let t = ts(n, indent, root, chain); + chain.pop(); + return t; + } + for (k, sep) in [("anyOf", " | "), ("oneOf", " | "), ("allOf", " & ")] { + if let Json::Arr(_) = s.get(k) { return join(s.get(k), sep, chain); } + } + let ty = s.get("type"); + if let Json::Arr(types) = ty { + let bits: Vec = types.iter().map(|t| { + let t = t.as_str().unwrap_or(""); + let with = |kv: Vec<(&str, Json)>, chain: &mut Vec| ts(&obj(kv), indent, root, chain); + let f = match t { + "null" => "null".into(), + "string" if has("const") => with(vec![("type", Json::Str("string".into())), ("const", s.get("const").clone())], chain), + "string" if truthy(s.get("enum")) => with(vec![("type", Json::Str("string".into())), ("enum", s.get("enum").clone())], chain), + "string" if matches!(s.get("format").as_str(), Some("date-time" | "date")) => "Date".into(), + "string" => "string".into(), + "number" | "integer" | "int" | "float" if has("const") => with(vec![("type", Json::Str(t.into())), ("const", s.get("const").clone())], chain), + "number" | "integer" | "int" | "float" => with(vec![("type", Json::Str(t.into())), ("enum", s.get("enum").clone())], chain), + "boolean" if has("const") => with(vec![("type", Json::Str("boolean".into())), ("const", s.get("const").clone())], chain), + "boolean" => "boolean".into(), + "object" | "dict" => { + let or = |v: &Json, d: Json| if truthy(v) { v.clone() } else { d }; + let mut kv = vec![("type", Json::Str("object".into())), ("properties", or(s.get("properties"), Json::Obj(vec![]))), ("required", or(s.get("required"), Json::Arr(vec![])))]; + if has("additionalProperties") { kv.push(("additionalProperties", s.get("additionalProperties").clone())); } + with(kv, chain) + } + "array" => { + let mut kv = vec![("type", Json::Str("array".into()))]; + if let Json::Arr(_) = s.get("prefixItems") { kv.push(("prefixItems", s.get("prefixItems").clone())); } else if has("items") { kv.push(("items", s.get("items").clone())); } + with(kv, chain) + } + _ => "any".into(), + }; + format!("({f})") + }).collect(); + return bits.join(" | "); + } + let ty = match ty.as_str() { Some("dict") => Some("object"), t => t }; + let props_map = matches!(s.get("properties"), Json::Obj(_)); + if has("const") && ty.is_none() && !props_map { return lit(s.get("const")); } + if truthy(s.get("enum")) && ty.is_none() && !props_map { + let Json::Arr(e) = s.get("enum") else { return "any".into() }; + return e.iter().map(|x| match x { Json::Str(v) => format!("\"{v}\""), v => v.param() }).collect::>().join(" | "); + } + match ty { + Some("object") | None if ty.is_some() || props_map => { + let mut out = String::from("{\n"); + let mut props: Vec<(String, Json)> = match s.get("properties") { Json::Obj(p) => p.clone(), _ => vec![] }; + match s.get("additionalProperties") { + Json::Bool(true) => props.push(("[key: string]".into(), obj(vec![("type", Json::Str("any".into()))]))), + a @ Json::Obj(_) => props.push(("[key: string]".into(), a.clone())), + _ => {} + } + let required: Vec<&str> = match s.get("required") { Json::Arr(r) => r.iter().filter_map(Json::as_str).collect(), _ => vec![] }; + for (key, val) in &props { + if let Some(d) = val.get("description").as_str() { + for l in d.split('\n').filter(|l| !l.trim().is_empty()) { out += &format!("{indent}// {l}\n"); } + } + if let Json::Obj(vo) = val { + for (k, v) in vo.iter().filter(|(k, v)| EXTRA.contains(&k.as_str()) && !matches!(v, Json::Null)) { + out += &match v { Json::Str(x) => format!("{indent}// {k}: \"{x}\"\n"), v => format!("{indent}// {k}: {}\n", v.param()) }; + } + } + let t = ts(val, &format!("{indent} "), root, chain); + let opt = if key == "[key: string]" || required.contains(&key.as_str()) { "" } else { "?" }; + out += &format!("{indent}{key}{opt}: {t},"); + if let Json::Obj(vo) = val && let Some((_, d)) = vo.iter().find(|(k, _)| k == "default").or_else(|| vo.iter().find(|(k, _)| k == "defalut_value")) { + out += &match d { Json::Str(x) => format!(" // default: \"{x}\""), d => format!(" // default: {}", d.param()) }; + } + out += "\n"; + } + out + &indent[..indent.len().saturating_sub(2)] + "}" + } + Some("string") => { + if has("const") { return lit(s.get("const")); } + if let Json::Arr(e) = s.get("enum") && !e.is_empty() { return e.iter().filter_map(Json::as_str).map(|v| format!("\"{v}\"")).collect::>().join(" | "); } + if matches!(s.get("format").as_str(), Some("date-time" | "date")) { "Date".into() } else { "string".into() } + } + Some(t @ ("number" | "integer" | "int" | "float")) => { + if has("const") { return lit(s.get("const")); } + if let Json::Arr(e) = s.get("enum") && !e.is_empty() { return e.iter().map(Json::param).collect::>().join(" | "); } + if matches!(t, "integer" | "int") { "integer".into() } else { "number".into() } + } + Some("boolean") => match s.get("const") { Json::Bool(b) => b.to_string(), _ => "boolean".into() }, + Some("null") => "null".into(), + Some("array") => { + let items = s.get("items"); + match (s.get("prefixItems"), items) { + (Json::Arr(a), _) | (_, Json::Arr(a)) => format!("[{}]", a.iter().map(|x| ts(x, indent, root, chain)).collect::>().join(", ")), + (_, Json::Obj(_)) => format!("({})[]", ts(items, indent, root, chain)), + _ => "Array".into(), + } + } + _ if matches!(s.get("not"), Json::Obj(_)) => "unknown".into(), + _ => "any".into(), + } +} + +/// The tool calls of a reply: the text before the block and (name, JSON arguments) per call. +pub fn parse_calls(text: &str) -> Option<(String, Vec<(String, String)>)> { crate::chat::markup_calls(text, "|GCML|", "tool_calls") } + +/// Greedy decode of up to `n` tokens after `logits`; `piece` gets each new piece of text and returns false to stop. +/// Returns the tokens and whether the model ended the reply itself. +fn decode(m: &mut GigaChat4Model, tok: &Tokenizer, lim: &mut Option, logits: Vec, n: usize, mut piece: impl FnMut(&str) -> bool) -> (Vec, bool) { + let (mut out, mut shown) = (vec![], 0); + let stopped = greedy_run(m, lim, logits, &tok.eos_ids(), n, |next| { + out.push(next); + crate::term::decoded(1); + let s = tok.decode(&out).unwrap_or_default(); + if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { + if !piece(&s[shown..]) { return false; } + shown = s.len(); + } + true + }); + (out, stopped) +} + +/// Greedy tokens after `logits`, up to `n` or an end token; `emit` gets each and returns false to stop. Returns +/// whether the model ended the reply itself. With MTP and no grammar, each step drafts the token after its own and +/// checks both in one trunk pass, so an accepted draft is a token for free. +pub fn greedy_run(m: &mut GigaChat4Model, lim: &mut Option, mut logits: Vec, eos: &[u32], n: usize, mut emit: impl FnMut(u32) -> bool) -> bool { + // An accepted draft: already in the caches, and `logits` are those after it. + let mut ahead = None; + for i in 0..n { + let (next, cached) = match ahead.take() { Some(d) => (d, true), None => (crate::grammar::greedy(lim, &mut logits), false) }; + if eos.contains(&next) { return true; } + if !emit(next) { break; } + if cached { continue; } + // Only when the draft has room to be emitted (the step after this one). + if lim.is_none() && i + 2 < n && m.mtp_ready() { + let d = m.draft(next); + if !eos.contains(&d) { + let (ok, l) = m.verify(next, d); + logits = l; + if ok { ahead = Some(d); } + continue; + } + } + if i + 1 < n { logits = m.step(next); } + } + false +} + +fn show(s: &str) -> bool { + print!("{s}"); + std::io::stdout().flush().is_ok() +} + +/// `rustingstrata generate`: raw prompt (BOS, no template), greedy, prints the continuation. +pub fn generate(g: &Gguf, prompt: &str, n: usize) -> anyhow::Result<()> { + gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = GigaChat4Model::new(g)?; + let max_ctx = m.cfg.n_ctx; + let ids = tok.encode_special(prompt, true)?; + anyhow::ensure!(!ids.is_empty() && ids.len() < max_ctx, "{}", crate::serve::too_long(ids.len(), max_ctx)); + if std::env::var_os("STRATA_DS_TRACE").is_some() { crate::say!("prompt tokens: {ids:?}"); } + let logits = m.prefill(&ids); + let (out, _) = decode(&mut m, &tok, &mut None, logits, n.min(max_ctx - ids.len()), show); + if m.drafts.0 > 0 { + crate::say!("\nMTP drafts accepted {}/{} ({:.1}%)", m.drafts.1, m.drafts.0, 100.0 * m.drafts.1 as f64 / m.drafts.0 as f64); + } + if std::env::var_os("STRATA_DS_TRACE").is_some() { crate::say!("\noutput tokens: {out:?}"); } + println!(); + Ok(()) +} + +pub fn chat(g: &Gguf, system: Option, n: usize, think: bool) -> anyhow::Result<()> { + gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = GigaChat4Model::new(g)?; + let max_ctx = m.cfg.n_ctx; + let stdin = std::io::stdin(); + loop { + print!("{}", crate::term::prompt()); + std::io::stdout().flush()?; + let mut line = String::new(); + if stdin.lock().read_line(&mut line)? == 0 { break; } + let line = line.trim_end(); + if line.is_empty() { continue; } + // First turn: the full template. Later turns: the cache holds everything up to the reply, so append the end of + // the turn and the next user turn. + let user = [Msg::new("user", line)]; + let text = if m.toks.is_empty() { + let msgs: Vec = system.iter().map(|s| Msg::new("system", s)).chain(user).collect(); + render(&msgs, &[], think) + } else { + let r = render(&user, &[], think); + format!("{END}{}", &r[r.find("user").unwrap()..]) + }; + let ids = tok.encode(&text)?; + if m.toks.len() + ids.len() >= max_ctx { + println!("context is full ({max_ctx} tokens); restart the chat"); + break; + } + let logits = m.prefill(&ids); + let left = max_ctx - m.toks.len(); + decode(&mut m, &tok, &mut None, logits, n.min(left), show); + println!(); + } + Ok(()) +} + +/// The chat of `rustingstrata serve` for GigaChat 4 (see `serve::Own`): one request at a time, JSON or SSE. +/// ponytail: greedy only; thinking arrives as `reasoning_content`; the +/// cache is reused only when the new prompt extends the last sequence. +pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Result> { + use anyhow::Context; + use serde_json::json; + gpu_defaults(); + let mut m = GigaChat4Model::new(g)?; + let max_ctx = m.cfg.n_ctx; + crate::serve::warm_up(tok, |ids| { m.prefill(ids); m.reset(); })?; + Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| { + let mut lim = crate::grammar::Constraint::new(q, tok)?; + let think = q.think.unwrap_or(true) && q.reasoning_effort.as_deref() != Some("none"); + let text = render(&q.messages, &q.tools, think); + let ids = tok.encode(&text).ok().filter(|i| !i.is_empty()).context("cannot encode prompt")?; + anyhow::ensure!(ids.len() < max_ctx, "{}", crate::serve::too_long(ids.len(), max_ctx)); + let t = std::time::Instant::now(); + let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; + if q.stream && !q.head_sent { let _ = write!(c, "{}", crate::serve::sse_head(c)); } + let logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); + let prefill_s = t.elapsed().as_secs_f64(); + let n = q.max_tokens.unwrap_or(usize::MAX).min(max_ctx - ids.len()); + let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); + let tools = q.tool_calls && !q.tools.is_empty(); + let mut hold = crate::chat::Hold::new(tools, q.stop.clone()).tagged(CALL); + let mut alive = std::time::Instant::now(); + // The prompt opens ``: text up to `` is reasoning, the answer starts after its blank line. + let (mut reasoning, mut thinking, mut lead) = (String::new(), think, true); + let d0 = m.drafts; + let (out, stopped) = decode(&mut m, tok, &mut lim, logits, n, |p| { + let mut p = p; + if thinking { + let (r, rest) = match p.find(THINK_END) { Some(i) => (&p[..i], Some(&p[i + THINK_END.len()..])), None => (p, None) }; + reasoning += r; + if q.stream && !r.is_empty() && write!(c, "data: {}\n\n", chunk(json!({"reasoning_content": r}), None)).is_err() { return false; } + match rest { Some(x) => { thinking = false; p = x; } None => return true } + } + if lead { p = p.trim_start(); lead = p.is_empty(); } + let t = hold.push(p); + (!q.stream || if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() }) && !hold.stopped + }); + let calls = if tools { parse_calls(&hold.text) } else { None }; + let done = if calls.is_some() { "tool_calls" } else if stopped || hold.stopped { "stop" } else { "length" }; + let calls_json = |(content, calls): &(String, Vec<(String, String)>), stream: bool| { + let c: Vec<_> = calls.iter().enumerate().map(|(k, (f, a))| { + let mut c = json!({"id": format!("call_{k}"), "type": "function", "function": {"name": f, "arguments": a}}); + if stream { c["index"] = k.into(); } + c + }).collect(); + if stream { json!({"tool_calls": c}) } else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } + }; + let drafts = crate::serve::draft_delta(crate::serve::draft_kind(crate::serve::DraftModel::Mtp, false), d0, m.drafts); + let d = crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done, drafts }; + let timings = d.timings(t); + let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), "prompt_tokens_details": {"cached_tokens": keep}}); + if q.stream { + match &calls { + Some(x) => { let _ = write!(c, "data: {}\n\n", chunk(calls_json(x, true), None)); } + None if !hold.rest().is_empty() => { let _ = write!(c, "data: {}\n\n", chunk(json!({"content": hold.rest()}), None)); } + None => {} + } + let mut last = chunk(json!({}), Some(done)); + last["usage"] = usage.clone(); + last["timings"] = timings; + let _ = write!(c, "data: {last}\n\n"); + if q.include_usage { let _ = write!(c, "data: {}\n\n", json!({"object": "chat.completion.chunk", "model": name, "choices": [], "usage": usage})); } + let _ = write!(c, "data: [DONE]\n\n"); + } else { + let mut message = match &calls { Some(x) => calls_json(x, false), None => json!({"role": "assistant", "content": hold.text}) }; + if !reasoning.is_empty() { message["reasoning_content"] = reasoning.into(); } + let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": message, "finish_reason": done}], "usage": usage, "timings": timings}); + crate::serve::send(c, "200 OK", "application/json", &b.to_string()); + } + Ok(d) + })) +} + +#[test] +fn template() { + // the strings from the GGUF's jinja template (rendered with jinja2) + let user = [Msg::new("user", "hi")]; + assert_eq!(render(&user, &[], true), "system<|role_sep|>\n<|message_sep|>\n\nuser<|role_sep|>\nhi<|message_sep|>\n\nassistant<|role_sep|>\n"); + assert_eq!(render(&user, &[], false), "system<|role_sep|>\n<|message_sep|>\n\nuser<|role_sep|>\nhi<|message_sep|>\n\nassistant<|role_sep|>\n\n\n"); + let mut a = Msg::new("assistant", "ok"); + a.reasoning = Some("plan".into()); + let msgs = [Msg::new("user", "q"), a, Msg::new("user", "q2")]; + assert_eq!(render(&msgs, &[], true), "system<|role_sep|>\n<|message_sep|>\n\nuser<|role_sep|>\nq<|message_sep|>\n\nassistant<|role_sep|>\nplan\n\nok<|message_sep|>\n\nuser<|role_sep|>\nq2<|message_sep|>\n\nassistant<|role_sep|>\n"); + let msgs = [Msg::new("system", "S"), Msg::new("user", "q"), Msg::new("assistant", "plan\n\nok"), Msg::new("user", "q2")]; + assert_eq!(render(&msgs, &[], false), "system<|role_sep|>\nS<|message_sep|>\n\nuser<|role_sep|>\nq<|message_sep|>\n\nassistant<|role_sep|>\n\n\nok<|message_sep|>\n\nuser<|role_sep|>\nq2<|message_sep|>\n\nassistant<|role_sep|>\n\n\n"); +} + +#[test] +fn tools() { + use crate::chat::Call; + // rendered with jinja2 from the GGUF's template + let tools: Vec = match serde_json::from_str::(r#"[{"type": "function", "function": {"name": "get_weather", "description": "Weather now.\nUse for cities.", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}, "unit": {"type": "string", "enum": ["c", "f"], "default": "c"}, "days": {"type": "integer", "minimum": 1, "maximum": 7}, "tags": {"type": "array", "items": {"type": ["string", "null"]}}, "opts": {"type": "object", "properties": {"deep": {"type": "boolean"}}, "required": ["deep"]}, "when": {"anyOf": [{"type": "string", "format": "date"}, {"type": "number"}]}}, "required": ["city"]}}}, {"type": "function", "function": {"name": "ping", "description": "", "parameters": {}}}]"#).unwrap() { Json::Arr(a) => a.iter().map(|t| crate::chat::tool_def(t).unwrap()).collect(), _ => unreachable!() }; + let args = |s: &str| serde_json::from_str::(s).unwrap(); + let mut a = Msg::new("assistant", ""); + a.reasoning = Some("plan".into()); + a.calls = vec![Call { name: "get_weather".into(), args: args(r#"{"city": "Kyiv", "days": 3, "opts": {"deep": true}}"#) }, Call { name: "ping".into(), args: args("{}") }]; + let msgs = [Msg::new("system", "S"), Msg::new("user", "weather?"), a, Msg::new("tool", "sun"), Msg::new("tool", r#"{"ok": true}"#)]; + assert_eq!(render(&msgs, &tools, true), r#"system<|role_sep|> +S<|message_sep|> + +function descriptions<|role_sep|> +namespace functions { +// Weather now. +// Use for cities. +type get_weather = (_: { + // City name + city: string, + unit?: "c" | "f", // default: "c" + // minimum: 1 + // maximum: 7 + days?: integer, + tags?: ((string) | (null))[], + opts?: { + deep: boolean, + }, + when?: (Date) | (number), +}) => any; + +type ping = () => any; + +} // namespace functions + +<|message_sep|> + +user<|role_sep|> +weather?<|message_sep|> + +assistant<|role_sep|> +plan + +<|GCML|tool_calls> +<|GCML|invoke name="get_weather"> +<|GCML|parameter name="city" string="true">Kyiv +<|GCML|parameter name="days" string="false">3 +<|GCML|parameter name="opts" string="false">{"deep": true} + +<|GCML|invoke name="ping"> + +<|message_sep|> + +function result<|role_sep|> +sun +{"ok": true}<|message_sep|> + +assistant<|role_sep|> +"#); + // the model's reply parses back into the calls + let reply = "plan\n\n<|GCML|tool_calls>\n<|GCML|invoke name=\"get_weather\">\n<|GCML|parameter name=\"city\" string=\"true\">Kyiv\n<|GCML|parameter name=\"days\" string=\"false\">3\n\n"; + assert_eq!(parse_calls(reply), Some(("plan".into(), vec![("get_weather".into(), r#"{"city": "Kyiv", "days": 3}"#.into())]))); + assert_eq!(parse_calls("x <|GCML|tool_calls>\n\nno call"), None); +} diff --git a/src/gigachat4/forward.rs b/src/gigachat4/forward.rs new file mode 100644 index 00000000..5062f02f --- /dev/null +++ b/src/gigachat4/forward.rs @@ -0,0 +1,1057 @@ +//! GigaChat 4 forward, mirroring llama.cpp `src/models/gigachat4.cpp` (trace names are its callback names, so +//! `STRATA_DS_DUMP` output lines up with `llama-eval-callback`). Decode is one token at a time; prefill runs a chunk +//! of prompt tokens layer by layer, so a routed expert is read once for all the tokens that picked it. +//! With `MTP` on, the file's MTP block drafts one token a decode step and the trunk checks it with the step's own +//! token (`draft`, `verify`). +use super::GigaChat4Config; +use crate::deepseek::mat::{Mat, swiglu_chunk, matvec_many, matvec_rows, matvec_rows_many, vec_f32}; +use crate::deepseek::ops::{Rope, rms_norm, rms_norm_w, swiglu_clamp}; +use crate::gguf::Gguf; +use crate::glm::forward::route_sigmoid; +use crate::hy4::forward::{host_mat, run_experts, sigmoid, silu}; +use crate::inkling2::forward::{dots_h, mix_h}; +use anyhow::Result; +use half::f16; +use half::slice::HalfFloatSliceExt; +use rayon::prelude::*; + +/// RMS norm with a learned low-rank sigmoid gate (llama.cpp `build_gated_norm`): w * rms(x) * sigmoid(down silu(up +/// rms)) * 2. +struct GNorm { + w: Vec, + /// [rank][n], and the down map [n][rank] stored transposed, [rank][n], so its sums run over n in SIMD lanes + up: Vec, + down: Vec, +} + +impl GNorm { + fn load(g: &Gguf, name: &str) -> Result { + let (w, up, d) = (vec_f32(g, &format!("{name}.weight"))?, vec_f32(g, &format!("{name}_gate_up.weight"))?, vec_f32(g, &format!("{name}_gate_down.weight"))?); + let r = up.len() / w.len(); + let down = (0..r).flat_map(|k| d.iter().skip(k).step_by(r).copied()).collect(); + Ok(GNorm { w, up, down }) + } + + fn apply(&self, x: &[f32], eps: f32) -> Vec { + let n = x.len(); + let mut cur = vec![0f32; n]; + rms_norm_w(x, &self.w, eps, &mut cur); + let h: Vec = self.up.chunks_exact(n).map(|r| silu(crate::weights::dot(r, &cur))).collect(); + // The gate sums over the rank in order, as a dot of each row would. + let mut acc = vec![0f32; n]; + for (r, &hk) in self.down.chunks_exact(n).zip(&h) { + for (a, d) in acc.iter_mut().zip(r) { *a += d * hk; } + } + for (c, a) in cur.iter_mut().zip(&acc) { *c *= 2.0 * sigmoid(*a); } + cur + } +} + +struct Gdn<'a> { + qkv: Mat<'a>, + z: Mat<'a>, + alpha: Mat<'a>, + beta: Mat<'a>, + a: Vec, + dt_bias: Vec, + conv: Vec, + norm: Vec, + out: Mat<'a>, +} + +struct Indexer<'a> { + q_b: Mat<'a>, + k: Mat<'a>, + k_norm: Vec, + proj: Mat<'a>, +} + +struct Mla<'a> { + gate: Mat<'a>, + q_a: Mat<'a>, + q_a_norm: GNorm, + q_b: Mat<'a>, + kv_a: Mat<'a>, + kv_a_norm: GNorm, + k_b: Vec>, + v_b: Vec>, + out: Mat<'a>, + ix: Option>, +} + +enum Mixer<'a> { + Gdn(Gdn<'a>), + Mla(Mla<'a>), +} + +enum Ffn<'a> { + Dense { gate: Mat<'a>, up: Mat<'a>, down: Mat<'a> }, + Moe { gate_inp: Mat<'a>, bias: Vec, gexps: Mat<'a>, uexps: Mat<'a>, dexps: Mat<'a>, gate_sh: Mat<'a>, up_sh: Mat<'a>, down_sh: Mat<'a> }, +} + +struct Layer<'a> { + attn_norm: GNorm, + post_attn_norm: GNorm, + ffn_norm: GNorm, + post_ffw_norm: GNorm, + mixer: Mixer<'a>, + ffn: Ffn<'a>, +} + +/// The MTP block (llama.cpp `graph_mtp`): the embedding of token t and the normed trunk row of token t - 1, joined by +/// `eh_proj`, go through one more MLA layer (`layers[n_layer]`, dense FFN) and a head of their own; its greedy token +/// is the guess at token t + 1. +struct Mtp<'a> { + eh_proj: Mat<'a>, + enorm: GNorm, + hnorm: GNorm, + head_norm: GNorm, + embed: Mat<'a>, + head: Mat<'a>, + /// The normed trunk rows h[m - 1..] not yet fed to the block (h[-1] is zeros); `m` is the rows in its cache. + hs: Vec>, + m: usize, +} + +/// Per-layer cache: DeltaNet conv rows and state, or the MLA latent rows [kv_cmpr, k_pe] (f16, as llama.cpp keeps +/// them) and the indexer keys. +#[derive(Clone, Default)] +struct State { + conv: Vec, + s: Vec, + /// `conv` and `s` live on the GPU (`gdn_prompt`); the host copies are stale. + on_card: bool, + kv: Vec, + ik: Vec, +} + +pub struct GigaChat4Model<'a> { + pub cfg: GigaChat4Config, + tok_embd: Mat<'a>, + out_norm: GNorm, + out_w: Mat<'a>, + layers: Vec>, + state: Vec, + rope: Rope, + /// Share of a layer's VRAM-cache misses that the CPU computes while the GPU runs the rest (see `ffn`). + /// The decode balances in [0]; a prefill chunk in [1 + layer], each layer apart: a chunk's misses are many + /// experts of many tokens each, and how many miss differs a lot between layers (few in the middle ones). + cpu_share: Vec>, + /// Loaded with `MTP` on, and dropped when a draft cannot be rolled back. + mtp: Option>, + /// MTP drafts checked and accepted. + pub drafts: (usize, usize), + pub toks: Vec, + pub trace: bool, +} + +/// SwiGLU, clamped like ggml `swiglu_oai`-free `swiglu_clamp` when `limit` > 0. +fn act(g: f32, u: f32, limit: f32) -> f32 { + if limit > 1e-6 { swiglu_clamp(g, u, limit) } else { silu(g) * u } +} + +/// `x / sqrt(sum x² + eps)` (llama.cpp `build_gdn_l2_norm`). +fn l2_norm(x: &mut [f32], eps: f32) { + let s = 1.0 / (x.iter().map(|v| v * v).sum::() + eps).sqrt(); + for v in x { *v *= s; } +} + +/// NeoX RoPE of the first `2 * rope.n_dims / 2` dims of `x` (pairs i, i + n_dims/2), the rest unrotated. +fn rope_neox(rope: &Rope, x: &mut [f32], pos: usize) { + let h = rope.n_dims / 2; + for i in 0..h { + let (c, s) = rope.cs(pos as f32, i); + let (a, b) = (x[i], x[i + h]); + x[i] = a * c - b * s; + x[i + h] = a * s + b * c; + } +} + +/// The `n` best of `scored` (score, index): highest score first, the lower index on a tie. Returns the indices. +fn top_n(mut scored: Vec<(f32, u32)>, n: usize) -> Vec { + if scored.len() > n { + scored.select_nth_unstable_by(n - 1, |a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))); + scored.truncate(n); + } + scored.into_iter().map(|s| s.1).collect() +} + +/// A SwiGLU FFN on each row of `x`: [t][down rows]. +fn swiglu_rows(gate: &Mat, up: &Mat, down: &Mat, x: &[&[f32]], lim: f32) -> Vec { + let (gy, uy) = (matvec_rows(gate, x), matvec_rows(up, x)); + let a: Vec = gy.iter().zip(&uy).map(|(g, u)| act(*g, *u, lim)).collect(); + matvec_rows(down, &a.chunks_exact(gate.rows).collect::>()) +} + +/// `m` on each row of `xs`, row-major: one GPU round trip for a single token. +fn rows(ms: &[Mat], xs: &[&[f32]]) -> Vec> { + if xs.len() == 1 { + let y = matvec_many(ms, xs[0], 0); + let mut at = 0; + return ms.iter().map(|m| { at += m.rows; y[at - m.rows..at].to_vec() }).collect(); + } + ms.iter().map(|m| matvec_rows(m, xs)).collect() +} + +impl<'a> GigaChat4Model<'a> { + pub fn new(g: &'a Gguf) -> Result { + // More of the expert cache in VRAM: 95% of free VRAM on a card with 8 GB or more free (decode +10% on a + // 12 GB card), the 80% default below that so a smaller card keeps room to stage experts. + if std::env::var_os("STRATA_DS_GPU_FRACTION").is_none() { unsafe { std::env::set_var("STRATA_DS_GPU_FRACTION", "0.8,0.95") } } + let cfg = GigaChat4Config::from_gguf(g)?; + // The K/V rows and indexer keys of the MLA layers and the prefill scratch live outside the expert budget. + // Without room for them at --ctx the expert cache fills VRAM and long prompts fall back to CPU attention + // (prefill dropped from ~400 to ~50 tok/s past 13-33k tokens on a 12 GB card). Before the first Mat::load opens the GPU. + let mla = cfg.recurrent[..cfg.n_layer].iter().filter(|r| !**r).count() + 1; + let kv = mla * cfg.n_ctx * (2 * (cfg.kv_lora + cfg.n_rot) + 4 * cfg.idx_head_dim); + let scratch = 4 * 1024 * cfg.n_ctx + (256 << 20); + crate::deepseek::mat::dev_set_margin(&[crate::deepseek::mat::dev_margin().max(kv * 5 / 4 + scratch)]); + let nextn = |n: &str| format!("blk.{}.nextn.{n}", cfg.n_layer); + let dump = std::env::var_os("STRATA_DS_TRACE").is_some() || std::env::var_os("STRATA_DS_DUMP").is_some(); + let with_mtp = super::MTP.load(std::sync::atomic::Ordering::Relaxed) && !dump && g.tensors.contains_key(&nextn("eh_proj.weight")); + let mut layers = Vec::with_capacity(cfg.n_layer + 1); + for il in 0..cfg.n_layer + with_mtp as usize { + // The MTP block's layer is MLA with a dense FFN. + let last = il == cfg.n_layer; + let name = |n: &str| format!("blk.{il}.{n}"); + let m = |n: &str| Mat::load(g, &name(&format!("{n}.weight"))); + let v = |n: &str| vec_f32(g, &name(n)); + let gn = |n: &str| GNorm::load(g, &name(n)); + let mixer = if !last && cfg.recurrent[il] { + Mixer::Gdn(Gdn { + qkv: m("attn_qkv")?, z: m("attn_gate")?, alpha: m("ssm_alpha")?, beta: m("ssm_beta")?, + a: v("ssm_a")?, dt_bias: v("ssm_dt.bias")?, conv: v("ssm_conv1d.weight")?, norm: v("ssm_norm.weight")?, out: m("ssm_out")?, + }) + } else { + // One VRAM copy a head (`Mat::load` leaves a 3-D tensor on the host). + let nh = cfg.n_head; + let (k_b, v_b) = (Mat::load_groups(g, &name("attn_k_b.weight"), nh)?, Mat::load_groups(g, &name("attn_v_b.weight"), nh)?); + Mixer::Mla(Mla { + gate: m("attn_gate")?, q_a: m("attn_q_a")?, q_a_norm: gn("attn_q_a_norm")?, q_b: m("attn_q_b")?, + kv_a: m("attn_kv_a_mqa")?, kv_a_norm: gn("attn_kv_a_norm")?, + k_b: (0..nh).map(|h| k_b.group(h, nh)).collect(), v_b: (0..nh).map(|h| v_b.group(h, nh)).collect(), + out: m("attn_output")?, + ix: match g.tensors.contains_key(&name("indexer.attn_q_b.weight")) { + true => Some(Indexer { q_b: m("indexer.attn_q_b")?, k: m("indexer.attn_k")?, k_norm: v("indexer.k_norm.weight")?, proj: m("indexer.proj")? }), + false => None, + }, + }) + }; + let ffn = if last || il < cfg.n_dense { + Ffn::Dense { gate: m("ffn_gate")?, up: m("ffn_up")?, down: m("ffn_down")? } + } else { + Ffn::Moe { + gate_inp: m("ffn_gate_inp")?, bias: v("exp_probs_b.bias")?, + gexps: m("ffn_gate_exps")?, uexps: m("ffn_up_exps")?, dexps: m("ffn_down_exps")?, + gate_sh: m("ffn_gate_shexp")?, up_sh: m("ffn_up_shexp")?, down_sh: m("ffn_down_shexp")?, + } + }; + layers.push(Layer { attn_norm: gn("attn_norm")?, post_attn_norm: gn("post_attention_norm")?, ffn_norm: gn("ffn_norm")?, post_ffw_norm: gn("post_ffw_norm")?, mixer, ffn }); + } + let ext = if cfg.rope_scale > 1.0 { 1.0 } else { 0.0 }; + let rope = Rope::new(cfg.rope_base, 1.0 / cfg.rope_scale, ext, cfg.n_rot, cfg.rope_ctx_orig, cfg.beta_fast, cfg.beta_slow); + let mtp = with_mtp.then(|| -> Result> { + Ok(Mtp { + eh_proj: Mat::load(g, &nextn("eh_proj.weight"))?, + enorm: GNorm::load(g, &nextn("enorm"))?, hnorm: GNorm::load(g, &nextn("hnorm"))?, head_norm: GNorm::load(g, &nextn("shared_head_norm"))?, + embed: host_mat(g, &nextn("embed_tokens.weight"))?, + head: Mat::load(g, &nextn("shared_head_head.weight"))?, + hs: vec![], m: 0, + }) + }).transpose()?; + let mut m = GigaChat4Model { + tok_embd: host_mat(g, "token_embd.weight")?, + out_norm: GNorm::load(g, "output_norm")?, + out_w: Mat::load(g, "output.weight")?, + state: vec![State::default(); layers.len()], + rope, + cpu_share: vec![std::cell::Cell::new(0.5); 1 + layers.len()], + mtp, + drafts: (0, 0), + layers, + cfg, + toks: vec![], + trace: std::env::var("STRATA_DS_TRACE").is_ok(), + }; + // STRATA_DS_PIN=1: page-lock the routed experts in the mapped file, so a prompt's staged copies are DMAs from + // there instead of a CPU copy into the pinned ring first. + if std::env::var("STRATA_DS_PIN").is_ok_and(|v| v == "1") { + let t0 = std::time::Instant::now(); + let (mut gb, mut ok) = (0.0, 0usize); + for l in &m.layers { + if let Ffn::Moe { gexps, uexps, dexps, .. } = &l.ffn { + for x in [gexps, uexps, dexps] { + if crate::deepseek::mat::pin_host(x.data) { gb += x.data.len() as f64 / 1e9; ok += 1; } + } + } + } + crate::say!("gigachat4: pinned {gb:.2} GB of experts ({ok} tensors) in {:.1} s", t0.elapsed().as_secs_f64()); + } + m.reset(); + Ok(m) + } + + pub fn reset(&mut self) { + let c = &self.cfg; + let channels = c.ssm_d_inner + 2 * c.ssm_n_group * c.ssm_d_state; + for (il, st) in self.state.iter_mut().enumerate() { + *st = State::default(); + if il < c.n_layer && c.recurrent[il] { + st.conv = vec![0.0; (c.ssm_conv - 1) * channels]; + st.s = vec![0.0; c.ssm_d_inner * c.ssm_d_state]; + } + } + if let Some(mt) = &mut self.mtp { (mt.hs, mt.m) = (vec![vec![0.0; c.n_embd]], 0); } + self.toks.clear(); + } + + fn tr(&self, name: &str, il: i32, v: &[f32]) { + if let Ok(dir) = std::env::var("STRATA_DS_DUMP") { + use std::io::Write; + let fname = if il < 0 { format!("{dir}/{name}.f32") } else { format!("{dir}/{name}-{il}.f32") }; + let bytes: Vec = v.iter().flat_map(|x| x.to_le_bytes()).collect(); + std::fs::OpenOptions::new().create(true).append(true).open(fname).unwrap().write_all(&bytes).unwrap(); + } + if self.trace { + let n = v.len(); + let f = |i: usize| format!("{:12.4}", v[i]); + eprintln!("TRACE {name}-{il} [{} {} {} ... {} {} {}] sum={:.6}", f(0), f(1), f(2), f(n - 3), f(n - 2), f(n - 1), v.iter().sum::()); + } + } + + /// Gated DeltaNet of the consecutive tokens `hs` (llama.cpp `build_layer_attn_linear`), before `ssm_out`'s norm. + fn gdn(&mut self, il: usize, hs: &[&[f32]]) -> Vec { + let c = &self.cfg; + let Mixer::Gdn(w) = &self.layers[il].mixer else { unreachable!() }; + let (dk, nk, nv, kw, eps) = (c.ssm_d_state, c.ssm_n_group, c.ssm_dt_rank, c.ssm_conv, c.eps); + let dv = c.ssm_d_inner / nv; + let channels = c.ssm_d_inner + 2 * nk * dk; + let st = &mut self.state[il]; + // The whole layer on the GPU, its state kept there (the gate's factor 2 goes into the norm weights). + if !self.trace { + let key = st as *const State as usize + 2; + let x: Vec = hs.concat(); + let norm: Vec = w.norm.iter().map(|v| 2.0 * v).collect(); + if let Some(y) = crate::deepseek::mat::gdn_prompt(key, !st.on_card, false, &[w.qkv, w.z, w.beta, w.alpha, w.out], &x, &w.conv, &w.dt_bias, &w.a, &norm, &mut st.conv, &mut st.s, nk, dk, eps) { + st.on_card = true; + return y; + } + // ponytail: a failure after the scan started leaves a half-updated card state; it only fails on allocation. + if st.on_card { st.on_card = !crate::deepseek::mat::gdn_fetch(key, &mut st.conv, &mut st.s); } + } + let p = rows(&[w.qkv, w.z, w.beta, w.alpha], hs); + let mut out = vec![0f32; hs.len() * nv * dv]; + let scale = 1.0 / (dk as f32).sqrt(); + // A prompt chunk scans on the GPU; the norm and gate stay here. + if hs.len() > 1 && !self.trace { + if let Some(o) = crate::deepseek::mat::gdn_scan(&p[0], &p[2], &p[3], &w.conv, &w.dt_bias, &w.a, &mut st.conv, &mut st.s, nk, dk, dv, eps) { + out.par_chunks_exact_mut(dv).zip(o.par_chunks_exact(dv)).enumerate().for_each(|(i, (oh, o))| { + rms_norm_w(o, &w.norm, eps, oh); + for (x, zz) in oh.iter_mut().zip(&p[1][i * dv..(i + 1) * dv]) { *x *= 2.0 * sigmoid(*zz); } + }); + return matvec_rows(&w.out, &out.chunks_exact(nv * dv).collect::>()); + } + } + for t in 0..hs.len() { + let qkv = &p[0][t * channels..(t + 1) * channels]; + let z = &p[1][t * nv * dv..(t + 1) * nv * dv]; + let beta: Vec = p[2][t * nv..(t + 1) * nv].iter().map(|&b| sigmoid(b)).collect(); + let g: Vec = p[3][t * nv..(t + 1) * nv].iter().enumerate().map(|(i, &al)| crate::ops::softplus(al + w.dt_bias[i]) * w.a[i]).collect(); + // Causal depthwise conv over [state..., current], then SiLU. + let mut y = vec![0f32; channels]; + for ch in 0..channels { + let mut acc = qkv[ch] * w.conv[ch * kw + kw - 1]; + for k in 0..kw - 1 { acc += st.conv[k * channels + ch] * w.conv[ch * kw + k]; } + y[ch] = silu(acc); + } + st.conv.copy_within(channels.., 0); + st.conv[(kw - 2) * channels..].copy_from_slice(qkv); + let (q, rest) = y.split_at_mut(nk * dk); + let (k, v) = rest.split_at_mut(nk * dk); + for h in q.chunks_exact_mut(dk).chain(k.chunks_exact_mut(dk)) { l2_norm(h, eps); } + let (q, k, v) = (&*q, &*k, &*v); + let o = &mut out[t * nv * dv..(t + 1) * nv * dv]; + st.s.par_chunks_exact_mut(dv * dk).zip(o.par_chunks_exact_mut(dv)).enumerate().for_each(|(vh, (sm, oh))| { + // v-head vh reads k-head vh / (nv / nk) (ggml repeats each k-head for consecutive v-heads) + let kh = vh / (nv / nk); + let (qh, khv, vv) = (&q[kh * dk..(kh + 1) * dk], &k[kh * dk..(kh + 1) * dk], &v[vh * dv..(vh + 1) * dv]); + let decay = g[vh].exp(); + let mut o = vec![0f32; dv]; + for j in 0..dv { + let row = &mut sm[j * dk..(j + 1) * dk]; + for x in row.iter_mut() { *x *= decay; } + let sk: f32 = row.iter().zip(khv).map(|(a, b)| a * b).sum(); + let d = beta[vh] * (vv[j] - sk); + for (r, kk) in row.iter_mut().zip(khv) { *r += d * kk; } + o[j] = row.iter().zip(qh).map(|(a, b)| a * b).sum::() * scale; + } + rms_norm_w(&o, &w.norm, eps, oh); + for (x, zz) in oh.iter_mut().zip(&z[vh * dv..(vh + 1) * dv]) { *x *= 2.0 * sigmoid(*zz); } + }); + } + matvec_rows(&w.out, &out.chunks_exact(nv * dv).collect::>()) + } + + /// The positions a query at `pos` attends by the lightning indexer, or None for all of them. + fn select(&self, il: usize, iq: &[f32], iw: &[f32], pos: usize) -> Option> { + let c = &self.cfg; + if pos < c.idx_top_k { return None; } + let (hd, ik) = (c.idx_head_dim, &self.state[il].ik); + let scored: Vec<(f32, u32)> = (0..=pos as u32).into_par_iter().map(|j| { + let kj = &ik[j as usize * hd..][..hd]; + (iq.chunks_exact(hd).zip(iw).map(|(q, w)| q.iter().zip(kj).map(|(a, b)| a * b).sum::().max(0.0) * w).sum(), j) + }).collect(); + let mut sel = top_n(scored, c.idx_top_k); + sel.sort_unstable(); + Some(sel) + } + + /// MLA attention of the consecutive tokens `hs` from position `p0` (llama.cpp `build_layer_attn_mla`). + fn mla(&mut self, il: usize, hs: &[&[f32]], p0: usize) -> Vec { + let c = &self.cfg; + let Mixer::Mla(w) = &self.layers[il].mixer else { unreachable!() }; + let (nt, nh, kd, kl, nr, eps) = (hs.len(), c.n_head, c.k_mla, c.kv_lora, c.n_rot, c.eps); + let (row, vd) = (kl + nr, c.v_mla); + let mut ms = vec![w.gate, w.q_a, w.kv_a]; + if let Some(ix) = &w.ix { ms.extend([ix.k, ix.proj]); } + let p = rows(&ms, hs); + let alpha_q = (c.n_embd as f32 / c.q_lora as f32).sqrt(); + let alpha_kv = (c.n_embd as f32 / kl as f32).sqrt(); + let qr: Vec = p[1].par_chunks_exact(c.q_lora).flat_map_iter(|x| w.q_a_norm.apply(x, eps).into_iter().map(|v| v * alpha_q)).collect(); + let qrs: Vec<&[f32]> = qr.chunks_exact(c.q_lora).collect(); + // one decode token past the indexer's window: its indexer query rides with q (one round trip) + let long: Vec = (0..nt).filter(|&t| w.ix.is_some() && p0 + t >= c.idx_top_k).collect(); + let (mut q, mut iq) = match &w.ix { + Some(ix) if nt == 1 && long.len() == 1 => { let mut r = rows(&[w.q_b, ix.q_b], &qrs); let iq = r.pop(); (r.pop().unwrap(), iq) } + _ => (matvec_rows(&w.q_b, &qrs), None), + }; + if nt == 1 { self.tr("q", il as i32, &q); } + let rope = &self.rope; + let kvs: Vec = p[2].par_chunks_exact(row).enumerate().flat_map_iter(|(t, kv)| { + let mut k_pe = kv[kl..].to_vec(); + rope.apply(&mut k_pe, p0 + t, false); + let lat: Vec = w.kv_a_norm.apply(&kv[..kl], eps).into_iter().map(|v| v * alpha_kv).collect(); + lat.into_iter().chain(k_pe).map(f16::from_f32).collect::>() + }).collect(); + self.state[il].kv.extend(kvs); + q.par_chunks_exact_mut(nh * kd).enumerate().for_each(|(t, qt)| { + for h in qt.chunks_exact_mut(kd) { rope.apply(h, p0 + t, false); } + }); + // indexer keys of these tokens, then each query's selection + let mut sels: Vec>> = vec![None; nt]; + if let Some(ix) = &w.ix { + let hd = c.idx_head_dim; + for t in 0..nt { + let mut ik = vec![0f32; hd]; + rms_norm(&p[3][t * hd..(t + 1) * hd], 1e-6, &mut ik); + for (x, n) in ik.iter_mut().zip(&ix.k_norm) { *x *= n; } + rope_neox(&self.rope, &mut ik, p0 + t); + self.state[il].ik.extend_from_slice(&ik); + } + if !long.is_empty() { + let mut iq = iq.take().unwrap_or_else(|| matvec_rows(&ix.q_b, &long.iter().map(|&t| qrs[t]).collect::>())); + let sc = 1.0 / ((hd * c.idx_n_head) as f32).sqrt(); + let nq = c.idx_n_head * hd; + let rope = &self.rope; + iq.par_chunks_exact_mut(nq).zip(&long).for_each(|(q, &t)| { + for h in q.chunks_exact_mut(hd) { rope_neox(rope, h, p0 + t); } + }); + let iw: Vec = long.iter().flat_map(|&t| &p[4][t * c.idx_n_head..(t + 1) * c.idx_n_head]).map(|v| v * sc).collect(); + // On the GPU: the scores of every query over all the keys, then each query's top keys among its own. + let ik = &self.state[il].ik; + let key = &self.state[il] as *const _ as usize + 1; + let gpu = (!self.trace).then(|| crate::deepseek::mat::idx_score(key, p0, ik, &iq, &iw, c.idx_n_head, hd)).flatten(); + if let Some(scores) = gpu { + let nk = ik.len() / hd; + let got: Vec> = long.par_iter().enumerate().map(|(i, &t)| { + let mut sel = top_n(scores[i * nk..i * nk + p0 + t + 1].iter().copied().zip(0u32..).collect(), c.idx_top_k); + sel.sort_unstable(); + sel + }).collect(); + for (&t, s) in long.iter().zip(got) { sels[t] = Some(s); } + } else { + for (i, &t) in long.iter().enumerate() { + sels[t] = self.select(il, &iq[i * nq..(i + 1) * nq], &iw[i * c.idx_n_head..(i + 1) * c.idx_n_head], p0 + t); + } + } + } + } + let mscale = c.mscale(); + let scale = mscale * mscale / (kd as f32).sqrt(); + let gpu = !self.trace && std::env::var_os("STRATA_GIGA_CPU_ATTN").is_none(); + // Each query's key list for `mla_attn`: its selection, or all its positions when the prompt has a selection. + let lists = || { + let ns = sels.iter().enumerate().map(|(t, s)| s.as_ref().map_or(p0 + t + 1, |s| s.len())).max().unwrap(); + let mut idx = vec![0u32; nt * ns]; + let cnt: Vec = sels.iter().zip(idx.chunks_exact_mut(ns)).enumerate().map(|(t, (s, r))| match s { + Some(s) => { r[..s.len()].copy_from_slice(s); s.len() as i32 } + None => { for (i, x) in r[..p0 + t + 1].iter_mut().enumerate() { *x = i as u32; } (p0 + t + 1) as i32 } + }).collect(); + (idx, ns, cnt) + }; + let all = sels.iter().all(|s| s.is_none()); + let causal = || (0..nt).map(|t| (p0 + t + 1) as i32).collect::>(); + // Absorption, attention and the value maps in one GPU round trip. + let fused = gpu.then(|| { + let key = &self.state[il] as *const _ as usize; + let kc: &[u16] = self.state[il].kv[..(p0 + nt) * row].reinterpret_cast(); + if all { return crate::deepseek::mat::mla_prompt(key, p0, &q, kc, None, &causal(), &w.k_b, &w.v_b, row, scale); } + let (idx, ns, cnt) = lists(); + crate::deepseek::mat::mla_prompt(key, p0, &q, kc, Some((&idx, ns)), &cnt, &w.k_b, &w.v_b, row, scale) + }).flatten(); + let mut heads = match fused { + Some(h) => h, + None => self.mla_heads(il, &q, &sels, p0, scale, gpu, &lists, &causal), + }; + if nt == 1 { self.tr("attn_pregate", il as i32, &heads); } + heads.par_chunks_mut(4096).zip(p[0].par_chunks(4096)).for_each(|(h, g)| for (x, g) in h.iter_mut().zip(g) { *x *= sigmoid(*g); }); + matvec_rows(&w.out, &heads.chunks_exact(nh * vd).collect::>()) + } + + /// The heads [t][head][vd] of an MLA layer, step by step: absorbed queries, attention (GPU or CPU), value maps. + #[allow(clippy::too_many_arguments)] + fn mla_heads(&self, il: usize, q: &[f32], sels: &[Option>], p0: usize, scale: f32, gpu: bool, lists: &dyn Fn() -> (Vec, usize, Vec), causal: &dyn Fn() -> Vec) -> Vec { + let c = &self.cfg; + let Mixer::Mla(w) = &self.layers[il].mixer else { unreachable!() }; + let (nt, nh, kd, kl, nr) = (sels.len(), c.n_head, c.k_mla, c.kv_lora, c.n_rot); + let (nope, row, vd) = (kd - nr, kl + nr, c.v_mla); + // Absorbed query per head: [k_b q_nope (kl), q_pe (nr)] + // All heads in one batch (head after head, each on its nt rows). + let mut qc = vec![0f32; nt * nh * row]; + let x: Vec = (0..nh).flat_map(|h| (0..nt).flat_map(move |t| (t * nh + h) * kd..(t * nh + h) * kd + nope)).map(|i| q[i]).collect(); + let ys = matvec_rows_many(&w.k_b.iter().map(|m| (*m, nt)).collect::>(), &x); + for h in 0..nh { + let y = &ys[h * nt * kl..(h + 1) * nt * kl]; + for t in 0..nt { + let dst = &mut qc[(t * nh + h) * row..][..row]; + dst[..kl].copy_from_slice(&y[t * kl..(t + 1) * kl]); + dst[kl..].copy_from_slice(&q[(t * nh + h) * kd + nope..][..nr]); + } + } + if nt == 1 { self.tr("Qcur", il as i32, &qc); } + let cache = &self.state[il].kv; + // On the GPU (`mla_attn`, the queries pre-scaled): each query brings its list of keys when one has a selection. + let key = &self.state[il] as *const _ as usize; + let on_gpu = gpu.then(|| { + let q: Vec = qc.iter().map(|v| v * scale).collect(); + let kc: &[u16] = cache[..(p0 + nt) * row].reinterpret_cast(); + if sels.iter().all(|s| s.is_none()) { return crate::deepseek::mat::mla_attn(key, p0, &q, kc, None, &causal(), nh, row, kl); } + let (idx, ns, cnt) = lists(); + crate::deepseek::mat::mla_attn(key, p0, &q, kc, Some((&idx, ns)), &cnt, nh, row, kl) + }).flatten(); + // Else one task per token and group of 4 heads; V is the first kl dims of each row. + const G: usize = 4; + let ast = if on_gpu.is_some() { kl } else { row }; + let att = on_gpu.unwrap_or_else(|| { + let mut att = vec![0f32; nt * nh * row]; + att.par_chunks_mut(G * row).enumerate().for_each(|(i, o)| { + let t = i * G / nh; + let pos = p0 + t; + let gathered: Vec; + let k: &[f16] = match &sels[t] { + Some(sel) => { gathered = sel.iter().flat_map(|&p| &cache[p as usize * row..][..row]).copied().collect(); &gathered } + None => &cache[..(pos + 1) * row], + }; + let nk = k.len() / row; + let qh = &qc[i * G * row..][..o.len()]; + let mut p = vec![0f32; o.len() / row * nk]; + dots_h(&mut p, scale, k, qh, nk); + for p in p.chunks_exact_mut(nk) { + let mx = p.iter().cloned().fold(f32::MIN, f32::max); + let mut z = 0f32; + for s in p.iter_mut() { *s = (*s - mx).exp(); z += *s; } + for s in p.iter_mut() { *s /= z; } + } + mix_h(o, &p, k, nk); + }); + att + }); + let mut heads = vec![0f32; nt * nh * vd]; + let x: Vec = (0..nh).flat_map(|h| (0..nt).flat_map(move |t| (t * nh + h) * ast..(t * nh + h) * ast + kl)).map(|i| att[i]).collect(); + let ys = matvec_rows_many(&w.v_b.iter().map(|m| (*m, nt)).collect::>(), &x); + for h in 0..nh { + let y = &ys[h * nt * vd..(h + 1) * nt * vd]; + for t in 0..nt { heads[(t * nh + h) * vd..][..vd].copy_from_slice(&y[t * vd..(t + 1) * vd]); } + } + heads + } + + /// The (gate, up) clamps of layer `il`: routed experts, shared expert / dense FFN. + fn clamps(&self, il: usize) -> (f32, f32) { + // The MTP block's FFN is a plain SwiGLU (the clamp arrays have an entry for it all the same). + if il >= self.cfg.n_layer { return (0.0, 0.0); } + (self.cfg.clamp_exp.get(il).copied().unwrap_or(0.0), self.cfg.clamp_shexp.get(il).copied().unwrap_or(0.0)) + } + + /// The FFN of 1 to 4 tokens (a decode step, or a step with an MTP draft), [t][n_embd]: the routed experts the + /// tokens picked run once for all of them. One token takes the plain decode path. + fn ffn(&self, il: usize, curs: &[Vec]) -> Vec { + let cfg = &self.cfg; + let (lim, lim_sh) = self.clamps(il); + let nt = curs.len(); + let xs: Vec<&[f32]> = curs.iter().map(|c| c.as_slice()).collect(); + match &self.layers[il].ffn { + Ffn::Dense { gate, up, down } if nt == 1 => { + let y = matvec_many(&[*gate, *up], xs[0], 0); + let a: Vec = (0..gate.rows).map(|i| act(y[i], y[gate.rows + i], lim_sh)).collect(); + let mut out = vec![0f32; down.rows]; + down.matvec(&a, &mut out); + out + } + Ffn::Dense { gate, up, down } => swiglu_rows(gate, up, down, &xs, lim_sh), + Ffn::Moe { gate_inp, bias, gexps, uexps, dexps, gate_sh, up_sh, down_sh } => { + let ne = cfg.n_expert; + // The shared expert rides with the routed ones on the GPU (weight 1) when both have the same clamp; a + // tensor dump keeps it apart. + let apart = self.trace || std::env::var_os("STRATA_DS_DUMP").is_some() || crate::deepseek::mat::dev_info().is_none() || lim != lim_sh; + // [router logits], then [shared gate], [shared up] when apart; each [t][rows] + let y = if apart { rows(&[*gate_inp, *gate_sh, *up_sh], &xs) } else { rows(&[*gate_inp], &xs) }; + if nt == 1 { self.tr("ffn_moe_logits", il as i32, &y[0]); } + let sels: Vec> = y[0].chunks_exact(ne).map(|l| route_sigmoid(l, bias, cfg.n_used, cfg.expert_norm, cfg.expert_scale)).collect(); + // The experts of all the tokens, in the order they first appear; `wt` is a token's weight of one. + let mut ex: Vec = vec![]; + for &(e, _) in sels.iter().flatten() { if !ex.contains(&e) { ex.push(e); } } + let wt = |t: usize, e: usize| sels[t].iter().find(|s| s.0 == e).map(|s| s.1); + if std::env::var_os("STRATA_DS_NOPREFETCH").is_none() { + for &e in &ex { + for m in [gexps, uexps, dexps] { m.prefetch_expert(e, ne); } + } + } + let nl = dexps.rows / ne; + // Experts resident in VRAM run on the GPU; of the others the CPU computes `cpu_share` while the GPU + // uploads and runs the rest (as in `kolibri::forward`). + let (share, fixed) = self.share(0); + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, true); if x.gpu.is_some() { x } else { x.staged() } }; + // An expert is a hit only when its three matrices are in VRAM (each has its own slot). + let mats: Vec<[Mat; 3]> = ex.iter().map(|&e| [gexps, uexps, dexps].map(|m| m.expert_opt(e, ne, share == 0.0))).collect(); + let miss = |m: &[Mat; 3]| m.iter().any(|x| x.gpu.is_none()); + let n_miss = mats.iter().filter(|m| miss(m)).count(); + let mut left = (share * n_miss as f32).round() as usize; + let (mut on_gpu, mut on_cpu) = (vec![], vec![]); + for (m, &e) in mats.into_iter().zip(&ex) { + if miss(&m) && left > 0 { + left -= 1; + on_cpu.push((gexps.expert_host(e, ne), uexps.expert_host(e, ne), dexps.expert_host(e, ne), e)); + } else { + on_gpu.push((m, e)); + } + } + // Each token runs the experts of `list` it picked (an expert of None, the shared one, with weight 1). + let per_token = |list: &[(Mat<'a>, Mat<'a>, Mat<'a>, Option)]| -> Vec { + (0..nt).flat_map(|t| { + let mine: Vec<_> = list.iter().filter_map(|&(g, u, d, e)| e.map_or(Some(1.0), |e| wt(t, e)).map(|w| (g, u, d, w))).collect(); + run_experts(&mine, xs[t], lim, nl) + }).collect() + }; + let cpu_side = || { + let t = std::time::Instant::now(); + if nt == 1 { + let list: Vec<_> = on_cpu.iter().map(|&(g, u, d, e)| (g, u, d, Some(e))).collect(); + return (per_token(&list), t.elapsed().as_secs_f32()); + } + // Each expert read once for the tokens that picked it. + let mut mix = vec![0f32; nt * nl]; + for &(g, u, d, e) in &on_cpu { + let ts: Vec<(usize, f32)> = (0..nt).filter_map(|t| wt(t, e).map(|w| (t, w))).collect(); + let y = swiglu_rows(&g, &u, &d, &ts.iter().map(|&(t, _)| xs[t]).collect::>(), lim); + for (&(t, w), y) in ts.iter().zip(y.chunks_exact(nl)) { + for (m, v) in mix[t * nl..(t + 1) * nl].iter_mut().zip(y) { *m += w * v; } + } + } + (mix, t.elapsed().as_secs_f32()) + }; + let gpu_side = || { + let t = std::time::Instant::now(); + let pick = |x: Mat<'a>, m: &Mat<'a>, e: usize| if x.gpu.is_some() { x } else { on(m, e) }; + let mut list: Vec<_> = on_gpu.iter().map(|&([g, u, d], e)| (pick(g, gexps, e), pick(u, uexps, e), pick(d, dexps, e), Some(e))).collect(); + if !apart { list.push((*gate_sh, *up_sh, *down_sh, None)); } + // One round trip for all of them (gates and ups, clamp, downs), else two a token. + if !list.is_empty() && std::env::var_os("STRATA_KOL_NOCHUNK").is_none() { + let col = |i: usize| -> Vec { list.iter().map(|g| [g.0, g.1, g.2][i]).collect() }; + if let Some(dy) = crate::deepseek::mat::swiglu_experts(&col(0), &col(1), &col(2), &xs.concat(), nt, lim) { + let mut mix = vec![0f32; nt * nl]; + for (e, d) in list.iter().zip(dy.chunks(nt * nl)) { + for (t, (m, d)) in mix.chunks_exact_mut(nl).zip(d.chunks_exact(nl)).enumerate() { + let Some(w) = e.3.map_or(Some(1.0), |e| wt(t, e)) else { continue }; + for (m, v) in m.iter_mut().zip(d) { *m += w * v; } + } + } + return (mix, t.elapsed().as_secs_f32()); + } + } + (per_token(&list), t.elapsed().as_secs_f32()) + }; + let ((a, tg), (b, tc)) = rayon::join(gpu_side, cpu_side); + if !fixed && n_miss > 0 { self.balance(0, tg, tc); } + let mut mix: Vec = a.iter().zip(&b).map(|(a, b)| a + b).collect(); + if !apart { return mix; } + if nt == 1 { self.tr("ffn_moe_out", il as i32, &mix); } + let ng = gate_sh.rows; + for (t, m) in mix.chunks_exact_mut(nl).enumerate() { + let a: Vec = (0..ng).map(|i| act(y[1][t * ng + i], y[2][t * ng + i], lim_sh)).collect(); + let mut s = vec![0f32; down_sh.rows]; + down_sh.matvec(&a, &mut s); + if nt == 1 { self.tr("ffn_shared", il as i32, &s); } + for (m, v) in m.iter_mut().zip(&s) { *m += v; } + } + mix + } + } + } + + /// The CPU's share of a layer's VRAM-cache misses, and whether it is fixed (no GPU, or set by the user). + fn share(&self, i: usize) -> (f32, bool) { + static FIXED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let fixed = *FIXED.get_or_init(|| { + let share = std::env::var("STRATA_DS_CPU_SHARE").ok().and_then(|v| v.parse().ok()); + share.or(std::env::var_os("STRATA_FIXED_EXPERTS").map(|_| 0.0)) + }); + if crate::deepseek::mat::dev_info().is_none() { return (1.0, true); } + (fixed.unwrap_or(self.cpu_share[i].get()).clamp(0.0, 1.0), fixed.is_some()) + } + + fn balance(&self, i: usize, tg: f32, tc: f32) { + let c = &self.cpu_share[i]; + if tg + tc > 0.0 { c.set((c.get() + 0.1 * (tg - tc) / (tg + tc)).clamp(0.0, 1.0)); } + } + + /// `ffn` for the tokens of a prefill chunk, token-major. A routed expert is read once and applied to every token + /// that picked it; the experts are split between the GPU and the CPU like the misses in `ffn`. + fn ffn_batch(&self, il: usize, curs: &[Vec]) -> Vec { + let cfg = &self.cfg; + let (lim, lim_sh) = self.clamps(il); + let xs: Vec<&[f32]> = curs.iter().map(|c| c.as_slice()).collect(); + let swiglu = swiglu_rows; + match &self.layers[il].ffn { + Ffn::Dense { gate, up, down } => swiglu(gate, up, down, &xs, lim_sh), + Ffn::Moe { gate_inp, bias, gexps, uexps, dexps, gate_sh, up_sh, down_sh } => { + let ne = cfg.n_expert; + let (nf, nl) = (gexps.rows / ne, dexps.rows / ne); + let logits = matvec_rows(gate_inp, &xs); + let sels: Vec> = logits.par_chunks_exact(ne).map(|l| route_sigmoid(l, bias, cfg.n_used, cfg.expert_norm, cfg.expert_scale)).collect(); + let mut by_e: std::collections::BTreeMap> = Default::default(); + for (t, sel) in sels.iter().enumerate() { + for (k, &(e, _)) in sel.iter().enumerate() { by_e.entry(e).or_default().push((t, k)); } + } + if std::env::var_os("STRATA_DS_NOPREFETCH").is_none() { + by_e.keys().collect::>().par_iter().for_each(|&&e| { + for m in [gexps, uexps, dexps] { m.prefetch_expert_whole(e, ne); } + }); + } + let (share, fixed) = self.share(1 + il); + // A chunk never evicts: its misses stream through `swiglu_chunk`'s slots or run on the CPU, and + // admitting each would thrash the cache the decode needs (hits fell to 0 with the share at 0). + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, false); if x.gpu.is_some() { x } else { x.staged() } }; + let gates: Vec<(usize, Mat)> = by_e.keys().map(|&e| (e, gexps.expert_opt(e, ne, false))).collect(); + // The CPU takes the misses with the fewest tokens: its time grows with the tokens, while a staged + // expert costs the GPU mostly its copy. + let mut misses: Vec = gates.iter().filter(|g| g.1.gpu.is_none()).map(|g| g.0).collect(); + let n_miss = misses.len(); + misses.sort_by_key(|e| by_e[e].len()); + misses.truncate((share * n_miss as f32).round() as usize); + let (mut on_gpu, mut on_cpu) = (vec![], vec![]); + for (e, g) in gates { + if g.gpu.is_none() && misses.contains(&e) { + on_cpu.push((e, g, uexps.expert_host(e, ne), dexps.expert_host(e, ne))); + } else { + on_gpu.push((e, if g.gpu.is_some() { g } else { g.staged() }, on(uexps, e), on(dexps, e))); + } + } + let rows_of = |e: usize| -> Vec<&[f32]> { by_e[&e].iter().map(|&(t, _)| xs[t]).collect() }; + let gpu = || { + let t = std::time::Instant::now(); + // One round trip for all the experts (as in `kolibri::forward`): the per-token weighted sums come + // back; the shared expert rides along in slot `n_used` with weight 1 when it has the same clamp. + if std::env::var_os("STRATA_KOL_NOCHUNK").is_none() { + let sh = (lim == lim_sh).then_some([gate_sh, up_sh, down_sh]); + let col = |i: usize| -> Vec { on_gpu.iter().map(|g| [g.1, g.2, g.3][i]).chain(sh.map(|s| *s[i])).collect() }; + let mut pairs: Vec> = on_gpu.iter().map(|(e, ..)| by_e[e].iter().map(|&(t, k)| (t, k, sels[t][k].1)).collect()).collect(); + if sh.is_some() { pairs.push((0..xs.len()).map(|t| (t, cfg.n_used, 1.0)).collect()); } + if !col(0).is_empty() && let Some(sum) = swiglu_chunk(&col(0), &col(1), &col(2), &pairs, &xs.concat(), cfg.n_used + 1, lim) { + return (vec![], Some((sum, sh.is_some())), t.elapsed().as_secs_f32()); + } + } + let n_of = |e: &usize| by_e[e].len(); + let mut x = Vec::with_capacity(2 * on_gpu.iter().map(|(e, ..)| n_of(e)).sum::() * cfg.n_embd); + for (e, ..) in &on_gpu { + for _ in 0..2 { for &(t, _) in &by_e[e] { x.extend_from_slice(xs[t]); } } + } + let y = matvec_rows_many(&on_gpu.iter().flat_map(|(e, g, u, _)| [(*g, n_of(e)), (*u, n_of(e))]).collect::>(), &x); + let mut a = Vec::with_capacity(y.len() / 2); + let mut at = 0; + for (e, ..) in &on_gpu { + let n = n_of(e) * nf; + a.extend(y[at..at + n].iter().zip(&y[at + n..at + 2 * n]).map(|(g, u)| act(*g, *u, lim))); + at += 2 * n; + } + let dy = matvec_rows_many(&on_gpu.iter().map(|(e, _, _, d)| (*d, n_of(e))).collect::>(), &a); + let mut at = 0; + let out: Vec<(usize, Vec)> = on_gpu.iter().map(|(e, ..)| { at += n_of(e) * nl; (*e, dy[at - n_of(e) * nl..at].to_vec()) }).collect(); + (out, None, t.elapsed().as_secs_f32()) + }; + let cpu = || { + let t = std::time::Instant::now(); + let out: Vec<(usize, Vec)> = on_cpu.par_iter().map(|(e, g, u, d)| (*e, swiglu(g, u, d, &rows_of(*e), lim))).collect(); + (out, t.elapsed().as_secs_f32()) + }; + let ((a, gsum, tg), (b, tc)) = rayon::join(gpu, cpu); + if !fixed && n_miss > 0 { self.balance(1 + il, tg, tc); } + // Each token sums its experts in its own selection order, as `ffn` does; the shared expert is added last. + let mut ds: Vec> = sels.iter().map(|s| vec![&[][..]; s.len()]).collect(); + for (e, dy) in a.iter().chain(&b) { + for (&(t, k), d) in by_e[e].iter().zip(dy.chunks_exact(nl)) { ds[t][k] = d; } + } + let mut mix = if gsum.as_ref().is_some_and(|g| g.1) { vec![0f32; xs.len() * nl] } else { swiglu(gate_sh, up_sh, down_sh, &xs, lim_sh) }; + mix.par_chunks_exact_mut(nl).enumerate().for_each(|(t, m)| { + let mut sum = vec![0f32; nl]; + // An expert of the device's chunk has no row here: its weighted output is in `gsum`. + for (d, &(_, w)) in ds[t].iter().zip(&sels[t]).filter(|(d, _)| !d.is_empty()) { + for j in 0..nl { sum[j] += w * d[j]; } + } + if let Some((g, _)) = &gsum { for j in 0..nl { sum[j] += g[t * nl + j]; } } + for j in 0..nl { m[j] += sum[j]; } + }); + mix + } + } + } + + pub fn step(&mut self, tok: u32) -> Vec { + self.forward(&[tok], true) + } + + /// Run `toks` through the model; logits only for the last one. All but the last go in chunks of + /// `STRATA_DS_CHUNK` tokens (default 1024, or 1 with a tensor dump). + pub fn prefill(&mut self, toks: &[u32]) -> Vec { + let Some((&last, head)) = toks.split_last() else { return vec![] }; + let dump = self.trace || std::env::var_os("STRATA_DS_DUMP").is_some(); + let chunk: usize = std::env::var("STRATA_DS_CHUNK").ok().and_then(|v| v.parse().ok()).unwrap_or(if dump { 1 } else { 1024 }); + for c in head.chunks(chunk.max(1)) { self.forward(c, false); crate::term::prefilled(c.len()); } + self.step(last) + } + + /// Layer-major pass over consecutive tokens; the logits of the last one when `want`. + fn forward(&mut self, toks: &[u32], want: bool) -> Vec { + let xs = self.trunk(toks); + let eps = self.cfg.eps; + if self.mtp.is_none() { + return if want { self.head(&self.out_norm.apply(&xs[xs.len() - 1], eps)) } else { vec![] }; + } + // The MTP block reads every normed row; it runs once a few have gathered (a draft takes the rest). + let hn: Vec> = xs.par_iter().map(|x| self.out_norm.apply(x, eps)).collect(); + let logits = if want { self.head(&hn[hn.len() - 1]) } else { vec![] }; + let mt = self.mtp.as_mut().unwrap(); + mt.hs.extend(hn); + if mt.hs.len() > 3 { self.feed(); } + logits + } + + /// The trunk over consecutive tokens, layer by layer: the rows after the last layer, before the output norm. + fn trunk(&mut self, toks: &[u32]) -> Vec> { + let t0 = std::time::Instant::now(); + let (n, nt) = (self.cfg.n_embd, toks.len()); + let p0 = self.toks.len(); + self.toks.extend_from_slice(toks); + let mut xs: Vec> = toks.iter().map(|&t| { + let mut emb = vec![0f32; n]; + self.tok_embd.row_into(t as usize, &mut emb); + emb + }).collect(); + let mut tm = [0f64; 3]; + for il in 0..self.cfg.n_layer { + for (a, b) in tm.iter_mut().zip(self.layer(il, &mut xs, p0)) { *a += b; } + } + if std::env::var_os("STRATA_DS_PROF").is_some() { + use std::sync::atomic::Ordering::Relaxed; + let ex = &crate::deepseek::mat::EX_LOOKUPS; + eprintln!("PROF {nt} at {p0}: {:.0} ms (attn {:.0} of it mla {:.0}, ffn {:.0}), expert cache hit {} miss {}, cpu share {:.2} (prefill: mean of the layers)", + t0.elapsed().as_secs_f64() * 1e3, tm[0] * 1e3, tm[1] * 1e3, tm[2] * 1e3, ex[0].swap(0, Relaxed), ex[1].swap(0, Relaxed), if nt > 1 { self.cpu_share[1..].iter().map(|c| c.get()).sum::() / (self.cpu_share.len() - 1) as f32 } else { self.cpu_share[0].get() }); + } + xs + } + + /// Layer `il` on the rows `xs` of consecutive tokens from position `p0`, in place. Returns the seconds of the + /// attention (with its norms and residual), of the MLA in it, and of the FFN. + fn layer(&mut self, il: usize, xs: &mut [Vec], p0: usize) -> [f64; 3] { + let (n, nt, eps) = (self.cfg.n_embd, xs.len(), self.cfg.eps); + let t = std::time::Instant::now(); + let mut t_mla = 0.0; + let hs: Vec> = xs.par_iter().map(|x| self.layers[il].attn_norm.apply(x, eps)).collect(); + if nt == 1 { self.tr("attn_norm", il as i32, &hs[0]); } + let hr: Vec<&[f32]> = hs.iter().map(|h| h.as_slice()).collect(); + let att = if matches!(self.layers[il].mixer, Mixer::Gdn(_)) { self.gdn(il, &hr) } else { let t = std::time::Instant::now(); let a = self.mla(il, &hr, p0); t_mla = t.elapsed().as_secs_f64(); a }; + if nt == 1 { self.tr("attn_out", il as i32, &att); } + xs.par_iter_mut().zip(att.par_chunks_exact(n)).for_each(|(x, a)| { + for (x, a) in x.iter_mut().zip(self.layers[il].post_attn_norm.apply(a, eps)) { *x += a; } + }); + if nt == 1 { self.tr("attn_residual", il as i32, &xs[0]); } + let t_attn = t.elapsed().as_secs_f64(); + let t = std::time::Instant::now(); + let hs: Vec> = xs.par_iter().map(|x| self.layers[il].ffn_norm.apply(x, eps)).collect(); + if nt == 1 { self.tr("ffn_norm", il as i32, &hs[0]); } + // A few tokens with MTP (a draft check) go the decode way: each picked expert once for all of them. + let f = if nt == 1 || (nt <= 4 && self.mtp.is_some()) { self.ffn(il, &hs) } else { self.ffn_batch(il, &hs) }; + if nt == 1 { self.tr("ffn_out", il as i32, &f); } + xs.par_iter_mut().zip(f.par_chunks_exact(n)).for_each(|(x, a)| { + for (x, a) in x.iter_mut().zip(self.layers[il].post_ffw_norm.apply(a, eps)) { *x += a; } + }); + if nt == 1 { self.tr("l_out", il as i32, &xs[0]); } + [t_attn, t_mla, t.elapsed().as_secs_f64()] + } + + /// The soft-capped logits of a row after the output norm. + fn head(&self, cur: &[f32]) -> Vec { + self.tr("result_norm", -1, cur); + let mut logits = vec![0f32; self.out_w.rows]; + self.out_w.matvec(cur, &mut logits); + let cap = self.cfg.softcap; + if cap > 0.0 { for l in logits.iter_mut() { *l = (*l / cap).tanh() * cap; } } + self.tr("result_output", -1, &logits); + logits + } + + /// Whether `draft` and `verify` can run: the MTP block is loaded and every DeltaNet layer has its matrices in VRAM + /// of the first GPU (else `gdn_prompt` keeps no state to step back to). + pub fn mtp_ready(&self) -> bool { + use crate::deepseek::mat::dev::{STAGED, gpu_of}; + let first = |m: &Mat<'a>| m.gpu.is_some_and(|i| i != STAGED && gpu_of(i) == 0); + self.mtp.is_some() && self.layers.iter().all(|l| match &l.mixer { + Mixer::Gdn(w) => [w.qkv, w.z, w.beta, w.alpha, w.out].iter().all(first), + Mixer::Mla(_) => true, + }) + } + + /// Feed the MTP block every gathered row but the last (that one waits for its next token). + fn feed(&mut self) { + let mt = self.mtp.as_mut().unwrap(); + let mut hs = std::mem::take(&mut mt.hs); + let last = hs.pop().unwrap(); + let toks = self.toks[mt.m..].to_vec(); + self.mtp_run(&hs, &toks, false); + self.mtp.as_mut().unwrap().hs.push(last); + } + + /// The MTP block on positions m.. (row h[t - 1] and token t each); the head's logits of the last when `want`. + fn mtp_run(&mut self, hs: &[Vec], toks: &[u32], want: bool) -> Vec { + assert_eq!(hs.len(), toks.len()); + let (n, eps, il) = (self.cfg.n_embd, self.cfg.eps, self.cfg.n_layer); + let Some(mt) = &self.mtp else { return vec![] }; + let cat: Vec> = hs.par_iter().zip(toks.par_iter()).map(|(h, &t)| { + let mut e = vec![0f32; n]; + mt.embed.row_into(t as usize, &mut e); + let mut x = mt.enorm.apply(&e, eps); + x.extend(mt.hnorm.apply(h, eps)); + x + }).collect(); + let y = matvec_rows(&mt.eh_proj, &cat.iter().map(|c| c.as_slice()).collect::>()); + let p0 = mt.m; + let mut xs: Vec> = y.chunks_exact(n).map(|r| r.to_vec()).collect(); + self.layer(il, &mut xs, p0); + let mt = self.mtp.as_mut().unwrap(); + mt.m += toks.len(); + if !want { return vec![]; } + let cur = mt.head_norm.apply(&xs[xs.len() - 1], eps); + let mut logits = vec![0f32; mt.head.rows]; + mt.head.matvec(&cur, &mut logits); + logits + } + + /// The MTP head's greedy guess at the token after `next` (the token the trunk takes next). Call `verify` (or + /// `step(next)`) after it. + pub fn draft(&mut self, next: u32) -> u32 { + let mt = self.mtp.as_mut().unwrap(); + let hs = std::mem::take(&mut mt.hs); + let mut toks = self.toks[mt.m..].to_vec(); + toks.push(next); + let mut logits = self.mtp_run(&hs, &toks, true); + crate::grammar::greedy(&mut None, &mut logits) + } + + /// `next` and the draft `d` through the trunk at once. Returns whether `d` is the greedy token after `next`, and + /// the logits after the last token kept: `d` when it is, else `next` (`d` is taken back out of the caches). + pub fn verify(&mut self, next: u32, d: u32) -> (bool, Vec) { + let (p, eps) = (self.toks.len(), self.cfg.eps); + let xs = self.trunk(&[next, d]); + let nl = self.cfg.n_layer; + // A DeltaNet state steps back only on the card (`gdn_prompt` keeps the state after `next`). + if (0..nl).any(|il| self.cfg.recurrent[il] && !self.state[il].on_card) { return (false, self.rebuild(p + 1)); } + let hn: Vec> = xs.par_iter().map(|x| self.out_norm.apply(x, eps)).collect(); + let mut l0 = self.head(&hn[0]); + self.drafts.0 += 1; + if crate::grammar::greedy(&mut None, &mut l0) == d { + self.drafts.1 += 1; + let l1 = self.head(&hn[1]); + self.mtp.as_mut().unwrap().hs.extend(hn); + return (true, l1); + } + self.toks.truncate(p + 1); + let (row, hd) = (self.cfg.kv_lora + self.cfg.n_rot, self.cfg.idx_head_dim); + let mut ok = true; + for il in 0..nl { + let st = &mut self.state[il]; + if self.cfg.recurrent[il] { + ok &= crate::deepseek::mat::gdn_rollback(&*st as *const State as usize + 2, st.s.len() + st.conv.len()); + } else { + // The card copies follow the host rows (`rows_on_card` uploads from the first new one). + st.kv.truncate((p + 1) * row); + st.ik.truncate((p + 1) * hd); + } + } + if !ok { return (false, self.rebuild(p + 1)); } + self.mtp.as_mut().unwrap().hs.push(hn.into_iter().next().unwrap()); + (false, l0) + } + + /// The caches again from the first `p` tokens, with MTP off from now on (a draft could not be taken back). + /// Returns the logits after the last. + fn rebuild(&mut self, p: usize) -> Vec { + crate::say!("warning: gigachat4: an MTP draft could not be rolled back; decoding without MTP"); + let toks = self.toks[..p].to_vec(); + self.mtp = None; + self.reset(); + self.prefill(&toks) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gated_norm_and_l2() { + // rank 1: up = [1, 0], down = [[0], [1]]; x = [3, 4] → rms = sqrt(12.5) + let g = GNorm { w: vec![1.0, 1.0], up: vec![1.0, 0.0], down: vec![0.0, 1.0] }; + let y = g.apply(&[3.0, 4.0], 0.0); + let r = 12.5f32.sqrt(); + let (c0, c1) = (3.0 / r, 4.0 / r); + let h = silu(c0); + assert!((y[0] - c0 * 2.0 * 0.5).abs() < 1e-6 && (y[1] - c1 * 2.0 * sigmoid(h)).abs() < 1e-6, "{y:?}"); + let mut v = [3.0, 4.0]; + l2_norm(&mut v, 0.0); + assert!((v[0] - 0.6).abs() < 1e-6 && (v[1] - 0.8).abs() < 1e-6); + } + + #[test] + fn neox_rope_rotates_the_first_dims() { + let rope = Rope::new(10000.0, 1.0, 0.0, 4, 4096, 32.0, 1.0); + let mut x = [1.0, 2.0, 0.0, 0.0, 7.0, 8.0]; + rope_neox(&rope, &mut x, 1); + assert!((x[0] - 1f32.cos()).abs() < 1e-6 && (x[2] - 1f32.sin()).abs() < 1e-6); + assert!((x[1] - 2.0 * 0.01f32.cos()).abs() < 1e-6 && (x[3] - 2.0 * 0.01f32.sin()).abs() < 1e-6); + assert_eq!(x[4..], [7.0, 8.0]); + } + + #[test] + fn top_n_ties_to_the_lower_index() { + assert_eq!(top_n(vec![(1.0, 0), (2.0, 1), (2.0, 2), (0.5, 3)], 2), [1, 2]); + assert_eq!(top_n(vec![(1.0, 0), (1.0, 1), (1.0, 2)], 2), [0, 1]); + } + + #[test] + fn routing_normalises_then_scales() { + let r = route_sigmoid(&[0.0, 0.0, 10.0], &[1.0, 0.0, 0.0], 2, true, 2.5); + assert_eq!(r.iter().map(|x| x.0).collect::>(), [0, 2]); + assert!((r[0].1 + r[1].1 - 2.5).abs() < 1e-6); + assert!((act(20.0, 20.0, 10.0) - swiglu_clamp(10.0, 10.0, 10.0)).abs() < 1e-6); + } +} diff --git a/src/gigachat4/mod.rs b/src/gigachat4/mod.rs new file mode 100644 index 00000000..d372f0cb --- /dev/null +++ b/src/gigachat4/mod.rs @@ -0,0 +1,120 @@ +//! SberDevices GigaChat 4 (`gigachat4`): three Gated DeltaNet layers, then one MLA layer (absorbed, one latent K/V +//! head) with a lightning indexer that picks the keys of a long context; every norm is a gated RMS norm; a dense FFN +//! in the leading layer, then a sigmoid-routed MoE with a shared expert and clamped SwiGLU; soft-capped logits. +//! CPU forward that mirrors llama.cpp `src/models/gigachat4.cpp`; matvecs and routed experts reuse `deepseek::mat`. +//! The MTP block (the last layer of the file) drafts a token a step when `MTP` is on (`--mtp`). +pub mod chat; +pub mod forward; + +use crate::gguf::Gguf; +use anyhow::{Context, ensure}; + +pub const ARCH: &str = "gigachat4"; + +/// Greedy decode with the file's MTP block as a one-token draft (`--mtp 1` or more; set before the model loads). +pub static MTP: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +#[derive(Debug, Clone)] +pub struct GigaChat4Config { + /// Trunk layers (the file's block count less the MTP layers). + pub n_layer: usize, + pub n_ctx: usize, + pub n_embd: usize, + pub n_vocab: usize, + pub eps: f32, + /// Gated DeltaNet layers (the others are MLA). + pub recurrent: Vec, + // MLA + pub n_head: usize, + pub q_lora: usize, + pub kv_lora: usize, + /// Per-head query/key size before absorption (nope + rope) and the value size per head. + pub k_mla: usize, + pub v_mla: usize, + pub n_rot: usize, + pub rope_base: f32, + pub rope_scale: f32, + pub rope_ctx_orig: u32, + pub beta_fast: f32, + pub beta_slow: f32, + pub yarn_log_mul: f32, + // indexer + pub idx_n_head: usize, + pub idx_head_dim: usize, + pub idx_top_k: usize, + // Gated DeltaNet + pub ssm_conv: usize, + pub ssm_d_state: usize, + pub ssm_n_group: usize, + pub ssm_dt_rank: usize, + pub ssm_d_inner: usize, + // FFN + pub n_expert: usize, + pub n_used: usize, + pub n_dense: usize, + pub expert_scale: f32, + pub expert_norm: bool, + pub clamp_exp: Vec, + pub clamp_shexp: Vec, + pub softcap: f32, +} + +impl GigaChat4Config { + pub fn from_gguf(g: &Gguf) -> anyhow::Result { + let k = |s: &str| format!("{ARCH}.{s}"); + let u = |s: &str| -> anyhow::Result { Ok(g.get(&k(s))?.as_u64().with_context(|| k(s))? as usize) }; + let f = |s: &str| -> anyhow::Result { g.get(&k(s))?.as_f32().with_context(|| k(s)) }; + let arr = |s: &str| -> anyhow::Result> { + g.get(&k(s))?.as_arr().with_context(|| k(s))?.iter().map(|v| v.as_f32().or(v.as_u64().map(|x| x as f32)).with_context(|| k(s))).collect() + }; + let n_layer = u("block_count")? - g.get(&k("nextn_predict_layers")).ok().and_then(|v| v.as_u64()).unwrap_or(0) as usize; + let recurrent: Vec = arr("attention.recurrent_layers")?.into_iter().map(|v| v != 0.0).collect(); + ensure!(recurrent.len() >= n_layer, "attention.recurrent_layers does not cover {n_layer} layers"); + ensure!(u("expert_gating_func")? == 2 && u("expert_shared_count")? == 1 && u("attention.head_count_kv")? == 1, "unsupported GigaChat 4 variant"); + let (k_mla, v_mla, kv_lora, n_rot) = (u("attention.key_length_mla")?, u("attention.value_length_mla")?, u("attention.kv_lora_rank")?, u("rope.dimension_count")?); + ensure!(u("attention.key_length")? == kv_lora + n_rot && u("attention.value_length")? == kv_lora && n_rot < k_mla, "unsupported GigaChat 4 attention shape"); + let yarn = g.get(&k("rope.scaling.type")).ok().and_then(|v| v.as_str()) == Some("yarn"); + Ok(GigaChat4Config { + n_ctx: crate::ctx_limit(u("context_length")?), + n_layer, + n_embd: u("embedding_length")?, + n_vocab: g.tensors.get("token_embd.weight").context("missing token_embd.weight")?.dims[1] as usize, + eps: f("attention.layer_norm_rms_epsilon")?, + recurrent, + n_head: u("attention.head_count")?, + q_lora: u("attention.q_lora_rank")?, + kv_lora, + k_mla, + v_mla, + n_rot, + rope_base: f("rope.freq_base")?, + rope_scale: if yarn { f("rope.scaling.factor")? } else { 1.0 }, + rope_ctx_orig: if yarn { u("rope.scaling.original_context_length")? as u32 } else { u("context_length")? as u32 }, + beta_fast: f("rope.scaling.yarn_beta_fast").unwrap_or(32.0), + beta_slow: f("rope.scaling.yarn_beta_slow").unwrap_or(1.0), + // llama.cpp reads the GGUF value as 0.1 times the multiplier + yarn_log_mul: f("rope.scaling.yarn_log_multiplier").map_or(0.0, |v| v / 0.1), + idx_n_head: u("attention.indexer.head_count")?, + idx_head_dim: u("attention.indexer.key_length")?, + idx_top_k: u("attention.indexer.top_k")?, + ssm_conv: u("ssm.conv_kernel")?, + ssm_d_state: u("ssm.state_size")?, + ssm_n_group: u("ssm.group_count")?, + ssm_dt_rank: u("ssm.time_step_rank")?, + ssm_d_inner: u("ssm.inner_size")?, + n_expert: u("expert_count")?, + n_used: u("expert_used_count")?, + n_dense: u("leading_dense_block_count")?, + expert_scale: f("expert_weights_scale")?, + expert_norm: u("expert_weights_norm")? != 0, + clamp_exp: arr("swiglu_clamp_exp")?, + clamp_shexp: arr("swiglu_clamp_shexp")?, + softcap: f("final_logit_softcapping").unwrap_or(0.0), + }) + } + + /// YaRN magnitude scale of the attention scores (llama.cpp `yarn_kq_scale` with attn_factor 1). + pub fn mscale(&self) -> f32 { + if self.rope_scale > 1.0 { 1.0 + 0.1 * self.yarn_log_mul * (self.rope_scale).ln() } else { 1.0 } + } +} diff --git a/src/glm/forward.rs b/src/glm/forward.rs index 702144ae..65e7ad4b 100644 --- a/src/glm/forward.rs +++ b/src/glm/forward.rs @@ -660,6 +660,7 @@ impl<'a> GlmModel<'a> { if chunk > 1 { for c in head.chunks(chunk) { self.prefill_chunk(c); + crate::term::prefilled(c.len()); } } else { for &t in head { diff --git a/src/glm/mod.rs b/src/glm/mod.rs index 48dfc42a..9ef1a2c0 100644 --- a/src/glm/mod.rs +++ b/src/glm/mod.rs @@ -253,6 +253,7 @@ pub fn generate(g: &Gguf, prompt: &str, n: usize) -> anyhow::Result<()> { if let Some(&f) = forced.get(i) { next = f; } if eos.contains(&next) { break; } out.push(next); + crate::term::decoded(1); let s = tok.decode(&out)?; if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { print!("{}", &s[shown..]); @@ -339,12 +340,13 @@ fn parse_calls(text: &str, tools: &[Json]) -> Option<(String, Vec<(String, Strin } /// Greedy decode up to `n` tokens from `logits`; `emit` gets each new text piece. Returns (ids, finish reason). -fn decode_greedy(m: &mut forward::GlmModel, tok: &crate::tokenizer::Tokenizer, eos: &[u32], mut logits: Vec, n: usize, emit: &mut dyn FnMut(&str) -> bool) -> (Vec, &'static str) { +fn decode_greedy(m: &mut forward::GlmModel, tok: &crate::tokenizer::Tokenizer, eos: &[u32], lim: &mut Option, mut logits: Vec, n: usize, emit: &mut dyn FnMut(&str) -> bool) -> (Vec, &'static str) { let (mut out, mut shown, mut done) = (vec![], 0, "length"); for i in 0..n { - let next = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; + let next = crate::grammar::greedy(lim, &mut logits); if eos.contains(&next) { done = "stop"; break; } out.push(next); + crate::term::decoded(1); let s = tok.decode(&out).unwrap_or_default(); if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { let ok = emit(&s[shown..]); @@ -400,7 +402,7 @@ pub fn chat(g: &Gguf, system: Option, n: usize) -> anyhow::Result<()> { let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; let logits = m.prefill(&ids[keep..]); let room = n.min(ctx_limit(&m) - ids.len()); - let (out, _) = decode_greedy(&mut m, &tok, &stop, logits, room, &mut |t| { print!("{t}"); let _ = std::io::stdout().flush(); true }); + let (out, _) = decode_greedy(&mut m, &tok, &stop, &mut None, logits, room, &mut |t| { print!("{t}"); let _ = std::io::stdout().flush(); true }); println!(); msgs.push(("assistant".into(), tok.decode(&out)?)); } @@ -408,34 +410,38 @@ pub fn chat(g: &Gguf, system: Option, n: usize) -> anyhow::Result<()> { } /// The chat of `rustingstrata serve` for GLM (see `serve::Own`): one request at a time, JSON or SSE. -/// ponytail: greedy only, no stop strings; prompt + reply limited to the model's context (STRATA_GLM_CTX overrides); KV reused when the prompt extends it. +/// ponytail: greedy only; prompt + reply limited to the model's context (STRATA_GLM_CTX overrides); KV reused when the prompt extends it. pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a str) -> anyhow::Result> { use anyhow::Context; use serde_json::json; use std::io::Write; gpu_defaults(); let mut m = forward::GlmModel::new(g)?; + crate::serve::warm_up(tok, |ids| { m.prefill(ids); m.reset(); })?; let stop = stop_ids(g, tok); let ctx = ctx_limit(&m); Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| { + let mut lim = crate::grammar::Constraint::new(q, tok)?; + if let Some(l) = &mut lim { l.eos.extend(&stop); } let ids = tok.encode(&chat_prompt_tools(&q.messages, &q.tools)).ok().filter(|i| !i.is_empty()).context("cannot encode prompt")?; - anyhow::ensure!(ids.len() < ctx, "prompt is {} tokens, the limit is {}", ids.len(), ctx - 1); + anyhow::ensure!(ids.len() < ctx, "{}", crate::serve::too_long(ids.len(), ctx - 1)); let t = std::time::Instant::now(); let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; - let logits = m.prefill(&ids[keep..]); + if q.stream && !q.head_sent { let _ = write!(c, "{}", crate::serve::sse_head(c)); } + let logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); let prefill_s = t.elapsed().as_secs_f64(); - let n = q.max_tokens.unwrap_or(256).min(ctx - ids.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let n = q.max_tokens.unwrap_or(usize::MAX).min(ctx - ids.len()); let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let stream = q.stream; let tools = q.tool_calls && !q.tools.is_empty(); - let mut hold = crate::chat::Hold::new(tools, vec![]); - let (out, done) = decode_greedy(&mut m, &tok, &stop, logits, n, &mut |t| { + let mut hold = crate::chat::Hold::new(tools, q.stop.clone()); + let mut alive = std::time::Instant::now(); + let (out, done) = decode_greedy(&mut m, &tok, &stop, &mut lim, logits, n, &mut |t| { let t = hold.push(t); - !stream || t.is_empty() || write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() + (!stream || if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() }) && !hold.stopped }); let calls = if tools { parse_calls(&hold.text, &q.tools) } else { None }; - let done = if calls.is_some() { "tool_calls" } else { done }; + let done = if calls.is_some() { "tool_calls" } else if hold.stopped { "stop" } else { done }; let calls_json = |(content, calls): &(String, Vec<(String, String)>), stream: bool| { let c: Vec<_> = calls.iter().enumerate().map(|(k, (f, a))| { let mut c = json!({"id": format!("call_{k}"), "type": "function", "function": {"name": f, "arguments": a}}); @@ -444,6 +450,10 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a st }).collect(); if stream { json!({"tool_calls": c}) } else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } }; + let d = crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done, drafts: None }; + let timings = d.timings(t); + let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), + "prompt_tokens_details": {"cached_tokens": keep}}); if stream { match &calls { Some(x) => { let _ = write!(c, "data: {}\n\n", chunk(calls_json(x, true), None)); } @@ -452,17 +462,16 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a crate::tokenizer::Tokenizer, name: &'a st } // llama-swap and OpenAI clients read the final chunk's usage. let mut last = chunk(json!({}), Some(done)); - last["usage"] = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), - "prompt_tokens_details": {"cached_tokens": keep}}); + last["usage"] = usage; + last["timings"] = timings; let _ = write!(c, "data: {last}\n\ndata: [DONE]\n\n"); } else { let message = match &calls { Some(x) => calls_json(x, false), None => json!({"role": "assistant", "content": hold.text}) }; let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": message, "finish_reason": done}], - "usage": {"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), - "prompt_tokens_details": {"cached_tokens": keep}}}); + "usage": usage, "timings": timings}); crate::serve::send(c, "200 OK", "application/json", &b.to_string()); } - Ok(crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done }) + Ok(d) })) } diff --git a/src/gpu_model.rs b/src/gpu_model.rs index 846b48ae..48035cf9 100644 --- a/src/gpu_model.rs +++ b/src/gpu_model.rs @@ -7,6 +7,10 @@ use crate::cpu_worker::{CpuWorker, TMAX}; /// Slots that `step_rows` decodes in one forward (its graphs are keyed by up to this many slots); `TMAX` is the /// wider limit of a multi-token verify. pub const STEP_ROWS: usize = 4; +/// Positions a slot's attention KV starts with when it grows on demand (`GpuModel::kv_need`). +const KV_START: usize = 512; +/// The start when the slots do not all fit at `KV_START`. +const KV_MIN: usize = 256; use crate::backend::{ATT_GQA_MIN, ATT_SPLITS, Backend, Buf, GpuTensor}; use crate::expert_cache::ExpertCache; use crate::model::Model; @@ -74,13 +78,13 @@ enum Mixer { } /// QSA indexer of an attention layer (qwen4exp, see `Model::qsa`): projections and norms, the pooled keys (128 floats -/// per block of 4 positions) and this layer's 32 rows of `QsaBufs::ring`. -struct Qsa { kp: GpuTensor, qp: GpuTensor, kn: GpuTensor, qn: GpuTensor, pool: Buf, ring: u64 } +/// per block of 4 positions, one buffer per slot) and the byte offset of this layer's 32 rows in `QsaBufs::ring`. +struct Qsa { kp: GpuTensor, qp: GpuTensor, kn: GpuTensor, qn: GpuTensor, pool: Vec, ring: u64 } /// QSA scratch shared by the layers: raw indexer keys of each layer's last 32 positions (`QSA_RING` floats a layer) /// and their copy at `save_state`, block scores (rows of `nbs`), decode cell lists (rows of `sst`), prefill masks /// (rows of `mw` words). -struct QsaBufs { ring: Buf, saved: Buf, score: Buf, sel: Buf, mask: Buf, top: usize, nbs: usize, sst: usize, mw: usize } +struct QsaBufs { ring: Vec, saved: Vec, score: Buf, sel: Buf, mask: Buf, top: usize, nbs: usize, sst: usize, mw: usize } /// Positions a QSA pool block covers, the indexer head size and heads (the kernels' QSA_D and QSA_H). const QSA_POOL: usize = 4; @@ -97,6 +101,49 @@ enum Ffn { Moe { router: GpuTensor, shared: Option }, } +/// The GPU's share of the experts that missed the cache: in a layer where a token misses at least `hmin` +/// experts, `moe_route` gives the last of them to the GPU, which runs it with `moe_gemv` over the expert's weights in +/// pinned host memory (read over PCIe, beside the CPU worker's experts) instead of leaving it to the CPU. Needs the +/// model file in anonymous memory (`--arena`, gguf.rs), which the backend pins (`host_register`). +/// `--host-share N` sets `hmin` (default 0: off; with the pinned CPU pool it measured slower). +/// Most tokens a fused `hc_write_norm` takes (its ticket buffer); more run the two kernels. +const HC_CNT: usize = 64; + +struct HostShare { hid: Buf, hmin: i32, layers: Vec> } + +/// Thread blocks of a host-share GEMV (per matrix): enough loads in flight to fill the PCIe link, few SMs held. +const HOST_BLOCKS: usize = 8; + +/// One layer's expert tensors in host memory: gate and up (`up_off` bytes after gate, the same stride), down. +#[derive(Clone, Copy)] +struct HostLayer { gate: u64, up_off: i64, down: u64, stride_gu: usize, stride_d: usize } + +impl HostShare { + fn new(m: &Model, gpu: &dyn Backend, moe_layers: &[usize]) -> anyhow::Result> { + let c = &m.cfg; + let hmin = m.w.g.moe.host_share; + let spans = m.w.g.anon_spans(); + // The arena is pinned with or without the share: prompt staging then copies from it with one DMA. + let mut pinned = Vec::new(); + if gpu.host_share() { for &(p, n) in &spans { if gpu.host_register(p, n)? { pinned.push((p, n)); } } } + if hmin < 2 || pinned.is_empty() || c.hadamard.is_some() || !m.loras.is_empty() { return Ok(None); } + let inside = |d: &[u8]| pinned.iter().any(|&(p, n)| d.as_ptr() as usize >= p && d.as_ptr() as usize + d.len() <= p + n); + let mut layers = vec![None; c.n_layer + 1]; + for &il in moe_layers { + let (Ok(g), Ok(u), Ok(d)) = (m.w.layer(il, "ffn_gate_exps.weight"), m.w.layer(il, "ffn_up_exps.weight"), m.w.layer(il, "ffn_down_exps.weight")) else { continue }; + if g.ty != u.ty || g.data.len() != u.data.len() || !(inside(g.data) && inside(u.data) && inside(d.data)) { continue; } + layers[il] = Some(HostLayer { + gate: g.data.as_ptr() as u64, up_off: u.data.as_ptr() as i64 - g.data.as_ptr() as i64, down: d.data.as_ptr() as u64, + stride_gu: g.data.len() / c.n_expert, stride_d: d.data.len() / c.n_expert, + }); + } + let n = layers.iter().flatten().count(); + if n == 0 { return Ok(None); } + crate::say!("host share: {n} MoE layers read a missed expert over PCIe when a token misses at least {hmin} (--host-share)"); + Ok(Some(HostShare { hid: gpu.zeros::(crate::cpu_worker::TMAX * c.n_expert_used)?, hmin, layers })) + } +} + /// qwen4exp hyper-connection read weights (`{p}norm/down/up/inject.weight`, see `Model::hc_read`). struct HcRead { norm: GpuTensor, down: GpuTensor, up: GpuTensor, inject: Option } @@ -107,7 +154,8 @@ struct Ple { key: GpuTensor, value: GpuTensor, norm_key: GpuTensor, norm_query: /// Buffers of `step_batch`: positions (2 ints a row), the KV cache addresses of each row's slot (2 a row, per /// layer) for `rows` rows; logits and argmax for `cap` rows; attention partials for `cap` rows at `ATT_SPLITS` /// splits (more rows fit at fewer splits). -struct Batch { cap: usize, rows: usize, step: Buf, kvt: Buf, logits: Buf, amax: Buf, attp: Buf } +/// `dense`: every layer attention and a dense FFN (the forward of `batch_rows`); else `prefill_chunk` in rows mode. +struct Batch { dense: bool, cap: usize, rows: usize, step: Buf, kvt: Buf, logits: Buf, amax: Buf, attp: Buf } /// SenseNova-Loop manifold-constrained hyper-connection (mHC) router (`mhc_attn` or `mhc_ffn`). #[derive(Clone)] @@ -117,16 +165,23 @@ struct Layer { attn_norm: Option, post_norm: Option, hc: O /// MTP draft head: the `nextn` block (layer n_layer) with its own KV cache and CPU worker. /// Buffers for a copy of the DeltaNet (conv, s) states of `layers` (all or none). -fn alloc_saved(g: &dyn Backend, layers: &[Layer]) -> anyhow::Result> { +/// `host`: in host memory where the backend has it (`Backend::host_buf`), as for the saved state of each of several +/// slots, which is copied only at a prompt's start and end; the VRAM goes to the slots' live state and the experts. +fn alloc_saved(g: &dyn Backend, layers: &[Layer], host: bool) -> anyhow::Result> { + let a = |n: usize| -> anyhow::Result { match if host { g.host_buf(n)? } else { None } { Some(b) => Ok(b), None => g.alloc(n) } }; layers.iter().filter_map(|l| match &l.mixer { Mixer::Delta { conv, s, .. } => Some((conv[0].len(), s[0].len())), _ => None }) - .map(|(c, s)| Ok((g.alloc(c)?, g.alloc(s)?))).collect() + .map(|(c, s)| Ok((a(c)?, a(s)?))).collect() } /// A saved conversation state in host memory: its tokens, the PLE tokens before it, the `slot` buffers and the KV /// rows of its positions in each attention layer. -struct Parked { ids: Vec, owner: u64, parts: Vec } +/// `sys`: the state right after a system prompt (`stash`). It is kept when a conversation that starts with it is parked, +/// and copied, not taken, when a prompt starts from it, so several system prompts stay reusable across conversations. +#[derive(Clone)] +struct Parked { ids: Vec, owner: u64, parts: Vec, sys: bool } /// One part's share of a parked state: its history ring position, saved slot buffers and KV rows. +#[derive(Clone)] struct PartCopy { ple_prev: [i64; 2], slot: Vec>, kv: Vec> } impl Parked { @@ -280,6 +335,10 @@ struct DFlashGpu { layers: Vec, /// `[TMAX, n_target_layers * n_embd]` concatenated post-layer target hidden states. feat: Buf, + /// hc stream gate for the mean collapse (all large => plain mean), `[hc_n * n_embd]`. + dfg: Buf, + /// hc-mean collapse output, `[TMAX, n_embd]`. + dfm: Buf, /// `[TMAX, n_embd]` projected & normalized `target_hidden = hidden_norm(fc(feat))` from the last forward. th: Buf, x: Buf, @@ -429,7 +488,8 @@ struct MtpHead { /// What a slot keeps while another slot is current (`use_slot`): the `GpuModel` fields of the same names. #[derive(Default)] -struct Seq { pos: usize, saved: Vec<(Buf, Buf)>, saved_pos: usize, saved_ids: Vec, saved_owner: u64, sys: Option, sys_owner: u64 } +struct Seq { pos: usize, rope: i32, saved: Vec<(Buf, Buf)>, saved_pos: usize, saved_ids: Vec, saved_owner: u64, sys: Option, sys_owner: u64, + ple_prev: [i64; 2], saved_ple_prev: [i64; 2], ple_undo: ([i64; 2], Vec) } /// See `GpuModel::sys`. type Stash = (Vec>, usize, [i64; 2], Vec); @@ -442,6 +502,8 @@ pub const SNAP_STRIDE: usize = 4; pub struct GpuModel<'a> { m: &'a Model<'a>, + /// `STRATA_KV_HOST` prefill: VRAM copies of one host layer's K and V cache (see `load_part`). + kv_stage: Option<(Buf, Buf)>, pub gpu: Box, layers: Vec, output_norm: Option, @@ -450,8 +512,8 @@ pub struct GpuModel<'a> { /// None on all but the last part of a split model. output: Option, /// qwen4exp PLE: the normalized rows of the last 16 positions (see `ple_conv`), its copy at `save_state`, the two - /// previous tokens for the n-gram hash and their copy. - ple_ring: Option<(Buf, Buf)>, + /// previous tokens for the n-gram hash and their copy. The rings are per slot (`cur` indexes them). + ple_ring: Option>, qsa: Option, ple_prev: [i64; 2], saved_ple_prev: [i64; 2], @@ -475,6 +537,10 @@ pub struct GpuModel<'a> { /// Set during an image token's `step_embed`: its M-RoPE positions [t, y, x, z] are in `mrope_buf`. mrope: bool, mrope_buf: Buf, + /// Set while `prefill_chunk` runs image rows: segments (first row, rows, whether section s moves by one a row, + /// else stays) and each segment's first M-RoPE positions as four [position, 0] pairs, put in `pf_mrope_buf`. + pf_mrope: Option<(Vec<(usize, usize, [bool; 4])>, Vec)>, + pf_mrope_buf: Option, /// DeltaNet (conv, s) copies per recurrent layer and the position, for `restore_state`. saved: Vec<(Buf, Buf)>, saved_pos: usize, @@ -503,9 +569,9 @@ pub struct GpuModel<'a> { pub adapt_every: usize, /// Experts one `adapt` may swap per pool (default 64; `STRATA_ADAPT_SWAPS`). pub adapt_swaps: usize, - /// Serve policy: after a prefill, forget the prompt's short-term routing counts so decode adapts to the reply - /// instead of the prompt (`STRATA_RESET_COUNTS`; `serve` turns it on). - pub reset_counts_after_prefill: bool, + /// Serve policy: a prefill may move only a few experts and leaves decode's routing counts as they were, so each + /// turn starts with the last reply's hot set (`ExpertCache::settle`; `STRATA_RESET_COUNTS`; `serve` turns it on). + pub keep_decode_set: bool, pub hits: usize, pub misses: usize, /// Forwards this part ran (decode tokens): the base of the per-token stats `Runner::finish` prints. @@ -515,6 +581,14 @@ pub struct GpuModel<'a> { pub mailbox_reads: std::cell::Cell, /// Last token's routing ids of each layer, the next token's prefetch prediction (`STRATA_MOE_PREFETCH=1`). pids: Option, + /// The GPU's share of the missed experts, read from pinned host memory (see `HostShare`). + host_exp: Option, + /// `forward` lets a layer leave its last hyper-connection stream write (of "mo") to the next layer's first + /// hc_read, which runs it fused with its norm (`hc_write_norm`): `hc_pend` holds that buffer's address, 0 none. + hc_defer: std::cell::Cell, + hc_pend: std::cell::Cell, + /// `hc_write_norm`'s per-token tickets (HC_CNT zeroed u32). + hc_cnt: Option, /// Time the CPU worker spent computing missed experts (overlaps GPU work). pub cpu_time: Duration, /// Forwards run again from a MoE combine that gave up waiting for the CPU worker (`finish`). @@ -553,13 +627,24 @@ pub struct GpuModel<'a> { /// The part on the next device of a model split by layers (`load_split`): this part's hidden state goes to it /// through host memory, and the last part computes the logits. Public calls go to the first part. next: Option>>, + /// The VRAM this part's load left free (`--vram-margin`): what `vram_reserve(None)` keeps free again. + vram_margin: usize, /// The current slot (`load_slots`), whose state the other methods use, and the others' (entry `cur` is stale). cur: usize, seqs: Vec, + /// Positions each slot's attention KV holds, when the slots' KV grows on demand (`kv_need`); empty when every + /// KV cache holds `ctx`. + kv_cap: Vec, + /// Positions a growing slot starts with and shrinks back to (`KV_START` or `KV_MIN`). + kv0: usize, /// The (slot, position) of each token of the `step_rows` forward being run (empty otherwise). rows: Vec<(usize, usize)>, /// Tokens `step_rows` ran, for the placement cadence. row_tokens: usize, + /// Share of a batch step's or prompt chunk's missed experts that the CPU runs (`prefill_chunk`). + cpu_frac: f64, + /// Eligible MoE layers since the last CPU timing sample. + cpu_unsampled: usize, } /// Layer shares of `--split`: one positive number per device, such as `60,40`. @@ -578,6 +663,41 @@ fn split_ends(share: &[f64], n: usize) -> Vec { ends } +fn add_weight(total: &mut usize, t: anyhow::Result>) { + if let Ok(t) = t { *total += t.data.len(); } +} + +/// The weights `load_part` uploads for `range`, and the output head in the last part: every non-expert tensor of +/// those layers' blocks, read off the file so that the list cannot drift from the load. A split part used to count +/// the whole model's weights, so a card with room for two slots saw no room for a second one: two requests then ran +/// one after the other instead of together. Routed experts (`_exps.`) live in the expert cache, not the weights; a +/// looped model's virtual layers share their block's weights, which `lt` uploads once per part; and the draft head +/// (`blk.{n_layer}`) is left out: `--parallel` turns MTP off (`resolve_flags`). +fn part_weight_bytes(m: &Model<'_>, range: std::ops::Range, last: bool) -> usize { + let c = &m.cfg; + let mut layers: Vec = range.map(|il| c.phys_layer.get(il).copied().unwrap_or(il)).collect(); + layers.sort_unstable(); + layers.dedup(); + let in_part = |name: &str| { + !name.contains("_exps.") + && name.strip_prefix("blk.").and_then(|r| r.split_once('.')) + .and_then(|(il, _)| il.parse::().ok()) + .is_some_and(|il| layers.binary_search(&il).is_ok()) + }; + // `get` rather than the file's bytes: a repacked or LoRA-baked tensor is uploaded in its new size. + let mut total: usize = m.w.g.tensors.values().filter(|t| in_part(&t.name)) + .filter_map(|t| m.w.get(&t.name).ok()).map(|t| t.data.len()).sum(); + if last { + if c.hc_n > 0 { + for s in ["norm", "down", "up", "inject"] { add_weight(&mut total, m.w.get(&format!("output_hc_{s}.weight"))); } + } else { + add_weight(&mut total, m.w.get("output_norm.weight")); + } + add_weight(&mut total, m.w.get("output.weight").or_else(|_| m.w.get("token_embd.weight"))); + } + total +} + /// Host-to-VRAM copy rate of `gpu` in MB/s over the path an expert upload takes (pageable host memory, so a fast /// link reads as the host's copy rate). The second of two 64 MB copies is timed: the first pays the set-up. fn copy_rate(gpu: &dyn Backend) -> anyhow::Result { @@ -643,6 +763,9 @@ impl<'a> GpuModel<'a> { crate::say!("device {i} ({}): layers {}..{}, host-to-VRAM copy {:.0} MB/s", gpu.name(), r.start, r.end, rates[i]); parts.push(Self::load_part(m, gpu, ctx, chunk, vram_margin[i], k, r, ns)?); } + // Every part holds the state of every slot (a part short of VRAM takes fewer). + let fit: Vec = parts.iter().map(|p| p.slots()).collect(); + ensure!(fit.iter().all(|&s| s == fit[0]), "--parallel {ns}: the devices fit {fit:?} slots; lower --parallel or --ctx"); // One draft length for every part: each caps it by its own backend's verify rows. let k = parts.iter().map(|p| p.k).min().unwrap(); let nsnap = parts.iter().map(|p| p.nsnap).min().unwrap(); @@ -654,8 +777,6 @@ impl<'a> GpuModel<'a> { } fn load_part(m: &'a Model<'a>, gpu: Box, ctx: usize, chunk: usize, vram_margin: usize, k: usize, range: std::ops::Range, ns: usize) -> anyhow::Result> { - let c = &m.cfg; - ensure!(ns == 1 || c.hc_n == 0 && c.n_embd_ple == 0 && c.idx_top_k == 0, "--parallel: not supported for this model (hyper-connections, PLE or QSA)"); ensure!((1..=255).contains(&ns), "--parallel {ns}: 1 to 255 slots"); let last = range.end == m.cfg.n_layer; if let Some(t) = m.w.g.tensors.values().find(|t| !cpu_only(&t.name) @@ -704,9 +825,29 @@ impl<'a> GpuModel<'a> { let (dk, nk, nv) = (c.ssm_d_state, c.ssm_n_group, c.ssm_dt_rank); let channels = c.ssm_d_inner + 2 * nk * dk; let kv = c.n_head_kv * c.head_dim; + // Several slots of a model without experts: each slot's attention KV starts at KV_START positions and doubles + // when a request needs more (`kv_need`), up to `ctx`, so that short requests do not each hold `ctx` of VRAM. + // ponytail: an MoE keeps `ctx` a slot, as its expert slots take the VRAM the KV would grow into. + // A host-RAM KV layer (STRATA_KV_HOST) keeps its `ctx`: growing allocates in VRAM. + let grow = ns > 1 && !c.is_moe() && ctx > KV_START && !(0..c.n_layer).any(crate::host_attn::on_host); + let mut kv0 = if grow { KV_START } else { ctx }; + // The slots' live state stays in VRAM; more slots than fit would end the load out of memory. A dense model's + // state may take the VRAM its weights leave (less 512 MB of scratch); an MoE's at most half, so that the other + // half holds experts. A request past the slots waits for one (`serve_slots`). + // ponytail: Vulkan keeps each slot's saved state in VRAM too (no `host_buf`), not counted here. + let ns = if ns > 1 { + let lay = &c.layers[range.clone()]; + let per = |kv0: usize| lay.iter().map(|&k| if k == LayerKind::Delta { 4 * ((c.ssm_conv - 1) * channels + nv * c.ssm_dv() * dk) } else { 2 * (gpu.kv_words(kv0 * kv) + gpu.kv_words_v(kv0 * kv)) }).sum::(); + let w = part_weight_bytes(m, range.clone(), last); + let room = free0.saturating_sub(w + vram_margin + (1 << 29)) / if c.is_moe() { 2 } else { 1 }; + // Short of VRAM for every slot (a BF16 4B on 12 GB): start at KV_MIN positions, which holds a short chat. + if grow && room / per(kv0).max(1) < ns { kv0 = KV_MIN; } + let fit = (room / per(kv0).max(1)).clamp(1, ns); + if fit < ns { crate::say!("--parallel {ns}: the state of {fit} slots fits in VRAM; the other requests wait for a free slot"); } + fit + } else { ns }; let qsa_on = c.idx_top_k > 0 && (0..c.n_layer).any(|il| m.w.layer(il, "indexer.k_proj.weight").is_ok()); if qsa_on { ensure!(c.idx_head_dim == QSA_D && c.idx_n_head == QSA_H, "QSA indexer: {} heads of {} (the GPU kernels take {QSA_H} of {QSA_D})", c.idx_n_head, c.idx_head_dim); } - let ring = gpu.zeros::(if qsa_on { c.n_layer * QSA_RING } else { 1 })?; let k = k.min(gpu.verify_rows() - 1); // The draft head goes with the last layers (a split model's last part): it reads their hidden rows. @@ -742,14 +883,14 @@ impl<'a> GpuModel<'a> { q: lt(il, "attn_q.weight")?, k: lt(il, "attn_k.weight")?, v: lt(il, "attn_v.weight")?, qn: lt(il, "attn_q_norm.weight")?, kn: lt(il, "attn_k_norm.weight")?, o: lt(il, "attn_output.weight")?, sink: if c.attn_sinks { Some(lt(il, "attn_sinks.weight")?) } else { None }, - kc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * kv))).collect::>()?, - vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * kv))).collect::>()?, + kc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words(kv0 * kv) * 2)).collect::>()?, + vc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words_v(kv0 * kv) * 2)).collect::>()?, qsa: if qsa_on && il < c.n_layer && m.w.layer(il, "indexer.k_proj.weight").is_ok() { Some(Qsa { kp: lt(il, "indexer.k_proj.weight")?, qp: lt(il, "indexer.q_proj.weight")?, kn: lt(il, "indexer.k_norm.weight")?, qn: lt(il, "indexer.q_norm.weight")?, // Rows of 128 floats per position, as the KV rows (`kv_bufs`): ctx / 4 blocks of 512. - pool: gpu.zeros::(ctx * QSA_D / QSA_POOL)?, ring: ring.addr() + (4 * il * QSA_RING) as u64, + pool: (0..ns).map(|_| gpu.zeros::(ctx * QSA_D / QSA_POOL)).collect::>()?, ring: (4 * il * QSA_RING) as u64, }) } else { None }, } @@ -787,7 +928,9 @@ impl<'a> GpuModel<'a> { }; let layers = range.clone().map(|il| load_layer(il, c.layers[il])).collect::>>()?; let (output_norm, output_hc) = if !last { (None, None) } else if c.hc_n > 0 { (None, Some(hc_read("output_hc_")?)) } else { (Some(up("output_norm.weight")?), None) }; - let ple_ring = if c.n_embd_ple > 0 { Some((gpu.zeros::(16 * hcn * c.n_embd)?, gpu.zeros::(16 * hcn * c.n_embd)?)) } else { None }; + let ple_ring = if c.n_embd_ple > 0 { + Some((0..ns).map(|_| Ok((gpu.zeros::(16 * hcn * c.n_embd)?, gpu.zeros::(16 * hcn * c.n_embd)?))).collect::>>()?) + } else { None }; let output = if last { Some(up("output.weight").or_else(|_| up("token_embd.weight"))?) } else { None }; let dflash = if k > 0 && last && ns == 1 { if let Some(dc) = c.dflash.clone() { @@ -820,7 +963,7 @@ impl<'a> GpuModel<'a> { Some(DFlashConv { base: df_lt("mlp_conv_base")?, proj: df_lt("mlp_conv_proj")? }) } else { None }, kc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * df_kv))).collect::>()?, - vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * df_kv))).collect::>()?, + vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words_v(ctx * df_kv))).collect::>()?, is_swa: dc.layer_swa.get(il).copied().unwrap_or(false), }); } @@ -844,7 +987,7 @@ impl<'a> GpuModel<'a> { let conv_dyn_len = if dc.conv_kernel_size > 0 && dc.conv_group_size > 0 { TMAX * 2 * dc.conv_kernel_size * (dc.n_embd / dc.conv_group_size) } else { 1 }; - crate::say!( + crate::detail!( "DFlash{} block-diffusion drafter loaded: {} layers (SWA={swa_cnt}, full={}), block_size={}, k={k}, w={}, target_layers={:?}", if selector.is_some() { "2" } else { "" }, dc.n_layer, @@ -859,6 +1002,10 @@ impl<'a> GpuModel<'a> { norm: up("dflash.norm.weight")?, layers: dl_layers, feat: gpu.zeros::(TMAX * dc.target_layer_ids.len() * c.n_embd)?, + // hc_mix indexes its gate buffer per position (g[t*hc*n + c*n + i]), so it needs + // TMAX rows; 12.0 => sigmoid ~ 1 => plain stream mean. + dfg: { let n = (TMAX * c.hc_n * c.n_embd).max(1); let b = gpu.zeros::(n)?; gpu.put(&vec![12.0f32; n], &b, 0)?; b }, + dfm: gpu.zeros::(TMAX * c.n_embd)?, th: gpu.zeros::(TMAX * dc.n_embd)?, x: gpu.zeros::(TMAX * dc.n_embd)?, h: gpu.zeros::(TMAX * dc.n_embd)?, @@ -904,8 +1051,8 @@ impl<'a> GpuModel<'a> { qn: lt(il, "nextn.enorm.weight")?, kn: lt(il, "nextn.hnorm.weight")?, o: lt(il, "attn_output.weight")?, - kc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * eg_kv))).collect::>()?, - vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * eg_kv))).collect::>()?, + kc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words(ctx * eg_kv) * 2)).collect::>()?, + vc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words_v(ctx * eg_kv) * 2)).collect::>()?, qsa: None, sink: None, }, @@ -962,7 +1109,8 @@ impl<'a> GpuModel<'a> { hnorm: lt(il, "nextn.hnorm.weight")?, head_norm: if c.hc_n > 0 { None } else { Some(lt(il, "nextn.shared_head_norm.weight")?) }, hc_head: if c.hc_n > 0 { Some(hc_read(&format!("blk.{il}.nextn.hc_head_"))?) } else { None }, - worker: Some(CpuWorker::new(m, &*gpu, vec![c.n_layer])?), + // A dense head never raises the worker's mailbox: a worker there would wait on it forever (#141). + worker: if c.is_moe_layer(c.n_layer) { Some(CpuWorker::new(m, &*gpu, vec![c.n_layer])?) } else { None }, step_buf: gpu.zeros::(2 * TMAX)?, emb: gpu.zeros::(TMAX * c.n_embd)?, eh: gpu.zeros::(TMAX * 2 * hcn * c.n_embd)?, @@ -1022,11 +1170,25 @@ impl<'a> GpuModel<'a> { } sizes.push(("hr", c.n_embd)); let up = |n: usize| -> anyhow::Result { let b = gpu.zeros::(n)?; gpu.put(r.signs(n), &b, 0)?; Ok(b) }; - Some([up(c.n_embd)?, up(c.n_ff_exp)?]) + if r.dense { + // A dense file rotates the inputs of its mixer and FFN matrices; the rotation of the attention and + // ssm_out inputs goes through "hr" with the n_embd signs. + anyhow::ensure!(c.n_head * c.head_dim == c.n_embd && (c.ssm_d_inner == 0 || c.ssm_d_inner == c.n_embd), + "a rotated (prism.hadamard) dense file runs on the GPU only with attention and ssm_out widths of n_embd"); + Some([up(c.n_embd)?, up(c.n_ff)?]) + } else { + Some([up(c.n_embd)?, up(c.n_ff_exp)?]) + } } None => None, }; - let bufs = sizes.into_iter().map(|(name, n)| Ok((name, gpu.zeros::(TMAX * n)?))).collect::>>()?; + let mut bufs = sizes.into_iter().map(|(name, n)| Ok((name, gpu.zeros::(TMAX * n)?))).collect::>>()?; + // The value-head order the ssm_out of a dense rotated file reads (`config::Hadamard::ssm_out_perm`). + if let Some(perm) = c.hadamard.as_ref().filter(|r| r.dense).and_then(|r| r.ssm_out_perm(c.ssm_d_inner, c.ssm_n_group, c.ssm_dt_rank)) { + let b = gpu.zeros::(perm.len())?; + gpu.put(&perm, &b, 0)?; + bufs.insert("hperm", b); + } let (x, logits, ids) = (gpu.zeros::(TMAX * hcn * c.n_embd)?, gpu.zeros::(TMAX * c.n_vocab)?, gpu.zeros::(TMAX * ke)?); let amax = gpu.zeros::(TMAX)?; let (slots, step_buf) = (gpu.zeros::(TMAX * ke)?, gpu.zeros::(2 * TMAX)?); @@ -1040,24 +1202,29 @@ impl<'a> GpuModel<'a> { let (top, nbs) = (c.idx_top_k / QSA_POOL, ctx / QSA_POOL); let (sst, mw) = (1 + c.idx_top_k + QSA_POOL, (nbs + 1).div_ceil(32)); let rows = pf.as_ref().map_or(0, |p| p.chunk.next_multiple_of(64)); - Some(QsaBufs { saved: gpu.zeros::(ring.len() / 4)?, ring, score: gpu.zeros::(QSA_ROWS.max(TMAX) * nbs)?, + let per = |_| gpu.zeros::(c.n_layer * QSA_RING); + Some(QsaBufs { ring: (0..ns).map(per).collect::>()?, saved: (0..ns).map(per).collect::>()?, score: gpu.zeros::(QSA_ROWS.max(TMAX) * nbs)?, sel: gpu.zeros::(TMAX * sst)?, mask: gpu.zeros::((rows * mw).max(1))?, top, nbs, sst, mw }) } else { None }; // Each slot's `save_state` copy, before the expert plan so that it leaves room for them (one slot allocates it // at its first `save_state`). - let mut seqs: Vec = (0..ns).map(|_| Seq::default()).collect(); - if ns > 1 { for q in &mut seqs { q.saved = alloc_saved(&*gpu, &layers)?; } } + let mut seqs: Vec = (0..ns).map(|_| Seq { ple_prev: [-1, -1], saved_ple_prev: [-1, -1], ple_undo: ([-1, -1], vec![]), ..Default::default() }).collect(); + if ns > 1 { for q in &mut seqs { q.saved = alloc_saved(&*gpu, &layers, true)?; } } let saved = std::mem::take(&mut seqs[0].saved); // `step_batch` covers plain dense attention models in one part; the rest decode `STEP_ROWS` rows a forward. - let plain = output_norm.is_some() && output.is_some() && range.start == 0 && !mtp && c.hc_n == 0 && c.n_embd_ple == 0 && !qsa_on - && layers.iter().enumerate().all(|(il, l)| l.attn_norm.is_some() && l.post_norm.is_some() && matches!(l.mixer, Mixer::Attn { .. }) - && matches!(l.ffn, Ffn::Dense { .. }) && c.rope_layer.get(il).copied().unwrap_or(true)); + // A model with DeltaNet layers or experts takes the layers of the prefill (`prefill_chunk` in rows mode), also + // over the parts of a --device split. + let dense = layers.iter().all(|l| matches!(l.mixer, Mixer::Attn { .. }) && matches!(l.ffn, Ffn::Dense { .. })); + let one = range.start == 0 && last; + let plain = (one || !dense) && (!last || output_norm.is_some() && output.is_some()) && !mtp && c.hc_n == 0 && c.n_embd_ple == 0 && !qsa_on + && c.hadamard.is_none() && layers.iter().enumerate().all(|(il, l)| l.attn_norm.is_some() && l.post_norm.is_some() && l.mhc.is_none() && l.ple.is_none() + && c.rope_layer.get(range.start + il).copied().unwrap_or(true)); let bt = match &pf { Some(p) if ns > STEP_ROWS && plain && gpu.kv_rows() => { - // ponytail: 64 rows a forward, the size of the backend's argmax scratch; split the argmax to go past it. - let cap = ns.min(p.chunk).min(64); + // ponytail: 128 rows a forward, the size of the CUDA argmax scratch; split the argmax to go past it. + let cap = ns.min(p.chunk).min(128); let rows = p.chunk; - Some(Batch { cap, rows, step: gpu.zeros::(2 * rows)?, kvt: gpu.zeros::(layers.len() * 2 * rows)?, logits: gpu.zeros::(cap * c.n_vocab)?, + Some(Batch { dense, cap, rows, step: gpu.zeros::(2 * rows)?, kvt: gpu.zeros::(layers.len() * 2 * rows)?, logits: gpu.zeros::(if last { cap * c.n_vocab } else { 1 })?, amax: gpu.zeros::(cap)?, attp: gpu.zeros::(cap * c.n_head * ATT_SPLITS * (c.head_dim + 2))? }) } _ => None, @@ -1068,12 +1235,22 @@ impl<'a> GpuModel<'a> { let mut dg = Self::load_part(dm, d_gpu, ctx, chunk, vram_margin, 0, 0..dm.cfg.n_layer, 1)?; dg.graph_tag = 1u64 << 62; if dg.saved.is_empty() { - dg.saved = alloc_saved(&*dg.gpu, &dg.layers)?; + dg.saved = alloc_saved(&*dg.gpu, &dg.layers, false)?; } Some(Box::new(dg)) } else { None }; + // STRATA_KV_HOST: one layer's cache-sized VRAM buffer pair. Prefill copies a host layer's cache prefix into it + // (a DMA copy, ~10x what the attention kernel reads from mapped memory) and runs the usual kernel on it. + let kv_stage = match layers.iter().enumerate().filter(|(il, _)| crate::host_attn::on_host(*il)) + .filter_map(|(_, l)| match &l.mixer { Mixer::Attn { kc, .. } => kc.first().map(|b| b.len()), _ => None }).max() { + Some(b) if std::env::var_os("STRATA_HA_NO_STAGE").is_none() => match (gpu.alloc(b), gpu.alloc(b)) { + (Ok(k), Ok(v)) => Some((k, v)), + _ => { crate::say!("host KV: no VRAM for the {} MB prefill staging, prefill reads the cache over PCIe", 2 * b >> 20); None } + }, + _ => None, + }; let (free1, _) = gpu.mem_info()?; // Past the budget the driver spills buffers to system memory: RADV then runs a long prefill slowly enough to // hit amdgpu's job timeout and lose the device. A margin above 512 MB only leaves fewer expert slots. @@ -1096,7 +1273,28 @@ impl<'a> GpuModel<'a> { }; Some(ExpertCache::new(m, &*gpu, budget, range.start..range.end + (mtp && c.eagle3.is_none()) as usize)?) } else { None }; + // STRATA_MLOCK_EXPERTS has locked the experts' pages already; registering them with the device (`pin_host`, + // HIP only) lets a prompt's staging copies DMA from the mapped file instead of a host copy through the pinned + // ring, which held the copies under the link's rate. Qwen3.8-Flash-Next UD-IQ4_XS: 57.6 GB in 7 s at load. + // Not when the model exceeds RAM: `weights::cold` drops each staged run's pages there, under the device. + if cache.is_some() && std::env::var_os("STRATA_MLOCK_EXPERTS").is_some_and(|v| v != "0") && crate::weights::fits_ram() { + let t0 = std::time::Instant::now(); + let mut bytes = 0usize; + 'pin: for il in range.clone().filter(|&il| c.is_moe_layer(il)) { + for name in crate::expert_cache::MATS { + let Ok(w) = m.w.layer(il, name) else { continue }; + match gpu.pin_host(w.data) { + Ok(true) => bytes += w.data.len(), + Ok(false) => break 'pin, + Err(e) => { crate::say!("warning: registering the expert pages failed at layer {il} ({e:#}); the rest stage through the ring"); break 'pin; } + } + } + } + if bytes > 0 { crate::say!("expert pages: registered {} MB with the device in {:.1} s (staging copies DMA from them)", bytes >> 20, t0.elapsed().as_secs_f64()); } + } let moe_layers: Vec = range.clone().filter(|&il| c.is_moe_layer(il)).collect(); + let hc_cnt = if c.hc_n > 0 { Some(gpu.zeros::(HC_CNT)?) } else { None }; + let host_exp = if cache.is_some() && !moe_layers.is_empty() { HostShare::new(m, &*gpu, &moe_layers)? } else { None }; let worker = if !moe_layers.is_empty() { Some(CpuWorker::new(m, &*gpu, moe_layers)?) } else { None }; // R3a: prefetch the next layer's experts predicted by the previous token's routing there. Disabled on gfx11xx/iGPU // where the small L2 cache causes prefetching to evict active lines and hurt decode throughput. @@ -1108,28 +1306,29 @@ impl<'a> GpuModel<'a> { let pids = if prefetch { Some(gpu.zeros::((c.n_layer + 1) * c.n_expert_used)?) } else { None }; let mb = |b: usize| b as f64 / 1048576.0; crate::say!( - "plan: weights+state+scratch {:.0} MB (KV {:.0} MB for {ctx} tokens{}, prefill {:.0} MB), expert slots {:.0} MB, resident experts {}/{}", - mb(free0.saturating_sub(free1)), mb(2 * 2 * gpu.kv_words(ctx * kv) * c.layers[range.clone()].iter().filter(|&&k| k == LayerKind::Attn).count()), - if ns > 1 { format!(" in each of {ns} slots") } else { String::new() }, mb(pf.as_ref().map_or(0, |p| p.bytes())), - mb(cache.as_ref().map_or(0, |x| x.slot_bytes_total())), - cache.as_ref().map_or(0, |x| x.resident_count()), cache.as_ref().map_or(0, |x| x.total_experts()), + "GPU memory: {:.0} MB for weights and state (KV {:.0} MB for {kv0} tokens{}{}, prefill {:.0} MB){}", + mb(free0.saturating_sub(free1)), mb((gpu.kv_words(kv0 * kv) + gpu.kv_words_v(kv0 * kv)) * 2 * c.layers[range.clone()].iter().filter(|&&k| k == LayerKind::Attn).count()), + if ns > 1 { format!(" in each of {ns} slots") } else { String::new() }, + if grow { format!(", growing to {ctx} on demand") } else { String::new() }, mb(pf.as_ref().map_or(0, |p| p.bytes())), + cache.as_ref().map_or(String::new(), |x| format!(", {} of {} experts on the GPU in {:.0} MB", x.resident_count(), x.total_experts(), mb(x.slot_bytes_total()))), ); // R3: expert bytes per token and the per-layer working set, against the 6 MB L2 of the V100, so the prefetch // decision has numbers in the log (the attained GB/s is printed after a bench run). if let Some(ca) = &cache { let k = c.n_expert_used; let per = (0..ca.layers_len()).map(|il| ca.active_set_bytes(il, k)).max().unwrap_or(0); - crate::say!("expert traffic: {:.1} MB per layer active set (top-{k}), {:.1} MB per token over {} MoE layers{}", + crate::detail!("expert traffic: {:.1} MB per layer active set (top-{k}), {:.1} MB per token over {} MoE layers{}", mb(per), mb(ca.token_bytes(k)), ca.total_experts() / c.n_expert.max(1), if prefetch { ", next-layer L2 prefetch on (STRATA_MOE_PREFETCH)" } else { "" }); } let mtp = mtp_head; let adapt_every = std::env::var("STRATA_ADAPT_EVERY").ok().and_then(|v| v.parse().ok()).unwrap_or(8); let adapt_swaps = std::env::var("STRATA_ADAPT_SWAPS").ok().and_then(|v| v.parse().ok()).unwrap_or(64); - let reset_counts_after_prefill = std::env::var_os("STRATA_RESET_COUNTS").is_some(); + let keep_decode_set = std::env::var_os("STRATA_RESET_COUNTS").is_some(); let _ = &mut ext_draft; - Ok(GpuModel { m, gpu, layers, output_norm, output_hc, output, ple_ring, qsa, ple_prev: [-1, -1], saved_ple_prev: [-1, -1], ple_undo: ([-1, -1], vec![]), bufs, x, worker, logits, amax, ids, slots, step_buf, rope_buf, rope_offset: 0, hada, mrope: false, mrope_buf: gpu_mrope, ctx, pos: 0, saved, saved_pos: 0, saved_ids: vec![], sys: None, parked: vec![], owner: 0, saved_owner: 0, sys_owner: 0, cache_ram: 0, cache, adapt_every, adapt_swaps, reset_counts_after_prefill, hits: 0, misses: 0, tokens: 0, mailbox_writes: Default::default(), mailbox_reads: Default::default(), pids, cpu_time: Duration::ZERO, resumed: Default::default(), lora_applied: Default::default(), drafts: (0, 0), split_time: Default::default(), k, nsnap, short: 32, pf, prompt_cache_path: None, bt, mtp, dflash, ext_draft, ext_draft_pend: Vec::new(), mhc_ones, graph_tag: 0, ngram: None, first: range.start, next: None, - cur: 0, seqs, rows: vec![], row_tokens: 0 }) + crate::weights::trim_working_set(); + Ok(GpuModel { m, gpu, layers, output_norm, output_hc, output, ple_ring, qsa, ple_prev: [-1, -1], saved_ple_prev: [-1, -1], ple_undo: ([-1, -1], vec![]), bufs, x, worker, logits, amax, ids, slots, step_buf, rope_buf, rope_offset: 0, hada, mrope: false, mrope_buf: gpu_mrope, pf_mrope: None, pf_mrope_buf: None, ctx, pos: 0, saved, saved_pos: 0, saved_ids: vec![], sys: None, parked: vec![], owner: 0, saved_owner: 0, sys_owner: 0, cache_ram: 0, cache, adapt_every, adapt_swaps, keep_decode_set, hits: 0, misses: 0, tokens: 0, mailbox_writes: Default::default(), mailbox_reads: Default::default(), pids, host_exp, hc_defer: Default::default(), hc_pend: Default::default(), hc_cnt, cpu_time: Duration::ZERO, resumed: Default::default(), lora_applied: Default::default(), drafts: (0, 0), split_time: Default::default(), k, nsnap, short: 32, pf, prompt_cache_path: None, bt, mtp, dflash, ext_draft, ext_draft_pend: Vec::new(), mhc_ones, graph_tag: 0, ngram: None, first: range.start, next: None, vram_margin, + cur: 0, seqs, kv_cap: if grow { vec![kv0; ns] } else { vec![] }, kv0, rows: vec![], row_tokens: 0, cpu_frac: 0.5, cpu_unsampled: 0, kv_stage }) } /// Clear KV and recurrent state (and forget the `prefill_cached` prefix, whose KV this zeroes). @@ -1157,10 +1356,14 @@ impl<'a> GpuModel<'a> { } self.ext_draft_pend.clear(); if let Some(ng) = self.ngram.as_mut() { ng.reset(); } + // A slot whose KV grew gives the VRAM back (its new caches are zeroed). + let shrink = self.kv_cap.get(self.cur).is_some_and(|&n| n > self.kv0); + if shrink { self.kv_resize(self.cur, self.kv0, false)?; } for l in self.layers.iter().chain(self.mtp.as_ref().map(|h| &h.layer)) { match &l.mixer { Mixer::Delta { conv, s, .. } => { self.gpu.memset(&conv[self.cur])?; self.gpu.memset(&s[self.cur])?; } - Mixer::Attn { kc, vc, .. } => { self.gpu.memset(&kc[self.cur])?; self.gpu.memset(&vc[self.cur])?; } + Mixer::Attn { kc, vc, .. } if !shrink => { self.gpu.memset(&kc[self.cur])?; self.gpu.memset(&vc[self.cur])?; } + Mixer::Attn { .. } => {} } } self.pos = 0; @@ -1216,35 +1419,85 @@ impl<'a> GpuModel<'a> { /// Run an image prompt as a fresh sequence and return its last logits: text tokens through `step`, image tokens /// through `step_embed` with their M-RoPE positions. `step` then uses the RoPE offset for text past the image. pub fn prefill_image(&mut self, p: &crate::vision::Prompt, embs: &[Vec>]) -> anyhow::Result> { - let c = &self.m.cfg; - ensure!(c.n_embd_ple == 0 && c.idx_top_k == 0, "image input is not supported for this model yet ({} with PLE or QSA layers)", c.arch); - self.reset()?; + Ok(self.prefill_image_with(p, embs, &[], 0, &mut |_| Ok(()))?.0) + } + + /// `prefill_image` with `prefill_cached`'s prefix cache and `between` every 64 tokens (the other slots' decode + /// steps, under `--parallel`; this slot is made current again after it). `hashes` name each image's source + /// (`Prompt::cache_keys`), so a cached prefix is reused across an image only when it is the same image; the + /// state after `keep` rows is saved for the next turn. Returns the logits and the rows reused. + pub fn prefill_image_with(&mut self, p: &crate::vision::Prompt, embs: &[Vec>], hashes: &[u64], keep: usize, + between: &mut dyn FnMut(&mut Self) -> anyhow::Result<()>) -> anyhow::Result<(Vec, usize)> { self.rows.clear(); - self.parked.clear(); // The draft head has not seen the image rows; image prompts decode without MTP/DFlash. let t = self.tail_mut(); t.mtp = None; t.dflash = None; t.ext_draft = None; t.ext_draft_pend.clear(); - let mut rows = p.images.iter().zip(embs).flat_map(|(span, e)| (span.start..).zip(e)).peekable(); - let mut logits = Vec::new(); - // ponytail: one token per forward (decode speed); a batched prefill needs M-RoPE in the prefill kernels. - for (i, &id) in p.ids.iter().enumerate() { - logits = match rows.next_if(|r| r.0 == i) { - Some((_, x)) => self.step_embed(x, p.positions[i])?, - None => { self.rope_offset = p.positions[i][0] - self.pos as i32; self.step(id)? } - }; + // Without a hash per image the prompt is not keyed: no reuse, nothing saved. + let keep = if hashes.len() == p.images.len() { keep.min(p.ids.len() - 1) } else { 0 }; + let keys = p.cache_keys(hashes); + let reused = self.cache_begin(&keys, keep)?; + if keep > reused { + self.prefill_image_range(p, embs, reused, keep, between)?; + self.save_state()?; + (self.saved_ids, self.saved_owner) = (keys[..keep].to_vec(), self.owner); } + let logits = self.prefill_image_range(p, embs, reused.max(keep), p.ids.len(), between)?; self.rope_offset = p.next_position - self.pos as i32; + Ok((logits, reused)) + } + + /// Rows `from..to` of an image prompt, from position `from`; returns the last row's logits. + fn prefill_image_range(&mut self, p: &crate::vision::Prompt, embs: &[Vec>], from: usize, to: usize, + between: &mut dyn FnMut(&mut Self) -> anyhow::Result<()>) -> anyhow::Result> { + let cur = self.cur; + let mut logits = Vec::new(); + // Text runs go through the batched prefill: their positions follow one another, shifted by `rope_offset`. + // Image rows go in batched forwards of up to a chunk (`prefill_image_rows`). + type Between<'a, M> = &'a mut dyn FnMut(&mut M) -> anyhow::Result<()>; + let text = |s: &mut Self, a: usize, b: usize, logits: &mut Vec, between: Between| -> anyhow::Result<()> { + if a >= b { return Ok(()) } + s.rope_offset = p.positions[a][0] - s.pos as i32; + *logits = s.prefill_with(&p.ids[a..b], &mut |s| { between(s)?; s.use_slot(cur); Ok(()) })?; + Ok(()) + }; + let mut i = from; + for (span, e) in p.images.iter().zip(embs) { + let end = span.start + e.len(); + if end <= i { continue; } + if span.start >= to { break; } + text(self, i, span.start.min(to), &mut logits, between)?; + // `between` after each batched run, or after 64 rows one per forward. + let (mut k, mut since) = (i.max(span.start) - span.start, 0); + let stop = end.min(to) - span.start; + while k < stop { + if since >= 64 { between(self)?; self.use_slot(cur); since = 0; } + let j = span.start + k; + let n = self.prefill_image_rows(&e[k..stop], &p.positions[j..span.start + stop], &p.ids[j..span.start + stop])?; + if n > 0 { (k, since) = (k + n, 64); continue; } + logits = self.step_embed(&e[k], p.positions[j], p.ids[j])?; + (k, since) = (k + 1, since + 1); + } + i = end.min(to); + } + text(self, i, to, &mut logits, between)?; Ok(logits) } - /// `step` for an image token: `x` is its embedding (a projector row), `pos` its M-RoPE positions [t, y, x, z]. - fn step_embed(&mut self, x: &[f32], pos: [i32; 4]) -> anyhow::Result> { + /// `step` for an image token: `x` is its embedding (a projector row), `pos` its M-RoPE positions [t, y, x, z], + /// `id` the placeholder token, whose PLE input the model takes as `Model::step_embed` does. + fn step_embed(&mut self, x: &[f32], pos: [i32; 4], id: u32) -> anyhow::Result> { if self.pos >= self.ctx { bail!("context full ({} tokens; raise --ctx)", self.ctx); } + self.kv_need(self.cur, self.pos + 1)?; let seq = self.begin_seq(); self.gpu.put(&x.repeat(self.m.cfg.hc_n.max(1)), &self.x, 0)?; + if self.ple_ring.is_some() { + self.ple_undo = (self.ple_prev, vec![id]); + let pe = self.m.ple_embed(&mut self.ple_prev, id); + self.gpu.put(&pe, &self.bufs["emb"], 0)?; + } self.gpu.put(&[self.pos as i32, seq as i32], &self.step_buf, 0)?; self.gpu.put(&pos.map(|p| [p, seq as i32]).concat(), &self.mrope_buf, 0)?; self.mrope = true; @@ -1267,16 +1520,24 @@ impl<'a> GpuModel<'a> { if s == self.cur { return; } let mut q = std::mem::take(&mut self.seqs[s]); std::mem::swap(&mut self.pos, &mut q.pos); + std::mem::swap(&mut self.rope_offset, &mut q.rope); std::mem::swap(&mut self.saved, &mut q.saved); std::mem::swap(&mut self.saved_pos, &mut q.saved_pos); std::mem::swap(&mut self.saved_ids, &mut q.saved_ids); std::mem::swap(&mut self.saved_owner, &mut q.saved_owner); std::mem::swap(&mut self.sys, &mut q.sys); std::mem::swap(&mut self.sys_owner, &mut q.sys_owner); + std::mem::swap(&mut self.ple_prev, &mut q.ple_prev); + std::mem::swap(&mut self.saved_ple_prev, &mut q.saved_ple_prev); + std::mem::swap(&mut self.ple_undo, &mut q.ple_undo); self.seqs[self.cur] = q; self.cur = s; } + /// Whether slot `s` holds an image prompt (its RoPE positions are offset from its KV rows): `step_rows` and + /// `step_batch` do not take it. + pub fn slot_shifted(&self, s: usize) -> bool { if s == self.cur { self.rope_offset != 0 } else { self.seqs[s].rope != 0 } } + /// The tokens behind slot `s`'s saved state and their owner (see `prefill_cached`). pub fn slot_saved(&self, s: usize) -> (&[u32], u64) { if s == self.cur { (&self.saved_ids, self.saved_owner) } else { (&self.seqs[s].saved_ids, self.seqs[s].saved_owner) } @@ -1286,13 +1547,62 @@ impl<'a> GpuModel<'a> { /// Most tokens of one `verify` forward on this backend (4 on CUDA, `TMAX` on Vulkan). pub fn tmax(&self) -> usize { self.gpu.verify_rows() } - pub fn batch_cap(&self) -> usize { self.bt.as_ref().map_or(0, |b| b.cap) } + pub fn batch_cap(&self) -> usize { if self.parts().all(|p| p.bt.is_some()) { self.bt.as_ref().map_or(0, |b| b.cap) } else { 0 } } + + pub fn is_moe(&self) -> bool { self.m.cfg.is_moe() } + + /// Context size in tokens (per slot). pub fn ctx(&self) -> usize { self.ctx } fn slot_pos(&mut self, s: usize) -> &mut usize { if s == self.cur { &mut self.pos } else { &mut self.seqs[s].pos } } + /// `kv_need` for slot `s`'s next token. + pub fn kv_step(&mut self, s: usize) -> anyhow::Result<()> { let p = *self.slot_pos(s); self.kv_need(s, p + 1) } + + /// Make slot `s`'s attention KV hold `upto` positions, when the slots' KV grows on demand: it doubles, to at least + /// `upto` and at most `ctx`, keeping its rows. Past `ctx` it leaves the "context full" error to the caller. + fn kv_need(&mut self, s: usize, upto: usize) -> anyhow::Result<()> { + if let Some(n) = self.next.as_mut() { n.kv_need(s, upto)?; } + let Some(&cap) = self.kv_cap.get(s) else { return Ok(()) }; + if upto <= cap || upto > self.ctx { return Ok(()) } + self.kv_resize(s, upto.max(2 * cap).next_multiple_of(self.kv0).min(self.ctx), true) + } + + /// Give slot `s` attention KV caches of `new` positions (zeroed; `keep`: with the old caches' rows), the MTP + /// head's too: it is allocated at the same start size (#150). Either all of them change or, out of VRAM, none. + /// The recorded graphs, which hold the old caches' addresses, go. + fn kv_resize(&mut self, s: usize, new: usize, keep: bool) -> anyhow::Result<()> { + let (g, cap) = (&*self.gpu, self.kv_cap[s]); + let mut fresh = vec![]; + for l in self.layers.iter().chain(self.mtp.as_ref().map(|h| &h.layer)) { + if let Mixer::Attn { kc, vc, .. } = &l.mixer { + for b in [&kc[s], &vc[s]] { + fresh.push(g.alloc(b.len() / cap * new).map_err(|e| anyhow::anyhow!( + "no VRAM to grow a slot's KV cache to {new} positions (lower --parallel or --ctx): {e:#}"))?); + } + } + } + g.sync()?; + let mut fresh = fresh.into_iter(); + for l in self.layers.iter_mut().chain(self.mtp.as_mut().map(|h| &mut h.layer)) { + if let Mixer::Attn { kc, vc, .. } = &mut l.mixer { + for b in [&mut kc[s], &mut vc[s]] { + let nb = fresh.next().unwrap(); + if keep { g.dtod(b, 0, &nb, 0, b.len().min(nb.len()))?; } + *b = nb; + } + } + } + self.kv_cap[s] = new; + g.sync()?; + g.graph_clear() + } + + /// Positions the current slot's attention KV holds. + fn kv_rows(&self) -> usize { self.kv_cap.get(self.cur).copied().unwrap_or(self.ctx) } + /// One decode step for each of up to `STEP_ROWS` distinct slots in one forward (each weight read once): `rows` holds /// (slot, token, whether to return its logits). Returns per row the greedy next token (argmax, first on ties) and /// the logits if asked (else empty: greedy rows copy back only the token). Each forward is graphed by its slots @@ -1302,7 +1612,17 @@ impl<'a> GpuModel<'a> { ensure!((1..=STEP_ROWS).contains(&nt) && self.mtp.is_none(), "step_rows: {nt} rows"); let pos: Vec = rows.iter().map(|&(s, ..)| *self.slot_pos(s)).collect(); if pos.iter().any(|&p| p >= self.ctx) { bail!("context full ({} tokens; raise --ctx)", self.ctx); } - self.put_embed(&rows.iter().map(|r| r.1).collect::>())?; + for (&(s, ..), &p) in rows.iter().zip(&pos) { self.kv_need(s, p + 1)?; } + let hc = self.m.cfg.hc_n.max(1); + self.gpu.put(&rows.iter().flat_map(|r| self.m.embed(r.1).repeat(hc)).collect::>(), &self.x, 0)?; + if self.ple_ring.is_some() { + // Each row's PLE n-gram context is its own slot's (`put_embed` used the current slot's). + let pe: Vec = rows.iter().flat_map(|&(s, t, _)| { + let prev = if s == self.cur { &mut self.ple_prev } else { &mut self.seqs[s].ple_prev }; + self.m.ple_embed(prev, t) + }).collect(); + self.gpu.put(&pe, &self.bufs["emb"], 0)?; + } let res = self.rows_pass(rows, &pos).and_then(|_| { let t = self.tail(); let g = &t.gpu; @@ -1317,7 +1637,7 @@ impl<'a> GpuModel<'a> { }); let every = self.adapt_every; let swaps = self.adapt_swaps; - let reset = self.reset_counts_after_prefill; + let reset = self.keep_decode_set; let mut p = Some(&mut *self); while let Some(q) = p { q.rows.clear(); @@ -1326,7 +1646,7 @@ impl<'a> GpuModel<'a> { q.row_tokens += nt; q.adapt_every = every; q.adapt_swaps = swaps; - q.reset_counts_after_prefill = reset; + q.keep_decode_set = reset; q.after_experts(nt, q.row_tokens)?; } p = q.next.as_deref_mut(); @@ -1348,9 +1668,13 @@ impl<'a> GpuModel<'a> { if self.next.is_none() { return Ok(()); } self.gpu.sync()?; self.finish(nt, 0, None)?; - let xs = self.gpu.get::(&self.x, 0, nt * self.m.cfg.n_embd)?; + // As in `pass`: every hyper-connection stream of the residual, and the PLE input. + let c = &self.m.cfg; + let xs = self.gpu.get::(&self.x, 0, nt * c.hc_n.max(1) * c.n_embd)?; + let pe = match self.bufs.get("emb") { Some(e) => self.gpu.get::(e, 0, nt * c.n_embd)?, None => vec![] }; let nx = self.next.as_deref_mut().unwrap(); nx.gpu.put(&xs, &nx.x, 0)?; + if !pe.is_empty() { nx.gpu.put(&pe, &nx.bufs["emb"], 0)?; } nx.rows_pass(rows, pos) } @@ -1359,6 +1683,41 @@ impl<'a> GpuModel<'a> { pub fn part_layers(&self) -> Vec { self.parts().map(|p| p.layers.len()).collect() } pub fn parts(&self) -> impl Iterator> { std::iter::successors(Some(self), |p| p.next.as_deref()) } + /// `POST /v1/vram`: resize each part's expert cache so that `reserve` bytes of its device stay free, counting + /// every program's use (`None`: the `--vram-margin` the part loaded with), between one slot a pool and the size + /// it loaded with. An expert that loses its slot runs on the CPU, so answers go on, slower; growing back takes the + /// hottest experts by the routing counts. After an error here the model should be loaded again. + pub fn vram_reserve(&mut self, reserve: Option) -> anyhow::Result { + let (mut slots, mut full_slots, mut bytes, mut full_bytes, mut free_min) = (0, 0, 0, 0, usize::MAX); + let mut devices = Vec::new(); + let mut part = Some(self); + while let Some(g) = part { + if let Some(cache) = g.cache.as_mut() { + let keep = reserve.unwrap_or(g.vram_margin); + g.gpu.sync_freed()?; + let before = cache.slot_bytes_total(); + let want = (before + g.gpu.mem_info()?.0).saturating_sub(keep); + if cache.resize(g.m, &*g.gpu, want)? { + g.gpu.graph_clear()?; + g.gpu.sync_freed()?; + crate::say!("vram: expert cache {} -> {} MB ({} of {} slots), {} MB of VRAM free", + before >> 20, cache.slot_bytes_total() >> 20, cache.slots(), cache.full().1, g.gpu.mem_info()?.0 >> 20); + } + let free = g.gpu.mem_info()?.0; + devices.push(serde_json::json!({"reserve_mib": keep >> 20, "expert_slots": cache.slots(), + "expert_cache_mib": cache.slot_bytes_total() >> 20, "vram_free_mib": free >> 20})); + (slots, full_slots) = (slots + cache.slots(), full_slots + cache.full().1); + (bytes, full_bytes) = (bytes + cache.slot_bytes_total(), full_bytes + cache.full().0); + free_min = free_min.min(free); + } + part = g.next.as_deref_mut(); + } + anyhow::ensure!(!devices.is_empty(), "this model has no expert cache to resize"); + Ok(serde_json::json!({"status": "ok", "reserve_mib": reserve.map(|r| r >> 20), "expert_slots": slots, + "expert_slots_full": full_slots, "expert_cache_mib": bytes >> 20, "expert_cache_full_mib": full_bytes >> 20, + "vram_free_mib": free_min >> 20, "devices": devices})) + } + /// The part that computes the logits. fn tail(&self) -> &GpuModel<'a> { self.parts().last().unwrap() } /// `tail`, which also holds the MTP draft head. @@ -1412,6 +1771,7 @@ impl<'a> GpuModel<'a> { /// Run one token; returns logits over the vocabulary. pub fn step(&mut self, token: u32) -> anyhow::Result> { if self.pos >= self.ctx { bail!("context full ({} tokens; raise --ctx)", self.ctx); } + self.kv_need(self.cur, self.pos + 1)?; self.dflash_commit_ctx()?; let prof = std::env::var_os("STRATA_VK_PROF").is_some(); let t0 = prof.then(std::time::Instant::now); @@ -1454,8 +1814,10 @@ impl<'a> GpuModel<'a> { /// `verify` for greedy speculation: `keep` gets the argmax of every row; returns its row n and that row's argmax. fn verify_greedy(&mut self, tokens: &[u32], keep: impl FnOnce(&[u32]) -> usize) -> anyhow::Result<(usize, u32)> { - self.dflash_commit_ctx()?; let (nt, nvoc) = (tokens.len(), self.m.cfg.n_vocab); + if self.pos + nt > self.ctx { bail!("context full ({} tokens; raise --ctx)", self.ctx); } + self.kv_need(self.cur, self.pos + nt)?; + self.dflash_commit_ctx()?; let prof = std::env::var_os("STRATA_VK_PROF").is_some(); let t0 = prof.then(std::time::Instant::now); let seq = self.begin_seq(); @@ -1491,6 +1853,7 @@ impl<'a> GpuModel<'a> { let nt = tokens.len(); if !(1..=self.tmax()).contains(&nt) { bail!("verify: {nt} tokens (1 to {})", self.tmax()); } if self.pos + nt > self.ctx { bail!("context full ({} tokens; raise --ctx)", self.ctx); } + self.kv_need(self.cur, self.pos + nt)?; self.dflash_commit_ctx()?; let seq = self.begin_seq(); self.put_embed(tokens)?; @@ -1505,7 +1868,7 @@ impl<'a> GpuModel<'a> { pub fn save_state(&mut self) -> anyhow::Result<()> { self.dflash_commit_ctx()?; let g = &self.gpu; - if self.saved.is_empty() { self.saved = alloc_saved(&**g, &self.layers)?; } + if self.saved.is_empty() { self.saved = alloc_saved(&**g, &self.layers, self.seqs.len() > 1)?; } let mut it = self.saved.iter(); for l in &self.layers { if let Mixer::Delta { conv, s, .. } = &l.mixer { @@ -1519,8 +1882,8 @@ impl<'a> GpuModel<'a> { let src = h.eagle.as_ref().map_or(&self.x, |e| &e.cur_g); g.dtod(src, 0, &h.saved_x, 0, h.saved_x.len())?; } - if let Some((r, sr)) = &self.ple_ring { g.dtod(r, 0, sr, 0, r.len())?; } - if let Some(q) = &self.qsa { g.dtod(&q.ring, 0, &q.saved, 0, q.ring.len())?; } + if let Some(pr) = &self.ple_ring { let (r, sr) = &pr[self.cur]; g.dtod(r, 0, sr, 0, r.len())?; } + if let Some(q) = &self.qsa { let (r, sr) = (&q.ring[self.cur], &q.saved[self.cur]); g.dtod(r, 0, sr, 0, r.len())?; } self.saved_ple_prev = self.ple_prev; self.saved_pos = self.pos; self.saved_ids.clear(); @@ -1532,15 +1895,15 @@ impl<'a> GpuModel<'a> { fn slot(&self) -> Vec<&Buf> { let mut v: Vec<&Buf> = self.saved.iter().flat_map(|(c, s)| [c, s]).collect(); v.extend(self.mtp.as_ref().map(|h| &h.saved_x)); - v.extend(self.ple_ring.as_ref().map(|(_, sr)| sr)); - v.extend(self.qsa.as_ref().map(|q| &q.saved)); + v.extend(self.ple_ring.as_ref().map(|pr| &pr[self.cur].1)); + v.extend(self.qsa.as_ref().map(|q| &q.saved[self.cur])); v } /// `save_state`, and keep a host copy of it as the state after `ids` (the system prompt). pub fn stash(&mut self, ids: &[u32]) -> anyhow::Result<()> { self.save_state()?; - let mut p = Some(self); + let mut p = Some(&mut *self); while let Some(q) = p { let data = q.slot().iter().map(|b| q.gpu.get::(b, 0, b.len())).collect::>()?; q.saved_ids = ids.to_vec(); @@ -1548,45 +1911,55 @@ impl<'a> GpuModel<'a> { (q.saved_owner, q.sys_owner) = (q.owner, q.owner); p = q.next.as_deref_mut(); } + // Also keep it among the parked states: the per-slot stash holds one system prompt, a caller that alternates + // two would otherwise read each from scratch. + if let Some(mut pk) = self.snapshot_saved(self.cache_ram)? { + pk.sys = true; + self.insert_parked(pk); + } Ok(()) } - /// The KV caches of the attention layers (and of the draft head/DFlash) and their QSA pooled keys, whose rows are positions. - fn kv_bufs(&self) -> Vec<&Buf> { - self.layers.iter().chain(self.mtp.as_ref().map(|h| &h.layer)) - .flat_map(|l| match &l.mixer { - Mixer::Attn { kc, vc, qsa, .. } => [&kc[self.cur], &vc[self.cur]].into_iter().chain(qsa.as_ref().map(|a| &a.pool)).collect(), + /// The KV caches of the attention layers (and of the draft head/DFlash) and their QSA pooled keys, whose rows are + /// positions, each with the positions it holds. + fn kv_bufs(&self) -> Vec<(&Buf, usize)> { + let (rows, ctx) = (self.kv_rows(), self.ctx); + self.layers.iter().map(|l| (l, rows)).chain(self.mtp.as_ref().map(|h| (&h.layer, rows))) + .flat_map(|(l, n)| match &l.mixer { + Mixer::Attn { kc, vc, qsa, .. } => [(&kc[self.cur], n), (&vc[self.cur], n)].into_iter().chain(qsa.as_ref().map(|a| (&a.pool[self.cur], ctx))).collect(), _ => vec![], }) - .chain(self.dflash.iter().flat_map(|df| df.layers.iter().flat_map(|dl| [&dl.kc[self.cur], &dl.vc[self.cur]]))) + .chain(self.dflash.iter().flat_map(|df| df.layers.iter().flat_map(|dl| [(&dl.kc[self.cur], ctx), (&dl.vc[self.cur], ctx)]))) .collect() } /// Snapshot the current saved GPU state into a host-memory `Parked` record if it fits in `cache_ram`. - fn snapshot_saved(&self) -> anyhow::Result> { + fn snapshot_saved(&self, cap: usize) -> anyhow::Result> { let n = self.saved_ids.len(); if n == 0 { return Ok(None) } let mut size = 0; let mut p = Some(self); while let Some(q) = p { - size += q.kv_bufs().iter().map(|b| b.len() / q.ctx * n).sum::() + q.slot().iter().map(|b| b.len()).sum::(); + size += q.kv_bufs().iter().map(|(b, r)| b.len() / r * n).sum::() + q.slot().iter().map(|b| b.len()).sum::(); p = q.next.as_deref(); } - if size > self.cache_ram { return Ok(None) } + if size > cap { return Ok(None) } let mut parts = vec![]; let mut p = Some(self); while let Some(q) = p { let g = &q.gpu; let slot = q.slot().iter().map(|b| g.get::(b, 0, b.len())).collect::>()?; - let kv = q.kv_bufs().iter().map(|b| g.get::(b, 0, b.len() / q.ctx * n)).collect::>()?; + let kv = q.kv_bufs().iter().map(|(b, r)| g.get::(b, 0, b.len() / r * n)).collect::>()?; parts.push(PartCopy { ple_prev: q.saved_ple_prev, slot, kv }); p = q.next.as_deref(); } - Ok(Some(Parked { ids: self.saved_ids.clone(), owner: self.saved_owner, parts })) + Ok(Some(Parked { ids: self.saved_ids.clone(), owner: self.saved_owner, parts, sys: false })) } - fn insert_parked(&mut self, pk: Parked) { - self.parked.retain(|old| !(old.owner == pk.owner && (pk.ids.starts_with(&old.ids) || old.ids == pk.ids))); + fn insert_parked(&mut self, mut pk: Parked) { + // A system-prompt state stays when a longer conversation that starts with it is parked. + pk.sys |= self.parked.iter().any(|old| old.sys && old.owner == pk.owner && old.ids == pk.ids); + self.parked.retain(|old| !(old.owner == pk.owner && (old.ids == pk.ids || (!old.sys && pk.ids.starts_with(&old.ids))))); self.parked.insert(0, pk); while self.parked.iter().map(Parked::bytes).sum::() > self.cache_ram { self.parked.pop(); } } @@ -1594,7 +1967,7 @@ impl<'a> GpuModel<'a> { /// Copy the saved state to host memory, so a later request that continues it can take it back (`unpark`); the /// least recently parked states go when they exceed `cache_ram`. fn park(&mut self) -> anyhow::Result<()> { - if let Some(pk) = self.snapshot_saved()? { + if let Some(pk) = self.snapshot_saved(self.cache_ram)? { self.insert_parked(pk); if self.prompt_cache_path.is_some() { if let Err(e) = self.save_prompt_cache() { @@ -1608,7 +1981,7 @@ impl<'a> GpuModel<'a> { /// Snapshot the current saved state into `parked` and persist to `prompt_cache_path` (Warm Start). pub(crate) fn sync_saved_to_prompt_cache(&mut self) -> anyhow::Result<()> { if self.prompt_cache_path.is_none() { return Ok(()) } - if let Some(pk) = self.snapshot_saved()? { + if let Some(pk) = self.snapshot_saved(self.cache_ram)? { self.insert_parked(pk); self.save_prompt_cache()?; } @@ -1625,12 +1998,12 @@ impl<'a> GpuModel<'a> { self.m.cfg.head_dim.hash(&mut h); self.m.cfg.ssm_d_inner.hash(&mut h); self.m.cfg.ssm_d_state.hash(&mut h); - if let Some(q) = &self.qsa { q.ring.len().hash(&mut h); } + if let Some(q) = &self.qsa { q.ring[0].len().hash(&mut h); } let mut p = Some(self); while let Some(q) = p { q.layers.len().hash(&mut h); q.kv_bufs().len().hash(&mut h); - for b in q.kv_bufs() { (b.len() / q.ctx).hash(&mut h); } + for (b, r) in q.kv_bufs() { (b.len() / r).hash(&mut h); } p = q.next.as_deref(); } h.finish() @@ -1638,9 +2011,14 @@ impl<'a> GpuModel<'a> { /// Save up to 4 most recent `Parked` states to `self.prompt_cache_path` atomically. pub fn save_prompt_cache(&self) -> anyhow::Result<()> { - use std::io::Write; let Some(path) = &self.prompt_cache_path else { return Ok(()) }; if self.parked.is_empty() { return Ok(()) } + self.write_states(path, &self.parked.iter().take(4).collect::>()) + } + + /// Write `entries` to `path` (a temporary file renamed over it), in the format `read_states` reads. + fn write_states(&self, path: &std::path::Path, entries: &[&Parked]) -> anyhow::Result<()> { + use std::io::Write; if let Some(parent) = path.parent() && !parent.as_os_str().is_empty() { std::fs::create_dir_all(parent)?; } @@ -1650,7 +2028,6 @@ impl<'a> GpuModel<'a> { w.write_all(b"STRATAPC")?; w.write_all(&1u32.to_le_bytes())?; w.write_all(&self.prompt_cache_fingerprint().to_le_bytes())?; - let entries: Vec<&Parked> = self.parked.iter().take(4).collect(); w.write_all(&(entries.len() as u32).to_le_bytes())?; for pk in entries { w.write_all(&pk.owner.to_le_bytes())?; @@ -1682,16 +2059,42 @@ impl<'a> GpuModel<'a> { /// Enable Warm Start persistence at `path` and load any existing compatible states into `self.parked`. pub fn load_prompt_cache(&mut self, path: &std::path::Path) -> anyhow::Result<()> { - use std::io::Read; self.prompt_cache_path = Some(path.to_path_buf()); if !path.exists() { return Ok(()); } + let loaded = self.read_states(path)?; + let mut total_toks = 0usize; + let mut total_bytes = 0usize; + for pk in loaded.into_iter().rev() { + total_toks += pk.ids.len(); + total_bytes += pk.bytes(); + self.insert_parked(pk); + } + if !self.parked.is_empty() { + crate::say!( + "warm start: loaded {} cached prefix state(s) ({total_toks} tokens, {:.1} MB) from {}", + self.parked.len(), + total_bytes as f64 / 1048576.0, + path.display() + ); + } + Ok(()) + } + + /// The states in a file of `write_states`; refused when this model's layout (or `--kv`) differs. + fn read_states(&self, path: &std::path::Path) -> anyhow::Result> { + self.read_states_from(path).map_err(|e| anyhow::anyhow!("{}: {e}", path.display())) + } + + fn read_states_from(&self, path: &std::path::Path) -> anyhow::Result> { + use std::io::Read; let f = std::fs::File::open(path)?; + let file_len = f.metadata()?.len() as usize; let mut r = std::io::BufReader::with_capacity(8 << 20, f); let mut magic = [0u8; 8]; r.read_exact(&mut magic)?; - ensure!(&magic == b"STRATAPC", "invalid magic in prompt cache {}", path.display()); + ensure!(&magic == b"STRATAPC", "not a prompt cache file"); let mut u4 = [0u8; 4]; let mut u8b = [0u8; 8]; r.read_exact(&mut u4)?; @@ -1711,7 +2114,7 @@ impl<'a> GpuModel<'a> { r.read_exact(&mut u4)?; let n_ids = u32::from_le_bytes(u4) as usize; if n_ids == 0 || n_ids > self.ctx { - bail!("cached sequence length {n_ids} exceeds --ctx {}", self.ctx); + bail!("cached sequence length {n_ids} is not in 1..={} (--ctx)", self.ctx); } let mut ids = Vec::with_capacity(n_ids); for _ in 0..n_ids { @@ -1733,6 +2136,7 @@ impl<'a> GpuModel<'a> { for _ in 0..n_slot { r.read_exact(&mut u8b)?; let len = u64::from_le_bytes(u8b) as usize; + ensure!(len <= file_len, "truncated or corrupt"); let mut buf = vec![0u8; len]; r.read_exact(&mut buf)?; slot.push(buf); @@ -1743,43 +2147,73 @@ impl<'a> GpuModel<'a> { for _ in 0..n_kv { r.read_exact(&mut u8b)?; let len = u64::from_le_bytes(u8b) as usize; + ensure!(len <= file_len, "truncated or corrupt"); let mut buf = vec![0u8; len]; r.read_exact(&mut buf)?; kv.push(buf); } parts.push(PartCopy { ple_prev: [p0, p1], slot, kv }); } - loaded.push(Parked { ids, owner, parts }); - } - let mut total_toks = 0usize; - let mut total_bytes = 0usize; - for pk in loaded.into_iter().rev() { - total_toks += pk.ids.len(); - total_bytes += pk.bytes(); - self.insert_parked(pk); + loaded.push(Parked { ids, owner, parts, sys: false }); } - if !self.parked.is_empty() { - crate::say!( - "warm start: loaded {} cached prefix state(s) ({total_toks} tokens, {:.1} MB) from {}", - self.parked.len(), - total_bytes as f64 / 1048576.0, - path.display() - ); - } - Ok(()) + Ok(loaded) + } + + /// Write slot `s`'s saved state (its cached prompt) to `path` (`serve --slot-save-path`); returns its tokens and + /// the file size. + pub fn save_slot(&mut self, s: usize, path: &std::path::Path) -> anyhow::Result<(usize, u64)> { + ensure!(s < self.slots().max(1), "no slot {s}"); + self.use_slot(s); + let pk = self.snapshot_saved(usize::MAX)?.context("the slot holds no cached prompt")?; + self.write_states(path, &[&pk])?; + Ok((pk.ids.len(), std::fs::metadata(path)?.len())) + } + + /// Make the state in `path` (`save_slot`) slot `s`'s saved state, owned by `owner`: the next prompt that + /// continues it starts from there. Returns its tokens. + pub fn restore_slot(&mut self, s: usize, path: &std::path::Path, owner: u64) -> anyhow::Result { + ensure!(s < self.slots().max(1), "no slot {s}"); + let mut pk = self.read_states(path)?.into_iter().next().context("no saved state in the file")?; + self.use_slot(s); + pk.owner = owner; + let n = pk.ids.len(); + self.parked.insert(0, pk); + if let Err(e) = self.unpark(0) { self.reset()?; return Err(e); } + Ok(n) + } + + /// Forget slot `s`'s cached prompt; returns its tokens. + pub fn erase_slot(&mut self, s: usize) -> anyhow::Result { + ensure!(s < self.slots().max(1), "no slot {s}"); + self.use_slot(s); + let n = self.saved_ids.len(); + self.reset()?; + Ok(n) } /// Make parked state `i` the saved state and return to it; the saved state is parked in its place. fn unpark(&mut self, i: usize) -> anyhow::Result<()> { let p = self.parked.remove(i); self.park()?; + self.kv_need(self.cur, p.ids.len())?; // A slot that never saved has no buffers to take the state yet. if self.saved.is_empty() { self.save_state()?; } + // A state read from a file must fit the buffers it goes to. + ensure!(p.parts.len() == self.parts().count(), "saved state does not fit this model's buffers"); + let mut q = Some(&*self); + for c in &p.parts { + let Some(m) = q else { break }; + let (slot, kv) = (m.slot(), m.kv_bufs()); + ensure!(slot.len() == c.slot.len() && slot.iter().zip(&c.slot).all(|(b, d)| b.len() == d.len()) + && kv.len() == c.kv.len() && kv.iter().zip(&c.kv).all(|((b, r), d)| d.len() == b.len() / r * p.ids.len()), + "saved state does not fit this model's buffers"); + q = m.next.as_deref(); + } let mut q = Some(&mut *self); for c in p.parts { let Some(m) = q else { break }; for (b, d) in m.slot().iter().zip(&c.slot) { m.gpu.put(d, b, 0)?; } - for (b, d) in m.kv_bufs().iter().zip(&c.kv) { m.gpu.put(d, b, 0)?; } + for ((b, _), d) in m.kv_bufs().iter().zip(&c.kv) { m.gpu.put(d, b, 0)?; } (m.saved_pos, m.saved_ple_prev, m.saved_ids, m.saved_owner) = (p.ids.len(), c.ple_prev, p.ids.clone(), p.owner); q = m.next.as_deref_mut(); } @@ -1911,8 +2345,8 @@ impl<'a> GpuModel<'a> { } } self.pos = self.saved_pos; - if let Some((r, sr)) = &self.ple_ring { g.dtod(sr, 0, r, 0, r.len())?; } - if let Some(q) = &self.qsa { g.dtod(&q.saved, 0, &q.ring, 0, q.ring.len())?; } + if let Some(pr) = &self.ple_ring { let (r, sr) = &pr[self.cur]; g.dtod(sr, 0, r, 0, r.len())?; } + if let Some(q) = &self.qsa { let (r, sr) = (&q.ring[self.cur], &q.saved[self.cur]); g.dtod(sr, 0, r, 0, r.len())?; } self.ple_prev = self.saved_ple_prev; // The draft head's entries before the saved position are still the ones its prompt fill wrote (see `mtp_synced`). if let Some(h) = self.mtp.as_mut() { @@ -1956,6 +2390,14 @@ impl<'a> GpuModel<'a> { let x = self.x.addr(); let vg = self.verify_gemm(nt); let mut res = 0; + // Nothing reads the stacks between layers but the next layer (no EAGLE features, no DFlash taps, no resume). + self.hc_defer.set(c.hc_n > 0 && from.is_none() && self.dflash.is_none() && self.mtp.as_ref().is_none_or(|h| h.eagle.is_none())); + let flush = || -> anyhow::Result<()> { + self.hc_defer.set(false); + let pend = self.hc_pend.take(); + if pend != 0 { g.hc_write(x, pend, p("inj"), ne, c.hc_n, nt, true)?; } + Ok(()) + }; for (i, l) in self.layers.iter().enumerate().skip(from.map_or(0, |il| il - self.first)) { let il = self.first + i; if from != Some(il) { @@ -1976,24 +2418,40 @@ impl<'a> GpuModel<'a> { if let Some(idx) = df.cfg.target_layer_ids.iter().position(|&tl| tl == il) { if res != 0 { g.add(x, res, nt * ne)?; res = 0; } let n_ids = df.cfg.target_layer_ids.len(); + // hc targets (qwen4exp): the drafter reads the plain mean of the hc streams + // (mirrors llama.cpp's hc_stream_mean); hc_mix with a constant large gate + // yields sum * sigmoid(g) / hc = mean. + let src = if self.m.cfg.hc_n > 0 { + g.hc_mix(self.x.addr(), df.dfg.addr(), df.dfm.addr(), ne, self.m.cfg.hc_n, nt)?; + &df.dfm + } else { + &self.x + }; g.batch(&mut || { for r in 0..nt { - g.dtod(&self.x, 4 * r * ne, &df.feat, 4 * (r * n_ids + idx) * ne, 4 * ne)?; + g.dtod(src, 4 * r * ne, &df.feat, 4 * (r * n_ids + idx) * ne, 4 * ne)?; } Ok(()) })?; } } } + flush()?; if self.next.is_some() { return if res != 0 { g.add(x, res, nt * ne) } else { Ok(()) }; } let out_w = self.output.as_ref().unwrap(); - let out_gemm = vg && self.output_hc.is_none() && out_w.cols % 64 == 0; + // A dense rotated file's head reads the rotated h ("hr", quantized into "hq"). + let dense = self.hada.as_ref().zip(c.hadamard.as_ref()).filter(|(_, r)| r.dense); + let out_gemm = vg && self.output_hc.is_none() && out_w.cols % 64 == 0 && dense.is_none(); match (&self.output_norm, &self.output_hc) { (Some(on), _) => { - let hq = if out_gemm { 0 } else { p("hq") }; + let hq = if out_gemm || dense.is_some() { 0 } else { p("hq") }; g.rms_norm_q(x, ne, on.ptr, p("h"), ne, ne, nt, eps, hq, res)?; + if let Some((s, r)) = dense { + g.hadamard(p("h"), 0, s[0].addr(), 0, p("hr"), ne, r.block, nt)?; + g.quant_xq(p("hr"), ne, ne, nt, p("hq"))?; + } } - (None, Some(hr)) => self.hc_read(hr, x, nt, &self.hc_at())?, + (None, Some(hr)) => self.hc_read(hr, x, nt, &self.hc_at(), None)?, _ => unreachable!(), } if let Some(eg) = self.mtp.as_ref().and_then(|h| h.eagle.as_ref()) { @@ -2011,7 +2469,7 @@ impl<'a> GpuModel<'a> { if out_gemm { g.gemm_dense(out_w, nt, p("h"), ne, self.logits.addr(), c.n_vocab, 0) } else { - g.gemvq(out_w, p("h"), ne, p("hq"), self.logits.addr(), c.n_vocab, nt) + g.gemvq(out_w, p(if dense.is_some() { "hr" } else { "h" }), ne, p("hq"), self.logits.addr(), c.n_vocab, nt) } } @@ -2033,22 +2491,27 @@ impl<'a> GpuModel<'a> { /// Hyper-connection read of the stacks at `r` (see `Model::hc_read`): the mixed vector into `a.h` (and `a.hq`), /// the injection weights into `a.inj`. - fn hc_read(&self, hr: &HcRead, r: u64, nt: usize, a: &HcAt) -> anyhow::Result<()> { + /// `pre`: an `hc_write` of (`out`, `clear`) into the stacks to run first, fused with the norm. + fn hc_read(&self, hr: &HcRead, r: u64, nt: usize, a: &HcAt, pre: Option<(u64, bool)>) -> anyhow::Result<()> { let (c, g) = (&self.m.cfg, &self.gpu); let (ne, hc, d) = (c.n_embd, c.hc_n, c.hc_n * c.n_embd); - self.gnorm(r, hr.norm.ptr, a.xn, nt)?; + match pre { + Some((out, clear)) => g.hc_write_norm(r, out, a.inj, hr.norm.ptr, a.xn, ne, hc, nt, clear, c.eps, self.hc_cnt.as_ref().filter(|_| nt <= HC_CNT).map_or(0, |b| b.addr()))?, + None => self.gnorm(r, hr.norm.ptr, a.xn, nt)?, + } + let mut silu_done = false; match &hr.inject { Some(inj) if a.gemm => { g.gemm_dense(&hr.down, nt, a.xn, d, a.lo, c.hc_rank, 0)?; g.gemm_dense(inj, nt, a.xn, d, a.inj, hc, 0)?; } + Some(inj) if nt == 1 && g.gemvq2_silu(&hr.down, inj, a.xn, a.lo, a.inj, 1.0 / hc as f32)? => silu_done = true, Some(inj) => g.gemvq2(&hr.down, inj, a.xn, d, 0, a.lo, a.inj, nt)?, None => self.hmv(a, &hr.down, a.xn, d, a.lo, c.hc_rank, nt)?, } - g.hc_silu(a.lo, 1.0 / hc as f32, nt * c.hc_rank)?; + if !silu_done { g.hc_silu(a.lo, 1.0 / hc as f32, nt * c.hc_rank)?; } self.hmv(a, &hr.up, a.lo, c.hc_rank, a.hg, d, nt)?; - g.hc_mix(a.xn, a.hg, a.h, ne, hc, nt)?; - if a.hq != 0 { g.quant_xq(a.h, ne, ne, nt, a.hq)?; } + g.hc_mix_q(a.xn, a.hg, a.h, ne, hc, nt, a.hq)?; Ok(()) } @@ -2062,7 +2525,14 @@ impl<'a> GpuModel<'a> { self.hmv(a, &pl.value, a.emb, ne, a.pv, ne, nt)?; g.ple_gate(a.pk, a.pq, a.pv, a.pg, ne, hc, nt)?; self.gnorm(a.pg, pl.norm_conv.ptr, a.pn, nt)?; - g.ple_conv(x, a.pg, a.pn, pl.conv.ptr, self.ple_ring.as_ref().unwrap().0.addr(), step, d, nt) + let ring = self.ple_ring.as_ref().unwrap(); + if self.rows.is_empty() { return g.ple_conv(x, a.pg, a.pn, pl.conv.ptr, ring[self.cur].0.addr(), step, d, nt); } + // `step_rows`: each row convolves over its own slot's ring. + for (r, &(sl, _)) in self.rows.iter().enumerate() { + let o = (4 * r * d) as u64; + g.ple_conv(x + o, a.pg + o, a.pn + o, pl.conv.ptr, ring[sl].0.addr(), step + 8 * r as u64, d, 1)?; + } + Ok(()) } /// y[t] = W x[t] for t < nt (strides in floats). @@ -2910,12 +3380,15 @@ impl<'a> GpuModel<'a> { fn mtp_run_inner(&mut self, tokens: &[u32], hid: u64, head: bool, allow_short: bool) -> anyhow::Result { if self.next.is_some() { return self.tail_mut().mtp_run_inner(tokens, hid, head, allow_short); } let nt = tokens.len(); + // The head's KV grows with the slot's (#150). + let upto = self.mtp.as_ref().map_or(0, |h| h.pos) + nt; + self.kv_need(self.cur, upto)?; let c = &self.m.cfg; let Some(h) = self.mtp.as_mut() else { bail!("MTP head not loaded") }; if h.pos + nt > self.ctx { bail!("context full ({} tokens; raise --ctx)", self.ctx); } let fast = h.eagle.is_some() || (self.cache.as_ref().is_some_and(|c| c.fully_resident()) && self.gpu.moe_mailbox_optional()); let short_on = head && allow_short && h.hc_head.is_none() && h.eagle.is_none() && h.short.is_some() && h.use_short.get(); - let seq = if fast { 0 } else { h.worker.as_mut().unwrap().begin() }; + let seq = match h.worker.as_mut() { Some(w) if !fast => w.begin(), _ => 0 }; let g = &self.gpu; let emb: Vec = tokens.iter().flat_map(|&t| self.m.embed(t)).collect(); g.put(&emb, &h.emb, 0)?; @@ -2939,9 +3412,9 @@ impl<'a> GpuModel<'a> { // (R2). The routing counters keep the head's share of the hit rate. if fast { self.hits += c.n_expert_used * nt; - } else if let Some(cache) = self.cache.as_mut() { + } else if let (Some(cache), Some(w)) = (self.cache.as_mut(), h.worker.as_ref()) { // One mailbox read per layer, as in `after_experts` (each is a bulk copy of the routing words). - let r = h.worker.as_mut().unwrap().routing(c.n_layer); + let r = w.routing(c.n_layer); self.mailbox_reads.set(self.mailbox_reads.get() + 1); let (hits, misses) = tally(&r); self.hits += hits; @@ -3007,8 +3480,11 @@ impl<'a> GpuModel<'a> { g.rope_neox(eg.k.addr(), hd, nt * nkv, nkv, ec.n_rot, h.step_buf.addr(), ec.rope_base) })?; g.kv_store(eg.k.addr(), eg.v.addr(), kc[self.cur].addr(), vc[self.cur].addr(), kv, nt, h.step_buf.addr(), hd)?; - g.attn_decode_q(eg.q.addr(), kc[self.cur].addr(), vc[self.cur].addr(), 0, eg.att.addr(), - eg.attp.addr(), h.step_buf.addr(), nh, nkv, hd, 1.0 / (hd as f32).sqrt(), gq, nt, 0, 0, 0, 0, 0)?; + if !(crate::host_attn::on_host(self.m.cfg.n_layer) + && g.attn_host(eg.q.addr(), kc[self.cur].addr(), vc[self.cur].addr(), 0, eg.att.addr(), h.step_buf.addr(), nh, nkv, hd, 1.0 / (hd as f32).sqrt(), nt)?) { + g.attn_decode_q(eg.q.addr(), kc[self.cur].addr(), vc[self.cur].addr(), 0, eg.att.addr(), + eg.attp.addr(), h.step_buf.addr(), nh, nkv, hd, 1.0 / (hd as f32).sqrt(), gq, nt, 0, 0, 0, 0, 0)?; + } self.mv(o, eg.att.addr(), nh * hd, self.bufs["mix"].addr(), ne, nt)?; g.rms_norm_q(x, ne, h.layer.post_norm.as_ref().unwrap().ptr, hp, ne, ne, nt, eps, 0, self.bufs["mix"].addr())?; g.batch(&mut || { @@ -3051,7 +3527,7 @@ impl<'a> GpuModel<'a> { } else { match &h.hc_head { Some(hr) => { - self.hc_read(hr, last, 1, &self.hc_at())?; + self.hc_read(hr, last, 1, &self.hc_at(), None)?; g.gemvq(self.output.as_ref().unwrap(), hp, ne, self.bufs["hq"].addr(), self.logits.addr(), c.n_vocab, 1)?; } None => { @@ -3074,10 +3550,24 @@ impl<'a> GpuModel<'a> { let (g, eps, ne) = (&self.gpu, c.eps, c.n_embd); let p = |n: &str| self.bufs[n].addr(); let rope = self.rope_buf.addr(); + // A dense rotated file (`config::Hadamard::dense`): the matrices that read "h" read its rotation "hr" (and "hq" + // quantizes "hr"); ssm_beta and ssm_alpha read the plain "h". `rot` rotates n wide rows of `src` into "hr". + let dense = self.hada.as_ref().zip(c.hadamard.as_ref()).filter(|(_, r)| r.dense); + let hx = if dense.is_some() { "hr" } else { "h" }; + let rot_h = || -> anyhow::Result<()> { + let Some((s, r)) = dense else { return Ok(()) }; + g.hadamard(p("h"), 0, s[0].addr(), 0, p("hr"), ne, r.block, nt)?; + g.quant_xq(p("hr"), ne, ne, nt, p("hq")) + }; + let rot = |src: &'static str, n: usize, perm: u64| -> anyhow::Result<&'static str> { + let Some((s, r)) = dense else { return Ok(src) }; + g.hadamard(p(src), 0, s[0].addr(), perm, p("hr"), n, r.block, nt)?; + Ok("hr") + }; // Inputs from "h" are quantized once ("hq", after each norm) instead of once per GEMV block. let mv = |w: &GpuTensor, x: &str, xs: usize, y: &str, ys: usize| - if x == "h" { g.gemvq(w, p(x), xs, p("hq"), p(y), ys, nt) } else { self.mv(w, p(x), xs, p(y), ys, nt) }; - let mv2 = |a: &GpuTensor, b: &GpuTensor, ya: &str, yb: &str| g.gemvq2(a, b, p("h"), ne, p("hq"), p(ya), p(yb), nt); + if x == "h" { g.gemvq(w, p(hx), xs, p("hq"), p(y), ys, nt) } else { self.mv(w, p(x), xs, p(y), ys, nt) }; + let mv2 = |a: &GpuTensor, b: &GpuTensor, ya: &str, yb: &str| g.gemvq2(a, b, p(hx), ne, p("hq"), p(ya), p(yb), nt); // The SwiGLU for a down GEMV of type `ty` (float weights read g itself). Returns the xq for the GEMV. let sw = |ty: GgmlType, ga: &str, ua: &str, n: usize, rows: usize, q: &str| -> anyhow::Result { if ty.float_x() { g.swiglu(p(ga), p(ua), rows * n)?; return Ok(0); } @@ -3090,10 +3580,18 @@ impl<'a> GpuModel<'a> { let sink_addr = match &l.mixer { Mixer::Attn { sink: Some(s), .. } => s.ptr, _ => 0 }; let win = c.swa.get(il).copied().unwrap_or(false).then_some(c.n_swa).unwrap_or(0); let use_rope = c.rope_layer.get(il).copied().unwrap_or(true); - let vg = self.verify_gemm(nt) && l.hc.is_none() && l.mhc.is_none(); + let vg = self.verify_gemm(nt) && l.hc.is_none() && l.mhc.is_none() && dense.is_none(); let mixer_gemm = vg && ne % 64 == 0 && !matches!(&l.mixer, Mixer::Attn { qsa: Some(_), .. }); if !resume { let ha = self.hc_at(); + // The previous layer's deferred stream write: fused into this layer's first hc_read, or run here when + // something else reads the stacks first. + let pend = self.hc_pend.take(); + let pre = (pend != 0).then_some((pend, true)); + if pre.is_some() && (l.ple.is_some() || l.hc.is_none() || l.mhc.is_some()) { + g.hc_write(x, pend, p("inj"), ne, c.hc_n, nt, true)?; + } + let pre = pre.filter(|_| l.ple.is_none() && l.hc.is_some() && l.mhc.is_none()); if let Some(pl) = &l.ple { self.ple(pl, x, step, nt, &ha)?; } if let Some((mk, mhc_a, _)) = &l.mhc { let s = c.mhc_streams; @@ -3110,11 +3608,12 @@ impl<'a> GpuModel<'a> { g.rms_norm_q(p("h"), ne, l.attn_norm.as_ref().unwrap().ptr, p("h"), ne, ne, nt, eps, if mixer_gemm { 0 } else { p("hq") }, 0)?; } else { match (&l.attn_norm, &l.hc) { - (Some(an), _) => g.rms_norm_q(x, ne, an.ptr, p("h"), ne, ne, nt, eps, if mixer_gemm { 0 } else { p("hq") }, res)?, - (None, Some(hc)) => self.hc_read(&hc[0], x, nt, &ha)?, + (Some(an), _) => g.rms_norm_q(x, ne, an.ptr, p("h"), ne, ne, nt, eps, if mixer_gemm || dense.is_some() { 0 } else { p("hq") }, res)?, + (None, Some(hc)) => self.hc_read(&hc[0], x, nt, &ha, pre)?, _ => unreachable!(), } } + rot_h()?; match &l.mixer { Mixer::Delta { qkv, gate, beta, alpha, dt_bias, a, conv_w, norm, out, conv, s, snap } => { // Every allocated snapshot, not `self.k` of them: the count is baked into the captured graph. @@ -3153,6 +3652,10 @@ impl<'a> GpuModel<'a> { g.conv_silu(p("qkv"), conv[self.cur].addr(), conv_w.ptr, y_dst, channels, c.ssm_conv, nn, eps)?; } mv(gate, "h", ne, "z", c.ssm_d_inner)?; + if dense.is_some() { + self.mv(beta, p("h"), ne, b_dst, nv, nt)?; + return self.mv(alpha, p("h"), ne, g_dst, nv, nt); + } g.gemvq2(beta, alpha, p("h"), ne, p("hq"), b_dst, g_dst, nt) })?; } @@ -3172,6 +3675,11 @@ impl<'a> GpuModel<'a> { if vg && c.ssm_d_inner % 64 == 0 { g.norm_gate(p("o"), norm.ptr, p("z"), dv, nt * nv, eps)?; g.gemm_dense(out, nt, p("o"), c.ssm_d_inner, p("mix"), ne, 0)?; + } else if dense.is_some() { + g.norm_gate(p("o"), norm.ptr, p("z"), dv, nt * nv, eps)?; + let perm = self.bufs.get("hperm").map_or(0, |b| b.addr()); + let ox = rot("o", c.ssm_d_inner, perm)?; + mv(out, ox, c.ssm_d_inner, "mix", ne)?; } else { let oq = if l.hc.is_some() { g.norm_gate_sig(p("o"), norm.ptr, p("z"), dv, nt * nv, eps, p("oq"))? } else { g.norm_gate_q(p("o"), norm.ptr, p("z"), dv, nt * nv, eps, p("oq"))? }; @@ -3221,12 +3729,30 @@ impl<'a> GpuModel<'a> { Ok(()) })?; } + // QSA: each row pools its key into and selects blocks from its own slot's pooled keys. + let (sel, sst) = match (qsa, &self.qsa) { + (Some(a), Some(b)) => { + mv2(&a.qp, &a.kp, "iq", "ik")?; + for (r, &(sl, _)) in self.rows.iter().enumerate() { + g.qsa_pool(at("ik", r, QSA_D), b.ring[sl].addr() + a.ring, a.pool[sl].addr(), a.kn.ptr, step + 8 * r as u64, 1, c.n_rot, c.rope_base, eps)?; + } + g.rms_norm(p("iq"), QSA_D, a.qn.ptr, p("iqn"), QSA_D, QSA_D, nt * QSA_H, eps)?; + for (r, &(sl, _)) in self.rows.iter().enumerate() { + // rope_neox turns row t by position step[0] + t: one call a row, each at its own slot's. + g.rope_neox(at("iqn", r, QSA_H * QSA_D), QSA_D, QSA_H, QSA_H, c.n_rot, rope + 8 * r as u64, c.rope_base)?; + g.qsa_select(at("iqn", r, QSA_H * QSA_D), a.pool[sl].addr(), b.score.addr() + (4 * r * b.nbs) as u64, b.sel.addr() + (4 * r * b.sst) as u64, + 0, step + 8 * r as u64, 0, 1, b.nbs, b.top, b.sst, 0)?; + } + (b.sel.addr(), b.sst) + } + _ => (0, 0), + }; for (r, &(sl, pos)) in self.rows.iter().enumerate() { g.attn_decode_q(at("q", r, nh * hd), kc[sl].addr(), vc[sl].addr(), if c.q_gate { at("qg", r, nh * qs) } else { 0 }, at("att", r, nh * hd), - p("attp"), step + 8 * r as u64, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), gq_min(pos, 1), 1, 0, 0, 0, - sink_addr, win)?; + p("attp"), step + 8 * r as u64, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), gq_min(pos, 1), 1, 0, + if sel == 0 { 0 } else { sel + (4 * r * sst) as u64 }, sst, sink_addr, win)?; } - mv(o, "att", nh * hd, "mix", ne)?; + mv(o, rot("att", nh * hd, 0)?, nh * hd, "mix", ne)?; } else { if use_rope && self.rope_offset == 0 && !self.mrope { g.batch(&mut || g.rms_norm_rope_qk(p("qg"), qs, qn.ptr, p("q"), nt * nh, nh, p("kraw"), kn.ptr, p("k"), nt * nkv, nkv, @@ -3255,28 +3781,35 @@ impl<'a> GpuModel<'a> { let (sel, sst) = match (qsa, &self.qsa) { (Some(a), Some(b)) => { mv2(&a.qp, &a.kp, "iq", "ik")?; - g.qsa_pool(p("ik"), a.ring, a.pool.addr(), a.kn.ptr, step, nt, c.n_rot, c.rope_base, eps)?; + g.qsa_pool(p("ik"), b.ring[self.cur].addr() + a.ring, a.pool[self.cur].addr(), a.kn.ptr, step, nt, c.n_rot, c.rope_base, eps)?; g.rms_norm(p("iq"), QSA_D, a.qn.ptr, p("iqn"), QSA_D, QSA_D, nt * QSA_H, eps)?; - g.rope_neox(p("iqn"), QSA_D, nt * QSA_H, QSA_H, c.n_rot, rope, c.rope_base)?; - g.qsa_select(p("iqn"), a.pool.addr(), b.score.addr(), b.sel.addr(), 0, step, 0, nt, b.nbs, b.top, b.sst, 0)?; + // An image row's query turns by its M-RoPE positions, as in attention. + match (self.mrope, c.mrope_sections) { + (true, Some(sec)) => g.rope_mrope(p("iqn"), QSA_D, nt * QSA_H, QSA_H, c.n_rot, self.mrope_buf.addr(), c.rope_base, sec)?, + _ => g.rope_neox(p("iqn"), QSA_D, nt * QSA_H, QSA_H, c.n_rot, if self.mrope { self.mrope_buf.addr() } else { rope }, c.rope_base)?, + } + g.qsa_select(p("iqn"), a.pool[self.cur].addr(), b.score.addr(), b.sel.addr(), 0, step, 0, nt, b.nbs, b.top, b.sst, 0)?; (b.sel.addr(), b.sst) } _ => (0, 0), }; let out_gemm = vg && (nh * hd) % 64 == 0; - let aq = g.attn_decode_q(p("q"), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { p("qg") } else { 0 }, p("att"), p("attp"), step, nh, nkv, hd, - 1.0 / (hd as f32).sqrt(), gq, nt, if out_gemm { 0 } else { p("attq") }, sel, sst, sink_addr, win)?; + let host = sel == 0 && sink_addr == 0 && win == 0 && crate::host_attn::on_host(il) + && g.attn_host(p("q"), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { p("qg") } else { 0 }, p("att"), step, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), nt)?; + let aq = if host { 0 } else { g.attn_decode_q(p("q"), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { p("qg") } else { 0 }, p("att"), p("attp"), step, nh, nkv, hd, + 1.0 / (hd as f32).sqrt(), gq, nt, if out_gemm || dense.is_some() { 0 } else { p("attq") }, sel, sst, sink_addr, win)? }; if out_gemm { g.gemm_dense(o, nt, p("att"), nh * hd, p("mix"), ne, 0)?; } else if aq != 0 { g.gemvq(o, p("att"), nh * hd, aq, p("mix"), ne, nt)?; } else { - mv(o, "att", nh * hd, "mix", ne)?; + mv(o, rot("att", nh * hd, 0)?, nh * hd, "mix", ne)?; } } } } let post_hq = match &l.ffn { + _ if dense.is_some() => 0, Ffn::Dense { down, .. } if vg && ne % 64 == 0 && down.cols % 64 == 0 => 0, _ => p("hq"), }; @@ -3294,13 +3827,11 @@ impl<'a> GpuModel<'a> { } else { match (&l.post_norm, &l.hc) { (Some(pn), _) => g.rms_norm_q(x, ne, pn.ptr, p("h"), ne, ne, nt, eps, post_hq, p("mix"))?, - (None, Some(hc)) => { - g.hc_write(x, p("mix"), p("inj"), ne, c.hc_n, nt, false)?; - self.hc_read(&hc[1], x, nt, &ha)?; - } + (None, Some(hc)) => self.hc_read(&hc[1], x, nt, &ha, Some((p("mix"), false)))?, _ => unreachable!(), } } + rot_h()?; } { match &l.ffn { @@ -3312,8 +3843,13 @@ impl<'a> GpuModel<'a> { g.gemm_dense(down, nt, p("ge"), down.cols, p("ye"), ne, 0)?; } else { g.batch(&mut || mv2(gate, up, "ge", "ue"))?; - let q = sw(down.ty, "ge", "ue", down.cols, nt, "ffq")?; - g.gemvq(down, p("ge"), down.cols, q, p("ye"), ne, nt)?; + if let Some((s, r)) = dense { + g.hadamard(p("ge"), p("ue"), s[1].addr(), 0, p("ge"), down.cols, r.block, nt)?; + self.mv(down, p("ge"), down.cols, p("ye"), ne, nt)?; + } else { + let q = sw(down.ty, "ge", "ue", down.cols, nt, "ffq")?; + g.gemvq(down, p("ge"), down.cols, q, p("ye"), ne, nt)?; + } } if let Some((mk, _, mhc_f)) = &l.mhc { let leave_bit = if mk & 2 != 0 { 0x200 } else { 0 }; @@ -3354,9 +3890,13 @@ impl<'a> GpuModel<'a> { let rot = self.hada.as_ref().zip(c.hadamard.as_ref()); let hx = if rot.is_some() { p("hr") } else { p("h") }; let swd = || match rot { - Some((s, r)) => g.hadamard(p("ge"), p("ue"), s[1].addr(), p("ge"), c.n_ff_exp, r.block, kt).map(|_| 0), + Some((s, r)) => g.hadamard(p("ge"), p("ue"), s[1].addr(), 0, p("ge"), c.n_ff_exp, r.block, kt).map(|_| 0), None => sw(md.ty, "ge", "ue", c.n_ff_exp, kt, "ffq"), }; + // The host share needs the CPU part (a mailbox) and a backend that is not resuming. + let hs = self.host_exp.as_ref().filter(|_| !fast && !resume && rot.is_none()) + .and_then(|h| h.layers.get(il).copied().flatten().map(|l| (h.hid.addr(), h.hmin, l))); + let (hid, hmin) = hs.map_or((0, 0), |(a, n, _)| (a, n)); // Prefetch the next layer's predicted experts while this layer runs (knob off by default). if !resume { self.prefetch_next(il, &**g, cache, k)?; } // The shared expert's GEMVs and swiglu share batches with the routed ones. @@ -3373,14 +3913,23 @@ impl<'a> GpuModel<'a> { g.batch(&mut || { if let Some(s) = shared { if let Some(gi) = &s.gate_inp { mv2(router, gi, "rl", "sg")?; } else { mv(router, "h", ne, "rl", c.n_expert)?; } - mv2(&s.gate, &s.up, "shg", "shu")?; + // With a CPU part the shared expert waits for the route below. + if fast { mv2(&s.gate, &s.up, "shg", "shu")?; } } else { mv(router, "h", ne, "rl", c.n_expert)?; } Ok(()) })?; } + let route = || g.moe_route(p("rl"), c.n_expert, k, c.expert_weights_scale, lx.table_dev.addr(), ids, p("wts"), slots, p("wh"), p("h"), mb, ne, w.layout.h, step, nt, pid, c.router_sigmoid, hid, hmin); + // With a CPU part the route (which raises the worker's request) goes right after the router, so the + // shared expert's gate/up and the rotation run while the CPU computes its experts: Qwen3.8-Flash-Next + // Gyro decode 33.6 -> 33.9 tok/s (6 alternated runs, all 6 won). + if !fast { + route()?; + if !sh_gemm && let Some(s) = shared { mv2(&s.gate, &s.up, "shg", "shu")?; } + } // ponytail: a launch of its own; it fits the router's batch if it shows in the decode profile. - if let Some((s, r)) = rot { g.hadamard(p("h"), 0, s[0].addr(), hx, ne, r.block, nt)?; } - g.moe_route(p("rl"), c.n_expert, k, c.expert_weights_scale, lx.table_dev.addr(), ids, p("wts"), slots, p("wh"), p("h"), mb, ne, w.layout.h, step, nt, pid, c.router_sigmoid)?; + if let Some((s, r)) = rot { g.hadamard(p("h"), 0, s[0].addr(), 0, hx, ne, r.block, nt)?; } + if fast { route()?; } g.batch(&mut || { if mg.ty == mu.ty && (mg.rows, mg.cols) == (mu.rows, mu.cols) { let pair = (mu.off as i64 - mg.off as i64, p("ue") as i64 - p("ge") as i64); @@ -3389,6 +3938,11 @@ impl<'a> GpuModel<'a> { g.moe_gemv(mg.ty, mg.rows, mg.cols, base + mg.off as u64, stride, slots, kt, hx, ne, k, p("ge"), None, p("hq"))?; g.moe_gemv(mu.ty, mu.rows, mu.cols, base + mu.off as u64, stride, slots, kt, hx, ne, k, p("ue"), None, p("hq"))?; } + // The host share's gate and up beside the cached experts' (the other stream), in few blocks: its + // blocks wait on PCIe, and in the usual launch shape they held the SMs the cached GEMVs needed. + if let Some((hid, _, hl)) = hs { + g.moe_gemv_blocks(mg.ty, mg.rows, mg.cols, hl.gate, hl.stride_gu, hid, kt, hx, ne, k, p("ge"), Some((hl.up_off, p("ue") as i64 - p("ge") as i64)), p("hq"), HOST_BLOCKS)?; + } if !sh_gemm { if let Some(s) = shared { sq = sw(s.down.ty, "shg", "shu", c.n_ff_shexp, nt, "shq")?; } } @@ -3409,13 +3963,19 @@ impl<'a> GpuModel<'a> { let (sh, sg) = match shared { Some(s) => (p("shy"), if s.gate_inp.is_some() { p("sg") } else { 0 }), None => (0, 0) }; // Hyper-connections: the FFN output collects in "mo" (zero) and goes to the streams from there. let fx = if l.hc.is_some() { p("mo") } else { x }; + if let Some((hid, _, hl)) = hs { + g.moe_gemv_blocks(md.ty, md.rows, md.cols, hl.down, hl.stride_d, hid, kt, p("ge"), md.cols, 1, p("ye"), None, dq, HOST_BLOCKS)?; + } g.moe_down_combine(md.ty, md.rows, md.cols, base + md.off as u64, stride, slots, k, p("ge"), p("ye"), dq, fx, p("wh"), sh, sg, mb, w.layout.y, step, nt)?; if !self.m.loras.is_empty() { let use_ge = md.ty.float_x(); self.apply_lora_gpu_down(il, nt, k, c.n_ff_exp, c.n_embd, l.hc.is_some(), use_ge)?; } - if l.hc.is_some() { g.hc_write(x, p("mo"), p("inj"), ne, c.hc_n, nt, true)?; } + // Deferred into the next layer's hc_read, where it runs fused with the norm (`hc_defer`). + if l.hc.is_some() { + if self.hc_defer.get() { self.hc_pend.set(p("mo")); } else { g.hc_write(x, p("mo"), p("inj"), ne, c.hc_n, nt, true)?; } + } } } } @@ -3429,10 +3989,10 @@ impl<'a> GpuModel<'a> { self.cache.as_ref().is_some_and(|c| c.fully_resident()) && self.gpu.moe_mailbox_optional() } - /// Serve policy: follow the reply, not the prompt, in the expert placement after each prefill. `serve` turns it on; + /// Serve policy: keep the reply's hot experts and routing counts across prompts (see `keep_decode_set`). `serve` turns it on; /// a split model's other parts follow through `next`. pub fn set_decode_only(&mut self, on: bool) { - self.reset_counts_after_prefill = on; + self.keep_decode_set = on; // Fewer, larger swaps than a benchmark run: the reply's hot set is learned in a few steps, while 64 swaps // every 8 tokens spend more on uploads and page-cache churn than the extra hits return. if std::env::var_os("STRATA_ADAPT_EVERY").is_none() { self.adapt_every = 16; } @@ -3440,14 +4000,6 @@ impl<'a> GpuModel<'a> { if let Some(n) = self.next.as_mut() { n.set_decode_only(on); } } - fn reset_counts(&mut self) { - let mut p = Some(&mut *self); - while let Some(q) = p { - if let Some(c) = q.cache.as_mut() { c.reset_counts(); } - p = q.next.as_deref_mut(); - } - } - /// The worker sequence number to publish in `step_buf`: 0 on the fast path, where the GPU asks the worker nothing. fn begin_seq(&mut self) -> u32 { let fast = self.expert_fast_path(); @@ -3561,7 +4113,7 @@ impl<'a> GpuModel<'a> { if let Some(n) = self.next.as_mut() { n.adapt_every = self.adapt_every; n.adapt_swaps = self.adapt_swaps; - n.reset_counts_after_prefill = self.reset_counts_after_prefill; + n.keep_decode_set = self.keep_decode_set; n.after_forward(nt)?; } Ok(()) @@ -3599,7 +4151,71 @@ impl<'a> GpuModel<'a> { #[cfg(test)] mod tests { - use super::{GpuModel, split_ends, split_shares, tally}; + use super::{GpuModel, split_ends, split_shares, tally, KV_START}; + use crate::gguf::Gguf; + use crate::model::Model; + + /// Regression (Qwen3.8-27B, `--parallel 2`, `--kv q8`): a greedy decode past a slot's growing KV wrote the row at + /// `pos` before reserving it. `verify_greedy` — the forward `step_greedy` runs — was the one forward of the model + /// that did not call `kv_need`, so at `pos == cap` the KV store landed past the end of the buffer (the Vulkan + /// "device is gone" of a lost device, one row past a full cache). + #[test] + fn greedy_step_grows_the_kv_cache() { + let dir = std::env::temp_dir().join(format!("strata_kv_grow_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("tiny.gguf"); + crate::testutil::make_qwen3(&path, 0); + let g = Gguf::open(&path).unwrap(); + let m = Model::load(&g).unwrap(); + if let Ok(bk) = crate::backend::open(None, 0) { + // Two slots and a context past KV_START: each slot's KV starts small and grows on demand, as under + // `--parallel` (`load_slots` is what serve uses then). + let ctx = KV_START + 8; + let mut gm = GpuModel::load_slots(&m, bk, ctx, 0, 0, 2).unwrap(); + let cap0 = *gm.kv_cap.first().expect("a slot's KV that grows on demand"); + assert!(cap0 <= ctx, "{} rows for a {ctx}-token slot", cap0); + // Decode up to the last row the slot holds: the cache is exactly full, nothing grew yet. + let mut t = 1u32; + while gm.pos < cap0 { t = gm.step_greedy(t).unwrap(); } + assert_eq!(gm.kv_cap[0], cap0, "growth before pos {cap0}"); + // The step that writes row `cap0`: without the reservation it stored past the buffer instead. + t = gm.step_greedy(t).unwrap(); + assert_eq!(gm.pos, cap0 + 1); + assert!(gm.kv_cap[0] > cap0, "step_greedy at pos {cap0} left the KV at {} rows", gm.kv_cap[0]); + // Rows past the old end are filled in a grown cache, and the decode goes on over them. + gm.step_greedy(t).unwrap(); + assert_eq!(gm.pos, cap0 + 2); + } else { + eprintln!("SKIP: no GPU backend"); + } + std::fs::remove_dir_all(&dir).ok(); + } + + /// `step_greedy` past `ctx` reports the "context full" error `step` does, rather than forwarding past the end of + /// a KV that has no room left to grow into. + #[test] + fn greedy_step_bails_at_the_context_limit() { + let dir = std::env::temp_dir().join(format!("strata_kv_ctx_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("tiny.gguf"); + crate::testutil::make_qwen3(&path, 0); + let g = Gguf::open(&path).unwrap(); + let m = Model::load(&g).unwrap(); + if let Ok(bk) = crate::backend::open(None, 0) { + // One slot: no growth, so the KV holds exactly `ctx` rows. + let ctx = 32; + let mut gm = GpuModel::load(&m, bk, ctx, 0, 0, 0).unwrap(); + for _ in 0..ctx { gm.step(1).unwrap(); } + assert_eq!(gm.pos, ctx); + let err = gm.step_greedy(1).unwrap_err().to_string(); + assert!(err.starts_with("context full"), "{err}"); + } else { + eprintln!("SKIP: no GPU backend"); + } + std::fs::remove_dir_all(&dir).ok(); + } /// Layer counts given as shares come back as the same counts: a calibrated split loads as it was measured. #[test] @@ -3609,6 +4225,29 @@ mod tests { assert_eq!(split_ends(&[30.0, 70.0], 48), [0, 14, 48]); } + /// A split part pays for its own layers; only the last part pays for the output head. Counting the whole model + /// on every part made a two-slot split believe it had room for one slot. + #[test] + fn a_split_part_counts_its_layers_and_the_last_the_head() { + let dir = std::env::temp_dir().join(format!("strata_part_weights_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("tiny.gguf"); + crate::testutil::make_qwen3(&path, 0); + let g = Gguf::open(&path).unwrap(); + let m = Model::load(&g).unwrap(); + let layers = super::part_weight_bytes(&m, 0..m.cfg.n_layer, false); + let head = super::part_weight_bytes(&m, 0..0, true); + let full = super::part_weight_bytes(&m, 0..m.cfg.n_layer, true); + assert!(layers > 0 && head > 0); + assert_eq!(full, layers + head); + assert_eq!(super::part_weight_bytes(&m, 0..0, false), 0); + // A range split in two adds up to the whole: no layer counted twice, none missed. + let half = m.cfg.n_layer / 2; + assert_eq!(super::part_weight_bytes(&m, 0..half, false) + super::part_weight_bytes(&m, half..m.cfg.n_layer, true), full); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn split_shares_take_one_positive_number_per_device() { assert_eq!(split_shares("30, 70", 2).unwrap(), [30.0, 70.0]); @@ -3618,6 +4257,38 @@ mod tests { } } + /// A prefill chunk belongs to its own slot after `between` ran another slot's decode. Writing it under the + /// decoding slot's state wrote past that slot's KV capacity (Qwen3.8-27B, `--parallel 2`, two 3k prompts). + #[test] + fn a_prefill_chunk_stays_on_its_slot_after_between() { + let dir = std::env::temp_dir().join(format!("strata_prefill_slot_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("tiny.gguf"); + crate::testutil::make_qwen3(&path, 0); + let g = Gguf::open(&path).unwrap(); + let m = Model::load(&g).unwrap(); + if let Ok(bk) = crate::backend::open(None, 0) { + let mut gm = GpuModel::load_slots(&m, bk, 256, 16, 0, 2).unwrap(); + gm.short = 0; // take the chunked prefill, not `step_all` + // Without the scratch, or with a prompt of one chunk, `prefill_with` never calls `between` and the test + // would pass without testing anything. + let chunk = gm.pf.as_ref().expect("no batched prefill scratch: the prompt would go through `step_all`").chunk; + // Slot 0 is decoding at position 1, as the other request is while a second prompt prefills. + gm.step(1).unwrap(); + gm.use_slot(1); + let tokens: Vec = (1..=20).map(|i| i % 7 + 1).collect(); + assert!(tokens.len() > chunk, "a {} token prompt is one chunk of {chunk}: `between` never runs", tokens.len()); + gm.prefill_with(&tokens, &mut |s| { s.use_slot(0); Ok(()) }).unwrap(); + assert_eq!((gm.cur, gm.pos), (1, tokens.len()), "the next chunk ran on slot {}", gm.cur); + gm.use_slot(0); + assert_eq!(gm.pos, 1, "the decoding slot's position moved"); + } else { + eprintln!("SKIP: no GPU backend"); + } + std::fs::remove_dir_all(&dir).ok(); + } + /// R1: a layer's routing gives the hit rate its numbers; a slot < 0 is an expert left on the CPU. #[test] fn routing_tally_of_a_partial_cache_counts_every_miss() { @@ -3640,3 +4311,9 @@ mod tests { fn _uses(g: &GpuModel) -> (bool, usize) { (g.expert_fast_path(), g.expert_bytes_per_token()) } } } + +/// `STRATA_KV_HOST=N`: the KV cache of the attention layers from block N on lives in host RAM (mapped pinned +/// memory the GPU reads over PCIe), freeing VRAM for a longer context. `all` = every layer. +fn kv_alloc(gpu: &dyn Backend, il: usize, bytes: usize) -> anyhow::Result { + if crate::host_attn::on_host(il) { gpu.alloc_host(bytes) } else { gpu.alloc(bytes) } +} diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index 7c0170c1..c16fa787 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -3,14 +3,77 @@ //! copied into a small staging area, a group of them at a time, each group's copy beside the previous group's GEMMs. use super::{Ffn, GpuModel, HcAt, Mixer}; -use crate::backend::{Backend, Buf, GEMM_BM, SAME_X}; -use crate::expert_cache::MATS; +use crate::cpu_worker::TMAX; +use crate::backend::{BATCHED, Backend, Buf, GEMM_BM, MOE_GATE_X, SAME_X}; +use crate::expert_cache::{ExpertCache, MATS}; use crate::model::Model; use crate::weights::Prefetch; /// Experts staged per group when a layer routes to experts outside the cache. Staging holds three groups. const STAGE: usize = 16; +/// `STRATA_ZERO_COPY_EXPERTS=1`: the GEMMs of a missed expert read its weights in place, from the file pages +/// `STRATA_MLOCK_EXPERTS` registered with the device (`Backend::host_ptr`, HIP only), instead of a staged copy. +/// Off by default because it is slower. A direct read moves the same bytes over the link as the copy (an expert's +/// second 128-slot tile comes from the cache), but kernel reads reach ~11.8 GB/s against the DMA's 14.1, and blocks +/// waiting on the bus hold the CUs that the resident experts' tiles would use. RX 9070 XT on PCIe 3.0 x16, this step loop +/// on 10 GB of Qwen3.8-Flash-Next UD-IQ4_XS experts with a 4096-token chunk's slot counts: 2.91 ms a step staged, +/// 4.18 in place. Prefill, two runs each: pp 9000 953/1023 tok/s staged, 879/906 in place; pp 32000 1005/1001 +/// staged, 894/892 in place. The logits are bit-identical either way. +static ZERO_COPY: std::sync::LazyLock = std::sync::LazyLock::new(|| std::env::var_os("STRATA_ZERO_COPY_EXPERTS").is_some_and(|v| v != "0")); + +/// Number of staging sections rotated by the copy and compute pipeline. +const STAGE_GROUPS: usize = 3; + +/// Pick whole experts by transfer and compute cost. Every miss saves one expert's +/// weight transfer, and its CPU cost grows with the number of routed rows. +fn split_cpu_experts(missed: &mut Vec, off: &[usize], early_ids: &[usize], frac: f64, fixed: bool, probe: bool) -> Vec { + let count = missed.len(); + let n_cpu = (count as f64 * frac).round() as usize; + if fixed || n_cpu == 0 && !probe || n_cpu == count { + return missed.split_off(count - n_cpu); + } + let rows = |e: usize| off[e + 1] - off[e]; + let row_total: usize = missed.iter().map(|&e| rows(e)).sum(); + let cost = |e: usize| row_total + count * rows(e); + let target = 2.0 * count as f64 * row_total as f64 * frac; + missed.sort_unstable_by_key(|&e| (early_ids.binary_search(&e).is_ok(), rows(e), std::cmp::Reverse(e))); + let mut cpu_cost = 0; + let mut take = 0; + for &e in missed.iter() { + let c = cost(e); + if (cpu_cost as f64 + c as f64 * 0.5) > target { break; } + cpu_cost += c; + take += 1; + } + let mut cpu: Vec<_> = missed.drain(..take.max(1)).collect(); + cpu.sort_unstable(); + missed.sort_unstable(); + cpu +} + +/// Keep GPU expert rows in expert order, with CPU expert rows in one contiguous tail. +fn pack_expert_rows(off: &[usize], cpu: &[usize]) -> Vec> { + if cpu.is_empty() { return off.windows(2).map(|p| p[0]..p[1]).collect(); } + let mut ranges: Vec<_> = off.windows(2).map(|p| p[0]..p[1]).collect(); + let mut next = 0; + for on_cpu in [false, true] { + for (e, range) in ranges.iter_mut().enumerate() { + if cpu.binary_search(&e).is_ok() == on_cpu { + let end = next + off[e + 1] - off[e]; + *range = next..end; + next = end; + } + } + } + ranges +} + +fn adjust_cpu_frac(frac: f64, cpu: std::time::Duration, gpu: std::time::Duration) -> f64 { + const STEP: f64 = 0.02; + (frac + if cpu > gpu { -STEP } else { STEP }).clamp(STEP, 1.0) +} + /// Float offsets into the scratch slab (each region holds `chunk` rows). Mixer and FFN regions alias, and so do the /// hyper-connection read and PLE temporaries (`xn` .. `pv`), which run outside both. struct Lay { h: usize, a: usize, b: usize, c: usize, d: usize, e: usize, rl: usize, wts: usize, ge: usize, ye: usize, shg: usize, shy: usize, sg: usize, hr: usize, @@ -24,6 +87,8 @@ pub(super) struct Scratch { feat: Option, /// `[chunk, n_ids * n_embd]` post-layer hidden states captured for DFlash `target_layer_ids`. dflash_feat: Option, + /// `[chunk, n_embd]` hc stream mean (hc targets), input to the DFlash capture. + dflash_mean: Option, /// ids | xrow | inv, `chunk * k` each. ints: Buf, tiles: Buf, @@ -60,6 +125,8 @@ impl Scratch { let (ye, shg, shy, sg) = (take(k * ne), take(c.n_ff_shexp), take(ne), take(1)); let hr = take(if c.hadamard.is_some() { ne } else { 0 }); // Gyro files: the rotated h let mut total = at.max(mix_end); + // A dense rotated file rotates mixer inputs too, so its "hr" overlaps neither region. + let hr = if c.hadamard.as_ref().is_some_and(|r| r.dense) { total += ne * chunk; total - ne * chunk } else { hr }; let (mut xn, mut lo, mut hg, mut pk, mut pq, mut pg, mut pn, mut pv, mut inj, mut mix, mut mo, mut emb) = Default::default(); if c.hc_n > 0 { at = base; @@ -85,8 +152,9 @@ impl Scratch { slab: gpu.zeros::(total)?, feat: if c.eagle3.is_some() { Some(gpu.zeros::(3 * ne * chunk)?) } else { None }, dflash_feat: c.dflash.as_ref().map(|dc| gpu.zeros::(dc.target_layer_ids.len() * ne * chunk)).transpose()?, + dflash_mean: if c.dflash.is_some() && c.hc_n > 0 { Some(gpu.zeros::(ne * chunk)?) } else { None }, ints: gpu.zeros::(3 * chunk * k)?, tiles: gpu.zeros::(2 * n_tiles)?, - staging: gpu.zeros::(if c.is_moe() { 3 * STAGE * stage_bytes } else { 0 })?, + staging: gpu.zeros::(if c.is_moe() { STAGE_GROUPS * STAGE * stage_bytes } else { 0 })?, }) } @@ -130,46 +198,89 @@ impl GpuModel<'_> { Ok(r) } - /// `prefill`, calling `between` between two chunks (`serve --parallel` decodes the other slots there; it must - /// leave the current slot's state alone). + /// `prefill`, calling `between` between two chunks (`serve --parallel` decodes the other slots there; it may + /// make another slot current, and the prompt's slot is made current again after it). pub fn prefill_with(&mut self, tokens: &[u32], between: &mut dyn FnMut(&mut Self) -> anyhow::Result<()>) -> anyhow::Result> { - let Some(chunk) = self.pf.as_ref().map(|p| p.chunk) else { return self.step_all(tokens) }; - if tokens.len() < self.short { return self.step_all(tokens); } + let short = |s: &mut Self| { let r = s.step_all(tokens); crate::term::prefilled(tokens.len()); r }; + let Some(chunk) = self.pf.as_ref().map(|p| p.chunk) else { return short(self) }; + if tokens.len() < self.short { return short(self); } anyhow::ensure!(self.pos + tokens.len() <= self.ctx, "context full ({} tokens; raise --ctx)", self.ctx); + self.kv_need(self.cur, self.pos + tokens.len())?; // STRATA_PF_ADAPT=N: place the hot experts after every N-th chunk of a long prompt, not only after all of it, // so the later chunks run with the placement the first ones showed (0 = off, the default; untested on real hardware). let every = std::env::var("STRATA_PF_ADAPT").ok().and_then(|v| v.parse::().ok()).unwrap_or(0); let nchunks = tokens.len().div_ceil(chunk); for (i, ch) in tokens.chunks(chunk).enumerate() { - if i > 0 { between(self)?; } - self.prefill_chunk(ch, None)?; + if i > 0 { let cur = self.cur; between(self)?; self.use_slot(cur); } + self.prefill_chunk(ch, None, None)?; + crate::term::prefilled(ch.len()); if every > 0 && (i + 1) % every == 0 && i + 1 < nchunks { self.adapt_experts()?; } } // The prompt's routing predicts the reply's: place its hot experts now instead of 64 per adapt during decode. self.adapt_experts()?; - // Serve: place the prompt's experts for the prefill, then let decode follow the reply's own routing. - if self.reset_counts_after_prefill { self.reset_counts(); } let s = self.tail(); let (g, ne) = (&s.gpu, s.m.cfg.n_embd); let h = s.bufs["h"].addr(); // `prefill_chunk` leaves the last hidden state in row 0 of `x`, as after `step` (the MTP draft reads it). match (&s.output_norm, &s.output_hc) { (Some(on), _) => g.rms_norm(s.x.addr(), 0, on.ptr, h, 0, ne, 1, s.m.cfg.eps)?, - (None, Some(hr)) => s.hc_read(hr, s.x.addr(), 1, &s.hc_at())?, + (None, Some(hr)) => s.hc_read(hr, s.x.addr(), 1, &s.hc_at(), None)?, _ => unreachable!(), } + let h = s.dense_head(h, 1)?; g.gemv(s.output.as_ref().unwrap(), h, s.logits.addr())?; g.get::(&s.logits, 0, s.m.cfg.n_vocab) } + /// Image rows of a prompt in one batched forward, up to a chunk. Returns how many rows it ran: 0 when this model + /// has no batched prefill for them, and never `ids`' last row (the caller takes that row's logits from + /// `step_embed`). + pub(super) fn prefill_image_rows(&mut self, embs: &[Vec], pos: &[[i32; 4]], ids: &[u32]) -> anyhow::Result { + let c = &self.m.cfg; + let Some(chunk) = self.pf.as_ref().map(|p| p.chunk) else { return Ok(0) }; + if c.mrope_sections.is_none() || self.qsa.is_some() || self.ple_ring.is_some() { return Ok(0); } + let n = embs.len().min(chunk).min(pos.len().saturating_sub(1)); + if n < 2 { return Ok(0); } + let segs = crate::backend::mrope_segments(&pos[..n]); + let first = segs.iter().flat_map(|&(a, ..)| pos[a].map(|p| [p, 0]).concat()).collect(); + anyhow::ensure!(self.pos + n <= self.ctx, "context full ({} tokens; raise --ctx)", self.ctx); + self.kv_need(self.cur, self.pos + n)?; + let emb: Vec = embs[..n].iter().flat_map(|x| x.repeat(c.hc_n.max(1))).collect(); + self.pf_mrope = Some((segs, first)); + let r = self.prefill_chunk(&ids[..n], Some((&emb, &[])), None); + self.pf_mrope = None; + r?; + crate::term::prefilled(n); + Ok(n) + } + + /// `rope_neox` of `t` tokens' heads at `x` (`per` a token, `stride` floats apart). Image rows (`pf_mrope`) turn + /// each M-RoPE section by its own position: in each segment a section that moves turns token by token, one that + /// stays turns the segment's rows as one token. + fn rope_chunk(&self, x: u64, stride: usize, t: usize, per: usize, rope: u64) -> anyhow::Result<()> { + let c = &self.m.cfg; + let (Some((segs, _)), Some(sec), Some(buf)) = (&self.pf_mrope, c.mrope_sections, &self.pf_mrope_buf) else { + return self.gpu.rope_neox(x, stride, t * per, per, c.n_rot, rope, c.rope_base); + }; + crate::backend::rope_mrope_segments(&*self.gpu, x, stride, per, segs, buf.addr(), c.n_rot, c.rope_base, sec) + } + + /// A dense rotated file (`config::Hadamard::dense`): the head reads H(s·h), in place over `nr` rows at `h`. + fn dense_head(&self, h: u64, nr: usize) -> anyhow::Result { + if let Some((s, r)) = self.hada.as_ref().zip(self.m.cfg.hadamard.as_ref()).filter(|(_, r)| r.dense) { + self.gpu.hadamard(h, 0, s[0].addr(), 0, h, self.m.cfg.n_embd, r.block, nr)?; + } + Ok(h) + } + /// Move the hot missed experts into VRAM (all parts of a split model). A fully resident cache has no hot missed /// expert to place: skip the scan over all its entries (issue #34 R2). fn adapt_experts(&mut self) -> anyhow::Result<()> { - let adapt = self.adapt_every > 0; + let (adapt, keep) = (self.adapt_every > 0, self.keep_decode_set); let mut p = Some(&mut *self); while let Some(q) = p { if let Some(cache) = q.cache.as_mut() { - if adapt && !cache.fully_resident() { cache.settle(q.m, &*q.gpu)?; } + if adapt && !cache.fully_resident() { cache.settle(q.m, &*q.gpu, keep)?; } } p = q.next.as_deref_mut(); } @@ -215,7 +326,9 @@ impl GpuModel<'_> { /// The start of `prefill_cached`: return to the longest state (saved, stashed or parked) that `tokens[..keep]` /// continues, and return its length. - fn cache_begin(&mut self, tokens: &[u32], keep: usize) -> anyhow::Result { + pub(super) fn cache_begin(&mut self, tokens: &[u32], keep: usize) -> anyhow::Result { + // A text prompt: positions are KV rows again (after an image prompt they were offset). + self.rope_offset = 0; let (hit, own) = (self.saved_ids.len(), self.owner); let stashed = self.sys.as_ref().filter(|_| self.sys_owner == own).map_or(0, |s| if tokens[..keep].starts_with(&s.3) { s.3.len() } else { 0 }); let extends = hit > 0 && hit >= stashed && self.saved_owner == own && tokens[..keep].starts_with(&self.saved_ids); @@ -224,7 +337,9 @@ impl GpuModel<'_> { .max_by_key(|(_, p)| p.ids.len()).map(|(i, p)| (i, p.ids.len())) .filter(|&(_, n)| n > stashed && !(extends && n <= hit)); let reused = if let Some((i, n)) = best { + let copy = self.parked[i].sys.then(|| self.parked[i].clone()); self.unpark(i)?; + if let Some(c) = copy { self.insert_parked(c); } n } else if extends { self.restore_state()?; @@ -246,8 +361,9 @@ impl GpuModel<'_> { /// `prefill_cached` for several slots in shared forwards (models with `batch_cap`): `jobs` holds (slot, owner, /// tokens, sys, keep) for distinct slots, each prompt within the context. The rows of all prompts go through the - /// batched forward in job order; `between` runs between two forwards. Returns per job the logits and the tokens - /// reused. On an error the jobs' slots are reset. + /// batched forward in job order; `between` runs between two forwards (it may make another slot current, and an + /// unshifted slot is made current again after it). Returns per job the logits and the tokens reused. On an error + /// the jobs' slots are reset. pub fn prefill_slots(&mut self, jobs: &[(usize, u64, &[u32], usize, usize)], between: &mut dyn FnMut(&mut Self) -> anyhow::Result<()>) -> anyhow::Result, usize)>> { let r = self.prefill_slots_run(jobs, between); @@ -260,29 +376,58 @@ impl GpuModel<'_> { use crate::backend::ATT_SPLITS; let (cap, max) = (self.batch_cap(), self.bt.as_ref().map_or(0, |b| b.rows)); anyhow::ensure!((1..=cap).contains(&jobs.len()), "prefill_slots: {} prompts, {cap} at most", jobs.len()); - let (mut rows, mut reused) = (vec![], vec![]); + let dense = self.bt.as_ref().is_some_and(|b| b.dense); + // Rows of three phases: up to `sys`, up to `keep`, the rest. A model without recurrent state runs them as one + // (a saved state is a position, and the forwards write its KV); else a phase's forwards end where the + // states of its prompts are stashed or saved. + let (mut phases, mut reused) = ([vec![], vec![], vec![]], vec![]); for &(sl, owner, tokens, sys, keep) in jobs { anyhow::ensure!(sys <= keep && keep < tokens.len() && tokens.len() <= self.ctx, "prefill_slots: sys {sys}, keep {keep} of {} tokens", tokens.len()); self.use_slot(sl); + self.kv_need(sl, tokens.len())?; self.owner = owner; let n = self.cache_begin(tokens, keep)?; - // These models have no recurrent state: a saved state is a position, and the forwards below write its KV. - if sys > n { self.pos = sys; self.stash(&tokens[..sys])?; } - if keep > n.max(sys) { - self.pos = keep; - self.save_state()?; - (self.saved_ids, self.saved_owner) = (tokens[..keep].to_vec(), owner); + if dense { + if sys > n { self.pos = sys; self.stash(&tokens[..sys])?; } + if keep > n.max(sys) { + self.pos = keep; + self.save_state()?; + (self.saved_ids, self.saved_owner) = (tokens[..keep].to_vec(), owner); + } } self.pos = n; - rows.extend(tokens[n..].iter().enumerate().map(|(i, &t)| (sl, t, n + i + 1 == tokens.len()))); + let cut = if dense { [n, n, n] } else { [n, sys.max(n), keep.max(n)] }; + for (ph, w) in phases.iter_mut().zip([cut[0]..cut[1], cut[1]..cut[2], cut[2]..tokens.len()]) { + ph.extend(w.map(|i| (sl, tokens[i], i + 1 == tokens.len()))); + } reused.push(n); } // The attention partials hold `cap` rows at ATT_SPLITS splits; short prompts need fewer splits a row. let splits = jobs.iter().map(|j| j.2.len()).max().unwrap().div_ceil(256).clamp(1, ATT_SPLITS); - let mut out = vec![]; - for (i, ch) in rows.chunks(max.min(cap * ATT_SPLITS / splits)).enumerate() { - if i > 0 { between(self)?; } - out.extend(self.batch_rows(ch, false)?); + let (mut out, mut first) = (vec![], true); + for (p, rows) in phases.iter().enumerate() { + for ch in rows.chunks(max.min(cap * ATT_SPLITS / splits)) { + if !first { + let cur = self.cur; + let r = between(self); + self.use_slot(cur); + r?; + } + first = false; + out.extend(self.batch_rows(ch, false)?); + } + if rows.is_empty() || p == 2 { continue; } + for &(sl, owner, tokens, sys, keep) in jobs { + let at = if p == 0 { sys } else { keep }; + if !rows.iter().any(|r| r.0 == sl) { continue; } + self.use_slot(sl); + self.owner = owner; + anyhow::ensure!(self.pos == at, "prefill_slots: slot {sl} at {} after phase {p}, not {at}", self.pos); + if p == 0 { self.stash(&tokens[..sys])?; } else { + self.save_state()?; + (self.saved_ids, self.saved_owner) = (tokens[..keep].to_vec(), owner); + } + } } Ok(out.into_iter().zip(reused).map(|((_, l), n)| (l, n)).collect()) } @@ -312,10 +457,18 @@ impl GpuModel<'_> { } /// `input`: the hidden rows and PLE input from the part before (None: embed `toks`). - fn prefill_chunk(&mut self, toks: &[u32], input: Option<(&[f32], &[f32])>) -> anyhow::Result<()> { + /// `rows`: the chunk is a step of a batch (`batch_rows` on a model with recurrent layers or experts): per row its + /// slot, and the attention splits. Row r runs at the position in `Batch::step` on its own slot's state, the KV + /// through `Batch::kvt`; the hidden rows are left in the slab, and no position moves. + fn prefill_chunk(&mut self, toks: &[u32], input: Option<(&[f32], &[f32])>, rows: Option<(&[usize], usize)>) -> anyhow::Result<()> { self.dflash_commit_ctx()?; + if let Some((_, first)) = &self.pf_mrope { + if self.pf_mrope_buf.is_none() { self.pf_mrope_buf = Some(self.gpu.zeros::(8 * self.pf.as_ref().unwrap().chunk)?); } + self.gpu.put(first, self.pf_mrope_buf.as_ref().unwrap(), 0)?; + } // Missed experts are read from the mapped weights in the order the staging copies take them. - let pre = self.cache.is_some().then(Prefetch::start); + let pre = (self.cache.is_some() && !(crate::weights::fits_ram() && crate::weights::preloaded())).then(Prefetch::start); + let anon = pre.as_ref().map(|_| self.m.w.g.anon_spans()).unwrap_or_default(); let owned: (Vec, Vec); let (emb, pe): (&[f32], &[f32]) = match input { Some(v) => v, @@ -336,6 +489,7 @@ impl GpuModel<'_> { g.put(&[self.pos as i32 + self.rope_offset, 0], &self.rope_buf, 0)?; let mut step = self.step_buf.addr(); let mut rope = self.rope_buf.addr(); + if rows.is_some() { step = self.bt.as_ref().unwrap().step.addr(); } let base = pf.slab.addr(); let at = |o: usize| base + 4 * o as u64; let l = &pf.lay; @@ -364,7 +518,67 @@ impl GpuModel<'_> { if let Some(i) = v.iter().position(|a| !a.is_finite()) { tr.push_str(&format!(" (non-finite row {})", i / w)); } Ok(()) }; + // A dense rotated file (`config::Hadamard::dense`): the matrices that read h read its rotation (`hm`, region + // hr), except ssm_beta and ssm_alpha; the attention and ssm_out outputs and the SwiGLU output are rotated + // before their matrices. SAME_X never spans h and hr. + let dense = self.hada.as_ref().zip(c.hadamard.as_ref()).filter(|(_, r)| r.dense); + let hm = if dense.is_some() { at(l.hr) } else { h }; + let rot = |src: u64, n: usize, perm: u64, t: usize| -> anyhow::Result { + let Some((s, r)) = dense else { return Ok(src) }; + g.hadamard(src, 0, s[if n == ne { 0 } else { 1 }].addr(), perm, at(l.hr), n, r.block, t)?; + Ok(at(l.hr)) + }; + let sx = if dense.is_some() { 0 } else { SAME_X }; + let cpu_enabled = c.hadamard.is_none() && (rows.is_some() || self.m.w.g.moe.prefill_cpu); + let fixed_cpu_frac = self.m.w.g.moe.cpu_frac + .filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0)); + let early_enabled = rows.is_none() && g.beside_overlaps(); + let mut early_utilization = 1.0f64; + let mut ahead = None; + let mut pending_timing: Option<(Box, std::time::Duration)> = None; + let model = self.m; + let plan_early = |cache: &ExpertCache, il: usize, t: usize, frac: f64, utilization: f64, predicted: bool| { + if !early_enabled || il >= c.n_layer || t * c.n_expert_used < 4 * c.n_expert { + return Vec::new(); + } + if cache.layer(il).is_none() { return Vec::new(); } + let mut cold: Vec<_> = if predicted { cache.cold_experts(il) } + else { (0..c.n_expert).filter(|&e| cache.slot(il, e) < 0).collect() }; + let window = (STAGE_GROUPS * STAGE) as f64 * utilization; + let gpu_share = cold.len() - (cold.len() as f64 * frac).round() as usize; + cold.truncate(gpu_share.min(window.round() as usize)); + cold.sort_unstable(); + cold + }; + let stage_early = |cache: &ExpertCache, il, experts: &[usize]| -> anyhow::Result<()> { + let Some(lx) = cache.layer(il).filter(|_| !experts.is_empty()) else { return Ok(()); }; + g.copy_beside(&mut || { + for (j, grp) in experts.chunks(STAGE).enumerate() { + for (name, mat) in MATS.iter().zip(&lx.mats) { + let w = model.w.layer(il, name)?; + let mut i = 0; + for run in grp.chunk_by(|a, b| *b == a + 1) { + let slice = &w.data[run[0] * mat.bytes..(run[0] + run.len()) * mat.bytes]; + g.htod(slice, &pf.staging, j * pf.staging.len() / STAGE_GROUPS + STAGE * mat.off + i * mat.bytes)?; + crate::weights::cold(slice); + i += run.len(); + } + } + } + Ok(()) + }) + }; for (il, ly) in self.layers.iter().enumerate().map(|(i, ly)| (self.first + i, ly)).chain(mtp.map(|mh| (c.n_layer, &mh.layer))) { + let cpu_frac = if cpu_enabled { fixed_cpu_frac.unwrap_or(self.cpu_frac) } else { 0.0 }; + let early = if let Some(experts) = ahead.take() { + experts + } else if let Some(cache) = self.cache.as_ref().filter(|_| matches!(ly.ffn, Ffn::Moe { .. })) { + let experts = plan_early(cache, il, t, cpu_frac, early_utilization, false); + stage_early(cache, il, &experts)?; + experts + } else { + Vec::new() + }; if il < c.n_layer { if let (Some(pff), Some(eg)) = (&pf.feat, self.mtp.as_ref().and_then(|mh| mh.eagle.as_ref()).filter(|_| fill)) { if let Some(idx) = eg.cfg.extract_layers.iter().position(|&el| el == il) { @@ -393,6 +607,8 @@ impl GpuModel<'_> { rope += 8; } // Hyper-connections / mHC: mixer and FFN outputs go to "mix" and "mo", then into the streams. + // A batched step (`rows`) may take the decode GEMM; one request keeps the prefill GEMM's bits. + let bf = if rows.is_some() { BATCHED } else { 0 }; let (mx, mact) = if c.hc_n > 0 || ly.mhc.is_some() { (at(l.mix), 0) } else { (x, 2) }; if let Some(pl) = &ly.ple { self.ple(pl, x, step, t, &ha)?; } if let Some((mk, mhc_a, _)) = &ly.mhc { @@ -413,51 +629,101 @@ impl GpuModel<'_> { } else { match (&ly.attn_norm, &ly.hc) { (Some(an), _) => g.rms_norm(x, ne, an.ptr, h, ne, ne, t, eps)?, - (None, Some(hr)) => self.hc_read(&hr[0], x, t, &ha)?, + (None, Some(hr)) => self.hc_read(&hr[0], x, t, &ha, None)?, _ => unreachable!(), } } + if dense.is_some() { rot(h, ne, 0, t)?; } match &ly.mixer { Mixer::Delta { qkv, gate, beta, alpha, dt_bias, a, conv_w, norm, out, conv, s, .. } => { let (eb, eg) = (at(l.e), at(l.e + n * nv)); - g.gemm_dense(qkv, t, h, ne, at(l.a), channels, 0)?; + // Rows mode: this layer's part of `Batch::kvt` holds each row's conv and scan state (`batch_rows`). + // Rows of one slot scan in order, so a launch takes a run of rows with distinct slots. + let tab = |r0: usize| self.bt.as_ref().map_or(0, |bt| bt.kvt.addr() + (8 * ((il - self.first) * bt.rows + r0) * 2) as u64); + let runs = |sl: &[usize]| { + let mut v = vec![]; + let mut r0 = 0; + for r in 1..=sl.len() { + if r == sl.len() || sl[r0..r].contains(&sl[r]) { v.push((r0, r)); r0 = r; } + } + v + }; + g.gemm_dense(qkv, t, hm, ne, at(l.a), channels, bf)?; // The qkv GEMM above already quantized `h`; when it did not (IQ2_XS, or a shape the int8 GEMM // skips), prepare it now so beta, alpha and the gate can all reuse one copy. - g.prequant_gemm_x(gate, t, h, ne)?; - g.conv_seq(at(l.a), conv[self.cur].addr(), conv_w.ptr, at(l.c), channels, c.ssm_conv, t, 0, 0)?; + if dense.is_none() { g.prequant_gemm_x(gate, t, h, ne)?; } + match rows { + // A row a slot: each its own conv state, in row order. + Some((sl, _)) => for (r0, r1) in runs(sl) { + let (st, o) = (sl[r0..r1].iter().map(|&s| conv[s].addr()).collect::>(), (4 * r0 * channels) as u64); + g.conv_silu_rows(at(l.a) + o, tab(r0), &st, conv_w.ptr, at(l.c) + o, channels, c.ssm_conv, eps)?; + }, + None => g.conv_seq(at(l.a), conv[self.cur].addr(), conv_w.ptr, at(l.c), channels, c.ssm_conv, t, 0, 0)?, + } // The beta and alpha GEMMs (16 blocks each) run beside the norm: batch launches alternate streams. g.batch(&mut || { - g.gemm_dense(beta, t, h, ne, eb, nv, SAME_X)?; + g.gemm_dense(beta, t, h, ne, eb, nv, sx | bf)?; g.l2_norm(at(l.c), dk, 2 * nk, channels, t * 2 * nk, eps)?; - g.gemm_dense(alpha, t, h, ne, eg, nv, SAME_X) + g.gemm_dense(alpha, t, h, ne, eg, nv, SAME_X | bf) })?; g.ssm_gates(eb, eg, dt_bias.ptr, a.ptr, t * nv, nv)?; probe(&mut tr, "qkv", &pf.slab, at(l.a), channels, t)?; probe(&mut tr, "conv", &pf.slab, at(l.c), channels, t)?; probe(&mut tr, "beta", &pf.slab, eb, nv, t)?; probe(&mut tr, "alpha", &pf.slab, eg, nv, t)?; - // The z GEMM runs beside the scan, on the SMs its last wave of blocks leaves idle. - g.batch(&mut || { - g.deltanet(at(l.c), s[self.cur].addr(), eb, eg, 0, 0, at(l.d), nk, nv, c.k_interleave, dk, dv, 1.0 / (dk as f32).sqrt(), t, channels, 0, 0)?; - g.gemm_dense(gate, t, h, ne, at(l.b), c.ssm_d_inner, SAME_X) - })?; + let scan = || -> anyhow::Result<()> { + let scale = 1.0 / (dk as f32).sqrt(); + match rows { + Some((sl, _)) => for (r0, r1) in runs(sl) { + let st: Vec = sl[r0..r1].iter().map(|&q| s[q].addr()).collect(); + g.deltanet_rows(at(l.c) + (4 * r0 * channels) as u64, tab(r0), &st, eb + (4 * r0 * nv) as u64, eg + (4 * r0 * nv) as u64, + at(l.d) + (4 * r0 * c.ssm_d_inner) as u64, nk, nv, c.k_interleave, dk, dv, scale, channels)?; + }, + None => g.deltanet(at(l.c), s[self.cur].addr(), eb, eg, 0, 0, at(l.d), nk, nv, c.k_interleave, dk, dv, scale, t, channels, 0, 0)?, + } + Ok(()) + }; + // The z GEMM runs beside the scan, on the SMs its last wave of blocks leaves idle. Runs of rows of + // one slot read each other's state, so those go in order, outside a batch. + if rows.is_some_and(|(sl, _)| runs(sl).len() > 1) { + scan()?; + g.gemm_dense(gate, t, hm, ne, at(l.b), c.ssm_d_inner, sx | bf)?; + } else { + g.batch(&mut || { scan()?; g.gemm_dense(gate, t, hm, ne, at(l.b), c.ssm_d_inner, sx | bf) })?; + } probe(&mut tr, "deltanet", &pf.slab, at(l.d), c.ssm_d_inner, t)?; probe(&mut tr, "state", &s[self.cur], s[self.cur].addr(), s[self.cur].len() / 4, 1)?; probe(&mut tr, "z", &pf.slab, at(l.b), c.ssm_d_inner, t)?; if ly.hc.is_some() { g.norm_gate_sig(at(l.d), norm.ptr, at(l.b), dv, t * nv, eps, 0)?; } else { g.norm_gate(at(l.d), norm.ptr, at(l.b), dv, t * nv, eps)?; } - g.gemm_dense(out, t, at(l.d), c.ssm_d_inner, mx, ne, mact)?; + let perm = self.bufs.get("hperm").map_or(0, |b| b.addr()); + g.gemm_dense(out, t, rot(at(l.d), c.ssm_d_inner, perm, t)?, c.ssm_d_inner, mx, ne, mact | bf)?; + } + Mixer::Attn { q, k, v, qn, kn, o, sink, .. } if let Some((_, splits)) = rows => { + // As `batch_rows` on a dense model: each row reads and extends its own slot's KV. + let (kraw, kk, vv) = (at(l.c), at(l.c + n * kv), at(l.c + 2 * n * kv)); + let qs = if c.q_gate { 2 * hd } else { hd }; + let bt = self.bt.as_ref().unwrap(); + let kvt = bt.kvt.addr() + (8 * (il - self.first) * 2 * bt.rows) as u64; + g.gemm_dense(q, t, hm, ne, at(l.a), nh * qs, BATCHED)?; + g.gemm_dense(k, t, hm, ne, kraw, kv, SAME_X | BATCHED)?; + g.gemm_dense(v, t, hm, ne, vv, kv, SAME_X | BATCHED)?; + let win = c.swa.get(il).copied().unwrap_or(false).then_some(c.n_swa).unwrap_or(0); + g.rms_norm_rope_qk_rows(at(l.a), qs, qn.ptr, at(l.b), nh, kraw, kn.ptr, kk, nkv, hd, eps, c.n_rot, step, c.rope_base, vv, kvt, t)?; + g.attn_rows(at(l.b), if c.q_gate { at(l.a) } else { 0 }, at(l.d), bt.attp.addr(), step, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), t, + sink.as_ref().map_or(0, |s| s.ptr), win, kvt, splits)?; + g.gemm_dense(o, t, rot(at(l.d), nh * hd, 0, t)?, nh * hd, mx, ne, mact | BATCHED)?; } Mixer::Attn { q, k, v, qn, kn, o, kc, vc, qsa, sink } => { let (kraw, kk, vv) = (at(l.c), at(l.c + n * kv), at(l.c + 2 * n * kv)); let qs = if c.q_gate { 2 * hd } else { hd }; let use_rope = c.rope_layer.get(il).copied().unwrap_or(true); - g.gemm_dense(q, t, h, ne, at(l.a), nh * qs, 0)?; + g.gemm_dense(q, t, hm, ne, at(l.a), nh * qs, 0)?; g.rms_norm(at(l.a), qs, qn.ptr, at(l.b), hd, hd, t * nh, eps)?; - if use_rope { g.rope_neox(at(l.b), hd, t * nh, nh, c.n_rot, rope, c.rope_base)?; } - g.gemm_dense(k, t, h, ne, kraw, kv, SAME_X)?; - g.gemm_dense(v, t, h, ne, vv, kv, SAME_X)?; + if use_rope { self.rope_chunk(at(l.b), hd, t, nh, rope)?; } + g.gemm_dense(k, t, hm, ne, kraw, kv, SAME_X)?; + g.gemm_dense(v, t, hm, ne, vv, kv, SAME_X)?; g.rms_norm(kraw, hd, kn.ptr, kk, hd, hd, t * nkv, eps)?; - if use_rope { g.rope_neox(kk, hd, t * nkv, nkv, c.n_rot, rope, c.rope_base)?; } + if use_rope { self.rope_chunk(kk, hd, t, nkv, rope)?; } g.kv_store(kk, vv, kc[self.cur].addr(), vc[self.cur].addr(), kv, t, step, hd)?; // QSA: region c (free after kv_store) holds the raw indexer keys, raw queries and normed queries. let (qm, mw) = match (qsa, &self.qsa) { @@ -466,13 +732,13 @@ impl GpuModel<'_> { let (dq, nq) = (super::QSA_D, super::QSA_H * super::QSA_D); g.gemm_dense(&a.kp, t, h, ne, ik, dq, 0)?; g.gemm_dense(&a.qp, t, h, ne, iq, nq, SAME_X)?; - g.qsa_pool(ik, a.ring, a.pool.addr(), a.kn.ptr, step, t, c.n_rot, c.rope_base, eps)?; + g.qsa_pool(ik, b.ring[self.cur].addr() + a.ring, a.pool[self.cur].addr(), a.kn.ptr, step, t, c.n_rot, c.rope_base, eps)?; // Rows with at most `top` complete blocks attend densely: no mask while all of them do. if self.pos + t >= super::QSA_POOL * (b.top + 1) { g.rms_norm(iq, dq, a.qn.ptr, iqn, dq, dq, t * super::QSA_H, eps)?; g.rope_neox(iqn, dq, t * super::QSA_H, super::QSA_H, c.n_rot, rope, c.rope_base)?; for r0 in (0..t).step_by(super::QSA_ROWS) { - g.qsa_select(iqn + (4 * r0 * nq) as u64, a.pool.addr(), b.score.addr(), 0, b.mask.addr() + (4 * r0 * b.mw) as u64, + g.qsa_select(iqn + (4 * r0 * nq) as u64, a.pool[self.cur].addr(), b.score.addr(), 0, b.mask.addr() + (4 * r0 * b.mw) as u64, step, r0, super::QSA_ROWS.min(t - r0), b.nbs, b.top, 0, b.mw)?; } (b.mask.addr(), b.mw) @@ -482,12 +748,21 @@ impl GpuModel<'_> { }; let sink_addr = sink.as_ref().map_or(0, |s| s.ptr); let win = c.swa.get(il).copied().unwrap_or(false).then_some(c.n_swa).unwrap_or(0); - g.attn_prefill_m(at(l.b), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win)?; + let (kca, vca) = match &self.kv_stage { + Some((sk, sv)) if crate::host_attn::on_host(il) => { + let bytes = (g.kv_words((self.pos + t) * kv) * 2).min(sk.len()); + g.dtod(&kc[self.cur], 0, sk, 0, bytes)?; + g.dtod(&vc[self.cur], 0, sv, 0, bytes)?; + (sk.addr(), sv.addr()) + } + _ => (kc[self.cur].addr(), vc[self.cur].addr()), + }; + g.attn_prefill_m(at(l.b), kca, vca, if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win)?; probe(&mut tr, "q", &pf.slab, at(l.a), nh * qs, t)?; probe(&mut tr, "k", &pf.slab, kk, kv, t)?; probe(&mut tr, "v", &pf.slab, vv, kv, t)?; probe(&mut tr, "attn", &pf.slab, at(l.d), nh * hd, t)?; - g.gemm_dense(o, t, at(l.d), nh * hd, mx, ne, mact)?; + g.gemm_dense(o, t, rot(at(l.d), nh * hd, 0, t)?, nh * hd, mx, ne, mact)?; } } probe(&mut tr, "| mixer", &pf.slab, x, d, t)?; @@ -509,16 +784,18 @@ impl GpuModel<'_> { (Some(pn), _) => g.rms_norm(x, ne, pn.ptr, h, ne, ne, t, eps)?, (None, Some(hr)) => { g.hc_write(x, mx, at(l.inj), ne, c.hc_n, t, false)?; - self.hc_read(&hr[1], x, t, &ha)?; + self.hc_read(&hr[1], x, t, &ha, None)?; } _ => unreachable!(), } } + if dense.is_some() { rot(h, ne, 0, t)?; } match &ly.ffn { Ffn::Dense { gate, up, down } => { - g.gemm_dense(gate, t, h, ne, at(l.ge), c.n_ff, 0)?; - g.gemm_dense(up, t, h, ne, at(l.ge), c.n_ff, 1 | SAME_X)?; + g.gemm_dense(gate, t, hm, ne, at(l.ge), c.n_ff, bf)?; + g.gemm_dense(up, t, hm, ne, at(l.ge), c.n_ff, 1 | SAME_X | bf)?; probe(&mut tr, "gate_up", &pf.slab, at(l.ge), c.n_ff, t)?; + if let Some((s, r)) = dense { g.hadamard(at(l.ge), 0, s[1].addr(), 0, at(l.ge), c.n_ff, r.block, t)?; } if let Some((mk, _, mhc_f)) = &ly.mhc { g.gemm_dense(down, t, at(l.ge), c.n_ff, at(l.mo), ne, 0)?; let leave_bit = if mk & 2 != 0 { 0x200 } else { 0 }; @@ -528,12 +805,15 @@ impl GpuModel<'_> { g.dtod(&pf.slab, 4 * l.mo, &pf.slab, 0, 4 * t * ne)?; } } else { - g.gemm_dense(down, t, at(l.ge), c.n_ff, x, ne, 2)?; + g.gemm_dense(down, t, at(l.ge), c.n_ff, x, ne, 2 | bf)?; } } Ffn::Moe { router, shared } => { let k = c.n_expert_used; let ids_d = pf.ints.addr(); + let read = if cpu_enabled && fixed_cpu_frac != Some(0.0) { + g.begin_prefill_read(&pf.slab, 4 * l.h, t * ne)? + } else { None }; // The 1-row shared gate_inp GEMM runs beside the router GEMM (both float: one launch each). g.batch(&mut || { g.gemm_dense(router, t, h, ne, at(l.rl), c.n_expert, 0)?; @@ -543,8 +823,8 @@ impl GpuModel<'_> { g.router_topk(at(l.rl), c.n_expert, k, c.expert_weights_scale, ids_d, at(l.wts), t, c.router_sigmoid)?; let (sh, sg) = match shared { Some(s) => { - g.gemm_dense(&s.gate, t, h, ne, at(l.shg), c.n_ff_shexp, SAME_X)?; - g.gemm_dense(&s.up, t, h, ne, at(l.shg), c.n_ff_shexp, 1 | SAME_X)?; + g.gemm_dense(&s.gate, t, h, ne, at(l.shg), c.n_ff_shexp, SAME_X | bf)?; + g.gemm_dense(&s.up, t, h, ne, at(l.shg), c.n_ff_shexp, 1 | SAME_X | bf)?; (at(l.shy), if s.gate_inp.is_some() { at(l.sg) } else { 0 }) } None => (0, 0), @@ -558,41 +838,117 @@ impl GpuModel<'_> { anyhow::bail!("prefill: router gave expert id {bad} at layer {il}, chunk of {t} tokens from position {}; \ lower --chunk (for example --chunk 1024) or --ctx, and try STRATA_NAN_TRACE=1 for a non-finite hidden state", self.pos); } + if let Some((timer, cpu_time)) = pending_timing.take() { + self.cpu_frac = adjust_cpu_frac(self.cpu_frac, cpu_time, timer.elapsed()?); + } + let cpu_frac = if cpu_enabled { fixed_cpu_frac.unwrap_or(self.cpu_frac) } else { 0.0 }; let cache = self.cache.as_mut().unwrap(); cache.record_prompt(il, &ids); // Sort (token, j) pairs by expert: slot s holds token xrow[s]; inv maps t * k + j to its slot. let mut off = vec![0usize; c.n_expert + 1]; for &e in &ids { off[e as usize + 1] += 1; } for e in 0..c.n_expert { off[e + 1] += off[e]; } - let (mut fill, mut xrow, mut inv) = (off.clone(), vec![0i32; t * k], vec![0i32; t * k]); + let lx = cache.layer(il).unwrap(); + let (pool, stride) = cache.base(lx); + let used = |e: &usize| off[e + 1] > off[*e]; + let mut missed: Vec = (0..c.n_expert).filter(used).filter(|&e| cache.slot(il, e) < 0).collect(); + let probe_cpu = cpu_enabled && fixed_cpu_frac.is_none() && self.cpu_unsampled >= 7; + let cpu_experts = split_cpu_experts(&mut missed, &off, &early, cpu_frac, fixed_cpu_frac.is_some(), probe_cpu); + if cpu_enabled && fixed_cpu_frac.is_none() && (!missed.is_empty() || !cpu_experts.is_empty()) { + self.cpu_unsampled = if cpu_experts.is_empty() { self.cpu_unsampled + 1 } else { 0 }; + } + let row_ranges = pack_expert_rows(&off, &cpu_experts); + let mut fill: Vec<_> = row_ranges.iter().map(|r| r.start).collect(); + let (mut xrow, mut inv) = (vec![0i32; t * k], vec![0i32; t * k]); for (i, &e) in ids.iter().enumerate() { - let s = &mut fill[e as usize]; - xrow[*s] = (i / k) as i32; - inv[i] = *s as i32; - *s += 1; + let slot = &mut fill[e as usize]; + xrow[*slot] = (i / k) as i32; + inv[i] = *slot as i32; + *slot += 1; } g.put(&xrow, &pf.ints, n * k)?; g.put(&inv, &pf.ints, 2 * n * k)?; - let lx = cache.layer(il).unwrap(); - let (pool, stride) = cache.base(lx); - let used = |e: &usize| off[e + 1] > off[*e]; - let missed: Vec = (0..c.n_expert).filter(used).filter(|&e| cache.slot(il, e) < 0).collect(); + let cpu = if cpu_experts.is_empty() { None } else { + let mut pairs: Vec<_> = cpu_experts.iter().flat_map(|&e| { + let xrow = &xrow; + row_ranges[e].clone().map(move |s| (xrow[s] as usize, e, 0.0)) + }).collect(); + let mut remap = vec![usize::MAX; t]; + for &(row, _, _) in &pairs { remap[row] = 0; } + let needed: Vec<_> = (0..t).filter(|&row| remap[row] == 0).collect(); + let runs = needed.chunk_by(|a, b| *b == a + 1); + let hs: Vec> = if let Some(read) = &read { + let all = read.rows()?; + for (i, &row) in needed.iter().enumerate() { remap[row] = i; } + for (row, _, _) in &mut pairs { *row = remap[*row]; } + needed.iter().map(|&row| all[row * ne..(row + 1) * ne].to_vec()).collect() + } else { + // Few rows in few runs: gather them into `ye` (not written yet in this layer) and read only those. + let hv = if needed.len() * 4 <= t * 3 && runs.clone().count() <= 16 { + let mut dst = 0; + for run in runs { + g.dtod(&pf.slab, 4 * (l.h + run[0] * ne), &pf.slab, 4 * (l.ye + dst * ne), 4 * run.len() * ne)?; + dst += run.len(); + } + for (i, &row) in needed.iter().enumerate() { remap[row] = i; } + for (row, _, _) in &mut pairs { *row = remap[*row]; } + g.get::(&pf.slab, l.ye, needed.len() * ne)? + } else { + g.get::(&pf.slab, l.h, t * ne)? + }; + hv.chunks_exact(ne).map(<[f32]>::to_vec).collect() + }; + Some((pairs, hs)) + }; + drop(read); + let mut early_runs = Vec::new(); + if !early.is_empty() { + early_runs = early.chunks(STAGE).map(|grp| grp.iter().enumerate() + .filter(|&(_, e)| missed.binary_search(e).is_ok()) + .map(|(i, &e)| (e, i)).collect::>()).collect(); + let used = early_runs.iter().map(Vec::len).sum::(); + early_utilization = (0.5 * early_utilization + 0.5 * used as f64 / early.len() as f64).max(0.25); + missed.retain(|e| early.binary_search(e).is_err()); + early_runs.truncate(early_runs.iter().rposition(|grp| !grp.is_empty()).map_or(0, |j| j + 1)); + } if let Some(pre) = &pre { let w: Vec<_> = MATS.iter().map(|name| self.m.w.layer(il, name)).collect::>()?; - pre.send(missed.chunks(STAGE).flat_map(|grp| w.iter().zip(&lx.mats).flat_map(move |(w, mat)| grp.chunk_by(|a, b| *b == a + 1) - .map(move |run| (w.data.as_ptr() as usize + run[0] * mat.bytes, run.len() * mat.bytes)))).collect()); + let mut rs: Vec<(usize, usize)> = missed.chunks(STAGE).flat_map(|grp| w.iter().zip(&lx.mats).flat_map(move |(w, mat)| grp.chunk_by(|a, b| *b == a + 1) + .map(move |run| (w.data.as_ptr() as usize + run[0] * mat.bytes, run.len() * mat.bytes)))).collect(); + // Overlap NVMe read-ahead for the next MoE layer's hottest cold experts behind this layer's GEMMs. + if let Some(next_il) = (il + 1..c.n_layer).find(|&j| cache.layer(j).is_some()) { + rs.extend(cache.cold_ranges_for_next(self.m, next_il, 16)); + } + rs.retain(|&(p, n)| !anon.iter().any(|&(a, len)| p >= a && p + n <= a + len)); + if !rs.is_empty() { pre.send(rs); } } - // Staged groups of at most STAGE missed experts, group j in staging third j % 3. Staging holds + // Staged groups of at most STAGE missed experts, group j in staging section j % STAGE_GROUPS. Staging holds // each matrix in its own section (all gates, then ups, then downs), so experts with consecutive // ids are contiguous there as in the weights and copy in one call. let sp = pf.staging.addr(); - let half = |j: usize| j % 3 * pf.staging.len() / 3; - let staged: Vec> = missed.chunks(STAGE).enumerate() - .map(|(j, grp)| grp.iter().enumerate().map(|(i, &e)| (e, lx.mats.each_ref().map(|m| sp + (half(j) + STAGE * m.off + i * m.bytes) as u64))).collect()) + let half = |j: usize| j % STAGE_GROUPS * pf.staging.len() / STAGE_GROUPS; // section j's offset + let ne0 = early_runs.len(); + let npin: Option> = if *ZERO_COPY { + MATS.iter().map(|name| self.m.w.layer(il, name).ok().and_then(|w| g.host_ptr(w.data))).collect() + } else { None }; + let slot_at = |j: usize, i: usize| lx.mats.each_ref().map(|m| sp + (half(j) + STAGE * m.off + i * m.bytes) as u64); + // A run's expert addresses: its weights in the registered file (STRATA_ZERO_COPY_EXPERTS) or its + // staging slot. Only experts missed at this layer read in place; the early (pre-staged) ones stay + // in their slots. + let run_at = |j: usize, run: &[(usize, usize)]| -> Vec<(usize, [u64; 3])> { + run.iter().map(|&(e, i)| (e, match &npin { + Some(b) if j >= ne0 => [0, 1, 2].map(|mi| b[mi] + (e * lx.mats[mi].bytes) as u64), + _ => slot_at(j, i), + })).collect() + }; + let staged: Vec> = early_runs.iter().enumerate() + .map(|(j, run)| run_at(j, run)) + .chain(missed.chunks(STAGE).enumerate() + .map(|(jj, grp)| run_at(ne0 + jj, &grp.iter().enumerate().map(|(i, &e)| (e, i)).collect::>()))) .collect(); // The resident experts split into one chunk per staged group, of about equal positions, so the // copies run beside them too: step s runs group s - 2 and chunk s beside the copy of group s - // (into the third group s - 3 used, done in step s - 1). A step waits only for the copies of the + // (into the section group s - STAGE_GROUPS used, done by step s - 1). A step waits only for the copies of the // step two before it (`beside`), so each copy has two steps of GEMMs to hide behind. // Without overlap (Vulkan without a transfer queue) one chunk: more, smaller GEMMs only cost there. let ns = if g.beside_overlaps() { staged.len().max(1) } else { 1 }; @@ -619,8 +975,8 @@ impl GpuModel<'_> { let push = |tiles: &mut Vec, grp: &[(usize, [u64; 3])], mi: usize, base: usize| { let start = tiles.len() / 2; for &(e, w) in grp { - for m0 in (off[e]..off[e + 1]).step_by(GEMM_BM) { - tiles.extend([w[mi], (m0 - base) as u64 | (GEMM_BM.min(off[e + 1] - m0) as u64) << 32]); + for m0 in row_ranges[e].clone().step_by(GEMM_BM) { + tiles.extend([w[mi], (m0 - base) as u64 | (GEMM_BM.min(row_ranges[e].end - m0) as u64) << 32]); } } (start, tiles.len() / 2 - start) @@ -633,7 +989,7 @@ impl GpuModel<'_> { let gu = [0, 1].map(|mi| { let s = tiles.len() / 2; for gi in gs.clone() { push(&mut tiles, &groups[gi], mi, 0); } (s, tiles.len() / 2 - s) }); let downs: Vec<_> = gs.clone().filter(|&gi| !groups[gi].is_empty()).map(|gi| { let grp = &groups[gi]; - let (lo, hi) = (off[grp[0].0], off[grp[grp.len() - 1].0 + 1]); + let (lo, hi) = (row_ranges[grp[0].0].start, row_ranges[grp[grp.len() - 1].0].end); (push(&mut tiles, grp, 2, lo), lo, hi) }).collect(); spans.push((gu, downs)); @@ -645,18 +1001,26 @@ impl GpuModel<'_> { let [mg, mu, md] = lx.mats; // Gyro files: the routed experts read the rotated h and the rotated SwiGLU output (`config::Hadamard`). let rot = self.hada.as_ref().zip(c.hadamard.as_ref()); - let (hx, same) = match rot { - Some((s, r)) => { g.hadamard(h, 0, s[0].addr(), at(l.hr), ne, r.block, t)?; (at(l.hr), 0) } - None => (h, SAME_X), + let hx = match rot { + Some((s, r)) => { g.hadamard(h, 0, s[0].addr(), 0, at(l.hr), ne, r.block, t)?; at(l.hr) } + None => h, }; + // Groups the layer start staged already (`early`): their copies are not repeated. + let pre_staged = |j: usize| j < ne0; + // The routed GEMMs below read the early groups: wait for their copies (long done behind the mixer). + if !early.is_empty() { g.copy_join()?; } let copy = |j: usize| -> anyhow::Result<()> { + if npin.is_some() { return Ok(()); } let grp = &staged[j]; for (name, mat) in MATS.iter().zip(&lx.mats) { let w = self.m.w.layer(il, name)?; let mut i = 0; for run in grp.chunk_by(|a, b| b.0 == a.0 + 1) { let e = run[0].0; - g.htod(&w.data[e * mat.bytes..(e + run.len()) * mat.bytes], &pf.staging, half(j) + STAGE * mat.off + i * mat.bytes)?; + let slice = &w.data[e * mat.bytes..(e + run.len()) * mat.bytes]; + g.htod(slice, &pf.staging, half(j) + STAGE * mat.off + i * mat.bytes)?; + // Release cold streamed prefill experts from OS page cache when the model exceeds RAM. + crate::weights::cold(slice); i += run.len(); } } @@ -664,24 +1028,55 @@ impl GpuModel<'_> { }; // `beside` starts a step's copies after the GEMMs before it. They queue last, so the GEMMs need not // wait for the host to stage them. - for ((_, cp), (gu, downs)) in steps.iter().zip(&spans) { - g.beside(&mut || { - if gu[0].1 > 0 { - g.gemm(mg.ty, mg.rows, mg.cols, tp(gu[0].0), gu[0].1, hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, same)?; - g.gemm(mu.ty, mu.rows, mu.cols, tp(gu[1].0), gu[1].1, hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, 1 | SAME_X)?; - } - for &((s0, n0), lo, hi) in downs { - let ge = at(l.ge) + (4 * lo * c.n_ff_exp) as u64; - if let Some((s, r)) = rot { g.hadamard(ge, 0, s[1].addr(), ge, c.n_ff_exp, r.block, hi - lo)?; } - g.gemm(md.ty, md.rows, md.cols, tp(s0), n0, at(l.ge) + (4 * lo * c.n_ff_exp) as u64, c.n_ff_exp, hi - lo, 0, at(l.ye) + (4 * lo * ne) as u64, ne, 0)?; - } - if let Some(j) = *cp { copy(j)?; } - Ok(()) - })?; + // The CPU experts run on their own thread, beside the host side of the staging copies below. + let m = self.m; + let balance = cpu.is_some() && fixed_cpu_frac.is_none(); + let mut timer = if balance { g.device_timer()? } else { None }; + let start = std::time::Instant::now(); + let (cpu_out, gpu_time) = std::thread::scope(|sc| -> anyhow::Result<_> { + let job = cpu.as_ref().map(|(pairs, hs)| sc.spawn(move || { + let o = crate::cpu_moe::expert_rows(m, il, hs, pairs); + (o, start.elapsed()) + })); + let mut gate_flags = MOE_GATE_X; + for ((_, cp), (gu, downs)) in steps.iter().zip(&spans) { + g.beside(&mut || { + if gu[0].1 > 0 { + g.gemm(mg.ty, mg.rows, mg.cols, tp(gu[0].0), gu[0].1, hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, gate_flags)?; + gate_flags |= SAME_X; + g.gemm(mu.ty, mu.rows, mu.cols, tp(gu[1].0), gu[1].1, hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, 1 | gate_flags)?; + } + for &((s0, n0), lo, hi) in downs { + let ge = at(l.ge) + (4 * lo * c.n_ff_exp) as u64; + if let Some((s, r)) = rot { g.hadamard(ge, 0, s[1].addr(), 0, ge, c.n_ff_exp, r.block, hi - lo)?; } + g.gemm(md.ty, md.rows, md.cols, tp(s0), n0, at(l.ge) + (4 * lo * c.n_ff_exp) as u64, c.n_ff_exp, hi - lo, 0, at(l.ye) + (4 * lo * ne) as u64, ne, 0)?; + } + if let Some(j) = *cp { if !pre_staged(j) { copy(j)?; } } + Ok(()) + })?; + } + g.beside_join()?; + let gpu_time = if let Some(timer) = timer.as_mut() { + timer.stop()?; + None + } else if balance { + g.sync()?; + Some(start.elapsed()) + } else { None }; + Ok((job.map(|j| j.join().expect("CPU expert thread")), gpu_time)) + })?; + if let Some((o, cpu_time)) = cpu_out { + let dst = l.ye + (t * k * ne - o.len()); + g.copy_independent(&mut || g.put(&o, &pf.slab, dst))?; + g.copy_join()?; + if let Some(timer) = timer { + pending_timing = Some((timer, cpu_time)); + } else if let Some(gpu_time) = gpu_time { + self.cpu_frac = adjust_cpu_frac(self.cpu_frac, cpu_time, gpu_time); + } } - g.beside_join()?; // The shared down runs last, so the routed gate and up above reuse the int8 h of the shared up. - if let Some(s) = shared { g.gemm_dense(&s.down, t, at(l.shg), c.n_ff_shexp, at(l.shy), ne, 0)?; } + if let Some(s) = shared { g.gemm_dense(&s.down, t, at(l.shg), c.n_ff_shexp, at(l.shy), ne, bf)?; } // Expert rows are slots (token, j) sorted by expert, not tokens. probe(&mut tr, "experts_gate_up", &pf.slab, at(l.ge), c.n_ff_exp, t * k)?; probe(&mut tr, "experts_down", &pf.slab, at(l.ye), ne, t * k)?; @@ -692,6 +1087,14 @@ impl GpuModel<'_> { } // "mo" is zero: hc_write clears it after use. let fx = if ly.hc.is_some() { at(l.mo) } else { x }; + if early_enabled && c.hadamard.is_none() + && self.layers.get(il + 1 - self.first).is_some_and(|next| matches!(next.ffn, Ffn::Moe { .. })) + && MATS.iter().all(|name| model.w.layer(il + 1, name).is_ok_and(|w| g.host_is_pinned(w.data))) { + let frac = if cpu_enabled { fixed_cpu_frac.unwrap_or(self.cpu_frac) } else { 0.0 }; + let experts = plan_early(cache, il + 1, t, frac, early_utilization, true); + stage_early(cache, il + 1, &experts)?; + ahead = Some(experts); + } g.moe_combine_seq(fx, at(l.ye), at(l.wts), pf.ints.addr() + 4 * (2 * n * k) as u64, k, sh, sg, ne, t)?; if ly.hc.is_some() { g.hc_write(x, fx, at(l.inj), ne, c.hc_n, t, true)?; } } @@ -702,14 +1105,39 @@ impl GpuModel<'_> { if let (Some(dff), Some(df)) = (&pf.dflash_feat, self.dflash.as_ref()) { if let Some(idx) = df.cfg.target_layer_ids.iter().position(|&tl| tl == il) { let n_ids = df.cfg.target_layer_ids.len(); - for r in 0..t { - g.dtod(&pf.slab, 4 * r * ne, dff, 4 * (r * n_ids + idx) * ne, 4 * ne)?; + // hc targets (qwen4exp): collapse the hc streams to their plain mean first + // (mirrors llama.cpp's hc_stream_mean); see the step-side note. hc_mix's gate + // buffer holds TMAX rows, so tile over TMAX-position blocks. + if c.hc_n > 0 { + let dfm = pf.dflash_mean.as_ref().expect("dflash_mean with hc"); + let mut done = 0; + while done < t { + let rows = (t - done).min(TMAX); + g.hc_mix(pf.slab.addr() + 4 * (done * c.hc_n * ne) as u64, df.dfg.addr(), dfm.addr() + 4 * (done * ne) as u64, ne, c.hc_n, rows)?; + for r in 0..rows { + g.dtod(dfm, 4 * (done + r) * ne, dff, 4 * ((done + r) * n_ids + idx) * ne, 4 * ne)?; + } + done += rows; + } + } else { + for r in 0..t { + g.dtod(&pf.slab, 4 * r * ne, dff, 4 * (r * n_ids + idx) * ne, 4 * ne)?; + } } } } } g.kick()?; } + if let Some((timer, cpu_time)) = pending_timing { + self.cpu_frac = adjust_cpu_frac(self.cpu_frac, cpu_time, timer.elapsed()?); + } + if rows.is_some() { + // A --device split: the next part takes the rows' hidden states as its input. + let Some(nx) = self.next.as_deref_mut() else { return Ok(()) }; + let xs = self.gpu.get::(&self.pf.as_ref().unwrap().slab, 0, t * d)?; + return nx.prefill_chunk(toks, Some((&xs, pe)), rows); + } if fill && is_eagle { g.dtod(&pf.slab, 4 * (t - 1) * d, &self.x, 0, 4 * d)?; let (lh, slab_h, old_cur_g) = { @@ -766,8 +1194,11 @@ impl GpuModel<'_> { } self.pos += toks.len(); let Some(nx) = self.next.as_deref_mut() else { return Ok(()) }; + (nx.rope_offset, nx.pf_mrope) = (self.rope_offset, self.pf_mrope.clone()); let xs = self.gpu.get::(&self.pf.as_ref().unwrap().slab, 0, toks.len() * d)?; - nx.prefill_chunk(toks, Some((&xs, pe))) + let r = nx.prefill_chunk(toks, Some((&xs, pe)), None); + nx.pf_mrope = None; + r } /// `step_rows` for up to `batch_cap` distinct slots, on the GEMM kernels of prefill: one decode step a row, each @@ -780,16 +1211,48 @@ impl GpuModel<'_> { /// every row; else only for the rows that ask for logits (a prompt's last row), in row order. fn batch_rows(&mut self, rows: &[(usize, u32, bool)], all: bool) -> anyhow::Result)>> { let t = rows.len(); + // ponytail: the attention-only branch below has no dense rotation; no such file exists yet (Bonsai has GDN). + anyhow::ensure!(!self.bt.as_ref().is_some_and(|b| b.dense) || !self.m.cfg.hadamard.as_ref().is_some_and(|r| r.dense), "step_batch: dense Hadamard needs recurrent layers"); let pos: Vec = rows.iter().enumerate().map(|(r, &(s, ..))| *self.slot_pos(s) + rows[..r].iter().filter(|x| x.0 == s).count()).collect(); let heads: Vec = (0..t).filter(|&r| all || rows[r].2).collect(); + for (&(s, ..), &p) in rows.iter().zip(&pos) { self.kv_need(s, p + 1)?; } + // Recurrent layers or experts: the layers of `prefill_chunk` in rows mode (`Batch::dense` is the forward below). + if self.bt.as_ref().is_some_and(|b| !b.dense) { + let bt = self.bt.as_ref().unwrap(); + anyhow::ensure!((1..=bt.rows).contains(&t) && heads.len() <= bt.cap && self.rope_offset == 0, "step_batch: {t} rows, {} answers", heads.len()); + if pos.iter().any(|&p| p >= self.ctx) { anyhow::bail!("context full ({} tokens; raise --ctx)", self.ctx); } + // Every part of a --device split holds the positions and the cache table of its own layers. + for q in self.parts() { + let (g, bt) = (&q.gpu, q.bt.as_ref().unwrap()); + g.put(&pos.iter().flat_map(|&p| [p as i32, 0]).collect::>(), &bt.step, 0)?; + let mut table = vec![0u64; q.layers.len() * 2 * bt.rows]; + for (i, ly) in q.layers.iter().enumerate() { + let (a, b) = match &ly.mixer { Mixer::Attn { kc, vc, .. } => (kc, vc), Mixer::Delta { conv, s, .. } => (conv, s) }; + for (r, &(sl, ..)) in rows.iter().enumerate() { table[(i * bt.rows + r) * 2..][..2].copy_from_slice(&[a[sl].addr(), b[sl].addr()]); } + } + g.put(&table, &bt.kvt, 0)?; + } + let splits = (pos.iter().max().unwrap() + 1).div_ceil(256).clamp(1, crate::backend::ATT_SPLITS); + anyhow::ensure!(t * splits <= bt.cap * crate::backend::ATT_SPLITS, "step_batch: {t} rows at {splits} splits"); + let (toks, slots): (Vec, Vec) = rows.iter().map(|r| (r.1, r.0)).unzip(); + self.prefill_chunk(&toks, None, Some((&slots, splits)))?; + } let res = { - let (Some(bt), Some(pf)) = (&self.bt, &self.pf) else { anyhow::bail!("step_batch: this model decodes with step_rows") }; + // The logits come from the last part of a --device split (only a model with recurrent layers or experts + // splits here, so the dense forward below runs on one part). + let tl = self.tail(); + let (Some(bt), Some(pf)) = (&tl.bt, &tl.pf) else { anyhow::bail!("step_batch: this model decodes with step_rows") }; anyhow::ensure!((1..=bt.rows).contains(&t) && heads.len() <= bt.cap && self.rope_offset == 0, "step_batch: {t} rows, {} answers", heads.len()); if pos.iter().any(|&p| p >= self.ctx) { anyhow::bail!("context full ({} tokens; raise --ctx)", self.ctx); } let c = &self.m.cfg; - let (g, eps, ne, nvoc) = (&self.gpu, c.eps, c.n_embd, c.n_vocab); + let (g, eps, ne, nvoc) = (&tl.gpu, c.eps, c.n_embd, c.n_vocab); let (hd, nh, nkv) = (c.head_dim, c.n_head, c.n_head_kv); let (kv, qs) = (nkv * hd, if c.q_gate { 2 * hd } else { hd }); + let base = pf.slab.addr(); + let at = |o: usize| base + 4 * o as u64; + let (l, n, step) = (&pf.lay, pf.chunk, bt.step.addr()); + let (x, h) = (at(0), at(l.h)); + if bt.dense { g.put(&rows.iter().flat_map(|r| self.m.embed(r.1)).collect::>(), &pf.slab, 0)?; g.put(&pos.iter().flat_map(|&p| [p as i32, 0]).collect::>(), &bt.step, 0)?; let mut table = vec![0u64; self.layers.len() * 2 * bt.rows]; @@ -803,44 +1266,251 @@ impl GpuModel<'_> { // 3060: 17 ms with the splits of `step_rows`, 3.5 ms so). let splits = (pos.iter().max().unwrap() + 1).div_ceil(256).clamp(1, crate::backend::ATT_SPLITS); anyhow::ensure!(t * splits <= bt.cap * crate::backend::ATT_SPLITS, "step_batch: {t} rows at {splits} splits"); - let base = pf.slab.addr(); - let at = |o: usize| base + 4 * o as u64; - let (l, n, step) = (&pf.lay, pf.chunk, bt.step.addr()); - let (x, h) = (at(0), at(l.h)); let (kraw, kk, vv) = (at(l.c), at(l.c + n * kv), at(l.c + 2 * n * kv)); for (i, ly) in self.layers.iter().enumerate() { let (Mixer::Attn { q, k, v, qn, kn, o, sink, .. }, Ffn::Dense { gate, up, down }) = (&ly.mixer, &ly.ffn) else { unreachable!() }; let kvt = bt.kvt.addr() + (8 * i * 2 * bt.rows) as u64; g.rms_norm(x, ne, ly.attn_norm.as_ref().unwrap().ptr, h, ne, ne, t, eps)?; - g.gemm_dense(q, t, h, ne, at(l.a), nh * qs, 0)?; - g.gemm_dense(k, t, h, ne, kraw, kv, SAME_X)?; - g.gemm_dense(v, t, h, ne, vv, kv, SAME_X)?; + g.gemm_dense(q, t, h, ne, at(l.a), nh * qs, BATCHED)?; + g.gemm_dense(k, t, h, ne, kraw, kv, SAME_X | BATCHED)?; + g.gemm_dense(v, t, h, ne, vv, kv, SAME_X | BATCHED)?; let win = c.swa.get(self.first + i).copied().unwrap_or(false).then_some(c.n_swa).unwrap_or(0); g.rms_norm_rope_qk_rows(at(l.a), qs, qn.ptr, at(l.b), nh, kraw, kn.ptr, kk, nkv, hd, eps, c.n_rot, step, c.rope_base, vv, kvt, t)?; g.attn_rows(at(l.b), if c.q_gate { at(l.a) } else { 0 }, at(l.d), bt.attp.addr(), step, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), t, sink.as_ref().map_or(0, |s| s.ptr), win, kvt, splits)?; - g.gemm_dense(o, t, at(l.d), nh * hd, x, ne, 2)?; + g.gemm_dense(o, t, at(l.d), nh * hd, x, ne, 2 | BATCHED)?; g.rms_norm(x, ne, ly.post_norm.as_ref().unwrap().ptr, h, ne, ne, t, eps)?; - g.gemm_dense(gate, t, h, ne, at(l.ge), c.n_ff, 0)?; - g.gemm_dense(up, t, h, ne, at(l.ge), c.n_ff, 1 | SAME_X)?; - g.gemm_dense(down, t, at(l.ge), c.n_ff, x, ne, 2)?; + g.gemm_dense(gate, t, h, ne, at(l.ge), c.n_ff, BATCHED)?; + g.gemm_dense(up, t, h, ne, at(l.ge), c.n_ff, 1 | SAME_X | BATCHED)?; + g.gemm_dense(down, t, at(l.ge), c.n_ff, x, ne, 2 | BATCHED)?; g.kick()?; } + } // Region a, not h: the next forward's first GEMM reads h, and the backend may keep the quantized rows of // the last GEMM input by its address. - let (on, nr) = (self.output_norm.as_ref().unwrap().ptr, heads.len()); + let (on, nr) = (tl.output_norm.as_ref().unwrap().ptr, heads.len()); + if nr == 0 { vec![] } else { if all { g.rms_norm(x, ne, on, at(l.a), ne, ne, t, eps)?; } else { for (j, &r) in heads.iter().enumerate() { g.rms_norm(at(r * ne), ne, on, at(l.a + j * ne), ne, ne, 1, eps)?; } } - g.gemm_dense(self.output.as_ref().unwrap(), nr, at(l.a), ne, bt.logits.addr(), nvoc, 0)?; + let hx = tl.dense_head(at(l.a), nr)?; + g.gemm_dense(tl.output.as_ref().unwrap(), nr, hx, ne, bt.logits.addr(), nvoc, BATCHED)?; g.argmax_rows(bt.logits.addr(), nvoc, nr, bt.amax.addr())?; let am = g.get::(&bt.amax, 0, nr)?; heads.iter().zip(am).enumerate() .map(|(j, (&r, tk))| Ok((tk as u32, if rows[r].2 { g.get::(&bt.logits, j * nvoc, nvoc)? } else { vec![] }))) .collect::>>()? + } }; - for &(s, ..) in rows { *self.slot_pos(s) += 1; } - self.row_tokens += t; - self.after_experts(t, self.row_tokens)?; + let mut q = Some(&mut *self); + while let Some(p) = q { + for &(s, ..) in rows { *p.slot_pos(s) += 1; } + p.row_tokens += t; + p.after_experts(t, p.row_tokens)?; + q = p.next.as_deref_mut(); + } Ok(res) } } + +#[cfg(test)] +mod tests { + use super::{GpuModel, pack_expert_rows, split_cpu_experts}; + use crate::backend::{Backend, Buf, GpuTensor}; + use crate::gguf::Gguf; + use crate::model::Model; + use crate::quant::GgmlType; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct StubBackend { + next_addr: AtomicU64, + } + + impl StubBackend { + fn new() -> Box { + Box::new(StubBackend { next_addr: AtomicU64::new(0x1000) }) + } + } + + impl Backend for StubBackend { + fn name(&self) -> &'static str { "stub" } + fn device(&self) -> String { "stub".into() } + fn alloc(&self, bytes: usize) -> anyhow::Result { + let len = bytes.max(1); + let addr = self.next_addr.fetch_add((len as u64).next_multiple_of(256), Ordering::Relaxed); + Ok(Buf::new(addr, len, ())) + } + fn htod(&self, _src: &[u8], _dst: &Buf, _off: usize) -> anyhow::Result<()> { Ok(()) } + fn dtoh(&self, _src: &Buf, _off: usize, dst: &mut [u8]) -> anyhow::Result<()> { dst.fill(0); Ok(()) } + fn dtod(&self, _src: &Buf, _src_off: usize, _dst: &Buf, _dst_off: usize, _bytes: usize) -> anyhow::Result<()> { Ok(()) } + fn memset(&self, _dst: &Buf) -> anyhow::Result<()> { Ok(()) } + fn mem_info(&self) -> anyhow::Result<(usize, usize)> { Ok((4 << 30, 8 << 30)) } + fn sync(&self) -> anyhow::Result<()> { Ok(()) } + fn graph(&self, _key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { f() } + fn host_mailbox(&self, words: usize) -> anyhow::Result<(Buf, *mut u32)> { + let mut v = vec![0u32; words.max(1)].into_boxed_slice(); + let ptr = v.as_mut_ptr(); + let addr = self.next_addr.fetch_add(((words.max(1) * 4) as u64).next_multiple_of(256), Ordering::Relaxed); + Ok((Buf::new(addr, words.max(1) * 4, v), ptr)) + } + fn kv_words(&self, n: usize) -> usize { n } + fn kv_rows(&self) -> bool { true } + fn rms_norm_rope_qk_rows(&self, _q: u64, _qs: usize, _qw: u64, _qo: u64, _nh: usize, _k: u64, _kw: u64, _ko: u64, _nkv: usize, _hd: usize, _eps: f32, _nr: usize, _step: u64, _base: f32, _v: u64, _kvt: u64, _nt: usize) -> anyhow::Result<()> { Ok(()) } + fn attn_rows(&self, _q: u64, _qg: u64, _out: u64, _part: u64, _step: u64, _nh: usize, _nkv: usize, _hd: usize, _scale: f32, _nt: usize, _sink: u64, _win: usize, _kvt: u64, _splits: usize) -> anyhow::Result<()> { Ok(()) } + fn gemm(&self, _ty: GgmlType, _r: usize, _c: usize, _t: u64, _nt: usize, _x: u64, _xs: usize, _nx: usize, _xr: u64, _y: u64, _ys: usize, _act: i32) -> anyhow::Result<()> { Ok(()) } + fn int8_gemm(&self, _ty: GgmlType) -> bool { false } + fn gemm_dense(&self, _w: &GpuTensor, _n: usize, _x: u64, _xs: usize, _y: u64, _ys: usize, _act: i32) -> anyhow::Result<()> { Ok(()) } + fn gemv(&self, _w: &GpuTensor, _x: u64, _y: u64) -> anyhow::Result<()> { Ok(()) } + fn gemvn(&self, _w: &GpuTensor, _x: u64, _xs: usize, _y: u64, _ys: usize, _nt: usize) -> anyhow::Result<()> { Ok(()) } + fn gemvq(&self, _w: &GpuTensor, _x: u64, _xs: usize, _xq: u64, _y: u64, _ys: usize, _nt: usize) -> anyhow::Result<()> { Ok(()) } + fn moe_gemv(&self, _ty: GgmlType, _r: usize, _c: usize, _w: u64, _s: usize, _ids: u64, _k: usize, _x: u64, _xs: usize, _xg: usize, _y: u64, _pair: Option<(i64, i64)>, _xq: u64) -> anyhow::Result<()> { Ok(()) } + fn dequant(&self, _w: &GpuTensor, _r: usize, _out: u64) -> anyhow::Result<()> { Ok(()) } + fn quant_xq(&self, _x: u64, _xs: usize, _n: usize, _nt: usize, _out: u64) -> anyhow::Result<()> { Ok(()) } + fn rms_norm(&self, _x: u64, _xs: usize, _w: u64, _out: u64, _os: usize, _n: usize, _r: usize, _eps: f32) -> anyhow::Result<()> { Ok(()) } + fn rms_norm_q(&self, _x: u64, _xs: usize, _w: u64, _out: u64, _os: usize, _n: usize, _r: usize, _eps: f32, _xq: u64, _res: u64) -> anyhow::Result<()> { Ok(()) } + fn argmax_rows(&self, _x: u64, _n: usize, _r: usize, _out: u64) -> anyhow::Result<()> { Ok(()) } + fn l2_norm(&self, _x: u64, _n: usize, _p: usize, _s: usize, _r: usize, _eps: f32) -> anyhow::Result<()> { Ok(()) } + fn rope_pairs(&self, _x: u64, _s: usize, _h: usize, _p: usize, _nr: usize, _step: u64, _base: f32, _lo: usize, _hi: usize) -> anyhow::Result<()> { Ok(()) } + fn rms_norm_rope_kv(&self, _x: u64, _xs: usize, _w: u64, _out: u64, _n: usize, _r: usize, _eps: f32, _p: usize, _nr: usize, _step: u64, _base: f32, _v: u64, _kc: u64, _vc: u64) -> anyhow::Result<()> { Ok(()) } + fn add(&self, _x: u64, _y: u64, _n: usize) -> anyhow::Result<()> { Ok(()) } + fn swiglu(&self, _g: u64, _u: u64, _n: usize) -> anyhow::Result<()> { Ok(()) } + fn ssm_gates(&self, _b: u64, _g: u64, _d: u64, _a: u64, _n: usize, _nv: usize) -> anyhow::Result<()> { Ok(()) } + fn conv_silu(&self, _qkv: u64, _st: u64, _w: u64, _y: u64, _ch: usize, _kw: usize, _nn: usize, _eps: f32) -> anyhow::Result<()> { Ok(()) } + fn deltanet(&self, _y: u64, _s: u64, _b: u64, _g: u64, _d: u64, _a: u64, _o: u64, _nk: usize, _nv: usize, _i: bool, _dk: usize, _dv: usize, _sc: f32, _t: usize, _ych: usize, _snap: u64, _nsnap: usize) -> anyhow::Result<()> { Ok(()) } + fn conv_seq(&self, _qkv: u64, _st: u64, _w: u64, _y: u64, _ch: usize, _kw: usize, _t: usize, _snap: u64, _nsnap: usize) -> anyhow::Result<()> { Ok(()) } + fn dflash2_conv(&self, _x: u64, _dw: u64, _base: u64, _out: u64, _h: usize, _gs: usize, _k: usize, _t: usize, _part: usize) -> anyhow::Result<()> { Ok(()) } + fn attn_prefill_m(&self, _q: u64, _kc: u64, _vc: u64, _qg: u64, _out: u64, _step: u64, _t: usize, _nh: usize, _nkv: usize, _hd: usize, _sc: f32, _qm: u64, _mw: usize, _sink: u64, _win: usize) -> anyhow::Result<()> { Ok(()) } + fn moe_combine_seq(&self, _x: u64, _ye: u64, _wts: u64, _inv: u64, _k: usize, _sh: u64, _sg: u64, _n: usize, _t: usize) -> anyhow::Result<()> { Ok(()) } + fn norm_gate(&self, _o: u64, _w: u64, _z: u64, _n: usize, _h: usize, _eps: f32) -> anyhow::Result<()> { Ok(()) } + fn kv_store(&self, _k: u64, _v: u64, _kc: u64, _vc: u64, _n: usize, _t: usize, _step: u64, _hd: usize) -> anyhow::Result<()> { Ok(()) } + fn attn_decode_gq(&self, _q: u64, _kc: u64, _vc: u64, _qg: u64, _out: u64, _part: u64, _step: u64, _nh: usize, _nkv: usize, _hd: usize, _sc: f32, _gq: i32, _nt: usize, _sink: u64, _win: usize) -> anyhow::Result<()> { Ok(()) } + fn router_topk(&self, _p: u64, _n: usize, _k: usize, _es: f32, _ids: u64, _wts: u64, _t: usize, _sig: bool) -> anyhow::Result<()> { Ok(()) } + fn moe_route(&self, _p: u64, _n: usize, _k: usize, _es: f32, _tbl: u64, _ids: u64, _wts: u64, _sl: u64, _wh: u64, _h: u64, _mb: u64, _nh: usize, _ho: usize, _step: u64, _t: usize, _pid: u64, _sig: bool, _hid: u64, _hmin: i32) -> anyhow::Result<()> { Ok(()) } + fn moe_combine(&self, _x: u64, _ye: u64, _w: u64, _k: usize, _sh: u64, _sg: u64, _mb: u64, _yo: usize, _step: u64, _sl: u64, _n: usize, _t: usize) -> anyhow::Result<()> { Ok(()) } + } + + struct TempFile(std::path::PathBuf); + impl Drop for TempFile { + fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } + } + + fn write_tiny_qwen3_gguf(tag: &str) -> TempFile { + let mut kvs = Vec::new(); + let w_s = |b: &mut Vec, s: &str| { b.extend((s.len() as u64).to_le_bytes()); b.extend(s.as_bytes()); }; + let w_kv = |b: &mut Vec, k: &str, t: u32, p: &[u8]| { w_s(b, k); b.extend(t.to_le_bytes()); b.extend(p); }; + let mut arch_v = Vec::new(); + w_s(&mut arch_v, "qwen3"); + w_kv(&mut kvs, "general.architecture", 8, &arch_v); + w_kv(&mut kvs, "qwen3.block_count", 4, &1u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.embedding_length", 4, &64u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.feed_forward_length", 4, &64u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.attention.head_count", 4, &1u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.attention.head_count_kv", 4, &1u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.attention.key_length", 4, &64u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.attention.layer_norm_rms_epsilon", 6, &1e-6f32.to_le_bytes()); + + let mut hdr = Vec::new(); + let mut body = Vec::new(); + let mut add_t = |name: &str, dims: &[u64]| { + w_s(&mut hdr, name); + hdr.extend((dims.len() as u32).to_le_bytes()); + for &d in dims { hdr.extend(d.to_le_bytes()); } + hdr.extend(0u32.to_le_bytes()); // F32 + hdr.extend((body.len() as u64).to_le_bytes()); + let n: usize = dims.iter().product::() as usize; + body.resize(body.len() + n * 4, 0); + while body.len() % 32 != 0 { body.push(0); } + }; + add_t("token_embd.weight", &[64, 16]); + add_t("output_norm.weight", &[64]); + add_t("output.weight", &[64, 16]); + add_t("blk.0.attn_norm.weight", &[64]); + add_t("blk.0.ffn_norm.weight", &[64]); + add_t("blk.0.attn_q_norm.weight", &[64]); + add_t("blk.0.attn_k_norm.weight", &[64]); + add_t("blk.0.attn_q.weight", &[64, 64]); + add_t("blk.0.attn_k.weight", &[64, 64]); + add_t("blk.0.attn_v.weight", &[64, 64]); + add_t("blk.0.attn_output.weight", &[64, 64]); + add_t("blk.0.ffn_gate.weight", &[64, 64]); + add_t("blk.0.ffn_up.weight", &[64, 64]); + add_t("blk.0.ffn_down.weight", &[64, 64]); + + let mut gg = Vec::new(); + gg.extend(b"GGUF"); + gg.extend(3u32.to_le_bytes()); + gg.extend(14u64.to_le_bytes()); + gg.extend(8u64.to_le_bytes()); + gg.extend(kvs); + gg.extend(hdr); + while gg.len() % 32 != 0 { gg.push(0); } + gg.extend(body); + + let path = std::env::temp_dir().join(format!("strata_prefill_slots_{}_{}.gguf", tag, std::process::id())); + std::fs::write(&path, &gg).unwrap(); + TempFile(path) + } + + #[test] + fn prefill_packs_cpu_rows_after_gpu_rows_without_reordering_each_group() { + let off = [0, 3, 5, 5, 6, 10]; + assert_eq!(pack_expert_rows(&off, &[0, 3]), [6..9, 0..2, 2..2, 9..10, 2..6]); + assert_eq!(pack_expert_rows(&off, &[]), [0..3, 3..5, 5..5, 5..6, 6..10]); + } + + #[test] + fn prefill_cpu_split_uses_routed_rows_and_keeps_staged_experts_on_gpu_first() { + let off = [0, 3, 4, 5, 15, 16]; + let mut missed = vec![0, 1, 2, 3, 4]; + assert_eq!(split_cpu_experts(&mut missed, &off, &[0, 1], 0.4, false, false), [2, 4]); + assert_eq!(missed, [0, 1, 3]); + } + + #[test] + fn prefill_cpu_split_can_probe_a_small_batch_without_changing_fixed_shares() { + let off = [0, 1, 4]; + let mut missed = vec![0, 1]; + assert!(split_cpu_experts(&mut missed, &off, &[], 0.02, true, true).is_empty()); + assert_eq!(split_cpu_experts(&mut missed, &off, &[], 0.02, false, true), [0]); + assert_eq!(missed, [1]); + } + + /// Under `--parallel`, `between` runs `Sched::run`. When only a shifted image slot (`rope_offset != 0`) decodes + /// alone in `lone`, `Sched::run` leaves `self.cur` on that shifted slot, so `prefill_slots` must make an unshifted + /// job slot current again before calling `batch_rows` for the next chunk. + #[test] + fn prefill_slots_restores_unshifted_slot_after_between_switches_to_shifted_slot() { + let path = write_tiny_qwen3_gguf("shifted"); + let gg = Gguf::open(&path.0).unwrap(); + let m = Model::load(&gg).unwrap(); + // ns > STEP_ROWS (4) enables `Batch` (`batch_cap() > 0`) for `prefill_slots`. + let mut gm = GpuModel::load_slots(&m, StubBackend::new(), 64, 4, 0, 5).unwrap(); + assert!(gm.batch_cap() > 0); + + // Slot 0 holds an image prompt with a non-zero RoPE offset. + gm.use_slot(0); + gm.rope_offset = 7; + + let p1 = [1u32, 2, 3, 4, 5]; + let p2 = [6u32, 7, 8, 9, 10]; + let jobs = [(1usize, 0u64, &p1[..], 0usize, 4usize), (2usize, 0u64, &p2[..], 0usize, 4usize)]; + let mut between_calls = 0usize; + let out = gm.prefill_slots(&jobs, &mut |g| { + between_calls += 1; + g.use_slot(0); + Ok(()) + }).unwrap(); + assert_eq!(out.len(), 2); + assert_eq!(between_calls, 2); + assert_eq!(*gm.slot_pos(1), p1.len()); + assert_eq!(*gm.slot_pos(2), p2.len()); + assert_eq!(*gm.slot_pos(0), 0); + assert!(gm.slot_shifted(0), "slot 0's rope_offset must remain intact"); + assert!(!gm.slot_shifted(gm.cur), "prefill_slots must leave an unshifted slot current"); + + // Follow-up batched decode on the prefilled slots must also succeed. + let dec = gm.step_batch(&[(1, 11, true), (2, 12, true)]).unwrap(); + assert_eq!(dec.len(), 2); + assert_eq!(*gm.slot_pos(1), p1.len() + 1); + assert_eq!(*gm.slot_pos(2), p2.len() + 1); + } +} diff --git a/src/grammar.rs b/src/grammar.rs new file mode 100644 index 00000000..475be1ff --- /dev/null +++ b/src/grammar.rs @@ -0,0 +1,885 @@ +//! Constrained decoding: `logit_bias` and llama.cpp's GBNF grammars (the request field `grammar`). A `Constraint` +//! changes the logits before a token is picked, greedy or sampled, and follows the tokens the reply gets. + +use anyhow::{Context, bail, ensure}; +use serde_json::Value; +use std::sync::Arc; + +/// A `logit_bias` entry: a token id, or a text whose every token gets the bias (llama.cpp). +#[derive(Clone, Debug, PartialEq)] +pub enum BiasKey { Id(u32), Text(String) } + +/// `logit_bias` as OpenAI (`{"": bias}`) or llama.cpp (`[[id or text, bias or false], ...]`) sends it; a key +/// that is not a number is a text. A bias is in [-100, 100]; -100 and `false` ban the token. +pub fn parse_bias(v: &Value) -> anyhow::Result> { + let key = |k: &Value| match k { + Value::String(s) => Ok(s.parse().map_or_else(|_| BiasKey::Text(s.clone()), BiasKey::Id)), + x => x.as_u64().and_then(|n| u32::try_from(n).ok()).map(BiasKey::Id).context("logit_bias: a key must be a token id or a text"), + }; + let bias = |b: &Value| match b { + Value::Bool(false) => Ok(f32::NEG_INFINITY), + x => x.as_f64().filter(|f| (-100.0..=100.0).contains(f)) + .map(|f| if f <= -100.0 { f32::NEG_INFINITY } else { f as f32 }).context("logit_bias: a bias must be a number in [-100, 100] or false"), + }; + match v { + Value::Null => Ok(vec![]), + Value::Object(o) => o.iter().map(|(k, b)| Ok((key(&Value::String(k.clone()))?, bias(b)?))).collect(), + Value::Array(a) => a.iter().map(|e| match e.as_array().map(Vec::as_slice) { + Some([k, b]) => Ok((key(k)?, bias(b)?)), + _ => bail!("logit_bias: an entry must be [token, bias]"), + }).collect(), + _ => bail!("logit_bias must be an object or an array"), + } +} + +/// llama.cpp's `grammars/json.gbnf`: any JSON object (`response_format` `json_object`). +pub const JSON_GBNF: &str = r#" +root ::= object +value ::= object | array | string | number | ("true" | "false" | "null") ws + +object ::= + "{" ws ( + string ":" ws value + ("," ws string ":" ws value)* + )? "}" ws + +array ::= + "[" ws ( + value + ("," ws value)* + )? "]" ws + +string ::= + "\"" ( + [^"\\\x7F\x00-\x1F] | + "\\" (["\\/bfnrt] | "u" [0-9a-fA-F]{4}) # escapes + )* "\"" ws + +number ::= ("-"? ([0-9] | [1-9] [0-9]{0,15})) ("." [0-9]+)? ([eE] [-+]? [0-9] [0-9]{0,15})? ws + +# Optional space: by convention, applied in this grammar after literal chars when allowed +ws ::= | " " | "\n" [ \t]{0,20} +"#; + +/// The JSON rules a schema grammar uses (json.gbnf without its root). +const JSON_RULES: &str = r#" +value ::= object | array | string | number | ("true" | "false" | "null") ws +object ::= "{" ws ( string ":" ws value ("," ws string ":" ws value)* )? "}" ws +array ::= "[" ws ( value ("," ws value)* )? "]" ws +string ::= "\"" ( [^"\\\x7F\x00-\x1F] | "\\" (["\\/bfnrt] | "u" [0-9a-fA-F]{4}) )* "\"" ws +number ::= ("-"? ([0-9] | [1-9] [0-9]{0,15})) ("." [0-9]+)? ([eE] [-+]? [0-9] [0-9]{0,15})? ws +integer ::= ("-"? ([0-9] | [1-9] [0-9]{0,15})) ws +boolean ::= ("true" | "false") ws +null ::= "null" ws +ws ::= | " " | "\n" [ \t]{0,20} +"#; + +/// JSON that keeps the order of an object's keys (`serde_json::Value` sorts them), so a schema's properties are +/// written in the order the schema gives. +#[derive(Debug)] +pub enum Json { Map(Vec<(String, Json)>), List(Vec), Leaf(Value) } + +impl<'de> serde::Deserialize<'de> for Json { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> serde::de::Visitor<'de> for V { + type Value = Json; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("JSON") } + fn visit_bool(self, b: bool) -> Result { Ok(Json::Leaf(b.into())) } + fn visit_i64(self, n: i64) -> Result { Ok(Json::Leaf(n.into())) } + fn visit_u64(self, n: u64) -> Result { Ok(Json::Leaf(n.into())) } + fn visit_f64(self, n: f64) -> Result { Ok(Json::Leaf(n.into())) } + fn visit_str(self, s: &str) -> Result { Ok(Json::Leaf(s.into())) } + fn visit_unit(self) -> Result { Ok(Json::Leaf(Value::Null)) } + fn visit_seq>(self, mut a: A) -> Result { + let mut v = vec![]; + while let Some(x) = a.next_element()? { v.push(x); } + Ok(Json::List(v)) + } + fn visit_map>(self, mut a: A) -> Result { + let mut v = vec![]; + while let Some(kv) = a.next_entry()? { v.push(kv); } + Ok(Json::Map(v)) + } + } + d.deserialize_any(V) + } +} + +static NULL: Json = Json::Leaf(Value::Null); + +impl Json { + fn get_opt(&self, k: &str) -> Option<&Json> { + match self { Json::Map(m) => m.iter().rev().find(|(n, _)| n == k).map(|(_, v)| v), _ => None } + } + pub fn get(&self, k: &str) -> &Json { self.get_opt(k).unwrap_or(&NULL) } + fn str(&self) -> Option<&str> { if let Json::Leaf(Value::String(s)) = self { Some(s) } else { None } } + fn null(&self) -> bool { matches!(self, Json::Leaf(Value::Null)) } + fn opt(&self) -> Option<&Json> { (!self.null()).then_some(self) } + /// The JSON text, keys in their order. + fn text(&self) -> String { + match self { + Json::Leaf(v) => v.to_string(), + Json::List(l) => format!("[{}]", l.iter().map(Json::text).collect::>().join(",")), + Json::Map(m) => format!("{{{}}}", m.iter().map(|(k, v)| format!("{}:{}", Value::from(k.as_str()), v.text())).collect::>().join(",")), + } + } + /// A JSON pointer (RFC 6901) into maps and lists. + fn pointer(&self, p: &str) -> Option<&Json> { + if p.is_empty() { return Some(self); } + p.strip_prefix('/')?.split('/').try_fold(self, |j, t| { + let t = t.replace("~1", "/").replace("~0", "~"); + match j { + Json::Map(_) => j.get_opt(&t).and_then(Json::opt), + Json::List(l) => t.parse::().ok().and_then(|i| l.get(i)).and_then(Json::opt), + Json::Leaf(_) => None, + } + }) + } +} + +/// The grammar of a request's `response_format`: `text` is none, `json_object` any JSON object (or, with a +/// `schema`, that schema as llama.cpp's server takes it), `json_schema` the OpenAI form `{"json_schema": {"schema"}}`. +pub fn response_format(v: &Json) -> anyhow::Result> { + let schema = match v.get("type").str() { + _ if v.null() => return Ok(None), + Some("text") => return Ok(None), + Some("json_object") if v.get("schema").null() => return Grammar::parse(JSON_GBNF).map(Some), + Some("json_object") => v.get("schema"), + Some("json_schema") => v.get("json_schema").get("schema").opt().unwrap_or(v.get("schema")), + _ => bail!("response_format.type must be text, json_object or json_schema"), + }; + ensure!(matches!(schema, Json::Map(_) | Json::Leaf(Value::Bool(_))), "response_format: the schema must be an object"); + let mut g = Schema { root: schema, rules: vec![], refs: vec![], size: 0, depth: 0 }; + let root = g.rule(schema)?; + let mut src = format!("root ::= {root}\n"); + for (i, r) in g.rules.iter().enumerate() { src += &format!("s{i} ::= {r}\n"); } + Grammar::parse(&(src + JSON_RULES)).map(Some) +} + +/// A JSON schema written out as GBNF rules `s0`, `s1`, ...: `type` (one or a list), `properties` with `required` +/// (in the schema's order), `items`, `enum`, `const`, `anyOf`/`oneOf`, `allOf` of one, and local `$ref`s. +/// ponytail: lengths, counts, patterns, formats and numeric bounds are not enforced; any value that fits the +/// structure passes them. +/// `size` counts the bytes written so far and `depth` the schemas being written, both bounded, so a schema that +/// repeats a large `const` through many `$ref`s or chains `$ref`s deep is refused before it takes memory or stack. +struct Schema<'a> { root: &'a Json, rules: Vec, refs: Vec<(*const Json, usize)>, size: usize, depth: usize } + +impl<'a> Schema<'a> { + fn add(&mut self, body: String) -> anyhow::Result { + self.grow(body.len())?; + self.rules.push(body); + Ok(format!("s{}", self.rules.len() - 1)) + } + + /// Counts `n` more bytes of grammar. + fn grow(&mut self, n: usize) -> anyhow::Result<()> { + self.size += n; + ensure!(self.size <= MAX_CHARS, "response_format: the schema's grammar is longer than {MAX_CHARS} characters"); + Ok(()) + } + + /// A GBNF literal of the JSON text of `v`, then `ws`. + fn lit(v: &Json) -> String { + let mut o = String::from("\""); + for c in v.text().chars() { + match c { '"' => o += "\\\"", '\\' => o += "\\\\", c => o.push(c) } + } + o + "\" ws" + } + + /// The rule (or a GBNF expression) that takes the values of `s`. + fn rule(&mut self, s: &'a Json) -> anyhow::Result { + ensure!(self.depth < 64, "response_format: the schema nests deeper than 64"); + self.depth += 1; + let r = self.rule_in(s); + self.depth -= 1; + let r = r?; + self.grow(r.len())?; + Ok(r) + } + + fn rule_in(&mut self, s: &'a Json) -> anyhow::Result { + if !matches!(s, Json::Map(_)) { + ensure!(!matches!(s, Json::Leaf(Value::Bool(false))), "response_format: a false schema takes no value"); + return Ok("value".into()); + } + if let Some(r) = s.get("$ref").str() { + let path = r.strip_prefix('#').with_context(|| format!("response_format: only local $refs work, not {r}"))?; + let target = self.root.pointer(path).with_context(|| format!("response_format: $ref {r} is not in the schema"))?; + // Keyed by the node, so two spellings of one $ref share its rule. + if let Some(&(_, i)) = self.refs.iter().find(|(n, _)| std::ptr::eq(*n, target)) { return Ok(format!("s{i}")); } + // The rule gets its name first, so a schema that refers to itself is a recursive rule. + let i = self.rules.len(); + self.rules.push(String::new()); + self.refs.push((target, i)); + self.rules[i] = self.rule(target)?; + return Ok(format!("s{i}")); + } + if let Some(c) = s.get_opt("const") { return Ok(Self::lit(c)); } + if let Some(e) = s.get("enum").opt() { + let Json::List(e) = e else { bail!("response_format: enum must be a non-empty array") }; + ensure!(!e.is_empty(), "response_format: enum must be a non-empty array"); + return Ok(format!("({})", e.iter().map(Self::lit).collect::>().join(" | "))); + } + for k in ["anyOf", "oneOf"] { + if let Some(a) = s.get(k).opt() { + let Json::List(a) = a else { bail!("response_format: {k} must be a non-empty array") }; + ensure!(!a.is_empty(), "response_format: {k} must be a non-empty array"); + let alts = a.iter().map(|x| self.rule(x)).collect::>>()?; + return Ok(format!("({})", alts.join(" | "))); + } + } + if let Json::List(a) = s.get("allOf") { + ensure!(a.len() == 1, "response_format: allOf works only with one schema"); + return self.rule(&a[0]); + } + let types: Vec<&str> = match s.get("type") { + Json::Leaf(Value::Null) => return Ok(if !s.get("properties").null() { self.object(s)? } else if !s.get("items").null() { self.array(s)? } else { "value".into() }), + Json::Leaf(Value::String(t)) => vec![t], + Json::List(a) => a.iter().map(|t| t.str().context("response_format: a type must be a string")).collect::>()?, + _ => bail!("response_format: type must be a string or an array"), + }; + let alts = types.iter().map(|&t| Ok(match t { + "object" => self.object(s)?, + "array" => self.array(s)?, + "string" | "number" | "integer" | "boolean" | "null" => t.into(), + t => bail!("response_format: unknown type {t}"), + })).collect::>>()?; + Ok(if alts.len() == 1 { alts.into_iter().next().unwrap() } else { format!("({})", alts.join(" | ")) }) + } + + /// An object with the listed properties: the required ones always, the rest each optional, all in the schema's + /// order. Without `properties` any object. + fn object(&mut self, s: &'a Json) -> anyhow::Result { + let Json::Map(props) = s.get("properties") else { return Ok("object".into()) }; + if props.is_empty() { return Ok("object".into()); } + let req: Vec<&str> = match s.get("required") { Json::List(r) => r.iter().filter_map(Json::str).collect(), _ => vec![] }; + let mut kv = vec![]; + for (k, v) in props { + let val = self.rule(v)?; + kv.push((req.contains(&k.as_str()), format!("{} \":\" ws {val}", Self::lit(&Json::Leaf(k.as_str().into()))))); + } + // rests[i]: the properties from i on, each after a comma; the optional ones may be left out. + let mut rests = vec![String::new(); kv.len() + 1]; + for i in (0..kv.len()).rev() { + let (r, x) = &kv[i]; + let tail = if rests[i + 1].is_empty() { String::new() } else { format!(" {}", rests[i + 1]) }; + rests[i] = self.add(if *r { format!("\",\" ws {x}{tail}") } else { format!("(\",\" ws {x})?{tail}") })?; + } + // The first property written: the first required one, any optional one before it, or (none required) none. + let mut first = vec![]; + for (i, (r, x)) in kv.iter().enumerate() { + first.push(format!("{x} {}", rests[i + 1])); + if *r { break; } + } + let empty = if kv.iter().any(|(r, _)| *r) { "" } else { " | " }; + self.add(format!("\"{{\" ws ({}{empty}) \"}}\" ws", first.join(" | "))) + } + + fn array(&mut self, s: &'a Json) -> anyhow::Result { + let item = match s.get("items").opt() { Some(i) => self.rule(i)?, None => "value".into() }; + self.add(format!("\"[\" ws ({item} (\",\" ws {item})*)? \"]\" ws")) + } +} + +/// One element of a rule's sequence: a character (in or, negated, not in the ranges) or another rule. +#[derive(Clone, Debug, PartialEq)] +enum Elem { Chars(bool, Vec<(u32, u32)>), Rule(usize) } + +/// A parsed GBNF grammar: each rule is a list of alternatives, each a sequence; repetitions and groups are rules of +/// their own, as in llama.cpp. +#[derive(Debug)] +pub struct Grammar { rules: Vec>>, root: usize } + +/// Limits for a grammar that comes with a request: its length, the nesting of groups, the elements and rules the +/// parser writes out (repetitions copy their body), and the expansion steps a check may take. +const MAX_CHARS: usize = 64 << 10; +const MAX_NEST: usize = 64; +const MAX_ELEMS: usize = 64 << 10; +/// Expansion budgets: a step costs 1 + the frames of its stack. One token's bytes (`allows`, `accept`), a whole +/// mask of the vocabulary, and checking every rule start at parse time. A budget that runs out drops the rest of the +/// stacks, so the grammar stays enforced but may refuse a valid token (only grammars far past what JSON needs). +const STEPS: usize = 200_000; +const MASK_STEPS: usize = 20_000_000; +const CHECK_STEPS: usize = 200_000; +/// Stacks kept after a character. ponytail: more are dropped (an odd ambiguous grammar may then refuse a valid text). +const MAX_STACKS: usize = 1024; + +struct Parser { c: Vec, i: usize, names: Vec, rules: Vec>>>, nest: usize, elems: usize } + +impl Parser { + fn peek(&self) -> Option { self.c.get(self.i).copied() } + fn at(&self, s: &str) -> bool { s.chars().enumerate().all(|(k, ch)| self.c.get(self.i + k) == Some(&ch)) } + /// Spaces and `#` comments, and line ends when `lines`. + fn ws(&mut self, lines: bool) { + while let Some(ch) = self.peek() { + match ch { + ' ' | '\t' => self.i += 1, + '\r' | '\n' if lines => self.i += 1, + '#' => while self.peek().is_some_and(|c| c != '\n') { self.i += 1 }, + _ => break, + } + } + } + fn name(&mut self) -> anyhow::Result { + let s = self.i; + while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { self.i += 1; } + ensure!(self.i > s, "grammar: a rule name was expected at character {}", s); + Ok(self.c[s..self.i].iter().collect()) + } + fn id(&mut self, name: &str) -> usize { + self.names.iter().position(|n| n == name).unwrap_or_else(|| { self.names.push(name.into()); self.rules.push(None); self.names.len() - 1 }) + } + /// Counts `n` more elements written out, and fails past `MAX_ELEMS`. + fn grow(&mut self, n: usize) -> anyhow::Result<()> { + self.elems = self.elems.saturating_add(n); + ensure!(self.elems <= MAX_ELEMS, "grammar: more than {MAX_ELEMS} elements once repetitions are written out"); + Ok(()) + } + fn new_rule(&mut self, alts: Vec>) -> usize { + self.names.push(String::new()); + self.rules.push(Some(alts)); + self.rules.len() - 1 + } + fn hex(&mut self, n: usize) -> anyhow::Result { + let s: String = self.c.get(self.i..self.i + n).context("grammar: a short escape")?.iter().collect(); + self.i += n; + u32::from_str_radix(&s, 16).ok().context("grammar: a bad hex escape") + } + /// One character of a literal or a class, escapes read. + fn chr(&mut self) -> anyhow::Result { + let ch = self.peek().context("grammar: unexpected end")?; + self.i += 1; + if ch != '\\' { return Ok(ch as u32); } + let e = self.peek().context("grammar: unexpected end")?; + self.i += 1; + Ok(match e { 'x' => self.hex(2)?, 'u' => self.hex(4)?, 'U' => self.hex(8)?, 'n' => 10, 'r' => 13, 't' => 9, c => c as u32 }) + } + fn alts(&mut self, nested: bool) -> anyhow::Result>> { + let mut out = vec![self.seq(nested)?]; + while self.peek() == Some('|') { + self.i += 1; + self.ws(true); + out.push(self.seq(nested)?); + } + Ok(out) + } + fn seq(&mut self, nested: bool) -> anyhow::Result> { + let (mut out, mut last) = (vec![], 0); + while let Some(ch) = self.peek() { + let start = out.len(); + match ch { + '"' => { + self.i += 1; + while self.peek() != Some('"') { let c = self.chr()?; out.push(Elem::Chars(false, vec![(c, c)])); } + self.i += 1; + } + '[' => { + self.i += 1; + let neg = self.peek() == Some('^'); + if neg { self.i += 1; } + let mut r = vec![]; + while self.peek() != Some(']') { + let lo = self.chr()?; + let hi = if self.peek() == Some('-') && self.c.get(self.i + 1) != Some(&']') { self.i += 1; self.chr()? } else { lo }; + r.push((lo, hi)); + } + self.i += 1; + out.push(Elem::Chars(neg, r)); + } + '.' => { self.i += 1; out.push(Elem::Chars(true, vec![])); } + '(' => { + self.i += 1; + self.ws(true); + self.nest += 1; + ensure!(self.nest <= MAX_NEST, "grammar: groups nested more than {MAX_NEST} deep"); + let alts = self.alts(true)?; + self.nest -= 1; + ensure!(self.peek() == Some(')'), "grammar: ')' expected at character {}", self.i); + self.i += 1; + out.push(Elem::Rule(self.new_rule(alts))); + } + '*' | '+' | '?' | '{' => { + ensure!(last < out.len(), "grammar: '{ch}' with nothing before it at character {}", self.i); + self.i += 1; + let (min, max) = match ch { + '*' => (0, None), + '+' => (1, None), + '?' => (0, Some(1)), + _ => { + let num = |p: &mut Parser| { p.ws(false); let s = p.i; while p.peek().is_some_and(|c| c.is_ascii_digit()) { p.i += 1; } + p.c[s..p.i].iter().collect::().parse::().ok() }; + let min = num(self).context("grammar: a number expected after '{'")?; + self.ws(false); + let max = if self.peek() == Some(',') { self.i += 1; num(self) } else { Some(min) }; + self.ws(false); + ensure!(self.peek() == Some('}') && max.is_none_or(|m| m >= min), "grammar: a bad {{m,n}} at character {}", self.i); + self.i += 1; + (min, max) + } + }; + let body = out.split_off(last); + self.repeat(&mut out, body, min, max)?; + self.ws(nested); + continue; + } + c if c.is_ascii_alphanumeric() || c == '-' || c == '_' => { + // `name ::=` starts the next rule. + let save = self.i; + let n = self.name()?; + self.ws(false); + if self.at("::=") { self.i = save; break; } + let id = self.id(&n); + out.push(Elem::Rule(id)); + } + _ => break, + } + last = start; + self.ws(nested); + } + Ok(out) + } + /// `body` from `min` to `max` (None: no limit) times, as llama.cpp writes it out. + fn repeat(&mut self, out: &mut Vec, body: Vec, min: usize, max: Option) -> anyhow::Result<()> { + // The copies, checked before they are made. + self.grow((body.len() + 1).saturating_mul(max.unwrap_or(min).max(1)))?; + for _ in 0..min { out.extend(body.iter().cloned()); } + match max { + None => { + // r ::= body r | + let r = self.new_rule(vec![]); + let mut a = body; + a.push(Elem::Rule(r)); + self.rules[r] = Some(vec![a, vec![]]); + out.push(Elem::Rule(r)); + } + Some(max) => { + let mut inner: Option = None; + for _ in min..max { + let mut a = body.clone(); + a.extend(inner.map(Elem::Rule)); + inner = Some(self.new_rule(vec![a, vec![]])); + } + out.extend(inner.map(Elem::Rule)); + } + } + Ok(()) + } +} + +impl Grammar { + pub fn parse(src: &str) -> anyhow::Result { + ensure!(src.chars().count() <= MAX_CHARS, "grammar: longer than {MAX_CHARS} characters"); + let mut p = Parser { c: src.chars().collect(), i: 0, names: vec![], rules: vec![], nest: 0, elems: 0 }; + p.ws(true); + while p.i < p.c.len() { + let name = p.name()?; + p.ws(false); + ensure!(p.at("::="), "grammar: '::=' expected after {name}"); + p.i += 3; + p.ws(true); + let id = p.id(&name); + let alts = p.alts(false)?; + ensure!(p.rules[id].is_none(), "grammar: rule {name} is defined twice"); + p.rules[id] = Some(alts); + p.ws(true); + ensure!(p.i == p.c.len() || p.peek().is_some_and(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'), + "grammar: unexpected {:?} at character {}", p.peek().unwrap_or(' '), p.i); + } + let root = p.names.iter().position(|n| n == "root").context("grammar: no root rule")?; + let rules = p.rules.into_iter().zip(&p.names).map(|(r, n)| r.with_context(|| format!("grammar: rule {n} is used but not defined"))) + .collect::>>()?; + ensure!(rules.iter().flatten().map(Vec::len).sum::() <= MAX_ELEMS, "grammar: more than {MAX_ELEMS} elements"); + let g = Grammar { rules, root }; + // Every rule start expands within one budget, so a grammar whose expansion blows up is refused here and not + // while it runs. + let mut steps = CHECK_STEPS; + for (r, alts) in g.rules.iter().enumerate() { + for a in 0..alts.len() { g.expand(vec![(r, a, 0)], 0, &mut steps, &mut vec![]); } + } + ensure!(steps > 0, "grammar: its expansion takes too many steps (left recursion, or alternatives that multiply)"); + Ok(g) + } + + /// The stacks of the grammar's start. + fn start(&self) -> Vec> { + let (mut out, mut steps) = (vec![], CHECK_STEPS); + for alt in 0..self.rules[self.root].len() { self.expand(vec![(self.root, alt, 0)], 0, &mut steps, &mut out); } + out + } + + /// The stacks `st` stands for with a character at the top of each (an empty stack: the grammar is complete). + /// `steps` is the budget of calls left; at 0 the rest is dropped (`parse` refuses a grammar that gets there). + fn expand(&self, mut st: Vec<(usize, usize, usize)>, depth: usize, steps: &mut usize, out: &mut Vec>) { + // ponytail: a depth cut instead of rejecting left recursion when parsing. + if depth > 200 || *steps <= st.len() { *steps = 0; return; } + if out.len() >= MAX_STACKS { return; } + *steps -= 1 + st.len(); + loop { + let Some(&(r, a, e)) = st.last() else { out.push(st); return }; + match self.rules[r][a].get(e) { + None => { st.pop(); } + Some(Elem::Chars(..)) => { out.push(st); return; } + Some(&Elem::Rule(k)) => { + st.last_mut().unwrap().2 += 1; + // A finished frame goes before the rule starts, so a repetition does not grow the stack. + while let Some(&(r, a, e)) = st.last() && e == self.rules[r][a].len() { st.pop(); } + for alt in 0..self.rules[k].len() { + let mut s = st.clone(); + s.push((k, alt, 0)); + self.expand(s, depth + 1, steps, out); + } + return; + } + } + } + } + + /// The stacks after the character `c`. + fn advance(&self, stacks: &[Vec<(usize, usize, usize)>], c: u32, steps: &mut usize) -> Vec> { + let mut out = vec![]; + for st in stacks { + let Some(&(r, a, e)) = st.last() else { continue }; + if let Elem::Chars(neg, rs) = &self.rules[r][a][e] && *neg != rs.iter().any(|&(lo, hi)| (lo..=hi).contains(&c)) { + let mut s = st.clone(); + s.last_mut().unwrap().2 += 1; + self.expand(s, 0, steps, &mut out); + } + } + if out.len() > 1 { (out.sort_unstable(), out.dedup()); } + out.truncate(MAX_STACKS); + out + } + + /// Whether some top could match a character from `lo` to `hi` (the start of a character split across tokens). + fn may(&self, stacks: &[Vec<(usize, usize, usize)>], lo: u32, hi: u32) -> bool { + stacks.iter().any(|st| st.last().is_some_and(|&(r, a, e)| match &self.rules[r][a][e] { + Elem::Chars(false, rs) => rs.iter().any(|&(l, h)| l <= hi && h >= lo), + Elem::Chars(true, rs) => !rs.iter().any(|&(l, h)| l <= lo && h >= hi), + Elem::Rule(_) => false, + })) + } + + /// The stacks and the unfinished UTF-8 bytes after `bytes`, or None when the grammar does not allow them. + fn feed(&self, stacks: &[Vec<(usize, usize, usize)>], part: &[u8], bytes: &[u8], steps: &mut usize) -> Option<(Vec>, Vec)> { + let buf: std::borrow::Cow<[u8]> = if part.is_empty() { bytes.into() } else { [part, bytes].concat().into() }; + let mut cur = std::borrow::Cow::Borrowed(stacks); + let mut i = 0; + while i < buf.len() { + let b = buf[i]; + let n = match b { 0..0x80 => 1, 0xc2..0xe0 => 2, 0xe0..0xf0 => 3, 0xf0..0xf5 => 4, _ => return None }; + let have = (buf.len() - i).min(n); + let mut c = if n == 1 { b as u32 } else { (b & (0x7f >> n)) as u32 }; + for &x in &buf[i + 1..i + have] { + if x & 0xc0 != 0x80 { return None; } + c = c << 6 | (x & 0x3f) as u32; + } + // The smallest code point of each length: a longer (overlong) form, such as F0 80 81 BB for "{", is not + // UTF-8, nor are surrogates. + let least = [0, 0, 0x80, 0x800, 0x10000][n]; + if have < n { + let k = 6 * (n - have) as u32; + let (lo, hi) = ((c << k).max(least), ((c << k) | ((1 << k) - 1)).min(0x10ffff)); + return (lo <= hi && self.may(&cur, lo, hi)).then(|| (cur.into_owned(), buf[i..].to_vec())); + } + if c < least || c > 0x10ffff || (0xd800..0xe000).contains(&c) { return None; } + cur = self.advance(&cur, c, steps).into(); + if cur.is_empty() { return None; } + i += n; + } + Some((cur.into_owned(), vec![])) + } +} + +/// Where a grammar is in the reply. +#[derive(Clone)] +struct Matcher { g: Arc, stacks: Vec>, part: Vec, bytes: Arc>> } + +/// The `logit_bias` and `grammar` of one request. +#[derive(Clone)] +pub struct Constraint { + bias: Vec<(u32, f32)>, + gram: Option, + /// The tokens that end the reply, which the grammar allows once it is complete. + pub eos: Vec, + /// `` while the reply is still reasoning: the grammar holds for the answer after it (as llama.cpp's), so + /// a thinking model can think before a constrained answer and the answer is not read as reasoning. + wait: Option, +} + +impl std::fmt::Debug for Constraint { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Constraint({} biases, grammar: {})", self.bias.len(), self.gram.is_some()) } +} + +impl Constraint { + /// None when the request has neither. + pub fn new(q: &crate::serve::ChatRequest, tok: &crate::tokenizer::Tokenizer) -> anyhow::Result> { + Constraint::of(&q.logit_bias, q.grammar.clone(), tok) + } + + pub fn of(bias: &[(BiasKey, f32)], grammar: Option>, tok: &crate::tokenizer::Tokenizer) -> anyhow::Result> { + if bias.is_empty() && grammar.is_none() { return Ok(None); } + let mut b = vec![]; + for (k, v) in bias { + match k { + BiasKey::Id(id) => { + ensure!((*id as usize) < tok.vocab_size(), "logit_bias: {id} is not a token id"); + b.push((*id, *v)); + } + BiasKey::Text(s) => b.extend(tok.encode(s)?.into_iter().map(|id| (id, *v))), + } + } + let gram = grammar.map(|g| { + let stacks = g.start(); + Matcher { g, stacks, part: vec![], bytes: tok.grammar_bytes() } + }); + Ok(Some(Constraint { bias: b, gram, eos: tok.eos_ids(), wait: None })) + } + + /// The reply starts inside a think block that `close` ends: the grammar waits for it. + pub fn after_think(&mut self, close: u32) { + if self.gram.is_some() { self.wait = Some(close); } + } + + /// Whether the grammar still waits for the end of the think block. + pub fn waiting(&self) -> bool { self.wait.is_some() } + + pub fn add_bias(&self, l: &mut [f32]) { + for &(t, b) in &self.bias { if let Some(x) = l.get_mut(t as usize) { *x += b; } } + } + + /// Whether the grammar allows token `t` next: an end-of-turn token only once the grammar is complete, a special + /// token never. + pub fn allows(&self, t: u32) -> bool { self.allows_in(t, &mut STEPS.clone()) } + + fn allows_in(&self, t: u32, steps: &mut usize) -> bool { + let Some(m) = &self.gram else { return true }; + if self.wait.is_some() { return true; } + if self.eos.contains(&t) { return m.part.is_empty() && m.stacks.iter().any(Vec::is_empty); } + let b = m.bytes.get(t as usize).map_or(&[][..], Vec::as_slice); + !b.is_empty() && m.g.feed(&m.stacks, &m.part, b, steps).is_some() + } + + /// Sets the logits of the tokens the grammar does not allow to -inf. + /// ponytail: one walk of the whole vocabulary (about 10 ms for 150K tokens); a token trie if that matters. + pub fn mask(&self, l: &mut [f32]) { + if self.gram.is_none() || self.wait.is_some() { return; } + let mut steps = MASK_STEPS; + for (t, x) in l.iter_mut().enumerate() { + // Each token gets at most its own budget, taken from what the mask has left. + let mut mine = steps.min(STEPS); + let left = steps - mine; + if *x != f32::NEG_INFINITY && !self.allows_in(t as u32, &mut mine) { *x = f32::NEG_INFINITY; } + steps = left + mine; + } + } + + /// The bias, then the mask when the best token is not allowed (else it is not needed for a greedy pick). + pub fn apply(&self, l: &mut [f32], greedy: bool) { + self.add_bias(l); + if !greedy || !self.allows(crate::ops::argmax(l) as u32) { self.mask(l); } + } + + /// The reply got token `t`. + pub fn accept(&mut self, t: u32) { + if let Some(close) = self.wait { + if t == close { self.wait = None; } + return; + } + let Some(m) = &mut self.gram else { return }; + if self.eos.contains(&t) { return; } + let b = m.bytes.get(t as usize).map_or(&[][..], Vec::as_slice); + (m.stacks, m.part) = m.g.feed(&m.stacks, &m.part, b, &mut STEPS.clone()).unwrap_or_default(); + } +} + +/// The greedy choice of the separate model forwards: their argmax (the last of equal logits) unchanged without a +/// constraint, else after it, and the constraint follows the token. +pub fn greedy(lim: &mut Option, logits: &mut [f32]) -> u32 { + let pick = |l: &[f32]| l.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; + let Some(c) = lim else { return pick(logits) }; + c.add_bias(logits); + let mut t = pick(logits); + if !c.allows(t) { c.mask(logits); t = pick(logits); } + c.accept(t); + t +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `after_think`: inside the think block every token goes; from `` on the grammar holds. + #[test] + fn grammar_waits_for_think_close() { + let g = Arc::new(Grammar::parse(JSON_GBNF).unwrap()); + // tokens: 0 "{", 1 "}", 2 "hello", 3 `` (special: no bytes), 4 end of turn + let bytes = Arc::new(vec![b"{".to_vec(), b"}".to_vec(), b"hello".to_vec(), vec![], vec![]]); + let mut c = Constraint { bias: vec![], gram: Some(Matcher { stacks: g.start(), g, part: vec![], bytes }), eos: vec![4], wait: None }; + c.after_think(3); + assert!(c.allows(2) && c.allows(3)); + c.accept(2); + c.accept(3); + assert!(!c.allows(2) && c.allows(0) && !c.allows(4)); + let mut l = vec![0.0; 5]; + c.mask(&mut l); + assert!(l[2] == f32::NEG_INFINITY && l[0] == 0.0); + c.accept(0); + c.accept(1); + assert!(c.allows(4)); + } + + /// Whether the grammar takes `s` whole. + fn full(g: &Grammar, s: &str) -> bool { + let st = g.start(); + match g.feed(&st, &[], s.as_bytes(), &mut STEPS.clone()) { Some((st, part)) => part.is_empty() && st.iter().any(Vec::is_empty), None => false } + } + /// Whether `s` can start a text the grammar takes. + fn prefix(g: &Grammar, s: &str) -> bool { + let st = g.start(); + g.feed(&st, &[], s.as_bytes(), &mut STEPS.clone()).is_some() + } + + + // llama.cpp grammars/arithmetic.gbnf. + const ARITH: &str = r#" +root ::= (expr "=" ws term "\n")+ +expr ::= term ([-+*/] term)* +term ::= ident | num | "(" ws expr ")" ws +ident ::= [a-z] [a-z0-9_]* ws +num ::= [0-9]+ ws +ws ::= [ \t\n]* +"#; + + // llama.cpp grammars/list.gbnf. + const LIST: &str = r#" +root ::= item+ + +# Excludes various line break characters +item ::= "- " [^\r\n\x0b\x0c\x85

]+ "\n" +"#; + + #[test] + fn response_format_schema() { + let rf = |v: &str| response_format(&serde_json::from_str(v).unwrap()).unwrap().unwrap(); + let rv = |v: &str| response_format(&serde_json::from_str(v).unwrap()); + let g = rf(r##"{"type": "json_object"}"##); + assert!(full(&g, r#"{"a": 1}"#) && !full(&g, "[1]")); + assert!(rv(r##"{"type": "text"}"##).unwrap().is_none()); + assert!(rv(r##"{"type": "xml"}"##).is_err()); + let g = rf(r##"{"type": "json_schema", "json_schema": {"name": "p", "schema": { + "type": "object", + "properties": {"name": {"type": "string"}, "age": {"type": "integer"}, "tags": {"type": "array", "items": {"enum": ["a", "b\"c"]}}, + "kind": {"$ref": "#/$defs/k"}}, + "required": ["name", "kind"], + "$defs": {"k": {"anyOf": [{"const": 1}, {"type": "null"}]}}}}}"##); + assert!(full(&g, r#"{"name": "x", "kind": 1}"#)); + assert!(full(&g, r#"{"name": "x", "age": -3, "tags": ["a", "b\"c"], "kind": null}"#)); + assert!(!full(&g, r#"{"name": "x"}"#), "kind is required"); + assert!(!full(&g, r#"{"kind": 1, "name": "x"}"#), "schema order"); + assert!(!full(&g, r#"{"name": "x", "age": 1.5, "kind": 1}"#)); + assert!(!full(&g, r#"{"name": "x", "tags": ["c"], "kind": 1}"#)); + // No required property: any subset in order, or none. + let g = rf(r##"{"type": "json_object", "schema": {"type": "object", "properties": {"a": {"type": "boolean"}, "b": {"type": "number"}}}}"##); + for t in ["{}", r#"{"a": true}"#, r#"{"b": 2.5}"#, r#"{"a": false, "b": 1}"#] { assert!(full(&g, t), "{t}"); } + assert!(!full(&g, r#"{"b": 1, "a": true}"#) && !full(&g, r#"{,"b": 1}"#)); + // A schema that refers to itself. + let g = rf(r##"{"type": "json_schema", "json_schema": {"schema": {"$ref": "#/$defs/n", "$defs": {"n": { + "type": "object", "properties": {"next": {"anyOf": [{"$ref": "#/$defs/n"}, {"type": "null"}]}}, "required": ["next"]}}}}}"##); + assert!(full(&g, r#"{"next": {"next": null}}"#) && !full(&g, "{}")); + // Explicit `"const": null` must match only `null`, not any JSON value. + let g = rf(r##"{"type": "json_schema", "json_schema": {"schema": { + "type": "object", + "properties": {"err": {"const": null}, "val": {"anyOf": [{"type": "string"}, {"const": null}]}}, + "required": ["err", "val"]}}}"##); + assert!(full(&g, r#"{"err": null, "val": null}"#)); + assert!(full(&g, r#"{"err": null, "val": "ok"}"#)); + assert!(!full(&g, r#"{"err": 1, "val": null}"#), "const: null must reject non-null"); + assert!(!full(&g, r#"{"err": "x", "val": null}"#), "const: null must reject strings"); + assert!(!full(&g, r#"{"err": null, "val": 123}"#), "anyOf string|const:null must reject numbers"); + // RFC 8259 escaped slashes and exponents containing zero digits in schema-derived JSON rules. + let g = rf(r##"{"type": "json_schema", "json_schema": {"schema": { + "type": "object", + "properties": {"url": {"type": "string"}, "scale": {"type": "number"}}, + "required": ["url", "scale"]}}}"##); + assert!(full(&g, r#"{"url": "https:\/\/example.com\/a", "scale": 1e10}"#)); + assert!(full(&g, r#"{"url": "<\/script>", "scale": 2.5e-10}"#)); + // A $ref pointing to a null definition (in a map or list) must be rejected as unresolved. + assert!(rv(r##"{"type": "json_schema", "json_schema": {"schema": {"$ref": "#/$defs/n", "$defs": {"n": null}}}}"##).is_err()); + assert!(rv(r##"{"type": "json_schema", "json_schema": {"schema": {"$ref": "#/$defs/arr/0", "$defs": {"arr": [null]}}}}"##).is_err()); + let g = rf(r##"{"type": "json_schema", "json_schema": {"schema": {"$ref": "#/$defs/arr/0", "$defs": {"arr": [{"type": "string"}]}}}}"##); + assert!(full(&g, r#""ok""#) && !full(&g, "123")); + // A large const repeated through $refs, and a $ref chain past the depth bound, are refused. + let big = "x".repeat(4000); + let refs = vec![r##"{"$ref": "#/$defs/a"}"##; 100].join(","); + assert!(rv(&format!(r##"{{"type": "json_object", "schema": {{"anyOf": [{refs}], "$defs": {{"a": {{"const": "{big}"}}}}}}}}"##)).is_ok()); + let wide = (0..100).map(|_| format!(r#"{{"const": "{big}"}}"#)).collect::>().join(","); + assert!(rv(&format!(r#"{{"type": "json_object", "schema": {{"anyOf": [{wide}]}}}}"#)).is_err()); + let defs = (0..100).map(|i| format!(r##""d{i}": {{"$ref": "#/$defs/d{}"}}"##, i + 1)).collect::>().join(","); + assert!(rv(&format!(r##"{{"type": "json_object", "schema": {{"$ref": "#/$defs/d0", "$defs": {{{defs}, "d100": {{"type": "null"}}}}}}}}"##)).is_err()); + } + + #[test] + fn json_grammar() { + let g = Grammar::parse(JSON_GBNF).unwrap(); + assert!(full(&g, r#"{"a": [1, -2.5e3, 1e10, 1e-10, 3e100, true, null], "b": {"c": "x\"\/é ✓"}}"#)); + assert!(full(&g, "{}")); + assert!(!full(&g, r#"{"a": 1,}"#)); + assert!(!full(&g, "[1]")); + assert!(!full(&g, r#"{"a": 01x}"#)); + assert!(prefix(&g, r#"{"key": [1, 2"#)); + assert!(!prefix(&g, "hello")); + // A character split across tokens: the start of "é" is allowed inside a string, not after "{". + let st = g.start(); + let (s1, p) = g.feed(&st, &[], b"{\"", &mut STEPS.clone()).unwrap(); + assert!(p.is_empty()); + let (s2, p) = g.feed(&s1, &[], &[0xc3], &mut STEPS.clone()).unwrap(); + assert_eq!(p, [0xc3]); + assert!(g.feed(&s2, &p, &[0xa9], &mut STEPS.clone()).is_some_and(|(_, p)| p.is_empty())); + assert!(g.feed(&st, &[], b"{\xc3", &mut STEPS.clone()).is_none()); + } + + #[test] + fn arithmetic_and_list_grammars() { + let g = Grammar::parse(ARITH).unwrap(); + assert!(full(&g, "1+2=3\n")); + assert!(full(&g, "(a*b_2) -7 = x\nx=1\n")); + assert!(!full(&g, "(a * b) = 1\n")); + assert!(!full(&g, "1+=3\n")); + assert!(!full(&g, "1+2=3")); + let g = Grammar::parse(LIST).unwrap(); + assert!(full(&g, "- one\n- two words\n")); + assert!(!full(&g, "- \n")); + assert!(!full(&g, "* one\n")); + } + + #[test] + fn grammar_syntax() { + let g = Grammar::parse("root ::= \"a\"{2,3} [^x]? . # note\n").unwrap(); + assert!(full(&g, "aab") && full(&g, "aaa") && full(&g, "aaaqx") && full(&g, "aaaab") && !full(&g, "aaaxq") && !full(&g, "aaaaab") && !full(&g, "ab")); + assert!(full(&Grammar::parse("root ::= (\"x\" | [0-9]){3,}").unwrap(), "x12x")); + assert!(Grammar::parse("root ::= foo").is_err()); + assert!(Grammar::parse("start ::= \"a\"").is_err()); + assert!(Grammar::parse("root ::= \"a\"\nroot ::= \"b\"").is_err()); + assert!(Grammar::parse("root ::= (\"a\"").is_err()); + // Left recursion, and grammars that are too big to write out or expand, are refused (a request's grammar). + assert!(Grammar::parse("root ::= root \"a\" | \"b\"").is_err()); + assert!(Grammar::parse(&format!("root ::= {}\"a\"{}", "(".repeat(100), ")".repeat(100))).is_err()); + assert!(Grammar::parse("root ::= \"a\"{100000}").is_err() && Grammar::parse("root ::= ((\"a\"{1000}){1000}){1000}").is_ok()); + let blow: String = (0..40).map(|i| format!("r{i} ::= r{} r{} | \"\"\n", i + 1, i + 1)).collect(); + assert!(Grammar::parse(&format!("root ::= r0\n{blow}r40 ::= \"y\"")).is_err()); + assert!(Grammar::parse(&"a".repeat(MAX_CHARS + 1)).is_err()); + // Stacks that grow with the text spend the budget by their depth and end (refused) instead of running on. + let g = Grammar::parse("root ::= \"a\" root \"b\" | \"\"").unwrap(); + assert!(full(&g, &format!("{}{}", "a".repeat(50), "b".repeat(50))) && !prefix(&g, &"a".repeat(5000))); + } + + #[test] + fn logit_bias_forms() { + use serde_json::json; + assert_eq!(parse_bias(&json!({"15": 5, "hi": -100})).unwrap(), [(BiasKey::Id(15), 5.0), (BiasKey::Text("hi".into()), f32::NEG_INFINITY)]); + assert_eq!(parse_bias(&json!([[15, false], ["hi", 1.5]])).unwrap(), [(BiasKey::Id(15), f32::NEG_INFINITY), (BiasKey::Text("hi".into()), 1.5)]); + assert!(parse_bias(&json!({"1": 101})).is_err() && parse_bias(&json!([[1]])).is_err() && parse_bias(&json!(3)).is_err()); + } +} diff --git a/src/hip/compat.h b/src/hip/compat.h new file mode 100644 index 00000000..d97ad0e7 --- /dev/null +++ b/src/hip/compat.h @@ -0,0 +1,167 @@ +// Device-side compatibility layer for the HIP backend. `src/hip/mod.rs` prepends this (and the quant tables) to +// `../cuda/kernels.cu`, which the CUDA backend hands to NVRTC unchanged: `kernels.cu` is one source with an explicit +// `STRATA_HIP` branch where the two architectures cannot share code, and this header supplies everything CUDA's +// headers give it for free (warp intrinsics, packed-byte helpers, the f16 SIMD ops) from HIP. +// +// The portable intrinsic implementations are adapted from Strata's include/strata/hip_compat/intrinsics.hpp +// (MIT, (c) 2025 Niko1221); see THANKS.md. They assume the wave32 model the kernels are written for (lane = +// threadIdx.x & 31), which is the default wavefront size on RDNA (gfx10+) — the same assumption the CUDA source +// makes about a warp. +// Prepended to a concatenated source string, so a plain include guard: `#pragma once` would warn in a main file. +#ifndef STRATA_HIP_COMPAT_H +#define STRATA_HIP_COMPAT_H +#include +#include + +// kernels.cu selects its code paths by the CUDA architecture level: ldmatrix from sm_75, cp.async/m16n8k16/int8-mma +// from sm_80, m8n8k4 (mma884) from sm_70. AMD has none of those instructions, so the build takes the portable +// pre-Volta level: per-lane shared loads instead of ldmatrix, plain typed copies instead of cp.async, and the +// CUDA-core (f16 FMA) multiplicands instead of mma.sync. On gfx11 and gfx12 the prefill GEMM and attention use the +// WMMA matrix cores instead (GEMM_WMMA, below); other targets and STRATA_HIP_WMMA=0 keep the f16 FMA path. Decode is +// unaffected (it has no tensor-core path). +#ifndef __CUDA_ARCH__ +#define __CUDA_ARCH__ 700 +#endif +#define STRATA_HIP 1 +#ifndef __forceinline__ +#define __forceinline__ inline __attribute__((always_inline)) +#endif +#ifndef __align__ +#define __align__(n) __attribute__((aligned(n))) +#endif +// The wave is 32 lanes wide here; a kernel that ever runs with a 64-wide wave would corrupt its reductions. +#if defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32 +#error "the HIP backend needs wave32 (RDNA); wave64 targets are not supported" +#endif + +namespace strata_hip { + +__device__ __forceinline__ int signed_byte(unsigned word, int lane) { + unsigned v = (word >> (lane * 8)) & 0xffu; + return v < 0x80u ? (int)v : (int)v - 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(__gfx1103__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1200__) || defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4) + return __builtin_amdgcn_sudot4(true, a, true, b, c, false); +#elif (defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__)) && __has_builtin(__builtin_amdgcn_sdot4) + return __builtin_amdgcn_sdot4(a, b, c, false); +#else + unsigned ua = (unsigned)a, ub = (unsigned)b, sum = (unsigned)c; +#pragma unroll + for (int i = 0; i < 4; ++i) sum += (unsigned)(signed_byte(ua, i) * signed_byte(ub, i)); + return (int)sum; +#endif +} + +// CUDA's __byte_perm: result byte i is byte s.nibble[i] & 7 of {y:x}. One v_perm_b32 instead of HIP's byte array. +__device__ __forceinline__ unsigned byte_perm(unsigned x, unsigned y, unsigned s) { + unsigned sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12); + return __builtin_amdgcn_perm(y, x, sel); +} + +// Packed byte arithmetic, four lanes at once (SWAR, Hacker's Delight 2-18): gfx11/gfx12 have no packed 8-bit +// add/sub, and a per-lane loop costs the Q3_K/Q6_K dots several times the instructions. +constexpr unsigned kHigh = 0x80808080u; + +__device__ __forceinline__ int vsub4(int a, int b) { + unsigned ua = (unsigned)a, ub = (unsigned)b; + return (int)(((ua | kHigh) - (ub & ~kHigh)) ^ ((ua ^ ~ub) & kHigh)); +} +__device__ __forceinline__ int vadd4(int a, int b) { + unsigned ua = (unsigned)a, ub = (unsigned)b; + return (int)(((ua & ~kHigh) + (ub & ~kHigh)) ^ ((ua ^ ub) & kHigh)); +} + +// The mask is informational here: an AMD wave either takes part in the corresponding `ds_bpermute` or does not, so a +// lane that is not in the mask still receives whatever the exchange computes (CUDA leaves it undefined). That matches +// CUDA whenever the lanes a participating lane exchanges with are participating too, which is how kernels.cu uses it +// (`quant8` shuffles inside groups of four active lanes; the rest pass 0xffffffff). +template __device__ __forceinline__ T shfl_xor_sync(unsigned, T v, int lane_mask, int width = 32) { return __shfl_xor(v, lane_mask, width); } +template __device__ __forceinline__ T shfl_down_sync(unsigned, T v, unsigned d, int width = 32) { return __shfl_down(v, d, width); } +template __device__ __forceinline__ T shfl_up_sync(unsigned, T v, unsigned d, int width = 32) { return __shfl_up(v, d, width); } +template __device__ __forceinline__ T shfl_sync(unsigned, T v, int src, int width = 32) { return __shfl(v, src, width); } +__device__ __forceinline__ unsigned ballot_sync(unsigned, int predicate) { return (unsigned)__ballot(predicate); } +__device__ __forceinline__ int any_sync(unsigned, int predicate) { return (int)(__ballot(predicate) != 0); } +// CUDA's __ldcg loads through L2 only, so a block reads what other blocks wrote (the split-K segments). hiprtc +// declares it only for halves; agent-scope atomic loads skip the CU's L1 the same way. +__device__ __forceinline__ float4 ldcg(const float4* p) { + const float* f = (const float*)p; + return make_float4(__hip_atomic_load(f, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT), __hip_atomic_load(f + 1, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT), + __hip_atomic_load(f + 2, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT), __hip_atomic_load(f + 3, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT)); +} + +// ---- matrix cores (gfx11/gfx12 WMMA) ---- +// D[16x16] += A[16x16] * B^T[16x16]: both operands are 16 rows of 16 halves, which is exactly how the prefill GEMM +// stages X (positions) and W (output rows) in shared memory, so no transpose is needed. Each lane supplies the +// k-values of its own row of both operands and holds 8 results of column lane & 15, in rows STRATA_WMMA_ROW(lane, i). +// gfx12 splits the k dimension across the two half-waves (each lane gives 8 halves, lanes 16-31 the upper half) and +// gives lanes 16-31 rows 8..15; gfx11 takes all 16 halves from every lane (lanes 16-31 repeat lanes 0-15) and +// interleaves the rows, even ones in lanes 0-15 and odd ones in lanes 16-31 (as llama.cpp's mma.cuh has it for RDNA3). +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1152__) +#define STRATA_WMMA 1 +#define STRATA_WMMA_K 16 +#define STRATA_WMMA_ROW(lane, i) (2 * (i) + ((lane) >> 4)) +#elif defined(__gfx1200__) || defined(__gfx1201__) +#define STRATA_WMMA 1 +#define STRATA_WMMA_K 8 +#define STRATA_WMMA_ROW(lane, i) (8 * ((lane) >> 4) + (i)) +#else +#define STRATA_WMMA 0 +#define STRATA_WMMA_K 0 +#endif +// First k half the lane supplies: gfx12 lanes 16-31 give k 8..15, every lane on gfx11 gives k 0..15. +#define STRATA_WMMA_K0(lane) (((lane) >> 4) * (16 - STRATA_WMMA_K)) + +#if STRATA_WMMA +typedef _Float16 strata_hk __attribute__((ext_vector_type(STRATA_WMMA_K))); +typedef float strata_f8 __attribute__((ext_vector_type(8))); + +__device__ __forceinline__ strata_f8 strata_wmma(strata_hk a, strata_hk b, strata_f8 c) { +#if defined(__gfx1200__) || defined(__gfx1201__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +#else + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#endif +} + +/// STRATA_WMMA_K halves at `p` (16-byte aligned); lanes 16-31 read their own upper half of the same row. +__device__ __forceinline__ strata_hk strata_ld_wmma(const unsigned short* p) { + union { uint4 u[STRATA_WMMA_K / 8]; strata_hk h; } c; +#pragma unroll + for (int i = 0; i < STRATA_WMMA_K / 8; i++) c.u[i] = *(const uint4*)(p + 8 * i); + return c.h; +} + +/// The same STRATA_WMMA_K halves one tile row apart from each other: the B operand when the operand's rows are the +/// transposed side (the prefill attention's V, whose rows are head dimensions and whose k are keys). One load a have +/// instead of a 16-byte vector load. +__device__ __forceinline__ strata_hk strata_ld_wmma_t(const unsigned short* p, int stride) { + strata_hk r; +#pragma unroll + for (int i = 0; i < STRATA_WMMA_K; i++) r[i] = *(const _Float16*)(p + i * stride); + return r; +} +#endif + +} // namespace strata_hip + +#define __dp4a(a, b, c) (strata_hip::dp4a((a), (b), (c))) +#define __byte_perm(x, y, s) (strata_hip::byte_perm((x), (y), (s))) +#define __vsub4(a, b) (strata_hip::vsub4((a), (b))) +#define __vadd4(a, b) (strata_hip::vadd4((a), (b))) +#define __shfl_xor_sync(...) (strata_hip::shfl_xor_sync(__VA_ARGS__)) +#define __shfl_down_sync(...) (strata_hip::shfl_down_sync(__VA_ARGS__)) +#define __shfl_up_sync(...) (strata_hip::shfl_up_sync(__VA_ARGS__)) +#define __shfl_sync(...) (strata_hip::shfl_sync(__VA_ARGS__)) +#define __ballot_sync(m, p) (strata_hip::ballot_sync((m), (p))) +#define __any_sync(m, p) (strata_hip::any_sync((m), (p))) +#define __ldcg(p) (strata_hip::ldcg(p)) +// The compiled-out sm_80+ paths still mention these; no CUDA-only helper may survive into a HIP build. +#define __trap() __builtin_trap() +#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1) + +#endif // STRATA_HIP_COMPAT_H diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs new file mode 100644 index 00000000..c5c5e08a --- /dev/null +++ b/src/hip/ffi.rs @@ -0,0 +1,374 @@ +//! HIP runtime and hiprtc, loaded by name like `cuda/nvrtc.rs` loads NVRTC: no ROCm headers, link flags or `hipcc` +//! at build time, and no C++ build step. Every entry point the backend uses is resolved once per process. + +use anyhow::{Context, bail}; +use libloading::Library; +use std::ffi::{CStr, c_char, c_int, c_void}; +use std::path::PathBuf; +use std::sync::OnceLock; + +pub type Stream = *mut c_void; +pub type Module = *mut c_void; +pub type Func = *mut c_void; +pub type Event = *mut c_void; +pub type Graph = *mut c_void; +pub type GraphExec = *mut c_void; +pub type RtcProgram = *mut c_void; + +// hipError_t / hiprtcResult +pub const HIP_SUCCESS: c_int = 0; + +// Values the ROCm 7 headers give these enums (probe-printed; see the module docs of `hip`). +pub const MEMCPY_H2D: c_int = 1; +pub const MEMCPY_D2H: c_int = 2; +pub const MEMCPY_D2D: c_int = 3; +pub const HOST_MALLOC_PORTABLE: u32 = 1; +pub const HOST_MALLOC_MAPPED: u32 = 2; +pub const HOST_REGISTER_PORTABLE: u32 = 1; +pub const HOST_REGISTER_READ_ONLY: u32 = 8; +pub const EVENT_DISABLE_TIMING: u32 = 2; +pub const STREAM_NON_BLOCKING: u32 = 1; +pub const CAPTURE_MODE_THREAD_LOCAL: c_int = 1; +pub const ATTR_MAX_DYNAMIC_SHARED: c_int = 8; +pub const ATTR_SHARED_PER_BLOCK_OPTIN: c_int = 75; +pub const ATTR_SHARED_PER_BLOCK: c_int = 74; +pub const ATTR_WARP_SIZE: c_int = 87; +/// `hipDeviceAttributeMultiprocessorCount`: compute units, or half of them in WGP mode. +pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; + +/// Room for `hipDeviceProp_t`, which `hipGetDeviceProperties` writes whole. ROCm 7's `hipDeviceProp_tR0600` is 1472 +/// bytes; the size is not exported and changes between versions, so the buffer leaves ample room for a larger one. +/// The architecture name is found by shape (`find_gfx`), and `STRATA_HIP_ARCH` overrides it. +const PROP_BUF: usize = 16 << 10; + +/// The first `gfxNNNN`-looking string at a 4-byte offset in `bytes` (at least 6 characters, at most 16), read only +/// within `bytes`. +fn find_gfx(bytes: &[u8]) -> Option { + for i in (0..bytes.len()).step_by(4) { + let w = &bytes[i..(i + 16).min(bytes.len())]; + if !w.starts_with(b"gfx") { continue } + let end = w.iter().position(|&b| b == 0 || !b.is_ascii_alphanumeric()).unwrap_or(w.len()); + if end < 6 { continue } + return String::from_utf8(w[..end].to_vec()).ok(); + } + None +} + +/// Library names to try, in order. `STRATA_HIP` (a path or a name) replaces the whole list. +fn candidates(vars: Option, default_suffix: &[&str]) -> Vec { + if let Some(p) = vars { return vec![p]; } + let mut v: Vec = Vec::new(); + for s in default_suffix { v.push(PathBuf::from(s)); } + // A ROCm install that is not on the loader path (`/opt/rocm` may be a symlink chain). + for root in ["/opt/rocm/lib", "/opt/rocm/core-10.1/lib", "/usr/lib/x86_64-linux-gnu", "/usr/local/lib"] { + for s in default_suffix { v.push(PathBuf::from(root).join(s)); } + } + v +} + +pub struct Hip { + pub init: unsafe extern "C" fn(c_int) -> c_int, + pub device_count: unsafe extern "C" fn(*mut c_int) -> c_int, + pub set_device: unsafe extern "C" fn(c_int) -> c_int, + pub device_name: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int, + pub device_attribute: unsafe extern "C" fn(*mut c_int, c_int, c_int) -> c_int, + pub mem_get_info: unsafe extern "C" fn(*mut usize, *mut usize) -> c_int, + pub malloc: unsafe extern "C" fn(*mut *mut c_void, usize) -> c_int, + pub free: unsafe extern "C" fn(*mut c_void) -> c_int, + pub memset_async: unsafe extern "C" fn(*mut c_void, c_int, usize, Stream) -> c_int, + pub memcpy: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int) -> c_int, + pub memcpy_async: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int, Stream) -> c_int, + pub stream_create: unsafe extern "C" fn(*mut Stream, u32) -> c_int, + pub stream_sync: unsafe extern "C" fn(Stream) -> c_int, + pub stream_begin_capture: unsafe extern "C" fn(Stream, c_int) -> c_int, + pub stream_end_capture: unsafe extern "C" fn(Stream, *mut Graph) -> c_int, + pub stream_is_capturing: unsafe extern "C" fn(Stream, *mut c_int) -> c_int, + pub graph_instantiate: unsafe extern "C" fn(*mut GraphExec, Graph, u64) -> c_int, + pub graph_launch: unsafe extern "C" fn(GraphExec, Stream) -> c_int, + pub graph_exec_destroy: unsafe extern "C" fn(GraphExec) -> c_int, + pub graph_destroy: unsafe extern "C" fn(Graph) -> c_int, + pub event_create: unsafe extern "C" fn(*mut Event, u32) -> c_int, + pub event_record: unsafe extern "C" fn(Event, Stream) -> c_int, + pub event_sync: unsafe extern "C" fn(Event) -> c_int, + pub event_destroy: unsafe extern "C" fn(Event) -> c_int, + pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> c_int, + pub host_malloc: unsafe extern "C" fn(*mut *mut c_void, usize, u32) -> c_int, + pub host_free: unsafe extern "C" fn(*mut c_void) -> c_int, + pub host_device_ptr: unsafe extern "C" fn(*mut *mut c_void, *mut c_void, u32) -> c_int, + pub host_register: unsafe extern "C" fn(*mut c_void, usize, u32) -> c_int, + pub host_unregister: unsafe extern "C" fn(*mut c_void) -> c_int, + pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> c_int, + pub function: unsafe extern "C" fn(*mut Func, Module, *const c_char) -> c_int, + pub launch: unsafe extern "C" fn(Func, u32, u32, u32, u32, u32, u32, u32, Stream, *mut *mut c_void, *mut *mut c_void) -> c_int, + pub func_set_attribute: unsafe extern "C" fn(*const c_void, c_int, c_int) -> c_int, + pub error_string: unsafe extern "C" fn(c_int) -> *const c_char, + _lib: Library, +} + +impl Hip { + /// The runtime, or an error naming what was missing. "HIP init" lets `backend::open` fall back to Vulkan. + pub fn open() -> anyhow::Result { + let want = candidates(std::env::var_os("STRATA_HIP").map(Into::into), + &["libamdhip64.so", "libamdhip64.so.7", "libamdhip64.so.6"]); + let mut tried = Vec::new(); + for path in &want { + if let Ok(lib) = unsafe { Library::new(path) } { + if let Some(h) = unsafe { Self::bind(lib) } { return Ok(h); } + tried.push(format!("{}: missing symbols", path.display())); + } else { + tried.push(format!("{}: not loadable", path.display())); + } + } + Err(anyhow::anyhow!("no HIP runtime: {}", tried.join(", "))).context("HIP init") + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } + + unsafe fn bind(lib: Library) -> Option { + macro_rules! g { ($n:literal) => { unsafe { Self::sym(&lib, $n)? } } } + Some(Hip { + init: g!("hipInit"), + device_count: g!("hipGetDeviceCount"), + set_device: g!("hipSetDevice"), + device_name: g!("hipDeviceGetName"), + device_attribute: g!("hipDeviceGetAttribute"), + mem_get_info: g!("hipMemGetInfo"), + malloc: g!("hipMalloc"), + free: g!("hipFree"), + memset_async: g!("hipMemsetAsync"), + memcpy: g!("hipMemcpy"), + memcpy_async: g!("hipMemcpyAsync"), + stream_create: g!("hipStreamCreateWithFlags"), + stream_sync: g!("hipStreamSynchronize"), + stream_begin_capture: g!("hipStreamBeginCapture"), + stream_end_capture: g!("hipStreamEndCapture"), + stream_is_capturing: g!("hipStreamIsCapturing"), + graph_instantiate: g!("hipGraphInstantiateWithFlags"), + graph_launch: g!("hipGraphLaunch"), + graph_exec_destroy: g!("hipGraphExecDestroy"), + graph_destroy: g!("hipGraphDestroy"), + event_create: g!("hipEventCreateWithFlags"), + event_record: g!("hipEventRecord"), + event_sync: g!("hipEventSynchronize"), + event_destroy: g!("hipEventDestroy"), + stream_wait_event: g!("hipStreamWaitEvent"), + host_malloc: g!("hipHostMalloc"), + host_free: g!("hipHostFree"), + host_device_ptr: g!("hipHostGetDevicePointer"), + host_register: g!("hipHostRegister"), + host_unregister: g!("hipHostUnregister"), + module_load: g!("hipModuleLoadData"), + function: g!("hipModuleGetFunction"), + launch: g!("hipModuleLaunchKernel"), + func_set_attribute: g!("hipFuncSetAttribute"), + error_string: g!("hipGetErrorString"), + _lib: lib, + }) + } + + pub fn err(&self, code: c_int) -> String { + let s = unsafe { (self.error_string)(code) }; + if s.is_null() { return format!("hip error {code}") } + unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned() + } + + pub fn check(&self, code: c_int, what: &str) -> anyhow::Result<()> { + if code == HIP_SUCCESS { return Ok(()) } + bail!("{what}: {}", self.err(code)) + } + + /// The device's `gfxNNNN` target, from `hipDeviceProp_t`'s `gcnArchName`. `STRATA_HIP_ARCH` overrides it. + /// ROCm 7 dropped the `hipDeviceAttributeArch`/`GcnArchName` attributes, so the property struct is the only + /// source; it is version-specific, hence the field-length and shape check before the value is trusted. + pub fn arch(&self, device: c_int) -> anyhow::Result { + if let Ok(a) = std::env::var("STRATA_HIP_ARCH") { return Ok(a) } + if let Some(a) = self.prop_arch(device) { return Ok(a) } + bail!("cannot read the device's gfx architecture; set STRATA_HIP_ARCH (e.g. gfx1201)") + } + + /// The device property struct is version-specific (`hipDeviceProp_t` and `hipDeviceProp_tR0600` differ, and ROCm 7 + /// resolves `hipGetDeviceProperties` to the latter), so the target name is found by shape inside the struct + /// instead of at a fixed offset: the first `gfxNNNN`-looking string, validated. + fn prop_arch(&self, device: c_int) -> Option { + // Resolved here and not in `bind`: this is the only use, and a missing symbol must not fail the backend. + let f: unsafe extern "C" fn(*mut c_void, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipGetDeviceProperties") }?; + let mut buf = vec![0u64; PROP_BUF / 8]; + let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; + if r != HIP_SUCCESS { return None } + find_gfx(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_BUF) }) + } + + /// The device's PCI address as sysfs names it ("0000:0c:00.0"), or None when the runtime does not give it. + pub fn pci_bus_id(&self, device: c_int) -> Option { + let f: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipDeviceGetPCIBusId") }?; + let mut buf = [0 as c_char; 64]; + if unsafe { f(buf.as_mut_ptr(), 64, device) } != HIP_SUCCESS { return None } + Some(unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().to_lowercase()) + } + + pub fn device_name(&self, device: c_int) -> String { + let mut buf = [0 as c_char; 256]; + let r = unsafe { (self.device_name)(buf.as_mut_ptr(), 256, device) }; + if r != HIP_SUCCESS { return "AMD GPU".into() } + unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().into_owned() + } + + pub fn attribute(&self, attr: c_int, device: c_int) -> anyhow::Result { + let mut v = 0; + self.check(unsafe { (self.device_attribute)(&mut v, attr, device) }, "hipDeviceGetAttribute")?; + Ok(v) + } +} + +pub struct Rtc { + version: unsafe extern "C" fn(*mut c_int, *mut c_int) -> c_int, + create: unsafe extern "C" fn(*mut RtcProgram, *const c_char, *const c_char, c_int, *const *const c_char, *const *const c_char) -> c_int, + compile: unsafe extern "C" fn(RtcProgram, c_int, *const *const c_char) -> c_int, + log_size: unsafe extern "C" fn(RtcProgram, *mut usize) -> c_int, + log: unsafe extern "C" fn(RtcProgram, *mut c_char) -> c_int, + code_size: unsafe extern "C" fn(RtcProgram, *mut usize) -> c_int, + code: unsafe extern "C" fn(RtcProgram, *mut c_char) -> c_int, + destroy: unsafe extern "C" fn(*mut RtcProgram) -> c_int, + error_string: unsafe extern "C" fn(c_int) -> *const c_char, + lib_path: PathBuf, + _lib: Library, +} + +static RTC: OnceLock> = OnceLock::new(); + +impl Rtc { + /// The library, or which paths were tried and why each failed. + pub fn get() -> Result<&'static Rtc, &'static str> { RTC.get_or_init(Self::open).as_ref().map_err(|e| e.as_str()) } + + fn open() -> Result { + let want = candidates(std::env::var_os("STRATA_HIPRTC").map(Into::into), + &["libhiprtc.so", "libhiprtc.so.7", "libhiprtc.so.6"]); + let mut tried = Vec::new(); + for path in &want { + let lib = match unsafe { Library::new(path) } { + Ok(l) => l, + Err(e) => { tried.push(format!("{}: not loadable ({e})", path.display())); continue } + }; + unsafe { + macro_rules! g { ($n:literal) => { match Self::sym(&lib, $n) { Some(f) => f, None => { tried.push(format!("{}: no {}", path.display(), $n)); continue } } } } + return Ok(Rtc { + version: g!("hiprtcVersion"), + create: g!("hiprtcCreateProgram"), + compile: g!("hiprtcCompileProgram"), + log_size: g!("hiprtcGetProgramLogSize"), + log: g!("hiprtcGetProgramLog"), + code_size: g!("hiprtcGetCodeSize"), + code: g!("hiprtcGetCode"), + destroy: g!("hiprtcDestroyProgram"), + error_string: g!("hiprtcGetErrorString"), + lib_path: path.clone(), + _lib: lib, + }); + } + } + Err(format!("no hiprtc: {}", tried.join(", "))) + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } + + pub fn version(&self) -> (i32, i32) { + let (mut maj, mut min) = (0, 0); + unsafe { (self.version)(&mut maj, &mut min) }; + (maj, min) + } + + fn err(&self, code: c_int) -> String { + let s = unsafe { (self.error_string)(code) }; + if s.is_null() { return format!("hiprtc error {code}") } + unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned() + } + + /// Directories holding `hip/hip_runtime.h`: hiprtc compiles a string in a scratch directory, so the ROCm headers + /// have to be named. Found next to the loaded `libhiprtc` and through the environment. + fn include_dirs(&self) -> Vec { + let mut v = Vec::new(); + for k in ["ROCM_PATH", "HIP_PATH"] { + if let Some(p) = std::env::var_os(k) { v.push(PathBuf::from(p).join("include")); } + } + if let Some(dir) = self.lib_path.parent() { + // libhiprtc.so -> /lib, headers in /include (also /include/hip). + v.push(dir.join("../include")); + } + for p in ["/opt/rocm/include", "/usr/include", "/usr/local/include"] { v.push(PathBuf::from(p)); } + v.retain(|p| p.join("hip/hip_runtime.h").exists()); + v + } + + /// Compile `src` to an AMDGPU code object for `arch` (`gfx1201`). `name` only labels diagnostics. + pub fn compile(&self, src: &str, name: &str, arch: &str, extra: &[&str]) -> anyhow::Result> { + let csrc = std::ffi::CString::new(src).context("kernel source contains a NUL byte")?; + let cname = std::ffi::CString::new(name)?; + let mut prog: RtcProgram = std::ptr::null_mut(); + let code = unsafe { (self.create)(&mut prog, csrc.as_ptr(), cname.as_ptr(), 0, std::ptr::null(), std::ptr::null()) }; + if code != HIP_SUCCESS { bail!("hiprtcCreateProgram: {}", self.err(code)) } + let guard = ProgGuard { prog, destroy: self.destroy }; + let mut opts: Vec = vec![ + std::ffi::CString::new(format!("--offload-arch={arch}"))?, + std::ffi::CString::new("-O3")?, + std::ffi::CString::new("--std=c++17")?, + ]; + for dir in self.include_dirs() { opts.push(std::ffi::CString::new(format!("-I{}", dir.display()))?); } + for e in extra { opts.push(std::ffi::CString::new(*e)?); } + let ptrs: Vec<*const c_char> = opts.iter().map(|o| o.as_ptr()).collect(); + let code = unsafe { (self.compile)(guard.prog, ptrs.len() as c_int, ptrs.as_ptr()) }; + let mut logsize = 0usize; + unsafe { (self.log_size)(guard.prog, &mut logsize) }; + if logsize > 1 { + let mut log = vec![0 as c_char; logsize]; + unsafe { (self.log)(guard.prog, log.as_mut_ptr()) }; + let text = unsafe { CStr::from_ptr(log.as_ptr()) }.to_string_lossy(); + if code != HIP_SUCCESS { bail!("hiprtc ({arch}): {}\n{}", self.err(code), text.trim_end()) } + let text = text.trim_end(); + if !text.is_empty() { eprintln!("hiprtc {name} ({arch}): {text}") } + } else if code != HIP_SUCCESS { + bail!("hiprtc ({arch}): {}", self.err(code)) + } + let mut n = 0usize; + unsafe { (self.code_size)(guard.prog, &mut n) }; + anyhow::ensure!(n > 0, "hiprtc produced no code for {arch}"); + let mut code_obj = vec![0u8; n]; + let r = unsafe { (self.code)(guard.prog, code_obj.as_mut_ptr().cast()) }; + if r != HIP_SUCCESS { bail!("hiprtcGetCode: {}", self.err(r)) } + Ok(code_obj) + } +} + +struct ProgGuard { + prog: RtcProgram, + destroy: unsafe extern "C" fn(*mut RtcProgram) -> c_int, +} + +impl Drop for ProgGuard { + fn drop(&mut self) { unsafe { (self.destroy)(&mut self.prog) }; } +} + +#[cfg(test)] +mod tests { + use super::find_gfx; + + /// The name is found at the end of the buffer without reading past it, a short `gfx` is passed over, and a + /// buffer without one gives None. + #[test] + fn find_gfx_reads_only_inside_the_buffer() { + let mut b = vec![0u8; 64]; + b[8..11].copy_from_slice(b"gfx"); + b[56..63].copy_from_slice(b"gfx1201"); + assert_eq!(find_gfx(&b).as_deref(), Some("gfx1201")); + assert_eq!(find_gfx(&b[..60]), None); + let mut tail = vec![0u8; 61]; + tail[52..61].copy_from_slice(b"gfx1100ab"); + assert_eq!(find_gfx(&tail).as_deref(), Some("gfx1100ab")); + assert_eq!(find_gfx(&[0u8; 32]), None); + } +} diff --git a/src/hip/mod.rs b/src/hip/mod.rs new file mode 100644 index 00000000..64a53ded --- /dev/null +++ b/src/hip/mod.rs @@ -0,0 +1,1873 @@ +//! HIP (ROCm) backend: the same `kernels.cu` as `cuda`, with `STRATA_HIP` selecting its portable code paths, compiled +//! at run time by hiprtc for the device's `gfx` target and launched through the HIP runtime loaded by name (see +//! `ffi` and `compat.h`). No ROCm headers, no `hipcc`, no C++ build step: `cargo build --release` and `--backend hip`. +//! +//! The device side is one source: `kernels.cu` keeps its CUDA paths behind `#if !STRATA_HIP`, and `compat.h` supplies +//! what CUDA's headers give it for free. On RDNA the kernel is compiled as wave32 (lane = threadIdx.x & 31), which is +//! the assumption the source already makes about a warp. +//! +//! Status: the host layer and the wave32 device build are in place; ops are being wired up one family at a time +//! against the CPU reference (`cargo test --release hip`). Everything not yet ported returns an error naming the op, +//! so a run says exactly which kernel is missing instead of computing silently wrong numbers. + +use crate::backend::{ATT_SPLITS, ATT_SPLITS_1, Backend, Buf, GpuTensor, GEMM_BM, SAME_X}; +use crate::cuda::{AMAX_PARTS, FA_BK, attn_prefill_smem_bk, dyn_shmem_need, kname, rpw_from, gemv_block_from, tuned}; +use crate::quant::GgmlType; +use anyhow::{Context, bail}; +use std::any::Any; +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::{Arc, LazyLock, Mutex}; + +/// `STRATA_HIP_SYNC`: one sync per launch (see `Gpu::launch`). +static SYNC_EACH: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_SYNC").is_some()); +/// `STRATA_NO_GRAPH` / `STRATA_HIP_GRAPH=0`: run the forward every time instead of capturing it. +static NO_GRAPH: LazyLock = LazyLock::new(|| { + std::env::var_os("STRATA_NO_GRAPH").is_some() || std::env::var("STRATA_HIP_GRAPH").map(|v| v == "0").unwrap_or(false) +}); +/// `STRATA_HIP_TRACE`: name every launch before it goes out, so a fault that kills the process names the kernel. +static TRACE: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_TRACE").is_some()); + +mod ffi; + +pub struct Gpu { + /// The runtime, shared with every allocation and graph so none of them outlives the library that frees it. + hip: Arc, + device: usize, + stream: ffi::Stream, + /// The copy queue of `htod_side`, and the events its marks are recorded in (reused round robin: a wait already + /// queued keeps the record it saw). + side: ffi::Stream, + marks: Vec, + next_mark: std::sync::atomic::AtomicUsize, + /// Host ranges `pin_host` registered (start, end, the device address of start or 0): `htod` copies from them + /// directly, and `host_ptr` hands kernels the device address. + pinned: std::sync::RwLock>, + /// Inside `beside`: `htod` copies go to `side` instead of `stream`. + beside: std::sync::atomic::AtomicBool, + /// The mark of the last `beside`'s copies on `side`; the next `beside` makes the main queue wait on it. + beside_lag: Mutex>, + fns: HashMap, + /// "gfx1201": the target hiprtc compiled for. + arch: String, + /// `--kv q8` (the kernels were compiled with `KV_MODE` 0 or 1; HIP has no q4/q2 cache rows). + /// (0 = f16, 1 = q8, 2 = q4, 3 = q2, 4 = turbo4, 5 = turbo3, 6 = turbo2). + pub kv_mode: u32, + pub kv_k_mode: u32, + pub kv_v_mode: u32, + /// The Inkling 2 kernel-choice flags (`STRATA_DS_FAST_KERNELS` and friends), read once at creation. + flags: crate::cuda::InkFlags, + /// The card's PCI address ("0000:0c:00.0"), read once: `mem_info` finds the card's sysfs entry by it. + pci: Option, + /// Opt-in shared memory per block on this device (64 KiB on RDNA). + max_smem: usize, + /// Compute units (or workgroup processors), for key splits in kernels that loop over a query's keys. + sms: usize, + /// Kernels that only exist on the matrix cores, fixed at creation with the source they were compiled from: + /// `mla_attn_wmma` (WMMA compiled in, `STRATA_MLA_SIMT` unset) and `idx_score_wmma` (also `STRATA_IDX_WMMA=1`). + mla_wmma: bool, + idx_wmma: bool, + /// `argmax_rows` partials. + am: Buf, + /// Recorded graphs by `Backend::graph` key. + graphs: Mutex>, + /// Set when a capture or instantiate on this device failed for want of memory: captures are then skipped here and + /// every forward runs its ops directly. Per device, so one card's out-of-memory does not cost the others their + /// graphs. + graph_failed: std::sync::atomic::AtomicBool, + /// Rope frequency tables, `base` and `n_rot` to the device buffer that holds them. + fr: Mutex<(HashMap<(u32, usize), Buf>, Vec<(f32, usize)>)>, + /// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next + /// region while the card reads the previous one (expert streaming in prefill). + staging: Mutex, +} + +// The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` +// requires `Send`: transfers, launches and synchronization may come from any thread. +unsafe impl Send for Gpu {} + +struct Graph { + exec: ffi::GraphExec, + graph: ffi::Graph, + hip: Arc, +} + +impl Drop for Graph { + fn drop(&mut self) { + unsafe { + (self.hip.graph_exec_destroy)(self.exec); + (self.hip.graph_destroy)(self.graph); + } + } +} + +/// One launch: grid and block dimensions and the dynamic shared memory the kernel asks for. +#[derive(Clone, Copy)] +pub struct LaunchConfig { + pub grid_dim: (u32, u32, u32), + pub block_dim: (u32, u32, u32), + pub shared_mem_bytes: u32, +} + +pub fn cfg(grid: (u32, u32), block: u32, smem: u32) -> LaunchConfig { + LaunchConfig { grid_dim: (grid.0, grid.1, 1), block_dim: (block, 1, 1), shared_mem_bytes: smem } +} + +/// Launch kernel `$name` with `cfg`. Every argument is evaluated into a local, so `hipModuleLaunchKernel` reads it +/// from a live address; the type of the expression gives the parameter width, as the kernel's signature expects. +macro_rules! launch { + ($g:expr, $name:expr, $cfg:expr, $($a:expr),* $(,)?) => {{ + let c = $cfg; + $g.launch(&$name, c, &mut [ $(&mut { $a } as &mut dyn Any),* ]) + .with_context(|| format!("launch {}", $name))?; + }}; +} + +/// `kernels.cu` assembled for hiprtc: the compatibility layer, the quant tables, the compile-time switches, the file. +fn source(k_mode: u32, v_mode: u32, hip_wmma: bool) -> String { + use crate::quant::tables::*; + let join = |v: Vec| v.join(","); + format!( + "{}\n\ + __device__ const unsigned long long iq2xs_grid[512] = {{{}}};\n\ + __device__ const unsigned long long iq2xxs_grid[256] = {{{}}};\n\ + __device__ const unsigned long long iq2s_grid[1024] = {{{}}};\n\ + __device__ const unsigned long long iq1s_grid[2048] = {{{}}};\n\ + __device__ const unsigned int iq3xxs_grid[256] = {{{}}};\n\ + __device__ const unsigned int iq3s_grid[512] = {{{}}};\n\ + __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ + __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ + __device__ const float tq_lut[4096] = {{{}}};\n\ + #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define K_MODE {}\n#define V_MODE {}\n#define TQ_KBITS {}\n#define TQ_VBITS {}\n#define GEMM_TC 0\n#define GEMM_WMMA (STRATA_WMMA && {})\n\ + #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS 1\n#define GEMV_LOADW {}\n\ + #define FA_BQ {}\n#define FA_BK {}\n{}", + include_str!("compat.h"), + join(IQ2XS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ2XXS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ2S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ1S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ3XXS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ3S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(KSIGNS_IQ2XS.iter().map(|v| v.to_string()).collect()), + join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), + join(crate::quant::TQ_LUT.iter().flatten().map(|v| format!("{v:e}f")).collect()), + crate::cuda::llama_numerics() as u8, + k_mode as u8, + k_mode as u8, + v_mode as u8, + crate::cuda::tq_bits(k_mode), + crate::cuda::tq_bits(v_mode), + hip_wmma as u8, + GEMM_BM, + crate::cuda::GEMM_BK, + tuned(std::env::var("STRATA_GEMV_LOADW").ok().as_deref(), 0, |v| v <= 1), + crate::cuda::FA_BQ, + crate::cuda::FA_BK, + include_str!("../cuda/kernels.cu"), + ) +} + +/// Cache key for a compiled code object: the source, the target and the hiprtc version. +fn cache_key(src: &str, arch: &str, rtc: &str) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (src, arch, rtc).hash(&mut h); + h.finish() +} + +impl Gpu { + pub fn new(device: usize) -> anyhow::Result { + let (kv_k_mode, kv_v_mode) = (crate::cuda::kv_k_mode(), crate::cuda::kv_v_mode()); + anyhow::ensure!(!((kv_k_mode > 0 || kv_v_mode > 0) && crate::cuda::llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)"); + let hip = Arc::new(ffi::Hip::open()?); + hip.check(unsafe { (hip.init)(0) }, "hipInit") + .map_err(|e| anyhow::anyhow!("{e} (check that `rocminfo` lists the card and that this user can open /dev/kfd)"))?; + let n = { + let mut n = 0; + hip.check(unsafe { (hip.device_count)(&mut n) }, "hipGetDeviceCount")?; + n as usize + }; + anyhow::ensure!(device < n, "HIP device {device}: {n} device(s) present"); + hip.check(unsafe { (hip.set_device)(device as i32) }, "hipSetDevice")?; + let arch = hip.arch(device as i32)?; + let warp = hip.attribute(ffi::ATTR_WARP_SIZE, device as i32)?; + anyhow::ensure!(warp == 32, "H100 HIP backend needs wave32; {arch} reports warp size {warp}"); + // Opt-in (75) is what a kernel may ask for; fall back to the plain per-block limit (74) if a runtime does not + // know the attribute, and never trust a figure below the smallest tile the prefill attention needs. + let mut max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK_OPTIN, device as i32).unwrap_or(0) as usize; + if max_smem < (16 << 10) { + max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK, device as i32).unwrap_or(16 << 10) as usize; + } + anyhow::ensure!(max_smem >= (16 << 10), "HIP device reports {max_smem} B of shared memory a block"); + let rtc = ffi::Rtc::get().map_err(|e| anyhow::anyhow!("{e}")).context("HIP init").context("hiprtc is required to compile the kernels")?; + let (maj, min) = rtc.version(); + let tag = format!("{maj}.{min}"); + crate::say!("hip: {} ({arch}, wave{warp}, {} B shared memory a block)", + hip.device_name(device as i32), max_smem); + // `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications (A/B comparison, and a workaround if a card's + // matrix cores misbehave). Read once: the same value compiles the kernels and picks the WMMA-only launches. + let hip_wmma = std::env::var("STRATA_HIP_WMMA").map(|v| v != "0").unwrap_or(true); + let src = source(kv_k_mode, kv_v_mode, hip_wmma); + let obj = compile_cached(rtc, &src, &arch, &tag)?; + let mut stream: ffi::Stream = std::ptr::null_mut(); + hip.check(unsafe { (hip.stream_create)(&mut stream, ffi::STREAM_NON_BLOCKING) }, "hipStreamCreate")?; + let mut side: ffi::Stream = std::ptr::null_mut(); + hip.check(unsafe { (hip.stream_create)(&mut side, ffi::STREAM_NON_BLOCKING) }, "hipStreamCreate(side)")?; + let marks = (0..MARKS).map(|_| Event::new(&hip)).collect::>>()?; + let mut module: ffi::Module = std::ptr::null_mut(); + hip.check(unsafe { (hip.module_load)(&mut module, obj.as_ptr().cast()) }, "hipModuleLoadData")?; + let mut fns = HashMap::new(); + for name in kernel_names() { + let c = std::ffi::CString::new(name.clone())?; + let mut f: ffi::Func = std::ptr::null_mut(); + hip.check(unsafe { (hip.function)(&mut f, module, c.as_ptr()) }, &format!("hipModuleGetFunction({name})"))?; + // The kernels ask for up to 49 KiB of dynamic shared memory, more than HIP allows by default. The ceiling + // is the device's opt-in minus what the kernel already uses statically, which the runtime only checks + // here, so an over-ask is halved instead of failing the backend. + if let Some((_, need)) = dyn_shmem_need(&name) { + let mut want = need.min(max_smem); + loop { + let r = unsafe { (hip.func_set_attribute)(f, ffi::ATTR_MAX_DYNAMIC_SHARED, want as i32) }; + if r == ffi::HIP_SUCCESS { break } + if want < 8192 { + bail!("hipFuncSetAttribute({name}, {want}): {}", hip.err(r)); + } + want /= 2; + } + } + fns.insert(name, f); + } + // argmax_part writes an int2 (8 bytes) per partial: AMAX_PARTS per row, up to 64 rows. + let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS * 8)?; + // Pinned ring for large host-to-device copies. + let mut host: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.host_malloc)(&mut host, RING, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc(ring)")?; + let mut dev: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer(ring)")?; + let staging = Staging { _pin: Buf::new(dev as u64, RING, PinnedHost { hip: hip.clone(), p: host }), host: host.cast(), head: 0, busy: VecDeque::new() }; + let pci = hip.pci_bus_id(device as i32); + let sms = hip.attribute(ffi::ATTR_MULTIPROCESSOR_COUNT, device as i32).unwrap_or(16).max(1) as usize; + let wm = hip_wmma && wmma_arch(&arch); + let (mla_wmma, idx_wmma) = (wm && std::env::var_os("STRATA_MLA_SIMT").is_none(), wm && std::env::var("STRATA_IDX_WMMA").is_ok_and(|v| v == "1")); + Ok(Gpu { hip, device, stream, side, marks, next_mark: Default::default(), pinned: Default::default(), beside: Default::default(), beside_lag: Default::default(), fns, arch, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags: ink_flags(), pci, max_smem, sms, mla_wmma, idx_wmma, am: am_buf, + graphs: Mutex::new(HashMap::new()), graph_failed: Default::default(), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) + } + + pub fn arch(&self) -> &str { &self.arch } + + /// Launch kernel `name` with `cfg`; `args` are the kernel parameters, in order, read from the given addresses. + pub fn launch(&self, name: &str, c: LaunchConfig, args: &mut [&mut dyn Any]) -> anyhow::Result<()> { + let f = *self.fns.get(name).ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded"))?; + if *TRACE { eprintln!("hip launch {name} grid {:?} block {:?} smem {}", c.grid_dim, c.block_dim, c.shared_mem_bytes); } + let mut params: Vec<*mut c_void> = args.iter_mut().map(|a| (*a as *mut dyn Any).cast::()).collect(); + let r = unsafe { + (self.hip.launch)(f, c.grid_dim.0, c.grid_dim.1, c.grid_dim.2, c.block_dim.0, c.block_dim.1, c.block_dim.2, + c.shared_mem_bytes, self.stream, params.as_mut_ptr(), std::ptr::null_mut()) + }; + if r != ffi::HIP_SUCCESS { bail!("{}: {}", name, self.hip.err(r)) } + // `STRATA_HIP_SYNC`: wait after every launch, so a hardware exception or bad argument names the kernel that + // raised it instead of the sync at the end of the pass. Debugging only: no overlap and no graphs. + if *SYNC_EACH { + self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, &format!("kernel {name} failed"))?; + } + Ok(()) + } + + fn wait(&self) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.stream_sync)(self.side) }, "hipStreamSynchronize(side)")?; + self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, "hipStreamSynchronize") + } + + /// Record the point `stream` has reached in the next mark event, and return the slot it went to. + /// + /// The 64 events are a ring, so a mark held across 64 later marks refers to a later point by the time it is + /// waited on. That over-synchronises, which is safe: the marks exist to save a wait between the two streams, + /// never to stand in for one, and no caller may depend on a mark being exactly the point it recorded. + fn mark(&self, stream: ffi::Stream) -> anyhow::Result { + let i = self.next_mark.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % MARKS; + self.marks[i].record(stream)?; + Ok(i) + } + + /// `htod` on `stream`: queue the copy and return once `src` may be reused. From pageable memory the runtime + /// stages the buffer inside the call, and large copies go through the pinned ring so the DMA does not stop the + /// host (expert streaming during prefill). + fn htod_on(&self, stream: ffi::Stream, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { + anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); + // From a range `pin_host` registered the DMA reads `src` itself: no host copy through the ring, which runs + // at ~9 GB/s on one thread where the link takes 14 GB/s (prefill's expert staging). + let (s0, s1) = (src.as_ptr() as usize, src.as_ptr() as usize + src.len()); + if src.len() < RING_MIN || self.pinned.read().unwrap().iter().any(|&(a, b, _)| a <= s0 && s1 <= b) { + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), + ffi::MEMCPY_H2D, stream) }; + return self.hip.check(r, "hipMemcpyAsync(htod)"); + } + let mut g = self.staging.lock().unwrap(); + for (i, c) in src.chunks(RING).enumerate() { + if g.head + c.len() > RING { g.head = 0; } + let (a, b) = (g.head, g.head + c.len()); + // Regions still being read by an earlier copy have to complete before the host overwrites them. Each + // event is recorded on the stream its copy went to, so this waits on the right queue. + while g.busy.iter().any(|&(s, e, _)| s < b && a < e) { + let (_, _, ev) = g.busy.pop_front().unwrap(); + self.hip.check(unsafe { (self.hip.event_sync)(ev.ev) }, "hipEventSynchronize")?; + } + unsafe { std::ptr::copy_nonoverlapping(c.as_ptr(), g.host.add(a), c.len()) }; + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + (off + i * RING) as u64) as *mut c_void, + g.host.add(a) as *const c_void, c.len(), ffi::MEMCPY_H2D, stream) }; + self.hip.check(r, "hipMemcpyAsync(htod ring)")?; + let ev = Event::new(&self.hip)?; + ev.record(stream)?; + g.busy.push_back((a, b, ev)); + g.head = b; + } + Ok(()) + } + + /// Wait on `stream` until the point mark `n` recorded has run. + /// + /// Once the ring has wrapped, slot `n % MARKS` holds a later mark: waiting on it orders `stream` after that later + /// point, which is past the one asked for. Over-synchronising is safe and costs only a longer wait, where a host + /// `hipStreamSynchronize` here would stall the CPU on every layer run of a long prompt. + fn wait_mark(&self, stream: ffi::Stream, n: usize) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.stream_wait_event)(stream, self.marks[n % MARKS].ev, 0) }, "hipStreamWaitEvent") + } + + fn ptr(&self, b: &Buf) -> u64 { b.addr() } + + /// Float-input types: `gemv_*`/`moe_gemv_*` for these are the `DEF_FGEMV` kernels, which read x as f32, ignore + /// `rpw`, and cover exactly one row per warp, so they must take the float launch config (`gemv_cfg`) and no + /// quantized-x shared memory. The trellis types (TQ2_T, TQK6, TQK7) are float types too, as on CUDA + /// (`cuda::Gpu::float_ty`): giving them the int8 grid (rpw > 1) leaves most rows of the GEMV unwritten. + fn float_ty(ty: GgmlType) -> bool { ty.float_x() } + + fn gemv_cols(prefix: &str, ty: GgmlType, cols: usize) -> anyhow::Result<(i32, String)> { + let b = ty.block_elems().max(32); + if cols % b != 0 { bail!("{} tensor with {cols} columns: GEMV needs a multiple of {b}", ty.name()); } + Ok((cols as i32, kname(prefix, ty) + if cols % 256 != 0 { "_p" } else { "" })) + } + + fn rpw(rows: usize, cols: usize, k: usize) -> usize { + let d = if k > 1 { if cols <= 512 { 4 } else { (2048 / cols).max(1) } } else if rows >= 65536 { 8 } else if rows >= 8192 || rows == 2048 { 2 } else { 1 }; + let fam = if k > 1 { "STRATA_RPW_MOE" } else { "STRATA_RPW_DENSE" }; + let family = std::env::var(fam).ok(); + rpw_from(std::env::var("STRATA_RPW").ok().as_deref(), family.as_deref(), d) + } + + fn gemv_block(k: usize) -> u32 { + let fam = if k > 1 { "STRATA_GEMV_BLOCK_MOE" } else { "STRATA_GEMV_BLOCK_DENSE" }; + let family = std::env::var(fam).ok(); + gemv_block_from(std::env::var("STRATA_GEMV_BLOCK").ok().as_deref(), family.as_deref()) + } + + fn xq_smem(ty: GgmlType, cols: usize) -> u32 { + if Self::float_ty(ty) { 0 } else { (cols + cols / 8) as u32 } + } + + fn gemv_cfg(ty: GgmlType, rows: usize, cols: usize, k: usize) -> (LaunchConfig, i32) { + if Self::float_ty(ty) { + let wpb = if rows >= 4096 { 8 } else { 1 }; + return (cfg((rows.div_ceil(wpb) as u32, k as u32), 32 * wpb as u32, 0), 1); + } + let (rpw, wpb) = (Self::rpw(rows, cols, k), Self::gemv_block(k) as usize / 32); + (cfg((rows.div_ceil(wpb * rpw) as u32, k as u32), (32 * wpb) as u32, Self::xq_smem(ty, cols)), rpw as i32) + } + + /// Whether the stream is capturing a graph: no allocation and no synchronous copy may be issued inside one. + fn capturing(&self) -> bool { + let mut status = 0; + unsafe { (self.hip.stream_is_capturing)(self.stream, &mut status) }; + status != 0 + } + + /// The rope frequencies base^(-2i / n_rot) as `rms_norm_rope` computes them in f64, made once by `rope_freq`. + /// While a graph is captured a missing table gives 0 (the kernel computes the frequencies itself) and is made + /// after the capture, which `graph` then repeats. + fn rope_fr(&self, base: f32, n_rot: usize) -> anyhow::Result { + let mut fr = self.fr.lock().unwrap(); + if let Some(b) = fr.0.get(&(base.to_bits(), n_rot)) { return Ok(b.addr()) } + if self.capturing() { + fr.1.push((base, n_rot)); + return Ok(0); + } + let buf = alloc_raw(&self.hip, 8 * (n_rot / 2).max(1))?; + let p = buf.addr(); + let (bs, nr) = (base, n_rot as i32); + launch!(self, "rope_freq", cfg((1, 1), 256, 0), p, bs, nr); + self.wait()?; + fr.0.insert((base.to_bits(), n_rot), buf); + Ok(p) + } + + /// `gemvq`; with z = 2 also the matrix of `pair.2` rows at byte offset `pair.0` into the output at byte offset + /// `pair.1` (token stride `pair.2`). + fn gemvq_pair(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize, + pair: (i64, i64, i32, f32), z: u32) -> anyhow::Result<()> { + // gemvn takes 4 inputs at most; a larger batch (Inkling 2's draft verify, up to 16 rows) runs 4 at a time and + // quantizes x itself, since xq holds the scales of all nt rows after all the rows (as on CUDA). + if nt > 4 { + for t0 in (0..nt).step_by(4) { + let (xt, yt) = (x + 4 * (t0 * x_stride) as u64, y + 4 * (t0 * y_stride) as u64); + let y2 = if z == 2 { pair.1 + 4 * t0 as i64 * (pair.2 as i64 - y_stride as i64) } else { 0 }; + self.gemvq_pair(w, xt, x_stride, 0, yt, y_stride, (nt - t0).min(4), (pair.0, y2, pair.2, pair.3), z)?; + } + return Ok(()); + } + if nt == 0 { bail!("gemvn: no inputs"); } + let (ncols, k1) = Self::gemv_cols("gemv", w.ty, w.cols)?; + let (mut c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); + let per = c.shared_mem_bytes; + c.shared_mem_bytes = if xq == 0 { per * nt as u32 } else { 0 }; + c.grid_dim.2 = z; + // gemvn caches one x row per token in shared memory; when that exceeds the block's limit, run a token at a time. + if xq == 0 && c.shared_mem_bytes as usize > self.max_smem { + c.shared_mem_bytes = per; + for t in 0..nt { + let (xt, yt) = (x + 4 * t as u64 * x_stride as u64, y + 4 * t as u64 * y_stride as u64); + launch!(self, &k1, c, w.ptr, xt, yt, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2, w.scale, pair.3); + } + return Ok(()); + } + if nt == 1 { + launch!(self, &k1, c, w.ptr, x, y, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2, w.scale, pair.3); + return Ok(()); + } + let kn = k1.replacen("gemv", "gemvn", 1); + launch!(self, &kn, c, w.ptr, x, x_stride as i32, y, y_stride as i32, w.rows as i32, ncols, rpw, nt as i32, xq, pair.0, pair.1, pair.2, w.scale, pair.3); + Ok(()) + } + + /// Prefill GEMM over a tile list (or one dense matrix when `tiles` is 0). Without int8 tensor cores the f16 + /// `gemm_*`/`gemms_*` kernels run; `gemm_tc` is compiled out of this build (`GEMM_TC 0`). + fn gemm_raw(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, wd: u64, nd: usize, + x: u64, x_stride: usize, _n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32, w_scale: f32) -> anyhow::Result<()> { + if cols % 64 != 0 { bail!("{} matrix with {cols} columns: GEMM needs a multiple of 64", ty.name()); } + if n_tiles == 0 { return Ok(()) } + // Only the activation reaches the kernel: SAME_X and BATCHED (the same kernels here) are flags for the host. + let (same, act) = (act & SAME_X != 0, act & 3); + let _ = same; + let grid = (rows.div_ceil(64) as u32, n_tiles as u32); + let sm = tiles == 0 && (grid.0 * grid.1 < 112 || nd <= 32); + let grid = if sm { (grid.0, nd.div_ceil(32) as u32) } else { grid }; + launch!(self, &kname(if sm { "gemms" } else { "gemm" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); + // Tile lists: gemm_* skips the tiles of at most 32 positions, which gemms_* takes. + if tiles != 0 { + launch!(self, &kname("gemms", ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); + } + Ok(()) + } + + /// Decode attention: `attn_decode_gq` plus `attn_merge`, which also writes `out` quantized into xq. + fn attn(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, + scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize, kvt: u64, ns1: usize) -> anyhow::Result<()> { + if ![64, 128, 256, 512].contains(&hd) { bail!("attention head_dim {hd} unsupported (64, 128, 256 or 512)"); } + let group = nh / nkv; + let g = [8, 4, 2, 1].into_iter().find(|&g| group % g == 0 && g * hd <= 2048).unwrap(); + let ns = if kvt != 0 { ns1 } else { ATT_SPLITS }; + let pz = (nh * ns * (hd + 2)) as i32; + if gq_min != 0 { + launch!(self, &format!("attn_decode_{hd}"), cfg(((nh * nt) as u32, ns1 as u32), 256, (8 * hd * 4) as u32), + q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); + } + // No cp.async double buffering here: that path is the sm_80+ one (`ATT_RUN_CP`), so the K/V tile comes + // through registers and the kernel needs no extra shared memory. + let g4 = false; + let (name, cp) = if g4 { ("attn_decode_gqa4_128".to_string(), 0) } else { (format!("attn_decode_gqa_{hd}"), 0) }; + if gq_min != i32::MAX { + launch!(self, &name, cfg(((nh / g * nt) as u32, ns as u32), 256, (8 * hd * 4 + cp) as u32), + q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); + } + launch!(self, "attn_merge", LaunchConfig { grid_dim: (nh as u32, 1, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }, + part, qg, out, hd as i32, ns as i32, step, ns1 as i32, gq_min, xq, sink); + Ok(()) + } + + fn grid(n: usize) -> LaunchConfig { cfg((n.div_ceil(256) as u32, 1), 256, 0) } + + /// The decode attention kernel and its key positions per block, chosen as on CUDA (`cuda::Gpu::ink_attn_kernel`). + fn ink_attn_kernel(&self, hd: usize, nr: usize) -> (&'static str, usize) { + crate::cuda::ink_attn_pick(self.kv_mode, self.flags.fast && !self.flags.attn_old, hd, nr) + } +} + +/// `flags` for a HIP `Gpu`, from the same variables as CUDA's: `STRATA_DS_FAST_KERNELS` `0`/`1` mean what they do +/// there, but unset or `auto` is the fast set. `--fixed-experts` (`STRATA_FIXED_EXPERTS`) keeps the old kernels, as +/// its output must stay bit-identical to Vulkan (`docs/HIP.md`). +fn ink_flags_from(fast: Option<&str>, fixed: bool, ctrl: Option<&str>, attn_old: Option<&str>, attn_kp4: Option<&str>) -> crate::cuda::InkFlags { + let default = !fixed; + let fast = match fast { + None | Some("auto") => default, + Some("0") => false, + Some(_) => true, + }; + // The tiled pair follows `fast` when `STRATA_CTRL_TILE` is unset, as on CUDA. + crate::cuda::InkFlags::from_parts(Some(if fast { "1" } else { "0" }), false, ctrl, attn_old, attn_kp4) +} + +fn ink_flags() -> crate::cuda::InkFlags { + ink_flags_from( + std::env::var("STRATA_DS_FAST_KERNELS").ok().as_deref(), + std::env::var_os("STRATA_FIXED_EXPERTS").is_some(), + std::env::var("STRATA_CTRL_TILE").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_OLD").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_KP4").ok().as_deref(), + ) +} + +/// Pinned host allocation freed with the runtime that made it. +struct PinnedHost { hip: Arc, p: *mut c_void } + +unsafe impl Send for PinnedHost {} +unsafe impl Sync for PinnedHost {} + +impl Drop for PinnedHost { + fn drop(&mut self) { unsafe { (self.hip.host_free)(self.p) }; } +} + +/// Pinned host memory used as a ring for `htod`: a region is free again once the copy that read it has completed. +struct Staging { + /// Owns the pinned allocation; dropping it frees the ring. + _pin: Buf, + host: *mut u8, + head: usize, + busy: VecDeque<(usize, usize, Event)>, +} + +impl Drop for Gpu { + /// Unlock what `pin_host` locked, before the mapping it belongs to goes. + fn drop(&mut self) { + let _ = self.wait(); + for &(s, _, _) in self.pinned.read().unwrap().iter() { unsafe { (self.hip.host_unregister)(s as *mut c_void) }; } + } +} + +/// A `hipEvent_t` that destroys itself. +struct Event { hip: Arc, ev: ffi::Event } + +impl Event { + fn new(hip: &Arc) -> anyhow::Result { + let mut ev: ffi::Event = std::ptr::null_mut(); + hip.check(unsafe { (hip.event_create)(&mut ev, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; + Ok(Event { hip: hip.clone(), ev }) + } + fn record(&self, stream: ffi::Stream) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.event_record)(self.ev, stream) }, "hipEventRecord") + } +} + +impl Drop for Event { + fn drop(&mut self) { unsafe { (self.hip.event_destroy)(self.ev) }; } +} + +/// Recorded graphs kept before a forward runs uncaptured (CUDA's cap, same reason). +const GRAPHS_MAX: usize = 32; + +const RING: usize = 64 << 20; +/// Mark events of the copy queue (`Gpu::mark`). +const MARKS: usize = 64; +const RING_MIN: usize = 256 << 10; + +fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { + let mut p: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.malloc)(&mut p, bytes.max(1)) }, "hipMalloc")?; + // The Buf owns the allocation through its address; the free happens when the owner (the backend or the tensor) + // drops, so the owner is a small RAII handle. + struct DevAlloc { hip: Arc, p: *mut c_void } + unsafe impl Send for DevAlloc {} + unsafe impl Sync for DevAlloc {} + impl Drop for DevAlloc { + fn drop(&mut self) { unsafe { (self.hip.free)(self.p) }; } + } + Ok(Buf::new(p as u64, bytes.max(1), DevAlloc { hip: hip.clone(), p })) +} + +fn compile_cached(rtc: &ffi::Rtc, src: &str, arch: &str, tag: &str) -> anyhow::Result> { + let dir = crate::expert_cache::cache_dir(); + let path = dir.join(format!("{:016x}.amdgcn", cache_key(src, arch, tag))); + // A read that fails the ELF check is a partial write from a process that died, or two runs racing the same file: + // compile again instead of handing the loader a truncated object (which fails as "no kernel image is available" + // and silently leaves the model on the CPU). + if let Ok(b) = std::fs::read(&path) { + if b.starts_with(b"\x7fELF") { return Ok(b) } + crate::say!("HIP kernel cache {:016x} is not an ELF object; compiling again", cache_key(src, arch, tag)); + let _ = std::fs::remove_file(&path); + } + crate::say!("compiling HIP kernels for {arch} with hiprtc {tag} (first run only)"); + let b = rtc.compile(src, "kernels.cu", arch, &[])?; + // Written beside the target and renamed: a concurrent reader (or a kill) then sees either no file or the whole + // object, never a truncated one. The counter keeps two devices of one process off the same temporary file. + static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!("{:016x}.{}.{seq}.tmp", cache_key(src, arch, tag), std::process::id())); + let _ = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&tmp, &b)).and_then(|_| std::fs::rename(&tmp, &path)); + let _ = std::fs::remove_file(&tmp); + Ok(b) +} + +/// Free VRAM as the kernel driver counts it, for the amdgpu card at PCI address `bus`. When the runtime gives no +/// address or no card has it, the card whose VRAM size is `total` (to 256 MiB; with two cards of one size that may be +/// the other card). `hipMemGetInfo` counts only compute allocations, so the desktop and other graphics clients look +/// free to it and a budget taken from it squeezes them out (the compositor then fails to pin its framebuffer). +/// Vulkan's memory budget already counts them. +fn drm_free(total: usize, bus: Option<&str>) -> Option { + let read = |p: std::path::PathBuf| std::fs::read_to_string(p).ok()?.trim().parse::().ok(); + let free_where = |ours: &dyn Fn(&std::path::Path, usize) -> bool| std::fs::read_dir("/sys/class/drm").ok()?.flatten().find_map(|e| { + let dev = e.path().join("device"); + let t = read(dev.join("mem_info_vram_total"))?; + if !ours(&dev, t) { return None } + Some(t.saturating_sub(read(dev.join("mem_info_vram_used"))?)) + }); + let at_bus = |dev: &std::path::Path, _| bus.is_some_and(|b| std::fs::canonicalize(dev).ok() + .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase())).is_some_and(|n| n == b)); + free_where(&at_bus).or_else(|| free_where(&|_, t: usize| t.abs_diff(total) <= 256 << 20)) +} + +/// The kernel names to load: `cuda::kernel_names(false)` has no int8-mma GEMM, which needs no separate list here, +/// plus the kernels `kernels.cu` compiles only under `STRATA_HIP`. +fn kernel_names() -> Vec { + let mut v = crate::cuda::kernel_names(false); + v.extend(["mla_attn_wmma", "idx_score_wmma", "mla_qpack"].map(String::from)); + v +} + +/// Whether `compat.h` defines `STRATA_WMMA` for `arch`, so `kernels.cu` compiles its WMMA paths when +/// `STRATA_HIP_WMMA` is not 0 (`GEMM_WMMA`). +fn wmma_arch(arch: &str) -> bool { + const ARCHS: [&str; 9] = ["gfx1100", "gfx1101", "gfx1102", "gfx1103", "gfx1150", "gfx1151", "gfx1152", "gfx1200", "gfx1201"]; + ARCHS.contains(&arch.split(':').next().unwrap_or(arch)) +} + +impl Backend for Gpu { + fn name(&self) -> &'static str { "hip" } + + fn device(&self) -> String { self.hip.device_name(self.device as i32) } + + fn alloc(&self, bytes: usize) -> anyhow::Result { + let b = alloc_raw(&self.hip, bytes)?; + self.memset(&b)?; + Ok(b) + } + + /// `htod_on` the kernels' stream, or the copy queue inside `beside`: a copy inside it runs beside the kernels. + fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { + let st = if self.beside.load(std::sync::atomic::Ordering::Relaxed) { self.side } else { self.stream }; + self.htod_on(st, src, dst, off) + } + + fn htod_side(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { self.htod_on(self.side, src, dst, off) } + + /// `hipHostRegister` of the pages under `data`, read-only when the runtime takes that flag (the model file is + /// mapped read-only). + fn pin_host(&self, data: &[u8]) -> anyhow::Result { + const PAGE: usize = 4096; + let (a, b) = (data.as_ptr() as usize, data.as_ptr() as usize + data.len()); + if self.pinned.read().unwrap().iter().any(|&(s, e, _)| s <= a && b <= e) { return Ok(true); } + let (pa, pb) = (a & !(PAGE - 1), b.div_ceil(PAGE) * PAGE); + let mut last = 0; + for flags in [ffi::HOST_REGISTER_READ_ONLY | ffi::HOST_REGISTER_PORTABLE, ffi::HOST_REGISTER_PORTABLE] { + last = unsafe { (self.hip.host_register)(pa as *mut c_void, pb - pa, flags) }; + if last == ffi::HIP_SUCCESS { + // ROCm maps registered pages into the device's address space with or without hipHostRegisterMapped. + let mut dev: *mut c_void = std::ptr::null_mut(); + // Without a device address the range is not counted as registered: unregister it, the ring stages it. + if unsafe { (self.hip.host_device_ptr)(&mut dev, pa as *mut c_void, 0) } != ffi::HIP_SUCCESS { + unsafe { (self.hip.host_unregister)(pa as *mut c_void) }; + return Ok(false); + } + self.pinned.write().unwrap().push((pa, pb, dev as u64)); + return Ok(true); + } + } + self.hip.check(last, "hipHostRegister").map(|_| false) + } + /// `htod` from a range this registered reads `src` directly, without the ring. + fn host_is_pinned(&self, data: &[u8]) -> bool { + let (a, b) = (data.as_ptr() as usize, data.as_ptr() as usize + data.len()); + self.pinned.read().unwrap().iter().any(|&(s, e, _)| s <= a && b <= e) + } + fn host_ptr(&self, data: &[u8]) -> Option { + let (a, b) = (data.as_ptr() as usize, data.as_ptr() as usize + data.len()); + self.pinned.read().unwrap().iter().find(|&&(s, e, d)| s <= a && b <= e && d != 0).map(|&(s, _, d)| d + (a - s) as u64) + } + fn side_mark(&self) -> anyhow::Result { self.mark(self.side) } + fn main_waits(&self, m: usize) -> anyhow::Result<()> { self.wait_mark(self.stream, m) } + fn main_mark(&self) -> anyhow::Result { self.mark(self.stream) } + fn side_waits(&self, m: usize) -> anyhow::Result<()> { self.wait_mark(self.side, m) } + + fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()> { + anyhow::ensure!(off + dst.len() <= src.len(), "dtoh: {} bytes at {off} from {}", dst.len(), src.len()); + self.wait()?; + let r = unsafe { (self.hip.memcpy)(dst.as_mut_ptr().cast(), (src.addr() + off as u64) as *const c_void, dst.len(), + ffi::MEMCPY_D2H) }; + self.hip.check(r, "hipMemcpyAsync(dtoh)") + } + + fn dtod(&self, src: &Buf, src_off: usize, dst: &Buf, dst_off: usize, bytes: usize) -> anyhow::Result<()> { + anyhow::ensure!(src_off + bytes <= src.len() && dst_off + bytes <= dst.len(), "dtod: {bytes} bytes out of range"); + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + dst_off as u64) as *mut c_void, + (src.addr() + src_off as u64) as *const c_void, bytes, ffi::MEMCPY_D2D, self.stream) }; + self.hip.check(r, "hipMemcpyAsync(dtod)") + } + + /// On the stream, so it is ordered against the copies and launches around it (the plain `hipMemset` goes to the + /// null stream and can land after a copy that was queued for the same buffer). + fn memset(&self, dst: &Buf) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.memset_async)(dst.addr() as *mut c_void, 0, dst.len(), self.stream) }, "hipMemsetAsync") + } + + fn mem_info(&self) -> anyhow::Result<(usize, usize)> { + let (mut free, mut total) = (0usize, 0usize); + self.hip.check(unsafe { (self.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo")?; + Ok((free.min(drm_free(total, self.pci.as_deref()).unwrap_or(usize::MAX)), total)) + } + + fn sync(&self) -> anyhow::Result<()> { self.wait() } + + fn beside_overlaps(&self) -> bool { true } + + /// CUDA's shape on the copy queue `htod_side` already has: the side queue waits for the main one as it stands + /// now, `f`'s copies queue there beside its launches, and the main queue waits on the PREVIOUS `beside`'s mark + /// only, so this step's copies hide behind the next step's kernels. Main's 64-slot mark ring is enough: the lag is + /// waited on at the next `beside`, one mark later, and a wait on a wrapped slot over-synchronises, which is safe. + fn beside(&self, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { + let start = self.mark(self.stream)?; + self.wait_mark(self.side, start)?; + self.beside.store(true, std::sync::atomic::Ordering::Relaxed); + let r = f(); + self.beside.store(false, std::sync::atomic::Ordering::Relaxed); + let m = self.mark(self.side)?; + // Only the previous beside's copies: waiting on this one would put the kernels behind them. + if let Some(p) = self.beside_lag.lock().unwrap().replace(m) { self.wait_mark(self.stream, p)?; } + r + } + + /// Ops after this see every `beside`'s copies: the main queue waits on the side queue as it stands now. + fn beside_join(&self) -> anyhow::Result<()> { + self.beside_lag.lock().unwrap().take(); + let m = self.mark(self.side)?; + self.wait_mark(self.stream, m) + } + + /// Recorded with `hipStreamBeginCapture`: the same launches, replayed by the driver with no host work. + /// HIP refuses an allocation on a capturing stream ("operation not permitted when stream is capturing"), where + /// CUDA's stream-ordered allocator allows it, so anything a step allocates has to be made before the capture (the + /// rope table defers itself, see `rope_fr`). `STRATA_HIP_GRAPH=0` turns capture off. + fn graph(&self, key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { + use std::sync::atomic::Ordering; + if *NO_GRAPH || self.graph_failed.load(Ordering::Relaxed) { return f() } + if let Some(g) = self.graphs.lock().unwrap().get(&key) { + let r = unsafe { (self.hip.graph_launch)(g.exec, self.stream) }; + return self.hip.check(r, "hipGraphLaunch"); + } + // Each graph holds device memory and `step_rows` keys one per combination of sequence slots: past the cap a + // forward runs uncaptured (the CUDA backend caps for the same reason). + if self.graphs.lock().unwrap().len() >= GRAPHS_MAX { return f() } + if self.capturing() { return f() } // never nest captures + // A capture or instantiate failure is not fatal, and the ops of a failed capture never ran: latch the flag + // (later forwards here run uncaptured) and run `f`. An out-of-memory instantiate — seen on a 16 GB card when the + // core graph holds the whole repeating core — is exactly the case to survive. An empty graph is not: nothing + // was recorded, so a forward would compute nothing, and that is a bug that must fail loudly. + let failed = |e: anyhow::Error, f: &mut dyn FnMut() -> anyhow::Result<()>| { + self.graph_failed.store(true, Ordering::Relaxed); + crate::say!("hip: graph capture failed ({e:#}); forwards run uncaptured from here"); + f() + }; + if let Err(e) = self.hip.check(unsafe { (self.hip.stream_begin_capture)(self.stream, ffi::CAPTURE_MODE_THREAD_LOCAL) }, "hipStreamBeginCapture") { + return failed(e, f); + } + let r = f(); + let mut graph: ffi::Graph = std::ptr::null_mut(); + let end = unsafe { (self.hip.stream_end_capture)(self.stream, &mut graph) }; + r?; + self.hip.check(end, "hipStreamEndCapture")?; + anyhow::ensure!(!graph.is_null(), "empty HIP graph"); + let mut exec: ffi::GraphExec = std::ptr::null_mut(); + if let Err(e) = self.hip.check(unsafe { (self.hip.graph_instantiate)(&mut exec, graph, 0) }, "hipGraphInstantiate") { + unsafe { (self.hip.graph_destroy)(graph) }; + return failed(e, f); + } + self.hip.check(unsafe { (self.hip.graph_launch)(exec, self.stream) }, "hipGraphLaunch")?; + // A rope table the capture lacked: make it, and capture again next time (this graph computes it per call). + let want = std::mem::take(&mut self.fr.lock().unwrap().1); + if !want.is_empty() { + for (base, n_rot) in want { self.rope_fr(base, n_rot)?; } + return Ok(()); + } + self.graphs.lock().unwrap().insert(key, Graph { exec, graph, hip: self.hip.clone() }); + Ok(()) + } + + fn graph_clear(&self) -> anyhow::Result<()> { + self.sync()?; + self.graphs.lock().unwrap().clear(); + Ok(()) + } + + /// Pinned host memory mapped into the device address space (the CPU expert worker's mailbox). + fn host_mailbox(&self, words: usize) -> anyhow::Result<(Buf, *mut u32)> { + let n = words.max(1); + let mut host: *mut c_void = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.host_malloc)(&mut host, 4 * n, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc")?; + let mut dev: *mut c_void = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer")?; + unsafe { std::ptr::write_bytes(host as *mut u8, 0, 4 * n) }; + let owner = PinnedHost { hip: self.hip.clone(), p: host }; + Ok((Buf::new(dev as u64, 4 * n, owner), host.cast())) + } + + fn kv_words(&self, n: usize) -> usize { crate::cuda::kv_mode_words(self.kv_k_mode, n) } + fn kv_words_v(&self, n: usize) -> usize { crate::cuda::kv_mode_words(self.kv_v_mode, n) } + + // ---- kernels ------------------------------------------------------------------------------------------------- + + fn gemm(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, x: u64, x_stride: usize, n_x: usize, + xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + self.gemm_raw(ty, rows, cols, tiles, n_tiles, 0, 0, x, x_stride, n_x, xrow, y, y_stride, act, 1.0f32) + } + + fn gemm_dense(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + self.gemm_raw(w.ty, w.rows, w.cols, 0, n.div_ceil(GEMM_BM), w.ptr, n, x, x_stride, n, 0, y, y_stride, act, w.scale) + } + + fn int8_gemm(&self, _ty: GgmlType) -> bool { false } + + /// No int8 GEMM here (see `int8_gemm`), so the prefill GEMM is f16 and its inputs are f16. The trait default is + /// CUDA's type policy alone, which would tell the tests to build their reference from int8 `x` (Q2_0 at 640 + /// columns read 0.0043 off that way), and callers that want the type policy use `cuda::Gpu::mmq`. + fn mmq(&self, _ty: GgmlType) -> bool { false } + + fn gemv(&self, w: &GpuTensor, x: u64, y: u64) -> anyhow::Result<()> { + let (ncols, kn) = Self::gemv_cols("gemv", w.ty, w.cols)?; + let (c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); + launch!(self, &kn, c, w.ptr, x, y, w.rows as i32, ncols, rpw, 0u64, 0i64, 0i64, 0i32, w.scale, 1.0f32); + Ok(()) + } + + fn gemvn(&self, w: &GpuTensor, x: u64, x_stride: usize, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { + self.gemvq(w, x, x_stride, 0, y, y_stride, nt) + } + + fn gemvq(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { + self.gemvq_pair(w, x, x_stride, xq, y, y_stride, nt, (0, 0, 0, 1.0f32), 1) + } + + fn gemvq2(&self, a: &GpuTensor, b: &GpuTensor, x: u64, x_stride: usize, xq: u64, ya: u64, yb: u64, nt: usize) -> anyhow::Result<()> { + if a.ty != b.ty || a.cols != b.cols { + self.gemvq(a, x, x_stride, xq, ya, a.rows, nt)?; + return self.gemvq(b, x, x_stride, xq, yb, b.rows, nt); + } + let ((a, ya), (b, yb)) = if a.rows >= b.rows { ((a, ya), (b, yb)) } else { ((b, yb), (a, ya)) }; + self.gemvq_pair(a, x, x_stride, xq, ya, a.rows, nt, (b.ptr as i64 - a.ptr as i64, yb as i64 - ya as i64, b.rows as i32, b.scale), 2) + } + + fn moe_gemv(&self, ty: GgmlType, rows: usize, cols: usize, w: u64, stride: usize, ids: u64, k: usize, x: u64, x_stride: usize, + xg: usize, y: u64, pair: Option<(i64, i64)>, xq: u64) -> anyhow::Result<()> { + let (ncols, kn) = Self::gemv_cols("moe_gemv", ty, cols)?; + let (mut c, mut rpw) = Self::gemv_cfg(ty, rows, cols, k); + if rpw == 1 && !Self::float_ty(ty) { + rpw = 2; + c.grid_dim.0 = rows.div_ceil(2 * (Self::gemv_block(k) as usize / 32)) as u32; + } + let (w2, y2) = pair.unwrap_or((0, 0)); + c.grid_dim.2 = if pair.is_some() { 2 } else { 1 }; + if xq != 0 { c.shared_mem_bytes = 0; } + launch!(self, &kn, c, w, ids, stride as i64, x, x_stride as i32, xg as i32, y, rows as i32, ncols, rpw, w2, y2, xq); + Ok(()) + } + + fn dequant(&self, w: &GpuTensor, rows: usize, out: u64) -> anyhow::Result<()> { + launch!(self, &kname("dequant", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, out, Self::gemv_cols("dequant", w.ty, w.cols)?.0, w.scale); + Ok(()) + } + + fn quant_xq(&self, x: u64, x_stride: usize, n: usize, nt: usize, out: u64) -> anyhow::Result<()> { + launch!(self, "quant_xq", cfg((nt as u32, 1), 256, 0), x, x_stride as i32, n as i32, out); + Ok(()) + } + + fn rms_norm(&self, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, n: usize, rows: usize, eps: f32) -> anyhow::Result<()> { + self.rms_norm_q(x, x_stride, w, out, out_stride, n, rows, eps, 0, 0) + } + + fn rms_norm_q(&self, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, n: usize, rows: usize, eps: f32, xq: u64, res: u64) -> anyhow::Result<()> { + launch!(self, "rms_norm", cfg((rows as u32, 1), 512, 0), x, x_stride as i32, w, out, out_stride as i32, n as i32, eps, xq, res, 1i32); + Ok(()) + } + + fn rms_norm_streams(&self, x: u64, w: u64, out: u64, n: usize, hc: usize, nt: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "rms_norm", cfg(((nt * hc) as u32, 1), 512, 0), x, n as i32, w, out, n as i32, n as i32, eps, 0u64, 0u64, hc as i32); + Ok(()) + } + + fn argmax_rows(&self, x: u64, n: usize, rows: usize, out: u64) -> anyhow::Result<()> { + let part = self.ptr(&self.am); + anyhow::ensure!(rows * AMAX_PARTS * 8 <= self.am.len(), "argmax_rows: {rows} rows"); // len is in bytes + launch!(self, "argmax_part", cfg((AMAX_PARTS as u32, rows as u32), 256, 0), x, n as i32, part); + launch!(self, "argmax_rows", cfg((rows as u32, 1), AMAX_PARTS as u32, 0), part, n as i32, out); + Ok(()) + } + + fn l2_norm(&self, x: u64, n: usize, per: usize, stride: usize, rows: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "l2_norm", cfg((rows as u32, 1), 128, 0), x, n as i32, per as i32, stride as i32, eps); + Ok(()) + } + + fn rope_neox(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { + self.rope_pairs(x, stride, heads, per, n_rot, step, base, 0, n_rot / 2) + } + + fn rope_pairs(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32, lo: usize, hi: usize) -> anyhow::Result<()> { + launch!(self, "rope_neox", cfg(((heads / per) as u32, 1), (n_rot / 2) as u32, 0), x, stride as i32, per as i32, n_rot as i32, step, base, lo as i32, hi as i32); + Ok(()) + } + + fn rms_norm_rope(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { + self.rms_norm_rope_kv(x, x_stride, w, out, n, rows, eps, per, n_rot, step, base, 0, 0, 0) + } + + fn rms_norm_rope_kv(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, + step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg((rows as u32, 1), 256, 0), x, x_stride as i32, w, out, n as i32, eps, per as i32, n_rot as i32, + step, base, v, kc, vc, 0i32, 0u64, 0i32, 0u64, 0u64, 0i32, fr, 0u64, 0u64); + Ok(()) + } + + fn rms_norm_rope_qk(&self, q: u64, q_stride: usize, qw: u64, qo: u64, qrows: usize, qper: usize, k: u64, kw: u64, ko: u64, + krows: usize, kper: usize, n: usize, eps: f32, n_rot: usize, step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg(((qrows + krows) as u32, 1), 256, 0), k, n as i32, kw, ko, n as i32, eps, kper as i32, n_rot as i32, + step, base, v, kc, vc, qrows as i32, q, q_stride as i32, qw, qo, qper as i32, fr, 0u64, 0u64); + Ok(()) + } + + fn kv_rows(&self) -> bool { true } + + fn rms_norm_rope_qk_rows(&self, q: u64, q_stride: usize, qw: u64, qo: u64, nh: usize, k: u64, kw: u64, ko: u64, nkv: usize, + hd: usize, eps: f32, n_rot: usize, step: u64, base: f32, v: u64, kvt: u64, nt: usize) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= hd.min(512) && hd % 32 == 0, "rms_norm_rope: head of {hd}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg(((nt * (nh + nkv)) as u32, 1), 256, 0), k, hd as i32, kw, ko, hd as i32, eps, nkv as i32, n_rot as i32, + step, base, v, 0u64, 0u64, (nt * nh) as i32, q, q_stride as i32, qw, qo, nh as i32, fr, kvt, 0u64); + Ok(()) + } + + fn attn_rows(&self, q: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, nt: usize, + sink: u64, win: usize, kvt: u64, splits: usize) -> anyhow::Result<()> { + self.attn(q, 0, 0, qg, out, part, step, nh, nkv, hd, scale, 0, nt, 0, 0, 0, sink, win, kvt, splits) + } + + fn add(&self, x: u64, y: u64, n: usize) -> anyhow::Result<()> { + launch!(self, "add", Self::grid(n), x, y, n as i32); + Ok(()) + } + + fn swiglu(&self, g: u64, u: u64, n: usize) -> anyhow::Result<()> { + launch!(self, "swiglu", Self::grid(n), g, u, n as i32); + Ok(()) + } + + fn swiglu_clamp(&self, g: u64, u: u64, n: usize, lim: f32) -> anyhow::Result<()> { + launch!(self, "swiglu_clamp", Self::grid(n), g, u, n as i32, lim); + Ok(()) + } + + fn swiglu_q(&self, g: u64, u: u64, n: usize, rows: usize, xq: u64) -> anyhow::Result { + launch!(self, "swiglu_q", cfg((n.div_ceil(256) as u32, rows as u32), 32, 0), g, u, n as i32, xq); + Ok(xq) + } + + fn ssm_gates(&self, beta: u64, g: u64, dt_bias: u64, a: u64, n: usize, nv: usize) -> anyhow::Result<()> { + launch!(self, "ssm_gates", Self::grid(n), beta, g, dt_bias, a, n as i32, nv as i32); + Ok(()) + } + + fn conv_silu(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, nn: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "conv_silu", cfg((ch.div_ceil(128) as u32, 1), 128, 0), qkv, state, w, y, ch as i32, kw as i32, nn as i32, eps, 0u64); + Ok(()) + } + + fn deltanet(&self, y: u64, s: u64, beta: u64, g: u64, dt_bias: u64, a: u64, o: u64, nk: usize, nv: usize, interleave: bool, + dk: usize, dv: usize, scale: f32, t: usize, ych: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { + let rows = 512 / dk.max(1); + anyhow::ensure!(matches!(dk, 32 | 64 | 128 | 256) && dv % rows == 0, "deltanet: head dims {dk}/{dv} unsupported"); + launch!(self, "deltanet_seq", cfg((nv as u32, dv.div_ceil(8 * rows) as u32), 256, 0), + y, s, beta, g, o, nk as i32, nv as i32, interleave as i32, dk as i32, dv as i32, scale, t as i32, ych as i32, + snap, nsnap as i32, dt_bias, a, 0u64); + Ok(()) + } + + fn conv_seq(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, t: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { + launch!(self, "conv_seq", Self::grid(t * ch), qkv, state, w, y, ch as i32, kw as i32, t as i32); + launch!(self, "conv_state", Self::grid(ch), qkv, state, ch as i32, kw as i32, t as i32, snap, nsnap as i32); + Ok(()) + } + fn graph_drop(&self, key: u64) -> anyhow::Result<()> { + self.graphs.lock().unwrap().remove(&key); + Ok(()) + } + + fn situ(&self, y: u64, n: usize, rows: usize, scale: u64, beta: f32, lb: f32) -> anyhow::Result<()> { + launch!(self, "situ", Self::grid(n * rows), y, n as i32, rows as i32, scale, beta, lb); + Ok(()) + } + + fn situ_q(&self, y: u64, n: usize, rows: usize, s: u64, beta: f32, lb: f32, xq: u64) -> anyhow::Result<()> { + anyhow::ensure!(n % 32 == 0, "situ_q: n ({n}) must be a multiple of 32"); + launch!(self, "situ_q", cfg((n.div_ceil(256) as u32, rows as u32), 32, 0), y, n as i32, s, beta, lb, xq); + Ok(()) + } + + fn softcap(&self, x: u64, n: usize, cap: f32) -> anyhow::Result<()> { + launch!(self, "softcap", Self::grid(n), x, n as i32, cap); + Ok(()) + } + + fn hadamard(&self, x: u64, u: u64, s: u64, perm: u64, out: u64, n: usize, block: usize, rows: usize) -> anyhow::Result<()> { + anyhow::ensure!((2..=4096).contains(&block), "prism.hadamard.block_size {block}: 2 to 4096 on the GPU"); + launch!(self, "hadamard", cfg(((rows * n / block) as u32, 1), block.min(1024) as u32, 0), x, u, s, perm, out, n as i32, block as i32, 1.0 / (block as f32).sqrt()); + Ok(()) + } + + // ---- Inkling 2 (the same kernels and launch shapes as src/cuda) ---- + + fn ink_mix_n(&self, blocks: u64, nb: usize, cur: u64, q: u64, nq: usize, out: u64, n: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ink_mix", cfg((nq as u32, nt as u32), 256, 0), blocks, nb as i32, cur, q, out, n as i32, nt as i32); + Ok(()) + } + + fn ink_ctrl_n(&self, down: u64, gain: u64, forget: u64, cur: u64, nins: usize, msg: u64, gate: u64, out: u64, n: usize, rank: usize, count: usize, nt: usize) -> anyhow::Result<()> { + // As CUDA: a prompt chunk uses the tiled pair (a weight row is read once per 64 tokens), a decoded token + // the per-token pair. Both pairs read and write the same gate layout. + if nt >= 64 && rank <= 64 && n % 64 == 0 && self.flags.ctrl_tile { + let g1 = cfg((count as u32, nt.div_ceil(64) as u32), 256, 0); + let g2 = LaunchConfig { grid_dim: (count as u32, n.div_ceil(64) as u32, nt.div_ceil(64) as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + launch!(self, "ink_ctrl_gate_b", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); + launch!(self, "ink_ctrl_out_b", g2, gain, forget, gate, cur, nins as i32, msg, out, n as i32, rank as i32, nt as i32); + return Ok(()); + } + let g1 = LaunchConfig { grid_dim: (rank as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + let g2 = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + launch!(self, "ink_ctrl_gate", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); + launch!(self, "ink_ctrl_out", g2, gain, forget, gate, cur, nins as i32, msg, out, n as i32, rank as i32, nt as i32); + Ok(()) + } + + fn ink_conv(&self, cur: u64, w: u64, taps: u64, hist: u64, out: u64, n: usize, n_conv: usize, per: usize) -> anyhow::Result<()> { + launch!(self, "ink_conv", Self::grid(n), cur, w, taps, hist, out, n as i32, n_conv as i32, per as i32); + Ok(()) + } + + fn ink_conv_batch(&self, cur: u64, w: u64, taps: u64, hist: u64, out: u64, n: usize, n_conv: usize, per: usize, nt: usize) -> anyhow::Result<()> { + anyhow::ensure!(cur != out, "ink_conv_batch: out must not alias cur"); + anyhow::ensure!(n_conv <= 8, "ink_conv_batch: n_conv={n_conv} > 8"); + launch!(self, "ink_conv_batch", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), cur, w, taps, hist, out, n as i32, n_conv as i32, per as i32, nt as i32, 0i32); + launch!(self, "ink_conv_batch", Self::grid(n), cur, w, taps, hist, out, n as i32, n_conv as i32, per as i32, nt as i32, 1i32); + Ok(()) + } + + fn ink_clip_n(&self, x: u64, scale: u64, w: usize, rows: usize, nt: usize, thr: f32, eps: f32, mul: f32, + dst: u64, dst_at0: usize, dst_ring: usize, pos0: usize, log_alpha: f32, log_floor: f32) -> anyhow::Result<()> { + anyhow::ensure!(w <= 128, "ink_clip_n: w={w} > 128"); + anyhow::ensure!(crate::cuda::kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); + let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; + let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; + launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), + x, scale, w as i32, thr, eps, mul, dst, dst_at0 as i32, ring as i32, pos0 as i32, log_alpha, fl, 0u64); + Ok(()) + } + + fn ink_clip_pos(&self, x: u64, scale: u64, w: usize, rows: usize, nt: usize, thr: f32, eps: f32, mul: f32, + dst: u64, dst_ring: usize, pos_ptr: u64, log_alpha: f32, log_floor: f32) -> anyhow::Result<()> { + anyhow::ensure!(w <= 128, "ink_clip_pos: w={w} > 128"); + anyhow::ensure!(crate::cuda::kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); + let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; + let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; + launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), + x, scale, w as i32, thr, eps, mul, dst, 0i32, ring as i32, 0i32, log_alpha, fl, pos_ptr); + Ok(()) + } + + fn ink_attn(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, rows: usize, at: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { + let (kn, ck) = self.ink_attn_kernel(hd, nr); + let chunks = rows.div_ceil(ck) as u32; + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); + launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); + Ok(()) + } + + fn ink_attn_pos(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, max_rows: usize, ring: usize, pos_ptr: u64, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { + let (kn, ck) = self.ink_attn_kernel(hd, nr); + let chunks = max_rows.div_ceil(ck) as u32; + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); + launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); + Ok(()) + } + + fn ink_attn_prefill(&self, q: u64, r: u64, sink: u64, gate: u64, kc: u64, vc: u64, kc_new: u64, vc_new: u64, bias: u64, out: u64, + pos: usize, nt: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize, ring: usize, win: usize) -> anyhow::Result<()> { + // The key-parallel kernels are the same choice as CUDA's; they need the f16 cache (kp16/kp are compiled + // for KV_MODE 0 only). `win` rides in the kernel's `ring` argument as on CUDA's old path. + if hd == 128 && self.kv_mode == 0 && (self.flags.fast || self.flags.attn_kp4) && !self.flags.attn_old { + let (kn, qb) = if self.flags.attn_kp4 { ("ink_attn_prefill_128_kp", 4) } else { ("ink_attn_prefill_128_kp16", 16) }; + launch!(self, kn, cfg((nt.div_ceil(qb) as u32, nh as u32), 128, 0), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); + return Ok(()); + } + if hd == 128 && self.flags.attn_old { + launch!(self, "ink_attn_prefill_128_old", cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); + return Ok(()); + } + let kn = match hd { + 32 => "ink_attn_prefill_32", + 64 => "ink_attn_prefill_64", + 128 => "ink_attn_prefill_128", + _ => bail!("ink_attn_prefill: unsupported hd={hd}"), + }; + launch!(self, kn, cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); + Ok(()) + } + + fn ink_ffn_sum_n(&self, acc: u64, d: u64, wts: u64, ne: usize, n: usize, nt: usize, cpu: u64) -> anyhow::Result<()> { + launch!(self, "ink_ffn_sum", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), acc, d, wts, ne as i32, n as i32, cpu); + Ok(()) + } + + fn ink_pool(&self) -> bool { true } + fn ink_slots(&self, ids: u64, wts: u64, table: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, k: usize) -> anyhow::Result<()> { + anyhow::ensure!(k <= 32, "ink_slots: k={k}"); + launch!(self, "ink_slots", cfg((1, 1), 256, 0), ids, wts, table, slots, wh, h, mb, nh as i32, h_off as i32, step, k as i32); + Ok(()) + } + fn ink_ffn_sum_mb(&self, acc: u64, d: u64, wh: u64, k: usize, n: usize, mb: u64, y_off: usize, step: u64, slots: u64) -> anyhow::Result<()> { + launch!(self, "ink_ffn_sum_mb", cfg((n.div_ceil(256) as u32, 1), 256, 0), acc, d, wh, k as i32, n as i32, mb, y_off as i32, step, slots); + Ok(()) + } + fn ink_route(&self, logits: u64, bias: u64, ids: u64, wts: u64, gu_sc: u64, dn_sc: u64, gsc_out: u64, n_expert: usize, k: usize, exp_scale: f32, rows: usize) -> anyhow::Result<()> { + anyhow::ensure!(n_expert <= 512 && k <= 32, "ink_route: n_expert={n_expert} k={k}"); + launch!(self, "ink_route", cfg((rows as u32, 1), 32, 0), logits, bias, ids, wts, gu_sc, dn_sc, gsc_out, n_expert as i32, k as i32, exp_scale); + Ok(()) + } + + fn dflash2_conv(&self, x: u64, dyn_w: u64, base: u64, out: u64, h: usize, gs: usize, k: usize, t: usize, part: usize) -> anyhow::Result<()> { + launch!(self, "dflash2_conv", cfg((h.div_ceil(256) as u32, t as u32), 256, 0), x, dyn_w, base, out, h as i32, gs as i32, k as i32, t as i32, part as i32); + Ok(()) + } + + fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, + scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { + if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } + // The tile depth has to be the one the kernel picks for itself (`FA_BK_FOR(HD)`, which takes 16 keys rather than + // 32 at head_dim 256): 32 keys plus the score staging tile need 78 KiB, more than a 64 KiB workgroup may use, + // while 16 keys need 58 KiB. A smaller depth here would under-allocate what the kernel addresses. + let bk = if hd == 256 { 16 } else { FA_BK }; + // The HIP kernel stages its matrix-core scores through an extra FA_BQ x (bk + 8) f32 tile (see attn_prefill_t); + // the qs/ks/vs/ps sizes the shared helper computes are the same as CUDA's. + let smem = (attn_prefill_smem_bk(hd, bk) + 4 * crate::cuda::FA_BQ * (bk + 8)) as u32; + // The V-turbo inverse-rotation tile is static shared memory in the compiled kernel (`__shared__ float + // tro[2][4][128]` in attn_prefill_t): the runtime adds it on top of the dynamic request, so it counts + // against the workgroup limit but must not be part of the launch size (a 64 KiB card then rejects the + // dispatch as HSA_STATUS_ERROR_INVALID_ALLOCATION). + let stat = if self.kv_v_mode >= 4 { 2 * 4 * 128 * 4 } else { 0 }; + anyhow::ensure!(smem as usize + stat <= self.max_smem, "attn_prefill_{hd}: {smem} B dynamic + {stat} B static shared memory, {} allowed", self.max_smem); + launch!(self, &format!("attn_prefill_{hd}"), cfg((t.div_ceil(64) as u32, nh as u32), 128, smem), + q, kc, vc, qg, out, step, t as i32, nh as i32, nkv as i32, scale, qm, mw as i32, sink, win as i32); + Ok(()) + } + + fn qsa_pool(&self, ik: u64, ring: u64, pool: u64, w: u64, step: u64, t: usize, n_rot: usize, base: f32, eps: f32) -> anyhow::Result<()> { + launch!(self, "qsa_pool", cfg(((t / 4 + 1) as u32, 1), 128, 0), ik, ring, pool, w, step, t as i32, n_rot as i32, base, eps); + Ok(()) + } + + fn qsa_select(&self, q: u64, pool: u64, score: u64, sel: u64, mask: u64, step: u64, r0: usize, rows: usize, nbs: usize, top: usize, sst: usize, mw: usize) -> anyhow::Result<()> { + launch!(self, "qsa_score", cfg((64, rows.div_ceil(8) as u32), 256, 0), q, pool, score, step, r0 as i32, rows as i32, nbs as i32, top as i32); + launch!(self, "qsa_select", cfg((rows as u32, 1), 1024, 0), score, sel, mask, step, r0 as i32, nbs as i32, top as i32, sst as i32, mw as i32); + Ok(()) + } + + fn moe_combine_seq(&self, x: u64, ye: u64, wts: u64, inv: u64, k: usize, sh: u64, sg: u64, n: usize, t: usize) -> anyhow::Result<()> { + launch!(self, "moe_combine_seq", Self::grid(n * t), x, ye, wts, inv, k as i32, sh, sg, n as i32, t as i32); + Ok(()) + } + + /// Lightning-indexer scores: a few queries take `idx_score_dec`, a prompt `idx_score`, as on CUDA. + /// `STRATA_IDX_WMMA=1` runs a prompt's scores on the matrix cores (`idx_score_wmma`, f16 products), which changes + /// which keys a query selects where scores are close (docs/HIP.md). + fn idx_score(&self, q: u64, w: u64, k: u64, out: u64, nt: usize, nk: usize, nh: usize, hd: usize) -> anyhow::Result<()> { + anyhow::ensure!(hd == 128, "idx_score: head dim {hd} not supported"); + // A few queries (decode): the 64-query tile would compute 60 or more rows for nothing. + if nt <= 4 && nh % 8 == 0 && nh <= 64 { + launch!(self, "idx_score_dec", cfg((nk.div_ceil(32) as u32, nt as u32), 256, 0), q, w, k, out, nk as i32, nh as i32); + } else { + // A block takes 64 keys and 64 queries (`t0 = blockIdx.y * 64` in both kernels). + let name = if self.idx_wmma && nh <= 64 { "idx_score_wmma" } else { "idx_score" }; + launch!(self, name, cfg((nk.div_ceil(64) as u32, nt.div_ceil(64) as u32), 256, 0), q, w, k, out, nt as i32, nk as i32, nh as i32); + } + Ok(()) + } + + /// Absorbed MLA attention. CUDA's prompt kernel (`mla_attn_tc`) needs m16n8k16, which Wave32 cards (gfx11/12) do + /// not have; a prompt or split queries take `mla_attn_wmma` instead, the same kernel on the WMMA matrix cores. + /// Without WMMA (`STRATA_HIP_WMMA=0`, `STRATA_MLA_SIMT`, an unsupported shape) the one-wave-a-head kernel runs + /// every query count, its split or scaled queries packed into whole scaled rows by `mla_qpack` first. Key + /// splitting is like CUDA's. + fn mla_attn(&self, q: u64, kc: u64, idx: u64, cnt: u64, out: u64, nt: usize, nh: usize, hd: usize, vd: usize, ns: usize, nmax: usize, qp: u64, qps: usize, qsc: f32) -> anyhow::Result<()> { + // A prompt or split queries: 32 heads a block on the matrix cores (`mla_attn_wmma`), else 4 (one wave a head). + let wm = (nt > 1 || qp != 0) && self.mla_wmma && nh % 32 == 0 && hd % 32 == 0 && hd <= 576 && vd % 64 == 0 && vd <= 512 + && vd <= hd; + let packed = if !wm && (qp != 0 || qsc != 1.0) { + let b = self.alloc(4 * nt * nh * hd)?; + launch!(self, "mla_qpack", Self::grid(nt * nh * hd), q, qp, qps as i32, qsc, b.addr(), (nt * nh) as i32, hd as i32, vd as i32); + Some(b) + } else { None }; + let (q, qp, qsc) = match &packed { Some(b) => (b.addr(), 0u64, 1.0f32), None => (q, qp, qsc) }; + let hb = if wm { 32 } else { 4 }; + let smem = if wm { 2 * 32 * (hd + 8) + 4 * 2 * 32 * 33 + 2 * 32 * 40 + 4 * 64 } else { 4 * hb * hd + 128 * (hd / 2 + 1) }; + anyhow::ensure!(hd % 2 == 0 && vd % 64 == 0 && vd <= 512 && vd <= hd && nh % hb == 0 && smem <= self.max_smem, "mla_attn: unsupported shape nh={nh} hd={hd} vd={vd}"); + let blocks = nt * nh / hb; + let nsp = (8 * self.sms).div_ceil(blocks).min(nmax.div_ceil(128)).max(1); + let part = if nsp > 1 { Some(self.alloc(nt * nh * nsp * (vd + 2) * 4)?) } else { None }; + let pa = part.as_ref().map_or(0, |b| b.addr()); + let lc = LaunchConfig { grid_dim: (nt as u32, (nh / hb) as u32, nsp as u32), block_dim: (if wm { 256 } else { 128 }, 1, 1), shared_mem_bytes: smem as u32 }; + if wm { + launch!(self, "mla_attn_wmma", lc, q, kc, idx, cnt, out, pa, nh as i32, hd as i32, vd as i32, ns as i32, nsp as i32, qp, qps as i32, qsc); + } else { + launch!(self, "mla_attn", lc, q, kc, idx, cnt, out, pa, nh as i32, hd as i32, vd as i32, ns as i32, nsp as i32); + } + if nsp > 1 { launch!(self, "mla_combine", cfg(((nt * nh) as u32, 1), 128, 0), pa, out, vd as i32, nsp as i32); } + Ok(()) + } + + fn norm_gate(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32) -> anyhow::Result<()> { + self.norm_gate_q(o, w, z, n, heads, eps, 0).map(|_| ()) + } + + fn norm_gate_q(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32, xq: u64) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() || n % 32 != 0 { 0 } else { xq }; + launch!(self, "norm_gate", cfg((heads as u32, 1), 128, 0), o, w, z, n as i32, eps, xq, 0i32); + Ok(xq) + } + + fn norm_gate_sig(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32, xq: u64) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() || n % 32 != 0 { 0 } else { xq }; + launch!(self, "norm_gate", cfg((heads as u32, 1), 128, 0), o, w, z, n as i32, eps, xq, 1i32); + Ok(xq) + } + + fn hc_silu(&self, x: u64, sc: f32, n: usize) -> anyhow::Result<()> { + launch!(self, "hc_silu", Self::grid(n), x, sc, n as i32); + Ok(()) + } + + fn hc_mix(&self, xn: u64, g: u64, out: u64, n: usize, hc: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "hc_mix", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), xn, g, out, n as i32, hc as i32); + Ok(()) + } + + fn hc_write(&self, r: u64, out: u64, inj: u64, n: usize, hc: usize, nt: usize, clear: bool) -> anyhow::Result<()> { + launch!(self, "hc_write", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), r, out, inj, n as i32, hc as i32, clear as i32); + Ok(()) + } + + fn ple_gate(&self, key: u64, query: u64, value: u64, gated: u64, n: usize, hc: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ple_gate", cfg((hc as u32, nt as u32), 256, 0), key, query, value, gated, n as i32); + Ok(()) + } + + fn ple_conv(&self, r: u64, gated: u64, norm: u64, kw: u64, ring: u64, step: u64, d: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ple_conv", Self::grid(d), r, gated, norm, kw, ring, step, d as i32, nt as i32); + Ok(()) + } + + fn kv_store(&self, k: u64, v: u64, kc: u64, vc: u64, n: usize, t: usize, step: u64, hd: usize) -> anyhow::Result<()> { + anyhow::ensure!((self.kv_k_mode == 0 && self.kv_v_mode == 0) || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32"); + if self.kv_k_mode >= 4 || self.kv_v_mode >= 4 { + anyhow::ensure!(hd % 128 == 0, "TurboQuant KV needs head_dim divisible by 128, got {hd}"); + launch!(self, "kv_store_turbo", cfg(((n * t / 128) as u32, 1), 128, 0), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + } else { + launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + } + Ok(()) + } + + fn attn_decode_gq(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, + scale: f32, gq_min: i32, nt: usize, sink: u64, win: usize) -> anyhow::Result<()> { + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, 0, 0, 0, sink, win, 0, ATT_SPLITS_1) + } + + fn attn_decode_q(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, + scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() { 0 } else { xq }; + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, xq, sel, sst, sink, win, 0, ATT_SPLITS_1)?; + Ok(xq) + } + + fn router_topk(&self, p: u64, n: usize, k: usize, extra_scale: f32, ids: u64, wts: u64, t: usize, sigmoid: bool) -> anyhow::Result<()> { + anyhow::ensure!(n <= 512 && k <= 32, "router_topk: {n} experts, top {k}"); + launch!(self, "router_topk", cfg((t as u32, 1), 32, 0), p, n as i32, k as i32, extra_scale, ids, wts, sigmoid as i32); + Ok(()) + } + + fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, + mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool, hid: u64, hmin: i32) -> anyhow::Result<()> { + let _ = (hid, hmin); + anyhow::ensure!(n <= 512 && k <= 32, "moe_route: {n} experts, top {k}"); + launch!(self, "moe_route", cfg((1, 1), 256, 0), p, n as i32, k as i32, extra_scale, table, ids, wts, slots, wh, h, mb, + nh as i32, h_off as i32, step, t as i32, pid, sigmoid as i32, 0u64, 0i32); + Ok(()) + } + + fn moe_mailbox_optional(&self) -> bool { true } + fn moe_prefetch_supported(&self) -> bool { false } + + fn moe_combine(&self, x: u64, ye: u64, w: u64, k: usize, sh: u64, sg: u64, mb: u64, y_off: usize, step: u64, slots: u64, n: usize, t: usize) -> anyhow::Result<()> { + let mut c = Self::grid(n); + c.grid_dim.1 = t as u32; + launch!(self, "moe_combine", c, x, ye, w, k as i32, sh, sg, mb, y_off as i32, step, slots, n as i32); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The whole plumbing on the device: allocate, upload, launch a real kernel, read it back. `add` is the + /// simplest kernel in the file, so a failure here is the backend, not the math. + #[test] + fn add_kernel_round_trips() { + let g = match Gpu::new(0) { + Ok(g) => g, + Err(e) => { + eprintln!("skipping: HIP unavailable: {e:#}"); + return; + } + }; + let n = 1024; + let x: Vec = (0..n).map(|i| i as f32).collect(); + let y: Vec = (0..n).map(|i| 0.5 * i as f32).collect(); + let want: Vec = (0..n).map(|i| 1.5 * i as f32).collect(); + let g: &dyn Backend = &g; + let bx = g.alloc(4 * n).unwrap(); + let by = g.alloc(4 * n).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.put(&y, &by, 0).unwrap(); + // `Backend::add` is x += y, so the result lands in x. + g.add(bx.addr(), by.addr(), n).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bx, 0, n).unwrap(); + assert!(got.iter().zip(&want).all(|(a, b)| a == b), "first mismatch at {:?}", got.iter().zip(&want).position(|(a, b)| a != b)); + } + + /// `argmax_rows` on 64 rows, the most a batch step has. The partials are 8 bytes each, AMAX_PARTS per row; the + /// buffer used to be sized as if they were one byte, so rows past 8 wrote past its end. + #[test] + fn argmax_rows_takes_64_rows() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (rows, n) = (64usize, 1000usize); + // Each row is a permutation of 0..n, so its maximum is unique and the reference needs no tie rule. + let x: Vec = (0..rows * n).map(|k| { let (r, i) = (k / n, k % n); ((i * 7919 + r * 31) % n) as f32 }).collect(); + let want: Vec = (0..rows).map(|r| { + let row = &x[r * n..(r + 1) * n]; + let mut best = 0; + for i in 1..n { if row[i] > row[best] { best = i; } } + best as i32 + }).collect(); + let bx = g.alloc(4 * rows * n).unwrap(); + let bo = g.alloc(4 * rows).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.argmax_rows(bx.addr(), n, rows, bo.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bo, 0, rows).unwrap(); + assert_eq!(got, want); + } + + /// `argmax_rows` on values 0..16, so most rows tie for the maximum: the first index wins, as in the CPU reference. + #[test] + fn argmax_rows_breaks_ties_at_the_first_index() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (rows, n) = (64usize, 1000usize); + let mut st = 77u32; + let x: Vec = (0..rows * n).map(|_| { st = st.wrapping_mul(1664525).wrapping_add(1013904223); ((st >> 16) % 16) as f32 }).collect(); + let want: Vec = (0..rows).map(|r| { + let row = &x[r * n..(r + 1) * n]; + let mut best = 0; + for i in 1..n { if row[i] > row[best] { best = i; } } + best as i32 + }).collect(); + assert!(want.iter().enumerate().any(|(r, &b)| x[r * n..(r + 1) * n].iter().filter(|&&v| v == x[r * n + b as usize]).count() > 1), "no row has a tie"); + let bx = g.alloc(4 * rows * n).unwrap(); + let bo = g.alloc(4 * rows).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.argmax_rows(bx.addr(), n, rows, bo.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bo, 0, rows).unwrap(); + assert_eq!(got, want); + } + + /// `--backend hip` reaches this backend through `backend::open`, the path the CLI takes. + #[test] + fn opens_through_backend_open() { + let Ok(b) = crate::backend::open(Some("hip"), 0) else { eprintln!("skipping: no HIP device"); return }; + assert_eq!(b.name(), "hip"); + } + + /// `norm_gate` with the quantize-to-int8 epilogue: the first kernel of the qwen35 attention layer, and the one + /// that faulted first on the card, so it gets its own comparison against the reference math. + #[test] + fn norm_gate_matches_the_reference() { + let g = match Gpu::new(0) { Ok(g) => g, Err(e) => { eprintln!("skipping: HIP unavailable: {e:#}"); return } }; + let (heads, n) = (4usize, 128usize); + let mut st = 12345u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 8) as f32 / 16777216.0 - 0.5 }; + let o: Vec = (0..heads * n).map(|_| rnd()).collect(); + let w: Vec = (0..n).map(|_| rnd() + 1.0).collect(); + let z: Vec = (0..heads * n).map(|_| rnd()).collect(); + let want: Vec = (0..heads).flat_map(|h| { + let row = &o[h * n..(h + 1) * n]; + let ss: f32 = row.iter().map(|v| v * v).sum(); + let sc = 1.0 / (ss / n as f32 + 1e-6).sqrt(); + let silu = |v: f32| v / (1.0 + (-v).exp()); + (0..n).map(|i| row[i] * sc * w[i] * silu(z[h * n + i])).collect::>() + }).collect(); + let gx = g.alloc(4 * heads * n).unwrap(); + let gw = g.alloc(4 * n).unwrap(); + let gz = g.alloc(4 * heads * n).unwrap(); + let xq_bytes = heads * n + heads * n / 32 * 4; + let gxq = g.alloc(xq_bytes).unwrap(); + let g: &dyn Backend = &g; + g.put(&o, &gx, 0).unwrap(); + g.put(&w, &gw, 0).unwrap(); + g.put(&z, &gz, 0).unwrap(); + g.norm_gate(gx.addr(), gw.addr(), gz.addr(), n, heads, 1e-6).unwrap(); + g.sync().unwrap(); + eprintln!("plain norm_gate ok: {:?}", &g.get::(&gx, 0, 2).unwrap()); + g.put(&o, &gx, 0).unwrap(); + g.norm_gate_q(gx.addr(), gw.addr(), gz.addr(), n, heads, 1e-6, gxq.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&gx, 0, heads * n).unwrap(); + let worst = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst < 2e-5, "max |diff| = {worst}"); + } + + /// `gemm_dense` against a CPU product, both tile regimes: the 16-position warp tile (`SM`) the small shapes take + /// and the 32-position one, which is what the matrix-core path in `gemm_q` computes. + #[test] + fn gemm_dense_matches_cpu_in_both_tile_regimes() { + let Ok(g) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + for (rows, n, cols) in [(128usize, 64usize, 64usize), (8192, 128, 64)] { + let mut st = 7u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let w: Vec = (0..rows * cols).map(|_| rnd()).collect(); + let x: Vec = (0..n * cols).map(|_| rnd()).collect(); + let mut want = vec![0f32; n * rows]; + for m in 0..n { + for r in 0..rows { + let mut a = 0f32; + for k in 0..cols { a += x[m * cols + k] * w[r * cols + k]; } + want[m * rows + r] = a; + } + } + let gw = g.alloc(4 * rows * cols).unwrap(); + let gx = g.alloc(4 * n * cols).unwrap(); + let gy = g.alloc(4 * n * rows).unwrap(); + let g: &dyn Backend = &g; + g.put(&w, &gw, 0).unwrap(); + g.put(&x, &gx, 0).unwrap(); + let t = GpuTensor::new(GgmlType::F32, rows, cols, gw); + g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, 0).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&gy, 0, n * rows).unwrap(); + // A batch step's flag picks no other kernel here, so it gives the same bits. The host masks the flag off + // (`act & 3`), so this call stores over y. If the flag ever reached the kernel as `act` 8, the kernel would add + // to the ones and the bit comparison below would fail. + g.put(&vec![1f32; n * rows], &gy, 0).unwrap(); + g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, crate::backend::BATCHED).unwrap(); + g.sync().unwrap(); + let batched: Vec = g.get(&gy, 0, n * rows).unwrap(); + assert!(got.iter().zip(&batched).all(|(a, b)| a.to_bits() == b.to_bits()), "rows {rows}: BATCHED changed the result"); + let mut worst = 0f32; + let mut at = 0; + for i in 0..n * rows { + let d = (got[i] - want[i]).abs(); + if d > worst { worst = d; at = i; } + } + // f32 products summed over 64 terms: a few ulps either way, and f16 inputs quantize harder, so compare by + // relative error against the magnitude of the row's terms. + assert!(worst < 1e-2 * cols as f32, "rows {rows}: max |diff| = {worst} at {at} (got {}, want {})", got[at], want[at]); + } + } + + /// `attn_prefill_t` end to end (score product, causal softmax, P·V, the epilogue) against a CPU reference, at + /// head_dim 128 with three query tiles and five key tiles and at head_dim 256 (the HIP build's 16-key tiles). + /// A wrong lane/lane-staging mapping, a lost half of a fragment or a missing key shows up as a large per-element + /// difference on a specific query or head — which is how the transposed-V bug below was found — rather than as + /// the near-tie token flip a parity run sees. + #[test] + fn attn_prefill_matches_cpu() { + use half::f16; + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (nh, nkv) = (4usize, 2usize); + for (hd, t) in [(128usize, 130usize), (256, 70)] { + let scale = 1.0 / (hd as f32).sqrt(); + let mut st = 99u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let q: Vec = (0..t * nh * hd).map(|_| rnd()).collect(); + let kh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let vh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let half = |h: u16| f16::from_bits(h).to_f32(); + // Reference: the kernel scales Q before rounding it to f16, sums in f32, rounds the weights to f16 to + // feed P·V, and divides by the row sum at the end (`out = o * inv` with `inv = sc / den`). + let mut want = vec![0f32; t * nh * hd]; + for h in 0..nh { + let kvh = h / (nh / nkv); + for ti in 0..t { + let mut sc = vec![0f32; ti + 1]; + for (j, s) in sc.iter_mut().enumerate() { + let mut a = 0f32; + for d in 0..hd { + a += half(f16::from_f32(q[ti * nh * hd + h * hd + d] * scale).to_bits()) + * half(kh[(j * nkv + kvh) * hd + d]); + } + *s = a; + } + let mx = sc.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let e: Vec = sc.iter().map(|s| (s - mx).exp()).collect(); + let den: f32 = e.iter().sum(); + for d in 0..hd { + let mut a = 0f32; + for (j, w) in e.iter().enumerate() { + a += half(f16::from_f32(w / den).to_bits()) * half(vh[(j * nkv + kvh) * hd + d]); + } + want[ti * nh * hd + h * hd + d] = a; + } + } + } + let gq = g.alloc(4 * q.len()).unwrap(); + let gk = g.alloc(2 * kh.len()).unwrap(); + let gv = g.alloc(2 * vh.len()).unwrap(); + let go = g.alloc(4 * q.len()).unwrap(); + let gs = g.alloc(4).unwrap(); + g.put(&q, &gq, 0).unwrap(); + g.put(&kh, &gk, 0).unwrap(); + g.put(&vh, &gv, 0).unwrap(); + g.put(&[0i32], &gs, 0).unwrap(); + g.attn_prefill_m(gq.addr(), gk.addr(), gv.addr(), 0, go.addr(), gs.addr(), t, nh, nkv, hd, scale, 0, 0, 0, 0).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&go, 0, q.len()).unwrap(); + let mut worst = 0f32; + let (mut at, mut gv_) = (0, 0f32); + for i in 0..q.len() { + let d = (got[i] - want[i]).abs(); + if d > worst { worst = d; at = i; gv_ = got[i]; } + } + eprintln!("hd {hd} T {t}: max |diff| = {worst:e} at {at} (row {}, head {}, d {}): got {gv_} want {}", + at / (nh * hd), (at / hd) % nh, at % hd, want[at]); + assert!(worst < 5e-3, "hd {hd}: max |diff| = {worst} at {at}"); + } + } + + /// MLA prompt attention (`mla_attn` with several queries: `mla_attn_wmma` on WMMA cards) against an f64 reference + /// at GigaChat 4's shape (32 heads, rows of 576 = 512 latent + 64 rope, V the first 512): all positions up to the + /// query, a selected key list, split queries with a scale (`mla_prompt`'s form), and few queries, which split the + /// keys and go through `mla_combine`. + #[test] + fn mla_attn_prompt_matches_cpu() { + use half::f16; + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (nh, hd, vd) = (32usize, 576usize, 512usize); + let mut st = 7u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let nk = 700; + let kc: Vec = (0..nk * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let half = |h: u16| f16::from_bits(h).to_f32() as f64; + // (queries, selected keys a query or 0 for all up to it, split queries) + for (nt, sel, split) in [(40usize, 0usize, false), (40, 300, false), (37, 0, true), (3, 0, true), (2, 500, false)] { + let base = nk - nt; + let qsc = if split { 0.07f32 } else { 1.0 }; + let qf: Vec = (0..nt * nh * hd).map(|_| rnd() * if split { 1.0 } else { 0.07 }).collect(); + let (idx, cnt): (Vec, Vec) = if sel > 0 { + let mut idx = vec![0u32; nt * sel]; + for t in 0..nt { for j in 0..sel { idx[t * sel + j] = ((j * 7 + t * 13) % (base + t + 1)) as u32; } } + (idx, vec![sel as i32; nt]) + } else { (vec![], (0..nt).map(|t| (base + t + 1) as i32).collect()) }; + let mut want = vec![0f64; nt * nh * vd]; + for t in 0..nt { + let keys: Vec = (0..cnt[t] as usize).map(|j| if sel > 0 { idx[t * sel + j] as usize } else { j }).collect(); + for h in 0..nh { + let qr = &qf[(t * nh + h) * hd..][..hd]; + let qh: Vec = qr.iter().map(|&v| f16::from_f32(v * qsc).to_f32() as f64).collect(); + let s: Vec = keys.iter().map(|&k| (0..hd).map(|d| qh[d] * half(kc[k * hd + d])).sum()).collect(); + let mx = s.iter().cloned().fold(f64::NEG_INFINITY, f64::max); + let e: Vec = s.iter().map(|v| (v - mx).exp()).collect(); + let den: f64 = e.iter().sum(); + for d in 0..vd { + want[(t * nh + h) * vd + d] = keys.iter().zip(&e).map(|(&k, w)| w * half(kc[k * hd + d])).sum::() / den; + } + } + } + // Split form: the first vd dims a (query, head) in q, rows vd apart; the rest from the start of a qp row, rows + // qps = hd apart (`mla_prompt` points qp at the rope part of its query rows). + let (qbuf, qpbuf): (Vec, Vec) = if split { + (qf.chunks_exact(hd).flat_map(|r| r[..vd].to_vec()).collect(), qf.chunks_exact(hd).flat_map(|r| { let mut v = r[vd..].to_vec(); v.resize(hd, 0.0); v }).collect()) + } else { (qf.clone(), vec![]) }; + let gq = g.alloc(4 * qbuf.len()).unwrap(); + let gqp = g.alloc(4 * qpbuf.len().max(1)).unwrap(); + let gk = g.alloc(2 * kc.len()).unwrap(); + let gi = g.alloc(4 * idx.len().max(1)).unwrap(); + let gc = g.alloc(4 * nt).unwrap(); + let go = g.alloc(4 * want.len()).unwrap(); + g.put(&qbuf, &gq, 0).unwrap(); + if split { g.put(&qpbuf, &gqp, 0).unwrap(); } + g.put(&kc, &gk, 0).unwrap(); + if sel > 0 { g.put(&idx, &gi, 0).unwrap(); } + g.put(&cnt, &gc, 0).unwrap(); + let (qp, qps) = if split { (gqp.addr(), hd) } else { (0, 0) }; + g.mla_attn(gq.addr(), gk.addr(), if sel > 0 { gi.addr() } else { 0 }, gc.addr(), go.addr(), nt, nh, hd, vd, sel, + *cnt.iter().max().unwrap() as usize, qp, qps, qsc).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&go, 0, want.len()).unwrap(); + let scale = want.iter().fold(0f64, |a, &v| a.max(v.abs())); + let worst = got.iter().zip(&want).map(|(&a, &b)| (a as f64 - b).abs()).fold(0f64, f64::max); + eprintln!("nt {nt} sel {sel} split {split}: max |diff| {worst:e} of max |want| {scale:e}"); + assert!(worst < 1e-3, "nt {nt} sel {sel} split {split}: max |diff| {worst} (max |want| {scale})"); + } + } + + /// Lightning-indexer scores (64 heads of 128) against an f64 reference: a prompt (`idx_score`, or `idx_score_wmma` + /// with f16 products under `STRATA_IDX_WMMA=1`) with partial query and key tiles, and two decode queries + /// (`idx_score_dec`). Only the scores + /// a query reads are compared: keys up to its own position. + #[test] + fn idx_score_matches_cpu() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (nh, hd) = (64usize, 128usize); + let mut st = 11u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + for (nt, nk, tol) in [(70usize, 300usize, if gpu.idx_wmma { 3e-3f64 } else { 1e-5 }), (2, 333, 1e-5)] { + let q: Vec = (0..nt * nh * hd).map(|_| 2.0 * rnd()).collect(); + let w: Vec = (0..nt * nh).map(|_| rnd() / 8.0).collect(); + let k: Vec = (0..nk * hd).map(|_| 2.0 * rnd()).collect(); + let (gq, gw, gk, go) = (g.alloc(4 * q.len()).unwrap(), g.alloc(4 * w.len()).unwrap(), g.alloc(4 * k.len()).unwrap(), g.alloc(4 * nt * nk).unwrap()); + g.put(&q, &gq, 0).unwrap(); + g.put(&w, &gw, 0).unwrap(); + g.put(&k, &gk, 0).unwrap(); + g.idx_score(gq.addr(), gw.addr(), gk.addr(), go.addr(), nt, nk, nh, hd).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&go, 0, nt * nk).unwrap(); + let (mut worst, mut scale) = (0f64, 0f64); + for t in 0..nt { + for j in 0..=(nk - nt + t) { + let want: f64 = (0..nh).map(|h| { + let d: f64 = (0..hd).map(|i| q[(t * nh + h) * hd + i] as f64 * k[j * hd + i] as f64).sum(); + d.max(0.0) * w[t * nh + h] as f64 + }).sum(); + scale = scale.max(want.abs()); + worst = worst.max((got[t * nk + j] as f64 - want).abs()); + } + } + eprintln!("nt {nt} nk {nk}: max |diff| {worst:e} of max |score| {scale:e}"); + assert!(worst <= tol * scale, "nt {nt} nk {nk}: max |diff| {worst} of {scale}"); + } + } + + /// `attn_prefill_t` with a QSA block mask, against the dense kernel run on the keys the mask keeps. The mask drops + /// the same 4-key blocks for every row, so taking those keys (and the query rows at their positions) out of Q, K + /// and V gives a dense problem whose causal rows see exactly what the masked rows see. Rows below the first + /// dropped block see an unchanged set; rows past it see the kept keys only. The dropped blocks sit in odd 16-key + /// tiles at head_dim 256 (the HIP build's tile depth), where the mask byte must be read relative to the tile. + #[test] + fn attn_prefill_mask_matches_dense_on_kept_keys() { + use half::f16; + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (nh, nkv, t) = (4usize, 2usize, 200usize); + // Blocks 8 (keys 32..35, an even 16-key tile), 13 (keys 52..55, odd tile k0 48) and 37 (keys 148..151, odd + // tile k0 144, mask word 1). + let drop = [8usize, 13, 37]; + let kept: Vec = (0..t).filter(|p| !drop.contains(&(p >> 2))).collect(); + let tc = kept.len(); + let mw = t.div_ceil(128) + 1; // one spare word, so a wrong row stride shows + let rows = t.div_ceil(64) * 64; // the kernel reads mask rows for the query tile padding too + let mut mask = vec![!0u32; rows * mw]; + for r in 0..rows { + for &b in &drop { mask[r * mw + (b >> 5)] &= !(1u32 << (b & 31)); } + } + let mut fails = Vec::new(); + for hd in [128usize, 256] { + let scale = 1.0 / (hd as f32).sqrt(); + let mut st = 7u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let q: Vec = (0..t * nh * hd).map(|_| rnd()).collect(); + let kh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let vh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let pick = |src: &[u16], w: usize| -> Vec { kept.iter().flat_map(|&p| src[p * w..(p + 1) * w].iter().copied()).collect() }; + let qc: Vec = kept.iter().flat_map(|&p| q[p * nh * hd..(p + 1) * nh * hd].iter().copied()).collect(); + let (kc, vc) = (pick(&kh, nkv * hd), pick(&vh, nkv * hd)); + let run = |q: &[f32], k: &[u16], v: &[u16], n: usize, qm: &[u32]| -> Vec { + let gq = g.alloc(4 * q.len()).unwrap(); + let gk = g.alloc(2 * k.len()).unwrap(); + let gv = g.alloc(2 * v.len()).unwrap(); + let go = g.alloc(4 * q.len()).unwrap(); + let gs = g.alloc(4).unwrap(); + let gm = g.alloc(4 * qm.len().max(1)).unwrap(); + g.put(q, &gq, 0).unwrap(); + g.put(k, &gk, 0).unwrap(); + g.put(v, &gv, 0).unwrap(); + g.put(&[0i32], &gs, 0).unwrap(); + let (qma, mwa) = if qm.is_empty() { (0, 0) } else { g.put(qm, &gm, 0).unwrap(); (gm.addr(), mw) }; + g.attn_prefill_m(gq.addr(), gk.addr(), gv.addr(), 0, go.addr(), gs.addr(), n, nh, nkv, hd, scale, qma, mwa, 0, 0).unwrap(); + g.sync().unwrap(); + g.get(&go, 0, q.len()).unwrap() + }; + let dense = run(&q, &kh, &vh, t, &[]); + let all = run(&q, &kh, &vh, t, &vec![!0u32; rows * mw]); + let masked = run(&q, &kh, &vh, t, &mask); + let want = run(&qc, &kc, &vc, tc, &[]); + // An all-kept mask takes the same path as no mask: bitwise. + let same = dense.iter().zip(&all).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + if same > 0 { fails.push(format!("hd {hd}: all-kept mask differs from qm = 0 in {same} values")); } + let mut worst = 0f32; + for (ci, &p) in kept.iter().enumerate() { + let w = nh * hd; + let d = masked[p * w..(p + 1) * w].iter().zip(&want[ci * w..(ci + 1) * w]).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); + worst = worst.max(d); + if d > 5e-3 { + eprintln!("hd {hd} row {p} (16-key tile {}, sees {} dropped blocks): max |diff| = {d:e}", p / 16, + drop.iter().filter(|&&b| 4 * b <= p).count()); + } + } + eprintln!("hd {hd}: masked vs dense-on-kept-keys max |diff| = {worst:e}"); + if worst >= 5e-3 { fails.push(format!("hd {hd}: masked rows differ from the dense reference by {worst}")); } + } + assert!(fails.is_empty(), "{fails:?}"); + } + + /// The decode attention's two regimes on one set of inputs. `attn_decode_gqa` (from `ATT_GQA_MIN` on) reads each + /// K/V row once for G query heads; `attn_decode` serves one head a block. Both are the same fp32 dots over the same + /// rows, so the GQA output must match the one-head output to f32 noise at any depth; this test exists because the + /// DFlash2 drafter (nh 32, nkv 8, G 4, hd 128) produced garbage above 2048 positions through the GQA path. + #[test] + fn attn_decode_gqa_matches_one_head_above_the_switch() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let q8 = crate::cuda::kv_q8(); + let (nh, nkv, hd) = (32usize, 8usize, 128usize); + let scale = 1.0 / (hd as f32).sqrt(); + let mut st = 11u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + for &depth in &[1500usize, 2100, 5000] { + let rows = depth + 8; + let row_w = if q8 { hd * 17 / 32 } else { hd }; + let mk = |rnd: &mut dyn FnMut() -> f32| -> Vec { + let mut v = vec![0u16; rows * nkv * row_w]; + for r in 0..rows * nkv { + if q8 { + for b in 0..hd / 32 { + v[r * row_w + hd / 2 + b] = half::f16::from_f32((rnd().abs() + 0.05) * 0.01).to_bits(); + for i in 0..16 { + // Two signed bytes a word, the even element low: both halves of the layout. + let (lo, hi) = ((rnd() * 25.0) as i8 as u8, (rnd() * 25.0) as i8 as u8); + v[r * row_w + b * 16 + i] = lo as u16 | (hi as u16) << 8; + } + } + } else { + for d in 0..hd { v[r * row_w + d] = half::f16::from_f32(rnd() * 0.1).to_bits(); } + } + } + v + }; + let kc = mk(&mut rnd); + let vc = mk(&mut rnd); + let pos = depth - 1; + let mut outs = Vec::new(); + // One query for both regimes, so they differ only in the kernel. + let q: Vec = (0..nh * hd).map(|_| rnd()).collect(); + for gq_min in [i32::MAX, 0] { + let gq = g.alloc(4 * q.len()).unwrap(); + let gk = g.alloc(2 * kc.len()).unwrap(); + let gv = g.alloc(2 * vc.len()).unwrap(); + // One split covers every case: ATT_SPLITS_1 (16) below the switch and ATT_SPLITS (32) above it, so the + // merge reads whatever the kernel wrote (a 16-split buffer under a 32-split merge reads as zeros). + let ns = 32; + let gp = g.alloc(4 * nh * ns * (hd + 2)).unwrap(); + let go = g.alloc(4 * q.len()).unwrap(); + let gs = g.alloc(8).unwrap(); + g.put(&q, &gq, 0).unwrap(); + g.put(&kc, &gk, 0).unwrap(); + g.put(&vc, &gv, 0).unwrap(); + g.put(&[pos as i32, 0], &gs, 0).unwrap(); + let zero = vec![0f32; nh * ns * (hd + 2)]; + g.put(&zero, &gp, 0).unwrap(); + g.attn_decode_gq(gq.addr(), gk.addr(), gv.addr(), 0, go.addr(), gp.addr(), gs.addr(), nh, nkv, hd, scale, gq_min, 1, 0, 0).unwrap(); + g.sync().unwrap(); + outs.push(g.get::(&go, 0, q.len()).unwrap()); + } + let d = outs[0].iter().zip(&outs[1]).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); + let mag = outs[0].iter().map(|v| v.abs()).fold(0f32, f32::max); + eprintln!("depth {depth}: one-head vs gqa max |diff| = {d:e}, max |out| = {mag:e}"); + assert!(d < 1e-4 * mag.max(1.0), "depth {depth}: the two decode-attention regimes disagree: {d:e} against |out| {mag:e}"); + } + } + + /// The desktop's VRAM is found on the card the device runs on, through its PCI address, and through the VRAM + /// size when no card has the address. + #[test] + fn drm_free_finds_the_device_by_its_pci_address() { + let g = match Gpu::new(0) { + Ok(g) => g, + Err(e) => { eprintln!("skipping: HIP unavailable: {e:#}"); return; } + }; + let Some(bus) = g.pci.clone() else { eprintln!("skipping: no PCI address from the runtime"); return }; + let (mut free, mut total) = (0usize, 0usize); + g.hip.check(unsafe { (g.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo").unwrap(); + let drm = drm_free(total, Some(&bus)).unwrap_or_else(|| panic!("no amdgpu card at {bus} in /sys/class/drm")); + eprintln!("{bus}: {:.2} GB free by the driver, {:.2} GB by HIP", drm as f64 / 1e9, free as f64 / 1e9); + assert!(drm <= total); + // The same card in another PCI function, which no card has: the size match finds the card. + let other = format!("{}{}", &bus[..bus.len() - 1], if bus.ends_with('7') { '6' } else { '7' }); + let by_size = drm_free(total, Some(&other)).expect("the VRAM size finds the card when no card has the address"); + assert!(by_size.abs_diff(drm) < 256 << 20, "{other}: {by_size} free, {bus}: {drm}"); + } + + /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). + #[test] + fn hiprtc_compiles_the_kernels() { + let Ok(rtc) = ffi::Rtc::get() else { + eprintln!("skipping: no hiprtc"); + return; + }; + let Ok(hip) = ffi::Hip::open() else { + eprintln!("skipping: no HIP runtime"); + return; + }; + let arch = hip.arch(0).unwrap(); + rtc.compile(&source(0, 0, true), "kernels.cu", &arch, &[]).expect("hiprtc compiles kernels.cu for the device"); + } + + /// The gfx11 (RDNA3) WMMA branch compiles, whatever card is present: its intrinsics, operand width and + /// `STRATA_WMMA_ROW` layout differ from gfx12's. Numerics on gfx11 need an RDNA3 card to check. + #[test] + fn hiprtc_compiles_the_kernels_for_gfx11() { + let Ok(rtc) = ffi::Rtc::get() else { + eprintln!("skipping: no hiprtc"); + return; + }; + rtc.compile(&source(0, 0, true), "kernels.cu", "gfx1100", &[]).expect("hiprtc compiles kernels.cu for gfx1100"); + } +} diff --git a/src/host_attn.rs b/src/host_attn.rs new file mode 100644 index 00000000..e00ef5c8 --- /dev/null +++ b/src/host_attn.rs @@ -0,0 +1,379 @@ +//! Decode attention on the CPU for KV caches in host RAM (`STRATA_KV_HOST`). The GPU copies the queries and +//! positions into mapped pinned memory, a stream host function runs this over the cache rows (the CPU reads RAM +//! far faster than the GPU does over PCIe), and `attn_merge` turns the one split per head into the output. +use rayon::prelude::*; + +/// Pointers are host addresses of mapped pinned memory (the same as their device addresses under UVA). +pub struct HostAttn { + pub q: usize, pub step: usize, pub part: usize, pub kc: usize, pub vc: usize, + pub nh: usize, pub nkv: usize, pub hd: usize, pub nt: usize, pub scale: f32, pub mode: u32, +} + +const CHUNK: usize = 1024; + +fn row_bytes(mode: u32, hd: usize) -> usize { + match mode { 0 => 2 * hd, 1 => hd + hd / 16, _ => hd / 2 + hd / 16 } +} + +/// Dequantize a cache row. q4 comes out permuted inside each 32-value block (the 16 low nibbles, then the 16 +/// high ones: values 0 2 4 .. 30, then 1 3 .. 31), which keeps the unpacking contiguous; `perm` maps a value index +/// to its place, and the queries and outputs use the same order. +#[inline(always)] +fn deq(mode: u32, r: &[u8], hd: usize, out: &mut [f32]) { + match mode { + 0 => for (o, c) in out[..hd].iter_mut().zip(r.chunks_exact(2)) { *o = half::f16::from_le_bytes([c[0], c[1]]).to_f32(); }, + 1 => for b in 0..hd / 32 { + let d = half::f16::from_le_bytes([r[hd + 2 * b], r[hd + 2 * b + 1]]).to_f32(); + let src: &[u8; 32] = r[b * 32..b * 32 + 32].try_into().unwrap(); + let dst: &mut [f32; 32] = (&mut out[b * 32..b * 32 + 32]).try_into().unwrap(); + for i in 0..32 { dst[i] = (src[i] as i8) as f32 * d; } + }, + _ => for b in 0..hd / 32 { + let d = half::f16::from_le_bytes([r[hd / 2 + 2 * b], r[hd / 2 + 2 * b + 1]]).to_f32(); + let src: &[u8; 16] = r[b * 16..b * 16 + 16].try_into().unwrap(); + let dst: &mut [f32; 32] = (&mut out[b * 32..b * 32 + 32]).try_into().unwrap(); + for i in 0..16 { + dst[i] = ((src[i] & 15) as f32 - 8.0) * d; + dst[16 + i] = ((src[i] >> 4) as f32 - 8.0) * d; + } + }, + } +} + +#[inline(always)] +fn perm(mode: u32, i: usize) -> usize { + if mode == 2 { let (b, w) = (i / 32, i % 32); b * 32 + if w % 2 == 0 { w / 2 } else { 16 + w / 2 } } else { i } +} + +#[inline(always)] +fn dot(a: &[f32], b: &[f32]) -> f32 { + // 64 lanes: four independent AVX-512 accumulators, so the FMAs do not wait on each other. + let mut s = [0f32; 16]; + for (x, y) in a.chunks_exact(16).zip(b.chunks_exact(16)) { for i in 0..16 { s[i] += x[i] * y[i]; } } + s.iter().sum() +} + +/// e^x for x <= 0 (softmax weights), ~1e-7 relative error, branch-free so loops over it vectorize. +#[inline(always)] +fn fexp(x: f32) -> f32 { + let x = x.max(-87.0); + let t = x * std::f32::consts::LOG2_E; + let fi = t.floor(); + let f = t - fi; + let p = 1.0 + f * (0.693_147_2 + f * (0.240_226_5 + f * (0.055_504_11 + f * (0.009_618_129 + f * (0.001_333_355_8 + f * 0.000_154_035_3))))); + f32::from_bits(((fi as i32 + 127) << 23) as u32) * p +} + +/// (max, sum, acc[nh * hd] in `perm` order) of positions `p0..p1` for one token; `q` is in `perm` order. +/// All `nt` tokens at once (each cache row is read once for all of them): `q` is [token][head][hd], token t sees +/// positions up to `lim[t]`; results are [token][head]. +fn chunk(a: &HostAttn, q: &[f32], lim: &[usize], p0: usize, p1: usize) -> (Vec, Vec, Vec) { + #[cfg(target_arch = "x86_64")] + if a.mode == 2 && a.hd % 32 == 0 && std::is_x86_feature_detected!("avx512f") && std::is_x86_feature_detected!("avx512bw") { + let grp = a.nh / a.nkv; + macro_rules! go { ($($g:literal),*; $($t:literal),*) => { go!(@g [$($g),*] [$($t),*]) }; + (@g [$($g:literal),*] $ts:tt) => { match grp { $( $g => go!(@t $g $ts), )* _ => None } }; + (@t $g:literal [$($t:literal),*]) => { match lim.len() { $( $t => Some(unsafe { avx512::chunk_q4::<$g, $t>(a, q, lim, p0, p1) }), )* _ => None } }; + } + if let Some(r) = go!(1, 2, 4, 6, 8; 1, 2, 3, 4) { return r; } + } + chunk_generic(a, q, lim, p0, p1) +} + +fn softmax_rows(sc: &mut [f32], nh: usize, n: usize) -> (Vec, Vec) { + let mut m = vec![f32::NEG_INFINITY; nh]; + let mut l = vec![0f32; nh]; + for h in 0..nh { + let s = &mut sc[h * n..(h + 1) * n]; + m[h] = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let mh = m[h]; + if mh == f32::NEG_INFINITY { s.fill(0.0); continue; } + let mut sum = 0.0; + for x in s.iter_mut() { *x = fexp(*x - mh); sum += *x; } + l[h] = sum; + } + (m, l) +} + +#[cfg(target_arch = "x86_64")] +mod avx512 { + use super::*; + use std::arch::x86_64::*; + + /// The 32 values of q4 block `b` of row `r`, scaled: (low nibbles = even values, high = odd), as `perm` orders them. + #[inline(always)] + unsafe fn blk(r: *const u8, hd: usize, b: usize) -> (__m512, __m512) { + unsafe { + let d = _mm512_set1_ps(half::f16::from_bits((r.add(hd / 2 + 2 * b) as *const u16).read_unaligned()).to_f32()); + let x = _mm512_cvtepu8_epi32(_mm_loadu_si128(r.add(16 * b) as *const __m128i)); + let e = _mm512_set1_ps(8.0); + let lo = _mm512_sub_ps(_mm512_cvtepi32_ps(_mm512_and_si512(x, _mm512_set1_epi32(15))), e); + let hi = _mm512_sub_ps(_mm512_cvtepi32_ps(_mm512_srli_epi32::<4>(x)), e); + (_mm512_mul_ps(lo, d), _mm512_mul_ps(hi, d)) + } + } + + /// K scores with int8 dot products (VNNI `vpdpbusd`, 64 products an instruction): the queries quantized to int8 + /// per 32-value block (as llama.cpp's q8_0 activations), the cache nibbles as unsigned bytes, and the -8 offset + /// folded in through each block's query sum. head_dim 256 (8 blocks: 4 vectors of 2 blocks, 8 f16 scales). + #[target_feature(enable = "avx512f,avx512bw,avx512vnni,f16c,avx2")] + unsafe fn kscores_vnni(a: &HostAttn, q: &[f32], lim: &[usize], p0: usize, p1: usize, sc: &mut [f32]) { + let (nh, nkv, hd) = (a.nh, a.nkv, a.hd); + let (rb, n, rows) = (hd / 2 + hd / 16, p1 - p0, T * nh); + let mut qq = vec![0i8; rows * hd]; + let mut qs = vec![0f32; rows * 64]; // per row, 4 vectors of 16 lanes: the block scale of each lane + let mut cl = vec![0f32; rows * 64]; // the scale times the block's int8 sum + for r in 0..rows { + for b in 0..8 { + let x = &q[r * hd + 32 * b..r * hd + 32 * b + 32]; + let mx = x.iter().fold(0f32, |m, v| m.max(v.abs())); + let d = mx / 127.0; + let id = if d > 0.0 { 1.0 / d } else { 0.0 }; + let mut sum = 0i32; + for i in 0..32 { let v = (x[i] * id).round() as i32; qq[r * hd + 32 * b + i] = v as i8; sum += v; } + for k in 0..8 { qs[r * 64 + 8 * b + k] = d; cl[r * 64 + 8 * b + k] = d * sum as f32; } + } + } + unsafe { + let m4 = _mm256_set1_epi8(15); + let order = _mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7); + let sidx: [__m512i; 4] = std::array::from_fn(|j| _mm512_setr_epi32( + 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, 2 * j as i32, + 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1, 2 * j as i32 + 1)); + let kc = a.kc as *const u8; + let (qqp, qsp, clp) = (qq.as_ptr(), qs.as_ptr(), cl.as_ptr()); + for p in p0..p1 { + for g in 0..nkv { + let r = kc.add((p * nkv + g) * rb); + let d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(_mm_loadu_si128(r.add(hd / 2) as *const __m128i))); + let mut z = [_mm512_setzero_si512(); 4]; + let mut dk = [_mm512_setzero_ps(); 4]; + for j in 0..4 { + let x = _mm256_loadu_si256(r.add(32 * j) as *const __m256i); + let lo = _mm256_and_si256(x, m4); + let hi = _mm256_and_si256(_mm256_srli_epi16::<4>(x), m4); + z[j] = _mm512_permutexvar_epi64(order, _mm512_inserti64x4::<1>(_mm512_castsi256_si512(lo), hi)); + dk[j] = _mm512_permutexvar_ps(sidx[j], d8); + } + for t in 0..T { + if p > lim[t] { continue; } + for h in 0..G { + let row = t * nh + g * G + h; + let mut acc = _mm512_setzero_ps(); + for j in 0..4 { + let dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), z[j], _mm512_loadu_si512(qqp.add(row * hd + 64 * j) as *const _)); + let v = _mm512_fmsub_ps(_mm512_cvtepi32_ps(dot), _mm512_loadu_ps(qsp.add(row * 64 + 16 * j)), _mm512_loadu_ps(clp.add(row * 64 + 16 * j))); + acc = _mm512_fmadd_ps(v, dk[j], acc); + } + *sc.get_unchecked_mut(row * n + p - p0) = _mm512_reduce_add_ps(acc) * a.scale; + } + } + } + } + } + } + + #[target_feature(enable = "avx512f,avx512bw,f16c")] + pub unsafe fn chunk_q4(a: &HostAttn, q: &[f32], lim: &[usize], p0: usize, p1: usize) -> (Vec, Vec, Vec) { + let (nh, nkv, hd, nt) = (a.nh, a.nkv, a.hd, T); + let (rb, nb, n) = (hd / 2 + hd / 16, hd / 32, p1 - p0); + let (kc, vc) = (a.kc as *const u8, a.vc as *const u8); + let rows = nt * nh; + let mut sc = vec![f32::NEG_INFINITY; rows * n]; + let qp = q.as_ptr(); + unsafe { + if nb == 8 && std::is_x86_feature_detected!("avx512vnni") { + kscores_vnni::(a, q, lim, p0, p1, &mut sc); + } else { + for p in p0..p1 { + for g in 0..nkv { + let r = kc.add((p * nkv + g) * rb); + for t in 0..T { + if p > lim[t] { continue; } + let mut acc = [_mm512_setzero_ps(); G]; + for b in 0..nb { + let (lo, hi) = blk(r, hd, b); + for h in 0..G { + let qh = qp.add((t * nh + g * G + h) * hd + 32 * b); + acc[h] = _mm512_fmadd_ps(lo, _mm512_loadu_ps(qh), acc[h]); + acc[h] = _mm512_fmadd_ps(hi, _mm512_loadu_ps(qh.add(16)), acc[h]); + } + } + for h in 0..G { sc[(t * nh + g * G + h) * n + p - p0] = _mm512_reduce_add_ps(acc[h]) * a.scale; } + } + } + } + } + let (m, l) = softmax_rows(&mut sc, rows, n); + let mut out = vec![0f32; rows * hd]; + // V by 32-value block: the accumulators of the G heads of each token stay in registers (or L1) over all positions. + for g in 0..nkv { + for b in 0..nb { + // One token at a time: 2 G accumulators stay in registers (all T tokens' would spill). + for t in 0..T { + let mut al = [_mm512_setzero_ps(); G]; + let mut ah = [_mm512_setzero_ps(); G]; + let pe = p1.min(lim[t] + 1); + for p in p0..pe { + let (lo, hi) = blk(vc.add((p * nkv + g) * rb), hd, b); + for h in 0..G { + let w = _mm512_set1_ps(*sc.get_unchecked((t * nh + g * G + h) * n + p - p0)); + al[h] = _mm512_fmadd_ps(w, lo, al[h]); + ah[h] = _mm512_fmadd_ps(w, hi, ah[h]); + } + } + for h in 0..G { + let o = out.as_mut_ptr().add((t * nh + g * G + h) * hd + 32 * b); + _mm512_storeu_ps(o, al[h]); + _mm512_storeu_ps(o.add(16), ah[h]); + } + } + } + } + (m, l, out) + } + } +} + +fn chunk_generic(a: &HostAttn, q: &[f32], lim: &[usize], p0: usize, p1: usize) -> (Vec, Vec, Vec) { + let w = a.nh * a.hd; + let (mut m, mut l, mut acc) = (vec![], vec![], vec![]); + for (t, <) in lim.iter().enumerate() { + let e = (lt + 1).min(p1).max(p0); + let (mt, lt, at) = if e > p0 { chunk1(a, &q[t * w..(t + 1) * w], p0, e) } else { (vec![f32::NEG_INFINITY; a.nh], vec![0.0; a.nh], vec![0.0; w]) }; + m.extend(mt); l.extend(lt); acc.extend(at); + } + (m, l, acc) +} + +fn chunk1(a: &HostAttn, q: &[f32], p0: usize, p1: usize) -> (Vec, Vec, Vec) { + let (nh, nkv, hd) = (a.nh, a.nkv, a.hd); + let grp = nh / nkv; + let rb = row_bytes(a.mode, hd); + let kc = unsafe { std::slice::from_raw_parts(a.kc as *const u8, p1 * nkv * rb) }; + let vc = unsafe { std::slice::from_raw_parts(a.vc as *const u8, p1 * nkv * rb) }; + let n = p1 - p0; + let mut sc = vec![0f32; nh * n]; + let mut row = vec![0f32; hd]; + for p in p0..p1 { + for g in 0..nkv { + let r = (p * nkv + g) * rb; + deq(a.mode, &kc[r..r + rb], hd, &mut row); + for h in g * grp..(g + 1) * grp { sc[h * n + p - p0] = dot(&q[h * hd..(h + 1) * hd], &row) * a.scale; } + } + } + let mut m = vec![f32::NEG_INFINITY; nh]; + let mut l = vec![0f32; nh]; + for h in 0..nh { + let s = &mut sc[h * n..(h + 1) * n]; + m[h] = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let mh = m[h]; + if mh == f32::NEG_INFINITY { s.fill(0.0); continue; } + let mut sum = 0.0; + for x in s.iter_mut() { *x = fexp(*x - mh); sum += *x; } + l[h] = sum; + } + let mut acc = vec![0f32; nh * hd]; + for p in p0..p1 { + for g in 0..nkv { + let r = (p * nkv + g) * rb; + deq(a.mode, &vc[r..r + rb], hd, &mut row); + for h in g * grp..(g + 1) * grp { + let w = sc[h * n + p - p0]; + for (o, v) in acc[h * hd..(h + 1) * hd].iter_mut().zip(&row) { *o += w * v; } + } + } + } + (m, l, acc) +} + +static PROF: std::sync::Mutex<(u32, f64, usize, f64)> = std::sync::Mutex::new((0, 0.0, 0, 0.0)); + +pub fn run(a: &HostAttn) { + let t0 = std::time::Instant::now(); + run_inner(a); + if std::env::var_os("STRATA_HA_PROF").is_some() { + let mut p = PROF.lock().unwrap(); + p.0 += 1; p.1 += t0.elapsed().as_secs_f64(); p.2 += a.nt; + if p.0 % 320 == 0 { + let pos = unsafe { *(a.step as *const i32) }; + eprintln!("host_attn window: {:.2} ms/call, {:.2} tokens/call, pos {pos}", 1e3 * p.1 / p.0 as f64, p.2 as f64 / p.0 as f64); + *p = (0, 0.0, 0, 0.0); + } + } +} + +/// Its own pool on every logical core (`STRATA_HA_THREADS` overrides): the global one has one thread a physical +/// core for the memory-bound GPU expert work, while this int8/f32 math gains from SMT (2.8 to 2.2 ms a layer at 52K). +fn pool() -> &'static rayon::ThreadPool { + static P: std::sync::OnceLock = std::sync::OnceLock::new(); + P.get_or_init(|| { + let n = std::env::var("STRATA_HA_THREADS").ok().and_then(|v| v.parse().ok()) + .unwrap_or_else(|| std::thread::available_parallelism().map_or(8, |n| n.get())); + rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("host-attn-{i}")).build().unwrap() + }) +} + +fn run_inner(a: &HostAttn) { + let (nh, hd, nt) = (a.nh, a.hd, a.nt); + let lim: Vec = (0..nt).map(|t| unsafe { *(a.step as *const i32).add(2 * t) } as usize).collect(); + let q0 = unsafe { std::slice::from_raw_parts(a.q as *const f32, nt * nh * hd) }; + let mut q = vec![0f32; nt * nh * hd]; + for r in 0..nt * nh { for i in 0..hd { q[r * hd + perm(a.mode, i)] = q0[r * hd + i]; } } + let n = lim.iter().max().unwrap() + 1; + let parts: Vec<_> = pool().install(|| (0..n.div_ceil(CHUNK)).into_par_iter().map(|c| chunk(a, &q, &lim, c * CHUNK, ((c + 1) * CHUNK).min(n))).collect()); + let part = unsafe { std::slice::from_raw_parts_mut(a.part as *mut f32, nt * nh * (hd + 2)) }; + for r in 0..nt * nh { + let mm = parts.iter().map(|p| p.0[r]).fold(f32::NEG_INFINITY, f32::max); + let o = &mut part[r * (hd + 2)..(r + 1) * (hd + 2)]; + o.fill(0.0); + let mut l = 0.0; + for p in &parts { + if p.0[r] == f32::NEG_INFINITY { continue; } + let w = (p.0[r] - mm).exp(); + l += p.1[r] * w; + for i in 0..hd { o[i] += p.2[r * hd + perm(a.mode, i)] * w; } + } + o[hd] = mm; + o[hd + 1] = l; + } +} + +pub unsafe extern "C" fn callback(user: *mut std::ffi::c_void) { + run(unsafe { &*(user as *const HostAttn) }); +} + +/// Whether block `il`'s KV cache lives in host RAM (`STRATA_KV_HOST=N`: blocks N and up, `all`: every one). +pub fn on_host(il: usize) -> bool { + match std::env::var("STRATA_KV_HOST").ok().as_deref() { + None | Some("") => false, + Some("all") => true, + Some(v) => v.parse::().is_ok_and(|n| il >= n), + } +} + +/// The CPU side of the `ha_post`/`ha_wait` mailbox at host address `mb` (u32 words: request at 0, context pointer +/// at 4-5, done at 16). Spins while requests come, naps after 2 ms without one. +pub fn start_worker(mb: usize) { + std::thread::Builder::new().name("host-attn".into()).spawn(move || { + let w = mb as *mut u32; + let mut last = 0u32; + let mut idle = std::time::Instant::now(); + loop { + let r = unsafe { std::ptr::read_volatile(w) }; + if r != last { + std::sync::atomic::fence(std::sync::atomic::Ordering::Acquire); + let ctx = unsafe { std::ptr::read_volatile(w.add(4) as *const u64) } as usize; + run(unsafe { &*(ctx as *const HostAttn) }); + std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); + unsafe { std::ptr::write_volatile(w.add(16), r) }; + last = r; + idle = std::time::Instant::now(); + } else if idle.elapsed() > std::time::Duration::from_millis(2) { + std::thread::sleep(std::time::Duration::from_micros(50)); + } else { + std::hint::spin_loop(); + } + } + }).expect("host-attn thread"); +} diff --git a/src/hy4/chat.rs b/src/hy4/chat.rs index 652c5d3a..7cab9a4a 100644 --- a/src/hy4/chat.rs +++ b/src/hy4/chat.rs @@ -102,13 +102,14 @@ pub fn parse_calls(text: &str) -> Option<(String, Vec<(String, String)>)> { /// Greedy decode of up to `n` tokens after `logits`; `piece` gets each new piece of text and returns false to stop. /// Returns the tokens and whether the model ended the reply itself. -fn decode(m: &mut Hy4Model, tok: &Tokenizer, mut logits: Vec, n: usize, mut piece: impl FnMut(&str) -> bool) -> (Vec, bool) { +fn decode(m: &mut Hy4Model, tok: &Tokenizer, lim: &mut Option, mut logits: Vec, n: usize, mut piece: impl FnMut(&str) -> bool) -> (Vec, bool) { let eos = tok.eos_ids(); let (mut out, mut shown) = (vec![], 0); for i in 0..n { - let next = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; + let next = crate::grammar::greedy(lim, &mut logits); if eos.contains(&next) { return (out, true); } out.push(next); + crate::term::decoded(1); let s = tok.decode(&out).unwrap_or_default(); if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { if !piece(&s[shown..]) { break; } @@ -131,10 +132,10 @@ pub fn generate(g: &Gguf, prompt: &str, n: usize) -> anyhow::Result<()> { let mut m = Hy4Model::new(g)?; let max_ctx = m.cfg.n_ctx; let ids = tok.encode(prompt)?; - anyhow::ensure!(!ids.is_empty() && ids.len() < max_ctx, "prompt is {} tokens, the limit is {max_ctx}", ids.len()); + anyhow::ensure!(!ids.is_empty() && ids.len() < max_ctx, "{}", crate::serve::too_long(ids.len(), max_ctx)); if std::env::var_os("STRATA_DS_TRACE").is_some() { crate::say!("prompt tokens: {ids:?}"); } let logits = m.prefill(&ids); - let (out, _) = decode(&mut m, &tok, logits, n.min(max_ctx - ids.len()), show); + let (out, _) = decode(&mut m, &tok, &mut None, logits, n.min(max_ctx - ids.len()), show); if std::env::var_os("STRATA_DS_TRACE").is_some() { crate::say!("\noutput tokens: {out:?}"); } println!(); Ok(()) @@ -169,39 +170,42 @@ pub fn chat(g: &Gguf, system: Option, n: usize, think: bool) -> anyhow:: } let logits = m.prefill(&ids); let left = max_ctx - m.toks.len(); - decode(&mut m, &tok, logits, n.min(left), show); + decode(&mut m, &tok, &mut None, logits, n.min(left), show); println!(); } Ok(()) } /// The chat of `rustingstrata serve` for Hy4-flash (see `serve::Own`): one request at a time, JSON or SSE. -/// ponytail: greedy only, no stop strings; thinking (`"think": true`) arrives inside `content` up to ``; +/// ponytail: greedy only; thinking (`"think": true`) arrives inside `content` up to ``; /// the KV cache is reused only when the new prompt extends the last sequence. pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Result> { use anyhow::Context; use serde_json::json; gpu_defaults(); let mut m = Hy4Model::new(g)?; + crate::serve::warm_up(tok, |ids| { m.prefill(ids); m.reset(); })?; let max_ctx = m.cfg.n_ctx; Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| { + let mut lim = crate::grammar::Constraint::new(q, tok)?; let ids = tok.encode(&render(&q.messages, &q.tools, q.think.unwrap_or(false), q.preserve_thinking)).ok().filter(|i| !i.is_empty()).context("cannot encode prompt")?; - anyhow::ensure!(ids.len() < max_ctx, "prompt is {} tokens, the limit is {max_ctx}", ids.len()); + anyhow::ensure!(ids.len() < max_ctx, "{}", crate::serve::too_long(ids.len(), max_ctx)); let t = std::time::Instant::now(); let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; - let logits = m.prefill(&ids[keep..]); + if q.stream && !q.head_sent { let _ = write!(c, "{}", crate::serve::sse_head(c)); } + let logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); let prefill_s = t.elapsed().as_secs_f64(); - let n = q.max_tokens.unwrap_or(256).min(max_ctx - ids.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let n = q.max_tokens.unwrap_or(usize::MAX).min(max_ctx - ids.len()); let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); - let mut hold = crate::chat::Hold::new(tools, vec![]).tagged(CALLS); - let (out, stopped) = decode(&mut m, &tok, logits, n, |p| { + let mut hold = crate::chat::Hold::new(tools, q.stop.clone()).tagged(CALLS); + let mut alive = std::time::Instant::now(); + let (out, stopped) = decode(&mut m, &tok, &mut lim, logits, n, |p| { let t = hold.push(p); - !q.stream || t.is_empty() || write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() + (!q.stream || if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() }) && !hold.stopped }); let calls = if tools { parse_calls(&hold.text) } else { None }; - let done = if calls.is_some() { "tool_calls" } else if stopped { "stop" } else { "length" }; + let done = if calls.is_some() { "tool_calls" } else if stopped || hold.stopped { "stop" } else { "length" }; let calls_json = |(content, calls): &(String, Vec<(String, String)>), stream: bool| { let c: Vec<_> = calls.iter().enumerate().map(|(k, (f, a))| { let mut c = json!({"id": format!("call_{k}"), "type": "function", "function": {"name": f, "arguments": a}}); @@ -210,20 +214,26 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Resu }).collect(); if stream { json!({"tool_calls": c}) } else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } }; + let d = crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done, drafts: None }; + let timings = d.timings(t); + let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), "prompt_tokens_details": {"cached_tokens": keep}}); if q.stream { match &calls { Some(x) => { let _ = write!(c, "data: {}\n\n", chunk(calls_json(x, true), None)); } None if !hold.rest().is_empty() => { let _ = write!(c, "data: {}\n\n", chunk(json!({"content": hold.rest()}), None)); } None => {} } - let _ = write!(c, "data: {}\n\ndata: [DONE]\n\n", chunk(json!({}), Some(done))); + let mut last = chunk(json!({}), Some(done)); + last["usage"] = usage; + last["timings"] = timings; + let _ = write!(c, "data: {last}\n\ndata: [DONE]\n\n"); } else { let message = match &calls { Some(x) => calls_json(x, false), None => json!({"role": "assistant", "content": hold.text}) }; let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": message, "finish_reason": done}], - "usage": {"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len()}}); + "usage": usage, "timings": timings}); crate::serve::send(c, "200 OK", "application/json", &b.to_string()); } - Ok(crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done }) + Ok(d) })) } diff --git a/src/hy4/forward.rs b/src/hy4/forward.rs index 70eebdb0..326df1a5 100644 --- a/src/hy4/forward.rs +++ b/src/hy4/forward.rs @@ -105,16 +105,16 @@ pub struct Hy4Model<'a> { } /// A table that is only read row by row: never uploaded (the Engram table is 36 GB). -fn host_mat<'a>(g: &'a Gguf, name: &str) -> Result> { +pub(crate) fn host_mat<'a>(g: &'a Gguf, name: &str) -> Result> { let t = g.tensors.get(name).with_context(|| format!("missing tensor {name}"))?; Ok(Mat { data: g.bytes(t), ty: GgmlType::from_u32(t.ty)?, rows: t.dims[1] as usize, cols: t.dims[0] as usize, cpu: false, gpu: None, scale: 1.0 }) } -fn sigmoid(x: f32) -> f32 { +pub(crate) fn sigmoid(x: f32) -> f32 { 1.0 / (1.0 + (-x).exp()) } -fn silu(x: f32) -> f32 { +pub(crate) fn silu(x: f32) -> f32 { x * sigmoid(x) } @@ -124,7 +124,7 @@ fn act(gate: f32, up: f32, limit: f32) -> f32 { /// Weighted sum of the listed experts' outputs, `(gate, up, down, weight)` each, for the latent input `x`. Experts /// that share a GPU run as two batched round trips; otherwise each matvec runs where its matrix lives. -fn run_experts(list: &[(Mat, Mat, Mat, f32)], x: &[f32], clamp: f32, nl: usize) -> Vec { +pub(crate) fn run_experts(list: &[(Mat, Mat, Mat, f32)], x: &[f32], clamp: f32, nl: usize) -> Vec { let mut mix = vec![0f32; nl]; let Some(first) = list.first() else { return mix }; let (k, nf) = (list.len(), first.0.rows); @@ -141,6 +141,19 @@ fn run_experts(list: &[(Mat, Mat, Mat, f32)], x: &[f32], clamp: f32, nl: usize) } } None => { + // Host experts: every gate and up row in one parallel pass, then every down row in another (the dots of + // `Mat::matvec`, so the same bits): two pool wake-ups a layer instead of three an expert. + let gu: Vec = list.iter().flat_map(|e| [e.0, e.1]).collect(); + if let Some(y) = crate::deepseek::mat::matvec_many_cpu_shared(&gu, x) { + let a: Vec> = y.chunks_exact(2 * nf).map(|c| c[..nf].iter().zip(&c[nf..]).map(|(g, u)| act(*g, *u, clamp)).collect()).collect(); + let downs: Vec = list.iter().map(|e| e.2).collect(); + if let Some(dy) = crate::deepseek::mat::matvec_many_cpu(&downs, &a.iter().map(|a| a.as_slice()).collect::>()) { + for (e, d) in list.iter().zip(dy.chunks_exact(nl)) { + for j in 0..nl { mix[j] += e.3 * d[j]; } + } + return mix; + } + } let (mut gy, mut uy, mut dy) = (vec![0f32; nf], vec![0f32; nf], vec![0f32; nl]); for (g, u, d, w) in list { g.matvec(x, &mut gy); @@ -779,7 +792,7 @@ impl<'a> Hy4Model<'a> { let Some((&last, head)) = toks.split_last() else { return vec![] }; let chunk: usize = std::env::var("STRATA_DS_CHUNK").ok().and_then(|v| v.parse().ok()).unwrap_or(1024); if chunk > 1 && !self.trace && std::env::var_os("STRATA_DS_DUMP").is_none() { - for c in head.chunks(chunk) { self.prefill_chunk(c); } + for c in head.chunks(chunk) { self.prefill_chunk(c); crate::term::prefilled(c.len()); } } else { for &t in head { self.step_opt(t, false); } } diff --git a/src/hy4/mod.rs b/src/hy4/mod.rs index 8c7be487..77482f6f 100644 --- a/src/hy4/mod.rs +++ b/src/hy4/mod.rs @@ -53,12 +53,18 @@ impl Hy4Config { let arr_u = |s: &str| -> anyhow::Result> { g.get(&k(s))?.as_arr().with_context(|| k(s))?.iter().map(|v| v.as_u64().with_context(|| k(s))).collect() }; - let n_layer = u("block_count")?; - let n_head: Vec = arr_u("attention.head_count")?.into_iter().map(|v| v as usize).collect(); - let swa: Vec = arr_u("attention.sliding_window_pattern")?.into_iter().map(|v| v != 0).collect(); - let clamp_exp: Vec = g.get(&k("swiglu_clamp_exp"))?.as_arr().with_context(|| k("swiglu_clamp_exp"))? + // `block_count` also counts the MTP draft blocks at the end, which have no hyper-connections (#160); the + // per-layer arrays cover every block. + let n_blocks = u("block_count")?; + let n_nextn = g.meta.get(&k("nextn_predict_layers")).and_then(|v| v.as_u64()).unwrap_or(0) as usize; + ensure!(n_nextn < n_blocks, "nextn_predict_layers {n_nextn} is not below block_count {n_blocks}"); + let n_layer = n_blocks - n_nextn; + let mut n_head: Vec = arr_u("attention.head_count")?.into_iter().map(|v| v as usize).collect(); + let mut swa: Vec = arr_u("attention.sliding_window_pattern")?.into_iter().map(|v| v != 0).collect(); + let mut clamp_exp: Vec = g.get(&k("swiglu_clamp_exp"))?.as_arr().with_context(|| k("swiglu_clamp_exp"))? .iter().map(|v| v.as_f32().context("swiglu_clamp_exp")).collect::>()?; - ensure!(n_head.len() == n_layer && swa.len() == n_layer && clamp_exp.len() == n_layer, "per-layer metadata does not cover {n_layer} layers"); + ensure!(n_head.len() == n_blocks && swa.len() == n_blocks && clamp_exp.len() == n_blocks, "per-layer metadata does not cover {n_blocks} blocks"); + (n_head.truncate(n_layer), swa.truncate(n_layer), clamp_exp.truncate(n_layer)); ensure!(u("hyper_connection.count")? == 4, "only 4 hyper-connection streams are supported"); ensure!(u("expert_gating_func")? == 2 && u("expert_shared_count")? == 1 && u("attention.head_count_kv")? == 1, "unsupported Hy4 variant"); let engram = if g.meta.contains_key(&k("ple.layers")) { diff --git a/src/inkling2/chat.rs b/src/inkling2/chat.rs index 1ee3e799..67a6beeb 100644 --- a/src/inkling2/chat.rs +++ b/src/inkling2/chat.rs @@ -42,13 +42,9 @@ impl Inkling2Opts { }; let mut m = Inkling2Model::new_with_ctx(g, self.max_ctx)?; m.dspark = dspark; - m.spec_draft_max = if self.ngram_cfg.is_enabled() { - self.ngram_cfg.draft_max - } else if self.ngram_cfg.draft_max != 16 { - self.ngram_cfg.draft_max - } else { - 3 - }; + // DSpark drafts 3 unless --spec-draft-n-max says otherwise (16 is its default): a `--spec-type` alone must not + // lengthen them, 8-row verifies cost a bandwidth-bound iGPU more than the extra drafts return (#154). + m.spec_draft_max = if self.ngram_cfg.draft_max != 16 { self.ngram_cfg.draft_max } else { 3 }; if self.ngram_cfg.is_enabled() { let mut cfg = self.ngram_cfg.clone(); cfg.n_vocab = m.cfg.n_vocab; @@ -74,6 +70,8 @@ const DONE: &str = "<|content_model_end_sampling|>"; pub fn gpu_defaults() { crate::deepseek::chat::gpu_defaults(); if std::env::var_os("STRATA_DS_GPU_FRACTION").is_none() { unsafe { std::env::set_var("STRATA_DS_GPU_FRACTION", "0.6,0.9") } } + // Local patch: with several GPUs the plain weights stay on GPU 0, where the device decode state lives. + if std::env::var_os("STRATA_DS_PLAIN_FIRST").is_none() { unsafe { std::env::set_var("STRATA_DS_PLAIN_FIRST", "1") } } } /// The template's `tojson(sort_keys=true, separators=(",", ":"))`. @@ -246,7 +244,7 @@ pub fn decode_with( let id = |t: &str| tok.token_id(t); let (model, end) = (id(MODEL), id(END)); let kinds = [(id(TEXT), Part::Text), (id(THINKING), Part::Think), (id(INVOKE), Part::Call)]; - let pure_greedy = smp.temp <= 0.0 && smp.repeat == 1.0 && smp.presence == 0.0 && smp.frequency == 0.0 && smp.dry_mult <= 0.0; + let pure_greedy = smp.temp <= 0.0 && smp.repeat == 1.0 && smp.presence == 0.0 && smp.frequency == 0.0 && smp.dry_mult <= 0.0 && smp.limit.is_none(); let pick_tok = |smp: &mut Sampler, l: &[f32]| -> u32 { if pure_greedy { crate::ops::argmax(l) as u32 @@ -309,6 +307,7 @@ pub fn decode_with( } } i += 1; + crate::term::decoded(1); if part == Some(Part::Think) && thinking_budget > 0 && think_tokens >= thinking_budget @@ -329,7 +328,7 @@ pub fn decode_with( if i < n { if let Some(t) = pending.pop_front() { next = t; - } else if m.has_spec() && stops.is_empty() { + } else if m.has_spec() && stops.is_empty() && smp.limit.is_none() { let budget_cap = if part == Some(Part::Think) && thinking_budget > 0 { thinking_budget.saturating_sub(think_tokens) } else { @@ -382,7 +381,7 @@ pub fn generate_image_opts( let tok = Tokenizer::from_gguf(g)?; let mut m = opts.build_model(g, &tok)?; let seq = prompt_seq(&tok, prompt, images)?; - ensure!(!seq.is_empty() && seq.len() < m.max_ctx, "prompt is {} tokens, the limit is {}", seq.len(), m.max_ctx); + ensure!(!seq.is_empty() && seq.len() < m.max_ctx, "{}", crate::serve::too_long(seq.len(), m.max_ctx)); let trace = std::env::var_os("STRATA_DS_TRACE").is_some(); if trace { let ids: Vec = seq.iter().map(|&(t, _)| t).collect(); @@ -398,6 +397,7 @@ pub fn generate_image_opts( for i in 0..max_gen { if eos.contains(&next) { break; } out.push(next); + crate::term::decoded(1); let s = tok.decode(&out).unwrap_or_default(); if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { print!("{}", &s[shown..]); @@ -507,42 +507,64 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str, opts: Inkling2O use serde_json::json; gpu_defaults(); let mut m = opts.build_model(g, tok)?; + crate::serve::warm_up(tok, |ids| { m.prefill(ids); m.reset(); })?; let projector = opts.mmproj.as_deref().map(crate::vision::VisionProjector::open).transpose()?; if let Some(p) = &projector { crate::vision::validate_projection(p.cfg(), m.cfg.n_embd)?; } - let mut turn_ckpt: Option<(Checkpoint, Vec)> = None; + // The images in the model's state and in the checkpoint, by hash of their source, in prompt order: a prefix is + // reused only when the images that start in it are the same ones. `encoded` keeps the last request's encodings. + let (mut turn_ckpt, mut ckpt_imgs, mut cur_imgs): (Option<(Checkpoint, Vec)>, Vec, Vec) = (None, vec![], vec![]); + let mut encoded: std::collections::HashMap>)> = Default::default(); Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| { let effort = parse_effort(q.reasoning_effort.as_deref(), q.think, opts.think_default)?; - let (mut grids, mut embs) = (vec![], vec![]); + let (mut grids, mut embs, mut hashes) = (vec![], vec![], vec![]); + let mut fresh = std::collections::HashMap::new(); for src in q.messages.iter().flat_map(|msg| &msg.images) { - let p = projector.as_ref().context("this server has no --mmproj")?; - let (feats, nx, ny) = crate::vision::encode_image(p, &crate::vision::load_image(src)?)?; - grids.push((nx, ny)); - embs.push(feats); + let h = { use std::hash::{Hash, Hasher}; let mut s = std::collections::hash_map::DefaultHasher::new(); src.hash(&mut s); s.finish() }; + let e = match encoded.get(&h).or_else(|| fresh.get(&h)) { + Some(e) => e.clone(), + None => { + let p = projector.as_ref().context("this server has no --mmproj")?; + let (feats, nx, ny) = crate::vision::encode_image(p, &crate::vision::load_image(src)?)?; + ((nx, ny), feats) + } + }; + grids.push(e.0); + embs.push(e.1.clone()); + hashes.push(h); + fresh.insert(h, e); } + encoded = fresh; let has_images = !grids.is_empty(); let seq = prompt_seq(tok, &render_with_effort(&q.messages, &q.tools, &effort), has_images.then_some((&grids[..], &embs[..])))?; let ids: Vec = seq.iter().map(|&(t, _)| t).collect(); ensure!(!ids.is_empty(), "cannot encode prompt"); - ensure!(ids.len() < m.max_ctx, "prompt is {} tokens, the limit is {}", ids.len(), m.max_ctx); + ensure!(ids.len() < m.max_ctx, "{}", crate::serve::too_long(ids.len(), m.max_ctx)); + // Images that start before `k` must be the cached ones. + let starts: Vec = (0..seq.len()).filter(|&i| seq[i].1.is_some() && (i == 0 || seq[i - 1].1.is_none())).collect(); + let same = |k: usize, cached: &[u64]| { let n = starts.iter().filter(|&&s| s < k).count(); cached.len() >= n && cached[..n] == hashes[..n] }; let t = std::time::Instant::now(); - let (keep, logits) = if !has_images && m.toks.len() < ids.len() && ids.starts_with(&m.toks) { + if q.stream && !q.head_sent { let _ = write!(c, "{}", crate::serve::sse_head(c)); } + let (keep, logits) = crate::serve::alive(c, q.stream, || if m.toks.len() < ids.len() && ids.starts_with(&m.toks) && same(m.toks.len(), &cur_imgs) { let k = m.toks.len(); (k, m.prefill_embds(&seq[k..])) - } else if !has_images && let Some((ck, ck_logits)) = &turn_ckpt && ck.toks.len() <= ids.len() && ids.starts_with(&ck.toks) { + } else if let Some((ck, ck_logits)) = &turn_ckpt && ck.toks.len() <= ids.len() && ids.starts_with(&ck.toks) && same(ck.toks.len(), &ckpt_imgs) { let k = ck.toks.len(); m.restore(ck); (k, if k == ids.len() { ck_logits.clone() } else { m.prefill_embds(&seq[k..]) }) } else { m.reset(); (0, m.prefill_embds(&seq)) - }; - turn_ckpt = (!has_images).then(|| (m.checkpoint(), logits.clone())); + }); + cur_imgs = hashes; + ckpt_imgs = cur_imgs.clone(); + turn_ckpt = Some((m.checkpoint(), logits.clone())); let prefill_s = t.elapsed().as_secs_f64(); let mut smp = opts.sampler.clone(); if let Some(t) = q.temperature { smp.temp = t; } if let Some(k) = q.top_k { smp.top_k = k; } if let Some(p) = q.top_p { smp.top_p = p; } + if let Some(p) = q.min_p { smp.min_p = p; } if let Some(p) = q.presence_penalty { smp.presence = p; } if let Some(f) = q.frequency_penalty { smp.frequency = f; } if let Some(rp) = q.repeat_penalty { smp.repeat = rp; } @@ -551,19 +573,21 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str, opts: Inkling2O if let Some(db) = q.dry_base { smp.dry_base = db; } if let Some(da) = q.dry_allowed_length { smp.dry_allowed = da; } if let Some(s) = q.seed { smp.rng = s.max(1); } + smp.limit = crate::grammar::Constraint::new(q, tok)?; let budget = q.thinking_budget.unwrap_or(opts.thinking_budget); - let n = q.max_tokens.unwrap_or(256).min(m.max_ctx - m.toks.len()); - if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let n = q.max_tokens.unwrap_or(usize::MAX).min(m.max_ctx - m.toks.len()); let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); let tools = q.tool_calls && !q.tools.is_empty(); let (mut content, mut reasoning, mut bodies) = (String::new(), String::new(), Vec::::new()); + let mut alive = std::time::Instant::now(); + let d0 = m.drafts; let (count, stopped) = decode_with(&mut m, tok, logits, n, &mut smp, budget, &q.stop, |p, start, s| { let key = match p { Part::Call if tools => { if start { bodies.push(String::new()); } *bodies.last_mut().unwrap() += s; - return true; + return !q.stream || crate::serve::held(c, &mut alive); } Part::Think => { reasoning += s; "reasoning_content" } _ => { content += s; "content" } @@ -576,20 +600,30 @@ pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str, opts: Inkling2O c }).collect(); let done = if !calls.is_empty() { "tool_calls" } else if stopped { "stop" } else { "length" }; + let kind = crate::serve::draft_kind( + if m.dspark.is_some() { crate::serve::DraftModel::Dspark } else { crate::serve::DraftModel::None }, + crate::serve::ngram_enabled(m.ngram.as_ref()), + ); + let drafts = crate::serve::draft_delta(kind, d0, m.drafts); + let d = crate::serve::Done { prompt: ids.len(), cached: keep, completion: count, prefill_s, finish: done, drafts }; + let timings = d.timings(t); let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": count, "total_tokens": ids.len() + count, "prompt_tokens_details": {"cached_tokens": keep}}); if q.stream { if !calls.is_empty() { let _ = write!(c, "data: {}\n\n", chunk(json!({"tool_calls": calls}), None)); } - let _ = write!(c, "data: {}\n\n", chunk(json!({}), Some(done))); + let mut last = chunk(json!({}), Some(done)); + last["usage"] = usage.clone(); + last["timings"] = timings; + let _ = write!(c, "data: {last}\n\n"); if q.include_usage { let _ = write!(c, "data: {}\n\n", json!({"object": "chat.completion.chunk", "model": name, "choices": [], "usage": usage})); } let _ = write!(c, "data: [DONE]\n\n"); } else { let mut message = json!({"role": "assistant", "content": content}); if !reasoning.is_empty() { message["reasoning_content"] = reasoning.into(); } if !calls.is_empty() { message["tool_calls"] = calls.into(); } - let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": message, "finish_reason": done}], "usage": usage}); + let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": message, "finish_reason": done}], "usage": usage, "timings": timings}); crate::serve::send(c, "200 OK", "application/json", &b.to_string()); } - Ok(crate::serve::Done { prompt: ids.len(), cached: keep, completion: count, prefill_s, finish: done }) + Ok(d) })) } diff --git a/src/inkling2/dspark.rs b/src/inkling2/dspark.rs index 1d184c8a..ee6d6186 100644 --- a/src/inkling2/dspark.rs +++ b/src/inkling2/dspark.rs @@ -37,6 +37,18 @@ struct DsparkLayer { ffn_down: Mat<'static>, } +struct MarkovW2Gpu { + w2: crate::backend::GpuTensor, + bias: crate::backend::Buf, +} + +enum MarkovHead { + /// Legacy Unsloth DSpark: projects `latent` (`[rank]`) to hidden space (`[n_embd]`), adds `h_row`, then runs target LM head. + HiddenOut { weight: Mat<'static>, bias: Vec }, + /// Mainline llama.cpp DSpark: adds low-rank logit delta `markov_w2 @ latent + bias` onto batched target LM head logits. + Logits { w2: Mat<'static>, bias: Vec, gpu: std::sync::OnceLock> }, +} + pub struct DsparkDrafter { pub n_layer: usize, pub n_embd: usize, @@ -52,13 +64,13 @@ pub struct DsparkDrafter { pub target_layers: [usize; 4], fuse: Vec, dspark_norm: Vec, + token_embd_norm: Option>, mask_embd: Vec, output_norm: Vec, markov_w1: Mat<'static>, joint_proj: Mat<'static>, joint_proj_b: Vec, - hidden_out: Mat<'static>, - hidden_out_b: Vec, + markov_head: MarkovHead, layers: Vec, k_cache: Vec>, v_cache: Vec>, @@ -122,24 +134,62 @@ impl DsparkDrafter { let markov_w1 = host_mat(g_ref, "markov_w1.weight")?; let rank = markov_w1.cols; - let fuse = f32s(g_ref, "dspark_fuse.weight")?; - ensure!(fuse.len() == 4 * (n_layer + 1), "dspark_fuse.weight len {} != {}", fuse.len(), 4 * (n_layer + 1)); - let dspark_norm = f32s(g_ref, "dspark_norm.weight")?; + let fuse = if g_ref.tensors.contains_key("dspark_fuse.weight") { + let f = f32s(g_ref, "dspark_fuse.weight")?; + ensure!(f.len() == 4 * (n_layer + 1), "dspark_fuse.weight len {} != {}", f.len(), 4 * (n_layer + 1)); + f + } else { + let mut f = Vec::with_capacity(4 * (n_layer + 1)); + for il in 0..n_layer { + let row = f32s(g_ref, &format!("blk.{il}.ctx_mix.weight"))?; + ensure!(row.len() == 4, "blk.{il}.ctx_mix.weight len {} != 4", row.len()); + f.extend_from_slice(&row); + } + let row = f32s(g_ref, "markov_ctx_mix.weight")?; + ensure!(row.len() == 4, "markov_ctx_mix.weight len {} != 4", row.len()); + f.extend_from_slice(&row); + f + }; + let dspark_norm = if g_ref.tensors.contains_key("dspark_norm.weight") { + f32s(g_ref, "dspark_norm.weight")? + } else { + f32s(g_ref, "markov_ctx_norm.weight")? + }; + let token_embd_norm = if g_ref.tensors.contains_key("token_embd_norm.weight") { + Some(f32s(g_ref, "token_embd_norm.weight")?) + } else { + None + }; let mask_embd = f32s(g_ref, "mask_embd.weight")?; + ensure!(mask_embd.len() >= n_embd && mask_embd.len() % n_embd == 0, "dspark: mask_embd.weight len {} is not rows of {n_embd}", mask_embd.len()); let output_norm = f32s(g_ref, "output_norm.weight")?; let joint_proj = host_mat(g_ref, "joint_proj.weight")?; let joint_proj_b = f32s(g_ref, "joint_proj.bias")?; - let hidden_out = host_mat(g_ref, "dspark_hidden_out.weight")?; - let hidden_out_b = f32s(g_ref, "dspark_hidden_out.bias")?; + let markov_head = if g_ref.tensors.contains_key("markov_w2.weight") { + let (w2, bias) = (host_mat(g_ref, "markov_w2.weight")?, f32s(g_ref, "markov_w2.bias")?); + ensure!(w2.cols == rank, "dspark: markov_w2.weight has {} columns, markov_w1 gives rank {rank}", w2.cols); + ensure!(bias.len() == w2.rows, "dspark: markov_w2.bias len {} != {} rows of markov_w2.weight", bias.len(), w2.rows); + MarkovHead::Logits { w2, bias, gpu: std::sync::OnceLock::new() } + } else { + MarkovHead::HiddenOut { + weight: host_mat(g_ref, "dspark_hidden_out.weight")?, + bias: f32s(g_ref, "dspark_hidden_out.bias")?, + } + }; let mut layers = Vec::with_capacity(n_layer); for il in 0..n_layer { let p = |s: &str| format!("blk.{il}.{s}"); let m = |s: &str| Mat::load(g_ref, &p(s)); let v = |s: &str| f32s(g_ref, &p(s)); + let dflare_norm = if g_ref.tensors.contains_key(&p("dflare_norm.weight")) { + v("dflare_norm.weight")? + } else { + v("ctx_norm.weight")? + }; layers.push(DsparkLayer { swa: swa[il], - dflare_norm: v("dflare_norm.weight")?, + dflare_norm, attn_k_ctx: m("attn_k_ctx.weight")?, attn_v_ctx: m("attn_v_ctx.weight")?, attn_k_ctx_norm: v("attn_k_ctx_norm.weight")?, @@ -172,13 +222,13 @@ impl DsparkDrafter { target_layers, fuse, dspark_norm, + token_embd_norm, mask_embd, output_norm, markov_w1, joint_proj, joint_proj_b, - hidden_out, - hidden_out_b, + markov_head, layers, k_cache: vec![Vec::new(); n_layer], v_cache: vec![Vec::new(); n_layer], @@ -270,9 +320,17 @@ impl DsparkDrafter { // 1. Build 8-token input: slot 0 is normed target token embedding of `anchor_tok`, slots 1..8 are `mask_embd`. let mut inp = vec![0.0f32; bs * n]; - target.embed_normed(anchor_tok, &mut inp[..n]); + if let Some(norm_w) = &self.token_embd_norm { + let mut emb = vec![0.0f32; n]; + target.embed_raw(anchor_tok, &mut emb); + rms_norm_w(&emb, norm_w, self.eps, &mut inp[..n]); + } else { + target.embed_normed(anchor_tok, &mut inp[..n]); + } + let per_pos_mask = self.mask_embd.len() >= (bs - 1) * n; for i in 1..bs { - inp[i * n..(i + 1) * n].copy_from_slice(&self.mask_embd); + let src = if per_pos_mask { &self.mask_embd[(i - 1) * n..i * n] } else { &self.mask_embd[..n] }; + inp[i * n..(i + 1) * n].copy_from_slice(src); } // 2. Run the 3 non-causal DSpark transformer layers over the 8-token block. @@ -372,34 +430,98 @@ impl DsparkDrafter { joint_in[2 * r + n..].copy_from_slice(ctx_feat); let mut joint = vec![0.0f32; 3 * r]; let mut latent = vec![0.0f32; r]; - let mut corr = vec![0.0f32; n]; let mut prev = anchor_tok; let mut drafts = Vec::with_capacity(count); - for step in 0..count { - let h_row = &hidden[(step + 1) * n..(step + 2) * n]; - self.markov_w1.row_into(prev as usize, &mut prev_embd); - joint_in[..r].copy_from_slice(&state); - joint_in[r..2 * r].copy_from_slice(&prev_embd); + let markov_step = |prev_tok: u32, + h_row: &[f32], + state: &mut [f32], + prev_embd: &mut [f32], + joint_in: &mut [f32], + joint: &mut [f32], + latent: &mut [f32]| { + self.markov_w1.row_into(prev_tok as usize, prev_embd); + joint_in[..r].copy_from_slice(state); + joint_in[r..2 * r].copy_from_slice(prev_embd); joint_in[2 * r..2 * r + n].copy_from_slice(h_row); - - self.joint_proj.matvec(&joint_in, &mut joint); + self.joint_proj.matvec(joint_in, joint); for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; } - for k in 0..r { let gate = crate::ops::sigmoid(joint[k]); let cand = joint[r + k].tanh(); state[k] = cand + gate * (state[k] - cand); latent[k] = joint[2 * r + k].tanh(); } + }; - self.hidden_out.matvec(&latent, &mut corr); - for ((c, &b), &h_v) in corr.iter_mut().zip(&self.hidden_out_b).zip(h_row) { - *c = *c + b + h_v; + match &self.markov_head { + MarkovHead::HiddenOut { weight, bias } => { + let mut corr = vec![0.0f32; n]; + for step in 0..count { + let h_row = &hidden[(step + 1) * n..(step + 2) * n]; + markov_step(prev, h_row, &mut state, &mut prev_embd, &mut joint_in, &mut joint, &mut latent); + weight.matvec(&latent, &mut corr); + for ((c, &b), &h_v) in corr.iter_mut().zip(bias).zip(h_row) { + *c = *c + b + h_v; + } + prev = target.lm_head_argmax(&corr); + drafts.push(prev); + } } + MarkovHead::Logits { w2, bias, gpu } => { + let gpu_w2 = gpu.get_or_init(|| { + if w2.rows > target.output_rows() || w2.cols > n { + return None; + } + let dm = crate::deepseek::mat::dev::get()?; + let d = dm.lock().ok()?; + let be = &*d.parts[0].be; + let w2_gpu = be.upload(&crate::weights::Tensor { + ty: w2.ty, + rows: w2.rows, + cols: w2.cols, + data: w2.data, + scale: w2.scale, + }).ok()?; + let bias_buf = be.alloc(bias.len() * 4).ok()?; + be.put(bias, &bias_buf, 0).ok()?; + Some(MarkovW2Gpu { w2: w2_gpu, bias: bias_buf }) + }); + let mut use_gpu = gpu_w2.is_some() + && target.lm_head_batch_gpu(&hidden[n..(1 + count) * n], count); + let mut cpu_base: Option> = None; + let mut delta = Vec::new(); + let n_vocab = target.cfg.n_vocab; + let nv = n_vocab.min(w2.rows).min(bias.len()); - prev = target.lm_head_argmax(&corr); - drafts.push(prev); + for step in 0..count { + let h_row = &hidden[(step + 1) * n..(step + 2) * n]; + markov_step(prev, h_row, &mut state, &mut prev_embd, &mut joint_in, &mut joint, &mut latent); + if use_gpu { + let g = gpu_w2.as_ref().unwrap(); + if let Some(id) = target.markov_w2_argmax_gpu(&g.w2, g.bias.addr(), bias.len(), &latent, step) { + prev = id; + drafts.push(prev); + continue; + } + use_gpu = false; + } + let base_all = cpu_base.get_or_insert_with(|| target.lm_head_batch_cpu(&hidden[n..(1 + count) * n], count)); + if delta.is_empty() { delta.resize(w2.rows, 0.0); } + w2.matvec(&latent, &mut delta); + let base = &base_all[step * n_vocab..(step + 1) * n_vocab]; + let (mut best_i, mut best_v) = (0usize, f32::NEG_INFINITY); + for i in 0..nv { + let v = base[i] + delta[i] + bias[i]; + if v > best_v { + best_v = v; + best_i = i; + } + } + prev = best_i as u32; + drafts.push(prev); + } + } } drafts } diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index 5ad7bc7c..06b944f5 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -15,6 +15,8 @@ use half::{f16, slice::HalfFloatSliceExt}; use rayon::prelude::*; mod device; +mod pool; +mod worker; /// Epsilon of the norms without a weight (depth mix, loop controllers). const MIX_EPS: f32 = 1e-6; @@ -96,10 +98,14 @@ pub struct Inkling2Model<'a> { out_norm: Vec, output: Mat<'a>, slots: Vec, - /// Share of a layer's VRAM-cache misses the CPU computes; it follows the two sides' times. + /// Share of a verify chunk's VRAM-cache misses the CPU computes; it follows the two sides' times. cpu_share: std::cell::Cell, /// The same share for a chunk of tokens, where an expert runs once for all its tokens. chunk_share: std::cell::Cell, + /// One token's split of the last `plan` (CPU experts, staged experts), and the seconds one expert takes on the + /// CPU and to copy up and run, with the plans since the copy was last timed (see `stage_count`). + split: std::cell::Cell<(usize, usize)>, + split_cost: std::cell::Cell<[f32; 3]>, pub toks: Vec, pub trace: bool, /// Seconds per part of a token, printed with `STRATA_DS_PROF`; see `PROF`. @@ -115,10 +121,41 @@ pub struct Inkling2Model<'a> { pub spec_draft_max: usize, /// Speculative decoding stats: `(drafts_proposed, drafts_accepted)`. pub drafts: (usize, usize), + /// DSpark's draft length, following its acceptance. + ds_gate: DraftGate, +} + +/// A DSpark draft length that follows acceptance (#154): one longer after a draft taken whole, one shorter after a +/// draft with nothing taken; a single rejected draft pauses drafting for `PAUSE` steps, then it tries one again. +/// ponytail: steps on the last verify only; weigh a moving acceptance against measured verify cost if this flaps. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct DraftGate { len: usize, pause: usize } + +impl DraftGate { + const PAUSE: usize = 16; + + /// Tokens to draft this step, at most `max` (0: step without a draft). + fn take(&mut self, max: usize) -> usize { + if self.pause > 0 { self.pause -= 1; return 0; } + if self.len == 0 { self.len = max; } + self.len.min(max) + } + + /// `accepted` of `drafted` draft tokens were taken. + fn feedback(&mut self, drafted: usize, accepted: usize, max: usize) { + if drafted == 0 { return; } + if accepted == drafted { self.len = (drafted + 1).min(max); } + else if accepted == 0 && drafted == 1 { (self.len, self.pause) = (1, Self::PAUSE); } + else if accepted == 0 { self.len = drafted - 1; } + } } /// A token of `device` counts all the device work before the router as "mix": the queue runs while the host waits /// for the router's input. +/// Per-token expert counters of `plan` for STRATA_DS_PROF: CPU bytes, CPU experts, GPU experts copied up for one +/// use, GPU experts; and the experts `Dev::admit` moved into VRAM. +static ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static HYB: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; const PROF: [&str; 8] = ["mix", "proj", "scores", "out-proj", "route", "experts-gpu", "experts-cpu", "logits"]; /// A tensor read from the mapped file only: never uploaded. @@ -243,7 +280,7 @@ fn hsum(v: std::arch::x86_64::__m256) -> f32 { /// `p[j * n + row]` += `scale` times the dot of f16 row `row` of `w` (`n` rows) with row j of `x`. /// One to three rows of `x` take the same sums in the same order, so a token gets the same bits alone or in a chunk. -fn dots_h(p: &mut [f32], scale: f32, w: &[f16], x: &[f32], n: usize) { +pub(crate) fn dots_h(p: &mut [f32], scale: f32, w: &[f16], x: &[f32], n: usize) { let hd = w.len() / n; #[cfg(all(target_feature = "f16c", target_feature = "fma"))] if hd % 32 == 0 && x.len() % hd == 0 && p.len() == x.len() / hd * n { @@ -281,7 +318,7 @@ fn dots_k(p: &mut [f32], scale: f32, w: &[f16], x: &[f32], n: us /// Dot of f16 weights and f32 values. The loop controllers are 113 MB of F32 in the file and every token reads them /// twice, at the speed of the memory: as f16 they take half the time (their values stay within 5e-4 relative). -fn dot_h(w: &[f16], x: &[f32]) -> f32 { +pub(crate) fn dot_h(w: &[f16], x: &[f32]) -> f32 { #[cfg(all(target_feature = "f16c", target_feature = "fma"))] { use std::arch::x86_64::*; @@ -322,7 +359,7 @@ fn axpy_h(o: &mut [f32], p: f32, w: &[f16]) { /// Row j of `o` += the sum over the `n` f16 rows of `w` of `p[j * n + row]` times that row. One to three rows of /// `o` take the same sums in the same order. -fn mix_h(o: &mut [f32], p: &[f32], w: &[f16], n: usize) { +pub(crate) fn mix_h(o: &mut [f32], p: &[f32], w: &[f16], n: usize) { let hd = w.len() / n; #[cfg(all(target_feature = "f16c", target_feature = "fma"))] if hd % 32 == 0 && o.len() % hd == 0 && p.len() == o.len() / hd * n { @@ -546,6 +583,8 @@ impl<'a> Inkling2Model<'a> { slots: (0..cfg.n_slot()).map(|_| Slot::default()).collect(), cpu_share: std::cell::Cell::new(0.5), chunk_share: std::cell::Cell::new(0.3), + split: Default::default(), + split_cost: Default::default(), toks: vec![], trace: std::env::var_os("STRATA_DS_TRACE").is_some(), prof: Default::default(), @@ -555,6 +594,7 @@ impl<'a> Inkling2Model<'a> { dspark: None, spec_draft_max: 3, drafts: (0, 0), + ds_gate: DraftGate::default(), cfg, }; if !m.trace && std::env::var_os("STRATA_DS_DUMP").is_none() { @@ -570,12 +610,24 @@ impl<'a> Inkling2Model<'a> { if let Some(d) = &mut self.device { d.forget(); } if let Some(ng) = &mut self.ngram { ng.reset(); } if let Some(ds) = &mut self.dspark { ds.reset(); } + self.ds_gate = DraftGate::default(); + } + + /// Layers whose experts all sit on a card as one slab (`bench` counts them as resident; the expert cache never sees them). + pub fn slab_layers(&self) -> usize { + self.device.as_ref().map_or(0, |d| d.slab_layers()) } pub fn has_spec(&self) -> bool { self.ngram.as_ref().is_some_and(|ng| ng.cfg.is_enabled()) || self.dspark.is_some() } + /// Look up `tok` in `tok_embd`, writing the row to `out` (`[n_embd]`) with no norm. + pub fn embed_raw(&self, tok: u32, out: &mut [f32]) { + assert!((tok as usize) < self.tok_embd.rows, "token {tok} is outside the vocabulary"); + self.tok_embd.row_into(tok as usize, out); + } + /// Look up `tok` in `tok_embd` and RMS-normalize with `tok_norm` (`cfg.eps`), writing `out` (`[n_embd]`). pub fn embed_normed(&self, tok: u32, out: &mut [f32]) { assert!((tok as usize) < self.tok_embd.rows, "token {tok} is outside the vocabulary"); @@ -584,6 +636,39 @@ impl<'a> Inkling2Model<'a> { rms_norm_w(&emb, &self.tok_norm, self.cfg.eps, out); } + /// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head on GPU, keeping the logits on device. + pub(super) fn lm_head_batch_gpu(&mut self, h_rows: &[f32], nt: usize) -> bool { + if let Some(mut d) = self.device.take() { + let ok = d.lm_head_batch_gpu(self, h_rows, nt).is_ok(); + self.device = Some(d); + return ok; + } + false + } + + /// Add `w2 @ latent + bias` onto `pf.logits_buf[step]` on GPU and return the argmax token ID. + pub(super) fn markov_w2_argmax_gpu( + &self, w2: &crate::backend::GpuTensor, bias_addr: u64, bias_len: usize, latent: &[f32], step: usize, + ) -> Option { + self.device.as_ref()?.markov_w2_argmax_gpu(self, w2, bias_addr, bias_len, latent, step).ok() + } + + pub(super) fn output_rows(&self) -> usize { self.output.rows } + + /// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head on CPU only. + pub(super) fn lm_head_batch_cpu(&self, h_rows: &[f32], nt: usize) -> Vec { + let rows: Vec<&[f32]> = h_rows.chunks_exact(self.cfg.n_embd).take(nt).collect(); + let raw = matvec_rows(&self.output, &rows); + if self.output.rows == self.cfg.n_vocab { + return raw; + } + let mut out = Vec::with_capacity(nt * self.cfg.n_vocab); + for row in raw.chunks_exact(self.output.rows) { + out.extend_from_slice(&row[..self.cfg.n_vocab]); + } + out + } + /// Project a single hidden state `h` (`[n_embd]`) through the target LM head (`output.weight`) and return the /// greedy argmax token ID (`0..cfg.n_vocab`) of the logits before the softcap. For drafts. pub fn lm_head_argmax(&self, h: &[f32]) -> u32 { @@ -747,9 +832,22 @@ impl<'a> Inkling2Model<'a> { share.or(std::env::var_os("STRATA_FIXED_EXPERTS").map(|_| 0.0)) }); if crate::deepseek::mat::dev_info().is_none() { return (1.0, true); } + // A single token (and a draft check) gives every miss to the CPU by default: staging an expert costs an + // allocation, copies and a wait a layer run, which the balance does not see as a fixed cost. That is also the + // placement that made the output repeatable on main: the share never moves, so a hit and a miss compute the + // same way on every run. `STRATA_DS_STAGE=1` opts into the timed split (one token's misses split between the + // CPU and staged copies, `stage_count`), which is faster on some cards but lets the route depend on timings. + let fixed = fixed.or(std::ptr::eq(share, &self.cpu_share).then_some(1.0)); (fixed.unwrap_or(share.get()).clamp(0.0, 1.0), fixed.is_some()) } + /// Whether a token's misses split between the CPU and staged copies by measured times (`STRATA_DS_STAGE=1`). + /// Off by default: the split then follows `share()`, so the output is the same on every run. + fn stage_split(&self) -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("STRATA_DS_STAGE").is_some()) + } + /// The routed experts of one token in layer `ip`: those of the GPU as `(gate_up, expert, weight)`, those of the /// CPU as `(gate_up, down, weight, gate_up scale)`, and whether the CPU share follows the two times. #[allow(clippy::type_complexity)] @@ -763,14 +861,40 @@ impl<'a> Inkling2Model<'a> { for m in [&l.gate_up, &l.down] { m.prefetch_expert(e, ne); } } } - // Experts resident in VRAM run on the GPU. Of the others, the CPU computes `cpu_share` from the mapped file - // while the GPU uploads and runs the rest, both at once (see `hy4::forward`). `STRATA_DS_CPU_SHARE` fixes the + // Experts resident in VRAM run on the GPU. Of the others, the CPU computes some from the mapped file while the + // GPU uploads and runs the rest, both at once (`stage_count` picks how many). `STRATA_DS_CPU_SHARE` fixes the // share; 0 (also `--fixed-experts`) runs every expert on the GPU: the same numerics on every run. self.lap(4, t); let (share, fixed) = self.share(&self.cpu_share); - let gus: Vec = sel.iter().map(|s| l.gate_up.expert_opt(s.0, ne, share == 0.0)).collect(); + let mut gus: Vec = sel.iter().map(|s| l.gate_up.expert_opt_in(s.0, ne, share == 0.0, &l.gate_up, l.down.data.len())).collect(); + if !fixed && let Some(d) = crate::deepseek::mat::dev::get() { + // An expert runs on the GPU when both its matrices are in VRAM. The most used of the others may take the + // slots of a less used one (`Dev::admit`): the cache follows what this text routes to. + let mut d = d.lock().unwrap(); + let mat = |m: &Mat<'a>| (m.data, m.ty, m.rows, m.cols, m.scale); + let mut miss = vec![]; + for (gu, &(e, _)) in gus.iter_mut().zip(&sel) { + let dn = l.down.expert_host(e, ne); + if gu.gpu.is_some() && d.resident(dn.data) { continue; } + gu.gpu = None; + miss.push((e, [mat(&l.gate_up.expert_host(e, ne)), mat(&dn)])); + } + let cands: Vec<_> = miss.iter().map(|m| m.1).collect(); + if let Some(i) = d.admit(&cands) { + let e = miss[i].0; + let j = sel.iter().position(|s| s.0 == e).unwrap(); + gus[j] = l.gate_up.expert_host(e, ne); + gus[j].gpu = d.ex.get(&(gus[j].data.as_ptr() as usize)).map(|&p| d.exs[p].0); + ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } let n_miss = gus.iter().filter(|m| m.gpu.is_none()).count(); - let mut left = (share * n_miss as f32).round() as usize; + // No staged copies unless `share()` said so (`--fixed-experts`' 0.0) or `STRATA_DS_STAGE=1` asked for the timed + // split: with the share fixed at 1.0 every miss goes to the CPU, as on main, and the output repeats run to run. + let n_stage = if fixed { n_miss - (share * n_miss as f32).round() as usize } + else if self.stage_split() { self.stage_count(n_miss) } else { 0 }; + let mut left = n_miss - n_stage; + self.split.set((left, n_stage)); let (mut on_gpu, mut on_cpu) = (vec![], vec![]); for (gu, &(e, w)) in gus.into_iter().zip(&sel) { if gu.gpu.is_none() && left > 0 { @@ -780,12 +904,49 @@ impl<'a> Inkling2Model<'a> { on_gpu.push((gu, e, w)); } } - (on_gpu, on_cpu, !fixed && n_miss > 0) + { + use std::sync::atomic::Ordering::Relaxed; + let b = |m: &Mat| m.data.len() as u64; + HYB[0].fetch_add(on_cpu.iter().map(|e| b(&e.0) + b(&e.1)).sum(), Relaxed); + HYB[1].fetch_add(on_cpu.len() as u64, Relaxed); + HYB[2].fetch_add(on_gpu.iter().filter(|e| e.0.gpu.is_none()).count() as u64, Relaxed); + HYB[3].fetch_add(on_gpu.len() as u64, Relaxed); + } + (on_gpu, on_cpu, !fixed && n_stage > 0) + } + + /// How many of a token's `n_miss` routed experts outside VRAM the GPU copies up for this use; the CPU computes + /// the rest from the mapped file. The two run at once, so the split is the one whose slower side is fastest, from + /// the measured time of one expert on each side. A layer has a handful of misses, and one copy can cost more than + /// the CPU takes for all of them (PCIe 3.0 against dual-channel DDR4, an 8.5 MB Q8_0 expert: 2.5 ms against + /// 0.25 ms): then nothing is copied. The copy cost is measured on first use and again every 512 plans. + fn stage_count(&self, n_miss: usize) -> usize { + if n_miss == 0 { return 0; } + let [cpu, up, since] = self.split_cost.get(); + if up == 0.0 || since >= 512.0 { + self.split_cost.set([cpu, up, 0.0]); + return 1; + } + self.split_cost.set([cpu, up, since + 1.0]); + let t = |s: usize| ((n_miss - s) as f32 * cpu).max(s as f32 * up); + (0..=n_miss).min_by(|&a, &b| t(a).total_cmp(&t(b))).unwrap() + } + + /// The times of the two sides of the last `plan` of one token: the per-expert costs `stage_count` splits by. + /// `staged`: the GPU side copied experts up and waited for its queue, so `tg` is their cost. + fn balance_split(&self, staged: bool, tg: f32, tc: f32) { + self.prof[5].set(self.prof[5].get() + tg as f64); + self.prof[6].set(self.prof[6].get() + tc as f64); + let ((n_cpu, n_stage), [mut cpu, mut up, since]) = (self.split.get(), self.split_cost.get()); + let ema = |old: f32, new: f32| if old == 0.0 { new } else { 0.8 * old + 0.2 * new }; + if n_cpu > 0 { cpu = ema(cpu, tc / n_cpu as f32); } + if staged && n_stage > 0 { up = ema(up, tg / n_stage as f32); } + self.split_cost.set([cpu, up, since]); } /// The GPU's experts of `plan` with both matrices in VRAM: in a cache slot, or copied up for this use. fn resident(l: &Layer<'a>, ne: usize, on_gpu: &[(Mat<'a>, usize, f32)]) -> Vec<(Mat<'a>, Mat<'a>, f32, f32)> { - let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, true); if x.gpu.is_some() { x } else { x.staged() } }; + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt_in(e, ne, true, &l.gate_up, l.down.data.len()); if x.gpu.is_some() { x } else { x.staged() } }; on_gpu.iter().map(|&(gu, e, w)| (if gu.gpu.is_some() { gu } else { on(&l.gate_up, e) }, on(&l.down, e), w, l.gu_scale[e])).collect() } @@ -810,7 +971,7 @@ impl<'a> Inkling2Model<'a> { (run_experts(&on_cpu, x, cfg), t.elapsed().as_secs_f32()) }; let ((a, tg), (b, tc)) = rayon::join(gpu_side, cpu_side); - self.balance(&self.cpu_share, adapt, tg, tc); + self.balance_split(adapt, tg, tc); a.iter().zip(&b).map(|(a, b)| a + b).collect() } @@ -836,8 +997,8 @@ impl<'a> Inkling2Model<'a> { // split of the prefill chunks alone. let cell = if xs.len() <= device::VERIFY_MAX { &self.cpu_share } else { &self.chunk_share }; let (share, fixed) = self.share(cell); - let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, share == 0.0); if x.gpu.is_some() { x } else { x.staged() } }; - let gus: Vec<(usize, Mat)> = by_e.keys().map(|&e| (e, l.gate_up.expert_opt(e, ne, share == 0.0))).collect(); + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt_in(e, ne, share == 0.0, &l.gate_up, l.down.data.len()); if x.gpu.is_some() { x } else { x.staged() } }; + let gus: Vec<(usize, Mat)> = by_e.keys().map(|&e| (e, l.gate_up.expert_opt_in(e, ne, share == 0.0, &l.gate_up, l.down.data.len()))).collect(); let n_miss = gus.iter().filter(|g| g.1.gpu.is_none()).count(); let mut left = (share * n_miss as f32).round() as usize; let (mut on_gpu, mut on_cpu) = (vec![], vec![]); @@ -990,7 +1151,7 @@ impl<'a> Inkling2Model<'a> { return out; } Err(e) => { - eprintln!("inkling2: no room in VRAM for the decode state ({e:#}); the tokens run as prompt chunks do"); + crate::say!("inkling2: no room in VRAM for the decode state ({e:#}); the tokens run as prompt chunks do"); d.to_host(&self.cfg, &self.layers, &mut self.slots, pos, self.max_ctx); self.no_device = true; } @@ -1039,13 +1200,13 @@ impl<'a> Inkling2Model<'a> { return res; } Err(e) => { - eprintln!("inkling2: GPU verify failed ({e:#}); falling back to host"); + crate::say!("inkling2: GPU verify failed ({e:#}); falling back to host"); d.to_host(&self.cfg, &self.layers, &mut self.slots, pos0, self.max_ctx); self.no_device = true; } }, Err(e) => { - eprintln!("inkling2: no room in VRAM for verify ({e:#}); falling back to host"); + crate::say!("inkling2: no room in VRAM for verify ({e:#}); falling back to host"); d.to_host(&self.cfg, &self.layers, &mut self.slots, pos0, self.max_ctx); self.no_device = true; } @@ -1067,25 +1228,30 @@ impl<'a> Inkling2Model<'a> { } } - fn propose_drafts(&mut self, anchor_tok: u32, max_draft: usize, eos: &[u32]) -> Vec { + /// Drafts for the next verify, and whether DSpark made them (its acceptance then steers `ds_gate`). + fn propose_drafts(&mut self, anchor_tok: u32, max_draft: usize, eos: &[u32]) -> (Vec, bool) { // Drafts are verified in one batch on the GPU; without a device there is nothing to gain from them. - if self.device.is_none() && self.no_device { return Vec::new(); } + if self.device.is_none() && self.no_device { return (Vec::new(), false); } let cap_ng = max_draft.min(device::VERIFY_MAX - 1); let cap_ds = max_draft.min(self.spec_draft_max).min(device::VERIFY_MAX - 1); let mut draft = Vec::new(); if cap_ng > 0 && let Some(ng) = &mut self.ngram && ng.cfg.is_enabled() { draft = ng.draft(anchor_tok, cap_ng); } - if draft.is_empty() && cap_ds > 0 && self.dspark.is_some() { - let pos0 = self.toks.len(); - let ds = self.dspark.take().unwrap(); - draft = ds.draft(self, anchor_tok, pos0, cap_ds); - self.dspark = Some(ds); + let ds = draft.is_empty() && cap_ds > 0 && self.dspark.is_some(); + if ds { + let n = self.ds_gate.take(cap_ds); + if n > 0 { + let pos0 = self.toks.len(); + let ds = self.dspark.take().unwrap(); + draft = ds.draft(self, anchor_tok, pos0, n); + self.dspark = Some(ds); + } } if let Some(p) = draft.iter().position(|t| eos.contains(t)) { draft.truncate(p + 1); } - draft + (draft, ds) } /// Greedy speculative step from `anchor_tok`: proposes up to `max_draft` draft tokens, verifies `[anchor_tok, drafts..]` @@ -1093,7 +1259,7 @@ impl<'a> Inkling2Model<'a> { /// tokens `[accepted_drafts.., bonus]` (where `bonus` is the next anchor token, not yet in `self.toks`, unless an /// accepted draft was EOS). pub fn spec_step_argmax(&mut self, anchor_tok: u32, max_draft: usize, eos: &[u32]) -> Vec { - let draft = self.propose_drafts(anchor_tok, max_draft, eos); + let (draft, from_ds) = self.propose_drafts(anchor_tok, max_draft, eos); if draft.is_empty() { return vec![self.step_argmax(anchor_tok)]; } @@ -1130,6 +1296,7 @@ impl<'a> Inkling2Model<'a> { let keep = 1 + accepted; self.drafts.0 += draft.len(); self.drafts.1 += accepted; + if from_ds { self.ds_gate.feedback(draft.len(), accepted, self.spec_draft_max.min(device::VERIFY_MAX - 1)); } self.commit_batch(pos0, keep, nt, &cand, feats.as_deref()); out } @@ -1146,7 +1313,7 @@ impl<'a> Inkling2Model<'a> { if pure_greedy { return self.spec_step_argmax(anchor_tok, max_draft, eos); } - let draft = self.propose_drafts(anchor_tok, max_draft, eos); + let (draft, from_ds) = self.propose_drafts(anchor_tok, max_draft, eos); if draft.is_empty() { let l = self.step(anchor_tok); let next = smp.pick(&l).unwrap_or_else(|_| crate::ops::argmax(&l)) as u32; @@ -1206,6 +1373,7 @@ impl<'a> Inkling2Model<'a> { let keep = 1 + accepted; self.drafts.0 += draft.len(); self.drafts.1 += accepted; + if from_ds { self.ds_gate.feedback(draft.len(), accepted, self.spec_draft_max.min(device::VERIFY_MAX - 1)); } self.commit_batch(pos0, keep, nt, &cand, feats.as_deref()); out } @@ -1264,7 +1432,8 @@ impl<'a> Inkling2Model<'a> { let target_end = self.toks.len() + seq.len() - 1; match d.prepare(self, target_end) { Ok(()) => { - let chunk = env_chunk.unwrap_or(256).clamp(1, 256); + let chunk = env_chunk.unwrap_or(device::pf_tokens()).clamp(1, device::pf_tokens()); + let chunk = d.prefill_rows(self, chunk.min(seq.len()).max(1)); let mut logits = vec![]; let mut done = 0usize; let mut failed = None; @@ -1278,13 +1447,14 @@ impl<'a> Inkling2Model<'a> { ds.inject_subset(pos0, c.len(), c.len(), f); } done += c.len(); + crate::term::prefilled(c.len()); if want { logits = l; } } Err(e) => { failed = Some(e); break; } } } if let Some(e) = failed { - eprintln!("inkling2: GPU prefill failed ({e:#}); falling back to host chunk path"); + crate::say!("inkling2: GPU prefill failed ({e:#}); falling back to host chunk path"); let pos = self.toks.len(); d.to_host(&self.cfg, &self.layers, &mut self.slots, pos, self.max_ctx); self.no_device = true; @@ -1300,7 +1470,7 @@ impl<'a> Inkling2Model<'a> { return logits; } Err(e) => { - eprintln!("inkling2: no room in VRAM for prefill ({e:#}); falling back to host chunk path"); + crate::say!("inkling2: no room in VRAM for prefill ({e:#}); falling back to host chunk path"); let pos = self.toks.len(); d.to_host(&self.cfg, &self.layers, &mut self.slots, pos, self.max_ctx); self.no_device = true; @@ -1311,7 +1481,7 @@ impl<'a> Inkling2Model<'a> { let mut chunk = env_chunk.unwrap_or(512); if dump_or_trace { chunk = 1; } let mut logits = vec![]; - for (i, c) in seq.chunks(chunk.max(1)).enumerate() { logits = self.run_seq(c, (i + 1) * chunk.max(1) >= seq.len()); } + for (i, c) in seq.chunks(chunk.max(1)).enumerate() { logits = self.run_seq(c, (i + 1) * chunk.max(1) >= seq.len()); crate::term::prefilled(c.len()); } if let Some(ng) = &mut self.ngram { ng.begin(&self.toks); } logits } @@ -1391,14 +1561,36 @@ impl<'a> Inkling2Model<'a> { use std::sync::atomic::Ordering::Relaxed; let ex = &crate::deepseek::mat::EX_LOOKUPS; let parts: Vec = PROF.iter().zip(&self.prof).map(|(n, c)| format!("{n} {:.1}", c.replace(0.0) * 1e3)).collect(); - eprintln!("PROF pos {pos}, {nt} tokens: {:.1} ms ({}), expert cache hit {} miss {}, cpu share {:.2} chunk {:.2}", - t0.elapsed().as_secs_f64() * 1e3, parts.join(", "), ex[0].swap(0, Relaxed), ex[1].swap(0, Relaxed), self.cpu_share.get(), self.chunk_share.get()); + eprintln!("PROF pos {pos}, {nt} tokens: {:.1} ms ({}), expert cache hit {} miss {}, expert ms cpu {:.2} copy {:.2}, chunk share {:.2}, CPU experts {} MB in {}, copied up {} of the GPU's {}, admitted {}", + t0.elapsed().as_secs_f64() * 1e3, parts.join(", "), ex[0].swap(0, Relaxed), ex[1].swap(0, Relaxed), self.split_cost.get()[0] * 1e3, self.split_cost.get()[1] * 1e3, self.chunk_share.get(), + HYB[0].swap(0, Relaxed) >> 20, HYB[1].swap(0, Relaxed), HYB[2].swap(0, Relaxed), HYB[3].swap(0, Relaxed), ADMITS.swap(0, Relaxed)); } } } #[cfg(test)] mod tests { + use super::DraftGate; + + /// #154: low acceptance shortens DSpark's drafts and then pauses them; full acceptance lengthens them to the cap. + #[test] + fn draft_gate_follows_acceptance() { + let mut g = DraftGate::default(); + assert_eq!(g.take(3), 3, "starts at the cap"); + g.feedback(3, 0, 3); + assert_eq!(g.take(3), 2); + g.feedback(2, 1, 3); + assert_eq!(g.take(3), 2, "a partly taken draft keeps its length"); + g.feedback(2, 0, 3); + assert_eq!(g.take(3), 1); + g.feedback(1, 0, 3); + for _ in 0..DraftGate::PAUSE { assert_eq!(g.take(3), 0, "paused"); } + assert_eq!(g.take(3), 1, "tries one again after the pause"); + g.feedback(1, 1, 3); + g.feedback(2, 2, 3); + g.feedback(3, 3, 3); + assert_eq!(g.take(3), 3, "full acceptance grows back to the cap, not past it"); + } use super::*; #[test] @@ -1473,4 +1665,37 @@ mod tests { let r = 2f32.sqrt() / 2.0; assert!((got[0] - r).abs() < 1e-4 && (got[1] - r).abs() < 1e-4, "{got:?}"); } + + /// A config with no file behind it: the shapes the scratch layout uses. + fn scratch_cfg(n_embd: usize, n_head: usize, n_used: usize) -> Inkling2Config { + Inkling2Config { + n_layer: 3, n_ctx: 4096, n_embd, n_head, n_head_kv: n_head / 3, head_dim: 128, n_expert: 128, n_used, + n_ff_exp: 1152, n_vocab: 1024, eps: 1e-6, n_swa: 1024, swa: vec![true, false, true], n_conv: 4, + exp_scale: 8.0, situ_beta: 4.0, situ_linear_beta: 25.0, block_size: 6, softcap: 30.0, n_rel: 16, + rel_extent: 1024, qk_clip: 22.6, rel_clip: 8.0, log_floor: 8192.0, log_alpha: 0.1, + loop_start: 1, loop_end: 2, loop_count: 1, ctx: 4096, + } + } + + /// Every region of the decode scratch is 16-byte aligned: `situ_q` reads `float4` from `y`, which follows `hn`, + /// `wh` and `step`. At the model's sizes most widths are a multiple of 4 floats anyway, so the odd ones are taken + /// too (`ids` is 3 * n_used floats, `pos` one), along with odd vocabularies. + #[test] + fn decode_scratch_regions_are_16_byte_aligned() { + for (n_embd, n_head, n_used, vocab) in [(2304, 24, 8, 248320), (2304, 24, 7, 1021), (2560, 32, 9, 1024), (2304, 24, 5, 999)] { + let c = scratch_cfg(n_embd, n_head, n_used); + assert!(device::Scratch::aligned(0, &c, 64, vocab), "n_used {n_used}, vocab {vocab}"); + assert!(device::Scratch::aligned(1 << 20, &c, 64, vocab), "n_used {n_used}, vocab {vocab}, other base"); + } + } + + /// `--tail-skip` can drop every CPU expert of a token. The worker writes what `run_experts` returns, so it has to be zeros. + #[test] + fn a_token_with_every_cpu_expert_dropped_gets_zeros() { + // A mailbox of one token with four picks: ids, weights, slots. The two lightest are on the CPU (slot -1). + let v: Vec = [10, 11, 12, 13].into_iter().chain([0.4f32, 0.3, 0.2, 0.1].map(f32::to_bits)).chain([0, 1, u32::MAX, u32::MAX]).collect(); + let on_cpu = |rank| { let keep = crate::cpu_worker::tail_keep(&v, 4, 4, rank); (0..4).filter(|&j| (v[8 + j] as i32) < 0 && keep[j]).count() }; + assert_eq!((on_cpu(0), on_cpu(3), on_cpu(2)), (2, 1, 0), "off, then --tail-skip 3 and 2"); + assert_eq!(run_experts(&[], &[1.0; 64], &scratch_cfg(64, 4, 8)), vec![0.0; 64]); + } } diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index d3787ab4..d39c75a7 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -14,6 +14,8 @@ use std::sync::Arc; /// Contiguous all-expert weights + F32 router uploaded once for a layer, enabling zero-round-trip GPU MoE. struct FullExps { + /// The GPU of the slabs: 0, or 1 when GPU 0 had no room (the FFN of that layer runs there, see `Remote`). + part: usize, _gi: Arc, gate_inp: GpuTensor, bias: Arc, @@ -38,11 +40,26 @@ struct DLoop { msg_query: Buf, down: Buf, gain: Buf, forget: Buf } /// sliding-window slot is a ring of `n_swa` rows (position p in row p % n_swa); the others grow. struct DSlot { k: Buf, v: Buf, hist: Buf, cap: usize } +/// What GPU 1 needs to run the FFN of the layers whose experts live there: a decode scratch (`s`) and, from the first +/// prompt chunk on, a prefill scratch. The activations come over the host once per layer run (about 10 KB per token). +struct Remote { part: usize, scr: Buf, s: Scratch, pf: Option } + +/// Tokens of one prompt chunk on the device: `STRATA_DS_PF_TOKENS` (default 2048 on one card, 512 on two or more; +/// at most 2048). On one card each chunk copies the pool's missing experts into the +/// staging slots again, so a longer chunk spreads that copy over more tokens; the scratch costs about 0.55 GB of VRAM +/// per 1024 rows, and `prefill_rows` halves the chunk when VRAM has no room for it. +pub(super) fn pf_tokens() -> usize { + let multi = std::env::var("STRATA_DS_DEVICES") + .map_or(false, |v| v.split(',').filter(|d| !d.trim().is_empty()).count() > 1); + let default = if multi { 512 } else { 2048 }; + std::env::var("STRATA_DS_PF_TOKENS").ok().and_then(|v| v.parse::().ok()).unwrap_or(default).clamp(1, 2048) +} + /// Device addresses of the regions of the decode scratch buffer (`sc` lives in `Device::sc_buf` so `--ctx` scales dynamically). #[derive(Clone, Copy)] -struct Scratch { +pub(super) struct Scratch { cur: u64, x: u64, blocks: u64, bank: u64, outb: u64, prelude: u64, msg: u64, ins: u64, ins2: u64, gate: u64, nrm: u64, nrm_xq: u64, - q: u64, r: u64, sink: u64, og: u64, k: u64, v: u64, kp: u64, vp: u64, att: u64, proj: u64, h: u64, h2: u64, hn: u64, + q: u64, r: u64, sink: u64, og: u64, k: u64, v: u64, kp: u64, vp: u64, att: u64, proj: u64, h: u64, h2: u64, hn: u64, wh: u64, step: u64, y: u64, d: u64, ids: u64, xh: u64, xq: u64, wc: u64, rlogits: u64, amax: u64, pos: u64, acc: u64, logits: u64, end: u64, } @@ -50,15 +67,37 @@ impl Scratch { fn at(base: u64, c: &Inkling2Config, rank: usize, vocab: usize) -> Self { let (n, q, mut a) = (c.n_embd, c.n_head * c.head_dim, base); let xq_row_floats = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; - let mut f = |floats: usize| { a += 4 * floats as u64; a - 4 * floats as u64 }; + // Every region starts at a multiple of 4 floats (16 bytes): `situ_q` and the other kernels read `float4`, and + // an unaligned address faults on CUDA. `wh` and `step` are padded at their fields too, so a reader of + // `c.n_used` floats reads what it always did; the rounding here also covers `ids`, `wc`, `pos` and any other + // region whose width is not a multiple of 4 floats on some config. + let mut f = |floats: usize| { + let at = a; + a += 4 * floats.next_multiple_of(4) as u64; + at + }; Scratch { cur: f(n), x: f(n), blocks: f(4 * n), bank: f(4 * n), outb: f(n), prelude: f(n), msg: f(4 * n), ins: f(3 * n), ins2: f(3 * n), gate: f(4 * rank), nrm: f(3 * n), nrm_xq: f(3 * xq_row_floats), q: f(q), r: f(c.n_head * c.n_rel), sink: f(c.n_head), og: f(q), k: f(c.n_head_kv * c.head_dim), v: f(c.n_head_kv * c.head_dim), kp: f(c.n_head_kv * c.n_conv), vp: f(c.n_head_kv * c.n_conv), att: f(q), proj: f(n), h: f(n), - h2: f(n), hn: f(n), y: f(c.n_used * 2 * c.n_ff_exp), d: f(c.n_used * n), ids: f(3 * c.n_used), xh: f(n), xq: f(c.n_used * c.n_ff_exp), wc: f(c.n_used + n), rlogits: f(c.n_expert), amax: f(16), pos: f(1), acc: f(n), + h2: f(n), hn: f(n), wh: f(c.n_used.next_multiple_of(4)), step: f(4), y: f(c.n_used * 2 * c.n_ff_exp), d: f(c.n_used * n), ids: f(3 * c.n_used), xh: f(n), xq: f(c.n_used * c.n_ff_exp), wc: f(c.n_used + n), rlogits: f(c.n_expert), amax: f(16), pos: f(1), acc: f(n), logits: f(vocab), end: a - base, } } + + /// Every region starts on a multiple of 4 floats and the buffer's total is one too: the kernels that read `float4` + /// need the first, and `end` is the size the scratch buffer is allocated with, so a misaligned `end` would make + /// the last region run past the allocation. `end` is an offset from `base` (the size), so it is checked directly + /// rather than against `base`. + #[cfg(test)] + pub(super) fn aligned(base: u64, c: &Inkling2Config, rank: usize, vocab: usize) -> bool { + let s = Self::at(base, c, rank, vocab); + [s.cur, s.x, s.blocks, s.bank, s.outb, s.prelude, s.msg, s.ins, s.ins2, s.gate, s.nrm, s.nrm_xq, s.q, s.r, + s.sink, s.og, s.k, s.v, s.kp, s.vp, s.att, s.proj, s.h, s.h2, s.hn, s.wh, s.step, s.y, s.d, s.ids, s.xh, + s.xq, s.wc, s.rlogits, s.amax, s.pos, s.acc, s.logits] + .iter().all(|&at| (at - base) % 16 == 0) + && s.end % 16 == 0 + } } #[derive(Clone, Copy)] @@ -116,23 +155,39 @@ struct PrefillScratch { } impl PrefillScratch { - fn alloc(be: &dyn Backend, c: &Inkling2Config, rank: usize, vocab_rows: usize, max_nt: usize) -> Result { + /// Bytes `alloc` takes (plus a little for the allocator). + fn bytes(be: &dyn Backend, c: &Inkling2Config, rank: usize, vocab_rows: usize, max_nt: usize, light: bool) -> usize { + let (kw, n_slot) = (c.n_head_kv * c.head_dim, c.n_slot()); + let rb = 2 * be.kv_words(kw).max(be.kv_words_v(kw)); + let lay = PrefillLayout::at(0, c, rank, max_nt).end as usize; + let swa = (n_slot * VERIFY_MAX * rb).max(1024); + let extra = if light { 0 } else { + 2 * max_nt * rb + 4 * VERIFY_MAX * vocab_rows + 16 * max_nt * c.n_embd + 4 * n_slot * hists(c).1 + + 4 * n_slot * VERIFY_MAX * (2 * kw + 2 * c.n_embd) + 2 * swa + }; + lay + 4 * max_nt * c.n_embd + (40 * max_nt * c.n_used).max(1024) + extra + (16 << 20) + } + + /// `light`: only what the routed experts of a layer need (GPU 1 runs nothing else): the attention logs are tiny. + fn alloc(be: &dyn Backend, c: &Inkling2Config, rank: usize, vocab_rows: usize, max_nt: usize, light: bool) -> Result { let lay0 = PrefillLayout::at(0, c, rank, max_nt); let buf = be.alloc(lay0.end as usize)?; let p = PrefillLayout::at(buf.addr(), c, rank, max_nt); let acc_buf = be.alloc(4 * max_nt * c.n_embd)?; let kw = c.n_head_kv * c.head_dim; - let rb = 2 * be.kv_words(kw); - let kv_bytes = max_nt * rb; + // Row bytes of the wider side: the scratch holds K rows or V rows, each at its own stride. + let rb = 2 * be.kv_words(kw).max(be.kv_words_v(kw)); + let kv_bytes = if light { 256 } else { max_nt * rb }; let (kc_tmp, vc_tmp) = (be.alloc(kv_bytes)?, be.alloc(kv_bytes)?); let max_np = max_nt * c.n_used; let meta = be.alloc((40 * max_np).max(1024))?; - let logits_buf = be.alloc(4 * VERIFY_MAX * vocab_rows)?; - let dspark_buf = be.alloc(4 * 4 * max_nt * c.n_embd)?; + let lt = |b: usize| if light { 256 } else { b }; + let logits_buf = be.alloc(lt(4 * VERIFY_MAX * vocab_rows))?; + let dspark_buf = be.alloc(lt(4 * 4 * max_nt * c.n_embd))?; let n_slot = c.n_slot(); - let hist_bak = be.alloc(4 * n_slot * hists(c).1)?; - let conv_log = be.alloc(4 * n_slot * VERIFY_MAX * (2 * kw + 2 * c.n_embd))?; - let swa_log_bytes = (n_slot * VERIFY_MAX * rb).max(1024); + let hist_bak = be.alloc(lt(4 * n_slot * hists(c).1))?; + let conv_log = be.alloc(lt(4 * n_slot * VERIFY_MAX * (2 * kw + 2 * c.n_embd)))?; + let swa_log_bytes = lt((n_slot * VERIFY_MAX * rb).max(1024)); let (swa_kc_log, swa_vc_log) = (be.alloc(swa_log_bytes)?, be.alloc(swa_log_bytes)?); Ok(Self { max_nt, buf, acc_buf, kc_tmp, vc_tmp, meta, logits_buf, dspark_buf, @@ -152,9 +207,18 @@ pub(super) struct Device { pf: Option, s: Scratch, rank: usize, + /// Every layer's experts run on the device: in a slab, or in `pool` with the CPU worker for the rest. all_full: bool, - /// Key of the recorded `step_fast` graph, by `argmax` (0: none). - graph_keys: [u64; 2], + /// GPU 1's share of the FFN layers (None when every layer's experts are on GPU 0). + rem: Option, + /// With `rem`: the loop layers are all on GPU 0, so the loop runs as one graph, and the layers around it launch one by one. + seg_graph: bool, + /// Blocks in the depth mix after the loop (what `layer_attn` counted when the loop graph was recorded). + loop_nb: usize, + /// VRAM slots and the CPU worker for the layers without a slab (decode only; None under `--fixed-experts`). + pool: Option, + /// Keys of the recorded `step_fast` graphs, by `argmax`, and of `core_graph` (0: none). + graph_keys: [u64; 3], /// Positions whose rows both sides hold, and whether the device has run tokens after them. synced: usize, ahead: bool, @@ -168,12 +232,33 @@ fn up(be: &dyn Backend, v: &[T]) -> Result { fn f(floats: usize) -> u64 { 4 * floats as u64 } +/// Rows of a K/V buffer that grows to hold `need`: a quarter more, so that a reply does not grow it at every token +/// and a long prompt does not take twice its rows from the experts. +/// K/V rows the expert pool leaves room for at load; a longer context rebuilds the pool in `prepare`. +const KV_RESERVE: usize = 16384; + +fn grown(need: usize, max_ctx: usize) -> usize { (need + need / 4).next_multiple_of(1024).min(max_ctx) } + /// Free expert slots until `need` bytes of VRAM are free. fn room(d: &mut dev::Dev, need: usize) { let free = d.parts[0].be.mem_info().map_or(0, |m| m.0); if free < need { d.release(0, need - free); } } +/// Bytes GPU 0 still needs free after the expert pool: the K/V rows of the layers that grow, to `rows` (the configured +/// context), plus as many again for the rows they hold during a growth (`prepare` allocates the new buffer before it +/// frees the old, and after earlier prompts the old one can be up to `rows` long, not the rows of the load), the +/// score buffer for them, the prefill scratch of `pf_tokens()` rows (allocated before the K/V growth) and the reserve +/// `prepare` keeps. The pool leaves this much (or `--vram-margin`, whichever is larger) free, so the K/V growth of a 16k +/// prompt finds the room it needs instead of dropping the pool, and the prompt scratch is allocated once instead of +/// being halved to 256 rows (`prefill_rows`). +fn state_bytes(be: &dyn Backend, c: &Inkling2Config, kw: usize, rows: usize, nt: usize, vocab_rows: usize, rank: usize) -> usize { + let n_att = (0..c.n_slot()).filter(|&il| !c.swa[layer_of(c, il)]).count(); + let kv = |r: usize| 2 * n_att * r * be.kv_row_words(kw); + 2 * kv(rows) + sc_bytes(c, rows) + PrefillScratch::bytes(be, c, rank, vocab_rows, nt, false) + + Scratch::at(0, c, rank, vocab_rows).end as usize + (512 << 20) +} + /// Bytes of the attention partials for `rows` full-attention rows. fn sc_bytes(c: &Inkling2Config, rows: usize) -> usize { 4 * c.n_head * rows.div_ceil(64) * (c.head_dim + 2) } @@ -214,6 +299,17 @@ fn shapes_fit(m: &Inkling2Model, rank: usize) -> bool { } /// The layer whose weights slot `il` runs. +/// (slot, layer) of each layer run of a token, in the order it runs them. +fn run_order(c: &Inkling2Config) -> Vec<(usize, usize)> { + let core = c.loop_end - c.loop_start; + let mut runs: Vec<(usize, usize)> = (0..c.loop_start).map(|il| (il, il)).collect(); + for pass in 0..c.loop_count { + runs.extend((c.loop_start..c.loop_end).map(|ip| (if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start }, ip))); + } + runs.extend((c.loop_end..c.n_layer).map(|il| (il, il))); + runs +} + fn layer_of(c: &Inkling2Config, il: usize) -> usize { if il < c.n_layer { il } else { c.loop_start + (il - c.n_layer) % (c.loop_end - c.loop_start) } } @@ -236,6 +332,8 @@ fn runs(from: usize, to: usize, ring: usize) -> impl Iterator usize { self.layers.iter().filter(|l| l.full_exps.is_some()).count() } + /// None when a token cannot run on the device: no GPU or more than one, a dense matrix that is not in VRAM, a /// shape the kernels do not take, a tensor trace, no room, or `STRATA_DS_DEVICE=0`. pub(super) fn new(m: &Inkling2Model) -> Option { @@ -248,14 +346,15 @@ impl Device { let full = (2 * (pos + 1)).clamp(4096.min(m.max_ctx), m.max_ctx); { let mut d = dev::get()?.lock().unwrap(); - if d.parts.len() != 1 { return None; } - let dense = |x: &Mat| !x.host_only(); + // Local patch: several GPUs are fine as long as the plain weights are on GPU 0 (see STRATA_DS_PLAIN_FIRST); the + // experts that live on another GPU run as a third share in `layer`. + let dense = |x: &Mat| !x.host_only() && d.on_first(x); if !dense(&m.output) || !m.layers.iter().all(|l| { [l.wq, l.wk, l.wv, l.wo, l.gate, l.rel, l.sink].iter().chain(l.conv_proj.iter().flatten()).all(dense) }) { return None; } let rows: usize = (0..c.n_slot()).map(|il| if c.swa[layer_of(c, il)] { c.n_swa } else { full }).sum(); - let row_words = d.parts[0].be.kv_words(kw); - room(&mut d, 4 * rows * row_words + sc_bytes(c, full) + Scratch::at(0, c, rank, m.output.rows).end as usize + (512 << 20)); + let kv_bytes = 2 * rows * d.parts[0].be.kv_row_words(kw); + room(&mut d, kv_bytes + sc_bytes(c, full) + Scratch::at(0, c, rank, m.output.rows).end as usize + (512 << 20)); } let made = (|| -> Result { let (mut layers, loops, slots, out_query, out_norm, scr, sc_buf) = { @@ -277,10 +376,10 @@ impl Device { let loops = m.loops.iter().map(|l| { Ok(DLoop { msg_query: up(be, &l.msg_query)?, down: half(&l.down)?, gain: half(&l.gain)?, forget: half(&l.forget)? }) }).collect::>>()?; - let row_words = be.kv_words(kw); + let (kwk, kwv) = (be.kv_words(kw), be.kv_words_v(kw)); let slots = (0..c.n_slot()).map(|il| { let rows = if c.swa[layer_of(c, il)] { c.n_swa } else { full }; - Ok(DSlot { k: be.alloc(2 * rows * row_words)?, v: be.alloc(2 * rows * row_words)?, hist: be.zeros::(hists(c).1)?, cap: rows }) + Ok(DSlot { k: be.alloc(2 * rows * kwk)?, v: be.alloc(2 * rows * kwv)?, hist: be.zeros::(hists(c).1)?, cap: rows }) }).collect::>>()?; let sc_buf = be.alloc(sc_bytes(c, (pos + 1).max(64)))?; let (out_query, out_norm, scr) = (up(be, &m.out_query)?, up(be, &m.out_norm)?, be.alloc(Scratch::at(0, c, rank, m.output.rows).end as usize)?); @@ -289,38 +388,73 @@ impl Device { let s = Scratch::at(scr.addr(), c, rank, m.output.rows); // Preload full-layer expert slabs so selected layers skip CPU routing, uploads, and host syncs. - // Core loop layers run 3x per token (75% of FFN compute), so prioritize them first. + // Core loop layers run 3x per token (75% of FFN compute), so they go first, and to GPU 0, where the attention is. + // Local patch: with two GPUs the layers that run once (outside the loop) prefer GPU 1, and a layer that does not + // fit on its GPU goes to the other one: every layer's experts end up in VRAM, and the FFN of a layer on GPU 1 + // runs there (`Remote`). GPU 0 keeps free what the state still needs: prompt chunk scratch and KV growth. let cpu_share = std::env::var("STRATA_DS_CPU_SHARE").ok().and_then(|v| v.parse::().ok()).unwrap_or(0.0); - let (mut n_full, mut slab_bytes) = (0usize, 0usize); - if cpu_share <= 0.0 && c.n_expert <= 512 && c.n_used <= 32 { + let (mut n_full, mut slab_bytes, mut per_part) = (0usize, 0usize, [0usize; 2]); + let mut rem: Option = None; + // With the expert pool (`pool`), every layer keeps its most used experts in VRAM instead: no slabs. + // STRATA_INK_SLABS=1 keeps the slabs and pools only the layers they leave out. One GPU only: a split + // keeps upstream's slabs on both cards. + let one_gpu = dev::get().unwrap().lock().unwrap().parts.len() == 1; + let pooled = one_gpu && cpu_share <= 0.0 && std::env::var_os("STRATA_FIXED_EXPERTS").is_none() + && std::env::var_os("STRATA_INK_SLABS").is_none() && dev::get().unwrap().lock().unwrap().parts[0].be.ink_pool(); + if cpu_share <= 0.0 && c.n_expert <= 512 && c.n_used <= 32 && !pooled { let (b_res, f_res) = (64 << 20, 384 << 20); - let order = (c.loop_start..c.loop_end).chain(0..c.loop_start).chain(c.loop_end..c.n_layer); + let (n_parts, pf_cap, vocab) = (dev::get().unwrap().lock().unwrap().parts.len().min(2), pf_tokens(), m.output.rows); + let (res0, res1) = { + let d = dev::get().unwrap().lock().unwrap(); + let be0 = &*d.parts[0].be; + // The KV rows GPU 0 must still be able to take: all of `--ctx` unless STRATA_DS_KV_TOKENS says less (a + // lower value frees room for more expert slabs on GPU 0, at the price of a host fallback past it). + let kv_rows = std::env::var("STRATA_DS_KV_TOKENS").ok().and_then(|v| v.parse::().ok()).unwrap_or(m.max_ctx) + .min(m.max_ctx).max(full); + let n_att = (0..c.n_slot()).filter(|&il| !c.swa[layer_of(c, il)]).count(); + let kv = 4 * n_att * kv_rows * be0.kv_words(kw) + sc_bytes(c, kv_rows); + let pf0 = PrefillScratch::bytes(be0, c, rank, vocab, pf_cap, false); + let pf1 = if n_parts > 1 { PrefillScratch::bytes(&*d.parts[1].be, c, rank, vocab, pf_cap, true) } else { 0 }; + // One card keeps the floor the pool keeps (`pool_floor` of `state_bytes`): with 384 MB the decode + // graph ran out of memory under --fixed-experts on 12 GB. The KV/prefill reserve is for the two-card plan. + let state = state_bytes(be0, c, kw, m.max_ctx.min(full.max(KV_RESERVE)), pf_cap, vocab, rank); + let res0 = if n_parts > 1 { f_res + pf0 + kv } else { super::pool::pool_floor(f_res, crate::deepseek::mat::dev_margin(), state) }; + (res0, (192 << 20) + pf1 + Scratch::at(0, c, rank, 0).end as usize) + }; let key = |s: &[u8]| Some((s.as_ptr() as usize, s.len())); + let on_loop = |ip: usize| (c.loop_start..c.loop_end).contains(&ip); + let order = (c.loop_start..c.loop_end).chain(0..c.loop_start).chain(c.loop_end..c.n_layer); for ip in order { let ml = &m.layers[ip]; let gi_bytes: Vec = ml.gate_inp.iter().flat_map(|x| x.to_le_bytes()).collect(); let bias_bytes: Vec = ml.bias.iter().flat_map(|x| x.to_le_bytes()).collect(); let gs_bytes: Vec = ml.gu_scale.iter().flat_map(|x| x.to_le_bytes()).collect(); let ds_bytes: Vec = ml.down_scale.iter().flat_map(|x| x.to_le_bytes()).collect(); - let Some((gu, dn, gi_slab, bias, gu_scale, dn_scale)) = (|| -> Option<_> { + let place = |part: usize| -> Option<(usize, Arc, Arc, Arc, Arc, Option>, Option>)> { let mut d = dev::get().unwrap().lock().unwrap(); - let gu = d.alloc_slab(ml.gate_up.data, key(ml.gate_up.data), b_res, f_res)?; - let dn = d.alloc_slab(ml.down.data, key(ml.down.data), b_res, f_res)?; - let gi = d.alloc_slab(&gi_bytes, None, b_res, f_res)?; - let bi = d.alloc_slab(&bias_bytes, None, b_res, f_res)?; - let gs = if gs_bytes.is_empty() { None } else { Some(d.alloc_slab(&gs_bytes, None, b_res, f_res)?) }; - let ds = if ds_bytes.is_empty() { None } else { Some(d.alloc_slab(&ds_bytes, None, b_res, f_res)?) }; - Some((gu, dn, gi, bi, gs, ds)) - })() else { + let fr = if part == 0 { res0 } else { res1 }; + let gu = d.alloc_slab_on(part, ml.gate_up.data, key(ml.gate_up.data), b_res, fr)?; + let dn = d.alloc_slab_on(part, ml.down.data, key(ml.down.data), b_res, fr)?; + let gi = d.alloc_slab_on(part, &gi_bytes, None, b_res, fr)?; + let bi = d.alloc_slab_on(part, &bias_bytes, None, b_res, fr)?; + let gs = if gs_bytes.is_empty() { None } else { Some(d.alloc_slab_on(part, &gs_bytes, None, b_res, fr)?) }; + let ds = if ds_bytes.is_empty() { None } else { Some(d.alloc_slab_on(part, &ds_bytes, None, b_res, fr)?) }; + Some((part, gu, dn, gi, bi, gs, ds)) + }; + let prefs: &[usize] = match (n_parts > 1, on_loop(ip)) { (false, _) => &[0], (true, true) => &[0, 1], (true, false) => &[1, 0] }; + let Some((part, gu, dn, gi_slab, bias, gu_scale, dn_scale)) = prefs.iter().find_map(|&p| place(p)) else { break; }; - slab_bytes += gu.len() + dn.len() + gi_slab.len() + bias.len() + let bytes = gu.len() + dn.len() + gi_slab.len() + bias.len() + gu_scale.as_ref().map_or(0, |b| b.len()) + dn_scale.as_ref().map_or(0, |b| b.len()); + slab_bytes += bytes; + per_part[part] += bytes; n_full += 1; let (gu_rows, gu_cols) = (ml.gate_up.rows / c.n_expert, ml.gate_up.cols); let (dn_rows, dn_cols) = (ml.down.rows / c.n_expert, ml.down.cols); layers[ip].full_exps = Some(FullExps { + part, gate_inp: GpuTensor::new(GgmlType::F32, c.n_expert, c.n_embd, Buf::new(gi_slab.addr(), gi_slab.len(), ())), _gi: gi_slab, bias, @@ -332,14 +466,53 @@ impl Device { dn_scale, }); } + if layers.iter().any(|l| l.full_exps.as_ref().is_some_and(|fe| fe.part == 1)) { + let d = dev::get().unwrap().lock().unwrap(); + let be1 = &*d.parts[1].be; + let r_scr = be1.alloc(Scratch::at(0, c, rank, 0).end as usize)?; + let r_s = Scratch::at(r_scr.addr(), c, rank, 0); + let pf = PrefillScratch::alloc(be1, c, rank, vocab, pf_cap, true).ok(); + rem = Some(Remote { part: 1, scr: r_scr, s: r_s, pf }); + } } if std::env::var_os("STRATA_DS_PROF").is_some() { - eprintln!("inkling2: preloaded {n_full}/{} expert layers ({:.2} GB) as contiguous slabs", c.n_layer, slab_bytes as f64 / 1e9); + crate::say!("inkling2: preloaded {n_full}/{} expert layers ({:.2} GB: {:.2} on GPU 0, {:.2} on GPU 1) as contiguous slabs; {} experts, {} used, core {}..{} x{}, budget left {:.2} GB", + c.n_layer, slab_bytes as f64 / 1e9, per_part[0] as f64 / 1e9, per_part[1] as f64 / 1e9, + c.n_expert, c.n_used, c.loop_start, c.loop_end, c.loop_count, crate::deepseek::mat::budget_left() as f64 / 1e9); + } + // The layers without a slab: a pool of expert slots in what the budget has left, the CPU worker for the + // rest. Not under --fixed-experts, whose numerics must not depend on the placement, and not on a split. + let need: Vec = (0..c.n_layer).filter(|&ip| layers[ip].full_exps.is_none()).collect(); + let pool = (one_gpu && !need.is_empty() && cpu_share <= 0.0 && std::env::var_os("STRATA_FIXED_EXPERTS").is_none()).then(|| { + let runs = run_order(c).into_iter().filter(|r| need.contains(&r.1)).collect(); + let state = { + let g = dev::get().unwrap(); + let d = g.lock().unwrap(); + // The K/V rows to `KV_RESERVE` (or the rows it holds at load, `full`) and the full prefill chunk: + // a 16k prompt's growth finds its room. Past that `prepare` rebuilds the pool smaller, so a large + // `--ctx` does not take its whole K/V from the experts up front (#173). + state_bytes(&*d.parts[0].be, c, kw, m.max_ctx.min(full.max(KV_RESERVE)), pf_tokens(), m.output.rows, rank) + }; + super::pool::Pool::new(m, &mut dev::get().unwrap().lock().unwrap(), &need, runs, state) + }).flatten(); + // The expert cache takes what is left of the budget as experts miss: on one card it must leave the same + // floor, or after a few tokens the next CUDA graph (or the K/V growth) finds no room. + if one_gpu { + let state = state_bytes(&*dev::get().unwrap().lock().unwrap().parts[0].be, c, kw, m.max_ctx.min(full.max(KV_RESERVE)), pf_tokens(), m.output.rows, rank); + let mut d = dev::get().unwrap().lock().unwrap(); + let room = d.parts[0].be.mem_info().map_or(0, |m| m.0).saturating_sub(super::pool::pool_floor(384 << 20, crate::deepseek::mat::dev_margin(), state)); + let over = d.budget_left().saturating_sub(room); + d.parts[0].budget = d.parts[0].budget.saturating_sub(over); } - let all_full = layers.iter().all(|l| l.full_exps.is_some()); - Ok(Device { layers, loops, slots, out_query, out_norm, scr, sc_buf, pf: None, s, rank, all_full, graph_keys: [0; 2], synced: 0, ahead: false }) + let all_full = rem.is_none() && (0..c.n_layer).all(|ip| layers[ip].full_exps.is_some() || pool.as_ref().is_some_and(|p| p.layer(ip).is_some())); + let core = c.loop_end - c.loop_start; + let seg_graph = rem.is_some() && std::env::var_os("STRATA_DS_NO_SEG_GRAPH").is_none() + && layers.iter().all(|l| l.full_exps.is_some()) + && (c.loop_start..c.loop_end).all(|ip| layers[ip].full_exps.as_ref().is_some_and(|fe| fe.part == 0)) + && (c.loop_count * core) % 2 == 0; + Ok(Device { layers, loops, slots, out_query, out_norm, scr, sc_buf, pf: None, s, rank, all_full, rem, seg_graph, loop_nb: 0, pool, graph_keys: [0; 3], synced: 0, ahead: false }) })(); - made.inspect_err(|e| eprintln!("inkling2: no room in VRAM for the decode state ({e:#}); the tokens run as prompt chunks do")).ok() + made.inspect_err(|e| crate::say!("inkling2: no room in VRAM for the decode state ({e:#}); the tokens run as prompt chunks do")).ok() } /// The model starts over: nothing is shared with the host's rows. @@ -354,14 +527,14 @@ impl Device { let be = &*d.parts[0].be; let len = hists(c).1; let kw = c.n_head_kv * c.head_dim; - let swa_words = c.n_swa * be.kv_words(kw); + let (swa_k, swa_v) = (c.n_swa * be.kv_words(kw), c.n_swa * be.kv_words_v(kw)); let mut dev_hist = Vec::with_capacity(self.slots.len()); let mut dev_swa = Vec::with_capacity(self.slots.len()); for (il, ds) in self.slots.iter().enumerate() { dev_hist.push(be.get(&ds.hist, 0, len).expect("inkling2 save_checkpoint hist")); if c.swa[layer_of(c, il)] { - let k: Vec = be.get(&ds.k, 0, swa_words).expect("inkling2 save_checkpoint swa k"); - let v: Vec = be.get(&ds.v, 0, swa_words).expect("inkling2 save_checkpoint swa v"); + let k: Vec = be.get(&ds.k, 0, swa_k).expect("inkling2 save_checkpoint swa k"); + let v: Vec = be.get(&ds.v, 0, swa_v).expect("inkling2 save_checkpoint swa v"); dev_swa.push(Some((k, v))); } else { dev_swa.push(None); @@ -397,32 +570,82 @@ impl Device { let need = need_pos + 1; ensure!(need <= m.max_ctx, "context is limited to {} tokens", m.max_ctx); let mut d = dev::get().unwrap().lock().unwrap(); - let row_words = d.parts[0].be.kv_words(kw); + // The pooled layers, when the pool went for the K/V rows: it comes back smaller once they are in. + let mut rebuild: Option> = None; + let (kwk, kwv) = (d.parts[0].be.kv_words(kw), d.parts[0].be.kv_words_v(kw)); let full_cap = self.slots.iter().enumerate().find(|&(il, _)| !c.swa[layer_of(c, il)]).map(|(_, s)| s.cap); if let Some(cap) = full_cap && need > cap { - let mut new_cap = cap; - while new_cap < need { new_cap = (new_cap * 2).min(m.max_ctx); } + let new_cap = grown(need, m.max_ctx); let n = (0..c.n_slot()).filter(|&il| !c.swa[layer_of(c, il)]).count(); - room(&mut d, 4 * n * new_cap * row_words + sc_bytes(c, new_cap) + (128 << 20)); + // The margin is the one of `new`: the prompt scratch and the graphs of the reply come after this. + let bytes = 2 * n * new_cap * (kwk + kwv) + sc_bytes(c, new_cap) + (512 << 20); + room(&mut d, bytes); + // The expert cache was not enough: whole layers of experts go, the last loaded first. Their experts + // then run through the expert cache or on the CPU, which costs less than a model without its device state. + let free = |d: &dev::Dev| d.parts[0].be.mem_info().map_or(0, |m| m.0); + if free(&d) < bytes { + d.parts[0].be.sync()?; + rebuild = self.pool.as_ref().map(|p| p.layers.iter().enumerate().filter_map(|(ip, l)| l.as_ref().map(|_| ip)).collect()); + // Counted here: the driver may report the freed bytes late. + let mut short = bytes - free(&d); + // The expert pool goes first: its layers then run like the other layers without a slab. The budget + // falls by what the K/V rows need, so the expert cache can use the rest of the pool's room. + // `unpin_all` runs here, while the device is held: the pool's `Drop` cannot take the lock and would + // leave the slots pinned to VRAM that is freed a moment later. The bytes are counted from the pool's + // own slots, not from `mem_info` after the drop: the driver may report freed VRAM late (as the count + // above notes), and a late report made the layer loop below take expert layers it did not need to. + if let Some(mut p) = self.pool.take() { + let got = p.unpin_all(&mut d); + let freed = got.min(short); + d.parts[0].budget = d.parts[0].budget.saturating_sub(freed); + short -= freed; + drop(p); + // The pooled layers have no experts on the device now: `step_fast` would skip their FFN. + self.all_full = false; + } + let order: Vec = (c.loop_start..c.loop_end).chain(0..c.loop_start).chain(c.loop_end..c.n_layer).collect(); + for &ip in order.iter().rev() { + if short == 0 { break; } + if let Some(fe) = self.layers[ip].full_exps.take() { + // The budget falls too, so the expert cache does not take the room back. + d.parts[0].budget = d.parts[0].budget.saturating_sub(fe.gu.len() + fe.dn.len()); + short = short.saturating_sub(fe.gu.len() + fe.dn.len()); + self.all_full = false; + } + } + } } let be = &*d.parts[0].be; - let need_sc = sc_bytes(c, need); + // The score buffer follows the K/V rows: it is in the room made above, and a reply does not grow it every 64 tokens. + let need_sc = sc_bytes(c, full_cap.map_or(need, |cap| if need > cap { grown(need, m.max_ctx) } else { cap })); if self.sc_buf.len() < need_sc { be.sync()?; self.sc_buf = be.alloc(need_sc)?; } for (il, s) in self.slots.iter_mut().enumerate() { if c.swa[layer_of(c, il)] || need <= s.cap { continue; } - let mut new_cap = s.cap; - while new_cap < need { new_cap = (new_cap * 2).min(m.max_ctx); } - for b in [&mut s.k, &mut s.v] { - let new = be.alloc(2 * new_cap * row_words)?; + let new_cap = grown(need, m.max_ctx); + // K and V are separate buffers with their own word width; sizing both with their sum doubles f16. + for (b, words) in [(&mut s.k, kwk), (&mut s.v, kwv)] { + let new = be.alloc(2 * new_cap * words)?; be.dtod(b, 0, &new, 0, b.len())?; be.sync()?; // the copy reads the buffer that `*b = new` frees *b = new; } s.cap = new_cap; } + if let Some(need) = rebuild.filter(|n| !n.is_empty()) { + // The rows are in: the pool leaves room for the scratch only, and the next growth rebuilds it again. + // ponytail: a rebuild re-uploads the pool (a second or two); a pool that gives back part of its slots + // would skip that. + let cap = grown(need_pos + 1, m.max_ctx); + let state = state_bytes(&*d.parts[0].be, c, kw, 0, pf_tokens(), m.output.rows, self.rank); + let runs = run_order(c).into_iter().filter(|r| need.contains(&r.1)).collect(); + self.pool = super::pool::Pool::new(m, &mut d, &need, runs, state); + self.all_full = self.rem.is_none() && (0..c.n_layer).all(|ip| self.layers[ip].full_exps.is_some() + || self.pool.as_ref().is_some_and(|p| p.layer(ip).is_some())); + crate::say!("inkling2: the expert pool was rebuilt for {cap} K/V rows ({})", if self.pool.is_some() { "ok" } else { "no room" }); + } Ok(()) } @@ -458,7 +681,7 @@ impl Device { pub(super) fn to_host(&mut self, c: &Inkling2Config, layers: &[Layer], slots: &mut [Slot], pos: usize, max_ctx: usize) { if !self.ahead { return; } assert!(crate::cuda::kv_mode() == 0 || self.synced == pos, - "quantized KV cache (--kv q8/q4/q2) is only supported on the GPU path"); + "the card has no room for the K/V cache, and a quantized KV cache (--kv q8/q4/q2) cannot move to the CPU: run with a smaller --ctx"); let d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; let (hd, (at, len)) = (c.head_dim, hists(c)); @@ -484,12 +707,14 @@ impl Device { let (mut emb, mut cur) = (vec![0f32; n], vec![0f32; n]); m.tok_embd.row_into(tok as usize, &mut emb); rms_norm_w(&emb, &m.tok_norm, c.eps, &mut cur); - let d = dev::get().unwrap().lock().unwrap(); + let mut d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; - (|| -> Result<(Vec, u32)> { + let out = (|| -> Result<(Vec, u32)> { if !self.ahead { self.to_device(m, be, pos)?; } be.put(&cur, &self.scr, ((self.s.cur - o) / 4) as usize)?; be.put(&[pos as i32], &self.scr, ((self.s.pos - o) / 4) as usize)?; + let seq = self.pool.as_mut().map_or(0, |p| p.worker.begin()); + be.put(&[pos as i32, seq as i32], &self.scr, ((self.s.step - o) / 4) as usize)?; let key = { use std::hash::{Hash, Hasher}; let mut h = std::hash::DefaultHasher::new(); @@ -501,14 +726,146 @@ impl Device { // 17 MiB of device memory, and the backend stops recording at 32 of them). let last = std::mem::replace(&mut self.graph_keys[argmax as usize], key); if last != 0 && last != key { be.graph_drop(last)?; } - be.graph(key, &mut || { + if !self.seg_graph { + be.graph(key, &mut || { + let mut nb = 0usize; + for il in 0..c.loop_start { + self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, il)?; + } + be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?; + let n_pre = nb; + for pass in 0..c.loop_count { + let n_bank = nb.saturating_sub(n_pre + 1); + if pass > 0 { + let s = self.s; + if n_bank > 0 { + be.dtod(&self.scr, (s.blocks - o) as usize + 4 * (n_pre + 1) * n, &self.scr, (s.bank - o) as usize, 4 * n_bank * n)?; + } + be.dtod(&self.scr, (s.cur - o) as usize, &self.scr, (s.outb - o) as usize, 4 * n)?; + be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; + nb = n_pre; + } + for ip in c.loop_start..c.loop_end { + let il = if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start }; + if pass > 0 { + let s = self.s; + be.ink_mix(s.bank, n_bank, s.outb, self.loops[ip - c.loop_start].msg_query.addr(), 4, s.msg, n)?; + } + self.layer_attn(be, &d, m, il, ip, pass > 0, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, ip)?; + } + } + for il in c.loop_end..c.n_layer { + self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, il)?; + } + self.finish_logits(be, &d, m, nb)?; + if argmax { + be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?; + } + Ok(()) + })?; + } else { + // Local patch: layers 0..loop_start and loop_end.. launch one by one (their FFN may be on GPU 1, which needs + // the host between the attention and the experts); the loop between them is one graph. + let prof = std::env::var_os("STRATA_DS_PROF").is_some(); + let mut tt = std::time::Instant::now(); let mut nb = 0usize; for il in 0..c.loop_start { self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; - self.layer_ffn_gpu(be, m, il, il)?; + if !self.layer_ffn_remote(&d, m, il, il)? { self.layer_ffn_gpu(be, m, il, il)?; } } - be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?; + if prof { be.sync()?; m.lap(1, tt); tt = std::time::Instant::now(); } let n_pre = nb; + be.graph(key, &mut || { + let mut nb = n_pre; + be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?; + for pass in 0..c.loop_count { + let n_bank = nb.saturating_sub(n_pre + 1); + if pass > 0 { + let s = self.s; + if n_bank > 0 { + be.dtod(&self.scr, (s.blocks - o) as usize + 4 * (n_pre + 1) * n, &self.scr, (s.bank - o) as usize, 4 * n_bank * n)?; + } + be.dtod(&self.scr, (s.cur - o) as usize, &self.scr, (s.outb - o) as usize, 4 * n)?; + be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; + nb = n_pre; + } + for ip in c.loop_start..c.loop_end { + let il = if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start }; + if pass > 0 { + let s = self.s; + be.ink_mix(s.bank, n_bank, s.outb, self.loops[ip - c.loop_start].msg_query.addr(), 4, s.msg, n)?; + } + self.layer_attn(be, &d, m, il, ip, pass > 0, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, ip)?; + } + } + self.loop_nb = nb; + Ok(()) + })?; + if prof { be.sync()?; m.lap(2, tt); tt = std::time::Instant::now(); } + let mut nb = self.loop_nb; + for il in c.loop_end..c.n_layer { + self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; + if !self.layer_ffn_remote(&d, m, il, il)? { self.layer_ffn_gpu(be, m, il, il)?; } + } + if prof { be.sync()?; m.lap(3, tt); } + self.finish_logits(be, &d, m, nb)?; + if argmax { + be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?; + } + } + let out = if argmax { + (Vec::new(), be.get::(&self.scr, ((self.s.amax - o) / 4) as usize, 1)?[0] as u32) + } else { + (be.get(&self.scr, ((self.s.logits - o) / 4) as usize, c.n_vocab)?, 0) + }; + Ok(out) + })().expect("inkling2 device fast step"); + // The read waited for the token: the pool's slots are free to change. + if let Some(p) = &mut self.pool { + p.adapt(&mut d).expect("inkling2 expert pool"); + if std::env::var_os("STRATA_DS_PROF").is_some() && pos % 32 == 0 { + let [hit, miss, moved] = std::mem::take(&mut p.stats); + eprintln!("PROF pool at {pos}: {hit} expert uses in VRAM, {miss} on the CPU, {moved} copied in; CPU worker {:.1} ms a token", + p.worker.busy().as_secs_f64() * 1e3 / p.tokens.max(1) as f64); + } + } + out + } + + /// The core passes as one HIP/CUDA graph when every core layer has its experts in VRAM: about 1100 launches a + /// token that would otherwise each leave the card idle for a few microseconds. Recorded again every 64 + /// positions (the attention's row bound) and when a buffer moves. False: the caller runs the layers one by one. + fn core_graph(&mut self, m: &Inkling2Model, pos: usize, nb: &mut usize) -> bool { + let c = &m.cfg; + if !(c.loop_start..c.loop_end).all(|ip| self.layers[ip].full_exps.as_ref().is_some_and(|fe| fe.part == 0)) { return false; } + let (n, core, o) = (c.n_embd, c.loop_end - c.loop_start, self.scr.addr()); + let n_pre = *nb; + // The block count after the last pass: the passes after the first start again from the prelude's. + let nb_end = n_pre + (c.loop_start..c.loop_end).filter(|ip| ip % c.block_size == 0).count(); + let swaps = core * c.loop_count; + let d = dev::get().unwrap().lock().unwrap(); + let be = &*d.parts[0].be; + let key = { + use std::hash::{Hash, Hasher}; + let mut h = std::hash::DefaultHasher::new(); + (pos / 64, n_pre, self.sc_buf.addr(), self.s.cur).hash(&mut h); + for sl in &self.slots { sl.k.addr().hash(&mut h); } + 0x494E_4B43_0000_0000u64 | (h.finish() & 0x0000_FFFF_FFFF_FFFF) + }; + let last = std::mem::replace(&mut self.graph_keys[2], key); + let s0 = self.s; + (|| -> Result<()> { + if last != 0 && last != key { be.graph_drop(last)?; } + be.put(&[pos as i32], &self.scr, ((self.s.pos - o) / 4) as usize)?; + let mut ran = false; + be.graph(key, &mut || { + ran = true; + self.s = s0; + let mut nb = n_pre; for pass in 0..c.loop_count { let n_bank = nb.saturating_sub(n_pre + 1); if pass > 0 { @@ -530,23 +887,18 @@ impl Device { self.layer_ffn_gpu(be, m, il, ip)?; } } - for il in c.loop_end..c.n_layer { - self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; - self.layer_ffn_gpu(be, m, il, il)?; - } - self.finish_logits(be, &d, m, nb)?; - if argmax { - be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?; - } + anyhow::ensure!(nb == nb_end, "inkling2 core graph: {nb} blocks, expected {nb_end}"); Ok(()) })?; - if argmax { - let id = be.get::(&self.scr, ((self.s.amax - o) / 4) as usize, 1)?[0] as u32; - Ok((Vec::new(), id)) - } else { - Ok((be.get(&self.scr, ((self.s.logits - o) / 4) as usize, c.n_vocab)?, 0)) + // A replay runs nothing here: put the scratch roles where the layers would have left them. + if !ran { + self.s = s0; + if swaps % 2 == 1 { (self.s.cur, self.s.x) = (s0.x, s0.cur); } } - })().expect("inkling2 device fast step") + Ok(()) + })().unwrap_or_else(|e| panic!("inkling2 device core graph: {e:#}")); + *nb = nb_end; + true } fn step_layers(&mut self, m: &Inkling2Model, tok: u32) -> usize { @@ -568,6 +920,10 @@ impl Device { // Every pass of the core starts from the prelude output. copy(&*lock().parts[0].be, &self.scr, self.s.cur, self.s.prelude); let n_pre = nb; + if self.core_graph(m, pos, &mut nb) { + for il in c.loop_end..c.n_layer { self.layer(m, il, il, false, pos, &mut nb); } + return nb; + } for pass in 0..c.loop_count { // The bank of the previous pass: its blocks after the first core block, and its output. let n_bank = nb.saturating_sub(n_pre + 1); @@ -609,7 +965,7 @@ impl Device { let pos = m.toks.len(); assert!(pos < m.max_ctx, "context is limited to {} tokens", m.max_ctx); assert!((tok as usize) < m.tok_embd.rows, "token {tok} is outside the vocabulary"); - if self.all_full { + if self.all_full || self.seg_graph { let t = std::time::Instant::now(); let (logits, _) = self.step_fast(m, tok, false); m.lap(7, t); @@ -633,7 +989,7 @@ impl Device { let pos = m.toks.len(); assert!(pos < m.max_ctx, "context is limited to {} tokens", m.max_ctx); assert!((tok as usize) < m.tok_embd.rows, "token {tok} is outside the vocabulary"); - if self.all_full { + if self.all_full || self.seg_graph { let t = std::time::Instant::now(); let (_, id) = self.step_fast(m, tok, true); m.lap(7, t); @@ -659,12 +1015,15 @@ impl Device { be.sync()?; self.pf = None; } - let target = need_nt.max(256).min(256); + let target = need_nt.max(pf_tokens()); let mut tries = vec![target]; - if need_nt < target { tries.push(need_nt.max(128)); tries.push(need_nt.max(64)); tries.push(need_nt); } + // A smaller scratch when VRAM is short: halve down to 256 rows, then the old small sizes. + let mut cap = target / 2; + while cap >= 256 && cap >= need_nt { tries.push(cap); cap /= 2; } + if need_nt < 256 { tries.push(need_nt.max(128)); tries.push(need_nt.max(64)); tries.push(need_nt); } let mut last_err = None; for cap in tries { - match PrefillScratch::alloc(be, c, self.rank, vocab_rows, cap) { + match PrefillScratch::alloc(be, c, self.rank, vocab_rows, cap, false) { Ok(pf) => { self.pf = Some(pf); return Ok(()); } Err(e) => last_err = Some(e), } @@ -672,6 +1031,17 @@ impl Device { Err(last_err.unwrap()) } + /// GPU 1's prefill scratch for `need_nt` rows, when some layer's experts live there. + fn ensure_pf_remote(&mut self, d: &dev::Dev, c: &Inkling2Config, vocab_rows: usize, need_nt: usize) -> Result<()> { + let rank = self.rank; + let Some(r) = &mut self.rem else { return Ok(()) }; + if r.pf.as_ref().is_some_and(|pf| pf.max_nt >= need_nt) { return Ok(()); } + let be1 = &*d.parts[r.part].be; + if r.pf.is_some() { be1.sync()?; r.pf = None; } + r.pf = Some(PrefillScratch::alloc(be1, c, rank, vocab_rows, need_nt.max(pf_tokens()), true)?); + Ok(()) + } + /// Project a single corrected hidden vector `h_corr` (`[n_embd]`) through the target's LM head on GPU /// and return the argmax token ID (`0..c.n_vocab`). No softcap: `softcap * tanh(x / softcap)` keeps the /// order of the logits (two that differ by a few ulp may become equal), and the token is a draft that @@ -688,6 +1058,42 @@ impl Device { Ok(id) } + /// Project `nt` hidden vectors (`[nt, n_embd]`) through the target's LM head on GPU into `pf.logits_buf` + /// (`[nt, m.output.rows]`), keeping the logits on device for `markov_w2_argmax_gpu`. + pub(super) fn lm_head_batch_gpu(&mut self, m: &Inkling2Model, h_rows: &[f32], nt: usize) -> Result<()> { + let c = &m.cfg; + let vrows = m.output.rows; + let d = dev::get().context("no GPU device")?.lock().map_err(|_| anyhow::anyhow!("GPU device lock poisoned"))?; + let be = &*d.parts[0].be; + self.ensure_pf(be, c, vrows, nt)?; + let pf = self.pf.as_ref().unwrap(); + let o = pf.buf.addr(); + be.put(h_rows, &pf.buf, ((pf.p.hn - o) / 4) as usize)?; + be.gemvq(d.tensor(m.output.gpu.context("output.weight not on GPU")?), pf.p.hn, c.n_embd, 0, pf.logits_buf.addr(), vrows, nt)?; + Ok(()) + } + + /// Add low-rank `w2 @ latent + bias` onto `pf.logits_buf[step]` on GPU and return the argmax token ID. + pub(super) fn markov_w2_argmax_gpu( + &self, m: &Inkling2Model, w2: &crate::backend::GpuTensor, bias_addr: u64, bias_len: usize, latent: &[f32], step: usize, + ) -> Result { + let c = &m.cfg; + let vrows = m.output.rows; + let nv = c.n_vocab.min(w2.rows).min(bias_len); + ensure!(nv > 0, "markov_w2: empty vocabulary intersection"); + let pf = self.pf.as_ref().context("lm_head_batch_gpu not called")?; + let (s, o) = (self.s, self.scr.addr()); + let d = dev::get().context("no GPU device")?.lock().map_err(|_| anyhow::anyhow!("GPU device lock poisoned"))?; + let be = &*d.parts[0].be; + be.put(latent, &self.scr, ((s.hn - o) / 4) as usize)?; + be.gemvq(w2, s.hn, w2.cols, 0, s.logits, w2.rows, 1)?; + be.add(s.logits, pf.logits_buf.addr() + (step * vrows * 4) as u64, nv)?; + be.add(s.logits, bias_addr, nv)?; + be.argmax_rows(s.logits, nv, 1, s.amax)?; + let id = be.get::(&self.scr, ((s.amax - o) / 4) as usize, 1)?[0] as u32; + Ok(id) + } + fn record_dspark_visit(&self, visit: usize, cur_a: u64, nt: usize, n: usize) -> Result<()> { let Some(k) = DSPARK_VISITS.iter().position(|&v| v == visit) else { return Ok(()) }; let d = dev::get().unwrap().lock().unwrap(); @@ -699,6 +1105,15 @@ impl Device { /// Run a chunk of token IDs or raw vision embeddings (`Some(emb)` skips `tok_norm`, matching `inkling2.cpp::build_inputs`). /// When `capture_dspark` is true, also returns the 4 target layer hidden states `[5, 23, 41, 48]` (`[4][nt][n_embd]`). + /// Rows the next prompt chunks may have: `want`, or half of it down to 256 when VRAM has no room for that scratch. + pub(super) fn prefill_rows(&mut self, m: &Inkling2Model, want: usize) -> usize { + let d = dev::get().unwrap().lock().unwrap(); + let be = &*d.parts[0].be; + let mut cap = want; + while cap > 256 && self.ensure_pf(be, &m.cfg, m.output.rows, cap).is_err() { cap /= 2; } + cap + } + pub(super) fn prefill_chunk_seq( &mut self, m: &Inkling2Model, @@ -726,6 +1141,7 @@ impl Device { let d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; self.ensure_pf(be, c, m.output.rows, nt)?; + self.ensure_pf_remote(&d, c, m.output.rows, nt)?; if !self.ahead { self.to_device(m, be, pos0)?; } let pf = self.pf.as_ref().unwrap(); be.put(&cur_host, &pf.buf, 0)?; @@ -839,6 +1255,7 @@ impl Device { let d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; self.ensure_pf(be, c, m.output.rows, nt)?; + self.ensure_pf_remote(&d, c, m.output.rows, nt)?; if !self.ahead { self.to_device(m, be, pos0)?; } let pf = self.pf.as_ref().unwrap(); for (il, ds) in self.slots.iter().enumerate() { @@ -941,15 +1358,15 @@ impl Device { let d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; let pf = self.pf.as_ref().unwrap(); - let rb = 2 * be.kv_words(kw); + let (rk, rv) = (2 * be.kv_words(kw), 2 * be.kv_words_v(kw)); for (il, ds) in self.slots.iter().enumerate() { let ip = layer_of(c, il); if m.layers[ip].swa { - let swa_base = il * VERIFY_MAX * rb; + let (bk, bv) = (il * VERIFY_MAX * rk, il * VERIFY_MAX * rv); for t in (keep..nt).rev() { let at = (pos0 + t) % c.n_swa; - be.dtod(&pf.swa_kc_log, swa_base + t * rb, &ds.k, at * rb, rb)?; - be.dtod(&pf.swa_vc_log, swa_base + t * rb, &ds.v, at * rb, rb)?; + be.dtod(&pf.swa_kc_log, bk + t * rk, &ds.k, at * rk, rk)?; + be.dtod(&pf.swa_vc_log, bv + t * rv, &ds.v, at * rv, rv)?; } } let bak_base = il * 4 * h_total; @@ -993,7 +1410,7 @@ impl Device { pos0: usize, nt: usize, verify_mode: bool, nb: &mut usize, cur_a: &mut u64, x_a: &mut u64, ) -> Result<()> { let (c, ml, l, ds, rank) = (&m.cfg, &m.layers[ip], &self.layers[ip], &self.slots[il], self.rank); - let (n, hd, nh, nkv, nr, nc, nf, k) = (c.n_embd, c.head_dim, c.n_head, c.n_head_kv, c.n_rel, c.n_conv, c.n_ff_exp, c.n_used); + let (n, hd, nh, nkv, nr, nc) = (c.n_embd, c.head_dim, c.n_head, c.n_head_kv, c.n_rel, c.n_conv); let kw = nkv * hd; let lp = &self.loops[ip.clamp(c.loop_start, c.loop_end - 1) - c.loop_start]; let hist = |j: usize| ds.hist.addr() + f(hists(c).0[j]); @@ -1053,23 +1470,23 @@ impl Device { be.ink_conv_batch(p.k, l.convs[0].addr(), taps[0], hist(0), p.k2, kw, nc, hd, nt)?; be.ink_conv_batch(p.v, l.convs[1].addr(), taps[1], hist(1), p.v2, kw, nc, hd, nt)?; let log_alpha = if ml.swa { 0.0 } else { c.log_alpha }; - let rb = 2 * be.kv_words(kw); + let (rk, rv) = (2 * be.kv_words(kw), 2 * be.kv_words_v(kw)); be.ink_clip_n(p.q, l.q_clip.addr(), hd, nh, nt, c.qk_clip, 0.0, 1.0, 0, 0, 1, pos0, log_alpha, c.log_floor)?; be.ink_clip_n(p.r, l.rel_clip.addr(), nr, nh, nt, c.rel_clip, 0.0, 1.0, 0, 0, 1, pos0, log_alpha, c.log_floor)?; if verify_mode { - let swa_base = il * VERIFY_MAX * rb; + let (bk, bv) = (il * VERIFY_MAX * rk, il * VERIFY_MAX * rv); if !ml.swa { be.ink_clip_n(p.k2, 0, hd, nkv, nt, c.qk_clip, 0.0, 1.0, ds.k.addr(), pos0, ds.cap, 0, 0.0, 1.0)?; - be.ink_clip_n(p.v2, 0, hd, nkv, nt, 0.0, c.eps, 1.0, ds.v.addr(), pos0, ds.cap, 0, 0.0, 1.0)?; + be.ink_clip_n_v(p.v2, 0, hd, nkv, nt, 0.0, c.eps, 1.0, ds.v.addr(), pos0, ds.cap, 0, 0.0, 1.0)?; } for t in 0..nt { let pos = pos0 + t; let (rows, at) = if ml.swa { let at = pos % c.n_swa; - be.dtod(&ds.k, at * rb, &pf.swa_kc_log, swa_base + t * rb, rb)?; - be.dtod(&ds.v, at * rb, &pf.swa_vc_log, swa_base + t * rb, rb)?; + be.dtod(&ds.k, at * rk, &pf.swa_kc_log, bk + t * rk, rk)?; + be.dtod(&ds.v, at * rv, &pf.swa_vc_log, bv + t * rv, rv)?; be.ink_clip_n(p.k2 + f(t * kw), 0, hd, nkv, 1, c.qk_clip, 0.0, 1.0, ds.k.addr(), at, c.n_swa, 0, 0.0, 1.0)?; - be.ink_clip_n(p.v2 + f(t * kw), 0, hd, nkv, 1, 0.0, c.eps, 1.0, ds.v.addr(), at, c.n_swa, 0, 0.0, 1.0)?; + be.ink_clip_n_v(p.v2 + f(t * kw), 0, hd, nkv, 1, 0.0, c.eps, 1.0, ds.v.addr(), at, c.n_swa, 0, 0.0, 1.0)?; ((pos + 1).min(c.n_swa), at) } else { (pos + 1, pos) @@ -1087,7 +1504,7 @@ impl Device { (ds.k.addr(), ds.v.addr(), pos0, ds.cap) }; be.ink_clip_n(p.k2, 0, hd, nkv, nt, c.qk_clip, 0.0, 1.0, kd, at0, kvr, 0, 0.0, 1.0)?; - be.ink_clip_n(p.v2, 0, hd, nkv, nt, 0.0, c.eps, 1.0, vd, at0, kvr, 0, 0.0, 1.0)?; + be.ink_clip_n_v(p.v2, 0, hd, nkv, nt, 0.0, c.eps, 1.0, vd, at0, kvr, 0, 0.0, 1.0)?; let (kc_new, vc_new, ring, win) = if ml.swa { (kd, vd, c.n_swa, c.n_swa) } else { @@ -1100,11 +1517,11 @@ impl Device { let src0 = nt - keep; let dst0 = (pos0 + src0) % c.n_swa; let first = keep.min(c.n_swa - dst0); - be.dtod(&pf.kc_tmp, src0 * rb, &ds.k, dst0 * rb, first * rb)?; - be.dtod(&pf.vc_tmp, src0 * rb, &ds.v, dst0 * rb, first * rb)?; + be.dtod(&pf.kc_tmp, src0 * rk, &ds.k, dst0 * rk, first * rk)?; + be.dtod(&pf.vc_tmp, src0 * rv, &ds.v, dst0 * rv, first * rv)?; if first < keep { - be.dtod(&pf.kc_tmp, (src0 + first) * rb, &ds.k, 0, (keep - first) * rb)?; - be.dtod(&pf.vc_tmp, (src0 + first) * rb, &ds.v, 0, (keep - first) * rb)?; + be.dtod(&pf.kc_tmp, (src0 + first) * rk, &ds.k, 0, (keep - first) * rk)?; + be.dtod(&pf.vc_tmp, (src0 + first) * rv, &ds.v, 0, (keep - first) * rv)?; } } } @@ -1127,7 +1544,7 @@ impl Device { h = p.h2; } if let Some(fe) = &l.full_exps { - let use_gemm = !small && fe.gu_cols % 64 == 0 && fe.dn_cols % 64 == 0; + let use_gemm = (!small || fe.part != 0) && fe.gu_cols % 64 == 0 && fe.dn_cols % 64 == 0; if use_gemm || fe.gu_ty.float_x() { be.rms_norm(h, n, l.ffn_norm.addr(), p.hn, n, n, nt, c.eps)?; } else { @@ -1135,86 +1552,24 @@ impl Device { } m.lap(0, t_prep); let t_gpu = std::time::Instant::now(); - Self::proj_n(be, &fe.gate_inp, small, nt, p.hn, 0, p.rlogits, 0)?; - let gu_sc = fe.gu_scale.as_ref().map_or(0, |b| b.addr()); - let dn_sc = fe.dn_scale.as_ref().map_or(0, |b| b.addr()); - let gsc_out = if gu_sc != 0 { p.gsc } else { 0 }; - be.ink_route(p.rlogits, fe.bias.addr(), p.ids, p.wts, gu_sc, dn_sc, gsc_out, c.n_expert, k, c.exp_scale, nt)?; - if !use_gemm { - // Process up to 16 tokens per moe_gemv batch so zero host sync is needed (exact decode speed for nt <= 16). - for tok0 in (0..nt).step_by(16) { - let bt = (nt - tok0).min(16); - let np = bt * k; - let xh_tok_floats = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; - let ids_a = p.ids + (4 * tok0 * k) as u64; - let wts_a = p.wts + f(tok0 * k); - let gsc_a = if gu_sc != 0 { p.gsc + f(tok0 * k) } else { 0 }; - let hn_a = p.hn + f(tok0 * n); - let xh_a = p.xh + f(tok0 * xh_tok_floats); - let y_a = p.y; - let d_a = p.d; - let acc_a = pf.acc_buf.addr() + f(tok0 * n); - be.moe_gemv(fe.gu_ty, fe.gu_rows, fe.gu_cols, fe.gu.addr(), fe.gu_stride, ids_a, np, hn_a, n, k, y_a, None, xh_a)?; - if fe.dn_ty.float_x() || nf % 32 != 0 { - be.situ(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; - be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, 0)?; - } else { - be.situ_q(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta, p.xq)?; - be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, p.xq)?; - } - be.ink_ffn_sum_n(acc_a, d_a, wts_a, k, n, bt, 0)?; - } + if fe.part == 0 { + Self::pf_ffn_core(be, m, ip, fe, pf, nt, small, use_gemm)?; } else { - use crate::backend::GEMM_BM; - let ids: Vec = be.get(&pf.buf, ((p.ids - buf_o) / 4) as usize, nt * k)?; - let mut by_e: Vec> = vec![vec![]; c.n_expert]; - for (t, row) in ids.chunks_exact(k).enumerate() { - for (j, &e) in row.iter().enumerate() { by_e[e as usize].push((t, j)); } - } - let np = nt * k; - let mut tiles_gu: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); - let mut tiles_dn: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); - let mut xrow: Vec = Vec::with_capacity(np); - let mut inv: Vec = vec![0i32; nt * k]; - let mut gsc_rows: Vec = if ml.gu_scale.is_empty() { Vec::new() } else { Vec::with_capacity(np) }; - let mut m0 = 0usize; - for e in 0..c.n_expert { - if by_e[e].is_empty() { continue; } - let wg = fe.gu.addr() + (e * fe.gu_stride) as u64; - let wd = fe.dn.addr() + (e * fe.dn_stride) as u64; - for at in (0..by_e[e].len()).step_by(GEMM_BM) { - let cnt = GEMM_BM.min(by_e[e].len() - at) as u64; - tiles_gu.extend([wg, (m0 + at) as u64 | (cnt << 32)]); - tiles_dn.extend([wd, (m0 + at) as u64 | (cnt << 32)]); - } - for &(t, j) in &by_e[e] { - inv[t * k + j] = xrow.len() as i32; - xrow.push(t as i32); - if !ml.gu_scale.is_empty() { gsc_rows.push(ml.gu_scale[e]); } - } - m0 += by_e[e].len(); + // Experts on GPU 1: the normed rows cross over, the experts run there, the sum comes back. + let r = self.rem.as_ref().ok_or_else(|| anyhow::anyhow!("experts on GPU 1 without a scratch there"))?; + let pf1 = r.pf.as_ref().ok_or_else(|| anyhow::anyhow!("no prefill scratch on GPU 1"))?; + let be1 = &*d.parts[r.part].be; + let (o0, o1) = (buf_o, pf1.buf.addr()); + let hn: Vec = be.get(&pf.buf, ((p.hn - o0) / 4) as usize, nt * n)?; + be1.put(&hn, &pf1.buf, ((pf1.p.hn - o1) / 4) as usize)?; + if !use_gemm && !fe.gu_ty.float_x() { + let xw = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + let xh: Vec = be.get(&pf.buf, ((p.xh - o0) / 4) as usize, nt * xw)?; + be1.put(&xh, &pf1.buf, ((pf1.p.xh - o1) / 4) as usize)?; } - let n_tiles = tiles_gu.len() / 2; - let dn_off = 8 * tiles_gu.len(); - let xr_off = dn_off + 8 * tiles_dn.len(); - let inv_off = xr_off + 4 * np; - ensure!(inv_off + 4 * nt * k <= pf.meta.len(), "prefill meta overflow"); - be.put(&tiles_gu, &pf.meta, 0)?; - be.put(&tiles_dn, &pf.meta, dn_off / 8)?; - be.put(&xrow, &pf.meta, xr_off / 4)?; - be.put(&inv, &pf.meta, inv_off / 4)?; - let gsc_a = if !gsc_rows.is_empty() { - be.put(&gsc_rows, &pf.buf, ((p.gsc - buf_o) / 4) as usize)?; - p.gsc - } else { - 0 - }; - let ma = pf.meta.addr(); - be.gemm(fe.gu_ty, fe.gu_rows, fe.gu_cols, ma, n_tiles, p.hn, n, nt, ma + xr_off as u64, p.y, 2 * nf, 0)?; - be.situ(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; - be.gemm(fe.dn_ty, fe.dn_rows, fe.dn_cols, ma + dn_off as u64, n_tiles, p.y, 2 * nf, np, 0, p.d, n, 0)?; - be.memset(&pf.acc_buf)?; - be.moe_combine_seq(pf.acc_buf.addr(), p.d, p.wts, ma + inv_off as u64, k, 0, 0, n, nt)?; + Self::pf_ffn_core(be1, m, ip, fe, pf1, nt, small, use_gemm)?; + let acc: Vec = be1.get(&pf1.acc_buf, 0, nt * n)?; + be.put(&acc, &pf.acc_buf, 0)?; } if verify_mode { be.dtod(&pf.acc_buf, 0, &pf.conv_log, log_base + 4 * VERIFY_MAX * (2 * kw + n), 4 * nt * n)?; @@ -1223,6 +1578,19 @@ impl Device { be.add(*x_a, p.acc2, nt * n)?; m.lap(5, t_gpu); true + } else if self.pool.as_ref().is_some_and(|q| q.has_room(ip)) { + m.lap(0, t_prep); + let t_gpu = std::time::Instant::now(); + let on = self.prefill_ffn_pool(be, m, ip, nt, small, h)?; + if on { + if verify_mode { + be.dtod(&pf.acc_buf, 0, &pf.conv_log, log_base + 4 * VERIFY_MAX * (2 * kw + n), 4 * nt * n)?; + } + be.ink_conv_batch(pf.acc_buf.addr(), l.convs[3].addr(), 0, hist(3), p.acc2, n, nc, hd, nt)?; + be.add(*x_a, p.acc2, nt * n)?; + m.lap(5, t_gpu); + } + on } else { be.rms_norm(h, n, l.ffn_norm.addr(), p.hn, n, n, nt, c.eps)?; m.lap(0, t_prep); @@ -1250,6 +1618,231 @@ impl Device { Ok(()) } + /// The routed experts of a prompt chunk on the GPU `be` runs on: from the normed rows in `pf.p.hn` (and, below the + /// GEMM size, their quantized copy in `pf.p.xh`) to the weighted sum in `pf.acc_buf`. + #[allow(clippy::too_many_arguments)] + fn pf_ffn_core(be: &dyn Backend, m: &Inkling2Model, ip: usize, fe: &FullExps, pf: &PrefillScratch, nt: usize, small: bool, use_gemm: bool) -> Result<()> { + let (c, ml) = (&m.cfg, &m.layers[ip]); + let (n, nf, k) = (c.n_embd, c.n_ff_exp, c.n_used); + let (p, buf_o) = (pf.p, pf.buf.addr()); + Self::proj_n(be, &fe.gate_inp, small, nt, p.hn, 0, p.rlogits, 0)?; + let gu_sc = fe.gu_scale.as_ref().map_or(0, |b| b.addr()); + let dn_sc = fe.dn_scale.as_ref().map_or(0, |b| b.addr()); + let gsc_out = if gu_sc != 0 { p.gsc } else { 0 }; + be.ink_route(p.rlogits, fe.bias.addr(), p.ids, p.wts, gu_sc, dn_sc, gsc_out, c.n_expert, k, c.exp_scale, nt)?; + if !use_gemm { + // Process up to 16 tokens per moe_gemv batch so zero host sync is needed (exact decode speed for nt <= 16). + for tok0 in (0..nt).step_by(16) { + let bt = (nt - tok0).min(16); + let np = bt * k; + let xh_tok_floats = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + let ids_a = p.ids + (4 * tok0 * k) as u64; + let wts_a = p.wts + f(tok0 * k); + let gsc_a = if gu_sc != 0 { p.gsc + f(tok0 * k) } else { 0 }; + let hn_a = p.hn + f(tok0 * n); + let xh_a = p.xh + f(tok0 * xh_tok_floats); + let y_a = p.y; + let d_a = p.d; + let acc_a = pf.acc_buf.addr() + f(tok0 * n); + be.moe_gemv(fe.gu_ty, fe.gu_rows, fe.gu_cols, fe.gu.addr(), fe.gu_stride, ids_a, np, hn_a, n, k, y_a, None, xh_a)?; + if fe.dn_ty.float_x() || nf % 32 != 0 { + be.situ(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, 0)?; + } else { + be.situ_q(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta, p.xq)?; + be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, p.xq)?; + } + be.ink_ffn_sum_n(acc_a, d_a, wts_a, k, n, bt, 0)?; + } + } else { + use crate::backend::GEMM_BM; + let ids: Vec = be.get(&pf.buf, ((p.ids - buf_o) / 4) as usize, nt * k)?; + let mut by_e: Vec> = vec![vec![]; c.n_expert]; + for (t, row) in ids.chunks_exact(k).enumerate() { + for (j, &e) in row.iter().enumerate() { by_e[e as usize].push((t, j)); } + } + let np = nt * k; + let mut tiles_gu: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); + let mut tiles_dn: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); + let mut xrow: Vec = Vec::with_capacity(np); + let mut inv: Vec = vec![0i32; nt * k]; + let mut gsc_rows: Vec = if ml.gu_scale.is_empty() { Vec::new() } else { Vec::with_capacity(np) }; + let mut m0 = 0usize; + for e in 0..c.n_expert { + if by_e[e].is_empty() { continue; } + let wg = fe.gu.addr() + (e * fe.gu_stride) as u64; + let wd = fe.dn.addr() + (e * fe.dn_stride) as u64; + for at in (0..by_e[e].len()).step_by(GEMM_BM) { + let cnt = GEMM_BM.min(by_e[e].len() - at) as u64; + tiles_gu.extend([wg, (m0 + at) as u64 | (cnt << 32)]); + tiles_dn.extend([wd, (m0 + at) as u64 | (cnt << 32)]); + } + for &(t, j) in &by_e[e] { + inv[t * k + j] = xrow.len() as i32; + xrow.push(t as i32); + if !ml.gu_scale.is_empty() { gsc_rows.push(ml.gu_scale[e]); } + } + m0 += by_e[e].len(); + } + let n_tiles = tiles_gu.len() / 2; + let dn_off = 8 * tiles_gu.len(); + let xr_off = dn_off + 8 * tiles_dn.len(); + let inv_off = xr_off + 4 * np; + ensure!(inv_off + 4 * nt * k <= pf.meta.len(), "prefill meta overflow"); + be.put(&tiles_gu, &pf.meta, 0)?; + be.put(&tiles_dn, &pf.meta, dn_off / 8)?; + be.put(&xrow, &pf.meta, xr_off / 4)?; + be.put(&inv, &pf.meta, inv_off / 4)?; + let gsc_a = if !gsc_rows.is_empty() { + be.put(&gsc_rows, &pf.buf, ((p.gsc - buf_o) / 4) as usize)?; + p.gsc + } else { + 0 + }; + let ma = pf.meta.addr(); + be.gemm(fe.gu_ty, fe.gu_rows, fe.gu_cols, ma, n_tiles, p.hn, n, nt, ma + xr_off as u64, p.y, 2 * nf, 0)?; + be.situ(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.gemm(fe.dn_ty, fe.dn_rows, fe.dn_cols, ma + dn_off as u64, n_tiles, p.y, 2 * nf, np, 0, p.d, n, 0)?; + be.memset(&pf.acc_buf)?; + be.moe_combine_seq(pf.acc_buf.addr(), p.d, p.wts, ma + inv_off as u64, k, 0, 0, n, nt)?; + } + Ok(()) + } + + /// The routed experts of a prompt chunk in a pool layer: the pool's slots, and the chunk's other experts copied + /// into the staging slots in rounds of `pool::STAGE`, with a wait before each refill. The experts run in the + /// order of their rounds, so a round's rows are one block. False: a small batch with more misses than staging + /// slots, left to the host path (`p.hn` holds the normed input). + fn prefill_ffn_pool(&self, be: &dyn Backend, m: &Inkling2Model, ip: usize, nt: usize, small: bool, h: u64) -> Result { + use super::pool::STAGE; + let (c, ml, l) = (&m.cfg, &m.layers[ip], &self.layers[ip]); + let pool = self.pool.as_ref().unwrap(); + let pl = pool.layer(ip).unwrap(); + let pf = self.pf.as_ref().unwrap(); + let (p, buf_o) = (pf.p, pf.buf.addr()); + let (n, nf, k) = (c.n_embd, c.n_ff_exp, c.n_used); + let ((gt, gr, gc), (dt, dr, dc)) = (pl.gu, pl.dn); + let (base, stride) = pool.base(pl); + let (dn_base, st0) = (base + pl.dn_off as u64, pool.stage(pl)); + let use_gemm = !small && gc % 64 == 0 && dc % 64 == 0; + if use_gemm || gt.float_x() { + be.rms_norm(h, n, l.ffn_norm.addr(), p.hn, n, n, nt, c.eps)?; + } else { + be.rms_norm_q(h, n, l.ffn_norm.addr(), p.hn, n, n, nt, c.eps, p.xh, 0)?; + } + Self::proj_n(be, &pl.gate_inp, small, nt, p.hn, 0, p.rlogits, 0)?; + let gu_sc = pl.gu_scale.as_ref().map_or(0, |b| b.addr()); + let dn_sc = pl.dn_scale.as_ref().map_or(0, |b| b.addr()); + be.ink_route(p.rlogits, pl.bias.addr(), p.ids, p.wts, gu_sc, dn_sc, if gu_sc != 0 { p.gsc } else { 0 }, c.n_expert, k, c.exp_scale, nt)?; + let ids: Vec = be.get(&pf.buf, ((p.ids - buf_o) / 4) as usize, nt * k)?; + let mut by_e: Vec> = vec![vec![]; c.n_expert]; + for (t, row) in ids.chunks_exact(k).enumerate() { + for (j, &e) in row.iter().enumerate() { by_e[e as usize].push((t, j)); } + } + let mut slot = vec![-1i32; c.n_expert]; + let (mut resident, mut missing) = (vec![], vec![]); + for e in (0..c.n_expert).filter(|&e| !by_e[e].is_empty()) { + slot[e] = pool.slot(ip, e); + if slot[e] >= 0 { resident.push(e) } else { missing.push(e) } + } + // Staging copies go on the copy queue (`Backend::htod_side`) into `st0 + first..`, and return its mark. The + // copy queue first waits for the kernels queued so far, which may still read those slots (an earlier round or + // layer run). + // `early`: the copy queue waits for the point the kernel queue had reached when the routing came back, not for + // the kernels queued since (the resident experts' GEMMs, which do not read the staging slots): the first two + // rounds then copy while those run instead of after them. + // Only the gemm path with misses stages anything, so only then is the mark taken. + let early_mark = if use_gemm && !missing.is_empty() { be.main_mark()? } else { 0 }; + let stage = |round: &[usize], first: usize, slot: &mut [i32], early: bool| -> Result { + be.side_waits(if early { early_mark } else { be.main_mark()? })?; + for (j, &e) in round.iter().enumerate() { + pool.upload_on(be, ip, e, st0 + first + j, true)?; + slot[e] = (st0 + first + j) as i32; + } + be.side_mark() + }; + if !use_gemm { + if missing.len() > STAGE { return Ok(false); } + if !missing.is_empty() { let m = stage(&missing, 0, &mut slot, false)?; be.main_waits(m)?; } + let sids: Vec = ids.iter().map(|&e| slot[e as usize]).collect(); + be.put(&sids, &pf.buf, ((p.ids - buf_o) / 4) as usize)?; + let xh_tok_floats = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + for tok0 in (0..nt).step_by(16) { + let (bt, ids_a) = ((nt - tok0).min(16), p.ids + (4 * tok0 * k) as u64); + let np = bt * k; + let gsc_a = if gu_sc != 0 { p.gsc + f(tok0 * k) } else { 0 }; + let (hn_a, xh_a, acc_a) = (p.hn + f(tok0 * n), p.xh + f(tok0 * xh_tok_floats), pf.acc_buf.addr() + f(tok0 * n)); + be.moe_gemv(gt, gr, gc, base, stride, ids_a, np, hn_a, n, k, p.y, None, xh_a)?; + if dt.float_x() || nf % 32 != 0 { + be.situ(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.moe_gemv(dt, dr, dc, dn_base, stride, ids_a, np, p.y, 2 * nf, 1, p.d, None, 0)?; + } else { + be.situ_q(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta, p.xq)?; + be.moe_gemv(dt, dr, dc, dn_base, stride, ids_a, np, p.y, 2 * nf, 1, p.d, None, p.xq)?; + } + be.ink_ffn_sum_n(acc_a, p.d, p.wts + f(tok0 * k), k, n, bt, 0)?; + } + return Ok(true); + } + use crate::backend::GEMM_BM; + // Groups: the residents, then one per round of misses. The rounds alternate between the two halves of the + // staging slots: while the kernels run on one half, the copy queue fills the other, and the residents run + // while the first two rounds copy in. + const HALF: usize = STAGE / 2; + let mut groups: Vec> = vec![resident]; + groups.extend(missing.chunks(HALF).map(|r| r.to_vec())); + let rounds = groups.len() - 1; + let mut ready = vec![0usize; rounds]; + let np = nt * k; + let (mut xrow, mut inv, mut gsc_rows) = (Vec::with_capacity(np), vec![0i32; np], Vec::with_capacity(np)); + let mut rows = vec![(0usize, 0usize); c.n_expert]; + for &e in groups.iter().flatten() { + rows[e] = (xrow.len(), by_e[e].len()); + for &(t, j) in &by_e[e] { + inv[t * k + j] = xrow.len() as i32; + xrow.push(t as i32); + if !ml.gu_scale.is_empty() { gsc_rows.push(ml.gu_scale[e]); } + } + } + let max_tiles = (0..c.n_expert).map(|e| by_e[e].len().div_ceil(GEMM_BM)).sum::(); + let dn_off = 16 * max_tiles; + let xr_off = 2 * dn_off; + let inv_off = xr_off + 4 * np; + ensure!(inv_off + 4 * np <= pf.meta.len(), "prefill meta overflow"); + be.put(&xrow, &pf.meta, xr_off / 4)?; + be.put(&inv, &pf.meta, inv_off / 4)?; + let gsc_a = if !gsc_rows.is_empty() { be.put(&gsc_rows, &pf.buf, ((p.gsc - buf_o) / 4) as usize)?; p.gsc } else { 0 }; + let ma = pf.meta.addr(); + for (gi, g) in groups.iter().enumerate() { + // The first two rounds are staged once the residents' kernels are queued: the host's part of a copy (into + // the pinned ring) then runs while the card works. + if gi == 1 { for i in 0..rounds.min(2) { ready[i] = stage(&groups[1 + i], (i % 2) * HALF, &mut slot, true)?; } } + if gi > 0 { be.main_waits(ready[gi - 1])?; } + let (mut tg, mut td) = (vec![], vec![]); + for &e in g { + let (m0, cnt) = rows[e]; + let at = slot[e] as u64 * stride as u64; + for a in (0..cnt).step_by(GEMM_BM) { + let tag = (m0 + a) as u64 | ((GEMM_BM.min(cnt - a) as u64) << 32); + tg.extend([base + at, tag]); + td.extend([dn_base + at, tag]); + } + } + if tg.is_empty() { continue; } + be.put(&tg, &pf.meta, 0)?; + be.put(&td, &pf.meta, dn_off / 8)?; + let (r0, r1) = (rows[g[0]].0, g.iter().map(|&e| rows[e].0 + rows[e].1).max().unwrap()); + be.gemm(gt, gr, gc, ma, tg.len() / 2, p.hn, n, nt, ma + xr_off as u64, p.y, 2 * nf, 0)?; + be.situ(p.y + f(r0 * 2 * nf), nf, r1 - r0, if gsc_a != 0 { gsc_a + f(r0) } else { 0 }, c.situ_beta, c.situ_linear_beta)?; + be.gemm(dt, dr, dc, ma + dn_off as u64, td.len() / 2, p.y, 2 * nf, np, 0, p.d, n, 0)?; + // Round r + 2 takes this round's half once the kernels above are done with it (`stage` waits for them). + if gi > 0 && gi + 1 < rounds { ready[gi + 1] = stage(&groups[gi + 2], ((gi - 1) % 2) * HALF, &mut slot, false)?; } + } + be.memset(&pf.acc_buf)?; + be.moe_combine_seq(pf.acc_buf.addr(), p.d, p.wts, ma + inv_off as u64, k, 0, 0, n, nt)?; + Ok(true) + } + fn layer_attn(&self, be: &dyn Backend, d: &dev::Dev, m: &Inkling2Model, il: usize, ip: usize, msgs: bool, pos: usize, graph: bool, nb: &mut usize) -> Result<()> { let (c, ml, l, ds, s, rank) = (&m.cfg, &m.layers[ip], &self.layers[ip], &self.slots[il], self.s, self.rank); let (n, hd, nh, nkv, nr, nc) = (c.n_embd, c.head_dim, c.n_head, c.n_head_kv, c.n_rel, c.n_conv); @@ -1310,7 +1903,7 @@ impl Device { be.batch(&mut || { be.ink_clip_pos(s.q, l.q_clip.addr(), hd, nh, 1, c.qk_clip, 0.0, 1.0, 0, 1, s.pos, log_alpha, c.log_floor)?; be.ink_clip_pos(s.k, 0, hd, nkv, 1, c.qk_clip, 0.0, 1.0, ds.k.addr(), ring, s.pos, 0.0, 1.0)?; - be.ink_clip_pos(s.v, 0, hd, nkv, 1, 0.0, c.eps, 1.0, ds.v.addr(), ring, s.pos, 0.0, 1.0)?; + be.ink_clip_pos_v(s.v, 0, hd, nkv, 1, 0.0, c.eps, 1.0, ds.v.addr(), ring, s.pos, 0.0, 1.0)?; be.ink_clip_pos(s.r, l.rel_clip.addr(), nr, nh, 1, c.rel_clip, 0.0, 1.0, 0, 1, s.pos, log_alpha, c.log_floor) })?; be.ink_attn_pos(s.q, s.r, s.sink, s.og, ds.k.addr(), ds.v.addr(), l.rel_bias.addr(), self.sc_buf.addr(), s.att, max_rows, ring, s.pos, nh, nkv, hd, nr, c.rel_extent)?; @@ -1319,7 +1912,7 @@ impl Device { be.batch(&mut || { be.ink_clip_n(s.q, l.q_clip.addr(), hd, nh, 1, c.qk_clip, 0.0, 1.0, 0, 0, 1, pos, log_alpha, c.log_floor)?; be.ink_clip_n(s.k, 0, hd, nkv, 1, c.qk_clip, 0.0, 1.0, ds.k.addr(), at, ring, 0, 0.0, 1.0)?; - be.ink_clip_n(s.v, 0, hd, nkv, 1, 0.0, c.eps, 1.0, ds.v.addr(), at, ring, 0, 0.0, 1.0)?; + be.ink_clip_n_v(s.v, 0, hd, nkv, 1, 0.0, c.eps, 1.0, ds.v.addr(), at, ring, 0, 0.0, 1.0)?; be.ink_clip_n(s.r, l.rel_clip.addr(), nr, nh, 1, c.rel_clip, 0.0, 1.0, 0, 0, 1, pos, log_alpha, c.log_floor) })?; be.ink_attn(s.q, s.r, s.sink, s.og, ds.k.addr(), ds.v.addr(), l.rel_bias.addr(), self.sc_buf.addr(), s.att, rows, at, nh, nkv, hd, nr, c.rel_extent)?; @@ -1343,11 +1936,10 @@ impl Device { be.rms_norm_q(h, n, l.ffn_norm.addr(), s.hn, n, n, 1, c.eps, s.xh, 0) } - fn layer_ffn_gpu(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result { - let Some(fe) = &self.layers[ip].full_exps else { return Ok(false) }; - let (c, ds, s) = (&m.cfg, &self.slots[il], self.s); - let (n, hd, nc, nf, k) = (c.n_embd, c.head_dim, c.n_conv, c.n_ff_exp, c.n_used); - let hist3 = ds.hist.addr() + f(hists(c).0[3]); + /// The routed experts of one token on the GPU `be` runs on, from the normed input in `s.hn` (and its quantized + /// copy `s.xh`) to the weighted sum in `s.acc`. All of it stays on that device. + fn ffn_core(be: &dyn Backend, c: &Inkling2Config, s: Scratch, fe: &FullExps) -> Result<()> { + let (n, nf, k) = (c.n_embd, c.n_ff_exp, c.n_used); be.gemv(&fe.gate_inp, s.hn, s.rlogits)?; let gu_sc = fe.gu_scale.as_ref().map_or(0, |b| b.addr()); let dn_sc = fe.dn_scale.as_ref().map_or(0, |b| b.addr()); @@ -1361,7 +1953,74 @@ impl Device { be.situ_q(s.y, nf, k, gsc_a, c.situ_beta, c.situ_linear_beta, s.xq)?; be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, s.ids, k, s.y, 2 * nf, 1, s.d, None, s.xq)?; } - be.ink_ffn_sum(s.acc, s.d, s.wc, k, n, 0)?; + be.ink_ffn_sum(s.acc, s.d, s.wc, k, n, 0) + } + + /// What follows the experts of a layer run: the short convolution, the residual add, and the swap of the streams. + fn ffn_tail(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result<()> { + let (c, ds, s) = (&m.cfg, &self.slots[il], self.s); + let (n, hd, nc) = (c.n_embd, c.head_dim, c.n_conv); + let hist3 = ds.hist.addr() + f(hists(c).0[3]); + be.ink_conv(s.acc, self.layers[ip].convs[3].addr(), 0, hist3, s.acc, n, nc, hd)?; + be.add(s.x, s.acc, n)?; + (self.s.cur, self.s.x) = (s.x, s.cur); + Ok(()) + } + + fn layer_ffn_gpu(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result { + let Some(fe) = &self.layers[ip].full_exps else { return self.layer_ffn_pool(be, m, il, ip) }; + Self::ffn_core(be, &m.cfg, self.s, fe)?; + self.ffn_tail(be, m, il, ip)?; + Ok(true) + } + + /// `layer_ffn_gpu` for a layer whose experts are on GPU 1: the normed input crosses to it through the host, the + /// experts run there, and the sum comes back (two small copies and two syncs per layer run). False: not that kind of layer. + fn layer_ffn_remote(&mut self, d: &dev::Dev, m: &Inkling2Model, il: usize, ip: usize) -> Result { + let (Some(fe), Some(r)) = (&self.layers[ip].full_exps, &self.rem) else { return Ok(false) }; + if fe.part == 0 { return Ok(false) } + let (c, s, rs) = (&m.cfg, self.s, r.s); + let (be0, be1) = (&*d.parts[0].be, &*d.parts[r.part].be); + let (n, o0, o1) = (c.n_embd, self.scr.addr(), r.scr.addr()); + let xh_words = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + let hn: Vec = be0.get(&self.scr, ((s.hn - o0) / 4) as usize, n)?; + let xh: Vec = be0.get(&self.scr, ((s.xh - o0) / 4) as usize, xh_words)?; + be1.put(&hn, &r.scr, ((rs.hn - o1) / 4) as usize)?; + be1.put(&xh, &r.scr, ((rs.xh - o1) / 4) as usize)?; + Self::ffn_core(be1, c, rs, fe)?; + let acc: Vec = be1.get(&r.scr, ((rs.acc - o1) / 4) as usize, n)?; + be0.put(&acc, &self.scr, ((s.acc - o0) / 4) as usize)?; + self.ffn_tail(be0, m, il, ip)?; + Ok(true) + } + + /// `layer_ffn_gpu` of a layer in the expert pool: the router and the slot lookup on the device, the experts in a + /// slot there, the others on the CPU worker (mailbox `il`), whose sum the combine waits for only after a miss. + fn layer_ffn_pool(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result { + let Some(pool) = &self.pool else { return Ok(false) }; + let Some(pl) = pool.layer(ip) else { return Ok(false) }; + let (c, ds, s) = (&m.cfg, &self.slots[il], self.s); + let (n, hd, nc, nf, k) = (c.n_embd, c.head_dim, c.n_conv, c.n_ff_exp, c.n_used); + let hist3 = ds.hist.addr() + f(hists(c).0[3]); + let (base, stride) = pool.base(pl); + let mb = pool.worker.mb(il); + let slots = s.ids + f(k); + be.gemv(&pl.gate_inp, s.hn, s.rlogits)?; + let gu_sc = pl.gu_scale.as_ref().map_or(0, |b| b.addr()); + let dn_sc = pl.dn_scale.as_ref().map_or(0, |b| b.addr()); + let gsc_a = if gu_sc != 0 { s.ids + f(2 * k) } else { 0 }; + be.ink_route(s.rlogits, pl.bias.addr(), s.ids, s.wc, gu_sc, dn_sc, gsc_a, c.n_expert, k, c.exp_scale, 1)?; + be.ink_slots(s.ids, s.wc, pl.table_dev.addr(), slots, s.wh, s.hn, mb, n, pool.worker.layout.h, s.step, k)?; + let ((gt, gr, gc), (dt, dr, dc)) = (pl.gu, pl.dn); + be.moe_gemv(gt, gr, gc, base, stride, slots, k, s.hn, n, k, s.y, None, s.xh)?; + if dt.float_x() { + be.situ(s.y, nf, k, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.moe_gemv(dt, dr, dc, base + pl.dn_off as u64, stride, slots, k, s.y, 2 * nf, 1, s.d, None, 0)?; + } else { + be.situ_q(s.y, nf, k, gsc_a, c.situ_beta, c.situ_linear_beta, s.xq)?; + be.moe_gemv(dt, dr, dc, base + pl.dn_off as u64, stride, slots, k, s.y, 2 * nf, 1, s.d, None, s.xq)?; + } + be.ink_ffn_sum_mb(s.acc, s.d, s.wh, k, n, mb, pool.worker.layout.y, s.step, slots)?; be.ink_conv(s.acc, self.layers[ip].convs[3].addr(), 0, hist3, s.acc, n, nc, hd)?; be.add(s.x, s.acc, n)?; (self.s.cur, self.s.x) = (s.x, s.cur); @@ -1381,7 +2040,7 @@ impl Device { let d = lock(); let be = &*d.parts[0].be; self.layer_attn(be, &d, m, il, ip, msgs, pos, false, nb).expect("inkling2 device step"); - if self.layer_ffn_gpu(be, m, il, ip).expect("inkling2 device step") { + if self.layer_ffn_remote(&d, m, il, ip).expect("inkling2 device step remote") || self.layer_ffn_gpu(be, m, il, ip).expect("inkling2 device step") { m.lap(0, t); return; } @@ -1390,17 +2049,22 @@ impl Device { m.lap(0, t); // The experts: those of the GPU read the device's copy of the input and leave their outputs there. let (on_gpu, on_cpu, adapt) = m.plan(ip, &hn); + // Local patch: an expert with a matrix on another GPU cannot run in this GPU's queue; `remote` runs through + // `run_experts` (each matrix where it lives), next to the CPU share. + let on_first = |x: &Mat| x.gpu.is_none_or(|i| i == dev::STAGED || dev::gpu_of(i) == 0); + let (list, remote): (Vec<_>, Vec<_>) = Inkling2Model::resident(ml, c.n_expert, &on_gpu).into_iter().partition(|e| on_first(&e.0) && on_first(&e.1)); let gpu_side = || -> Option { let t = std::time::Instant::now(); - let list = Inkling2Model::resident(ml, c.n_expert, &on_gpu); let d = lock(); - let (p, mut owned) = (&d.parts[0], vec![]); + let (p, mut staged) = (&d.parts[0], None); (|| -> Option<()> { // One moe_gemv per matrix kind for all of them (8 small gemvs leave most of the card idle). let Some((gu, dn, ..)) = list.first() else { return Some(()) }; let (k, gs) = (list.len(), list.iter().map(|e| e.3).collect::>()); - let mut ptrs = |down: bool| list.iter().map(|e| d.weight(p, if down { &e.1 } else { &e.0 }, &mut owned).map(|t| t.ptr)).collect::>>(); - let (pg, pd) = (ptrs(false)?, ptrs(true)?); + let (gm, dm): (Vec<_>, Vec<_>) = list.iter().map(|e| (e.0, e.1)).unzip(); + let (buf, ptrs) = d.weights(p, &[&gm, &dm])?; + let (pg, pd) = (ptrs[..k].to_vec(), ptrs[k..].to_vec()); + staged = (buf.len() > 0).then_some(buf); match (slab(&pg), slab(&pd)) { (Some((bg, sg, ig)), Some((bd, sd, id))) => { p.be.put(&[ig, id].concat(), &self.scr, ((s.ids - o) / 4) as usize).ok()?; @@ -1426,7 +2090,7 @@ impl Device { } // Wait when an expert came from the file: its copy lives until the run ends, and the CPU share // follows the time. With every expert in VRAM the queue runs on. - if adapt || !owned.is_empty() { p.be.sync().ok()?; } + if adapt || staged.is_some() { p.be.sync().ok()?; } Some(()) })()?; Some(t.elapsed().as_secs_f32()) @@ -1435,15 +2099,24 @@ impl Device { let t = std::time::Instant::now(); (run_experts(&on_cpu, &hn, c), t.elapsed().as_secs_f32()) }; - let (gpu, (cpu, tc)) = rayon::join(gpu_side, cpu_side); + let remote_side = || (!remote.is_empty()).then(|| run_experts(&remote, &hn, c)); + let (gpu, ((cpu, tc), rem)) = rayon::join(gpu_side, || rayon::join(cpu_side, remote_side)); let d = lock(); let be = &*d.parts[0].be; match gpu { Some(tg) => { - m.balance(&m.cpu_share, adapt, tg, tc); - let wc: Vec = (0..c.n_used).map(|i| on_gpu.get(i).map_or(0.0, |e| e.2)).chain(cpu).collect(); + m.balance_split(adapt, tg, tc); + // `cpu` and `r` are per-dimension sums (`run_experts` returns the weighted mix), not per-expert + // weights: both have length `n`, and the elementwise add is the host total. + debug_assert_eq!(cpu.len(), n); + let host: Vec = match rem { + Some(r) => { debug_assert_eq!(r.len(), n); cpu.iter().zip(&r).map(|(a, b)| a + b).collect() } + None => cpu, + }; + debug_assert_eq!(host.len(), n); + let wc: Vec = (0..c.n_used).map(|i| list.get(i).map_or(0.0, |e| e.2)).chain(host).collect(); be.put(&wc, &self.scr, ((s.wc - o) / 4) as usize).expect("inkling2 device step"); - be.ink_ffn_sum(s.acc, s.d, s.wc, on_gpu.len(), n, s.wc + f(c.n_used)).expect("inkling2 device step"); + be.ink_ffn_sum(s.acc, s.d, s.wc, list.len(), n, s.wc + f(c.n_used)).expect("inkling2 device step"); } None => { // No room to stage a routed weight (a card with little free VRAM): the experts of the GPU run on diff --git a/src/inkling2/forward/pool.rs b/src/inkling2/forward/pool.rs new file mode 100644 index 00000000..a312ffaa --- /dev/null +++ b/src/inkling2/forward/pool.rs @@ -0,0 +1,363 @@ +//! VRAM slots for the routed experts of the layers without a slab (see `device`): one pool of equal slots per +//! expert layout, a table per layer (expert -> slot, -1 = on the CPU) that `ink_slots` reads, and usage counts that +//! decide which experts hold the slots. Routes skew hard: in the coda of Inkling 2 Mini, 100 of 768 experts take +//! 60-67% of a text's uses. The table changes between tokens only, with the queue idle. +use super::*; +use super::worker::{HostExperts, InkWorker}; +use crate::backend::{Buf, GpuTensor}; +use crate::deepseek::mat::dev::{self, SlabBuf}; +use crate::quant::GgmlType; +use std::sync::Arc; + +/// Share of a usage count kept per token: a count forgets in a few hundred tokens. +const KEEP: f32 = 0.995; +/// Experts copied into free slots per token while a pool fills, and into a less used expert's slot once it is full. +/// A copy of an 8.5 MB expert takes about 0.7 ms over PCIe 3.0. +const FILLS: usize = 4; +const SWAPS: usize = 2; +/// Share of a long count kept per token: the saved profile, which places the next run's experts at load. +const LONG_KEEP: f32 = 0.9999; +/// Slots past each pool's own for a prompt chunk's experts that are not in it (`stage`). +pub(super) const STAGE: usize = 32; + +/// Bytes the pool keeps free on GPU 0 after its own allocations: at least 512 MB (`--vram-margin`'s default, which +/// the maintainer measured: the CUDA graph of the core layers needs that much), at least what this call allocated for +/// the LUT and gate/bias slabs plus 64 MB, and at least what the K/V growth to the context and the decode and prefill +/// buffers still need (`state`). The pool fills first and those buffers come after it, so the floor is where that room +/// comes from: a larger `--vram-margin` raises it, a smaller one cannot go below it. +pub(super) fn pool_floor(f_res: usize, margin: usize, state: usize) -> usize { + margin.max(512 << 20).max(f_res + (64 << 20)).max(state) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pool_floor_follows_the_vram_margin_and_the_state() { + let (f_res, mib) = (384 << 20, 1 << 20); + let state = 1200 * mib; + // No margin given: the 512 MB default stands (the maintainer's fix), above the pool's own 448 MB. + assert_eq!(pool_floor(f_res, 0, 300 * mib), 512 * mib); + assert_eq!(pool_floor(f_res, 0, state), state); + // A larger margin wins; a smaller one does not go below the 512 MB default. + assert_eq!(pool_floor(f_res, 2048 * mib, state), 2048 * mib); + assert_eq!(pool_floor(f_res, 128 * mib, 300 * mib), 512 * mib); + // A 16k context needs its K/V rows whether the margin says so or not (the prefill OOM when it was dropped). + assert!(pool_floor(f_res, 512 * mib, 1800 * mib) > 512 * mib); + } +} + +pub(super) struct PoolLayer { + pub pool: usize, + pub table_dev: Buf, + table: Vec, + pub gate_inp: GpuTensor, + _gi: Arc, + pub bias: Arc, + pub gu_scale: Option>, + pub dn_scale: Option>, + /// (type, rows, cols) of one expert's gate_up and down matrices; down starts `dn_off` bytes into a slot. + pub gu: (GgmlType, usize, usize), + pub dn: (GgmlType, usize, usize), + pub dn_off: usize, + host: HostExperts, +} + +/// `owner.len()` slots of `bytes`, then `STAGE` more for a prompt chunk. +struct Slots { buf: Option>, bytes: usize, owner: Vec> } + +pub(super) struct Pool { + slots: Vec, + pub layers: Vec>, + /// Decayed uses, [layer * n_expert + expert]. + counts: Vec, + /// The same with a memory of some ten thousand tokens: saved when the pool goes, read at the next load. + long: Vec, + profile: std::path::PathBuf, + ne: usize, + pub worker: InkWorker, + /// (mailbox, layer) of the runs with a pool layer, in token order. + runs: Vec<(usize, usize)>, + /// Since the last PROF line: expert uses found in a slot, uses on the CPU, experts copied in. + pub stats: [usize; 3], + pub tokens: usize, + /// No saved profile was found: this pool adapts its slots as it runs and saves the profile when it goes. A pool + /// that loaded one keeps the placement it made at load, so a hit and a miss compute the same way on every run. + learn: bool, +} + +impl Pool { + /// The pool for layers `need` with what the weight budget has left, or None when nothing fits or the backend + /// has no pool kernels. `state` is what the forward still allocates after the pool up to the context (see + /// `device::state_bytes`): the free floor is the larger of it and `--vram-margin`. + pub fn new(m: &Inkling2Model, d: &mut dev::Dev, need: &[usize], runs: Vec<(usize, usize)>, state: usize) -> Option { + let (c, ne) = (&m.cfg, m.cfg.n_expert); + if !d.parts[0].be.ink_pool() { return None; } + let (b_res, f_res) = (64 << 20, 384 << 20); + let bytes = |x: &[f32]| -> Vec { x.iter().flat_map(|v| v.to_le_bytes()).collect() }; + // Layout of a slot per layer, and the layers of each layout. + let mut kinds: Vec<((GgmlType, usize, usize, GgmlType, usize, usize), usize, Vec)> = vec![]; + let mut layers: Vec> = (0..c.n_layer).map(|_| None).collect(); + let mut host: Vec> = vec![None; c.n_layer]; + for &ip in need { + let ml = &m.layers[ip]; + let (gu, dn) = (ml.gate_up.expert_host(0, ne), ml.down.expert_host(0, ne)); + let dn_off = gu.data.len().next_multiple_of(256); + let slot = (dn_off + dn.data.len()).next_multiple_of(256); + let key = (gu.ty, gu.rows, gu.cols, dn.ty, dn.rows, dn.cols); + let g = kinds.iter().position(|k| k.0 == key).unwrap_or_else(|| { kinds.push((key, slot, vec![])); kinds.len() - 1 }); + kinds[g].2.push(ip); + let gi = d.alloc_slab_on(0, &bytes(&ml.gate_inp), None, b_res, f_res)?; + let bias = d.alloc_slab_on(0, &bytes(&ml.bias), None, b_res, f_res)?; + let sc = |v: &[f32], d: &mut dev::Dev| if v.is_empty() { Some(None) } else { d.alloc_slab_on(0, &bytes(v), None, b_res, f_res).map(Some) }; + let (gu_scale, dn_scale) = (sc(&ml.gu_scale, d)?, sc(&ml.down_scale, d)?); + let be = &*d.parts[0].be; + let table = vec![-1i32; ne]; + let table_dev = be.alloc(4 * ne).ok()?; + be.put(&table, &table_dev, 0).ok()?; + // SAFETY: the mapped file outlives the model, which owns the device state and so the worker (joined on drop). + let st = |x: Mat| unsafe { std::mem::transmute::, Mat<'static>>(x) }; + let he = HostExperts { gate_up: st(ml.gate_up), down: st(ml.down), gu_scale: ml.gu_scale.clone() }; + host[ip] = Some(he.clone()); + layers[ip] = Some(PoolLayer { + pool: g, table_dev, table, + gate_inp: GpuTensor::new(GgmlType::F32, ne, c.n_embd, Buf::new(gi.addr(), gi.len(), ())), _gi: gi, + bias, gu_scale, dn_scale, + gu: (gu.ty, gu.rows, gu.cols), dn: (dn.ty, dn.rows, dn.cols), dn_off, host: he, + }); + } + // STRATA_INK_PIN=1: page-lock the pooled layers' experts in the mapped file, so a prompt chunk's staging copies + // are DMAs from there (`Backend::pin_host`) instead of a host copy through the pinned ring. + if std::env::var_os("STRATA_INK_PIN").is_some() { + let t0 = std::time::Instant::now(); + let (mut gb, mut ok) = (0.0, true); + for &ip in need { + let ml = &m.layers[ip]; + for data in [ml.gate_up.data, ml.down.data] { + match d.parts[0].be.pin_host(data) { + Ok(true) => gb += data.len() as f64 / 1e9, + Ok(false) => ok = false, + Err(e) => { eprintln!("inkling2: pinning the experts failed ({e:#}); staging copies go through the ring"); ok = false; } + } + if !ok { break; } + } + if !ok { break; } + } + eprintln!("inkling2: pinned {gb:.2} GB of experts in {:.1} s", t0.elapsed().as_secs_f64()); + } + // Slots in proportion to each layout's experts, from what the budget and the card have left. The free floor is + // `pool_floor`: the 512 MB default (or a larger `--vram-margin`), at least what this call allocated, and what + // the K/V rows to the context and the decode and prefill buffers still need (`state`): those are allocated + // after the pool, out of this room. + let total: usize = kinds.iter().map(|k| k.1 * ne * k.2.len()).sum(); + let floor = pool_floor(f_res, crate::deepseek::mat::dev_margin(), state); + let free = d.parts[0].be.mem_info().map_or(0, |m| m.0).saturating_sub(floor); + let room = d.budget_left().saturating_sub(b_res).min(free); + let frac = (room as f64 / total.max(1) as f64).min(1.0); + let mut slots = vec![]; + for k in &kinds { + // A layout takes its share; when that does not fit (the floor was raised by a later allocation), the rest + // of the room, down to its staging slots alone: the Q8 layers' experts still get a pool, if a small one. + let want = ((frac * (ne * k.2.len()) as f64) as usize).saturating_sub(STAGE).min(ne * k.2.len()); + let avail = d.parts[0].be.mem_info().map_or(0, |m| m.0).saturating_sub(floor).min(d.budget_left().saturating_sub(b_res)); + let (n, buf) = match d.alloc_room((want + STAGE) * k.1, b_res, floor) { + Some(b) => (want, Some(b)), + None => { + let fit = (avail / k.1).saturating_sub(STAGE).min(want); + (fit, d.alloc_room((fit + STAGE) * k.1, b_res, floor)) + } + }; + let n = if buf.is_some() { n } else { 0 }; + slots.push(Slots { buf, bytes: k.1, owner: vec![None; n] }); + } + if std::env::var_os("STRATA_DS_PROF").is_some() { + let desc: Vec = kinds.iter().zip(&slots).map(|(k, s)| format!("{:?} layers {:?}: {} of {} experts ({:.2} GB)", + k.0.0, k.2, s.owner.len(), ne * k.2.len(), (s.owner.len() * k.1) as f64 / 1e9)).collect(); + eprintln!("inkling2: expert pool {}", desc.join("; ")); + } + if slots.iter().all(|s| s.buf.is_none()) { return None; } + let worker = InkWorker::new(&*d.parts[0].be, c, runs.clone(), host).inspect_err(|e| eprintln!("inkling2: no CPU expert worker ({e:#})")).ok()?; + let profile = crate::expert_cache::cache_dir().join(format!("inkling2-profile-{}x{}-{}-{:?}.f32", c.n_layer, ne, c.n_embd, m.layers[0].gate_up.ty)); + let long: Vec = std::fs::read(&profile).ok().filter(|b| b.len() == 4 * c.n_layer * ne) + .map(|b| b.chunks_exact(4).map(|x| f32::from_le_bytes(x.try_into().unwrap())).collect()).unwrap_or_default(); + let learn = long.is_empty(); + let mut pool = Pool { slots, layers, counts: vec![0.0; c.n_layer * ne], long, profile, ne, worker, runs, stats: [0; 3], tokens: 0, learn }; + pool.fill(d).inspect_err(|e| eprintln!("inkling2: expert pool fill: {e:#}")).ok()?; + Some(pool) + } + + pub fn layer(&self, ip: usize) -> Option<&PoolLayer> { self.layers[ip].as_ref() } + + /// The first placement: the saved profile's most used experts, else in every layer the same share of experts + /// for each time a token runs it (a core layer runs three times). + fn fill(&mut self, d: &mut dev::Dev) -> Result<()> { + let ne = self.ne; + let per: Vec = (0..self.layers.len()).map(|ip| self.runs.iter().filter(|r| r.1 == ip).count() as f32).collect(); + let runs = |ip: usize| per[ip]; + let have = !self.long.is_empty(); + if !have { self.long = vec![0.0; self.counts.len()]; } + for g in 0..self.slots.len() { + let mut cand: Vec<(f32, usize, usize)> = self.layers.iter().enumerate() + .filter(|(_, l)| l.as_ref().is_some_and(|l| l.pool == g)) + .flat_map(|(ip, _)| (0..ne).map(move |e| (ip, e))) + .map(|(ip, e)| (if have { self.long[ip * ne + e] } else { runs(ip) / (e + 1) as f32 }, ip, e)).collect(); + cand.sort_by(|a, b| b.0.total_cmp(&a.0)); + for (slot, &(_, ip, e)) in cand.iter().take(self.slots[g].owner.len()).enumerate() { self.place(d, g, slot, ip, e)?; } + } + // Counts start from the profile at their steady size, so the first tokens move no more than later ones. + let steady = 1.0 / (1.0 - KEEP); + for (ip, l) in self.long.chunks(ne).enumerate() { + let s: f32 = l.iter().sum(); + if s > 0.0 { for e in 0..ne { self.counts[ip * ne + e] = l[e] / s * steady * 8.0; } } + } + for pl in self.layers.iter().flatten() { d.parts[0].be.put(&pl.table, &pl.table_dev, 0)?; } + Ok(()) + } + + /// Copy expert `e` of layer `ip` into slot `slot` of pool `g` and point the table (on the host) at it. + fn place(&mut self, d: &mut dev::Dev, g: usize, slot: usize, ip: usize, e: usize) -> Result<()> { + let ne = self.ne; + let at = self.upload(&*d.parts[0].be, ip, e, slot)?; + let pl = self.layers[ip].as_mut().unwrap(); + let (gu, dn) = (pl.host.gate_up.expert_host(e, ne), pl.host.down.expert_host(e, ne)); + // A prompt chunk's host lookups find the slot too (`Dev::expert`). + d.pin(gu.data, gu.ty, gu.rows, gu.cols, gu.scale, at); + d.pin(dn.data, dn.ty, dn.rows, dn.cols, dn.scale, at + pl.dn_off as u64); + pl.table[e] = slot as i32; + self.slots[g].owner[slot] = Some((ip, e)); + Ok(()) + } + + /// Copy expert `e` of layer `ip` into slot `slot` (a staging slot too) of its pool: its address. + pub fn upload(&self, be: &dyn crate::backend::Backend, ip: usize, e: usize, slot: usize) -> Result { + self.upload_on(be, ip, e, slot, false) + } + + /// `upload`, on the backend's copy queue when `side` (`Backend::htod_side`). + pub fn upload_on(&self, be: &dyn crate::backend::Backend, ip: usize, e: usize, slot: usize, side: bool) -> Result { + let pl = self.layers[ip].as_ref().unwrap(); + let sl = &self.slots[pl.pool]; + let at = sl.buf.as_ref().unwrap().addr() + (slot * sl.bytes) as u64; + let (gu, dn) = (pl.host.gate_up.expert_host(e, self.ne), pl.host.down.expert_host(e, self.ne)); + let (gb, db) = (Buf::new(at, gu.data.len(), ()), Buf::new(at + pl.dn_off as u64, dn.data.len(), ())); + if side { be.htod_side(gu.data, &gb, 0)?; be.htod_side(dn.data, &db, 0)?; } + else { be.htod(gu.data, &gb, 0)?; be.htod(dn.data, &db, 0)?; } + Ok(at) + } + + /// Slot of expert `e` of layer `ip` (-1: not in the pool), and the first of the pool's `STAGE` staging slots. + pub fn slot(&self, ip: usize, e: usize) -> i32 { self.layers[ip].as_ref().unwrap().table[e] } + pub fn stage(&self, pl: &PoolLayer) -> usize { self.slots[pl.pool].owner.len() } + /// Whether layer `ip`'s pool got VRAM (its staging slots exist, so a prompt chunk can run there). + pub fn has_room(&self, ip: usize) -> bool { self.layers[ip].as_ref().is_some_and(|pl| self.slots[pl.pool].buf.is_some()) } + + /// Base address and slot size of layer `ip`'s pool. + pub fn base(&self, pl: &PoolLayer) -> (u64, usize) { let s = &self.slots[pl.pool]; (s.buf.as_ref().map_or(0, |b| b.addr()), s.bytes) } + + /// After a token, with the queue idle: count its routing, copy the most used missed experts into free slots, and + /// give a full pool's least used slot to a missed expert used more often (by more than one). Only while learning + /// (no saved profile): a pool placed from the profile only counts, because a slot that changes during a run + /// changes which experts the CPU computes, and with it the output of the next run on the same text. + pub fn adapt(&mut self, d: &mut dev::Dev) -> Result<()> { + let ne = self.ne; + self.tokens += 1; + if !self.learn { + for &(il, _) in &self.runs { + for (_, s) in self.worker.routing(il) { self.stats[if s < 0 { 1 } else { 0 }] += 1; } + } + return Ok(()); + } + for v in &mut self.counts { *v *= KEEP; } + for v in &mut self.long { *v *= LONG_KEEP; } + let mut missed = vec![]; + for &(il, ip) in &self.runs { + for (e, s) in self.worker.routing(il) { + if e >= ne { continue; } + self.counts[ip * ne + e] += 1.0; + self.long[ip * ne + e] += 1.0; + if s < 0 { missed.push((ip, e)); self.stats[1] += 1; } else { self.stats[0] += 1; } + } + } + missed.sort_by(|a, b| self.counts[b.0 * ne + b.1].total_cmp(&self.counts[a.0 * ne + a.1])); + missed.dedup(); + let (mut fills, mut swaps, mut changed) = (0, 0, vec![]); + for (ip, e) in missed { + let g = self.layers[ip].as_ref().unwrap().pool; + if self.layers[ip].as_ref().unwrap().table[e] >= 0 { continue; } + let slot = match self.slots[g].owner.iter().position(|o| o.is_none()) { + Some(s) if fills < FILLS => { fills += 1; s } + Some(_) => continue, + None if swaps < SWAPS => { + let Some((s, (vip, ve))) = self.slots[g].owner.iter().enumerate().filter_map(|(s, o)| o.map(|o| (s, o))) + .min_by(|a, b| self.counts[a.1.0 * ne + a.1.1].total_cmp(&self.counts[b.1.0 * ne + b.1.1])) else { continue }; + if self.counts[ip * ne + e] <= self.counts[vip * ne + ve] + 1.0 { continue; } + let vl = self.layers[vip].as_mut().unwrap(); + vl.table[ve] = -1; + d.unpin(vl.host.gate_up.expert_host(ve, ne).data); + d.unpin(vl.host.down.expert_host(ve, ne).data); + changed.push(vip); + swaps += 1; + s + } + None => continue, + }; + self.place(d, g, slot, ip, e)?; + changed.push(ip); + self.stats[2] += 1; + } + changed.sort_unstable(); + changed.dedup(); + for ip in changed { + let pl = self.layers[ip].as_ref().unwrap(); + d.parts[0].be.put(&pl.table, &pl.table_dev, 0)?; + } + Ok(()) + } +} + +impl Pool { + /// Drop the `Dev::pin`s of the filled slots and return the bytes the pool's slot buffers hold (what its `Drop` + /// frees): the pins are views of this pool's VRAM, which goes with the pool. The caller must hold the device and + /// drop the pool right after. + pub fn unpin_all(&mut self, d: &mut dev::Dev) -> usize { + let ne = self.ne; + for s in &mut self.slots { + for (ip, e) in s.owner.iter_mut().filter_map(Option::take) { + let h = &self.layers[ip].as_ref().unwrap().host; + d.unpin(h.gate_up.expert_host(e, ne).data); + d.unpin(h.down.expert_host(e, ne).data); + } + } + self.slots.iter().filter_map(|s| s.buf.as_ref()).map(|b| b.len()).sum::() + + self.layers.iter().flatten().map(|l| l._gi.len() + l.bias.len() + + l.gu_scale.as_ref().map_or(0, |b| b.len()) + l.dn_scale.as_ref().map_or(0, |b| b.len())).sum::() + } +} + +impl Drop for Pool { + /// Unpin the slots (unless `unpin_all` ran) and, when it learned one, save the profile: the next load places from it. + /// + /// Every path that drops a pool while the device is held calls `unpin_all` first. This is for the paths where the + /// device is open but free to take: `Pool` is owned by `Device`, so its `Drop` runs as the `Device` field is + /// dropped, and a `Device` is dropped when a model is (normally with no one holding the device) or when a decode + /// or prefill state gives way (also outside a device lock). A caller that does hold the lock would leave the slots + /// pinned to VRAM that is freed a moment later, so the cases are listed and none of them holds it: + /// `Inkling2Model::reset`/`forget` (keeps the pool), the `self.device = None` fallbacks in `forward.rs` (the + /// device is taken out of the model and dropped outside every lock), and `prepare`'s growth path (`unpin_all`). + fn drop(&mut self) { + if self.slots.iter().any(|s| s.owner.iter().any(Option::is_some)) { + match dev::get().map(|m| m.try_lock()) { + Some(Ok(mut d)) => { let _ = self.unpin_all(&mut d); } + Some(Err(_)) => eprintln!("inkling2: the expert pool's slots are still pinned: its Drop ran under the device lock"), + None => {} + } + } + // ponytail: the profile is written once, by the first run long enough to learn one; a later change of + // workload keeps the old placement. Delete the file (`inkling2-profile-*.f32` in the cache dir) to learn again. + if !self.learn || self.tokens < 16 { return; } + let bytes: Vec = self.long.iter().flat_map(|v| v.to_le_bytes()).collect(); + if let Some(dir) = self.profile.parent() { let _ = std::fs::create_dir_all(dir); } + if let Err(e) = std::fs::write(&self.profile, bytes) { eprintln!("inkling2: expert profile {}: {e}", self.profile.display()); } + } +} diff --git a/src/inkling2/forward/worker.rs b/src/inkling2/forward/worker.rs new file mode 100644 index 00000000..fe3a97ed --- /dev/null +++ b/src/inkling2/forward/worker.rs @@ -0,0 +1,115 @@ +//! The CPU side of the expert pool in a decode token (see `pool`): the mailboxes and flags of `crate::cpu_worker`, +//! one per layer run whose experts are not all in VRAM, answered with `run_experts` as `plan`'s CPU experts are. +//! `ink_slots` raises a run's request flag when one of its experts missed, else its skip flag; +//! `ink_ffn_sum_mb` waits for the done flag only after a miss. +use super::*; +use crate::backend::{Backend, Buf}; +use crate::cpu_worker::{DONE, IDS, Mailbox, REQ, SKIP, read_wc}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering, fence}; +use std::sync::{Arc, mpsc}; +use std::thread::JoinHandle; + +/// A layer's routed experts in the mapped file, for the worker thread. +#[derive(Clone)] +pub(super) struct HostExperts { pub gate_up: Mat<'static>, pub down: Mat<'static>, pub gu_scale: Vec } + +pub(super) struct InkWorker { + _mem: Buf, + host: usize, + /// Device address of the mailboxes: run `il` at `dev + 4 * il * layout.stride`. + pub dev: u64, + pub layout: Mailbox, + seq: u32, + tx: Option>, + stop: Arc, + busy_ns: Arc, + thread: Option>, +} + +impl InkWorker { + /// `runs`: (mailbox index, layer) of every layer run with a mailbox, in the order a token runs them; + /// `experts[ip]` the host experts of each such layer. + pub fn new(be: &dyn Backend, cfg: &Inkling2Config, runs: Vec<(usize, usize)>, experts: Vec>) -> Result { + let layout = Mailbox::new(cfg.n_used, cfg.n_embd); + let len = layout.stride * runs.iter().map(|r| r.0 + 1).max().unwrap_or(1); + let (mem, host) = be.host_mailbox(len)?; + let (host, dev) = (host as usize, mem.addr()); + let (tx, rx) = mpsc::channel::(); + let (stop, busy_ns) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicU64::new(0))); + let (st, bn, cfg) = (stop.clone(), busy_ns.clone(), cfg.clone()); + let lay = Mailbox::new(cfg.n_used, cfg.n_embd); + // Its own pool, as `CpuWorker`'s: the expert passes start on the spinning thread at once. + let pool = rayon::ThreadPoolBuilder::new().num_threads(rayon::current_num_threads()) + .thread_name(|i| format!("inkling-experts-{i}")).build()?; + let thread = std::thread::Builder::new().name("inkling-cpu-experts".into()).spawn(move || pool.install(move || { + let w = |i: usize| (host + 4 * i) as *mut u32; + let ne = cfg.n_expert; + while let Ok(seq) = rx.recv() { + for &(il, ip) in &runs { + let at = |o: usize| w(il * lay.stride + o); + // A newer seq anywhere: the GPU moved on without waiting for this one. + let ahead = |v: u32| v != 0 && (v.wrapping_sub(seq) as i32) >= 0; + let mut r; + while { r = unsafe { at(REQ).read_volatile() }; r != seq } { + if st.load(Ordering::Relaxed) { return; } + if ahead(r) || ahead(unsafe { at(SKIP).read_volatile() }) { break; } + std::hint::spin_loop(); + } + if r != seq { continue; } + fence(Ordering::SeqCst); + let t0 = std::time::Instant::now(); + let k = lay.k; + let mut v = vec![0u32; (3 * k).next_multiple_of(4)]; + unsafe { read_wc(at(IDS), &mut v) }; + let mut h = vec![0u32; lay.n.next_multiple_of(4)]; + unsafe { read_wc(at(lay.h), &mut h) }; + let h: Vec = h[..lay.n].iter().map(|&b| f32::from_bits(b)).collect(); + let ex = experts[ip].as_ref().expect("a mailbox run of a layer without host experts"); + // `--tail-skip`; when it drops every CPU expert, `run_experts` of nothing writes the zeros the + // combine adds. + let keep = crate::cpu_worker::tail_select(&v, k, k); + let list: Vec<_> = (0..k).filter(|&j| (v[2 * k + j] as i32) < 0 && keep[j]).map(|j| { + let e = v[j] as usize; + (ex.gate_up.expert_host(e, ne), ex.down.expert_host(e, ne), f32::from_bits(v[k + j]), ex.gu_scale[e]) + }).collect(); + let y = run_experts(&list, &h, &cfg); + unsafe { std::ptr::copy_nonoverlapping(y.as_ptr(), at(lay.y) as *mut f32, lay.n) }; + fence(Ordering::SeqCst); + unsafe { at(DONE).write_volatile(seq) }; + fence(Ordering::SeqCst); + bn.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed); + } + } + }))?; + Ok(InkWorker { _mem: mem, host, dev, layout, seq: 0, tx: Some(tx), stop, busy_ns, thread: Some(thread) }) + } + + /// Start a token: the sequence number the kernels must find in `step[1]`. + pub fn begin(&mut self) -> u32 { + self.seq = self.seq.wrapping_add(1).max(1); + let _ = self.tx.as_ref().unwrap().send(self.seq); + self.seq + } + + /// Mailbox of run `il` on the device. + pub fn mb(&self, il: usize) -> u64 { self.dev + (4 * il * self.layout.stride) as u64 } + + /// The routing of run `il` in the last token: (expert, slot or -1) for each of its k experts. + pub fn routing(&self, il: usize) -> Vec<(usize, i32)> { + let k = self.layout.k; + let mut v = vec![0u32; (3 * k).next_multiple_of(4)]; + unsafe { read_wc((self.host as *const u32).add(il * self.layout.stride + IDS), &mut v) }; + (0..k).map(|j| (v[j] as usize, v[2 * k + j] as i32)).collect() + } + + /// Time the worker spent computing experts. + pub fn busy(&self) -> std::time::Duration { std::time::Duration::from_nanos(self.busy_ns.load(Ordering::Relaxed)) } +} + +impl Drop for InkWorker { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + self.tx = None; + if let Some(t) = self.thread.take() { let _ = t.join(); } + } +} diff --git a/src/inkling2/mod.rs b/src/inkling2/mod.rs index 819bf1a0..7c54d020 100644 --- a/src/inkling2/mod.rs +++ b/src/inkling2/mod.rs @@ -120,6 +120,8 @@ impl Inkling2Config { ensure!(cfg.loop_end <= cfg.n_layer, "bad loop range"); ensure!(cfg.n_conv >= 2 && cfg.block_size >= 1 && cfg.rel_extent >= 1 && cfg.n_swa >= 1, "bad shortconv, block or window size"); ensure!(u("attention.value_length")? == cfg.head_dim, "key and value head widths differ"); + // The device K store tells K from V by a positive clip, so a K cache with its own type needs one. + ensure!(cfg.qk_clip > 0.0, "attention.qk_clip must be positive (got {})", cfg.qk_clip); ensure!(g.meta.get(&k("loop.varying")).and_then(|v| v.as_u64()).unwrap_or(0) == 0, "loop.varying is not supported"); Ok(cfg) } diff --git a/src/kolibri/chat.rs b/src/kolibri/chat.rs new file mode 100644 index 00000000..82174242 --- /dev/null +++ b/src/kolibri/chat.rs @@ -0,0 +1,246 @@ +//! `rustingstrata generate|chat|serve` for Kolibri 1.1: greedy, CUDA for the matvecs and expert staging, KV kept across turns. +use super::forward::KolibriModel; +use crate::{chat::{Json, Msg}, gguf::Gguf, tokenizer::Tokenizer}; +use std::io::{BufRead, Write}; + +const END: &str = "<|im_end|>\n"; +const THINK_END: &str = ""; +const CALL: &str = ""; +const CALL_END: &str = ""; + +pub use crate::deepseek::chat::gpu_defaults; + +/// The template's reasoning effort: `reasoning_effort` when given, else "none" when thinking is switched off, else high. +pub fn effort(think: Option, effort: Option<&str>) -> &str { + effort.unwrap_or(if think == Some(false) { "none" } else { "high" }) +} + +/// The GGUF's chat template with `add_generation_prompt`. `effort` is its `reasoning_effort` ("none" disables +/// thinking); `preserve` is its `preserve_thinking`. +pub fn render(msgs: &[Msg], tools: &[Json], effort: &str, preserve: bool) -> String { + let sentence = match effort { + "none" => "Reasoning is disabled. Proceed straight to answering according to the user's instructions.", + "minimal" | "low" => "Reasoning effort is set to low. Think briefly through only the essential steps in the user's language, then proceed directly to the answer.", + "medium" => "Reasoning effort is set to medium. Think through the task methodically in the user's language, check key assumptions, and provide a well-supported answer.", + _ => "Reasoning effort is set to high. Think carefully through the task in the user's language, validate key assumptions, consider plausible alternatives, and prioritize correctness and clarity.", + }; + let mut s = String::from("<|im_start|>system\n"); + if let Some(m) = msgs.first().filter(|m| m.role == "system") { s += &format!("{}\n\n", m.content); } + s += &format!("# Reasoning effort\n\n{sentence}"); + if !tools.is_empty() { + s += "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n"; + for t in tools { s += &format!("\n{}", t.dump()); } + s += "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n"; + } + s += END; + // Replies after the last real user turn keep their thinking. + let last_query = msgs.iter().rposition(|m| m.role == "user" && !(m.content.starts_with("") && m.content.ends_with(""))).unwrap_or(msgs.len().saturating_sub(1)); + for (i, m) in msgs.iter().enumerate() { + match m.role.as_str() { + "system" if i == 0 => {} + "assistant" => { + let (mut content, mut reasoning) = (m.content.as_str(), m.reasoning.as_deref()); + if reasoning.is_none() && let Some((r, c)) = content.rsplit_once(THINK_END) { + reasoning = Some(r.trim_end_matches('\n').rsplit("").next().unwrap_or("")); + content = c; + } + s += "<|im_start|>assistant\n"; + if i > last_query || preserve { + s += &format!("\n{}\n\n\n", reasoning.filter(|r| !r.trim().is_empty()).map_or("", |r| r.trim_matches('\n'))); + } + let content = content.trim_start_matches('\n'); + s += content; + for (k, c) in m.calls.iter().enumerate() { + if k > 0 || !content.is_empty() { s += "\n"; } + s += &format!("{CALL}\n{{\"name\": \"{}\", \"arguments\": {}}}\n{CALL_END}", c.name, c.args.dump()); + } + s += END; + } + "tool" => { + // Consecutive tool messages share one user turn. + if i == 0 || msgs[i - 1].role != "tool" { s += "<|im_start|>user"; } + s += &format!("\n\n{}\n", m.content); + if msgs.get(i + 1).is_none_or(|x| x.role != "tool") { s += END; } + } + role => s += &format!("<|im_start|>{role}\n{}{END}", m.content), + } + } + s += "<|im_start|>assistant\n"; + if effort == "none" { s += "\n\n\n\n"; } + s +} + +/// The tool calls of a reply: the text before the first call and (name, JSON arguments) per call. The thinking part +/// is skipped, so a tag inside it is not a call. +pub fn parse_calls(text: &str) -> Option<(String, Vec<(String, String)>)> { + let from = text.rfind(THINK_END).map_or(0, |p| p + THINK_END.len()); + let start = from + text[from..].find(CALL)?; + let mut calls = vec![]; + for c in text[start..].split(CALL).skip(1) { + let v: serde_json::Value = serde_json::from_str(c.split(CALL_END).next()?.trim()).ok()?; + let args = match &v["arguments"] { serde_json::Value::String(s) => s.clone(), a => a.to_string() }; + calls.push((v["name"].as_str()?.to_string(), args)); + } + (!calls.is_empty()).then(|| (text[from..start].trim().to_string(), calls)) +} + +/// Greedy decode of up to `n` tokens after `logits`; `piece` gets each new piece of text and returns false to stop. +/// Returns the tokens and whether the model ended the reply itself. +fn decode(m: &mut KolibriModel, tok: &Tokenizer, lim: &mut Option, mut logits: Vec, n: usize, mut piece: impl FnMut(&str) -> bool) -> (Vec, bool) { + let eos = tok.eos_ids(); + let (mut out, mut shown) = (vec![], 0); + for i in 0..n { + let next = crate::grammar::greedy(lim, &mut logits); + if eos.contains(&next) { return (out, true); } + out.push(next); + crate::term::decoded(1); + let s = tok.decode(&out).unwrap_or_default(); + if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { + if !piece(&s[shown..]) { break; } + shown = s.len(); + } + if i + 1 < n { logits = m.step(next); } + } + (out, false) +} + +fn show(s: &str) -> bool { + print!("{s}"); + std::io::stdout().flush().is_ok() +} + +/// `rustingstrata generate`: raw prompt (no template), greedy, prints the continuation. +pub fn generate(g: &Gguf, prompt: &str, n: usize) -> anyhow::Result<()> { + gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = KolibriModel::new(g)?; + let max_ctx = m.cfg.n_ctx; + let ids = tok.encode(prompt)?; + anyhow::ensure!(!ids.is_empty() && ids.len() < max_ctx, "{}", crate::serve::too_long(ids.len(), max_ctx)); + if std::env::var_os("STRATA_DS_TRACE").is_some() { crate::say!("prompt tokens: {ids:?}"); } + let logits = m.prefill(&ids); + let (out, _) = decode(&mut m, &tok, &mut None, logits, n.min(max_ctx - ids.len()), show); + if std::env::var_os("STRATA_DS_TRACE").is_some() { crate::say!("\noutput tokens: {out:?}"); } + println!(); + Ok(()) +} + +pub fn chat(g: &Gguf, system: Option, n: usize, think: bool) -> anyhow::Result<()> { + gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = KolibriModel::new(g)?; + let max_ctx = m.cfg.n_ctx; + let effort = if think { "high" } else { "none" }; + let stdin = std::io::stdin(); + loop { + print!("{}", crate::term::prompt()); + std::io::stdout().flush()?; + let mut line = String::new(); + if stdin.lock().read_line(&mut line)? == 0 { break; } + let line = line.trim_end(); + if line.is_empty() { continue; } + // First turn: the full template. Later turns: the cache already holds everything up to the reply, so append only + // the end token and the next user turn (earlier think blocks stay in the cache). + let user = [Msg::new("user", line)]; + let text = if m.toks.is_empty() { + let msgs: Vec = system.iter().map(|s| Msg::new("system", s)).chain(user).collect(); + render(&msgs, &[], effort, false) + } else { + format!("{END}{}", render(&user, &[], effort, false).split_once(END).unwrap().1) + }; + let ids = tok.encode(&text)?; + if m.toks.len() + ids.len() >= max_ctx { + println!("context is full ({max_ctx} tokens); restart the chat"); + break; + } + let logits = m.prefill(&ids); + let left = max_ctx - m.toks.len(); + decode(&mut m, &tok, &mut None, logits, n.min(left), show); + println!(); + } + Ok(()) +} + +/// The chat of `rustingstrata serve` for Kolibri 1.1 (see `serve::Own`): one request at a time, JSON or SSE. +/// ponytail: greedy only; thinking arrives inside `content` up to `` (split it into +/// `reasoning_content` when a client needs that); the KV cache is reused only when the new prompt extends the last +/// sequence. +pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Result> { + use anyhow::Context; + use serde_json::json; + gpu_defaults(); + let mut m = KolibriModel::new(g)?; + crate::serve::warm_up(tok, |ids| { m.prefill(ids); m.reset(); })?; + let max_ctx = m.cfg.n_ctx; + Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| { + let mut lim = crate::grammar::Constraint::new(q, tok)?; + let text = render(&q.messages, &q.tools, effort(q.think, q.reasoning_effort.as_deref()), q.preserve_thinking.unwrap_or(false)); + let ids = tok.encode(&text).ok().filter(|i| !i.is_empty()).context("cannot encode prompt")?; + anyhow::ensure!(ids.len() < max_ctx, "{}", crate::serve::too_long(ids.len(), max_ctx)); + let t = std::time::Instant::now(); + let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; + if q.stream && !q.head_sent { let _ = write!(c, "{}", crate::serve::sse_head(c)); } + let logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); + let prefill_s = t.elapsed().as_secs_f64(); + let n = q.max_tokens.unwrap_or(usize::MAX).min(max_ctx - ids.len()); + let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); + let tools = q.tool_calls && !q.tools.is_empty(); + let mut hold = crate::chat::Hold::new(tools, q.stop.clone()).tagged(CALL); + let mut alive = std::time::Instant::now(); + let (out, stopped) = decode(&mut m, &tok, &mut lim, logits, n, |p| { + let t = hold.push(p); + (!q.stream || if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() }) && !hold.stopped + }); + let calls = if tools { parse_calls(&hold.text) } else { None }; + let done = if calls.is_some() { "tool_calls" } else if stopped || hold.stopped { "stop" } else { "length" }; + let calls_json = |(content, calls): &(String, Vec<(String, String)>), stream: bool| { + let c: Vec<_> = calls.iter().enumerate().map(|(k, (f, a))| { + let mut c = json!({"id": format!("call_{k}"), "type": "function", "function": {"name": f, "arguments": a}}); + if stream { c["index"] = k.into(); } + c + }).collect(); + if stream { json!({"tool_calls": c}) } else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } + }; + let d = crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done, drafts: None }; + let timings = d.timings(t); + let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), "prompt_tokens_details": {"cached_tokens": keep}}); + if q.stream { + match &calls { + Some(x) => { let _ = write!(c, "data: {}\n\n", chunk(calls_json(x, true), None)); } + None if !hold.rest().is_empty() => { let _ = write!(c, "data: {}\n\n", chunk(json!({"content": hold.rest()}), None)); } + None => {} + } + let mut last = chunk(json!({}), Some(done)); + last["usage"] = usage.clone(); + last["timings"] = timings; + let _ = write!(c, "data: {last}\n\n"); + if q.include_usage { let _ = write!(c, "data: {}\n\n", json!({"object": "chat.completion.chunk", "model": name, "choices": [], "usage": usage})); } + let _ = write!(c, "data: [DONE]\n\n"); + } else { + let message = match &calls { Some(x) => calls_json(x, false), None => json!({"role": "assistant", "content": hold.text}) }; + let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": message, "finish_reason": done}], "usage": usage, "timings": timings}); + crate::serve::send(c, "200 OK", "application/json", &b.to_string()); + } + Ok(d) + })) +} + +#[test] +fn template_and_calls() { + let user = [Msg::new("user", "hi")]; + assert_eq!(render(&user, &[], "none", false), + "<|im_start|>system\n# Reasoning effort\n\nReasoning is disabled. Proceed straight to answering according to the user's instructions.<|im_end|>\n\ + <|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"); + // A reply before the last user turn loses its thinking; a tool round after it keeps the think block. + let mut a = Msg::new("assistant", "\nplan\n\n\nok"); + let mut msgs = vec![Msg::new("system", "S"), Msg::new("user", "q"), a.clone(), Msg::new("user", "q2")]; + let r = render(&msgs, &[], "low", false); + assert!(r.starts_with("<|im_start|>system\nS\n\n# Reasoning effort\n\nReasoning effort is set to low."), "{r}"); + assert!(r.ends_with("<|im_start|>user\nq<|im_end|>\n<|im_start|>assistant\nok<|im_end|>\n<|im_start|>user\nq2<|im_end|>\n<|im_start|>assistant\n"), "{r}"); + a.calls = vec![crate::chat::Call { name: "get".into(), args: serde_json::from_str(r#"{"city": "Kyiv"}"#).unwrap() }]; + msgs.extend([a, Msg::new("tool", "sun"), Msg::new("tool", "rain")]); + assert!(render(&msgs, &[], "high", false).ends_with("<|im_start|>assistant\n\nplan\n\n\nok\n\n{\"name\": \"get\", \"arguments\": {\"city\": \"Kyiv\"}}\n<|im_end|>\n\ + <|im_start|>user\n\nsun\n\n\nrain\n<|im_end|>\n<|im_start|>assistant\n")); + let reply = "\n no\n\n\nok\n\n{\"name\": \"get\", \"arguments\": {\"city\": \"Kyiv\", \"n\": 3}}\n\n\n{\"name\": \"b\", \"arguments\": {}}\n"; + assert_eq!(parse_calls(reply), Some(("ok".into(), vec![("get".into(), r#"{"city":"Kyiv","n":3}"#.into()), ("b".into(), "{}".into())]))); +} diff --git a/src/kolibri/forward.rs b/src/kolibri/forward.rs new file mode 100644 index 00000000..3d7baa4c --- /dev/null +++ b/src/kolibri/forward.rs @@ -0,0 +1,743 @@ +//! Kolibri 1.1 forward, mirroring llama.cpp `src/models/kolibri1.cpp` (trace names are its callback names, so +//! `STRATA_DS_DUMP` output lines up with `llama-eval-callback`). Decode is one token at a time; prefill runs a chunk +//! of prompt tokens layer by layer, so a routed expert is read once for all the tokens that picked it. +//! ponytail: attention scores and the indexer run on the CPU; a GPU kernel is the next step for prompt speed. +use super::{KolibriConfig, N_RECENT, N_SINK}; +use crate::deepseek::mat::{Mat, matvec_many, matvec_rows, matvec_rows_many, swiglu_chunk, vec_f32}; +use crate::deepseek::ops::rms_norm_w; +use crate::gguf::Gguf; +use crate::hy4::forward::{host_mat, run_experts, sigmoid, silu}; +use crate::inkling2::forward::{dot_h, dots_h, mix_h}; +use anyhow::Result; +use half::f16; +use half::slice::HalfFloatSliceExt; +use rayon::prelude::*; + +enum Ffn<'a> { + Dense { gate: Mat<'a>, up: Mat<'a>, down: Mat<'a> }, + Moe { gate_inp: Mat<'a>, bias: Vec, gexps: Mat<'a>, uexps: Mat<'a>, dexps: Mat<'a>, gate_sh: Mat<'a>, up_sh: Mat<'a>, down_sh: Mat<'a> }, +} + +struct Layer<'a> { + attn_norm: Vec, + q: Mat<'a>, + q_norm: Vec, + /// K and V projections and the K norm; None on a layer that reads the K/V of another layer. + kv: Option<(Mat<'a>, Mat<'a>, Vec)>, + out: Mat<'a>, + post_attn_norm: Vec, + ffn_norm: Vec, + post_ffw_norm: Vec, + ffn: Ffn<'a>, +} + +pub struct KolibriModel<'a> { + pub cfg: KolibriConfig, + tok_embd: Mat<'a>, + out_norm: Vec, + out_w: Mat<'a>, + layers: Vec>, + /// Per layer with its own K/V and per K/V head: one f16 row of `head_dim` per position from `first[il]` on, as + /// llama.cpp keeps them. Sliding layers: K rotated; sparse layers: K and V rounded to NVFP4. + k: Vec>>, + v: Vec>>, + /// Position of row 0 (a sliding layer drops the rows no later query sees). + first: Vec, + /// Per sparse layer with its own K/V: the rounded mean routing key of each complete block of positions. + blocks: Vec>, + /// Share of a layer's VRAM-cache misses that the CPU computes while the GPU runs the rest (see `ffn`). + cpu_share: std::cell::Cell, + pub toks: Vec, + pub trace: bool, +} + +/// The E4M3 value nearest to `x` > 0 (ties to even), as ggml encodes and decodes the NVFP4 block scale. +fn e4m3(x: f32) -> f32 { + if x >= 448.0 { return 448.0; } + if x < 0.015625 { return (x * 512.0).round_ties_even() / 512.0; } + let b = x.to_bits(); + let frac = f32::from_bits((b & 0x7f_ffff) | 0x3f80_0000) - 1.0; + ((1.0 + (frac * 8.0).round_ties_even() / 8.0) * 2f32.powi((b >> 23) as i32 - 127)).min(448.0) +} + +/// Nearest E2M1 value, ties to even, saturated at 6. +fn e2m1(x: f32) -> f32 { + let a = x.abs(); + let r: f32 = if a <= 0.25 { 0.0 } else if a < 0.75 { 0.5 } else if a <= 1.25 { 1.0 } else if a < 1.75 { 1.5 } + else if a <= 2.5 { 2.0 } else if a < 3.5 { 3.0 } else if a <= 5.0 { 4.0 } else { 6.0 }; + r.copysign(x) +} + +/// ggml `round_nvfp4`: every block of 16 values becomes E2M1 values times one E4M3 scale. +pub(crate) fn round_nvfp4(x: &mut [f32]) { + for g in x.chunks_exact_mut(16) { + let amax = g.iter().fold(0f32, |m, v| m.max(v.abs())); + let scale = e4m3((amax / 6.0).max(0.001953125)); + for v in g { *v = e2m1(*v / scale) * scale; } + } +} + +/// (cos, sin) of a position's rotations, with ggml's running product for the angle. +fn rope_tab(pos: usize, n: usize, base: f32) -> Vec<(f32, f32)> { + let scale = base.powf(-2.0 / n as f32); + let mut theta = pos as f32; + (0..n / 2).map(|_| { + let cs = (theta.cos(), theta.sin()); + theta *= scale; + cs + }).collect() +} + +/// NeoX RoPE of one head: dimension i pairs with i + n/2. +fn rope(x: &mut [f32], tab: &[(f32, f32)]) { + let h = tab.len(); + for (i, &(c, s)) in tab.iter().enumerate() { + let (a, b) = (x[i], x[i + h]); + x[i] = a * c - b * s; + x[i + h] = a * s + b * c; + } +} + +/// The routed experts of one token, best first: the bias only picks, the weight is the sigmoid of the logit. +fn route(logits: &[f32], bias: &[f32], n_used: usize) -> Vec<(usize, f32)> { + let mut sel: Vec = (0..logits.len()).collect(); + sel.sort_by(|&a, &b| (logits[b] + bias[b]).total_cmp(&(logits[a] + bias[a])).then(a.cmp(&b))); + sel.truncate(n_used); + sel.into_iter().map(|e| (e, sigmoid(logits[e]))).collect() +} + +/// The `n` best of `scored` (score, index): highest score first, the lower index on a tie. Returns the indices. +fn top_n(mut scored: Vec<(f32, u32)>, n: usize) -> Vec { + if scored.len() > n { + scored.select_nth_unstable_by(n - 1, |a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))); + scored.truncate(n); + } + scored.into_iter().map(|s| s.1).collect() +} + +/// The positions a sparse query at `pos` attends, ascending, or None for all of them. `score` rates a position's +/// routing key and `block_score` a block's mean key. A query attends its first `N_SINK` and last `N_RECENT` +/// positions and the `top_k` best of the candidates between them. On an indexer layer the candidates of a long +/// context are narrowed to the `pool_blocks` best complete blocks first; `pool` carries them to the sparse layers +/// that follow (None: every candidate). +fn select(cfg: &KolibriConfig, indexer: bool, pos: usize, pool: &mut Option>, score: impl Fn(u32) -> f32 + Sync, block_score: impl Fn(u32) -> f32 + Sync) -> Option> { + if pos < N_SINK + N_RECENT + cfg.top_k { return None; } + let last = (pos - N_RECENT) as u32; + if indexer { + let live = (pos + 1) / cfg.block; + *pool = (live > cfg.pool_blocks).then(|| { + let mut b = top_n((0..live as u32).into_par_iter().map(|j| (block_score(j), j)).collect(), cfg.pool_blocks); + b.sort_unstable(); + b.into_iter().flat_map(|j| j * cfg.block as u32..(j + 1) * cfg.block as u32).filter(|&p| p >= N_SINK as u32 && p <= last).collect() + }); + } + let scored: Vec<(f32, u32)> = match pool { + Some(p) if p.len() <= cfg.top_k => p.iter().map(|&c| (0.0, c)).collect(), + Some(p) => p.par_iter().map(|&c| (score(c), c)).collect(), + None => (N_SINK as u32..=last).into_par_iter().map(|c| (score(c), c)).collect(), + }; + let mut picks = top_n(scored, cfg.top_k); + picks.sort_unstable(); + Some((0..N_SINK as u32).chain(picks).chain(last + 1..=pos as u32).collect()) +} + +/// Softmax attention of `n` query heads `q` over the f16 key rows `k` with values `v`, into `o` (zeroed). +fn head_group(q: &[f32], k: &[f16], v: &[f16], hd: usize, scale: f32, o: &mut [f32]) { + let (nk, n) = (k.len() / hd, q.len() / hd); + let mut p = vec![0f32; n * nk]; + dots_h(&mut p, scale, k, q, nk); + for p in p.chunks_exact_mut(nk) { + let mx = p.iter().cloned().fold(f32::MIN, f32::max); + let mut z = 0f32; + for s in p.iter_mut() { + *s = (*s - mx).exp(); + z += *s; + } + for s in p.iter_mut() { *s /= z; } + } + mix_h(o, &p, v, nk); +} + +impl<'a> KolibriModel<'a> { + pub fn new(g: &'a Gguf) -> Result { + let cfg = KolibriConfig::from_gguf(g)?; + let mut layers = Vec::with_capacity(cfg.n_layer); + for il in 0..cfg.n_layer { + let m = |n: &str| Mat::load(g, &format!("blk.{il}.{n}.weight")); + let v = |n: &str| vec_f32(g, &format!("blk.{il}.{n}.weight")); + let ffn = if il < cfg.n_dense { + Ffn::Dense { gate: m("ffn_gate")?, up: m("ffn_up")?, down: m("ffn_down")? } + } else { + Ffn::Moe { + gate_inp: m("ffn_gate_inp")?, + bias: vec_f32(g, &format!("blk.{il}.exp_probs_b.bias"))?, + gexps: m("ffn_gate_exps")?, + uexps: m("ffn_up_exps")?, + dexps: m("ffn_down_exps")?, + gate_sh: m("ffn_gate_shexp")?, + up_sh: m("ffn_up_shexp")?, + down_sh: m("ffn_down_shexp")?, + } + }; + layers.push(Layer { + attn_norm: v("attn_norm")?, + q: m("attn_q")?, + q_norm: v("attn_q_norm")?, + kv: if cfg.kv_src[il] == il { Some((m("attn_k")?, m("attn_v")?, v("attn_k_norm")?)) } else { None }, + out: m("attn_output")?, + post_attn_norm: v("post_attention_norm")?, + ffn_norm: v("ffn_norm")?, + post_ffw_norm: v("post_ffw_norm")?, + ffn, + }); + } + let per_head = vec![vec![vec![]; cfg.n_head_kv]; cfg.n_layer]; + Ok(KolibriModel { + tok_embd: host_mat(g, "token_embd.weight")?, + out_norm: vec_f32(g, "output_norm.weight")?, + out_w: Mat::load(g, "output.weight")?, + k: per_head.clone(), + v: per_head, + first: vec![0; cfg.n_layer], + blocks: vec![vec![]; cfg.n_layer], + cpu_share: std::cell::Cell::new(0.5), + layers, + cfg, + toks: vec![], + trace: std::env::var("STRATA_DS_TRACE").is_ok(), + }) + } + + pub fn reset(&mut self) { + for h in self.k.iter_mut().chain(&mut self.v).flatten() { h.clear(); } + for b in &mut self.blocks { b.clear(); } + self.first.fill(0); + self.toks.clear(); + } + + fn tr(&self, name: &str, il: i32, v: &[f32]) { + if let Ok(dir) = std::env::var("STRATA_DS_DUMP") { + use std::io::Write; + let fname = if il < 0 { format!("{dir}/{name}.f32") } else { format!("{dir}/{name}-{il}.f32") }; + let bytes: Vec = v.iter().flat_map(|x| x.to_le_bytes()).collect(); + std::fs::OpenOptions::new().create(true).append(true).open(fname).unwrap().write_all(&bytes).unwrap(); + } + if self.trace { + let n = v.len(); + let f = |i: usize| format!("{:12.4}", v[i]); + eprintln!("TRACE {name}-{il} [{} {} {} ... {} {} {}] sum={:.6}", f(0), f(1), f(2), f(n - 3), f(n - 2), f(n - 1), v.iter().sum::()); + } + } + + /// Attention output (before its norm) of the consecutive positions from `p0`. `pools` holds each position's key + /// pool from the last indexer layer. + fn attention(&mut self, il: usize, curs: &[Vec], p0: usize, pools: &mut [Option>]) -> Vec { + let cfg = &self.cfg; + let l = &self.layers[il]; + let (nh, nkv, hd, eps, nt, swa, src) = (cfg.n_head, cfg.n_head_kv, cfg.head_dim, cfg.eps, curs.len(), cfg.swa[il], cfg.kv_src[il]); + let xs: Vec<&[f32]> = curs.iter().map(|c| c.as_slice()).collect(); + // One token: the projections share a GPU round trip. + let mats: Vec = std::iter::once(l.q).chain(l.kv.iter().flat_map(|kv| [kv.0, kv.1])).collect(); + let mut proj: Vec> = if nt == 1 { + let y = matvec_many(&mats, xs[0], 0); + let mut at = 0; + mats.iter().map(|m| { at += m.rows; y[at - m.rows..at].to_vec() }).collect() + } else { + mats.iter().map(|m| matvec_rows(m, &xs)).collect() + }; + let tabs: Vec> = if swa { (0..nt).map(|t| rope_tab(p0 + t, hd, cfg.rope_base)).collect() } else { vec![] }; + let mut q = std::mem::take(&mut proj[0]); + let norm_heads = |x: &mut [f32], w: &[f32], per_tok: usize| { + let mut y = vec![0f32; hd]; + for (i, h) in x.chunks_exact_mut(hd).enumerate() { + rms_norm_w(h, w, eps, &mut y); + h.copy_from_slice(&y); + if swa { rope(h, &tabs[i / per_tok]); } + } + }; + if let Some((_, _, k_norm)) = &l.kv { + let (mut k, mut v) = (std::mem::take(&mut proj[1]), std::mem::take(&mut proj[2])); + norm_heads(&mut k, k_norm, nkv); + if nt == 1 { self.tr(if swa { "Kcur_rope" } else { "Kcur_normed" }, il as i32, &k); } + if !swa { + round_nvfp4(&mut k); + round_nvfp4(&mut v); + if nt == 1 { + self.tr("Kcur_nvfp4", il as i32, &k); + self.tr("Vcur_nvfp4", il as i32, &v); + } + } + for (rows, store) in [(&k, &mut self.k[il]), (&v, &mut self.v[il])] { + for (i, h) in rows.chunks_exact(hd).enumerate() { store[i % nkv].extend(h.iter().map(|&x| f16::from_f32(x))); } + } + if !swa { + // The mean routing key of every block that is complete now, summed member by member as ggml does. + let (k0, bs) = (&self.k[il][0], cfg.block); + for j in self.blocks[il].len() / hd..k0.len() / hd / bs { + let mut mean = vec![0f32; hd]; + for row in k0[j * bs * hd..(j + 1) * bs * hd].chunks_exact(hd) { + for (m, x) in mean.iter_mut().zip(row) { *m += x.to_f32(); } + } + for m in &mut mean { *m *= 1.0 / bs as f32; } + round_nvfp4(&mut mean); + self.blocks[il].extend(mean); + } + } + } + norm_heads(&mut q, &l.q_norm, nh); + if nt == 1 { self.tr(if swa { "Qcur_rope" } else { "Qcur_normed" }, il as i32, &q); } + let (ks, vs, first, blocks) = (&self.k[src], &self.v[src], self.first[src], &self.blocks[src]); + let (per, scale) = (nh / nkv, 1.0 / (hd as f32).sqrt()); + // Sparse layers: the keys each query attends (None: all of them). + let sels: Vec>> = if swa { vec![None; nt] } else { + let w = 1.0 / (per as f32 * (hd as f32).sqrt()); + pools.par_iter_mut().enumerate().map(|(t, pool)| { + let rated = |key: &[f16], qr: &Vec| qr.chunks_exact(hd).map(|qh| dot_h(key, qh).max(0.0) * w).sum::(); + let route_q = || { let mut r = q[t * nh * hd..][..per * hd].to_vec(); round_nvfp4(&mut r); r }; + // Made only when the context is longer than the keys a query attends. + let r = std::sync::OnceLock::new(); + select(cfg, cfg.indexer[il], p0 + t, pool, + |c| rated(&ks[0][c as usize * hd..][..hd], r.get_or_init(route_q)), + |j| { let key: Vec = blocks[j as usize * hd..][..hd].iter().map(|&x| f16::from_f32(x)).collect(); rated(&key, r.get_or_init(route_q)) }) + }).collect() + }; + if nt == 1 && let Some(s) = &sels[0] { self.tr("kq_sel", il as i32, &s.iter().map(|&p| p as f32).collect::>()); } + // A chunk whose queries all see a run of consecutive keys (a sliding layer, or a sparse one before it selects) runs on the GPU. + let gpu = nt > 4 && std::env::var_os("STRATA_KOL_CPU_ATTN").is_none(); + // Rows `from..` of a K or V store as the GPU cache: the K/V heads of a position side by side. + let rows = |hs: &Vec>, from: usize| -> Vec { + let mut o = Vec::with_capacity((p0 + nt - from) * nkv * hd); + for r in from - first..p0 + nt - first { + for h in hs { o.extend_from_slice(h[r * hd..(r + 1) * hd].reinterpret_cast()); } + } + o + }; + if gpu && sels.iter().all(|s| s.is_none()) { + let from = if swa { (p0 + 1).saturating_sub(cfg.n_swa).max(first) } else { 0 }; + if let Some(att) = crate::deepseek::mat::attn_rows(&q, &rows(ks, from), &rows(vs, from), p0 - from, nt, nh, nkv, hd, if swa { cfg.n_swa } else { 0 }) { + return matvec_rows(&l.out, &att.chunks_exact(nh * hd).collect::>()); + } + } + // A sparse chunk with selections: each query brings its list of keys (all the earlier ones when it has none). + if gpu && !swa { + let ns = sels.iter().enumerate().map(|(t, s)| s.as_ref().map_or(p0 + t + 1, |s| s.len())).max().unwrap(); + let mut idx = vec![0u32; nt * ns]; + let cnt: Vec = sels.iter().zip(idx.chunks_exact_mut(ns)).enumerate().map(|(t, (s, row))| match s { + Some(s) => { row[..s.len()].copy_from_slice(s); s.len() as i32 } + None => { for (i, x) in row[..p0 + t + 1].iter_mut().enumerate() { *x = i as u32; } (p0 + t + 1) as i32 } + }).collect(); + if let Some(att) = crate::deepseek::mat::attn_sel(&q, &rows(ks, first), &rows(vs, first), &idx, &cnt, nt, nh, nkv, hd) { + return matvec_rows(&l.out, &att.chunks_exact(nh * hd).collect::>()); + } + } + // One task per token and K/V head; the query heads of a K/V head go three at a time (`dots_h`). + let group = if per % 3 == 0 { 3 } else { 1 }; + let mut att = vec![0f32; nt * nh * hd]; + att.par_chunks_mut(per * hd).enumerate().for_each(|(i, o)| { + let (t, g) = (i / nkv, i % nkv); + let pos = p0 + t; + let (gk, gv): (Vec, Vec); + let (k, v) = match &sels[t] { + Some(sel) => { + let gather = |rows: &[f16]| sel.iter().flat_map(|&p| &rows[p as usize * hd..][..hd]).copied().collect(); + (gk, gv) = (gather(&ks[g]), gather(&vs[g])); + (&gk[..], &gv[..]) + } + None => { + let from = if swa { (pos + 1).saturating_sub(cfg.n_swa).max(first) } else { 0 }; + let r = (from - first) * hd..(pos + 1 - first) * hd; + (&ks[g][r.clone()], &vs[g][r]) + } + }; + let qt = &q[i * per * hd..(i + 1) * per * hd]; + for (qh, o) in qt.chunks(group * hd).zip(o.chunks_mut(group * hd)) { head_group(qh, k, v, hd, scale, o); } + }); + if nt == 1 { self.tr("kqv_out", il as i32, &att); } + matvec_rows(&l.out, &att.chunks_exact(nh * hd).collect::>()) + } + + fn ffn(&self, il: usize, cur: &[f32]) -> Vec { + let cfg = &self.cfg; + match &self.layers[il].ffn { + Ffn::Dense { gate, up, down } => { + let y = matvec_many(&[*gate, *up], cur, 0); + let a: Vec = (0..gate.rows).map(|i| silu(y[i]) * y[gate.rows + i]).collect(); + let mut out = vec![0f32; down.rows]; + down.matvec(&a, &mut out); + out + } + Ffn::Moe { gate_inp, bias, gexps, uexps, dexps, gate_sh, up_sh, down_sh } => { + let ne = cfg.n_expert; + // The shared expert rides with the routed ones on the GPU (weight 1); a tensor dump keeps it apart. + let apart = self.trace || std::env::var_os("STRATA_DS_DUMP").is_some() || crate::deepseek::mat::dev_info().is_none(); + let y = if apart { matvec_many(&[*gate_inp, *gate_sh, *up_sh], cur, 0) } else { matvec_many(&[*gate_inp], cur, 0) }; + let (logits, sh) = y.split_at(ne); + self.tr("ffn_moe_logits", il as i32, logits); + let sel = route(logits, bias, cfg.n_used); + if std::env::var_os("STRATA_DS_NOPREFETCH").is_none() { + for &(e, _) in &sel { + for m in [gexps, uexps, dexps] { m.prefetch_expert(e, ne); } + } + } + let nl = dexps.rows / ne; + // Experts resident in VRAM run on the GPU. Of the others, the CPU computes `cpu_share` from the mapped + // file while the GPU uploads and runs the rest, both at once; the share follows the two sides' times. + // `STRATA_DS_CPU_SHARE` fixes it; 0 (also `--fixed-experts`) runs every expert on the GPU, replacing + // the least recently used VRAM slots: the same numerics on every run. + let (share, fixed) = self.share(); + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, true); if x.gpu.is_some() { x } else { x.staged() } }; + let gates: Vec = sel.iter().map(|s| gexps.expert_opt(s.0, ne, share == 0.0)).collect(); + let n_miss = gates.iter().filter(|m| m.gpu.is_none()).count(); + let mut left = (share * n_miss as f32).round() as usize; + let (mut on_gpu, mut on_cpu) = (vec![], vec![]); + for (g, &(e, w)) in gates.into_iter().zip(&sel) { + if g.gpu.is_none() && left > 0 { + left -= 1; + on_cpu.push((g, uexps.expert_host(e, ne), dexps.expert_host(e, ne), w)); + } else { + on_gpu.push((g, e, w)); + } + } + let cpu_side = || { let t = std::time::Instant::now(); (run_experts(&on_cpu, cur, 0.0, nl), t.elapsed().as_secs_f32()) }; + let gpu_side = || { + let t = std::time::Instant::now(); + let mut list: Vec<_> = on_gpu.iter().map(|&(g, e, w)| (if g.gpu.is_some() { g } else { on(gexps, e) }, on(uexps, e), on(dexps, e), w)).collect(); + if !apart { list.push((*gate_sh, *up_sh, *down_sh, 1.0)); } + (run_experts(&list, cur, 0.0, nl), t.elapsed().as_secs_f32()) + }; + let ((a, tg), (b, tc)) = rayon::join(gpu_side, cpu_side); + if !fixed && n_miss > 0 { self.balance(tg, tc); } + let mix: Vec = a.iter().zip(&b).map(|(a, b)| a + b).collect(); + if !apart { return mix; } + self.tr("ffn_moe_out", il as i32, &mix); + let a: Vec = (0..gate_sh.rows).map(|i| silu(sh[i]) * sh[gate_sh.rows + i]).collect(); + let mut s = vec![0f32; down_sh.rows]; + down_sh.matvec(&a, &mut s); + self.tr("ffn_shexp_out", il as i32, &s); + mix.iter().zip(&s).map(|(a, b)| a + b).collect() + } + } + } + + /// The CPU's share of a layer's VRAM-cache misses, and whether it is fixed (no GPU, or set by the user). + fn share(&self) -> (f32, bool) { + static FIXED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let fixed = *FIXED.get_or_init(|| { + let share = std::env::var("STRATA_DS_CPU_SHARE").ok().and_then(|v| v.parse().ok()); + share.or(std::env::var_os("STRATA_FIXED_EXPERTS").map(|_| 0.0)) + }); + if crate::deepseek::mat::dev_info().is_none() { return (1.0, true); } + (fixed.unwrap_or(self.cpu_share.get()).clamp(0.0, 1.0), fixed.is_some()) + } + + /// Move the share toward the side that finished first (`tg`, `tc`: seconds the GPU and the CPU side took). + fn balance(&self, tg: f32, tc: f32) { + if tg + tc > 0.0 { self.cpu_share.set((self.cpu_share.get() + 0.1 * (tg - tc) / (tg + tc)).clamp(0.0, 1.0)); } + } + + /// `ffn` for the tokens of a prefill chunk, token-major. A routed expert is read once and applied to every token + /// that picked it; the experts are split between the GPU and the CPU like the misses in `ffn`. + fn ffn_batch(&self, il: usize, curs: &[Vec]) -> Vec { + let cfg = &self.cfg; + let xs: Vec<&[f32]> = curs.iter().map(|c| c.as_slice()).collect(); + let swiglu = |gate: &Mat, up: &Mat, down: &Mat, x: &[&[f32]]| -> Vec { + let (gy, uy) = (matvec_rows(gate, x), matvec_rows(up, x)); + let a: Vec = gy.iter().zip(&uy).map(|(g, u)| silu(*g) * u).collect(); + matvec_rows(down, &a.chunks_exact(gate.rows).collect::>()) + }; + match &self.layers[il].ffn { + Ffn::Dense { gate, up, down } => swiglu(gate, up, down, &xs), + Ffn::Moe { gate_inp, bias, gexps, uexps, dexps, gate_sh, up_sh, down_sh } => { + let ne = cfg.n_expert; + let (nf, nl) = (gexps.rows / ne, dexps.rows / ne); + let logits = matvec_rows(gate_inp, &xs); + let sels: Vec> = logits.par_chunks_exact(ne).map(|l| route(l, bias, cfg.n_used)).collect(); + // Per expert: the (token, rank in the token's selection) pairs that use it. + let mut by_e: std::collections::BTreeMap> = Default::default(); + for (t, sel) in sels.iter().enumerate() { + for (k, &(e, _)) in sel.iter().enumerate() { by_e.entry(e).or_default().push((t, k)); } + } + if std::env::var_os("STRATA_DS_NOPREFETCH").is_none() { + // In parallel: a read-ahead call waits for the drive's queue. + by_e.keys().collect::>().par_iter().for_each(|&&e| { + for m in [gexps, uexps, dexps] { m.prefetch_expert(e, ne); } + }); + } + let (share, fixed) = self.share(); + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, share == 0.0); if x.gpu.is_some() { x } else { x.staged() } }; + let gates: Vec<(usize, Mat)> = by_e.keys().map(|&e| (e, gexps.expert_opt(e, ne, share == 0.0))).collect(); + let n_miss = gates.iter().filter(|g| g.1.gpu.is_none()).count(); + let mut left = (share * n_miss as f32).round() as usize; + let (mut on_gpu, mut on_cpu) = (vec![], vec![]); + for (e, g) in gates { + if g.gpu.is_none() && left > 0 { + left -= 1; + on_cpu.push((e, g, uexps.expert_host(e, ne), dexps.expert_host(e, ne))); + } else { + on_gpu.push((e, if g.gpu.is_some() { g } else { g.staged() }, on(uexps, e), on(dexps, e))); + } + } + let rows_of = |e: usize| -> Vec<&[f32]> { by_e[&e].iter().map(|&(t, _)| xs[t]).collect() }; + let gpu = || { + let t = std::time::Instant::now(); + // One round trip for all the experts: the per-token weighted sums come back. + // The shared expert rides along as one more expert of every token, with weight 1, in slot `n_used`. + if std::env::var_os("STRATA_KOL_NOCHUNK").is_none() { + let sh = [gate_sh, up_sh, down_sh]; + let col = |i: usize| -> Vec { on_gpu.iter().map(|g| [g.1, g.2, g.3][i]).chain([*sh[i]]).collect() }; + let mut pairs: Vec> = on_gpu.iter().map(|(e, ..)| by_e[e].iter().map(|&(t, k)| (t, k, sels[t][k].1)).collect()).collect(); + pairs.push((0..xs.len()).map(|t| (t, cfg.n_used, 1.0)).collect()); + if let Some(sum) = swiglu_chunk(&col(0), &col(1), &col(2), &pairs, &xs.concat(), cfg.n_used + 1, 0.0) { + return (vec![], Some(sum), t.elapsed().as_secs_f32()); + } + } + // Else two batches for all the experts (gates and ups, then downs). + let n_of = |e: &usize| by_e[e].len(); + let mut x = Vec::with_capacity(2 * on_gpu.iter().map(|(e, ..)| n_of(e)).sum::() * cfg.n_embd); + for (e, ..) in &on_gpu { + for _ in 0..2 { for &(t, _) in &by_e[e] { x.extend_from_slice(xs[t]); } } + } + let y = matvec_rows_many(&on_gpu.iter().flat_map(|(e, g, u, _)| [(*g, n_of(e)), (*u, n_of(e))]).collect::>(), &x); + let mut act = Vec::with_capacity(y.len() / 2); + let mut at = 0; + for (e, ..) in &on_gpu { + let n = n_of(e) * nf; + act.extend(y[at..at + n].iter().zip(&y[at + n..at + 2 * n]).map(|(g, u)| silu(*g) * u)); + at += 2 * n; + } + let dy = matvec_rows_many(&on_gpu.iter().map(|(e, _, _, d)| (*d, n_of(e))).collect::>(), &act); + let mut at = 0; + let out: Vec<(usize, Vec)> = on_gpu.iter().map(|(e, ..)| { at += n_of(e) * nl; (*e, dy[at - n_of(e) * nl..at].to_vec()) }).collect(); + (out, None, t.elapsed().as_secs_f32()) + }; + let cpu = || { + let t = std::time::Instant::now(); + // Each weight row is read once for all the tokens of its expert (`matvec_rows`). + let out: Vec<(usize, Vec)> = on_cpu.par_iter().map(|(e, g, u, d)| (*e, swiglu(g, u, d, &rows_of(*e)))).collect(); + (out, t.elapsed().as_secs_f32()) + }; + let ((a, gsum, tg), (b, tc)) = rayon::join(gpu, cpu); + if !fixed && n_miss > 0 { self.balance(tg, tc); } + // Each token sums its experts in its own selection order, as `ffn` does; the shared expert is added last. + let mut ds: Vec> = sels.iter().map(|s| vec![&[][..]; s.len()]).collect(); + for (e, dy) in a.iter().chain(&b) { + for (&(t, k), d) in by_e[e].iter().zip(dy.chunks_exact(nl)) { ds[t][k] = d; } + } + let mut mix = if gsum.is_some() { vec![0f32; xs.len() * nl] } else { swiglu(gate_sh, up_sh, down_sh, &xs) }; + for (t, m) in mix.chunks_exact_mut(nl).enumerate() { + let mut sum = vec![0f32; nl]; + // An expert of the device's chunk has no row here: its weighted output is in `gsum`. + for (d, &(_, w)) in ds[t].iter().zip(&sels[t]).filter(|(d, _)| !d.is_empty()) { + for j in 0..nl { sum[j] += w * d[j]; } + } + if let Some(g) = &gsum { for j in 0..nl { sum[j] += g[t * nl + j]; } } + for j in 0..nl { m[j] += sum[j]; } + } + mix + } + } + } + + pub fn step(&mut self, tok: u32) -> Vec { + self.forward(&[tok], true) + } + + /// Run `toks` through the model; logits only for the last one. All but the last go in chunks of + /// `STRATA_DS_CHUNK` tokens (default 1024, or 1 with a tensor dump, which covers only the tokens that run alone). A chunk reads each routed expert + /// once, so on a machine whose RAM does not hold the experts a larger chunk means less disk traffic per token. + pub fn prefill(&mut self, toks: &[u32]) -> Vec { + let Some((&last, head)) = toks.split_last() else { return vec![] }; + let dump = self.trace || std::env::var_os("STRATA_DS_DUMP").is_some(); + let chunk: usize = std::env::var("STRATA_DS_CHUNK").ok().and_then(|v| v.parse().ok()).unwrap_or(if dump { 1 } else { 1024 }); + for c in head.chunks(chunk.max(1)) { self.forward(c, false); crate::term::prefilled(c.len()); } + self.step(last) + } + + /// Layer-major pass over consecutive tokens; the logits of the last one when `want`. + fn forward(&mut self, toks: &[u32], want: bool) -> Vec { + let t0 = std::time::Instant::now(); + let (n, nt, eps) = (self.cfg.n_embd, toks.len(), self.cfg.eps); + let p0 = self.toks.len(); + self.toks.extend_from_slice(toks); + let mut xs: Vec> = toks.iter().map(|&t| { + let mut emb = vec![0f32; n]; + self.tok_embd.row_into(t as usize, &mut emb); + emb + }).collect(); + let normed = |xs: &[Vec], w: &[f32]| -> Vec> { + xs.iter().map(|x| { let mut h = vec![0f32; n]; rms_norm_w(x, w, eps, &mut h); h }).collect() + }; + let mut pools: Vec>> = vec![None; nt]; + let mut cur = vec![0f32; n]; + let (mut t_attn, mut t_ffn) = (0f64, 0f64); + for il in 0..self.cfg.n_layer { + let t = std::time::Instant::now(); + let hs = normed(&xs, &self.layers[il].attn_norm); + if nt == 1 { self.tr("attn_norm", il as i32, &hs[0]); } + let att = self.attention(il, &hs, p0, &mut pools); + if nt == 1 { self.tr("attn_out", il as i32, &att); } + for (x, a) in xs.iter_mut().zip(att.chunks_exact(n)) { + rms_norm_w(a, &self.layers[il].post_attn_norm, eps, &mut cur); + for j in 0..n { x[j] += cur[j]; } + } + if nt == 1 { self.tr("ffn_inp", il as i32, &xs[0]); } + t_attn += t.elapsed().as_secs_f64(); + let t = std::time::Instant::now(); + let hs = normed(&xs, &self.layers[il].ffn_norm); + if nt == 1 { self.tr("ffn_norm", il as i32, &hs[0]); } + let f = if nt == 1 { self.ffn(il, &hs[0]) } else { self.ffn_batch(il, &hs) }; + for (x, f) in xs.iter_mut().zip(f.chunks_exact(n)) { + rms_norm_w(f, &self.layers[il].post_ffw_norm, eps, &mut cur); + for j in 0..n { x[j] += cur[j]; } + } + if nt == 1 { self.tr("l_out", il as i32, &xs[0]); } else if self.trace { self.tr("l_out", il as i32, &xs.concat()); } + t_ffn += t.elapsed().as_secs_f64(); + } + // A sliding layer keeps the rows its window still reaches. + let (hd, keep) = (self.cfg.head_dim, self.cfg.n_swa); + for il in (0..self.cfg.n_layer).filter(|&il| self.cfg.swa[il]) { + let rows = self.k[il][0].len() / hd; + if rows > 4 * keep { + for h in self.k[il].iter_mut().chain(&mut self.v[il]) { h.drain(..(rows - keep) * hd); } + self.first[il] += rows - keep; + } + } + let mut logits = vec![]; + if want { + rms_norm_w(&xs[nt - 1], &self.out_norm, eps, &mut cur); + self.tr("result_norm", -1, &cur); + logits = vec![0f32; self.out_w.rows]; + self.out_w.matvec(&cur, &mut logits); + } + if std::env::var_os("STRATA_DS_PROF").is_some() { + use std::sync::atomic::Ordering::Relaxed; + let ex = &crate::deepseek::mat::EX_LOOKUPS; + eprintln!("PROF {nt} at {p0}: {:.0} ms (attn {:.0}, ffn {:.0}), expert cache hit {} miss {}, cpu share {:.2}", + t0.elapsed().as_secs_f64() * 1e3, t_attn * 1e3, t_ffn * 1e3, ex[0].swap(0, Relaxed), ex[1].swap(0, Relaxed), self.cpu_share.get()); + } + logits + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nvfp4_rounding_follows_ggml() { + // Scales: the subnormal floor, a tie in the mantissa (to even), a carry into the exponent, saturation. + for (x, want) in [(0.001953125, 0.001953125), (0.01, 5.0 / 512.0), (1.0625, 1.0), (1.1875, 1.25), (1.96875, 2.0), (1000.0, 448.0), (0.3, 0.3125)] { + assert_eq!(e4m3(x), want, "e4m3({x})"); + } + for (x, want) in [(0.25, 0.0), (0.26, 0.5), (-0.75, -1.0), (1.25, 1.0), (1.75, 2.0), (2.5, 2.0), (3.5, 4.0), (5.0, 4.0), (5.1, 6.0), (-9.0, -6.0)] { + assert_eq!(e2m1(x), want, "e2m1({x})"); + } + // amax 6 gives scale 1: the values round on the E2M1 grid; a block of zeros stays zero. + let mut x = [6.0, -5.1, 3.4, 0.7, 0.2, 1.3, 2.6, -1.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + round_nvfp4(&mut x); + assert_eq!(x[..8], [6.0, -6.0, 3.0, 0.5, 0.0, 1.5, 3.0, -1.5]); + assert!(x[8..].iter().all(|&v| v == 0.0)); + } + + #[test] + fn rope_is_neox() { + let mut x = [1.0, 2.0, 0.0, 0.0]; + rope(&mut x, &rope_tab(1, 4, 10000.0)); + let (c1, s1) = (0.01f32.cos(), 0.01f32.sin()); + assert!((x[0] - 1f32.cos()).abs() < 1e-6 && (x[2] - 1f32.sin()).abs() < 1e-6); + assert!((x[1] - 2.0 * c1).abs() < 1e-6 && (x[3] - 2.0 * s1).abs() < 1e-6); + } + + /// The GPU chunk attention against `head_group` on the same f16 rows, with a window and keys from before the + /// chunk. Skips without a GPU (`STRATA_DS_GPU=1` opens one). + #[test] + fn gpu_window_attention_matches_cpu() { + let (nt, nh, nkv, hd, win, base) = (40usize, 6usize, 2usize, 128usize, 7usize, 5usize); + let mut seed = 1u32; + let mut rnd = |n: usize| -> Vec { (0..n).map(|_| { seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); (seed >> 8) as f32 / (1 << 23) as f32 - 1.0 }).collect() }; + let (q, k, v) = (rnd(nt * nh * hd), rnd((base + nt) * nkv * hd), rnd((base + nt) * nkv * hd)); + let bits = |x: &[f32]| -> Vec { x.iter().map(|&x| f16::from_f32(x).to_bits()).collect() }; + let Some(got) = crate::deepseek::mat::attn_rows(&q, &bits(&k), &bits(&v), base, nt, nh, nkv, hd, win) else { eprintln!("no GPU attention, skipping"); return }; + let (per, scale) = (nh / nkv, 1.0 / (hd as f32).sqrt()); + let mut worst = 0f32; + for t in 0..nt { + for h in 0..nh { + let g = h / per; + let rows = |x: &[f32]| -> Vec { ((base + t + 1).saturating_sub(win)..=base + t).flat_map(|p| x[(p * nkv + g) * hd..][..hd].iter().map(|&x| f16::from_f32(x))).collect() }; + let mut o = vec![0f32; hd]; + head_group(&q[(t * nh + h) * hd..][..hd], &rows(&k), &rows(&v), hd, scale, &mut o); + for (a, b) in o.iter().zip(&got[(t * nh + h) * hd..][..hd]) { worst = worst.max((a - b).abs()); } + } + } + assert!(worst < 5e-3, "GPU window attention differs from the CPU by {worst}"); + } + + /// The GPU attention over key lists against `head_group` on the gathered rows: lists of different lengths, one + /// shorter than a tile of 32 keys. Skips without a GPU (`STRATA_DS_GPU=1` opens one). + #[test] + fn gpu_list_attention_matches_cpu() { + let (nt, nh, nkv, hd, np) = (9usize, 6usize, 2usize, 128usize, 300usize); + let mut seed = 7u32; + let mut next = || { seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); seed >> 8 }; + let mut rnd = |n: usize| -> Vec { (0..n).map(|_| next() as f32 / (1 << 23) as f32 - 1.0).collect() }; + let (q, k, v) = (rnd(nt * nh * hd), rnd(np * nkv * hd), rnd(np * nkv * hd)); + let lens = [1usize, 5, 31, 32, 33, 64, 100, 257, 300]; + let ns = 300; + let mut idx = vec![0u32; nt * ns]; + for (t, row) in idx.chunks_exact_mut(ns).enumerate() { + for (i, x) in row[..lens[t]].iter_mut().enumerate() { *x = ((i * 37 + t * 11) % np) as u32; } + } + let cnt: Vec = lens.iter().map(|&n| n as i32).collect(); + let bits = |x: &[f32]| -> Vec { x.iter().map(|&x| f16::from_f32(x).to_bits()).collect() }; + let Some(got) = crate::deepseek::mat::attn_sel(&q, &bits(&k), &bits(&v), &idx, &cnt, nt, nh, nkv, hd) else { eprintln!("no GPU attention, skipping"); return }; + let (per, scale) = (nh / nkv, 1.0 / (hd as f32).sqrt()); + let mut worst = 0f32; + for t in 0..nt { + for h in 0..nh { + let g = h / per; + let rows = |x: &[f32]| -> Vec { idx[t * ns..][..lens[t]].iter().flat_map(|&p| x[(p as usize * nkv + g) * hd..][..hd].iter().map(|&x| f16::from_f32(x))).collect() }; + let mut o = vec![0f32; hd]; + head_group(&q[(t * nh + h) * hd..][..hd], &rows(&k), &rows(&v), hd, scale, &mut o); + for (a, b) in o.iter().zip(&got[(t * nh + h) * hd..][..hd]) { worst = worst.max((a - b).abs()); } + } + } + assert!(worst < 1e-4, "GPU list attention differs from the CPU by {worst}"); + } + + fn cfg(top_k: usize, pool_blocks: usize) -> KolibriConfig { + KolibriConfig { n_layer: 1, n_ctx: 0, n_embd: 0, n_vocab: 0, n_head: 0, n_head_kv: 0, head_dim: 0, rope_base: 0.0, eps: 0.0, n_expert: 0, n_used: 0, + n_dense: 0, swa: vec![], n_swa: 0, indexer: vec![], kv_src: vec![], top_k, block: 16, pool_blocks } + } + + #[test] + fn sparse_selection() { + let c = cfg(4, 3); + let none = |_: u32| -> f32 { panic!("not scored") }; + // Short context: every key, nothing is scored. + assert_eq!(select(&c, true, 139, &mut None, none, none), None); + // Sinks, the 4 best candidates (ties: the lower position), the recent keys. Candidates are 8..=22 here. + let score = |p: u32| if p == 22 || p == 9 { 2.0 } else if p == 21 { -1.0 } else { 1.0 }; + let mut pool = None; + let sel = select(&cfg(4, 9), true, 150, &mut pool, score, none).unwrap(); + assert_eq!(pool, None); + assert_eq!(sel[..12], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22]); + assert_eq!(sel[12..], (23..=150).collect::>()[..]); + // Long context: 13 complete blocks at position 208; the 3 best blocks (1, 3 and, by the tie, 0) hold the pool. + let block = |j: u32| if j == 3 || j == 1 { 5.0 } else if j == 12 { -1.0 } else { 0.0 }; + let sel = select(&c, true, 208, &mut pool, |p| p as f32, block).unwrap(); + let want: Vec = (8..32).chain(48..64).collect(); + assert_eq!(pool.as_deref(), Some(&want[..])); + assert_eq!(sel[8..12], [60, 61, 62, 63]); + // A sparse layer that is not an indexer selects from the pool it is given. + let sel = select(&c, false, 208, &mut pool, |p| -(p as f32), none).unwrap(); + assert_eq!(sel[8..12], [8, 9, 10, 11]); + assert_eq!(sel.len(), 8 + 4 + 128); + } + + #[test] + fn routing_adds_the_bias_only_to_pick() { + let r = route(&[0.0, 2.0, 1.0, 1.0], &[5.0, 0.0, 0.0, 0.0], 3); + assert_eq!(r.iter().map(|x| x.0).collect::>(), [0, 1, 2]); + assert_eq!(r[0].1, 0.5); + } +} diff --git a/src/kolibri/mod.rs b/src/kolibri/mod.rs new file mode 100644 index 00000000..9dd5a841 --- /dev/null +++ b/src/kolibri/mod.rs @@ -0,0 +1,91 @@ +//! Aleph Alpha Kolibri 1.1 (`kolibri1`): sliding-window layers with RoPE, every fifth layer a sparse layer without +//! positions that attends the best keys of an indexer over K/V rounded to NVFP4, some sparse layers reading the K/V +//! of an earlier one; a dense FFN in the leading layers, then a sigmoid-routed MoE with a shared expert. +//! CPU forward that mirrors llama.cpp `src/models/kolibri1.cpp`; matvecs and routed experts reuse `deepseek::mat`. +pub mod chat; +pub mod forward; + +use crate::gguf::Gguf; +use anyhow::{Context, ensure}; + +pub const ARCH: &str = "kolibri1"; + +/// Keys every sparse query attends: the first `N_SINK` positions and its last `N_RECENT`. +pub const N_SINK: usize = 8; +pub const N_RECENT: usize = 128; + +#[derive(Debug, Clone)] +pub struct KolibriConfig { + pub n_layer: usize, + /// Prompt plus reply limit: `--ctx`, else the trained context. + pub n_ctx: usize, + pub n_embd: usize, + pub n_vocab: usize, + pub n_head: usize, + pub n_head_kv: usize, + pub head_dim: usize, + pub rope_base: f32, + pub eps: f32, + pub n_expert: usize, + pub n_used: usize, + /// Leading layers with a dense FFN instead of the MoE. + pub n_dense: usize, + /// Sliding-window layers (the others are sparse), and the keys a sliding query sees. + pub swa: Vec, + pub n_swa: usize, + /// Sparse layers that choose the pool of keys; the other sparse layers select from the pool of the one before. + pub indexer: Vec, + /// The layer whose K/V a layer attends (itself, or an earlier sparse layer). + pub kv_src: Vec, + /// Keys a sparse query selects, and the pool of a long context: `pool_blocks` blocks of `block` positions. + pub top_k: usize, + pub block: usize, + pub pool_blocks: usize, +} + +impl KolibriConfig { + pub fn from_gguf(g: &Gguf) -> anyhow::Result { + let k = |s: &str| format!("{ARCH}.{s}"); + let u = |s: &str| -> anyhow::Result { Ok(g.get(&k(s))?.as_u64().with_context(|| k(s))? as usize) }; + let f = |s: &str| -> anyhow::Result { g.get(&k(s))?.as_f32().with_context(|| k(s)) }; + let arr_u = |s: &str| -> anyhow::Result> { + g.get(&k(s))?.as_arr().with_context(|| k(s))?.iter().map(|v| Ok(v.as_u64().with_context(|| k(s))? as usize)).collect() + }; + let n_layer = u("block_count")?; + let swa: Vec = arr_u("attention.sliding_window_pattern")?.into_iter().map(|v| v != 0).collect(); + let indexer: Vec = arr_u("attention.indexer.types")?.into_iter().map(|v| v != 0).collect(); + let kv_src = arr_u("attention.kv_source_map")?; + let (head_dim, n_head, n_head_kv) = (u("attention.key_length")?, u("attention.head_count")?, u("attention.head_count_kv")?); + ensure!(swa.len() == n_layer && indexer.len() == n_layer && kv_src.len() == n_layer, "per-layer metadata does not cover {n_layer} layers"); + ensure!(u("expert_gating_func")? == 2 && u("expert_shared_count")? == 1 && u("expert_weights_norm")? == 0, "unsupported Kolibri MoE variant"); + ensure!(head_dim % 16 == 0 && u("attention.value_length")? == head_dim && u("rope.dimension_count")? == head_dim && n_head % n_head_kv == 0, "unsupported Kolibri attention shape"); + let mut seen = false; + for il in 0..n_layer { + let src = kv_src[il]; + ensure!(src <= il && kv_src[src] == src && swa[src] == swa[il] && (!swa[il] || (src == il && !indexer[il])) && (swa[il] || indexer[il] || seen), + "layer {il}: invalid indexer or K/V source"); + seen |= indexer[il]; + } + Ok(KolibriConfig { + n_ctx: crate::ctx_limit(u("context_length")?), + n_layer, + n_embd: u("embedding_length")?, + n_vocab: g.tensors.get("token_embd.weight").context("missing token_embd.weight")?.dims[1] as usize, + n_head, + n_head_kv, + head_dim, + rope_base: f("rope.freq_base")?, + eps: f("attention.layer_norm_rms_epsilon")?, + n_expert: u("expert_count")?, + n_used: u("expert_used_count")?, + n_dense: u("leading_dense_block_count")?, + swa, + n_swa: u("attention.sliding_window")?, + indexer, + kv_src, + top_k: u("attention.indexer.top_k")?, + block: u("attention.indexer.candidate_block_size")?, + pool_blocks: u("attention.indexer.candidate_top_k_blocks")?, + }) + } +} diff --git a/src/kv_turbo.rs b/src/kv_turbo.rs new file mode 100644 index 00000000..a3e45bc1 --- /dev/null +++ b/src/kv_turbo.rs @@ -0,0 +1,248 @@ +//! Faithful TurboQuant KV core: WHT-128 rotation, Lloyd-Max scalar quantizers and the QJL 1-bit residual. +//! +//! Based on arXiv 2504.19874 and the constants of `llama-cpp-turboquant` (`ggml-turbo-quant.c`, +//! `ggml-cuda/turbo-quant.cuh`, seeds 42 and 1042). The rotation is applied on store and to Q on the fly; attention +//! runs entirely in the rotated domain and only the attention output is inverse-rotated, which is what makes this +//! cheaper than inverse-rotating every K/V load. + +/// Seed-42 sign diagonals of the signed WHT, from the reference implementation. +pub const WHT_S1: [f32; 128] = [ + -1.,1.,1.,-1.,-1.,1.,-1.,1.,-1.,-1.,1.,1.,1.,1.,1.,1., + 1.,-1.,1.,-1.,1.,-1.,-1.,1.,1.,1.,-1.,1.,1.,-1.,-1.,-1., + -1.,1.,1.,-1.,1.,1.,-1.,1.,-1.,1.,1.,-1.,-1.,1.,-1.,1., + 1.,1.,1.,-1.,-1.,-1.,-1.,-1.,1.,-1.,1.,1.,1.,1.,-1.,1., + -1.,-1.,1.,-1.,-1.,-1.,1.,-1.,-1.,-1.,1.,-1.,-1.,-1.,1.,1., + 1.,-1.,-1.,1.,1.,1.,-1.,-1.,1.,1.,-1.,1.,1.,-1.,1.,-1., + -1.,1.,1.,-1.,1.,-1.,1.,-1.,1.,1.,1.,1.,-1.,1.,-1.,1., + 1.,-1.,1.,1.,-1.,-1.,-1.,-1.,-1.,1.,1.,-1.,1.,1.,-1.,1., +]; +pub const WHT_S2: [f32; 128] = [ + 1.,1.,1.,1.,-1.,1.,1.,-1.,1.,-1.,-1.,-1.,1.,-1.,-1.,-1., + 1.,1.,-1.,-1.,1.,-1.,1.,-1.,1.,-1.,-1.,1.,-1.,1.,1.,1., + 1.,1.,-1.,-1.,-1.,1.,-1.,-1.,-1.,-1.,-1.,-1.,1.,1.,1.,-1., + 1.,-1.,1.,1.,1.,-1.,-1.,1.,-1.,-1.,-1.,-1.,-1.,-1.,1.,1., + 1.,-1.,1.,-1.,-1.,-1.,-1.,1.,-1.,1.,-1.,1.,-1.,-1.,1.,1., + -1.,1.,-1.,1.,1.,-1.,1.,-1.,-1.,-1.,-1.,1.,-1.,-1.,1.,-1., + 1.,-1.,1.,1.,1.,-1.,-1.,1.,-1.,1.,-1.,1.,1.,-1.,-1.,1., + -1.,1.,-1.,1.,1.,-1.,1.,-1.,1.,-1.,-1.,-1.,-1.,-1.,1.,-1., +]; + +/// Lloyd-Max centroids for N(0, 1/128), i.e. for a unit-L2 128-vector after rotation. +pub const CENTROIDS2: [f32; 4] = [-0.133462, -0.039994, 0.039994, 0.133462]; +pub const CENTROIDS3: [f32; 8] = [ + -0.190207, -0.118786, -0.066822, -0.021663, + 0.021663, 0.066822, 0.118786, 0.190207, +]; +pub const CENTROIDS4: [f32; 16] = [ + -0.241529, -0.182877, -0.143016, -0.111036, -0.083292, -0.058050, -0.034299, -0.011349, + 0.011349, 0.034299, 0.058050, 0.083292, 0.111036, 0.143016, 0.182877, 0.241529, +]; +pub const MID2: [f32; 3] = [-0.086728, 0.0, 0.086728]; +pub const MID3: [f32; 7] = [-0.154496, -0.092804, -0.044243, 0.0, 0.044243, 0.092804, 0.154496]; +pub const MID4: [f32; 15] = [ + -0.212203, -0.162947, -0.127026, -0.097164, -0.070671, -0.046174, -0.022824, 0.0, + 0.022824, 0.046174, 0.070671, 0.097164, 0.127026, 0.162947, 0.212203, +]; + +pub const QJL_CONST: f32 = 1.2533141373155003; // sqrt(pi/2) +const D: usize = 128; +const INV_SQRT: f32 = 0.08838834764831845; // 1 / sqrt(128) + +/// In-place normalized Walsh-Hadamard transform (self-inverse). +pub fn fwht(x: &mut [f32; D]) { + let mut h = 1; + while h < D { + let mut i = 0; + while i < D { + for j in i..i + h { + let (a, b) = (x[j], x[j + h]); + x[j] = a + b; + x[j + h] = a - b; + } + i += 2 * h; + } + h *= 2; + } + for v in x.iter_mut() { *v *= INV_SQRT; } +} + +/// Rotate a vector into the TurboQuant domain: D(s2) * H * D(s1) (s1 applied first), matching the reference. +pub fn rotate_forward(x: &mut [f32; D]) { + for i in 0..D { x[i] *= WHT_S1[i]; } + fwht(x); + for i in 0..D { x[i] *= WHT_S2[i]; } +} + +/// Inverse of `rotate_forward`: D(s1) * H * D(s2) (s2 applied first); H is self-inverse and signs are +-1. +pub fn rotate_inverse(x: &mut [f32; D]) { + for i in 0..D { x[i] *= WHT_S2[i]; } + fwht(x); + for i in 0..D { x[i] *= WHT_S1[i]; } +} + +pub fn bits_centroids(bits: usize) -> &'static [f32] { + match bits { 2 => &CENTROIDS2, 3 => &CENTROIDS3, 4 => &CENTROIDS4, _ => panic!("bits must be 2, 3 or 4") } +} +pub fn bits_mids(bits: usize) -> &'static [f32] { + match bits { 2 => &MID2, 3 => &MID3, 4 => &MID4, _ => panic!("bits must be 2, 3 or 4") } +} + +/// Nearest Lloyd-Max centroid index of a value in a unit-L2 vector. +pub fn nearest(v: f32, bits: usize) -> usize { + let mids = bits_mids(bits); + let mut i = 0; + while i < mids.len() && v >= mids[i] { i += 1; } + i +} + +/// Pack 128 rotated, unit-L2 coordinates into 64 bytes of 4-bit centroid indices (low nibble = even index) +/// plus the reconstruction-corrected norm used at dequant time. Mirrors TheTom's `block_turbo4_0` layout. +pub fn quantize4(x: &[f32; D], l2: f32) -> ([u8; D / 2], f32) { + let mut codes = [0u8; D / 2]; + let mut recon2 = 0f32; + for i in 0..D { + let q = nearest(x[i] / l2, 4); + let c = CENTROIDS4[q]; + recon2 += c * c; + if i % 2 == 0 { codes[i / 2] = q as u8; } else { codes[i / 2] |= (q as u8) << 4; } + } + (codes, l2 / recon2.sqrt().max(1e-6)) +} + +/// Unpack 4-bit codes into 128 rotated values, scaled by the stored corrected norm. +pub fn dequantize4(codes: &[u8; D / 2], norm: f32) -> [f32; D] { + let mut out = [0f32; D]; + for i in 0..D { + let q = if i % 2 == 0 { codes[i / 2] & 15 } else { codes[i / 2] >> 4 }; + out[i] = CENTROIDS4[q as usize] * norm; + } + out +} + +/// Deterministic Gaussian PRNG and QJL projection matrix, matching the reference (LCG + Box-Muller, seed 1042). +struct Prng(u64); +impl Prng { + fn new(seed: u64) -> Self { Self(seed) } + fn next_u(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + self.0 + } + fn normal(&mut self) -> f64 { + let u1 = (self.next_u() >> 11) as f64 / (1u64 << 53) as f64; + let u1 = u1.max(1e-15); + let u2 = (self.next_u() >> 11) as f64 / (1u64 << 53) as f64; + (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos() + } +} + +/// The QJL projection S (128x128, iid N(0,1), seed 1042) as row-major S[i*128+j]. +pub fn qjl_matrix() -> Vec { + let mut p = Prng::new(1042); + let mut m = vec![0f32; D * D]; + for v in &mut m { *v = p.normal() as f32; } + m +} + +/// Signs of S @ r for a residual r (one bit per projection), stored as booleans (true = +1). +pub fn qjl_signs(r: &[f32; D], s: &[f32]) -> Vec { + (0..D).map(|i| { + let mut dot = 0f32; + for j in 0..D { dot += s[i * D + j] * r[j]; } + dot >= 0.0 + }).collect() +} + +/// Reconstruct the estimator `S^T @ signs * QJL_CONST / d * rnorm` used by the legacy 3-bit+QJL mode. +pub fn qjl_reconstruct(signs: &[bool], s: &[f32], rnorm: f32) -> Vec { + let scale = QJL_CONST / D as f32 * rnorm; + let mut out = vec![0f32; D]; + for j in 0..D { + let mut dot = 0f32; + for i in 0..D { dot += s[i * D + j] * if signs[i] { 1f32 } else { -1f32 }; } + out[j] = dot * scale; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wht_is_orthogonal_and_involutive() { + let mut x = [0f32; D]; + for i in 0..D { x[i] = ((i * 37 + 11) % 101) as f32 / 101.0 - 0.5; } + let norm2: f32 = x.iter().map(|v| v * v).sum(); + let mut y = x; + rotate_forward(&mut y); + let yn2: f32 = y.iter().map(|v| v * v).sum(); + assert!((yn2 - norm2).abs() < 1e-3, "rotation must preserve L2: {yn2} vs {norm2}"); + rotate_inverse(&mut y); + for i in 0..D { assert!((y[i] - x[i]).abs() < 1e-4, "round trip at {i}"); } + } + + #[test] + fn centroids_are_sorted_and_symmetric() { + for bits in [2, 3, 4] { + let c = bits_centroids(bits); + assert!(c.windows(2).all(|w| w[0] < w[1])); + assert!((c[0] + c[c.len() - 1]).abs() < 1e-6); + assert_eq!(nearest(0.0, bits), c.len() / 2); + } + } + + #[test] + fn turbo4_encode_decode_random_vectors() { + let mut state = 0x1234_5678_9abc_def0u64; + let mut next = || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((state >> 11) as f32 / (1u64 << 53) as f32) * 2.0 - 1.0 + }; + for _ in 0..8 { + let mut v = [0f32; D]; + for x in &mut v { *x = next(); } + let l2 = v.iter().map(|x| x * x).sum::().sqrt(); + for x in &mut v { *x /= l2; } + let mut rotated = v; + rotate_forward(&mut rotated); + let (codes, norm) = quantize4(&rotated, 1.0); + let back_rot = dequantize4(&codes, norm); + + // Byte layout: even values in low nibbles, odd values in high nibbles. + assert_eq!(codes[0] & 15, nearest(rotated[0], 4) as u8); + assert_eq!(codes[0] >> 4, nearest(rotated[1], 4) as u8); + + let mean_err = rotated.iter().zip(&back_rot).map(|(a, b)| (a - b).abs()).sum::() / D as f32; + assert!(mean_err < 0.05, "4-bit rotated error {mean_err} too high"); + + let mut restored = back_rot; + rotate_inverse(&mut restored); + let dot = v.iter().zip(&restored).map(|(a, b)| a * b).sum::(); + let vnorm = v.iter().map(|x| x * x).sum::().sqrt(); + let cos = dot / (vnorm * restored.iter().map(|x| x * x).sum::().sqrt()); + assert!(cos > 0.99, "round-trip cosine {cos} too low"); + } + } + + #[test] + fn qjl_estimates_inner_products_unbiasedly() { + let s = qjl_matrix(); + let mut p = Prng::new(7); + let mut err = 0f64; + let trials = 64; + for _ in 0..trials { + let mut q = [0f32; D]; + let mut r = [0f32; D]; + for i in 0..D { q[i] = p.normal() as f32 / 8.0; r[i] = p.normal() as f32 / 8.0; } + let target: f64 = q.iter().zip(&r).map(|(a, b)| (*a as f64) * (*b as f64)).sum(); + let signs = qjl_signs(&r, &s); + let rnorm = r.iter().map(|v| v * v).sum::().sqrt(); + let recon = qjl_reconstruct(&signs, &s, rnorm); + let est: f64 = q.iter().zip(&recon).map(|(a, b)| (*a as f64) * (*b as f64)).sum(); + err += (est - target).abs(); + } + // The 1-bit estimator is noisy; require only that it is in the right ballpark, not exact. + let mean = err / (trials as f64); + assert!(mean < 5.0, "mean absolute QJL error {mean} too high"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 54f6a169..c49f1559 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,7 @@ pub mod memory; +pub mod host_attn; pub mod term; +pub mod calibrate; /// `--ctx` when it was given on the command line, else 0. The models outside the main engine (Inkling 2, Hy4, GLM, /// DeepSeek, Gemma 4) read it through [`ctx_limit`]. @@ -14,11 +16,13 @@ pub mod gguf; pub mod quant; pub mod weights; pub mod ops; +pub mod grammar; pub mod tokenizer; pub mod model; pub mod backend; pub mod cuda; pub mod vulkan; +pub mod hip; pub mod gpu_model; pub mod cpu_moe; pub mod expert_cache; @@ -27,10 +31,19 @@ pub mod serve; pub mod chat; pub mod vision; pub mod hf; +pub mod update; pub mod mcp; pub mod deepseek; pub mod gemma4; pub mod glm; pub mod hy4; +pub mod gigachat4; +pub mod kolibri; pub mod inkling2; pub mod ngram; +pub mod raon; +pub mod kv_turbo; + +/// Fixtures shared by the unit tests (a tiny GGUF built in a temp file). +#[cfg(test)] +mod testutil; diff --git a/src/main.rs b/src/main.rs index 39820459..700fc756 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,11 @@ use clap::{Args, Parser, Subcommand}; use anyhow::Context; use rusting_strata::memory; -use rusting_strata::{say, term}; +use rusting_strata::calibrate::{self, KnobSpec, Knobs, Measurement, Objective, SearchConfig, Workload}; +use std::cell::RefCell; +use std::process::{Command, Stdio}; +use std::sync::atomic::AtomicUsize; +use rusting_strata::{detail, say, term}; use rusting_strata::model::{Model, State}; use rusting_strata::{backend, gpu_model::GpuModel}; use rusting_strata::{config::ModelConfig, gguf::Gguf, hf, ops, ops::Sampler, quant::GgmlType, serve, tokenizer::Tokenizer}; @@ -20,11 +24,51 @@ struct Cli { cmd: Option, } +/// A clap parser for a sampling number in `lo..=hi` (`lo` excluded when `open`), the ranges `serve` checks per +/// request: a repeat penalty of 0 or a min-p above 1 otherwise ends every reply in "NaN or infinite logits". +fn range(lo: f32, hi: f32, open: bool) -> impl Fn(&str) -> Result + Clone + Send + Sync + 'static { + move |s| { + let f: f32 = s.parse().map_err(|e| format!("{e}"))?; + let ok = f.is_finite() && (if open { f > lo } else { f >= lo }) && f <= hi; + if ok { Ok(f) } else if hi == f32::MAX { Err(format!("must be a number >= {lo}")) } else { Err(format!("must be a number in {}{lo}, {hi}]", if open { "(" } else { "[" })) } + } +} + #[derive(Args, Clone)] struct Engine { + /// Render the inline progress panel and live metrics instead of the default timestamped speed logs. + #[arg(long)] + pretty: bool, + /// Inline status refresh interval (100ms..=5s; default 500ms). + #[arg(long, value_parser = parse_status_interval)] + status_interval: Option, + /// Show a Braille graph of recent prefill and decode speed. Requires --pretty. + #[arg(long, requires = "pretty")] + graph: bool, /// Run on the GPU (experts that do not fit in VRAM run on the CPU) instead of the CPU reference. #[arg(long)] gpu: bool, + /// Accelerate CPU generation using Q8_K activations. This can change logits and generated tokens. + #[arg(long)] + fast_cpu: bool, + /// Load model weights into anonymous RAM when they fit with 6 GiB to spare. Pin for CUDA transfers when possible. + #[arg(long)] + arena: bool, + /// Pin CPU expert workers to physical cores and reserve the first core for the GPU driver thread (Linux). + #[arg(long)] + pin: bool, + /// Compute some experts missing from VRAM on the CPU during prompt prefill. Can change prompt numerics. + #[arg(long)] + prefill_cpu: bool, + /// Fix the CPU share of missing prefill experts between 0 and 1. By default the share adapts. + #[arg(long, value_parser = parse_cpu_frac)] + cpu_frac: Option, + /// Let CUDA compute one expert from pinned host RAM when at least N experts miss VRAM. Requires --arena. Default 0 disables it. + #[arg(long, default_value_t = 0, value_name = "N", value_parser = parse_host_share)] + host_share: i32, + /// Use the two-pass CPU expert path for decode and prefill. + #[arg(long)] + no_fused: bool, /// GPU context length (KV cache size) in tokens. Inkling 2, Hy4, GLM, DeepSeek and Gemma 4: the prompt plus reply /// limit, the model's trained context when not given (their caches grow with the text). #[arg(long, default_value_t = 4096)] @@ -72,31 +116,34 @@ struct Engine { #[arg(long)] prompt_cache: Option, /// Sampling temperature; 0 is greedy. - #[arg(long, default_value_t = 0.0)] + #[arg(long, default_value_t = 0.0, value_parser = range(0.0, f32::MAX, false))] temp: f32, /// Sample only from the K most likely tokens (0 = all). #[arg(long, default_value_t = 0)] top_k: usize, - #[arg(long, default_value_t = 1.0)] + #[arg(long, default_value_t = 1.0, value_parser = range(0.0, 1.0, true))] top_p: f32, + /// Drop the tokens whose probability is below this times the best one's (llama.cpp min-p; 0 = off). + #[arg(long, default_value_t = 0.0, value_parser = range(0.0, 1.0, false))] + min_p: f32, /// Default presence penalty (OpenAI `presence_penalty`); needs --temp > 0. Qwen recommends 1.5 against loops. - #[arg(long, default_value_t = 0.0)] + #[arg(long, default_value_t = 0.0, value_parser = range(-2.0, 2.0, false), allow_negative_numbers = true)] presence_penalty: f32, /// Default frequency penalty (OpenAI `frequency_penalty`); needs --temp > 0. - #[arg(long, default_value_t = 0.0)] + #[arg(long, default_value_t = 0.0, value_parser = range(-2.0, 2.0, false), allow_negative_numbers = true)] frequency_penalty: f32, /// Repeat penalty (llama.cpp `repeat_penalty`; 1 = off, 1.1 is a usual value) on the tokens among the last /// --penalty-last-n of the reply. Needs --temp > 0. - #[arg(long, default_value_t = 1.0)] + #[arg(long, default_value_t = 1.0, value_parser = range(0.0, 5.0, true))] repeat_penalty: f32, - /// How many of the reply's last tokens --repeat-penalty looks at (0 = off, -1 = the whole reply). + /// How many of the reply's last tokens the repeat, presence and frequency penalties look at (0 = off, -1 = the whole reply). #[arg(long, default_value_t = 64, allow_negative_numbers = true)] penalty_last_n: i32, /// DRY multiplier (0 = off; 0.8 is the usual value): penalizes a token that would repeat a sequence the reply /// already wrote, more the longer the repeat. Stops paragraph loops that a presence penalty does not. Needs --temp > 0. - #[arg(long, default_value_t = 0.0)] + #[arg(long, default_value_t = 0.0, value_parser = range(0.0, 5.0, false))] dry_multiplier: f32, - #[arg(long, default_value_t = 1.75)] + #[arg(long, default_value_t = 1.75, value_parser = range(1.0, 4.0, true))] dry_base: f32, /// Repeats up to this many tokens long are free. #[arg(long, default_value_t = 2)] @@ -104,7 +151,11 @@ struct Engine { /// Random seed for sampling [default: from the clock]. #[arg(long)] seed: Option, - /// CPU threads for expert work [default: calibrated, else physical cores on the GPU, else all logical cores]. + /// `serve`: ignore the sampling fields of requests (temperature, top_k, top_p, min_p, the penalties, DRY), so the + /// flags above hold for clients that send their own and cannot be told not to. + #[arg(long)] + force_sampling: bool, + /// CPU threads for expert work [default: calibrated, else physical cores on Linux with --gpu or --fast-cpu, else all logical cores]. #[arg(long)] threads: Option, /// Match llama.cpp's CPU numerics on the GPU (q8_K activations, f32 prefill attention, f16 decode attention @@ -115,6 +166,19 @@ struct Engine { /// repeat exactly. #[arg(long)] fixed_experts: bool, + /// Decode faster on a card that holds few experts by not running some of them: an expert outside VRAM that a token + /// ranks at R or lower among its picks (0-based, by routed weight; in a verify window, every token that picked + /// it) is neither read nor computed, and its weight is dropped. Experts in VRAM and prompts are unchanged, but the + /// answers differ from the model's (PolyStrata's route tail skip). 0 is off; main engine and Inkling 2 (there not + /// with `--fixed-experts`), not with `--parallel`. + #[arg(long, default_value_t = 0, value_name = "R")] + tail_skip: usize, + /// Qwen3.8 Flash-Next: the GGUF that holds the n-gram table (`per_layer_token_embd`), for a model file without it + /// (`-noPLE`) or to use another quant of the table. Without it, a model with no table takes the one file next to + /// it whose name has "PLE" in it (`STRATA_PLE`). Also the shard of a split model that is in another folder. With + /// a table from `--ple`, one missing shard of a split model (the one that held the old table) is skipped. + #[arg(long)] + ple: Option, /// Host RAM left free for the OS, in MB. The cap is `total RAM - margin` and bounds memory the process owns /// (baked tensors, LoRA factors, `--cache-ram`); the mmapped model is evictable page cache and is not counted. #[arg(long, default_value_t = 512)] @@ -142,11 +206,21 @@ struct Engine { /// Cap tokens inside `` in `chat` and `serve`, then inject `\n\n` so the model answers immediately (0 = unlimited). A request's `thinking_budget` overrides it. #[arg(long, default_value_t = 0)] thinking_budget: usize, + /// `serve`: the reasoning effort of a request that names none, as its `reasoning_effort`: none, off, minimal, + /// low, medium, high, xhigh, max, or a number from 0 to 0.99 (Inkling 2). A request's own value wins. + #[arg(long, value_parser = parse_effort)] + reasoning_effort: Option, /// KV cache format (GPU): f16, q8 (q8_0, half KV memory), q4 (q4_0, quarter KV memory), or q2 (2-bit affine, /// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16). - #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2"])] + #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo4-3", "turbo4-2", "turbo3", "turbo2", "turbo3-2"])] kv: String, - /// GPU backend: cuda or vulkan [default: cuda if it loads, else vulkan]. + /// K cache type; overrides the K half of `--kv`. Supported: f16, q8, q4, q2, turbo4, turbo3, turbo2. + #[arg(long, value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo3", "turbo2"])] + k: Option, + /// V cache type; overrides the V half of `--kv`. Supported: f16, q8, q4, q2, turbo4, turbo3, turbo2. + #[arg(long, value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo3", "turbo2"])] + v: Option, + /// GPU backend: cuda, vulkan or hip [default: cuda if it loads, else vulkan]. #[arg(long)] backend: Option, /// GPU index, or several separated by commas (such as 0,1) to split the layers over those GPUs in proportion to @@ -166,22 +240,108 @@ struct Engine { /// Sequences in GPU memory at once (`serve --parallel`). #[arg(skip)] parallel: usize, - /// Multimodal projector (mmproj) GGUF used by `--image`. + /// Multimodal projector (mmproj) GGUF used by `--image` (default: an `mmproj*.gguf` next to the model; `none` + /// loads no projector). #[arg(long)] mmproj: Option, } -fn set_kv_env(kv: &str) { - match kv { - "q8" | "q4" | "q2" => { - unsafe { std::env::set_var("STRATA_KV", kv) }; - if kv == "q8" { unsafe { std::env::set_var("STRATA_KV_Q8", "1") }; } - else { unsafe { std::env::remove_var("STRATA_KV_Q8") }; } - } - _ => { - unsafe { std::env::remove_var("STRATA_KV") }; - unsafe { std::env::remove_var("STRATA_KV_Q8") }; +/// Resolve the independent K and V cache types. `--kv` supplies both unless `--k`/`--v` override a half. +fn effective_kv(kv: &str, k: Option<&str>, v: Option<&str>) -> anyhow::Result<(String, String)> { + let valid = |s: &str| matches!(s, "f16" | "q8" | "q4" | "q2" | "turbo4" | "turbo3" | "turbo2"); + let base = match kv { + "turbo4-3" => ("turbo4", "turbo3"), + "turbo4-2" => ("turbo4", "turbo2"), + "turbo3-2" => ("turbo3", "turbo2"), + other => (other, other), + }; + let (k, v) = match (k, v) { + (None, None) => base, + (Some(k), None) => (k, base.1), + (None, Some(v)) => (base.0, v), + (Some(k), Some(v)) => (k, v), + }; + anyhow::ensure!(valid(k) && valid(v), "unsupported KV combination K={k}, V={v}"); + Ok((k.to_string(), v.to_string())) +} + +/// Publish the resolved types to both backends. `STRATA_KV_K`/`STRATA_KV_V` are independent; `STRATA_KV` is +/// kept as a symmetric-only alias for code paths that have not been split yet (serve/Vulkan). +fn set_kv_env(k: &str, v: &str) { + unsafe { + std::env::set_var("STRATA_KV_K", k); + std::env::set_var("STRATA_KV_V", v); + if k == v { std::env::set_var("STRATA_KV", k); } + else { std::env::remove_var("STRATA_KV"); } + if k == "q8" || v == "q8" { std::env::set_var("STRATA_KV_Q8", "1"); } + else { std::env::remove_var("STRATA_KV_Q8"); } + } +} + +fn set_kv_env_for(kv: &str, k: Option<&str>, v: Option<&str>) -> anyhow::Result<()> { + let (k, v) = effective_kv(kv, k, v)?; + set_kv_env(&k, &v); + Ok(()) +} + +/// Flags of the other commands that `calibrate` hands to every measurement, so it tunes the run that is used later. +#[derive(clap::Args, Clone, Debug, Default)] +struct CalibSetup { + /// K cache type, as `--k` of the other commands. + #[arg(long, value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo3", "turbo2"])] + k: Option, + /// V cache type, as `--v` of the other commands. + #[arg(long, value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo3", "turbo2"])] + v: Option, + /// The GGUF with the n-gram table, or the shard that is in another folder, as `--ple` of the other commands. + #[arg(long)] + ple: Option, + /// CPU threads for expert work, as `--threads` of the other commands. + #[arg(long)] + threads: Option, + /// As `--cache-ram` of the other commands, in MB. + #[arg(long)] + cache_ram: Option, + /// As `--ram-margin` of the other commands, in MB. + #[arg(long)] + ram_margin: Option, + /// As `--max-ram` of the other commands, in MB. + #[arg(long)] + max_ram: Option, + /// As `--arena` of the other commands. + #[arg(long)] + arena: bool, + /// As `--pin` of the other commands. + #[arg(long)] + pin: bool, + /// As `--prefill-cpu` of the other commands. + #[arg(long)] + prefill_cpu: bool, + /// As `--cpu-frac` of the other commands. + #[arg(long, value_parser = parse_cpu_frac)] + cpu_frac: Option, + /// As `--host-share` of the other commands. + #[arg(long, value_name = "N", value_parser = parse_host_share)] + host_share: Option, +} + +impl CalibSetup { + /// The flags as `bench` takes them. `--ple` is not here: the measurements inherit `STRATA_PLE`. + fn args(&self) -> Vec { + let mut a = vec![]; + let mut val = |flag: &str, v: Option| if let Some(v) = v { a.extend([flag.to_string(), v]); }; + val("--k", self.k.clone()); + val("--v", self.v.clone()); + val("--threads", self.threads.map(|n| n.to_string())); + val("--cache-ram", self.cache_ram.map(|n| n.to_string())); + val("--ram-margin", self.ram_margin.map(|n| n.to_string())); + val("--max-ram", self.max_ram.map(|n| n.to_string())); + val("--cpu-frac", self.cpu_frac.map(|n| n.to_string())); + val("--host-share", self.host_share.map(|n| n.to_string())); + for (flag, on) in [("--arena", self.arena), ("--pin", self.pin), ("--prefill-cpu", self.prefill_cpu)] { + if on { a.push(flag.to_string()); } } + a } } @@ -208,6 +368,14 @@ struct Hosting { /// server is reached through a LAN name while bound to `0.0.0.0`. [default: $STRATA_ALLOWED_HOSTS] #[arg(long, value_delimiter = ',')] allowed_hosts: Vec, + /// Origins whose web pages may call the server from a browser (CORS), comma-separated, or `*` for any. The + /// responses then carry `Access-Control-Allow-*` headers and a preflight `OPTIONS` gets `204` without a key; every + /// other request still needs the key. [default: none, no CORS headers] + #[arg(long, value_delimiter = ',', value_name = "ORIGIN")] + cors_origin: Vec, + /// No chat page at `/`: it answers `404` like any unknown path (only the API is served). + #[arg(long)] + no_webui: bool, /// Most reply tokens a request may ask for (and the default when it asks for none) [default: what the context /// leaves]. #[arg(long)] @@ -225,6 +393,11 @@ struct Hosting { /// configured for this name keep working when another model is loaded. #[arg(long)] alias: Option, + /// Folder for `POST /slots/{id}?action=save|restore` (llama-server's endpoints, admin key): a slot's cached + /// prompt is written to a file there and read back later, also by another server run of the same model and + /// `--kv`. Without it the endpoints answer 501. + #[arg(long, value_name = "DIR")] + slot_save_path: Option, } /// `Own`: a model outside the main engine (`config::OWN_ARCHS`). Its chat answers a request whole, so the token @@ -238,7 +411,7 @@ impl Runner<'_> { /// Feed a prompt; returns the logits after its last token. fn prefill(&mut self, ts: &[u32]) -> anyhow::Result> { match self { - Runner::Cpu(m, st) => Ok(ts.iter().map(|&t| m.step(st, t)).last().unwrap_or_default()), + Runner::Cpu(m, st) => Ok(m.prefill(st, ts, &mut term::prefilled)), Runner::Gpu(g) => g.prefill(ts), Runner::Slot(_) | Runner::Own(_) => anyhow::bail!("prefill on a slot or a model outside the main engine"), } @@ -246,26 +419,35 @@ impl Runner<'_> { /// Feed a chat prompt as a fresh sequence, reusing the earlier request's state for the shared message history /// (GPU; `history` is the prompt without the assistant header, `system` its system and tools block, kept for /// later requests that rewrite the history). Returns the logits and the number of tokens reused. - fn chat(&mut self, tok: &Tokenizer, prompt: &str, history: &str, system: &str) -> anyhow::Result<(Vec, Vec, usize)> { + fn chat(&mut self, tok: &Tokenizer, prompt: &str, history: &str, system: &str, live: &mut term::Live) -> anyhow::Result<(Vec, Vec, usize)> { let ids = tok.encode(prompt)?; let h = tok.encode(history)?; let keep = if ids.starts_with(&h) { h.len() } else { 0 }; let s = if system.is_empty() { vec![] } else { tok.encode(system)? }; let sys = if ids.starts_with(&s) && s.len() <= keep { s.len() } else { 0 }; + live.prefill_total(ids.len().saturating_sub(keep)); + live.prefill_cached(keep); let (logits, reused) = match self { Runner::Gpu(g) => g.prefill_cached(&ids, sys, keep)?, Runner::Slot(c) => c.chat(&ids, sys, keep)?, _ => { self.reset()?; (self.prefill(&ids)?, 0) } }; + live.prefill_cached(reused); Ok((ids, logits, reused)) } - /// Feed a prompt that contains image embeddings as a fresh sequence. - fn chat_image(&mut self, p: &vision::Prompt, embs: &[Vec>]) -> anyhow::Result> { - match self { - Runner::Cpu(m, st) => { *st = State::new(&m.cfg); vision::feed_prompt(m, st, p, embs) } - Runner::Gpu(g) => g.prefill_image(p, embs), - Runner::Slot(_) | Runner::Own(_) => anyhow::bail!("image input is not supported on a serve slot"), - } + /// Feed a prompt that contains image embeddings as a fresh sequence; on the GPU it reuses the earlier request's + /// state as `chat` does, by `p`'s rows and each image's hash (`hashes`), and keeps the state after `keep` rows. + /// Returns the logits and the rows reused. + fn chat_image(&mut self, p: &vision::Prompt, embs: &[Vec>], hashes: &[u64], keep: usize, live: &mut term::Live) -> anyhow::Result<(Vec, usize)> { + live.prefill_total(p.ids.len()); + let (logits, reused) = match self { + Runner::Cpu(m, st) => { *st = State::new(&m.cfg); Ok((vision::feed_prompt(m, st, p, embs)?, 0)) } + Runner::Gpu(g) => g.prefill_image_with(p, embs, hashes, keep, &mut |_| Ok(())), + Runner::Slot(c) => c.chat_image(p, embs, hashes, keep), + Runner::Own(_) => anyhow::bail!("image input on a model outside the main engine"), + }?; + live.prefill_cached(reused); + Ok((logits, reused)) } /// Forget the sequence so far. fn reset(&mut self) -> anyhow::Result<()> { @@ -319,46 +501,178 @@ impl Runner<'_> { let sum = |f: &dyn Fn(&GpuModel) -> usize| g.parts().map(f).sum::(); let st = self.expert_stats().expect("Runner::Gpu has expert stats"); if g.drafts.0 > 0 { - let kind = if g.has_dflash() && g.ngram.is_some() { - "FlashCascade (DFlash + suffix/ngram)" - } else if g.has_dflash() { - "DFlash" - } else if g.has_ext_draft() && g.ngram.is_some() { - "FlashCascade (external draft + suffix/ngram)" - } else if g.has_ext_draft() { - "external draft" - } else if g.ngram.is_some() { - "speculative ngram" - } else { - "MTP" - }; + term::quality(None, Some(g.drafts)); + let kind = gpu_draft_kind(g); say!("{kind} drafts accepted {}/{} ({:.1}%)", g.drafts.1, g.drafts.0, 100.0 * g.drafts.1 as f64 / g.drafts.0 as f64); } - say!("expert hit rate {:.1}% ({} misses), cache swaps {}", 100.0 * st.hits as f64 / (st.hits + st.misses).max(1) as f64, st.misses, st.swaps); - // Issue #34 R1: printed on every run, so a fully resident run reads as a measured 0 in the log instead of - // an absent line. `tokens` counts the token forwards the worker could have been asked about. + term::quality(Some((st.hits, st.misses)), None); + if st.cached { say!("expert hit rate {:.1}% ({} misses), cache swaps {}", 100.0 * st.hits as f64 / (st.hits + st.misses).max(1) as f64, st.misses, st.swaps); } + // With STRATA_VERBOSE a fully resident run prints a measured 0, not an absent line. `tokens` counts the + // token forwards the worker could have been asked about. let tokens = sum(&|p| p.tokens); let busy: f64 = g.parts().map(|p| p.cpu_time.as_secs_f64()).sum(); let stalls = sum(&|p| p.resumed.get()); - say!("worker busy {:.1} µs/token, worker stalls {stalls}", if tokens > 0 { 1e6 * busy / tokens as f64 } else { 0.0 }); + // Stalls are a problem the user can act on (see docs/AMD.md), so a run that had some says so. + if stalls > 0 || term::verbose() { say!("worker busy {:.1} µs/token, worker stalls {stalls}", if tokens > 0 { 1e6 * busy / tokens as f64 } else { 0.0 }); } let mode = if !st.cached { "no expert cache".to_string() } else if st.all_fast { format!("fast path on, {}/{} experts resident", st.resident, st.total) } else { format!("fast path off, {}/{} experts resident", st.resident, st.total) }; - say!("mailbox traffic: {} GPU writes, {} host routing reads ({mode})", sum(&|p| p.mailbox_writes.get()), sum(&|p| p.mailbox_reads.get())); + detail!("mailbox traffic: {} GPU writes, {} host routing reads ({mode})", sum(&|p| p.mailbox_writes.get()), sum(&|p| p.mailbox_reads.get())); for p in g.parts() { if let Some(c) = &p.cache { c.save_profile()?; } } } Ok(()) } } +fn gpu_draft_kind(g: &GpuModel) -> &'static str { + let model = if g.has_dflash() { + serve::DraftModel::DFlash + } else if g.has_ext_draft() { + serve::DraftModel::External + } else { + serve::DraftModel::Mtp + }; + serve::draft_kind(model, serve::ngram_enabled(g.ngram.as_ref())) +} + +/// Chunk variables an `own_calib` call set, with the value each had before it. `serve` loads several models in one +/// process; without restoring them, a model with no calibration runs with the previous model's chunk. +static CALIB_ENV: std::sync::Mutex)>> = std::sync::Mutex::new(Vec::new()); + +/// Undo the chunk variables set by the previous `own_calib` call, before a new model applies its own calibration. +fn restore_calib_env() { + let saved = std::mem::take(&mut *CALIB_ENV.lock().unwrap_or_else(|e| e.into_inner())); + for (key, old) in saved { + // SAFETY: called before a model is loaded, before any thread of that model reads these variables. + unsafe { match old { Some(v) => std::env::set_var(key, v), None => std::env::remove_var(key) } } + } +} + +fn parse_cpu_frac(value: &str) -> Result { + value.parse().ok().filter(|v| (0.0..=1.0).contains(v)) + .ok_or_else(|| "CPU fraction must be between 0 and 1".into()) +} + +/// `--reasoning-effort`: a level name, or Inkling 2's number from 0 to 0.99 (what a request may send). +fn parse_effort(value: &str) -> Result { + const NAMES: [&str; 8] = ["none", "off", "minimal", "low", "medium", "high", "xhigh", "max"]; + let v = value.trim(); + if NAMES.contains(&v) || v.parse::().is_ok_and(|n| (0.0..=0.99).contains(&n)) { return Ok(v.to_string()); } + Err(format!("reasoning effort must be one of {} or a number from 0 to 0.99", NAMES.join(", "))) +} + +fn parse_host_share(value: &str) -> Result { + value.parse().ok().filter(|&n| n == 0 || n >= 2) + .ok_or_else(|| "host share must be 0 or at least 2".into()) +} + impl Engine { + fn status_options(&self) -> anyhow::Result<(Duration, bool, bool)> { + let interval = configured_status_interval(self.status_interval, std::env::var("STRATA_STATUS_INTERVAL").ok().as_deref(), self.pretty)?; + Ok((interval, self.pretty, self.graph)) + } + + fn open_model(&self, path: &Path) -> anyhow::Result { + let g = Gguf::open_with_moe_options(path, rusting_strata::gguf::MoeOptions { + arena: self.arena, pin: self.pin, prefill_cpu: self.prefill_cpu, + cpu_frac: self.cpu_frac, host_share: self.host_share, no_fused: self.no_fused, + })?; + // PTQ1 repacking and tokenization can start Rayon before runner gets control. + if self.fast_cpu && !self.gpu && g.get("general.architecture").ok().and_then(|v| v.as_str()) + .is_some_and(|arch| !rusting_strata::config::OWN_ARCHS.contains(&arch)) { + let path_cal = calibration_path(path, "cuda", &self.device); + let cal = read_calibration(path, &path_cal, false); // `runner` reads it again and says why it is ignored + if let Some(n) = self.worker_threads(&cal, true) { + let _ = rayon::ThreadPoolBuilder::new().num_threads(n).build_global(); + } + } + Ok(g) + } + + fn worker_threads(&self, cal: &serde_json::Value, memory_bound: bool) -> Option { + self.threads.or_else(|| cal["threads"].as_u64().map(|n| n as usize)) + .or_else(|| if memory_bound { physical_cores() } else { None }) + } + + /// The projector for `model`: `--mmproj`, else an `mmproj*.gguf` next to it, else the model itself when it + /// embeds the vision tower; `--mmproj none` gives none. + fn mmproj_for(&self, model: &Path) -> Option { + match &self.mmproj { + Some(p) if p.as_os_str() == "none" => None, + Some(p) => Some(p.clone()), + None => vision::find_sibling(model).or_else(|| vision::embedded(model)), + } + } + /// Hand `--backend`, `--device`, and `--kv` to the DeepSeek, GLM, Gemma 4 and Inkling 2 paths. - fn ds_env(&self) { + fn ds_env(&self) -> anyhow::Result<()> { + if self.gpu { vision::use_gpu(self.backend.clone(), self.device.first().copied().unwrap_or(0)); } // SAFETY: called at the start of a command, before any thread reads these variables. if let Some(b) = &self.backend { unsafe { std::env::set_var("STRATA_DS_BACKEND", b) } } - if self.device != [0] { unsafe { std::env::set_var("STRATA_DS_DEVICES", self.device.iter().map(|d| d.to_string()).collect::>().join(",")) } } + // An explicit `--device 0` is kept too: DeepSeek runs on every CUDA device when the flag is absent. + let given = std::env::args().any(|a| a == "--device" || a.starts_with("--device=")); + if self.device != [0] || given { unsafe { std::env::set_var("STRATA_DS_DEVICES", self.device.iter().map(|d| d.to_string()).collect::>().join(",")) } } if self.fixed_experts { unsafe { std::env::set_var("STRATA_FIXED_EXPERTS", "1") } } // Hy4: every expert on the GPU - if self.kv != "f16" && std::env::var_os("STRATA_KV").is_none() { set_kv_env(&self.kv); } + // `--k`/`--v` must take effect even when `--kv` is left at its f16 default; otherwise an Inkling 2 + // mixed layout silently degrades to plain f16. + if (self.kv != "f16" || self.k.is_some() || self.v.is_some()) && std::env::var_os("STRATA_KV_K").is_none() { + set_kv_env_for(&self.kv, self.k.as_deref(), self.v.as_deref())?; + } + Ok(()) + } + + /// DeepSeek's rayon pool: `--threads`, else one thread a physical core. The CPU computes the experts VRAM + /// misses, memory-bound work that SMT siblings only slow (as on the main engine). Before the first rayon use. + fn ds_threads(&self) { + if let Some(n) = self.threads.or_else(physical_cores) { let _ = rayon::ThreadPoolBuilder::new().num_threads(n).build_global(); } + } + + /// `--vram-margin` for Inkling 2, whose forward keeps its own VRAM state outside the `dev` budget: the weights + /// leave that much of every device free and the expert pool leaves what the K/V growth to the context still needs. + /// Before the model opens the GPUs, so the weight budget is computed with it. The other model families never call + /// this and keep the budget their fraction of free VRAM gives. Also sets `--tail-skip`, which Inkling 2's CPU + /// worker reads (it answers one request at a time). + fn inkling_margin(&self) -> anyhow::Result<()> { + let mb = vram_margins(&self.vram_margin, &self.device)?; + rusting_strata::deepseek::mat::dev_set_margin_mb(&mb); + rusting_strata::cpu_worker::set_tail_skip(self.tail_skip); + Ok(()) + } + + /// The per-device `--vram-margin` (MB) a model of its own forward gets: Some for Inkling 2 and GigaChat 4, None for the others. + fn own_margin(&self, g: &Gguf) -> anyhow::Result>> { + let ink = g.get("general.architecture").ok().and_then(|v| v.as_str()) + .is_some_and(|a| rusting_strata::inkling2::is_arch(a) || a == rusting_strata::gigachat4::ARCH); + Ok(ink.then(|| vram_margins(&self.vram_margin, &self.device)).transpose()?) + } + + /// Models on their own code path never call `Engine::runner`, the only place that reads a calibration file. + /// Apply the measured chunk through the environment those engines actually read. Context and threads are not + /// searched (they are memory choices), so this never touches the global CTX: doing that once made an explicit + /// --ctx look implicit to the main engine's runner. + fn own_calib(&self, model: &Path) { + restore_calib_env(); + let Ok(g) = Gguf::open(model) else { return }; + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or(""); + if !rusting_strata::config::OWN_ARCHS.contains(&arch) { return; } + // Like `runner`, look up the file under the backend that really opened: with no --backend, CUDA may fall + // back to Vulkan, and `calibrate` writes the file under that name. + let Some(&d) = self.device.first() else { return }; + let Ok(b) = backend::open(self.backend.as_deref(), d) else { return }; + let path = calibration_path(model, b.name(), &self.device); + let Ok(bytes) = std::fs::read(&path) else { return }; + let Ok(v) = serde_json::from_slice::(&bytes) else { return }; + let gpu = b.device(); + if !calibration_fits(&v, &gpu) { return; } + if v["bytes"].as_u64().is_some_and(|n| std::fs::metadata(model).is_ok_and(|m| m.len() != n)) { return; } + // GLM reads its own variable, Gemma 4 its own, the others read STRATA_DS_CHUNK. Explicit values win. + if let Some(n) = v["chunk"].as_u64() { + let mut saved = CALIB_ENV.lock().unwrap_or_else(|e| e.into_inner()); + for (k, value) in chunk_env_updates(n as usize, |k| std::env::var_os(k).is_some()) { + saved.push((k, std::env::var_os(k))); + unsafe { std::env::set_var(k, value); } + } + } } /// Fills settings not given on the command line from the model's calibration file, else built-in defaults. @@ -377,7 +691,31 @@ impl Engine { if let Some(n) = num("vram_margin", 0, 1 << 20)? { e.vram_margin = vec![n.to_string()]; } if let Some(n) = num("mtp", 0, 8)? { e.mtp = Some(n); } if let Some(n) = num("chunk", 0, 1 << 20)? { e.chunk = Some(n); } - if !v["kv"].is_null() { e.kv = v["kv"].as_str().filter(|k| ["f16", "q8", "q4", "q2"].contains(k)).context("kv must be f16, q8, q4 or q2")?.into(); } + if let Some(n) = num("parallel", 1, 255)? { + // A load with several slots turned MTP off (`resolve_flags`); with one slot again it takes its default back. + if e.parallel > 1 && n == 1 && v["mtp"].is_null() { e.mtp = None; } + e.parallel = n; + } + if !v["device"].is_null() { + // As `--device` takes it: `0` or `0,1`. + e.device = v["device"].as_str().and_then(|s| s.split(',').map(|d| d.trim().parse().ok()).collect::>>()) + .context("device must be GPU indexes separated by commas, such as 0 or 0,1")?; + } + if !v["kv"].is_null() { + // The values of `--kv`. A new `kv` replaces a `--k`/`--v` pair of the command line. + e.kv = v["kv"].as_str().filter(|k| effective_kv(k, None, None).is_ok()).context("kv must be one of the --kv values, such as f16, q8, q4, q2 or turbo4")?.into(); + (e.k, e.v) = (None, None); + } + if !v["status_interval"].is_null() { + e.status_interval = Some(parse_status_interval(v["status_interval"].as_str().context("status_interval must be a duration string")?).map_err(anyhow::Error::msg)?); + } + if !v["pretty"].is_null() { e.pretty = v["pretty"].as_bool().context("pretty must be true or false")?; } + if !v["graph"].is_null() { + e.graph = v["graph"].as_bool().context("graph must be true or false")?; + } else if !v["status_graph"].is_null() { + // Accept the old key in API load bodies for existing clients. + e.graph = v["status_graph"].as_bool().context("status_graph must be true or false")?; + } Ok(e) } @@ -393,24 +731,20 @@ impl Engine { } } if self.llama_numerics { unsafe { std::env::set_var("STRATA_LLAMA_NUMERICS", "1") } } // read by Gpu::new - set_kv_env(&self.kv); // read by Gpu::new and Vk::new - let open = || self.device.iter().map(|&d| backend::open(self.backend.as_deref(), d)).collect::>>(); + set_kv_env_for(&self.kv, self.k.as_deref(), self.v.as_deref())?; // read by Gpu::new and Vk::new + let open = || backend::open_all(self.backend.as_deref(), &self.device); let bk = match self.gpu.then(open).transpose() { Err(e) if self.cpu_fallback => { say!("no GPU backend ({e:#}), running on the CPU"); None } r => r?, }; let path = calibration_path(model, bk.as_ref().map_or("cuda", |b| b[0].name()), &self.device); - let mut v: serde_json::Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + let mut v = read_calibration(model, &path, true); if let Some(gpu) = bk.as_ref().map(|b| b[0].device()).filter(|gpu| !calibration_fits(&v, gpu)) { say!("warning: {} was measured on {}, not on {gpu}: ignored", path.display(), v["gpu"]); v = serde_json::Value::Null; } - if let Some(n) = v["bytes"].as_u64().filter(|&n| std::fs::metadata(model).is_ok_and(|m| m.len() != n)) { - say!("warning: {} was measured on another file with this name ({n} bytes): ignored", path.display()); - v = serde_json::Value::Null; - } if !v.is_null() { say!("calibration: {}", path.display()); } - else if bk.is_some() { say!("warning: not calibrated on this machine, so the prefill chunk, MTP drafts and the short-prompt threshold are defaults: run `rustingstrata calibrate --model {}` (a few minutes, once per model)", model.display()); } + else if bk.is_some() { say!("note: not calibrated on this machine, the defaults are used. Run `rustingstrata calibrate --model {}` once to tune them.", model.display()); } let get = |k: &str| v[k].as_u64().map(|x| x as usize); if let Some(dp) = &self.draft_model { anyhow::ensure!(dp.exists(), "draft model path does not exist: {}", dp.display()); @@ -418,11 +752,14 @@ impl Engine { } let mut ngram_cfg = self.ngram_config()?; ngram_cfg.n_vocab = m.cfg.n_vocab; + let auto_chunk = self.chunk.is_none(); + let (mtp_given, short_given, threads_given) = (self.mtp.is_some(), self.short.is_some(), self.threads.is_some()); + let mut mtp_cal = false; self.chunk.get_or_insert(get("chunk").unwrap_or(4096)); // The draft count was measured with this draft file (`calibrate --mtp-model/--draft-model`), or with none. let aux = self.aux_model_path().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()); let cal_mtp = get("mtp").filter(|_| v["aux"].as_str() == aux.as_deref()); - if aux.is_some() && self.mtp.is_none() { self.mtp = cal_mtp; } + if aux.is_some() && self.mtp.is_none() { self.mtp = cal_mtp; mtp_cal = cal_mtp.is_some(); } if let Some(df) = &m.cfg.dflash { if self.mtp.is_none() { self.mtp = Some(df.block_size.saturating_sub(1).max(1)); @@ -433,15 +770,31 @@ impl Engine { self.mtp = Some(1); } else if ngram_cfg.is_enabled() && self.mtp.is_none() { self.mtp = Some(0); - } else { - self.mtp.get_or_insert(cal_mtp.unwrap_or(0)); + } else if self.mtp.is_none() { + self.mtp = Some(cal_mtp.unwrap_or(0)); + mtp_cal = cal_mtp.is_some(); } let short = self.short.unwrap_or_else(|| get("short").unwrap_or(32)); // The global pool can be built once; a model loaded later by `serve` keeps the first one's threads. // GPU expert work is memory-bound, so SMT siblings only add contention (6 threads beat 12 on the reference - // 6-core/12-thread Ryzen). CPU-only inference keeps every logical core. - let gpu_threads = bk.is_some().then(physical_cores).flatten(); - if let Some(n) = self.threads.or(get("threads")).or(gpu_threads) { + // 6-core/12-thread Ryzen). `--fast-cpu` is memory-bound the same way (Qwen4-35B-A3B IQ4_XS on a 16-core/32-thread + // Ryzen 9 7945HX: 14.5 tok/s on 16 threads, 11.8 on 32). The F32 reference keeps every logical core. + let fast_cpu = self.fast_cpu && !self.gpu; + let threads = self.worker_threads(&v, bk.is_some() || fast_cpu); + // Every tuning value and where it came from, so a run says what it uses. + let settings = |e: &Self, chunk: usize, mtp: usize| { + // The `--kv` flag alone lies when `--k`/`--v` override a half: say the resolved combination. + let kv = match effective_kv(&e.kv, e.k.as_deref(), e.v.as_deref()) { + Ok((k, v)) if k == v => k, + Ok((k, v)) => format!("{k}/{v}"), + Err(_) => e.kv.clone(), + }; + say!("settings: ctx {}, kv {}, chunk {chunk} ({}), mtp {mtp} ({}), short {short} ({}), threads {} ({}), cache-ram {} MB", + e.ctx, kv, setting_source("chunk", !auto_chunk, get("chunk").is_some()), setting_source("mtp", mtp_given, mtp_cal), + setting_source("short", short_given, get("short").is_some()), + threads.map_or("all".into(), |n| n.to_string()), setting_source("threads", threads_given, get("threads").is_some()), e.cache_ram); + }; + if !fast_cpu && let Some(n) = threads { let _ = rayon::ThreadPoolBuilder::new().num_threads(n).build_global(); } let aux_heads = m.cfg.n_nextn.max(usize::from(m.cfg.dflash.is_some() || m.draft_model.is_some())); @@ -449,11 +802,17 @@ impl Engine { let (notes, _, mtp) = resolve_flags(false, self.parallel, self.mtp(), aux_heads)?; for n in notes { say!("{n}"); } self.mtp = Some(mtp); + settings(self, 0, mtp); return Ok(Runner::Cpu(m, State::new(&m.cfg))); }; let (notes, parallel, mtp) = resolve_flags(true, self.parallel, self.mtp(), aux_heads)?; for n in notes { say!("{n}"); } (self.parallel, self.mtp) = (parallel, Some(mtp)); + // Under --parallel the slots share a step's experts, so one request's skips would depend on the others'. + if self.tail_skip > 0 && parallel > 1 { + say!("--tail-skip {} and --parallel {parallel}: not supported together, running every expert", self.tail_skip); + } + rusting_strata::cpu_worker::set_tail_skip(if parallel > 1 { 0 } else { self.tail_skip }); if self.fixed_experts { unsafe { std::env::set_var("STRATA_FIXED_EXPERTS", "1") } } // read by ExpertCache::new // Before the first weight is uploaded: fail if a pipeline these weight types need does not fit the device's // shared memory (Vulkan; a no-op elsewhere). No pipeline or model buffer exists yet. @@ -477,15 +836,26 @@ impl Engine { Some(s) => Some(s), None => calibrated_split(&v, &self.device, &bk.iter().map(|b| b.device()).collect::>()), }; - let mut g = if self.parallel > 1 { - GpuModel::load_split_margins(m, bk, self.ctx, self.chunk(), &margins, split.as_deref(), 0, self.parallel).context(LOAD_HINT)? - } else { - GpuModel::load_split_margins(m, bk, self.ctx, self.chunk(), &margins, split.as_deref(), mtp, 1).context(LOAD_HINT)? + let (ns, k) = if self.parallel > 1 { (self.parallel, 0) } else { (1, mtp) }; + let mut bk = Some(bk); + let mut g = loop { + match GpuModel::load_split_margins(m, bk.take().unwrap(), self.ctx, self.chunk(), &margins, split.as_deref(), k, ns) { + // The prefill scratch grows with the chunk: when the default or calibrated chunk runs VRAM out or + // leaves it under the margin, halve it (down to 512) and load again on freshly opened devices. + Err(e) if auto_chunk && self.chunk() > 512 && vram_short(&e) => { + let half = self.chunk() / 2; + say!("prefill chunk {} leaves too little VRAM, loading again with {half} (--chunk sets it)", self.chunk()); + self.chunk = Some(half); + bk = Some(backend::open_all(self.backend.as_deref(), &self.device)?); + } + r => break r.context(LOAD_HINT)?, + } }; if ngram_cfg.is_enabled() && self.parallel <= 1 { let tok = Tokenizer::from_gguf(&m.w.g).ok(); g.ngram = Some(rusting_strata::ngram::NgramDrafter::new(ngram_cfg, tok.as_ref())?); } + settings(self, self.chunk(), mtp); g.short = short; g.cache_ram = self.cache_ram << 20; if let Some(p) = &self.prompt_cache { @@ -516,7 +886,7 @@ impl Engine { }) } fn sampler(&self) -> Sampler { - Sampler { temp: self.temp, top_k: self.top_k, top_p: self.top_p, rng: seed(self.seed), + Sampler { temp: self.temp, top_k: self.top_k, top_p: self.top_p, min_p: self.min_p, rng: seed(self.seed), presence: self.presence_penalty, frequency: self.frequency_penalty, repeat: self.repeat_penalty, last_n: self.penalty_last_n, dry_mult: self.dry_multiplier, dry_base: self.dry_base, dry_allowed: self.dry_allowed_length, ..Sampler::greedy() } @@ -530,6 +900,15 @@ impl Engine { let Some(arch) = g.get("general.architecture").ok().and_then(|v| v.as_str()) else { return }; if !rusting_strata::config::OWN_ARCHS.contains(&arch) { return; } let mtp = self.mtp.is_some_and(|n| n > 0) || self.mtp_model.is_some(); + // GigaChat 4 drafts one token a step with the MTP block of its own file. + if arch == rusting_strata::gigachat4::ARCH { + rusting_strata::gigachat4::MTP.store(self.mtp.is_some_and(|n| n > 0), std::sync::atomic::Ordering::Relaxed); + if self.mtp.is_some_and(|n| n > 1) { say!("warning: '{arch}' models draft one MTP token a step: --mtp counts as 1"); } + if self.mtp_model.is_some() || self.draft_model.is_some() || self.spec_type != "none" { + say!("warning: '{arch}' models draft only with the MTP block of the file: --mtp-model, --draft-model and --spec-type are ignored"); + } + return; + } // Inkling 2 drafts with a DSpark file (`--draft-model`) and with n-grams (`--spec-type`); it has no MTP head. if rusting_strata::inkling2::is_arch(arch) { if mtp { say!("warning: '{arch}' models have no MTP drafts: --mtp and --mtp-model are ignored"); } @@ -539,6 +918,47 @@ impl Engine { } } +fn configured_status_interval(cli: Option, env: Option<&str>, pretty: bool) -> anyhow::Result { + if let Some(interval) = cli { return Ok(interval); } + // The plain speed lines keep the 2 s step they had before the panel. + let default = Duration::from_millis(if pretty { 500 } else { 2000 }); + env.map(parse_status_interval).transpose().map(|v| v.unwrap_or(default)).map_err(anyhow::Error::msg) +} + +fn parse_status_interval(s: &str) -> Result { + let (number, unit) = if let Some(v) = s.strip_suffix("ms") { (v, "ms") } + else if let Some(v) = s.strip_suffix('s') { (v, "s") } + else { return Err(format!("invalid status interval {s:?}: use milliseconds (e.g. 250ms) or seconds (e.g. 1s)")); }; + let n: u64 = number.parse().map_err(|_| format!("invalid status interval {s:?}: expected a positive duration"))?; + let ms = if unit == "s" { n.checked_mul(1000).ok_or_else(|| "status interval is too large".to_string())? } else { n }; + if !(100..=5000).contains(&ms) { return Err(format!("status interval must be from 100ms to 5s; got {s:?}")); } + Ok(Duration::from_millis(ms)) +} + +#[cfg(test)] +mod status_interval_tests { + use super::{configured_status_interval, parse_status_interval}; + use std::time::Duration; + + #[test] + fn parses_supported_intervals_and_rejects_out_of_range_values() { + for (input, ms) in [("100ms", 100), ("250ms", 250), ("500ms", 500), ("1s", 1000), ("5s", 5000)] { + assert_eq!(parse_status_interval(input).unwrap(), Duration::from_millis(ms)); + } + for input in ["99ms", "5001ms", "", "1m", "250", "0s", "1.5s"] { + assert!(parse_status_interval(input).is_err(), "{input:?}"); + } + } + + #[test] + fn defaults_to_500ms_with_the_panel_and_cli_overrides_the_environment() { + assert_eq!(configured_status_interval(None, None, true).unwrap(), Duration::from_millis(500)); + assert_eq!(configured_status_interval(None, None, false).unwrap(), Duration::from_secs(2)); + assert_eq!(configured_status_interval(None, Some("1s"), false).unwrap(), Duration::from_secs(1)); + assert_eq!(configured_status_interval(Some(Duration::from_millis(250)), Some("bad"), false).unwrap(), Duration::from_millis(250)); + } +} + /// Per-device VRAM margins in MB from `--vram-margin`: one value for every device, one per device like `512,256`, /// or one per GPU index like `0:512,1:256`. The result is in the order of `devices`. fn vram_margins(spec: &[String], devices: &[usize]) -> anyhow::Result> { @@ -581,6 +1001,8 @@ fn vram_margins(spec: &[String], devices: &[usize]) -> anyhow::Result struct ImageInput { grids: Vec<(usize, usize)>, embeddings: Vec>>, + /// Each image's source and projector, hashed: the prefix cache keys image rows by it. + hashes: Vec, } /// Physical cores, not SMT siblings: the CPU expert workers are memory-bound, and oversubscribing them with the @@ -612,20 +1034,30 @@ fn cpu_topology_groups(dir: &std::path::Path) -> usize { groups.len() } -/// Decode and encode every `--image` with the projector at `mmproj`. +/// Decode and encode every `--image` with the projector at `mmproj`. The last call's encodings are kept by source: +/// a chat client sends its images again with every turn. fn load_images(mmproj: &Path, images: &[String]) -> anyhow::Result { - let projector = VisionProjector::open(mmproj)?; - let mut grids = Vec::with_capacity(images.len()); - let mut embeddings = Vec::with_capacity(images.len()); + use std::hash::{Hash, Hasher}; + type Encoded = (u64, (usize, usize), Vec>); + static LAST: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let mut last = std::mem::take(&mut *LAST.lock().unwrap_or_else(|e| e.into_inner())); + let mut projector = None; + let mut kept = Vec::with_capacity(images.len()); for src in images { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (mmproj, src).hash(&mut h); + let key = h.finish(); + if let Some(i) = last.iter().position(|e| e.0 == key) { kept.push(last.swap_remove(i)); continue; } + let projector = match &mut projector { Some(p) => p, None => projector.insert(VisionProjector::open(mmproj)?) }; let img = vision::load_image(src)?; let t0 = Instant::now(); - let (feats, nx, ny) = vision::encode_image(&projector, &img)?; + let (feats, nx, ny) = vision::encode_image(projector, &img)?; say!("image: {nx}x{ny} tokens encoded in {:.1} s", t0.elapsed().as_secs_f64()); - grids.push((nx, ny)); - embeddings.push(feats); + kept.push((key, (nx, ny), feats)); } - Ok(ImageInput { grids, embeddings }) + let input = ImageInput { grids: kept.iter().map(|e| e.1).collect(), embeddings: kept.iter().map(|e| e.2.clone()).collect(), hashes: kept.iter().map(|e| e.0).collect() }; + *LAST.lock().unwrap_or_else(|e| e.into_inner()) = kept; + Ok(input) } /// Expand `` placeholders into the projector's vision tokens and assign M-RoPE positions. @@ -668,6 +1100,12 @@ fn seed(s: Option) -> u64 { .wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1 } +/// Whether a load failed for VRAM: the driver's out-of-memory error (CUDA, HIP, Vulkan) or `GpuModel::load`'s check +/// that the loaded model leaves the margin free. +fn vram_short(e: &anyhow::Error) -> bool { + let s = format!("{e:#}").to_lowercase(); + ["out_of_memory", "out of memory", "outofmemory", "out_of_device_memory", "of vram free, under the"].iter().any(|k| s.contains(k)) +} const LOAD_HINT: &str = "loading the model onto the GPU failed (if VRAM ran out: lower --ctx, add --kv q8, or close programs using VRAM)"; /// Settle the flag combinations that cannot all take effect: an invalid request (`--parallel` outside 1..=255) is an @@ -704,6 +1142,16 @@ fn calibration_path(model: &Path, backend: &str, devices: &[usize]) -> PathBuf { rusting_strata::expert_cache::cache_dir().join(format!("strata-{stem}{sfx}.json")) } +/// The calibration file at `path`, or null when it was measured on another file with the model's name (`warn` says so). +fn read_calibration(model: &Path, path: &Path, warn: bool) -> serde_json::Value { + let v: serde_json::Value = std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + if let Some(n) = v["bytes"].as_u64().filter(|&n| std::fs::metadata(model).is_ok_and(|m| m.len() != n)) { + if warn { say!("warning: {} was measured on another file with this name ({n} bytes): ignored", path.display()); } + return serde_json::Value::Null; + } + v +} + /// The layer shares of `--split` or, without the flag, of `STRATA_SPLIT`, for `n` devices (`None`: not given, or one /// device). fn split_arg(flag: Option<&str>, n: usize) -> anyhow::Result>> { @@ -720,29 +1168,44 @@ fn calibrated_split(v: &serde_json::Value, devices: &[usize], gpus: &[String]) - (l.len() == devices.len()).then_some(l) } -/// The splits one move away from `cur` (layers per device): `step` layers moved between two neighbouring devices, -/// each device keeping at least one layer. -fn split_moves(cur: &[usize], step: usize) -> Vec> { - let mut v = vec![]; - for i in 0..cur.len().saturating_sub(1) { - for (a, b) in [(i, i + 1), (i + 1, i)] { - if cur[a] > step { - let mut c = cur.to_vec(); - (c[a], c[b]) = (c[a] - step, c[b] + step); - v.push(c); - } +/// Whether calibration file `v` may be used on `gpu` (`Backend::device`). A file names the GPU it was measured on; +/// one without a name (written before that was recorded, or the driver gave none) is accepted. +fn calibration_fits(v: &serde_json::Value, gpu: &str) -> bool { + v["gpu"].as_str().is_none_or(|g| g.is_empty() || gpu.is_empty() || g == gpu) +} + +/// Values a calibrated chunk may write to the environment. An explicit value set by the user must win, so the +/// caller skips names that are already present. +/// OpenAI stream deltas for tool calls (issue 122): a call not sent yet goes out with its id and name, then the part +/// of its arguments past what `sent` holds. Arguments that do not start with what was sent add nothing. +fn call_deltas(calls: &[(String, String)], sent: &mut Vec, i: impl std::fmt::Display) -> Vec { + let mut v = Vec::new(); + for (k, (f, a)) in calls.iter().enumerate() { + if k == sent.len() { + v.push(json!({"index": k, "id": format!("call_{i}_{k}"), "type": "function", "function": {"name": f, "arguments": ""}})); + sent.push(String::new()); + } + if a.len() > sent[k].len() && a.starts_with(sent[k].as_str()) { + v.push(json!({"index": k, "function": {"arguments": &a[sent[k].len()..]}})); + sent[k] = a.clone(); } } v } -/// Whether calibration file `v` may be used on `gpu` (`Backend::device`). A file names the GPU it was measured on; -/// one without a name (written before that was recorded, or the driver gave none) is accepted. -fn calibration_fits(v: &serde_json::Value, gpu: &str) -> bool { - v["gpu"].as_str().is_none_or(|g| g.is_empty() || gpu.is_empty() || g == gpu) +fn chunk_env_updates(n: usize, present: impl Fn(&str) -> bool) -> Vec<(&'static str, String)> { + if !(1..=(1 << 20)).contains(&n) { return vec![]; } + ["STRATA_DS_CHUNK", "STRATA_GLM_CHUNK", "STRATA_G4_CHUNK"].into_iter() + .filter(|k| !present(k)) + .map(|k| (k, n.to_string())) + .collect() } impl Engine { + fn load_inference_model<'a>(&self, g: &'a Gguf, aux: Option<&'a Gguf>) -> anyhow::Result> { + Model::load_with_matvec(g, aux, &self.lora_specs(), self.fast_cpu && !self.gpu) + } + pub fn lora_specs(&self) -> Vec<(String, f32)> { self.lora.iter().map(|s| { if let Some(idx) = s.rfind(':') { @@ -859,7 +1322,7 @@ fn bench_record(meta: &BenchMeta, results: &[BenchResult], expert: Option<&Exper v["results"] = json!(results); if let Some(e) = expert { v["expert"] = json!({ - "hit_rate_pct": round1(100.0 * e.hits as f64 / (e.hits + e.misses).max(1) as f64), + "hit_rate_pct": if e.hits + e.misses == 0 { 100.0 } else { round1(100.0 * e.hits as f64 / (e.hits + e.misses) as f64) }, "misses": e.misses, "swaps": e.swaps, "resident": e.resident, @@ -913,8 +1376,20 @@ enum Cmd { #[command(flatten)] engine: Engine, }, - /// OpenAI-compatible HTTP server: POST /v1/chat/completions (streaming or not), GET /v1/models. - /// One request at a time; temperature, top_k, top_p and seed are honored, greedy when left out. A request that + /// Print the tokens `serve` answered, by model and by API key name, over all runs. The totals are kept in + /// usage.json next to the default models folder; delete that file to start again. + #[command(alias = "statistics")] + Stats, + /// Replace this binary with the newest GitHub release (Linux and Windows x86_64). The old one is kept as + /// `.old`. + Update { + /// Only say whether a newer release is out. + #[arg(long)] + check: bool, + }, + /// OpenAI-compatible HTTP server: POST /v1/chat/completions (streaming or not), GET /v1/models, and the Anthropic + /// POST /v1/messages. One request at a time unless `--parallel`; temperature, top_k, top_p and seed are honored, + /// greedy when left out. A request that /// extends the previous one's messages prefills only the new part (usage.prompt_tokens_details.cached_tokens); /// one that keeps only the system prompt and tools (a compacted conversation) starts after them. /// GET / is a chat page that can also switch between the models in `--models-dir` (POST /api/load), so the @@ -945,13 +1420,22 @@ enum Cmd { #[command(flatten)] engine: Engine, }, - /// Measure prefill chunk, MTP drafts per step and the short-prompt threshold on this machine (GPU) and write - /// them to the model's calibration file, which later runs read unless flags override. + /// Benchmark a budgeted search over prefill chunk, MTP drafts and the short-prompt threshold on this machine, + /// and write the best point to the model's calibration file, which later runs read unless flags override. Calibrate { + /// Render the inline calibration progress and metrics instead of the default timestamped speed logs. + #[arg(long)] + pretty: bool, + /// Inline status refresh interval (100ms..=5s; default 500ms). + #[arg(long, value_parser = parse_status_interval)] + status_interval: Option, + /// Show a Braille graph of recent calibration speeds. Requires --pretty. + #[arg(long, requires = "pretty")] + graph: bool, /// The GGUF to calibrate, or a folder: every model in it (and its subfolders, as the chat page lists them) - /// is calibrated in turn. + /// is calibrated in turn. With the `spec` subcommand this may be omitted in favour of its own --model. #[arg(long)] - model: PathBuf, + model: Option, /// GPU context length used while measuring and assumed for the results. #[arg(long, default_value_t = 4096)] ctx: usize, @@ -971,8 +1455,10 @@ enum Cmd { #[arg(long, value_name = "PATH:SCALE", action = clap::ArgAction::Append)] lora: Vec, /// KV cache format to calibrate with (q8/q4/q2 leave more VRAM for experts), as `--kv` of the runs that use it. - #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2"])] + #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo4-3", "turbo4-2", "turbo3", "turbo2", "turbo3-2"])] kv: String, + #[command(flatten)] + setup: CalibSetup, /// Accepted for symmetry with the other commands: calibration always runs on the GPU. #[arg(long, hide = true)] gpu: bool, @@ -983,6 +1469,48 @@ enum Cmd { /// calibrate the drafts with it. #[arg(long)] draft_model: Option, + + /// Hard cap on benchmark samples: the search stops when this many have been taken, or earlier when it has + /// converged. One sample benchmarks the whole workload matrix (all --pp lengths of one task). + #[arg(long, default_value_t = 24)] + samples: usize, + /// Benchmark repetitions inside each sample; their mean is used and run-to-run spread is reported. + #[arg(long, default_value_t = 2, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..))] + reps: usize, + /// Extra discarded run before each sample (off by default: it loads the model a second time). + #[arg(long, default_value_t = 0)] + warmup: usize, + /// Prompt depths of the workload matrix, comma-separated. + #[arg(long, value_delimiter = ',', default_value = "128,512,2048", value_parser = clap::builder::RangedU64ValueParser::::new().range(1..))] + pp: Vec, + /// Tokens greedily decoded per workload. + #[arg(long, default_value_t = 64)] + tg: usize, + /// Prefill chunk sizes to search, comma-separated. [default: 256,512,1024,2048,4096] + #[arg(long, value_delimiter = ',')] + chunk_values: Option>, + /// Extra task corpus: `user:PATH` (a prompt file), `coding` or `prose`. Repeatable. + #[arg(long)] + task: Vec, + /// Deterministic seed for the low-discrepancy coarse sweep and the search. + #[arg(long, default_value_t = 1)] + seed: u64, + /// Print the derived knob space, workload matrix and sample plan, then exit without benchmarking. + #[arg(long)] + dry_run: bool, + /// Per-sample time limit in seconds (0 = no limit). A timeout is recorded as a failed sample. + #[arg(long, default_value_t = 0)] + timeout: u64, + /// Time limit of the search in minutes (0 = none): no sample starts after it, and the best point so far is + /// written. The baseline comes before it. + #[arg(long, default_value_t = 30)] + minutes: u64, + /// Keep the full benchmark report and sample trace in this directory. + #[arg(long)] + out: Option, + /// Sweep spec-type and draft settings for different tasks instead of tuning the engine knobs. + #[command(subcommand)] + sub: Option, }, /// Check that every Vulkan pipeline this model needs fits the device's `maxComputeSharedMemorySize`, naming the /// kernel, specialization, bytes needed and limit when one does not; exits non-zero on overflow. No model is @@ -1002,11 +1530,11 @@ enum Cmd { Bench { #[arg(long)] model: PathBuf, - #[arg(long, value_delimiter = ',', default_value = "512,4096")] + #[arg(long, value_delimiter = ',', default_value = "512,4096", value_parser = clap::builder::RangedU64ValueParser::::new().range(1..))] pp: Vec, #[arg(long, default_value_t = 128)] tg: usize, - #[arg(long, default_value_t = 3)] + #[arg(long, default_value_t = 3, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..))] reps: usize, #[arg(long, value_parser = json_out_path)] json_out: Option, @@ -1061,19 +1589,215 @@ enum Cmd { }, } +/// `rustingstrata calibrate spec …`: sweep speculative-decoding settings per task. +#[derive(Subcommand, Clone, Debug)] +enum CalibrateSub { + /// Measure every combination of spec type, draft count and n-gram size on each task corpus, and store the best + /// per task in the calibration file. Inkling 2 uses these with (or instead of) a DSpark draft; the main engine + /// combines them with its MTP head. + Spec { + /// The model to sweep (a folder is not accepted: the sweep writes one calibration file). + #[arg(long)] + model: PathBuf, + /// Tasks: `prose`, `coding`, `user:PATH` (a prompt file). Repeatable. + #[arg(long, value_delimiter = ',', default_value = "prose,coding")] + tasks: Vec, + /// Spec types: none, suffix, ngram-simple, ngram-map-k, ngram-map-k4v, ngram-mod, ngram-cache. + #[arg(long, value_delimiter = ',', default_value = "none,ngram-simple,ngram-mod,ngram-cache")] + spec_types: Vec, + /// Maximum drafts verified per step. + #[arg(long, value_delimiter = ',', default_value = "4,8,16")] + draft_max: Vec, + /// N-gram lookup key lengths. + #[arg(long, value_delimiter = ',', default_value = "3,6,12")] + ngram_n: Vec, + /// MTP draft counts to combine with the lookup (main engine only). + #[arg(long, value_delimiter = ',', default_value = "0,2")] + mtp: Vec, + #[arg(long)] + draft_model: Option, + #[arg(long)] + backend: Option, + #[arg(long, value_delimiter = ',', default_value = "0")] + device: Vec, + #[arg(long, default_value_t = 4096)] + ctx: usize, + #[arg(long, default_value = "512")] + vram_margin: Vec, + #[arg(long, value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo4-3", "turbo4-2", "turbo3", "turbo2", "turbo3-2"], default_value = "f16")] + kv: String, + #[command(flatten)] + setup: CalibSetup, + #[arg(long, default_value_t = 512)] + pp: usize, + #[arg(long, default_value_t = 128)] + tg: usize, + #[arg(long, default_value_t = 3)] + reps: usize, + #[arg(long, default_value_t = 24)] + samples: usize, + #[arg(long, default_value_t = 1)] + seed: u64, + #[arg(long)] + out: Option, + #[arg(long)] + dry_run: bool, + }, +} + fn main() { - if let Err(e) = start() { + no_power_throttling(); + let r = start(); + if let Some(line) = rusting_strata::cpu_worker::tail_skip_report() { say!("{line}"); } + if let Err(e) = r { say!("error: {e:#}"); std::process::exit(1); } } +/// Windows 11 runs a process whose console window is not in front in "efficiency mode" (EcoQoS): lower clocks, +/// efficiency cores and coarse timers, so decode slowed down whenever the terminal was in the background. Opt out +/// of execution speed throttling and of the timer resolution being ignored. +#[cfg(windows)] +fn no_power_throttling() { + #[repr(C)] + struct State { version: u32, control: u32, state: u32 } + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetCurrentProcess() -> *mut core::ffi::c_void; + fn SetProcessInformation(p: *mut core::ffi::c_void, class: i32, info: *mut core::ffi::c_void, size: u32) -> i32; + } + // ProcessPowerThrottling = 4; PROCESS_POWER_THROTTLING_EXECUTION_SPEED 1 | IGNORE_TIMER_RESOLUTION 4, state 0 = off. + // Fails harmlessly before Windows 10 1709 (execution speed) and Windows 11 (timer resolution). + let mut s = State { version: 1, control: 1 | 4, state: 0 }; + if unsafe { SetProcessInformation(GetCurrentProcess(), 4, (&raw mut s).cast(), size_of::() as u32) } == 0 { + s.control = 1; + unsafe { SetProcessInformation(GetCurrentProcess(), 4, (&raw mut s).cast(), size_of::() as u32) }; + } +} +#[cfg(not(windows))] +fn no_power_throttling() {} + +/// `--preset FILE` of any command, and the flags it set that the command line did not (`settings_line`). +static PRESET: std::sync::OnceLock<(PathBuf, Vec)> = std::sync::OnceLock::new(); + +/// `--preset FILE`: the preset's flags, put before the command line's own, which win over them. A preset has +/// `name = value` lines with the names of the flags (`ctx = 32768`, `kv = "q8"`, `fixed_experts = true`, +/// `device = [0, 1]`) and `#` comments. A key that is a flag of another command is skipped, so one preset serves +/// `serve`, `chat` and `calibrate`; a key that is no flag at all is an error. +fn expand_preset(args: Vec) -> anyhow::Result> { + let s: Vec = args.iter().map(|a| a.to_string_lossy().into_owned()).collect(); + let Some(i) = s.iter().position(|a| a == "--preset" || a.starts_with("--preset=")) else { return Ok(args) }; + let path = PathBuf::from(match s[i].strip_prefix("--preset=") { Some(p) => p, None => s.get(i + 1).context("--preset needs a file")? }); + let root = ::command(); + let sub = s.get(1).and_then(|n| root.find_subcommand(n)) + .with_context(|| format!("--preset goes after a command, as in `rustingstrata serve --preset {}`", path.display()))?; + let find = |c: &clap::Command, k: &str| c.get_arguments().find(|a| a.get_long() == Some(k) || a.get_all_aliases().is_some_and(|v| v.contains(&k))).cloned(); + let given: Vec = s[2..].iter().filter_map(|a| a.strip_prefix("--")) + .filter_map(|a| find(sub, a.split('=').next().unwrap_or(a))).map(|a| a.get_id().clone()).collect(); + let text = std::fs::read_to_string(&path).with_context(|| format!("--preset {}", path.display()))?; + let (mut out, mut set) = (args[..2].to_vec(), vec![]); + for (n, k, vals) in parse_preset(&text).with_context(|| path.display().to_string())? { + let key = k.replace('_', "-"); + let Some(a) = find(sub, &key) else { + anyhow::ensure!(root.get_subcommands().any(|c| find(c, &key).is_some()), "{}:{n}: `{k}` is not a flag of any command", path.display()); + continue + }; + if given.contains(a.get_id()) { continue } + if a.get_action().takes_values() { + out.extend(vals.iter().map(|v| format!("--{key}={v}").into())); + } else if vals == ["true"] { + out.push(format!("--{key}").into()); + } else { + anyhow::ensure!(vals == ["false"], "{}:{n}: `{k}` is true or false", path.display()); + } + set.push(key); + } + out.extend_from_slice(&args[2..]); + let _ = PRESET.set((path, set)); + Ok(out) +} + +/// The lines of a preset: (line number, name, values). A value is a number, `true`/`false`, a word, a string in `"` +/// (with `\\` and `\"`) or `'`, or a list of them in `[...]`. +fn parse_preset(text: &str) -> anyhow::Result)>> { + let mut out = vec![]; + for (n, l) in text.lines().enumerate().map(|(n, l)| (n + 1, l.trim())) { + if l.is_empty() || l.starts_with('#') { continue } + let (k, v) = l.split_once('=').with_context(|| format!("line {n}: `name = value`, not {l:?}"))?; + let k = k.trim(); + anyhow::ensure!(!k.is_empty() && k.bytes().all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)), "line {n}: bad name {k:?}"); + let vals = preset_values(v.trim()).with_context(|| format!("line {n}: bad value {:?}", v.trim()))?; + out.push((n, k.to_string(), vals)); + } + Ok(out) +} + +fn preset_values(v: &str) -> Option> { + let mut c = v.chars().peekable(); + let array = c.next_if_eq(&'[').is_some(); + let mut out = vec![]; + loop { + while c.next_if(|ch| ch.is_whitespace() || array && *ch == ',').is_some() {} + match c.peek().copied() { + Some(']') if array => { c.next(); break } + None | Some('#') if !array => break, + None | Some('#') => return None, + Some(q @ ('"' | '\'')) => { + c.next(); + let mut s = String::new(); + loop { + match c.next()? { + ch if ch == q => break, + '\\' if q == '"' => s.push(c.next()?), + ch => s.push(ch), + } + } + out.push(s); + } + Some(_) => out.push(std::iter::from_fn(|| c.next_if(|ch| !ch.is_whitespace() && !"],#".contains(*ch))).collect()), + } + if !array { break } + } + while c.next_if(|ch| ch.is_whitespace()).is_some() {} + (c.peek().is_none_or(|&ch| ch == '#') && (array || out.len() == 1 && !out[0].is_empty())).then_some(out) +} + +/// `text` with each `key = value` line of `set` replaced, or added at the end (`calibrate --preset`). +fn set_preset_keys(text: &str, set: &[(&str, String)]) -> String { + let mut lines: Vec = text.lines().map(str::to_string).collect(); + for (k, v) in set { + let line = format!("{k} = {v}"); + let same = |l: &String| l.split_once('=').is_some_and(|(a, _)| a.trim().replace('-', "_") == k.replace('-', "_") && !a.trim_start().starts_with('#')); + match lines.iter().position(same) { Some(i) => lines[i] = line, None => lines.push(line) } + } + lines.join("\n") + "\n" +} + +/// Where a tuning value came from, for `settings_line`. +fn setting_source(key: &str, given: bool, calibrated: bool) -> &'static str { + if given { if PRESET.get().is_some_and(|(_, k)| k.iter().any(|k| k == key)) { "preset" } else { "flag" } } + else if calibrated { "calibration" } else { "default" } +} + +/// The command line, with `--preset` on every command (`expand_preset` has read it). +fn cli_command() -> clap::Command { + ::command().mut_subcommands(|c| c.arg(clap::Arg::new("preset").long("preset").value_name("FILE") + .help("Read flags from FILE (`name = value` lines, see docs/USAGE.md); flags given here win"))) +} + fn start() -> anyhow::Result<()> { - let m = ::command().get_matches(); + let m = cli_command().get_matches_from(expand_preset(std::env::args_os().collect())?); if let Some((_, sm)) = m.subcommand() && let Ok(Some(&n)) = sm.try_get_one::("ctx") && sm.value_source("ctx") == Some(clap::parser::ValueSource::CommandLine) { rusting_strata::CTX.store(n, std::sync::atomic::Ordering::Relaxed); } + // Read by `Gguf::open`, which every command calls before it looks at its engine flags. + if let Some((_, sm)) = m.subcommand() + && let Some(p) = [Some(sm), sm.subcommand().map(|x| x.1)].into_iter().flatten().find_map(|a| a.try_get_one::("ple").ok().flatten()) { + // SAFETY: no other thread runs yet. + unsafe { std::env::set_var("STRATA_PLE", p) }; + } let Some(cmd) = ::from_arg_matches(&m).unwrap_or_else(|e| e.exit()).cmd else { // Started without arguments, as by a double click: keep the window open on an error so it can be read. let Some(Cmd::Serve { model, models_dir, addr, api_key, mcp, open, host, mut engine }) = Cli::parse_from(["rustingstrata", "serve", "--gpu", "--open"]).cmd else { unreachable!() }; @@ -1098,6 +1822,13 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { RUSTFLAGS=\"-C target-cpu=native\" (or x86-64-v3), or use a release binary."); } match cmd { + Cmd::Stats => { + let f = usage_file(); + let u = serve::Usage::load(&f)?; + if u.models.is_empty() { println!("no requests recorded yet in {}", f.display()); } + else { print!("{}", u.table()); println!("({})", f.display()); } + } + Cmd::Update { check } => rusting_strata::update::run(check)?, Cmd::Info { model } => { let g = Gguf::open(&model)?; println!("{:#?}", ModelConfig::from_gguf(&g)?); @@ -1123,9 +1854,31 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { }; let (prompt, cont) = (ids("prompt")?, ids("continuation")?); anyhow::ensure!(!prompt.is_empty() && !cont.is_empty(), "empty prompt or continuation"); - let g = Gguf::open(&model)?; + let g = engine.open_model(&model)?; + // Kolibri and Inkling 2 have their own forwards: the continuation goes in a token at a time. + macro_rules! score_tokenwise { ($chat:path, $model:path) => {{ + use $chat as chat; use $model as Fwd; + engine.ds_env()?; + chat::gpu_defaults(); + let mut m = Fwd::new(&g)?; + let (mut argmax, mut top5) = (Vec::new(), Vec::new()); + let mut logits = m.prefill(&prompt); + for i in 0..cont.len() { + if i > 0 { logits = m.step(cont[i - 1]); } + let lse = logits.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)); + let lse = lse + logits.iter().map(|x| (x - lse).exp()).sum::().ln(); + argmax.push(ops::argmax(&logits)); + top5.push(ops::top_k(&logits, 5).into_iter().map(|j| (j, logits[j] - lse)).collect::>()); + } + println!("{}", serde_json::json!({"argmax": argmax, "top5": top5})); + return Ok(()); + }} } + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or(""); + if arch == rusting_strata::kolibri::ARCH { score_tokenwise!(rusting_strata::kolibri::chat, rusting_strata::kolibri::forward::KolibriModel) } + if arch == rusting_strata::gigachat4::ARCH { score_tokenwise!(rusting_strata::gigachat4::chat, rusting_strata::gigachat4::forward::GigaChat4Model) } + if rusting_strata::inkling2::is_arch(arch) { score_tokenwise!(rusting_strata::inkling2::chat, rusting_strata::inkling2::forward::Inkling2Model) } let aux_g = open_mtp_gguf(engine.aux_model_path())?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?; + let m = engine.load_inference_model(&g, aux_g.as_ref())?; if let Some(&t) = prompt.iter().chain(&cont).find(|&&t| t as usize >= m.cfg.n_vocab) { anyhow::bail!("token id {t} out of range (vocabulary has {} tokens)", m.cfg.n_vocab); } @@ -1144,13 +1897,18 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { println!("{}", serde_json::json!({"argmax": argmax, "top5": top5})); } Cmd::Generate { model, prompt, n, image, mut engine } => { - engine.ds_env(); - let g = Gguf::open(&model)?; + let (interval, pretty, graph) = engine.status_options()?; + term::live(false, interval, pretty, graph); + engine.own_calib(&model); + let _ = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; + engine.ds_env()?; + let g = engine.open_model(&model)?; engine.own_warn(&g); if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("gemma4") { let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; + let _live = term::Live::start(); if image.is_empty() { return rusting_strata::gemma4::generate(&g, &prompt, n); } - let mmproj = engine.mmproj.clone().or_else(|| vision::find_sibling(&model)); + let mmproj = engine.mmproj_for(&model); let mmproj = mmproj.as_deref().context("--image needs --mmproj")?; let input = load_images(mmproj, &image)?; return rusting_strata::gemma4::generate_image(&g, &prompt, &input.grids, &input.embeddings, n); @@ -1158,22 +1916,46 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("glm5-next") { anyhow::ensure!(image.is_empty(), "--image is not supported for glm5-next"); let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; + let _live = term::Live::start(); return rusting_strata::glm::generate(&g, &prompt, n); } if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("deepseek41") { anyhow::ensure!(image.is_empty(), "--image is not supported for deepseek41"); let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; + let _live = term::Live::start(); + engine.ds_threads(); return rusting_strata::deepseek::chat::generate(&g, &prompt, n); } if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::hy4::ARCH) { anyhow::ensure!(image.is_empty(), "--image is not supported for hy_v4_flash"); let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; + let _live = term::Live::start(); return rusting_strata::hy4::chat::generate(&g, &prompt, n); } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::gigachat4::ARCH) { + anyhow::ensure!(image.is_empty(), "--image is not supported for gigachat4"); + let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; + let _live = term::Live::start(); + return rusting_strata::gigachat4::chat::generate(&g, &prompt, n); + } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::kolibri::ARCH) { + anyhow::ensure!(image.is_empty(), "--image is not supported for kolibri1"); + let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; + let _live = term::Live::start(); + return rusting_strata::kolibri::chat::generate(&g, &prompt, n); + } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::raon::ARCH) { + anyhow::ensure!(image.is_empty(), "--image is not supported for raon1"); + let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; + let _live = term::Live::start(); + return rusting_strata::raon::chat::generate(&g, &prompt, n, engine.draft_model.as_deref()); + } if g.get("general.architecture").ok().and_then(|v| v.as_str()) .is_some_and(rusting_strata::inkling2::is_arch) { + engine.inkling_margin()?; let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; + let _live = term::Live::start(); let max_ctx = 0; - let mmproj = engine.mmproj.clone().or_else(|| vision::find_sibling(&model)); + let mmproj = engine.mmproj_for(&model); let opts = rusting_strata::inkling2::chat::Inkling2Opts { max_ctx, sampler: engine.sampler(), @@ -1191,7 +1973,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { return rusting_strata::inkling2::chat::generate_image_opts(&g, &prompt, Some((&input.grids, &input.embeddings)), n, opts); } let aux_g = open_mtp_gguf(engine.aux_model_path())?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?; + let m = engine.load_inference_model(&g, aux_g.as_ref())?; let tok = Tokenizer::from_gguf(&g)?; let prompt = if prompt == "-" { let mut s = String::new(); @@ -1201,18 +1983,23 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { let vision_prompt = if image.is_empty() { None } else { - let mmproj = engine.mmproj.clone().or_else(|| vision::find_sibling(&model)); + let mmproj = engine.mmproj_for(&model); let mmproj = mmproj.as_deref().context("--image needs --mmproj")?; let input = load_images(mmproj, &image)?; Some((build_image_prompt(&tok, &input, &image, &prompt)?, input)) }; let ids = tok.encode(&prompt)?; anyhow::ensure!(!ids.is_empty() || vision_prompt.is_some(), "empty prompt"); + // The CPU state grows past --ctx; refuse the prompt the same way the GPU does. + let n_in = vision_prompt.as_ref().map_or(ids.len(), |(p, _)| p.ids.len()); + anyhow::ensure!(n_in <= engine.ctx, "the prompt is {n_in} tokens, more than --ctx {}; raise --ctx", engine.ctx); let mut r = engine.runner(&m, &model)?; + let mut _live = term::Live::start(); + _live.prefill_total(vision_prompt.as_ref().map_or(ids.len(), |(p, _)| p.ids.len())); let t0 = Instant::now(); let (logits, n_prompt) = match vision_prompt { None => (r.prefill(&ids)?, ids.len()), - Some((p, input)) => (r.chat_image(&p, &input.embeddings)?, p.ids.len()), + Some((p, input)) => (r.chat_image(&p, &input.embeddings, &[], 0, &mut _live)?.0, p.ids.len()), }; let t1 = Instant::now(); let (cpu0, split0) = (r.cpu_secs(), r.split_secs()); @@ -1222,7 +2009,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { let (pp, tg) = ((t1 - t0).as_secs_f64(), t1.elapsed().as_secs_f64()); if out.len() == cap && cap < n { eprint!("\n(stopped: the context is full at {} tokens; raise --ctx)", engine.ctx); } say!("\nprompt {} tok {:.2} tok/s | gen {} tok {:.2} tok/s", n_prompt, n_prompt as f64 / pp, out.len(), out.len() as f64 / tg); - if engine.gpu { say!("CPU expert compute, share of gen time: {:.1}%", 100.0 * (r.cpu_secs() - cpu0) / tg); } + if r.expert_stats().is_some_and(|s| s.cached) { say!("experts on the CPU: {:.1}% of the gen time", 100.0 * (r.cpu_secs() - cpu0) / tg); } let ms = |s: f64| 1e3 * s / out.len().max(1) as f64; for (i, ((a, b), (a0, b0))) in r.split_secs().into_iter().zip(split0).enumerate() { say!("device {i}: {:.2} ms/token forward, {:.2} ms/token copy to the next device", ms(a - a0), ms(b - b0)); @@ -1231,17 +2018,27 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { r.finish()?; } Cmd::Perplexity { model, file, ctx_len: n, chunks, kld_base, mut engine } => { - let g = Gguf::open(&model)?; - let aux_g = open_mtp_gguf(engine.aux_model_path())?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?; + let g = engine.open_model(&model)?; let tok = Tokenizer::from_gguf(&g)?; // ponytail: no BOS at chunk starts (llama-perplexity adds one where the vocabulary asks for it; Qwen does not) - let ids = tok.encode(&std::fs::read_to_string(&file)?)?; + let ids = tok.encode(&std::fs::read_to_string(&file).with_context(|| format!("--file {}", file.display()))?)?; let n_chunk = (ids.len() / n).min(chunks.unwrap_or(usize::MAX)); anyhow::ensure!(n >= 4 && n_chunk > 0, "{} tokens: need at least one chunk of --ctx-len {n} (>= 4)", ids.len()); engine.ctx = engine.ctx.max(n); - let mut r = engine.runner(&m, &model)?; - let nv = m.cfg.n_vocab; + // Inkling 2 runs its own forward (`Model` does not load that architecture); it scores the same way, so + // `--kld-base` compares it with another build the same as it compares llama.cpp with the others. + let mut ink = if g.get("general.architecture").ok().and_then(|v| v.as_str()).is_some_and(rusting_strata::inkling2::is_arch) { + rusting_strata::inkling2::chat::gpu_defaults(); + engine.ds_env()?; + engine.inkling_margin()?; + Some(rusting_strata::inkling2::forward::Inkling2Model::new_with_ctx(&g, n)?) + } else { + None + }; + let aux_g = if ink.is_none() { open_mtp_gguf(engine.aux_model_path())? } else { None }; + let m = if ink.is_none() { Some(engine.load_inference_model(&g, aux_g.as_ref())?) } else { None }; + let mut r = match &m { Some(m) => Some(engine.runner(m, &model)?), None => None }; + let nv = match (&ink, &m) { (Some(im), _) => im.cfg.n_vocab, (_, Some(m)) => m.cfg.n_vocab, _ => unreachable!() }; let mut out = kld_base.map(|p| std::fs::File::create(p).map(std::io::BufWriter::new)).transpose()?; if let Some(o) = &mut out { o.write_all(b"_logits_")?; @@ -1251,10 +2048,19 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { let (mut nll, mut count, mut row) = (0f64, 0usize, Vec::new()); let first = n / 2; for c in ids.chunks_exact(n).take(n_chunk) { - r.reset()?; - let mut logits = r.prefill(&c[..=first])?; + let mut logits = match (&mut ink, &mut r) { + (Some(im), _) => { im.reset(); im.prefill(&c[..=first]) } + (_, Some(run)) => { run.reset()?; run.prefill(&c[..=first])? } + _ => unreachable!(), + }; for i in first..n - 1 { - if i > first { logits = r.step(c[i])?; } + if i > first { + logits = match (&mut ink, &mut r) { + (Some(im), _) => im.step(c[i]), + (_, Some(run)) => run.step(c[i])?, + _ => unreachable!(), + }; + } anyhow::ensure!(logits.len() == nv, "{} logits, vocabulary {nv}", logits.len()); nll += log_probs(&logits, c[i + 1], &mut row); if let Some(o) = &mut out { for v in &row { o.write_all(&v.to_le_bytes())?; } } @@ -1264,26 +2070,35 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } if let Some(o) = &mut out { o.flush()?; } println!("\nPPL = {:.4} over {n_chunk} chunks of {n} tokens ({count} scored)", (nll / count as f64).exp()); - r.finish()?; + if let Some(run) = &mut r { run.finish()?; } } Cmd::Bench { model, pp, tg, reps, json_out, prompt_file, mut engine } => { + let _ = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; if let Some(f) = &prompt_file { let text = std::fs::read_to_string(f).with_context(|| format!("--prompt-file {}", f.display()))?; anyhow::ensure!(!text.trim().is_empty(), "--prompt-file {} is empty", f.display()); let _ = BENCH_TEXT.set(text); } - let g = Gguf::open(&model)?; + let g = engine.open_model(&model)?; engine.own_warn(&g); engine.ctx = engine.ctx.max(pp.iter().max().unwrap_or(&0) + tg); if let Some(arch) = g.get("general.architecture").ok().and_then(|v| v.as_str()) { - if arch == "deepseek41" || arch == "glm5-next" || arch == rusting_strata::hy4::ARCH || rusting_strata::inkling2::is_arch(arch) { - engine.ds_env(); + if arch == "deepseek41" || arch == "glm5-next" || arch == "gemma4" || arch == rusting_strata::hy4::ARCH || arch == rusting_strata::kolibri::ARCH || arch == rusting_strata::gigachat4::ARCH || arch == rusting_strata::raon::ARCH || rusting_strata::inkling2::is_arch(arch) { + engine.ds_env()?; // A --ctx below the test grows to fit it, as on the main engine. if rusting_strata::CTX.load(std::sync::atomic::Ordering::Relaxed) != 0 { rusting_strata::CTX.store(engine.ctx, std::sync::atomic::Ordering::Relaxed); } return if arch == "deepseek41" { bench_deepseek(&g, &model, &pp, tg, reps, json_out, &mut engine) + } else if arch == "gemma4" { + bench_gemma4(&g, &model, &pp, tg, reps, json_out, &mut engine) } else if arch == rusting_strata::hy4::ARCH { bench_hy4(&g, &model, &pp, tg, reps, json_out, &mut engine) + } else if arch == rusting_strata::kolibri::ARCH { + bench_kolibri(&g, &model, &pp, tg, reps, json_out, &mut engine) + } else if arch == rusting_strata::gigachat4::ARCH { + bench_gigachat4(&g, &model, &pp, tg, reps, json_out, &mut engine) + } else if arch == rusting_strata::raon::ARCH { + bench_raon(&g, &model, &pp, tg, reps, json_out, &mut engine) } else if rusting_strata::inkling2::is_arch(arch) { bench_inkling2(&g, &model, &pp, tg, reps, json_out, &mut engine) } else { @@ -1292,7 +2107,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } } let aux_g = open_mtp_gguf(engine.aux_model_path())?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?; + let m = engine.load_inference_model(&g, aux_g.as_ref())?; let tok = Tokenizer::from_gguf(&g)?; let mut r = engine.runner(&m, &model)?; let mut results = Vec::with_capacity(pp.len()); @@ -1337,44 +2152,63 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { reps, }; let unix_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs()); - let record = bench_record(&meta, &results, r.expert_summary().as_ref(), unix_time); + let mut record = bench_record(&meta, &results, r.expert_summary().as_ref(), unix_time); + // The arch-specific benchners print this; putting it in the JSON too gives tools one reliable source. + let drafts = if let Runner::Gpu(g) = &r { g.drafts } else { (0, 0) }; + record["drafts"] = json!({"made": drafts.0, "accepted": drafts.1}); let mut line = serde_json::to_string(&record)?; line.push('\n'); std::fs::write(&path, line).with_context(|| format!("writing the JSON record to {}", path.display()))?; } } - Cmd::Calibrate { model, ctx, vram_margin, backend, device, split, kv, lora, gpu: _, mtp_model, draft_model } => { - set_kv_env(&kv); // read by Gpu::new and Vk::new + Cmd::Calibrate { status_interval, pretty, graph, model, ctx, vram_margin, backend, device, split, kv, setup, lora, gpu: _, mtp_model, draft_model, + samples, reps, warmup, pp, tg, chunk_values, task, seed, + dry_run, timeout, minutes, out, sub } => { + let interval = configured_status_interval(status_interval, std::env::var("STRATA_STATUS_INTERVAL").ok().as_deref(), pretty)?; + term::live(false, interval, pretty, graph); + set_kv_env_for(&kv, setup.k.as_deref(), setup.v.as_deref())?; // read by Gpu::new and Vk::new; expands turbo pair aliases + anyhow::ensure!(PRESET.get().is_none() || !model.as_ref().is_some_and(|m| m.is_dir()), "--preset holds the tuning of one model: give --model a file, not a folder"); if !lora.is_empty() { say!("note: --lora is ignored by calibrate; calibration uses the base model"); } - let margins = vram_margins(&vram_margin, &device)?.into_iter().map(|mb| mb << 20).collect::>(); - let split = split_arg(split.as_deref(), device.len())?; - // The architecture of a file that runs on its own code path, where nothing reads a calibration file. - let own_arch = |p: &std::path::Path| { - let arch = Gguf::open(p).ok()?.get("general.architecture").ok()?.as_str()?.to_string(); - rusting_strata::config::OWN_ARCHS.contains(&arch.as_str()).then_some(arch) - }; - if !model.is_dir() { - if let Some(arch) = own_arch(&model) { - say!("nothing to calibrate: '{arch}' models run on their own code path, which reads no calibration file. Run chat, generate, bench or serve with this model as it is."); - return Ok(()); - } - return calibrate(&model, draft_model.as_deref().or(mtp_model.as_deref()), ctx, &margins, backend.as_deref(), &device, split); + if split.is_some() { say!("note: --split is ignored by calibrate; measurements use the free-VRAM split"); } + + if let Some(CalibrateSub::Spec { model, tasks, spec_types, draft_max, ngram_n, mtp, draft_model, backend, + device, ctx, vram_margin, kv, setup, pp, tg, reps, samples, seed, out, dry_run }) = sub { + set_kv_env_for(&kv, setup.k.as_deref(), setup.v.as_deref())?; + let mut s = CalibSettings::new(model); + s.extra = setup.args(); + s.backend = backend; s.device = device; s.vram_margin = vram_margin; s.kv = kv; + s.ctx = ctx; s.tasks = tasks; s.spec_types = spec_types; s.draft_max = draft_max; s.ngram_n = ngram_n; + s.mtp_values = mtp; s.pp = vec![pp]; s.tg = tg; s.reps = reps; s.samples = samples; + s.seed = seed; s.out = out; s.dry_run = dry_run; + s.aux = draft_model.map(|p| ("--draft-model", p)); + ensure_spec_defaults(&mut s); + return calibrate_spec(&s); } - anyhow::ensure!(draft_model.is_none() && mtp_model.is_none(), "--mtp-model and --draft-model belong to one model: give --model a file"); + + let Some(model) = model else { anyhow::bail!("--model PATH is required (or use `calibrate spec --model PATH`)") }; + let mut settings = CalibSettings::new(model.clone()); + settings.backend = backend; + settings.device = device; + settings.vram_margin = vram_margin; + settings.kv = kv; + settings.extra = setup.args(); + settings.chunk_values = chunk_values.unwrap_or_else(|| vec![256, 512, 1024, 2048, 4096]); + settings.ctx = ctx; + settings.aux = draft_model.map(|p| ("--draft-model", p)).or_else(|| mtp_model.map(|p| ("--mtp-model", p))); + settings.samples = samples; settings.reps = reps; settings.warmup = warmup; settings.pp = pp; + settings.tg = tg; settings.tasks = task; + settings.seed = seed; settings.dry_run = dry_run; settings.timeout = timeout; settings.minutes = minutes; settings.out = out; + if settings.pp.is_empty() || settings.pp.iter().any(|&n| n == 0) { anyhow::bail!("--pp needs at least one positive prompt depth"); } + if settings.samples == 0 { anyhow::bail!("--samples must be positive"); } + if !model.is_dir() { return calibrate_v2(&settings); } let list = rusting_strata::serve::list_models(&model); anyhow::ensure!(!list.is_empty(), "no .gguf models in {}", model.display()); + anyhow::ensure!(settings.aux.is_none(), "--mtp-model and --draft-model belong to one model: give --model a file"); let mut failed = vec![]; for (k, (id, path, _)) in list.iter().enumerate() { say!("calibrate {}/{}: {id}", k + 1, list.len()); - if let Some(arch) = own_arch(path) { - say!("calibrate {id}: skipped, calibrate measures the main engine only and '{arch}' models run on their own code path"); - continue; - } - // One model that fails (too big, not a model) does not stop the others. - if let Err(e) = calibrate(path, None, ctx, &margins, backend.as_deref(), &device, split.clone()) { - say!("calibrate {id}: failed: {e:#}"); - failed.push(id.as_str()); - } + settings.model = path.clone(); + if let Err(e) = calibrate_v2(&settings) { say!("calibrate {id}: failed: {e:#}"); failed.push(id.as_str()); } } anyhow::ensure!(failed.is_empty(), "calibration failed for {}", failed.join(", ")); } @@ -1390,6 +2224,21 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { println!("check: hy_v4_flash ok: {} layers, {} experts ({} used), {} tensors, every tensor of the forward is present", m.cfg.n_layer, m.cfg.n_expert, m.cfg.n_used, g.tensors.len()); return Ok(()); } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::gigachat4::ARCH) { + let m = rusting_strata::gigachat4::forward::GigaChat4Model::new(&g)?; + println!("check: gigachat4 ok: {} layers, {} experts ({} used), {} tensors, every tensor of the forward is present", m.cfg.n_layer, m.cfg.n_expert, m.cfg.n_used, g.tensors.len()); + return Ok(()); + } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::kolibri::ARCH) { + let m = rusting_strata::kolibri::forward::KolibriModel::new(&g)?; + println!("check: kolibri1 ok: {} layers, {} experts ({} used), {} tensors, every tensor of the forward is present", m.cfg.n_layer, m.cfg.n_expert, m.cfg.n_used, g.tensors.len()); + return Ok(()); + } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::raon::ARCH) { + let m = rusting_strata::raon::forward::RaonModel::new(&g)?; + println!("check: raon1 ok: {} layers, {} experts ({} used), {} tensors, every tensor of the forward is present", m.cfg.n_layer, m.cfg.n_expert, m.cfg.n_used, g.tensors.len()); + return Ok(()); + } if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("deepseek41") { let c = rusting_strata::deepseek::DsConfig::from_gguf(&g)?; c.validate(&g)?; @@ -1424,9 +2273,23 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } Cmd::Interface { models_dir } => { println!("{}", term::paint(term::out(), "1", concat!("RustingStrata ", env!("CARGO_PKG_VERSION")))); - let mut models = serve::list_models(&models_dir.clone().unwrap_or_else(models_dir_default)); - for m in serve::cached_models() { if !models.iter().any(|x| x.1 == m.1) { models.push(m); } } - let mut args = interface_args(&mut std::io::stdin().lock(), models)?; + // The models picked in earlier runs come first, the last one at the top (issue #82). + let hist = rusting_strata::expert_cache::cache_dir().join("interface-models.txt"); + let old: Vec = std::fs::read_to_string(&hist).unwrap_or_default().lines().map(PathBuf::from).filter(|p| p.is_file()).collect(); + let mut models: Vec<_> = old.iter().map(|p| { + let name = p.file_name().map_or_else(|| p.to_string_lossy(), |n| n.to_string_lossy()).into_owned(); + (name, p.clone(), std::fs::metadata(p).map_or(0, |m| m.len())) + }).collect(); + let found = serve::list_models(&models_dir.clone().unwrap_or_else(models_dir_default)).into_iter().chain(serve::cached_models()); + for m in found { + let p = m.1.canonicalize().unwrap_or_else(|_| m.1.clone()); + if !models.iter().any(|x| x.1 == p) { models.push(m); } + } + let mut args = interface_args(&mut std::io::stdin().lock(), models, rusting_strata::cuda::device_uuids().len())?; + if let Ok(p) = std::path::Path::new(&args[2]).canonicalize() { + let keep: Vec<_> = std::iter::once(&p).chain(old.iter().filter(|&o| *o != p)).take(10).map(|p| p.to_string_lossy()).collect(); + let _ = std::fs::create_dir_all(hist.parent().unwrap()).and_then(|_| std::fs::write(&hist, keep.join("\n") + "\n")); + } if let Some(d) = models_dir.filter(|_| args[0] == "serve") { args.extend(["--models-dir".into(), d.to_string_lossy().into()]); } let shown: Vec<_> = args.iter().map(|a| if a.contains(' ') { format!("\"{a}\"") } else { a.clone() }).collect(); println!("\n{} rustingstrata {}\n", term::paint(term::out(), "2", "running:"), shown.join(" ")); @@ -1439,16 +2302,21 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { std::process::exit(cmd.status()?.code().unwrap_or(1)); } Cmd::Chat { model, system, n, image, mut engine } => { + let _ = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; let think = engine.think_default; - engine.ds_env(); - let g = Gguf::open(&model)?; + let (interval, pretty, graph) = engine.status_options()?; + term::live(false, interval, pretty, graph); + engine.own_calib(&model); + engine.ds_env()?; + let g = engine.open_model(&model)?; engine.own_warn(&g); if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("gemma4") { let input = if image.is_empty() { None } else { - let mmproj = engine.mmproj.clone().or_else(|| vision::find_sibling(&model)); + let mmproj = engine.mmproj_for(&model); let mmproj = mmproj.as_deref().context("--image needs --mmproj")?; Some(load_images(mmproj, &image)?) }; + let _live = term::Live::start(); return match &input { Some(i) => rusting_strata::gemma4::chat(&g, system, n, think, Some((&i.grids, &i.embeddings))), None => rusting_strata::gemma4::chat(&g, system, n, think, None), @@ -1456,19 +2324,39 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("glm5-next") { anyhow::ensure!(image.is_empty(), "--image is not supported for glm5-next"); + let _live = term::Live::start(); return rusting_strata::glm::chat(&g, system, n); } if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("deepseek41") { anyhow::ensure!(image.is_empty(), "--image is not supported for deepseek41"); + let _live = term::Live::start(); + engine.ds_threads(); return rusting_strata::deepseek::chat::chat(&g, system, n, think); } if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::hy4::ARCH) { anyhow::ensure!(image.is_empty(), "--image is not supported for hy_v4_flash"); + let _live = term::Live::start(); return rusting_strata::hy4::chat::chat(&g, system, n, think); } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::gigachat4::ARCH) { + anyhow::ensure!(image.is_empty(), "--image is not supported for gigachat4"); + let _live = term::Live::start(); + return rusting_strata::gigachat4::chat::chat(&g, system, n, think); + } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::kolibri::ARCH) { + anyhow::ensure!(image.is_empty(), "--image is not supported for kolibri1"); + let _live = term::Live::start(); + return rusting_strata::kolibri::chat::chat(&g, system, n, think); + } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::raon::ARCH) { + anyhow::ensure!(image.is_empty(), "--image is not supported for raon1"); + let _live = term::Live::start(); + return rusting_strata::raon::chat::chat(&g, system, n, think, engine.draft_model.as_deref()); + } if g.get("general.architecture").ok().and_then(|v| v.as_str()) .is_some_and(rusting_strata::inkling2::is_arch) { + engine.inkling_margin()?; let max_ctx = 0; - let mmproj = engine.mmproj.clone().or_else(|| vision::find_sibling(&model)); + let mmproj = engine.mmproj_for(&model); let opts = rusting_strata::inkling2::chat::Inkling2Opts { max_ctx, sampler: engine.sampler(), @@ -1484,16 +2372,17 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { let mmproj = mmproj.as_deref().context("--image needs --mmproj")?; Some(load_images(mmproj, &image)?) }; + let _live = term::Live::start(); return match &input { Some(i) => rusting_strata::inkling2::chat::chat_image_opts(&g, system, n, Some((&i.grids, &i.embeddings)), opts), None => rusting_strata::inkling2::chat::chat_opts(&g, system, n, opts), }; } let aux_g = open_mtp_gguf(engine.aux_model_path())?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?; + let m = engine.load_inference_model(&g, aux_g.as_ref())?; let tok = Tokenizer::from_gguf(&g)?; let image_input = if image.is_empty() { None } else { - let mmproj = engine.mmproj.clone().or_else(|| vision::find_sibling(&model)); + let mmproj = engine.mmproj_for(&model); let mmproj = mmproj.as_deref().context("--image needs --mmproj")?; Some(load_images(mmproj, &image)?) }; @@ -1509,42 +2398,75 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { if stdin.lock().read_line(&mut line)? == 0 { break; } if line.trim().is_empty() { continue; } msgs.push(Msg::new("user", line.trim_end())); + // Keep room for a reply: drop the oldest user/assistant pairs (never the system message) while the + // prompt would leave less than `n` (at most a quarter of --ctx) free. ponytail: text tokens only, an + // image prompt can still run into "context full". + let (first, reserve) = (system.is_some() as usize, n.min(engine.ctx / 4).max(1)); + let over = |m: &[Msg]| -> anyhow::Result { Ok(tok.encode(&tpl.render(m, &[], think, engine.preserve_thinking, true))?.len() + reserve > engine.ctx) }; + let alone: Vec = msgs[..first].iter().chain(msgs.last()).cloned().collect(); + if over(&alone)? { + eprintln!("(this message is too long for --ctx {}; raise --ctx)", engine.ctx); + msgs.pop(); + continue; + } + let mut dropped = 0; + while over(&msgs)? { + msgs.drain(first..first + 2); + dropped += 1; + } + if dropped > 0 { eprintln!("(context: dropped the {dropped} oldest exchange(s) to stay within --ctx {})", engine.ctx); } + let mut _live = term::Live::start(); let prompt = tpl.render(&msgs, &[], think, engine.preserve_thinking, true); let (ids, logits) = match &image_input { Some(input) => { let p = build_image_prompt(&tok, input, &image, &prompt)?; let ids = p.ids.clone(); - let logits = r.chat_image(&p, &input.embeddings)?; + let logits = r.chat_image(&p, &input.embeddings, &[], 0, &mut _live)?.0; (ids, logits) } None => { - let (ids, logits, _) = r.chat(&tok, &prompt, &tpl.render(&msgs, &[], think, engine.preserve_thinking, false), "")?; + let (ids, logits, _) = r.chat(&tok, &prompt, &tpl.render(&msgs, &[], think, engine.preserve_thinking, false), "", &mut _live)?; (ids, logits) } }; let think_cap = Some((prompt.trim_end().ends_with(""), engine.thinking_budget)); - (smp.seen.clear(), smp.hist.clear()); // the penalties count this reply only, not the earlier turns + smp.hist.clear(); // the penalties count this reply only, not the earlier turns // The reasoning is dim on a terminal; it starts in the prompt when the template opens the block itself. let dim = term::out(); if dim && think_cap.is_some_and(|c| c.0) { print!("\x1b[2m"); } - let (out, _) = decode(&mut r, &tok, engine.mtp() > 0, &mut smp, logits, room(&engine, ids.len(), n), think_cap, &mut |t| { + let (h0, t0) = (r.expert_summary(), Instant::now()); + let cap = room(&engine, ids.len(), n); + let (out, _) = decode(&mut r, &tok, engine.mtp() > 0, &mut smp, logits, cap, think_cap, &mut |t| { if dim { print!("{}", t.replace("", "\x1b[2m").replace("", "\x1b[0m")); } else { print!("{t}"); } std::io::stdout().flush()?; Ok(false) })?; println!("{}", if dim { "\x1b[0m" } else { "" }); + if out.len() == cap && cap < n { eprintln!("(stopped: the context is full at {} tokens; raise --ctx)", engine.ctx); } + // One status line a reply: its decode speed and, with an expert cache, its own expert hit rate. + let hit = match (h0, r.expert_summary()) { + (Some(a), Some(b)) if b.hits + b.misses > a.hits + a.misses => + format!(", expert hit rate {:.1}%", 100.0 * (b.hits - a.hits) as f64 / (b.hits + b.misses - a.hits - a.misses) as f64), + _ => String::new(), + }; + say!("decode: {:.1} tok/s, {} tok{hit}", out.len() as f64 / t0.elapsed().as_secs_f64().max(1e-9), out.len()); msgs.push(Msg::new("assistant", &answer(&tok.decode(&out)?))); } r.finish()?; } Cmd::Serve { model, models_dir, addr, api_key, mcp, open, host, mut engine } => { - engine.ds_env(); + rusting_strata::update::notice(); + let (interval, pretty, graph) = engine.status_options()?; + let _server_status = term::server_status(interval, pretty, graph); + let _ = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; + engine.ds_env()?; anyhow::ensure!(host.auto_unload != Some(0), "--auto-unload must be at least 1 second"); engine.parallel = host.parallel; // Before the model is loaded: a slot count outside 1..=255 is an invalid request, not a downgrade. anyhow::ensure!((1..=255).contains(&engine.parallel), "--parallel {}: 1 to 255 slots", engine.parallel); let api_key = api_key.or_else(|| std::env::var("STRATA_API_KEY").ok()); anyhow::ensure!(api_key.as_ref().is_none_or(|k| !k.is_empty()), "empty API key"); + let no_webui = host.no_webui; let mut allowed_hosts = host.allowed_hosts.clone(); if allowed_hosts.is_empty() && let Ok(v) = std::env::var("STRATA_ALLOWED_HOSTS") { allowed_hosts.extend(v.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_owned)); @@ -1568,6 +2490,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { .with_context(|| format!("opening {}", f.display()))?)), None => None, }; + if !host.cors_origin.is_empty() { let _ = serve::CORS_ORIGINS.set(host.cors_origin.clone()); } let max_waiting = host.max_waiting.map_or(usize::MAX, |n| n.max(1)); anyhow::ensure!(host.max_per_key != Some(0), "--max-per-key must be at least 1"); let url = format!("http://{addr}/"); @@ -1631,13 +2554,22 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } let (tx, oc, st, a, k, allowed, held, hub, offer) = (tx.clone(), open_conns.clone(), st.clone(), a.clone(), k.clone(), allowed.clone(), held.clone(), hub.clone(), offer.clone()); std::thread::spawn(move || { - let q = c.set_read_timeout(Some(Duration::from_secs(30))).and_then(|_| c.set_write_timeout(Some(Duration::from_secs(30)))) - .map_err(Into::into).and_then(|_| serve::read_request(&mut BufReader::new(&c))); + let q = c.set_write_timeout(Some(Duration::from_secs(30))).map_err(Into::into) + .and_then(|_| serve::read_request(&mut BufReader::new(serve::Deadline::new(&c, Instant::now() + serve::REQUEST_TIME)))); let reply = |v: serde_json::Value, status: &str| { let b = v.to_string(); - let _ = write!(&c, "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()); + let _ = write!(&c, "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n{b}", b.len(), cors = serve::cors(&c)); oc.fetch_sub(1, Relaxed); }; + // `--cors-origin`: every response head carries the CORS lines, and a browser's preflight is + // answered before the key check (it carries no key); the request after it still needs the key. + if let Ok(r) = &q { serve::cors_keep(&c, r); } + if let Ok(r) = &q && r.method == "OPTIONS" && serve::CORS_ORIGINS.get().is_some() { + let _ = serve::cors(&c); + let _ = write!(&c, "HTTP/1.1 204 No Content\r\n{}Content-Length: 0\r\nConnection: close\r\n\r\n", serve::cors_lines(&r.origin, &r.cors_headers)); + oc.fetch_sub(1, Relaxed); + return; + } // For load balancers: no key, no Host check, and an answer while a reply is generated. if let Ok(r) = &q && r.method == "GET" && r.path == "/health" { let (model, loading, slots, unloaded) = { let g = st.lock().unwrap(); (g.model.is_some() && !g.loading, g.loading, g.slots, g.unloaded) }; @@ -1653,7 +2585,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { && (k.any() || serve::host_ok(&r.host, &a, &allowed)) && k.who(&r.auth).is_some_and(|w| w.admin) { if r.path == "/metrics" { let b = st.lock().unwrap().prometheus(oc.load(Relaxed) - 1, t0.elapsed().as_secs()); - let _ = write!(&c, "HTTP/1.1 200 OK\r\nContent-Type: text/plain; version=0.0.4\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()); + let _ = write!(&c, "HTTP/1.1 200 OK\r\nContent-Type: text/plain; version=0.0.4\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n{b}", b.len(), cors = serve::cors(&c)); oc.fetch_sub(1, Relaxed); return; } @@ -1696,8 +2628,18 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { say!("request {i}: {e:#}"); return reply(json!({"error": {"message": format!("{e:#}"), "type": "invalid_request_error"}}), "400 Bad Request"); } - Ok(r) if r.method == "GET" && r.path == "/" && (k.read().unwrap().any() || serve::host_ok(&r.host, &a, &allowed)) => { - let _ = write!(&c, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nX-Frame-Options: DENY\r\nContent-Security-Policy: frame-ancestors 'none'\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{PAGE}", PAGE.len()); + Ok(r) if r.method == "GET" && r.path == "/" && !no_webui && (k.read().unwrap().any() || serve::host_ok(&r.host, &a, &allowed)) => { + let _ = write!(&c, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nX-Frame-Options: DENY\r\nContent-Security-Policy: frame-ancestors 'none'\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n{PAGE}", PAGE.len(), cors = serve::cors(&c)); + oc.fetch_sub(1, Relaxed); + return; + } + // The KaTeX files of the page (math in replies), under /katex/ with the same checks as the page. + // The files never change with the server running, so the browser may keep them. + Ok(r) if r.method == "GET" && (k.read().unwrap().any() || serve::host_ok(&r.host, &a, &allowed)) + && let Some(file) = r.path.strip_prefix("/katex/") + && let Some((_, ty, b)) = serve::KATEX.iter().find(|&(n, _, _)| *n == file) => { + let _ = write!(&c, "HTTP/1.1 200 OK\r\nContent-Type: {ty}\r\nCache-Control: max-age=31536000, immutable\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", b.len()); + let _ = c.write_all(b); oc.fetch_sub(1, Relaxed); return; } @@ -1706,13 +2648,13 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { // Clients list the models often; a model still loading is listed, as its chats wait for the load. Ok(r) if r.method == "GET" && r.path.split('?').next() == Some("/v1/models") && (k.read().unwrap().any() || serve::host_ok(&r.host, &a, &allowed)) => { let created = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs()); - let (m, file, n_ctx, n_ctx_train) = { + let (m, file, n_ctx, n_ctx_train, efforts) = { let state = st.lock().unwrap(); - (state.model.clone(), state.file.clone(), state.ctx, state.ctx_train) + (state.model.clone(), state.file.clone(), state.ctx, state.ctx_train, state.efforts.clone()) }; let mut data: Vec<_> = m.iter().map(|id| json!({ "id": id, "object": "model", "created": created, "owned_by": "strata", - "meta": {"n_ctx": n_ctx, "n_ctx_train": n_ctx_train} + "meta": {"n_ctx": n_ctx, "n_ctx_train": n_ctx_train, "reasoning_effort": efforts} })).collect(); // An admin key also sees the other models the server offers, by file name: a chat request // that names one loads it (`Serving::other`). Customer keys may not load models. @@ -1726,27 +2668,46 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } return reply(json!({"object": "list", "data": data}), "200 OK"); } + // llama-server's server properties: clients with a llama.cpp provider (maki, issue #131) read + // the context length here. + Ok(r) if r.method == "GET" && r.path.split('?').next() == Some("/props") && (k.read().unwrap().any() || serve::host_ok(&r.host, &a, &allowed)) => { + let state = st.lock().unwrap(); + let alias = state.model.clone().unwrap_or_else(|| state.file.clone()); + let b = json!({"role": "model", "model_alias": alias, "model_path": state.file, "total_slots": state.slots.max(1), + "default_generation_settings": {"n_ctx": state.ctx, "params": {}}, "n_ctx_train": state.ctx_train, + "build_info": concat!("rustingstrata ", env!("CARGO_PKG_VERSION"))}); + drop(state); + return reply(b, "200 OK"); + } _ => {} } // A customer key over `--max-per-key` is refused here, before it takes a place in the queue. - let hold = match (who, per_key) { + let hold = match (who.as_ref(), per_key) { (Some(w), Some(cap)) if !w.admin => match serve::Hold::take(&held, w.id, cap) { Some(h) => Some(h), None => { say!("request {i}: {} already has {cap} requests open, answered 429", w.name); let b = json!({"error": {"message": format!("this key already has {cap} requests open, retry later"), "type": "rate_limit_error"}}).to_string(); - let _ = write!(&c, "HTTP/1.1 429 Too Many Requests\r\nRetry-After: 1\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()); + let _ = write!(&c, "HTTP/1.1 429 Too Many Requests\r\nRetry-After: 1\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n{b}", b.len(), cors = serve::cors(&c)); oc.fetch_sub(1, Relaxed); return; } }, _ => None, }; + // A streamed chat for a model that answers one request at a time gets its head while it waits. + let mut q = q; + if let Ok(r) = &mut q && st.lock().unwrap().own && r.method == "POST" && r.path == "/v1/chat/completions" && who.is_some() + && (k.read().unwrap().any() || serve::host_ok(&r.host, &a, &allowed)) + && serde_json::from_slice::(&r.body).is_ok_and(|v| v["stream"] == true) { + r.queued = serve::Queued::start(&c).ok(); + } let _ = tx.send((c, q, i, hold)); }); }); let s = Serving { rx: rx.into(), waiting, stop, addr, allowed_hosts, keys, usage, max_tokens: host.max_tokens.unwrap_or(usize::MAX), dir, model: model.clone(), extra, - dl: Default::default(), stats, opts: Default::default(), idle: host.auto_unload.map(Duration::from_secs), asleep: Default::default(), parked: Default::default(), alias: host.alias }; + dl: Default::default(), stats, opts: Default::default(), idle: host.auto_unload.map(Duration::from_secs).into(), asleep: Default::default(), parked: Default::default(), alias: host.alias, + slot_dir: host.slot_save_path }; // The model to load next and the /api/load request waiting for the outcome (none for --model). let mut next = model.map(|p| (p, None)); say!("listening on {} (models folder: {})", term::hl(&url), s.dir.display()); @@ -1770,13 +2731,13 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { // The models outside the main engine read their limit here (`ctx_limit`). if !o["ctx"].is_null() { rusting_strata::CTX.store(engine.ctx, Relaxed); } // `runner` also sets it, and calibrate runs before `runner`. - set_kv_env(&engine.kv); + set_kv_env_for(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; } // The page's calibrate button: measure with no model loaded, then load with the measured chunk and MTP // (they replace `--chunk`/`--mtp` and the page's earlier values). let cal = if o["calibrate"] == true && engine.gpu { (engine.chunk, engine.mtp) = (None, None); - set_kv_env(&engine.kv); + set_kv_env_for(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; s.stats.lock().unwrap().unload(Some(s.name(&p))); vram_margins(&engine.vram_margin, &engine.device) .and_then(|mb| calibrate(&p, engine.aux_model_path(), engine.ctx, &mb.into_iter().map(|mb| mb << 20).collect::>(), engine.backend.as_deref(), &engine.device, @@ -1789,7 +2750,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { // `--auto-unload`: `serve_model` has freed the model. Its name stays in the model list, as a chat // loads it again. Ok(Next::Idle) => { - say!("unloaded {} after {} s without a chat request", p.display(), s.idle.map_or(0, |d| d.as_secs())); + say!("unloaded {} after {} s without a chat request", p.display(), s.idle.lock().unwrap().map_or(0, |d| d.as_secs())); s.sleep(p, engine.ctx); } Ok(_) => return Ok(()), @@ -1801,7 +2762,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { let (mut c, ..) = s.parked.lock().unwrap().take().unwrap(); s.waiting.fetch_sub(1, Relaxed); let b = json!({"error": {"message": format!("loading {}: {e:#}", stem(&p)), "type": "server_error"}}).to_string(); - let _ = write!(c, "HTTP/1.1 503 Service Unavailable\r\nRetry-After: 10\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()); + let _ = write!(c, "HTTP/1.1 503 Service Unavailable\r\nRetry-After: 10\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n{b}", b.len(), cors = serve::cors(&c)); let back = s.asleep.lock().unwrap().take(); match back { Some(a) => s.sleep(a, engine.ctx), None => s.stats.lock().unwrap().unload(None) } } @@ -1809,11 +2770,11 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { Err(e) => { engine = old; rusting_strata::CTX.store(old_ctx, Relaxed); - set_kv_env(&engine.kv); + set_kv_env_for(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; s.stats.lock().unwrap().unload(None); say!("loading {}: {e:#}", p.display()); let b = json!({"error": {"message": format!("{e:#}"), "type": "server_error"}}).to_string(); - let _ = write!(w.unwrap(), "HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()); + let mut w = w.unwrap(); let _ = write!(w, "HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n{b}", b.len(), cors = serve::cors(&w)); } } } @@ -1882,11 +2843,15 @@ fn decode_greedy_big(m: &mut dyn FnMut(u32) -> Vec, logits: Vec, eos: /// `strata bench` for DeepSeek-V4.1 (token-at-a-time reference forward, GPU matvecs when enabled). fn bench_deepseek(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { - rusting_strata::deepseek::chat::gpu_defaults(); + rusting_strata::deepseek::chat::ds_defaults(); + engine.ds_threads(); let tok = Tokenizer::from_gguf(g)?; let mut m = rusting_strata::deepseek::forward::DsModel::new(g)?; let eos = tok.eos_ids(); let mut results = Vec::with_capacity(pp.len()); + // One untimed prefill first, as llama-bench does: the first run reads the experts off disk (page cache cold), + // which is load time, not prefill speed. + if let Some(&n) = pp.first() { m.reset(); m.prefill(&prose(&tok, n)?); } for &n in pp { let ids = prose(&tok, n)?; let (mut p, mut d) = (Vec::new(), Vec::new()); @@ -1920,15 +2885,22 @@ fn bench_deepseek(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, write_bench_json(json_out, &meta, &results, expert.as_ref()) } -/// `strata bench` for a token-by-token forward (GPU matvecs when enabled). +/// `strata bench` for a token-by-token forward (GPU matvecs when enabled); `$decode` runs the greedy tokens and +/// returns their count (`step` after step by default). macro_rules! bench_tokenwise { ($name:ident, $model:ty) => { + bench_tokenwise!($name, $model, |m: &mut $model, logits: Vec, eos: &[u32], tg: usize| decode_greedy_big(&mut |t| m.step(t), logits, eos, tg), 0); + }; + ($name:ident, $model:ty, $decode:expr, $mtp:expr) => { fn $name(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { rusting_strata::deepseek::chat::gpu_defaults(); let tok = Tokenizer::from_gguf(g)?; let mut m = <$model>::new(g)?; let eos = tok.eos_ids(); let mut results = Vec::with_capacity(pp.len()); + // One untimed prefill first, as llama-bench does: the first run reads the experts off disk (page cache cold), + // which is load time, not prefill speed. + if let Some(&n) = pp.first() { m.reset(); m.prefill(&prose(&tok, n)?); } for &n in pp { let ids = prose(&tok, n)?; let (mut p, mut d) = (Vec::new(), Vec::new()); @@ -1938,7 +2910,7 @@ fn $name(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: let logits = m.prefill(&ids); p.push(n as f64 / t.elapsed().as_secs_f64()); let t = Instant::now(); - let k = decode_greedy_big(&mut |t| m.step(t), logits, &eos, tg); + let k = ($decode)(&mut m, logits, &eos, tg); d.push(k as f64 / t.elapsed().as_secs_f64()); } let (prefill, decode_stat) = (Stat::of(&p), Stat::of(&d)); @@ -1955,7 +2927,7 @@ fn $name(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: ctx: engine.ctx, chunk: 1, kv: &engine.kv, - mtp: 0, + mtp: $mtp, tg, reps, }; @@ -1964,10 +2936,72 @@ fn $name(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: }; } bench_tokenwise!(bench_hy4, rusting_strata::hy4::forward::Hy4Model); - -/// `strata bench` for Inkling 2 (uses GPU argmax decode, plus `--draft-model` DSpark / `--spec-type` context lookup). -fn bench_inkling2(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { - rusting_strata::deepseek::chat::gpu_defaults(); +bench_tokenwise!(bench_kolibri, rusting_strata::kolibri::forward::KolibriModel); +bench_tokenwise!(bench_gigachat4, rusting_strata::gigachat4::forward::GigaChat4Model, |m: &mut rusting_strata::gigachat4::forward::GigaChat4Model, logits: Vec, eos: &[u32], tg: usize| { + let mut k = 0; + m.drafts = (0, 0); + rusting_strata::gigachat4::chat::greedy_run(m, &mut None, logits, eos, tg, |_| { k += 1; true }); + if m.drafts.0 > 0 { say!("MTP drafts accepted {}/{}", m.drafts.1, m.drafts.0); } + k +}, rusting_strata::gigachat4::MTP.load(std::sync::atomic::Ordering::Relaxed) as usize); +bench_tokenwise!(bench_raon, rusting_strata::raon::forward::RaonModel); + +/// `strata bench` for Gemma 4, with the `gpu_defaults` of its generate and chat paths. +fn bench_gemma4(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { + // Use the engine's own defaults so the bench measures the same configuration as chat and generate. + rusting_strata::gemma4::gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = rusting_strata::gemma4::forward::Gemma4Model::new(g)?; + let eos = tok.eos_ids(); + let mut results = Vec::with_capacity(pp.len()); + // One untimed prefill first, as llama-bench does: the first run reads the experts off disk (page cache cold), + // which is load time, not prefill speed. + if let Some(&n) = pp.first() { m.reset(); m.prefill(&prose(&tok, n)?); } + for &n in pp { + let ids = prose(&tok, n)?; + let (mut p, mut d) = (Vec::new(), Vec::new()); + for _ in 0..reps { + m.reset(); + let t = Instant::now(); + let logits = m.prefill(&ids); + p.push(n as f64 / t.elapsed().as_secs_f64()); + let t = Instant::now(); + let k = decode_greedy_big(&mut |t| m.step(t), logits, &eos, tg); + d.push(k as f64 / t.elapsed().as_secs_f64()); + } + let (prefill, decode_stat) = (Stat::of(&p), Stat::of(&d)); + println!("pp {n:6}: prefill {} tok/s | tg {tg}: decode {} tok/s", prefill.text(), decode_stat.text()); + results.push(BenchResult { pp: n, prefill, decode: decode_stat, bytes_per_token: 0, decode_median: 0.0 }); + } + let expert = big_expert_stats(m.cfg.n_layer, m.cfg.n_expert); + let backend = rusting_strata::deepseek::mat::dev_info().map_or("cpu", |i| i.0); + let meta = BenchMeta { + backend, + backend_arg: engine.backend.as_deref(), + device: if backend == "cpu" { &[] } else { &engine.device }, + model, + ctx: engine.ctx, + // The chunk bench_sample applied through STRATA_G4_CHUNK, not the old token-at-a-time placeholder. + chunk: gemma_bench_chunk(std::env::var("STRATA_G4_CHUNK").ok().as_deref()), + kv: &engine.kv, + mtp: 0, + tg, + reps, + }; + write_bench_json(json_out, &meta, &results, expert.as_ref()) +} + +/// The Gemma 4 prefill chunk used by this process; 256 is the engine's default. +fn gemma_bench_chunk(v: Option<&str>) -> usize { + v.and_then(|s| s.parse().ok()).unwrap_or(256) +} + +/// `strata bench` for Inkling 2 (uses GPU argmax decode, plus `--draft-model` DSpark / `--spec-type` context lookup). +fn bench_inkling2(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { + // The same defaults `chat`, `generate` and `serve` set: without them the plain weights spread over both cards, + // `Device::new` refuses the second one and the whole benchmark runs the host path (about a fifth of the speed). + rusting_strata::inkling2::chat::gpu_defaults(); + engine.inkling_margin()?; let tok = Tokenizer::from_gguf(g)?; let max_ctx = engine.ctx.max(pp.iter().copied().max().unwrap_or(0) + tg + 64); let opts = rusting_strata::inkling2::chat::Inkling2Opts { @@ -1979,6 +3013,9 @@ fn bench_inkling2(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, let mut m = opts.build_model(g, &tok)?; let eos = tok.eos_ids(); let mut results = Vec::with_capacity(pp.len()); + // One untimed prefill first, as llama-bench does: the first run reads the experts off disk (page cache cold), + // which is load time, not prefill speed. + if let Some(&n) = pp.first() { m.reset(); m.prefill(&prose(&tok, n)?); } for &n in pp { let ids = prose(&tok, n)?; let (mut p, mut d) = (Vec::new(), Vec::new()); @@ -2015,7 +3052,12 @@ fn bench_inkling2(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, if m.drafts.0 > 0 { say!("speculative drafts accepted {}/{} ({:.1}%)", m.drafts.1, m.drafts.0, 100.0 * m.drafts.1 as f64 / m.drafts.0 as f64); } - let expert = big_expert_stats(m.cfg.n_layer, m.cfg.n_expert); + // A layer whose experts are one slab on a card makes no expert-cache lookups, so its tensors count as resident here; + // the hit rate is that of the cache alone (with every layer in slabs there is no lookup, and it says 100%). + let expert = big_expert_stats(m.cfg.n_layer, m.cfg.n_expert).map(|mut e| { + e.resident = (e.resident + 3 * m.slab_layers() * m.cfg.n_expert).min(e.total); + e + }); let backend = rusting_strata::deepseek::mat::dev_info().map_or("cpu", |i| i.0); let meta = BenchMeta { backend, @@ -2040,6 +3082,9 @@ fn bench_glm(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_ let eos = tok.eos_ids(); let chunk = std::env::var("STRATA_GLM_CHUNK").ok().and_then(|v| v.parse().ok()).unwrap_or(512); let mut results = Vec::with_capacity(pp.len()); + // One untimed prefill first, as llama-bench does: the first run reads the experts off disk (page cache cold), + // which is load time, not prefill speed. + if let Some(&n) = pp.first() { m.reset(); m.prefill(&prose(&tok, n)?); } for &n in pp { let ids = prose(&tok, n)?; let (mut p, mut d) = (Vec::new(), Vec::new()); @@ -2073,144 +3118,654 @@ fn bench_glm(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_ write_bench_json(json_out, &meta, &results, expert.as_ref()) } -/// Best (lowest) of three timings of `f`, in seconds. -fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { - let mut b = f64::INFINITY; - for _ in 0..3 { - let t = Instant::now(); - f()?; - b = b.min(t.elapsed().as_secs_f64()); +/// Settings shared by the v2 calibration workflow and its `spec` subcommand. +#[derive(Clone, Debug)] +struct CalibSettings { + model: PathBuf, + backend: Option, + device: Vec, + vram_margin: Vec, + kv: String, + /// More flags for every measurement ([`CalibSetup::args`]). + extra: Vec, + /// (flag, path): an MTP head or a draft model used for every measurement. + aux: Option<(&'static str, PathBuf)>, + ctx: usize, + samples: usize, + reps: usize, + warmup: usize, + pp: Vec, + tg: usize, + chunk_values: Vec, + tasks: Vec, + seed: u64, + dry_run: bool, + timeout: u64, + minutes: u64, + out: Option, + /// Only used by the `spec` subcommand. + spec_types: Vec, + draft_max: Vec, + ngram_n: Vec, + mtp_values: Vec, +} + +impl CalibSettings { + fn new(model: PathBuf) -> Self { + Self { + model, backend: None, device: vec![0], vram_margin: vec!["512".into()], kv: "f16".into(), extra: vec![], + aux: None, ctx: 4096, samples: 24, reps: 2, warmup: 0, pp: vec![128, 512, 2048], tg: 64, + chunk_values: vec![256, 512, 1024, 2048, 4096], tasks: vec!["prose".into()], + seed: 1, dry_run: false, timeout: 0, minutes: 30, out: None, + spec_types: vec![], draft_max: vec![], ngram_n: vec![], mtp_values: vec![], + } } - Ok(b) } -/// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use -/// the measured draft count. -fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { - let g = Gguf::open(model)?; - let aux_g = open_mtp_gguf(aux)?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; - // Most drafts per step to measure: a DFlash block, else as many as the runs default to. - let kload = m.cfg.dflash.as_ref().map_or(if m.draft_model.is_some() { 4 } else { 3 }, |d| d.block_size.saturating_sub(1).max(1)); - let tok = Tokenizer::from_gguf(&g)?; - let n_pf = 4096.min(ctx.saturating_sub(256)); - anyhow::ensure!(n_pf >= 512, "--ctx too small to calibrate"); - let pf = prose(&tok, n_pf)?; - let load = |chunk: usize, split: Option<&[f64]>| -> anyhow::Result { - let bk = device.iter().map(|&d| backend::open(kind, d)).collect::>>()?; - let mut gm = GpuModel::load_split_margins(&m, bk, ctx, chunk, margin, split, kload, 1).context(LOAD_HINT)?; - gm.adapt_every = 0; // fixed placement: steadier timings - Ok(gm) - }; +fn calib_work_dir() -> anyhow::Result { + let d = rusting_strata::expert_cache::cache_dir().join("calibrate"); + std::fs::create_dir_all(&d)?; + Ok(d) +} - let mut chunk = (0, 0.0); - for c in [512, 1024, 2048, 4096].into_iter().filter(|&c| c <= ctx) { - // A larger chunk's prefill scratch may not fit beside a long --ctx: keep the chunks measured so far. - let mut gm = match load(c, split.as_deref()) { Ok(gm) => gm, Err(e) if chunk.0 > 0 => { say!("chunk {c:5}: {e:#}"); break } Err(e) => return Err(e) }; - let t = best(&mut || { gm.reset()?; gm.prefill(&pf).map(drop) })?; - let tps = n_pf as f64 / t; - say!("chunk {c:5}: prefill {n_pf} tok {tps:.0} tok/s"); - if tps > chunk.1 { chunk = (c, tps); } - } - - let dec = tok.encode("Write a long story about a dragon.")?; - // Several devices and no split given by hand: measure other layer splits and keep the fastest. The split by free - // VRAM does not know a card's speed or its PCIe link; the timings do. A card with fewer layers keeps more of - // their experts in VRAM (fewer uploads over its link in prefill), and the other cards then keep fewer. - if device.len() > 1 && split.is_none() { - // Prefill of the long prompt and decode after the short one, in tok/s, with the layers per device. - let measure = |s: Option<&[f64]>| -> anyhow::Result<(Vec, f64, f64)> { - let mut gm = load(chunk.0, s)?; - gm.k = 1; - let layers = gm.part_layers(); - let mut r = Runner::Gpu(Box::new(gm)); - let tp = best(&mut || { r.reset()?; r.prefill(&pf).map(drop) })?; - let mut toks = 0; - let td = best(&mut || { - r.reset()?; - let l = r.prefill(&dec)?; - toks = decode(&mut r, &tok, false, &mut Sampler::greedy(), l, 64, None, &mut |_| Ok(false))?.0.len(); - Ok(()) - })?; - Ok((layers, n_pf as f64 / tp, toks as f64 / td)) - }; - let (base, mut bp, mut bd) = measure(None)?; - say!("split {base:?} (by free VRAM): prefill {bp:.0} tok/s, decode {bd:.1} tok/s"); - // ponytail: a fixed step of 15% of the layers and three rounds; a finer search if a report shows the best - // split lies between two steps. - let step = (m.cfg.n_layer * 3 / 20).max(1); - let (mut cur, mut seen) = (base.clone(), vec![base.clone()]); - for _ in 0..3 { - let mut better = None; - for c in split_moves(&cur, step) { - if seen.contains(&c) { continue; } - seen.push(c.clone()); - match measure(Some(&c.iter().map(|&x| x as f64).collect::>())) { - Ok((_, p, d)) => { - say!("split {c:?}: prefill {p:.0} tok/s, decode {d:.1} tok/s, prefill x decode {:.3} of the best so far", p * d / (bp * bd)); - // Prefill and decode count the same; 3% over the best so far, above the run-to-run spread. - if p * d > 1.03 * bp * bd { (bp, bd, better) = (p, d, Some(c)); } - } - Err(e) => say!("split {c:?}: {e:#}"), +static CALIB_SEQ: AtomicUsize = AtomicUsize::new(0); + +/// A short, fixed coding corpus for the built-in `coding` task. The prose paragraph routes few experts; real code +/// repeats punctuation and identifiers, which changes both n-gram acceptance and the prefill cost. +const CALIB_CODE: &str = r#"fn parse_config(path: &str) -> Result { + let text = std::fs::read_to_string(path)?; + let mut config = Config::default(); + for (line_no, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { continue; } + let mut parts = line.splitn(2, '='); + let key = parts.next().unwrap().trim(); + let value = parts.next().ok_or(Error::Syntax(line_no))?.trim(); + match key { + "threads" => config.threads = value.parse()?, + "chunk" => config.chunk = value.parse()?, + "kv" => config.kv = value.to_string(), + _ => return Err(Error::UnknownKey(line_no)), + } + } + Ok(config) +} +"#; + +/// Resolve a task label to a prompt file. `None` means the built-in prose (no `--prompt-file`). +fn calib_prompt(task: &str, dir: &Path) -> anyhow::Result> { + match task { + "prose" => Ok(None), + "coding" => { + let p = dir.join("task-coding.txt"); + std::fs::write(&p, CALIB_CODE)?; + Ok(Some(p)) + } + t if t.starts_with("user:") => { + let p = PathBuf::from(&t[5..]); + anyhow::ensure!(p.is_file(), "task prompt file {} does not exist", p.display()); + Ok(Some(p)) + } + other => anyhow::bail!("unknown task {other:?} (expected prose, coding or user:PATH)"), + } +} + +struct BenchSample { + measurements: Vec, + backend: String, +} + +struct CappedOutput { + success: bool, + stdout: String, + stderr: String, +} + +/// Run a child with a time limit. Output goes to files rather than pipes: polling a piped child without draining +/// it can deadlock once the pipe fills, and a bench failure prints a stack trace and a usage block. +fn run_capped(mut c: Command, secs: u64, dir: &Path, id: usize) -> anyhow::Result { + let out = dir.join(format!("calib-{id}-out.txt")); + let err = dir.join(format!("calib-{id}-err.txt")); + c.stdout(Stdio::from(std::fs::File::create(&out)?)).stderr(Stdio::from(std::fs::File::create(&err)?)); + let mut child = c.spawn()?; + if secs > 0 { + let deadline = Instant::now() + Duration::from_secs(secs); + loop { + if child.try_wait()?.is_some() { break; } + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); // reap the child before returning the error + let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_file(&err); + anyhow::bail!("sample timed out after {secs}s"); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + let status = child.wait()?; + let stdout = std::fs::read_to_string(&out).unwrap_or_default(); + let stderr = std::fs::read_to_string(&err).unwrap_or_default(); + let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_file(&err); + Ok(CappedOutput { success: status.success(), stdout, stderr }) +} + +/// Draft counts are in the main engine's bench JSON; the arch-specific benchners print them. Accept both. +fn parse_drafts(v: &serde_json::Value, stdout: &str) -> (usize, usize) { + let made = v["drafts"]["made"].as_u64(); + let accepted = v["drafts"]["accepted"].as_u64(); + if let (Some(a), Some(b)) = (made, accepted) { return (a as usize, b as usize); } + if let Some(pos) = stdout.find("drafts accepted ") { + let rest = &stdout[pos + "drafts accepted ".len()..]; + if let Some(tok) = rest.split_whitespace().next() { + let mut it = tok.split('/'); + if let (Some(a), Some(b)) = (it.next(), it.next()) { + if let (Ok(accepted), Ok(made)) = (a.parse::(), b.parse::()) { + return (made, accepted); } } - match better { Some(c) => cur = c, None => break } - } - if cur != base { - chunk.1 = bp; - split = Some(cur.iter().map(|&x| x as f64).collect()); - } - } - - let mut gm = load(chunk.0, split.as_deref())?; - let mut short = usize::MAX; - for n in [8, 16, 32, 64, 128] { - let p = &pf[..n]; - gm.short = usize::MAX; - let ts = best(&mut || { gm.reset()?; gm.prefill(p).map(drop) })?; - gm.short = 0; - let tb = best(&mut || { gm.reset()?; gm.prefill(p).map(drop) })?; - say!("prompt {n:4}: steps {:.1} ms, batched {:.1} ms", ts * 1e3, tb * 1e3); - if tb < ts && short == usize::MAX { short = n; } - } - if short == usize::MAX { short = 256; } - - let drafts = m.cfg.n_nextn > 0 || m.cfg.dflash.is_some() || m.cfg.eagle3.is_some() || m.draft_model.is_some(); - let kmax = if drafts { gm.k } else { 0 }; - let mut r = Runner::Gpu(Box::new(gm)); - let mut mtp = (0, 0.0); - for k in (0..=kmax).filter(|&k| k <= 4 || k % 2 == 0 || k == kmax) { - if let Runner::Gpu(g) = &mut r { g.k = k.max(1); } - let mut toks = 0; - let t = best(&mut || { - r.reset()?; - let l = r.prefill(&dec)?; - toks = decode(&mut r, &tok, k > 0, &mut Sampler::greedy(), l, 128, None, &mut |_| Ok(false))?.0.len(); - Ok(()) - })?; - // `best` times prefill too; it is the same for every k, so the ranking holds. - let tps = toks as f64 / t; - say!("mtp {k}: decode {toks} tok {tps:.1} tok/s"); - if tps > mtp.1 { mtp = (k, tps); } + } } + (0, 0) +} - let Runner::Gpu(g) = &r else { unreachable!() }; - let path = calibration_path(model, g.gpu.name(), device); - std::fs::create_dir_all(path.parent().unwrap())?; - // The file size tells another file of the same name (another repo or quant source) from this one. - let mut v = json!({"chunk": chunk.0, "mtp": mtp.0, "short": short, "ctx": ctx, "gpu": g.gpu.device(), "bytes": std::fs::metadata(model)?.len(), - "measured": {"prefill_tok_s": chunk.1.round(), "decode_tok_s": (mtp.1 * 10.0).round() / 10.0}}); - if let Some(a) = aux.and_then(|a| a.file_name()) { v["aux"] = a.to_string_lossy().into(); } - // Only a split that was measured as faster, or given by hand: without one, later runs split by the free VRAM - // they find. - if split.is_some() { - v["split"] = json!({"devices": device, "gpus": g.parts().map(|p| p.gpu.device()).collect::>(), "layers": g.part_layers()}); +/// One measurement sample: run `bench` as a child process with the candidate knobs applied, then read its JSON. +/// Using the public bench command as the measurement channel is what makes calibration work with every architecture: +/// there is one code path that times a prompt and a decode, and calibration never duplicates it. +fn bench_sample(s: &CalibSettings, knobs: &Knobs, task: &str, pps: &[usize]) -> anyhow::Result { + let dir = calib_work_dir()?; + let id = CALIB_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let json = dir.join(format!("bench-{}-{id}.json", std::process::id())); + let prompt = calib_prompt(task, &dir)?; + let exe = std::env::current_exe().context("finding this executable")?; + let chunk = knobs.i("chunk").unwrap_or(4096); + let short = knobs.i("short").unwrap_or(32); + // In a spec sweep the mtp knob holds an index into --mtp; in the main search it is the value itself. + let mtp = if s.mtp_values.is_empty() { knobs.i("mtp").unwrap_or(0) } + else { s.mtp_values[knobs.i("mtp").unwrap_or(0).min(s.mtp_values.len() - 1)] }; + + let build = |reps: usize| { + let mut c = Command::new(&exe); + c.arg("bench") + .arg("--model").arg(&s.model) + .arg("--gpu") + .arg("--pp").arg(pps.iter().map(|n| n.to_string()).collect::>().join(",")) + .arg("--tg").arg(s.tg.to_string()) + .arg("--reps").arg(reps.to_string()) + .arg("--ctx").arg(s.ctx.to_string()) + .arg("--kv").arg(&s.kv) + .arg("--chunk").arg(chunk.to_string()) + .arg("--mtp").arg(mtp.to_string()) + .arg("--short").arg(short.to_string()) + .arg("--device").arg(s.device.iter().map(|d| d.to_string()).collect::>().join(",")) + .arg("--json-out").arg(&json) + .args(&s.extra); + if let Some(b) = &s.backend { c.arg("--backend").arg(b); } + if let Some((flag, p)) = &s.aux { c.arg(flag).arg(p); } + if let Some(p) = &prompt { c.arg("--prompt-file").arg(p); } + if !s.vram_margin.is_empty() { c.arg("--vram-margin").arg(s.vram_margin.join(",")); } + // The architectures outside the main engine read their chunk from the environment at prefill time. + c.env("STRATA_DS_CHUNK", chunk.to_string()); + c.env("STRATA_GLM_CHUNK", chunk.to_string()); + c.env("STRATA_G4_CHUNK", chunk.to_string()); + if !s.spec_types.is_empty() { + let ti = knobs.i("spec_type").unwrap_or(0).min(s.spec_types.len() - 1); + let di = knobs.i("draft_max").unwrap_or(0).min(s.draft_max.len() - 1); + let ni = knobs.i("ngram_n").unwrap_or(0).min(s.ngram_n.len() - 1); + c.arg("--spec-type").arg(s.spec_types[ti].clone()); + c.arg("--spec-draft-n-max").arg(s.draft_max[di].to_string()); + c.arg("--spec-ngram-size-n").arg(s.ngram_n[ni].to_string()); + } + c + }; + if s.warmup > 0 { let _ = run_capped(build(1), s.timeout, &dir, id)?; } + let out = run_capped(build(s.reps), s.timeout, &dir, id + 1)?; + if !out.success { + let _ = std::fs::remove_file(&json); + anyhow::bail!("bench failed: {}{}", out.stdout, out.stderr); + } + let text = std::fs::read_to_string(&json).with_context(|| format!("reading {}", json.display()))?; + let v: serde_json::Value = match serde_json::from_str(&text) { + Ok(v) => v, + Err(e) => { let _ = std::fs::remove_file(&json); return Err(e.into()); } + }; + if v["schema"] != "strata.bench.v1" { + let _ = std::fs::remove_file(&json); + anyhow::bail!("bench wrote an unexpected schema"); + } + let rows = v["results"].as_array().context("bench JSON has no results")?; + let (made, accepted) = parse_drafts(&v, &out.stdout); + let mut ms = Vec::with_capacity(pps.len()); + for &pp in pps { + let r = rows.iter().find(|r| r["pp"].as_u64() == Some(pp as u64)) + .with_context(|| format!("bench JSON has no pp {pp}"))?; + let rate = |key: &str| -> anyhow::Result { + r[key]["mean"].as_f64().with_context(|| format!("bench JSON pp {pp} has no {key}.mean")) + }; + ms.push(Measurement { + prefill_tok_s: rate("prefill_tok_s")?, + decode_tok_s: rate("decode_tok_s")?, + drafts_offered: made, + drafts_accepted: accepted, + }); + } + let _ = std::fs::remove_file(&json); + Ok(BenchSample { measurements: ms, backend: v["backend"].as_str().unwrap_or("cuda").to_string() }) +} + +/// Group workloads by task, keeping their order, so one sample can benchmark several prompt depths of a corpus in a +/// single child process while different corpora use different `--prompt-file`s. +fn workload_groups(ws: &[Workload]) -> Vec<(String, Vec<(usize, Workload)>)> { + let mut out: Vec<(String, Vec<(usize, Workload)>)> = Vec::new(); + for (i, w) in ws.iter().enumerate() { + if let Some(g) = out.iter_mut().find(|g| g.0 == w.task) { g.1.push((i, w.clone())); } + else { out.push((w.task.clone(), vec![(i, w.clone())])); } + } + out +} + +fn measure_fn<'a>(s: &'a CalibSettings, backend: &'a RefCell) -> impl FnMut(&Knobs, &[Workload]) -> anyhow::Result> + 'a { + move |knobs, ws| { + let mut out: Vec<(usize, Measurement)> = Vec::with_capacity(ws.len()); + for (task, group) in workload_groups(ws) { + let pps: Vec = group.iter().map(|(_, w)| w.pp).collect(); + let sample = bench_sample(s, knobs, &task, &pps)?; + if backend.borrow().is_empty() { *backend.borrow_mut() = sample.backend.clone(); } + for ((i, _), m) in group.into_iter().zip(sample.measurements) { out.push((i, m)); } + } + // Restore the caller's workload order: the JSON report indexes both arrays by the same position. + out.sort_by_key(|(i, _)| *i); + Ok(out.into_iter().map(|(_, m)| m).collect()) + } +} + +/// A failed baseline (typically OOM at the default chunk) must not abort the run: the search can still find a +/// working point. Returning no baseline makes `search` use its neutral fallback for scoring. +fn baseline_samples(r: anyhow::Result>) -> (Vec, bool) { + match r { Ok(v) => (v, true), Err(_) => (vec![], false) } +} + +/// Whether the model has a draft head: an MTP head in the file, a DFlash/EAGLE3 head, or an auxiliary draft. +fn model_has_mtp(g: &Gguf, aux: bool) -> bool { + if aux { return true; } + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or(""); + let nextn = g.get(&format!("{arch}.nextn_predict_layers")).ok().and_then(|v| v.as_u64()).unwrap_or(0); + nextn > 0 || g.meta.keys().any(|k| k.starts_with("dflash.") || k.starts_with("eagle3.")) +} + +/// The chunk a user gets without a calibration file. `None`: the engine prefills one token at a time and reads no +/// chunk at all, so there is no chunk to search and none to write. +fn arch_default_chunk(arch: &str) -> Option { + if arch == "gemma4" { Some(256) } + else if arch == "glm5-next" { Some(512) } + else if arch == rusting_strata::hy4::ARCH || arch == rusting_strata::kolibri::ARCH || arch == rusting_strata::gigachat4::ARCH { Some(1024) } + else if rusting_strata::inkling2::is_arch(arch) { Some(256) } // its GPU prefill clamps to 256 + else if arch == "deepseek41" { None } + else { Some(4096) } +} + +/// The search space. Context and KV format are deliberately absent: they are memory choices the user makes, not +/// speed knobs to be silently changed by a calibration. An own-arch model only has its chunk (read from the +/// environment at prefill time); main-engine models also have MTP drafts and the short-prompt threshold. +fn build_space(arch: &str, s: &CalibSettings, has_mtp: bool) -> Vec { + let own = rusting_strata::config::OWN_ARCHS.contains(&arch); + let mut space = Vec::new(); + if let Some(default_chunk) = arch_default_chunk(arch) { + // A chunk larger than the context cannot be used: drop it instead of spending samples on guaranteed failures. + let mut chunks: Vec = s.chunk_values.iter().map(|n| *n as f64).filter(|&c| c <= s.ctx as f64).collect(); + // Inkling 2 clamps its GPU chunk to 256: larger values measure the same point under another label. + if rusting_strata::inkling2::is_arch(arch) { chunks.retain(|&c| c <= 256.0); } + // The engine's own default must be in the space; otherwise the baseline would be a point nobody searches. + if default_chunk <= s.ctx && !chunks.contains(&(default_chunk as f64)) { chunks.push(default_chunk as f64); } + // A chunk splits only the prompts longer than it: below the default it is searched only when a workload is at + // least the default long, above it only when one is longer. Otherwise it ties the default on every workload + // and wins on decode noise, then slows the long prompts nobody measured (#143: 1024 won on pp512 alone). + if default_chunk <= s.ctx { + let (p, d) = (s.pp.iter().max().copied().unwrap_or(0) as f64, default_chunk as f64); + chunks.retain(|&c| c == d || p >= d && (c < d || p > d)); + } + if chunks.is_empty() { chunks.push(s.ctx.min(default_chunk) as f64); } + chunks.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + space.push(KnobSpec::new("chunk", chunks, false)); + } + if !own { + let mtp: Vec = if has_mtp { vec![0.0, 1.0, 2.0, 4.0] } else { vec![0.0] }; + // `short` skips chunked prefill for prompts shorter than the threshold. The old 16/32/64/128 candidates + // never crossed a workload depth (128/512/2048), so every candidate measured the same timings. One + // threshold just above each --pp depth flips exactly that depth into the short path; 32 is the default. + // Depths past 4096 are left out: a 16K prompt on the short path runs token by token for minutes, and its + // samples used up the time budget without ever winning (issue #168). + let mut short: Vec = vec![32.0]; + short.extend(s.pp.iter().filter(|&&pp| pp <= 4096).map(|&pp| pp.saturating_add(1) as f64)); + short.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + short.dedup(); + debug_assert!(short.contains(&32.0)); + space.push(KnobSpec::new("mtp", mtp, false)); + space.push(KnobSpec::new("short", short, false)); + } + space +} + +/// A prompt plus its reply must fit the context the measurement will run at; the old calibrate checked this and the +/// diagnostic is much more useful than a run of failed samples ending in "no successful measurement". +fn check_workload_ctx(s: &CalibSettings) -> anyhow::Result<()> { + for &pp in &s.pp { + anyhow::ensure!(pp + s.tg <= s.ctx, "--pp {pp} + --tg {} exceeds --ctx {}; raise --ctx or shorten the workload", s.tg, s.ctx); + } + Ok(()) +} + +/// The baseline must be what a user runs today without a calibration file: the engine's own chunk (4096 for the +/// main engine, 256/512/1024 for Gemma 4/GLM/Hy4 and Kolibri, 256 for Inkling 2, none for DeepSeek), short 32, the physical +/// core count (left to the engine's own default), and no drafts. Not the first point of the search space. +fn baseline_knobs(space: &[KnobSpec], arch: &str) -> Knobs { + let mut k = Knobs::default(); + let default_chunk = arch_default_chunk(arch).unwrap_or(4096) as f64; + for s in space { + let v = match s.name.as_str() { + "chunk" => default_chunk, + "short" => 32.0, + "mtp" => 0.0, + _ => s.values.first().copied().unwrap_or(0.0), + }; + k.set(&s.name, if s.values.contains(&v) { v } else { s.values[0] }); + } + k +} + +/// The backend a run will look up: the one the bench child really opened, not the `--backend` request. Without a +/// request CUDA falls back to Vulkan on some machines; writing under "cuda" would make every run miss the file. +/// The request is only a fallback when nothing was measured. +fn calib_backend_name(s: &CalibSettings, measured: &RefCell) -> String { + let real = measured.borrow().clone(); + if real.is_empty() { s.backend.clone().unwrap_or_else(|| "cuda".into()) } else { real } +} + +/// The physical device the search measured on, for the v1 `gpu` compatibility check. +fn calib_gpu_name(s: &CalibSettings, backend_name: &str) -> String { + s.device.first().and_then(|&d| backend::open(Some(backend_name), d).ok()) + .map(|b| b.device().to_string()).unwrap_or_default() +} + +fn write_report(s: &CalibSettings, result: &calibrate::SearchResult) -> anyhow::Result<()> { + if let Some(out) = &s.out { + std::fs::create_dir_all(out)?; + let stem = s.model.file_stem().and_then(|x| x.to_str()).unwrap_or("model"); + let report = out.join(format!("strata-{stem}-calib-report.json")); + std::fs::write(&report, serde_json::to_string_pretty(result)?)?; + say!("full benchmark report: {}", report.display()); } + Ok(()) +} + +/// The v2 search does not measure a layer split, so a stale v1 `split` must not survive into the file it rewrites. +fn drop_split(v: &mut serde_json::Value) { + if let Some(o) = v.as_object_mut() { o.remove("split"); } +} + +/// An engine with no tunable knobs (DeepSeek reads no chunk) still gets a file: later runs stop warning and a later +/// `calibrate spec` has somewhere to put its result. Only identity and measured rates are recorded; a stale chunk +/// left by an older file of this name must not survive. +fn write_knobless_calibration(s: &CalibSettings, baseline: &[Measurement], workloads: &[Workload], arch: &str, + backend: &str, gpu: &str) -> anyhow::Result { + let path = calibration_path(&s.model, backend, &s.device); + std::fs::create_dir_all(path.parent().unwrap())?; + let mut v: serde_json::Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + drop_split(&mut v); + let first = baseline.iter().find(|m| m.valid()).cloned().unwrap_or_default(); + v["schema"] = json!(2); + v["arch"] = json!(arch); + v["gpu"] = json!(gpu); + if s.device.len() > 1 { v["devices"] = json!(s.device); } // `gpu` names the first one only (#209) + v["bytes"] = json!(std::fs::metadata(&s.model)?.len()); + v["measured"] = json!({ + "prefill_tok_s": round1(first.prefill_tok_s), + "decode_tok_s": round1(first.decode_tok_s), + }); + v["workloads"] = serde_json::to_value(workloads)?; + if let Some(o) = v.as_object_mut() { for k in ["chunk", "mtp", "short", "best", "search"] { o.remove(k); } } std::fs::write(&path, serde_json::to_string_pretty(&v)?)?; - println!("{v}\nwritten to {}", path.display()); + Ok(path) +} + +fn write_calibration(s: &CalibSettings, result: &calibrate::SearchResult, workloads: &[Workload], arch: &str, backend: &str, gpu: &str) -> anyhow::Result { + let path = calibration_path(&s.model, backend, &s.device); + std::fs::create_dir_all(path.parent().unwrap())?; + let mut v: serde_json::Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + drop_split(&mut v); + let best = &result.best; + let first = best.measurements.first().cloned().unwrap_or_default(); + v["schema"] = json!(2); + v["arch"] = json!(arch); + v["chunk"] = json!(best.knobs.i("chunk").unwrap_or(4096)); + v["mtp"] = json!(best.knobs.i("mtp").unwrap_or(0)); + v["short"] = json!(best.knobs.i("short").unwrap_or(32)); + v["ctx"] = json!(s.ctx); // the context the measurement ran at; never a recommendation to apply later + v["gpu"] = json!(gpu); + if s.device.len() > 1 { v["devices"] = json!(s.device); } // `gpu` names the first one only (#209) + v["bytes"] = json!(std::fs::metadata(&s.model)?.len()); + v["measured"] = json!({ + "prefill_tok_s": round1(first.prefill_tok_s), + "decode_tok_s": round1(first.decode_tok_s), + }); + v["best"] = serde_json::to_value(&best.knobs)?; + v["search"] = json!({ + "samples_used": result.samples_used, + "score": round1(result.best.score * 1000.0) / 1000.0, + "stop_reason": result.stop_reason, + "elapsed_ms": result.elapsed_ms, + "seed": result.seed, + }); + v["workloads"] = serde_json::to_value(workloads)?; + if let Some(a) = &s.aux { if let Some(name) = a.1.file_name() { v["aux"] = name.to_string_lossy().into(); } } + std::fs::write(&path, serde_json::to_string_pretty(&v)?)?; + write_report(s, result)?; + Ok(path) +} + +/// Pure merge used by a spec sweep: it must not replace the engine knobs measured by a previous run. +fn merge_spec_calibration(mut old: serde_json::Value, spec: &serde_json::Value, arch: &str, gpu: &str, bytes: u64) -> serde_json::Value { + old["schema"] = json!(2); + old["arch"] = json!(arch); + old["gpu"] = json!(gpu); + old["bytes"] = json!(bytes); + old["spec"] = spec.clone(); + old +} + +/// A spec sweep only adds its `spec` section: it must not replace the engine knobs measured by a previous run. +fn write_spec_calibration(s: &CalibSettings, result: &calibrate::SearchResult, arch: &str, backend: &str, gpu: &str, spec: &serde_json::Value) -> anyhow::Result { + let path = calibration_path(&s.model, backend, &s.device); + std::fs::create_dir_all(path.parent().unwrap())?; + let old: serde_json::Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + let mut v = merge_spec_calibration(old, spec, arch, gpu, std::fs::metadata(&s.model)?.len()); + v["spec_search"] = json!({"samples_used": result.samples_used, + "score": round1(result.best.score * 1000.0) / 1000.0, + "stop_reason": result.stop_reason, "seed": result.seed}); + std::fs::write(&path, serde_json::to_string_pretty(&v)?)?; + write_report(s, result)?; + Ok(path) +} + +/// The universal calibration workflow. Every supported architecture goes through here; the measurement is delegated +/// to `bench`, so there is no arch-specific timing code to keep in sync. +fn calibration_rates(samples: &[Measurement]) -> (Option, Option, Option<(usize, usize)>) { + let valid: Vec<_> = samples.iter().filter(|m| m.valid()).collect(); + if valid.is_empty() { return (None, None, None); } + let count = valid.len() as f64; + let (prefill, decode, offered, accepted) = valid.iter().fold((0.0, 0.0, 0usize, 0usize), |a, m| { + (a.0 + m.prefill_tok_s, a.1 + m.decode_tok_s, a.2 + m.drafts_offered, a.3 + m.drafts_accepted) + }); + (Some(prefill / count), Some(decode / count), (offered > 0).then_some((offered, accepted))) +} + +fn calibrate_v2(s: &CalibSettings) -> anyhow::Result<()> { + backend::check_devices(s.backend.as_deref(), &s.device)?; // before the GGUF is read: a bad --device fails here + check_workload_ctx(s)?; + let g = Gguf::open(&s.model)?; + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); + let has_mtp = model_has_mtp(&g, s.aux.is_some()); + let space = build_space(&arch, s, has_mtp); + let tasks: Vec = if s.tasks.is_empty() { vec!["prose".into()] } else { s.tasks.clone() }; + let workloads: Vec = tasks.iter().flat_map(|task| { + s.pp.iter().map(move |&pp| Workload::new(pp, s.tg, task)) + }).collect(); + say!("calibrate {arch}: {} workloads, {}-sample budget, scoring prefill and decode equally", workloads.len(), s.samples); + // Each sample is a `bench` run of its own on every device given; this process opens only the first, for its name. + if s.device.len() > 1 { say!(" devices {}", s.device.iter().map(|d| d.to_string()).collect::>().join(",")); } + for w in &workloads { say!(" {}", w.label()); } + say!("knobs: {}", space.iter().map(|k| format!("{}=[{}]", k.name, k.values.iter().map(|v| format!("{v:.0}")).collect::>().join(","))).collect::>().join(" ")); + say!("baseline (current defaults): {}", baseline_knobs(&space, &arch).label()); + if s.dry_run { say!("dry run: no measurements taken"); return Ok(()); } + + let _calibration_live = term::calibration_start(s.samples + 1); + term::calibration_sample_start("baseline"); + + let backend = RefCell::new(String::new()); + let mut measure = measure_fn(s, &backend); + let base_knobs = baseline_knobs(&space, &arch); + say!("baseline (current defaults): {}", base_knobs.label()); + let t0 = std::time::Instant::now(); + let (baseline, ok) = baseline_samples(measure(&base_knobs, &workloads)); + let (prefill_rate, decode_rate, draft_rates) = calibration_rates(&baseline); + term::calibration_sample_done("baseline", prefill_rate, decode_rate, draft_rates); + if let Some((p, d)) = prefill_rate.zip(decode_rate) { + let draft = draft_rates.map_or_else(String::new, |(n, a)| format!(" · draft {:.1}%", a as f64 * 100.0 / n as f64)); + say!("baseline sample rates: prefill {p:.0} tok/s · decode {d:.1} tok/s{draft}"); + } + let each = t0.elapsed().as_secs_f64(); + let limit = if s.minutes > 0 { format!(", stopping after {} min (--minutes)", s.minutes) } else { String::new() }; + say!("baseline took {each:.0} s; up to {} more samples of about that, {:.0} min{limit}", s.samples, each * s.samples as f64 / 60.0); + if !ok { say!("warning: baseline failed (e.g. OOM at the default chunk); searching from a neutral reference"); } + let backend_name = calib_backend_name(s, &backend); + let gpu = calib_gpu_name(s, &backend_name); + if space.is_empty() { + let path = write_knobless_calibration(s, &baseline, &workloads, &arch, &backend_name, &gpu)?; + say!("{arch}: this engine reads no chunk, MTP count or short threshold; nothing to tune"); + say!("written to {}", path.display()); + return Ok(()); + } + let cfg = SearchConfig { samples: s.samples, coarse: (s.samples / 3).min(8), starts: 3, patience: 2, seed: s.seed, + deadline: (s.minutes > 0).then(|| std::time::Instant::now() + std::time::Duration::from_secs(s.minutes * 60)) }; + let result = calibrate::search(&space, &workloads, &cfg, &Objective::balanced(), &base_knobs, baseline, &mut measure)?; + anyhow::ensure!(result.best.error.is_none(), "no successful measurement; calibration not written"); + // The baseline competes at score calibrate::MIN_GAIN, so this only happens when the baseline measurement itself failed. Never + // write a setting that cannot be shown to beat the defaults. + if result.best.score < 1.0 { + say!("best score {:.3} is below today's defaults; keeping the defaults and not writing a calibration", result.best.score); + return Ok(()); + } + say!("best {}: score {:.3} vs baseline ({:.1} samples, {}, {:.1}s)", result.best.knobs.label(), result.best.score, + result.samples_used, result.stop_reason, result.elapsed_ms as f64 / 1000.0); + let path = write_calibration(s, &result, &workloads, &arch, &backend_name, &gpu)?; + println!("{}\nwritten to {}", serde_json::to_string_pretty(&serde_json::from_str::(&std::fs::read_to_string(&path)?)?)?, path.display()); + // `--preset`: the tuned values go into it, where later runs read them as flags. + if let Some((preset, _)) = PRESET.get() { + let k = &result.best.knobs; + let set: Vec<(&str, String)> = ["chunk", "mtp", "short"].into_iter().filter_map(|n| Some((n, k.i(n)?.to_string()))).collect(); + std::fs::write(preset, set_preset_keys(&std::fs::read_to_string(preset)?, &set))?; + say!("written to {}: {}", preset.display(), set.iter().map(|(k, v)| format!("{k} = {v}")).collect::>().join(", ")); + } + Ok(()) +} + +/// Every spec knob is stored as an index into the flag's value list: the search only sees small contiguous ranges +/// and `bench_sample` can index the list directly. +fn spec_space(s: &CalibSettings) -> Vec { + vec![ + KnobSpec::new("spec_type", (0..s.spec_types.len()).map(|i| i as f64), false), + KnobSpec::new("draft_max", (0..s.draft_max.len()).map(|i| i as f64), false), + KnobSpec::new("ngram_n", (0..s.ngram_n.len()).map(|i| i as f64), false), + KnobSpec::new("mtp", (0..s.mtp_values.len()).map(|i| i as f64), false), + ] +} + +/// The baseline can only be the current defaults if those defaults are in the candidate lists. +fn ensure_spec_defaults(s: &mut CalibSettings) { + if !s.spec_types.iter().any(|t| t == "none") { s.spec_types.push("none".into()); } + if !s.draft_max.contains(&16) { s.draft_max.push(16); } + if !s.ngram_n.contains(&12) { s.ngram_n.push(12); } + if !s.mtp_values.contains(&0) { s.mtp_values.push(0); } +} + +/// The spec settings a user gets without a calibration file, expressed as indices into the --lists. +fn spec_baseline(s: &CalibSettings) -> Knobs { + let mut k = Knobs::default(); + k.set("spec_type", s.spec_types.iter().position(|t| t == "none").unwrap_or(0) as f64); + k.set("draft_max", s.draft_max.iter().position(|&n| n == 16).unwrap_or(0) as f64); + k.set("ngram_n", s.ngram_n.iter().position(|&n| n == 12).unwrap_or(0) as f64); + k.set("mtp", s.mtp_values.iter().position(|&n| n == 0).unwrap_or(0) as f64); + k +} + +/// The `spec` subcommand: one task-specific sweep of speculative settings, written under `spec` in the calibration +/// file. It uses the same budgeted search, with each task as its own workload so acceptance can differ by corpus. +fn calibrate_spec(s: &CalibSettings) -> anyhow::Result<()> { + backend::check_devices(s.backend.as_deref(), &s.device)?; + check_workload_ctx(s)?; + let g = Gguf::open(&s.model)?; + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); + let space = spec_space(s); + let workloads: Vec = s.tasks.iter().map(|t| Workload::new(s.pp[0], s.tg, t)).collect(); + say!("spec sweep {arch}: {} tasks x {} types x {} drafts x {} n-grams x {} mtp", workloads.len(), s.spec_types.len(), s.draft_max.len(), s.ngram_n.len(), s.mtp_values.len()); + if s.dry_run { say!("dry run: no measurements taken"); return Ok(()); } + let _calibration_live = term::calibration_start(s.samples + 1); + term::calibration_sample_start("baseline"); + let backend = RefCell::new(String::new()); + let mut measure = measure_fn(s, &backend); + let base = spec_baseline(s); + let (baseline, ok) = baseline_samples(measure(&base, &workloads)); + let (prefill_rate, decode_rate, draft_rates) = calibration_rates(&baseline); + term::calibration_sample_done("baseline", prefill_rate, decode_rate, draft_rates); + if let Some((p, d)) = prefill_rate.zip(decode_rate) { + let draft = draft_rates.map_or_else(String::new, |(n, a)| format!(" · draft {:.1}%", a as f64 * 100.0 / n as f64)); + say!("baseline sample rates: prefill {p:.0} tok/s · decode {d:.1} tok/s{draft}"); + } + if !ok { say!("warning: baseline failed; searching from a neutral reference"); } + say!("baseline (current defaults): {}", base.label()); + let cfg = SearchConfig { samples: s.samples, coarse: (s.samples / 3).min(8), starts: 3, patience: 2, seed: s.seed, + deadline: (s.minutes > 0).then(|| std::time::Instant::now() + std::time::Duration::from_secs(s.minutes * 60)) }; + let result = calibrate::search(&space, &workloads, &cfg, &Objective::balanced(), &base, baseline, &mut measure)?; + anyhow::ensure!(result.best.error.is_none(), "no successful spec measurement; calibration not written"); + if result.best.score < 1.0 { + say!("best spec score {:.3} is below today's defaults; keeping the defaults and not writing a spec section", result.best.score); + return Ok(()); + } + let idx = |name: &str, len: usize| result.best.knobs.i(name).unwrap_or(0).min(len.saturating_sub(1)); + let mut spec = serde_json::Map::new(); + for (i, w) in workloads.iter().enumerate() { + let m = result.best.measurements.get(i).cloned().unwrap_or_default(); + let share = if m.drafts_offered > 0 { round1(10000.0 * m.drafts_accepted as f64 / m.drafts_offered as f64) / 100.0 } else { 0.0 }; + spec.insert(w.task.clone(), json!({ + "spec_type": s.spec_types[idx("spec_type", s.spec_types.len())], + "draft_max": s.draft_max[idx("draft_max", s.draft_max.len())], + "ngram_n": s.ngram_n[idx("ngram_n", s.ngram_n.len())], + "mtp": s.mtp_values[idx("mtp", s.mtp_values.len())], + "decode_tok_s": round1(m.decode_tok_s), + "acceptance_pct": share, + })); + } + let backend_name = calib_backend_name(s, &backend); + let path = write_spec_calibration(s, &result, &arch, &backend_name, &calib_gpu_name(s, &backend_name), &serde_json::Value::Object(spec))?; + say!("spec sweep written to {}", path.display()); Ok(()) } +/// Compatibility wrapper used by the chat page's calibrate button and by any code calling the old six-argument +/// function. It maps the previous defaults onto the v2 workflow. +fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], _split: Option>) -> anyhow::Result<()> { + let mut s = CalibSettings::new(model.to_path_buf()); + s.aux = aux.map(|p| ("--draft-model", p.to_path_buf())); + s.ctx = ctx; + s.backend = kind.map(str::to_string); + s.device = device.to_vec(); + s.vram_margin = margin.iter().map(|m| (m >> 20).to_string()).collect(); + s.samples = 12; + s.pp = vec![512]; + calibrate_v2(&s) +} + + /// Which tokens end a DRY match: those whose text has a newline, colon, double quote or asterisk (llama.cpp's /// default breakers). Built once per model, as decoding the whole vocabulary takes a moment. fn dry_breakers(tok: &Tokenizer, model: &str) -> std::sync::Arc> { @@ -2237,34 +3792,44 @@ fn decode(r: &mut Runner, tok: &Tokenizer, mtp: bool, smp: &mut Sampler, mut log let (mut out, mut start, mut row, mut ahead, mut stopped) = (Vec::new(), 0, 0, None, false); let (mut in_think, budget) = think_cap.unwrap_or((false, 0)); let (mut saw_close, mut tail) = (false, String::new()); + // With a logit_bias or grammar every token is picked from the logits here: no speculation, no argmax on the GPU. + let free = smp.limit.is_none(); 'outer: while out.len() < n { let next = match ahead.take() { Some(t) => t, None => smp.pick(&logits)? as u32 }; if eos.contains(&next) { stopped = true; break; } + let mut feed = false; let toks = match r { - Runner::Gpu(g) if mtp && g.ngram.is_some() => { + Runner::Gpu(g) if free && mtp && g.ngram.is_some() => { let (toks, nx, rw) = g.hybrid_spec_step(next, row, smp)?; (ahead, row) = (Some(nx), rw); toks } - Runner::Gpu(g) if mtp => { + Runner::Gpu(g) if free && mtp => { let (toks, nx, rw) = g.spec_step(next, row, smp)?; (ahead, row) = (Some(nx), rw); toks } - Runner::Gpu(g) if g.ngram.is_some() => { + Runner::Gpu(g) if free && g.ngram.is_some() => { let (toks, nx) = g.ngram_spec_step(next, smp)?; ahead = Some(nx); toks } // Greedy without MTP: the argmax on the GPU, so only the token id is copied back, not the logits. - Runner::Gpu(g) if smp.temp <= 0.0 => { ahead = Some(g.step_greedy(next)?); vec![next] } - Runner::Slot(c) if smp.temp <= 0.0 => { ahead = Some(c.step(next, false)?.0); vec![next] } + Runner::Gpu(g) if free && smp.temp <= 0.0 => { ahead = Some(g.step_greedy(next)?); vec![next] } + // `--parallel`: a slot's step waits for the scheduler, which may prefill other prompts first, so the token + // is emitted before it is fed (else every request's first token waits for all queued prefills). + Runner::Slot(_) => { feed = true; vec![next] } _ => { logits = r.step(next)?; vec![next] } }; + macro_rules! feed { () => { if std::mem::take(&mut feed) { match r { + Runner::Slot(c) if free && smp.temp <= 0.0 => ahead = Some(c.step(next, false)?.0), + _ => logits = r.step(next)?, + } } } } for t in toks { if eos.contains(&t) { stopped = true; break 'outer; } if out.len() == n { break; } out.push(t); + term::decoded(1); let s = tok.decode(&out[start..])?; if !s.ends_with('\u{fffd}') { if budget > 0 && !saw_close { @@ -2276,15 +3841,19 @@ fn decode(r: &mut Runner, tok: &Tokenizer, mtp: bool, smp: &mut Sampler, mut log if !in_think && tail.contains("") { in_think = true; } if in_think && tail.contains("") { in_think = false; saw_close = true; } } - if emit(&s)? { stopped = true; break 'outer; } + if emit(&s)? { stopped = true; if feed { r.step(next)?; } break 'outer; } start = out.len(); } } + feed!(); if budget > 0 && in_think && !saw_close && out.len() >= budget && out.len() < n { let close_str = if tail.ends_with('\n') { "\n\n" } else { "\n\n\n" }; let mut close_ids = tok.encode(close_str)?; close_ids.truncate(n - out.len()); if !close_ids.is_empty() { + // Forced, not picked: a grammar waiting for `` has to see it. The blank lines after it are + // not part of the answer the grammar describes (JSON starts at its "{"). + if let Some(c) = smp.limit.as_mut() { for &ct in &close_ids { if !c.waiting() { break; } c.accept(ct); } } ahead = None; match r { Runner::Gpu(g) => { logits = g.force_tokens(&close_ids, &mut row)?; } @@ -2312,9 +3881,10 @@ fn decode(r: &mut Runner, tok: &Tokenizer, mtp: bool, smp: &mut Sampler, mut log } /// The answers `interface` asks for, as the arguments of the command to run: the model (a number from `models`, or -/// the last row and then a path to a file or to a folder to list), the mode, GPU or CPU, the context length and, for a server, the -/// address. An empty answer takes the default in brackets. -fn interface_args(input: &mut impl BufRead, mut models: Vec<(String, PathBuf, u64)>) -> anyhow::Result> { +/// the last row and then a path to a file or to a folder to list), the mode, GPU or CPU, which GPUs (every one of the +/// `gpus` found by default), the context length and, for a server, the address. An empty answer takes the default in +/// brackets. +fn interface_args(input: &mut impl BufRead, mut models: Vec<(String, PathBuf, u64)>, gpus: usize) -> anyhow::Result> { let on = term::out(); let mut ask = |q: &str, default: &str| -> anyhow::Result { if default.is_empty() { print!("{q}: "); } else { print!("{q} {}: ", term::paint(on, "2", &format!("[{default}]"))); } @@ -2358,6 +3928,13 @@ fn interface_args(input: &mut impl BufRead, mut models: Vec<(String, PathBuf, u6 head("Settings"); let gpu = !ask("run on the GPU (y/n)", "y")?.to_lowercase().starts_with('n'); + // Several GPUs split the layers (issue #153). + let all = (0..gpus.max(1)).map(|d| d.to_string()).collect::>().join(","); + let devices = if !gpu { String::new() } else { loop { + let a = ask("GPUs to use, by number (such as 0,1)", &all)?.replace(' ', ""); + if a.split(',').all(|d| d.parse::().is_ok()) { break a; } + println!("GPU numbers separated by commas, such as 0,1"); + } }; let ctx = loop { let a = ask("context length in tokens", "default")?; if a == "default" || a.parse::().is_ok_and(|n| n > 0) { break a; } @@ -2367,6 +3944,7 @@ fn interface_args(input: &mut impl BufRead, mut models: Vec<(String, PathBuf, u6 let mut args: Vec = vec![["chat", "serve", "serve", "bench"][mode - 1].into(), "--model".into(), model.to_string_lossy().into()]; if gpu { args.push("--gpu".into()); } + if !devices.is_empty() && devices != "0" { args.extend(["--device".into(), devices]); } if ctx != "default" { args.extend(["--ctx".into(), ctx]); } if !addr.is_empty() { args.extend(["--addr".into(), addr]); } if mode == 2 { args.push("--open".into()); } @@ -2379,10 +3957,28 @@ fn room(e: &Engine, used: usize, n: usize) -> usize { n.min(e.ctx.saturating_sub /// The chat format from the GGUF's `tokenizer.chat_template`. fn template(g: &Gguf) -> Template { let t = Template::detect(g.meta.get("tokenizer.chat_template").and_then(|v| v.as_str())); - say!("chat template: {t:?}"); + detail!("chat template: {t:?}"); t } +/// The `reasoning_effort` levels the loaded model honours, for `/v1/models`' meta and the page's think dropdown: +/// the first turns thinking off ("off" for Qwen4, whose template names its levels that way, "none" elsewhere, +/// which every model reads), the last its default or highest level. `names` is a Raon model's GGUF +/// `raon1.reasoning_effort.names` (its steering levels), `None` for every other model. Families outside the three +/// below reason at one level: "none" off, anything else their default. +fn effort_levels(arch: &str, tpl: Template, names: Option<&[String]>) -> Vec { + let lv = |v: &[&str]| v.iter().map(|&s| s.to_string()).collect::>(); + match arch { + rusting_strata::raon::ARCH => match names { + Some(n) => { let mut v = lv(&["none"]); for s in n { if !v.contains(s) { v.push(s.clone()); } } v } + None => lv(&["none", "high"]), + }, + rusting_strata::inkling2::ARCH | rusting_strata::inkling2::ARCH_RUNS => lv(&["none", "minimal", "low", "medium", "high", "xhigh"]), + rusting_strata::kolibri::ARCH => lv(&["none", "low", "medium", "high"]), + _ => match tpl { Template::Qwen4 { .. } => lv(&["off", "low", "high", "xhigh"]), _ => lv(&["none", "high"]) }, + } +} + /// Reply text without the thinking part (the template drops it from history too). /// Streams one (reasoning, answer) pair as `reasoning_content` and `content` deltas. fn send_split(w: &mut impl Write, chunk: &impl Fn(serde_json::Value, Option<&str>) -> serde_json::Value, (r, a): (String, String)) -> anyhow::Result<()> { @@ -2420,12 +4016,14 @@ struct Serving { stats: std::sync::Arc>, /// Load options of the last /api/load (`Engine::with`), applied before the next model loads. opts: std::sync::Mutex, - /// `--auto-unload`: the model is freed after this long without a chat request. - idle: Option, + /// `--auto-unload` (or the page's load option): the model is freed after this long without a chat request. + idle: std::sync::Mutex>, /// The model `--auto-unload` freed (while another loads for a chat request: the model to go back to if that load /// fails), and the chat request that waits for a load (answered once the model has loaded). asleep: std::sync::Mutex>, parked: std::sync::Mutex>, + /// `--slot-save-path`. + slot_dir: Option, } /// A complete request from the queue, with its key's place when `--max-per-key` counts it (freed once answered). @@ -2471,7 +4069,7 @@ impl Serving { let (c, q, i, hold) = match parked.map_or_else(|| rx.recv_timeout(Duration::from_millis(200)), Ok) { Ok(x) => x, Err(std::sync::mpsc::RecvTimeoutError::Timeout) if self.stopped() => { say!("stopped"); return Next::Stop } - Err(std::sync::mpsc::RecvTimeoutError::Timeout) if l.is_some() && self.idle.is_some_and(|d| last.elapsed() >= d) => return Next::Idle, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) if l.is_some() && self.idle.lock().unwrap().is_some_and(|d| last.elapsed() >= d) => return Next::Idle, Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return Next::Stop, }; @@ -2522,9 +4120,11 @@ impl Serving { if !self.wants_model(q) || !self.keys.read().unwrap().who(&r.auth).is_some_and(|w| w.admin) { return None; } let want = serde_json::from_slice::(&r.body).ok()?.model?; // Before the folders are read: most requests name the loaded model. - if loaded.is_some_and(|p| want == self.name(p) || want == stem(p)) { return None; } + // The file name with a split model's shard number still names it, as `/v1/models` listed it up to v1.5.1. + let named = |p: &Path| want == stem(p) || p.file_stem().and_then(|n| n.to_str()) == Some(want.as_str()); + if loaded.is_some_and(|p| want == self.name(p) || named(p)) { return None; } // ponytail: two files with one name in different folders: the first of the list is meant. - self.models().into_iter().find(|(id, p, _)| want == stem(p) || want == *id).map(|m| m.1).filter(|p| Some(p.as_path()) != loaded) + self.models().into_iter().find(|(id, p, _)| named(p) || want == *id).map(|m| m.1).filter(|p| Some(p.as_path()) != loaded) } /// Adds a GGUF file from anywhere on this computer to the list (`/api/load` with `path`). Only the file's @@ -2545,10 +4145,35 @@ enum Job { /// `prefill_cached` in a free slot; answers the logits, the tokens reused, the slot and when the prefill began. /// `gone` is set when the client leaves while the chat waits for a slot; the chat is then dropped. Chat { ids: Vec, sys: usize, keep: usize, owner: u64, gone: std::sync::Arc, back: std::sync::mpsc::Sender, usize, usize, Instant)>> }, + /// `prefill_image_with` in a free slot, answered as `Chat`. + Image { p: vision::Prompt, embs: Vec>>, hashes: Vec, keep: usize, owner: u64, gone: std::sync::Arc, back: std::sync::mpsc::Sender, usize, usize, Instant)>> }, /// One decode step in a slot the request holds; answers the greedy next token and the logits if `logits`. Step { slot: usize, token: u32, logits: bool, back: std::sync::mpsc::Sender)>> }, /// The request is done with its slot. Done(usize), + /// `POST /slots/{id}` (`slot_action`), refused while a request holds the slot. + Slot { slot: usize, action: String, file: Option<(String, PathBuf)>, owner: u64, back: std::sync::mpsc::Sender> }, + /// `POST /v1/vram` (`GpuModel::vram_reserve`), between two decode steps. + Vram { reserve: Option, back: std::sync::mpsc::Sender> }, +} + +/// Save, restore or erase slot `id`'s cached prompt; answers as llama-server does. +fn slot_action(g: &mut GpuModel, id: usize, action: &str, file: Option<(String, PathBuf)>, owner: u64) -> anyhow::Result { + let t = Instant::now(); + let ms = || t.elapsed().as_secs_f64() * 1e3; + Ok(match (action, file) { + ("save", Some((f, p))) => { + let (n, bytes) = g.save_slot(id, &p)?; + say!("slot {id}: saved {n} tokens to {}", p.display()); + json!({"id_slot": id, "filename": f, "n_saved": n, "n_written": bytes, "timings": {"save_ms": ms()}}) + } + ("restore", Some((f, p))) => { + let n = g.restore_slot(id, &p, owner)?; + say!("slot {id}: restored {n} tokens from {}", p.display()); + json!({"id_slot": id, "filename": f, "n_restored": n, "n_read": std::fs::metadata(&p).map_or(0, |m| m.len()), "timings": {"restore_ms": ms()}}) + } + _ => json!({"id_slot": id, "n_erased": g.erase_slot(id)?}), + }) } /// A request's handle on the model under `--parallel`; dropping it frees the slot. @@ -2558,10 +4183,20 @@ struct Client { tx: std::sync::mpsc::Sender, slot: Option, owner: u6 impl Client { fn chat(&mut self, ids: &[u32], sys: usize, keep: usize) -> anyhow::Result<(Vec, usize)> { + let ids = ids.to_vec(); + self.submit(|owner, gone, back| Job::Chat { ids, sys, keep, owner, gone, back }) + } + fn chat_image(&mut self, p: &vision::Prompt, embs: &[Vec>], hashes: &[u64], keep: usize) -> anyhow::Result<(Vec, usize)> { + let (p, embs, hashes) = (p.clone(), embs.to_vec(), hashes.to_vec()); + self.submit(|owner, gone, back| Job::Image { p, embs, hashes, keep, owner, gone, back }) + } + /// Send a prompt job and wait for its slot. + fn submit(&mut self, job: impl FnOnce(u64, std::sync::Arc, std::sync::mpsc::Sender, usize, usize, Instant)>>) -> Job) + -> anyhow::Result<(Vec, usize)> { if let Some(s) = self.slot.take() { let _ = self.tx.send(Job::Done(s)); } let (back, r) = std::sync::mpsc::channel(); let gone = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - self.tx.send(Job::Chat { ids: ids.to_vec(), sys, keep, owner: self.owner, gone: gone.clone(), back }).map_err(|_| anyhow::anyhow!("model gone"))?; + self.tx.send(job(self.owner, gone.clone(), back)).map_err(|_| anyhow::anyhow!("model gone"))?; let (logits, reused, s, started) = loop { match r.recv_timeout(Duration::from_millis(250)) { Ok(x) => break x?, @@ -2602,6 +4237,8 @@ struct Sched { chats: std::collections::VecDeque, steps: Vec<(usize, u32, bool, std::sync::mpsc::Sender)>>)>, since: Option, + /// `Job::Slot`s, run before the next prefill. + slot_jobs: Vec, } impl Sched { @@ -2614,7 +4251,7 @@ impl Sched { /// customer's burst of requests does not hold back the others'. With one key (or none) it is the oldest. fn next_chat(&self) -> Option { let holds = |o: u64| self.held.iter().zip(&self.who).filter(|&(&h, &w)| h && w == o).count(); - (0..self.chats.len()).min_by_key(|&j| (if let Job::Chat { owner, .. } = &self.chats[j] { holds(*owner) } else { usize::MAX }, j)) + (0..self.chats.len()).min_by_key(|&j| (if let Job::Chat { owner, .. } | Job::Image { owner, .. } = &self.chats[j] { holds(*owner) } else { usize::MAX }, j)) } /// How long to wait for jobs: until the steps of all decoding slots are in, at most `GATHER` after the first. @@ -2634,6 +4271,7 @@ impl Sched { match j { Job::Done(s) => { self.held[s] = false; self.tick += 1; self.freed[s] = self.tick; } Job::Step { slot, token, logits, back } => { self.since.get_or_insert_with(Instant::now); self.steps.push((slot, token, logits, back)); } + j @ (Job::Slot { .. } | Job::Vram { .. }) => self.slot_jobs.push(j), c => self.chats.push_back(c), } } @@ -2645,13 +4283,33 @@ impl Sched { /// (fewer graphs to capture). fn run(&mut self, g: &mut GpuModel) { // ponytail: fixed row count from which the GEMM forward (`step_batch`) replaces the matvec one; `calibrate` - // should measure it per model and machine. STRATA_BATCH_MIN overrides. - let min = std::env::var("STRATA_BATCH_MIN").ok().and_then(|v| v.parse().ok()).unwrap_or(8); + // should measure it per model and machine. STRATA_BATCH_MIN overrides. With experts 16: below it the step of + // `STEP_ROWS` rows, whose missed experts the CPU worker runs beside the GPU, was faster (Qwen3.6-35B-A3B, RTX 3060). + // Dense 4: at 4 rows step_batch took 15.9 ms against step_rows' 17.0 (Qwen3-4B Q4_K_M) and 29.4 against 36.9 + // (BF16), and from 5 rows step_rows needs two forwards. + let min = std::env::var("STRATA_BATCH_MIN").ok().and_then(|v| v.parse().ok()).unwrap_or(if g.is_moe() { 16 } else { 4 }); let big = g.batch_cap() > 0 && self.steps.len() >= min; let cap = if big { g.batch_cap() } else { rusting_strata::gpu_model::STEP_ROWS }; - let mut batch: Vec<_> = self.steps.drain(..self.steps.len().min(cap)).collect(); - batch.sort_by_key(|s| s.0); + let batch: Vec<_> = self.steps.drain(..self.steps.len().min(cap)).collect(); self.since = if self.steps.is_empty() { None } else { Some(Instant::now() - Self::GATHER) }; + // ponytail: a slot that holds an image prompt (RoPE offset from its KV rows) steps alone; give the batched + // forwards per-row offsets if image chats under --parallel get common. + let (lone, mut batch): (Vec<_>, Vec<_>) = batch.into_iter().partition(|b| g.slot_shifted(b.0)); + for (sl, token, want, back) in lone { + g.use_slot(sl); + let _ = back.send(g.step(token).map(|l| (rusting_strata::ops::argmax(&l) as u32, if want { l } else { vec![] }))); + } + // A slot whose KV cannot grow for its token (no VRAM left) fails alone, not the whole forward. + batch.retain(|b| match g.kv_step(b.0) { Ok(()) => true, Err(err) => { let _ = b.3.send(Err(err)); false } }); + if batch.is_empty() { return; } + batch.sort_by_key(|s| s.0); + // The batched forwards read the current slot's RoPE offset: make an unshifted slot current. + g.use_slot(batch[0].0); + let big = big && batch.len() >= min; + if !big && batch.len() > rusting_strata::gpu_model::STEP_ROWS { + self.steps.extend(batch.drain(rusting_strata::gpu_model::STEP_ROWS..)); + self.since = Some(Instant::now() - Self::GATHER); + } let rows: Vec<_> = batch.iter().map(|b| (b.0, b.1, b.2)).collect(); match if big { g.step_batch(&rows) } else { g.step_rows(&rows) } { Ok(rows) => for (b, l) in batch.into_iter().zip(rows) { let _ = b.3.send(Ok(l)); }, @@ -2710,16 +4368,31 @@ impl Serving { if open && self.stopped() { say!("stopped"); open = false; } if (!open || wake.is_some() || next.lock().unwrap().is_some()) && live.load(Relaxed) == 0 { break; } // A request that comes now stays in the queue and loads the model again. - if live.load(Relaxed) == 0 && self.idle.is_some_and(|d| last.lock().unwrap().elapsed() >= d) { idle = true; break; } + if live.load(Relaxed) == 0 && self.idle.lock().unwrap().is_some_and(|d| last.lock().unwrap().elapsed() >= d) { idle = true; break; } s.take(&jobs, s.wait()); + for j in std::mem::take(&mut s.slot_jobs) { + match j { + Job::Slot { slot, action, file, owner, back } => { + let busy = s.held.get(slot).copied().unwrap_or(false); + let _ = back.send(if busy { Err(anyhow::anyhow!("slot {slot} is busy with a request")) } else { slot_action(g, slot, &action, file, owner) }); + } + Job::Vram { reserve, back } => { let _ = back.send(g.vram_reserve(reserve)); } + _ => unreachable!("only slot and vram jobs are queued here"), + } + } // Prefill between decode steps, in the free slot whose saved state the prompt extends the furthest, else // the least recently used one. - s.chats.retain(|j| !matches!(j, Job::Chat { gone, .. } if gone.load(Relaxed))); + s.chats.retain(|j| !matches!(j, Job::Chat { gone, .. } | Job::Image { gone, .. } if gone.load(Relaxed))); // Models with a batched forward prefill the queued prompts together, one free slot each. let lim = g.batch_cap().max(1); let fits = |c: &Job| matches!(c, Job::Chat { ids, .. } if ids.len() <= g.ctx()); let mut adm: Vec<(usize, Job)> = vec![]; - while adm.len() < lim { + // An image prompt runs alone, in the least recently used free slot. + if let Some(j) = s.next_chat().filter(|&j| matches!(s.chats[j], Job::Image { .. })) + && let Some(sl) = (0..n).filter(|&i| !s.held[i]).min_by_key(|&i| s.freed[i]) { + adm.push((sl, s.chats.remove(j).unwrap())); + } + while adm.len() < lim && !matches!(adm.first(), Some((_, Job::Image { .. }))) { let Some(j) = s.next_chat() else { break }; if !adm.is_empty() && !(fits(&s.chats[j]) && fits(&adm[0].1)) { break; } let Job::Chat { ids, keep, owner, .. } = &s.chats[j] else { break }; @@ -2757,14 +4430,23 @@ impl Serving { Err(e) => adm.iter().map(|_| Err(serve::copy_err(&e))).collect(), } } else { - let (sl, Job::Chat { ids, sys, keep, owner, .. }) = &adm[0] else { unreachable!() }; - g.use_slot(*sl); - g.owner = *owner; - vec![g.prefill_cached_with(ids, *sys, *keep, &mut between)] + match &adm[0] { + (sl, Job::Chat { ids, sys, keep, owner, .. }) => { + g.use_slot(*sl); + g.owner = *owner; + vec![g.prefill_cached_with(ids, *sys, *keep, &mut between)] + } + (sl, Job::Image { p, embs, hashes, keep, owner, .. }) => { + g.use_slot(*sl); + g.owner = *owner; + vec![g.prefill_image_with(p, embs, hashes, *keep, &mut between)] + } + _ => unreachable!(), + } } }; for ((sl, c), r) in adm.into_iter().zip(res) { - let Job::Chat { owner, back, .. } = c else { unreachable!() }; + let (Job::Chat { owner, back, .. } | Job::Image { owner, back, .. }) = c else { unreachable!() }; (s.held[sl], s.who[sl]) = (r.is_ok(), owner); // A client that left during the prefill takes no slot. if back.send(r.map(|(l, u)| (l, u, sl, started))).is_err() && s.held[sl] { @@ -2815,6 +4497,8 @@ fn open_mtp_gguf(path: Option<&Path>) -> anyhow::Result> { (p.to_path_buf(), None) }; if p.is_dir() && !gguf.exists() && !p.join("model.safetensors").exists() { + // A directory with shards picks the first shard, not `…-00001-of-00004`'s neighbours: `found.sort()` puts + // `…-00002-…` first once there are ten or more shards. if let Ok(rd) = std::fs::read_dir(p) { let mut found: Vec = rd .flatten() @@ -2822,8 +4506,10 @@ fn open_mtp_gguf(path: Option<&Path>) -> anyhow::Result> { .filter(|f| f.extension().and_then(|e| e.to_str()) == Some("gguf")) .collect(); found.sort(); - if let Some(first) = found.into_iter().next() { - gguf = first; + let sharded = |f: &PathBuf| f.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.contains("-of-")); + match found.iter().position(sharded) { + Some(i) => gguf = found.swap_remove(i), + None => { if let Some(first) = found.into_iter().next() { gguf = first; } } } } } @@ -2851,7 +4537,13 @@ fn open_mtp_gguf(path: Option<&Path>) -> anyhow::Result> { /// Loads `model`, answers `w` (the /api/load request that asked for it) and serves until another model is asked /// for or `--auto-unload` ends it. The model and its GPU memory are freed on return. /// A model file's name without `.gguf`: its name in `/v1/models` and in the replies unless `--alias` gives one. -fn stem(p: &Path) -> String { p.file_stem().and_then(|n| n.to_str()).unwrap_or("strata").to_string() } +fn stem(p: &Path) -> String { model_name(p.file_name().and_then(|n| n.to_str()).unwrap_or("strata.gguf")) } + +/// A model file's name as the server shows it: without `.gguf` and without the `-00001-of-0000N` of a split model's +/// first shard (issue #210). +fn model_name(file: &str) -> String { + serve::shard(file).map_or(file.strip_suffix(".gguf").unwrap_or(file), |(stem, _)| stem).to_string() +} /// The models the server offers: the models folder, the Hugging Face and llama.cpp caches, then `--model` and the /// files `/api/load` was given by path, if they are elsewhere. @@ -2874,50 +4566,77 @@ fn serve_model(model: &Path, mut engine: Engine, s: &Serving, w: &mut Option rusting_strata::gemma4::serve(&g, &tok, &name, mmproj.as_deref())?, "glm5-next" => rusting_strata::glm::serve(&g, &tok, &name)?, - "deepseek41" => rusting_strata::deepseek::chat::serve(&g, &tok, &name)?, + "deepseek41" => { engine.ds_threads(); rusting_strata::deepseek::chat::serve(&g, &tok, &name)? } rusting_strata::hy4::ARCH => rusting_strata::hy4::chat::serve(&g, &tok, &name)?, + rusting_strata::kolibri::ARCH => rusting_strata::kolibri::chat::serve(&g, &tok, &name)?, + rusting_strata::gigachat4::ARCH => rusting_strata::gigachat4::chat::serve(&g, &tok, &name)?, + rusting_strata::raon::ARCH => rusting_strata::raon::chat::serve(&g, &tok, &name)?, _ => rusting_strata::inkling2::chat::serve(&g, &tok, &name, rusting_strata::inkling2::chat::Inkling2Opts { max_ctx: 0, sampler: engine.sampler(), thinking_budget: engine.thinking_budget, think_default: engine.think_default, mmproj, draft_model: engine.draft_model.clone(), ngram_cfg: engine.ngram_config()? })?, }) } else { aux_g = open_mtp_gguf(engine.aux_model_path())?; - m = { let mut m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?; if !engine.lora.is_empty() { m.apply_lora(&engine.lora_specs())?; } m }; + m = engine.load_inference_model(&g, aux_g.as_ref())?; engine.runner(&m, model)? }; // Serving decodes one reply after a (usually cached) prompt: follow the reply's routing, not the prompt's. if let Runner::Gpu(g) = &mut r { g.set_decode_only(true); } + if r.expert_bytes_per_token() > 0 { + rusting_strata::serve::warm_up(&tok, |ids| if let Err(e) = r.prefill(ids).and_then(|_| r.reset()) { say!("warm-up: {e:#}") })?; + } { let mut st = s.stats.lock().unwrap(); st.loading = false; (st.backend, st.device, st.ctx, st.slots) = match &r { - Runner::Gpu(g) => (g.gpu.name().into(), g.gpu.device(), engine.ctx, g.slots()), + Runner::Gpu(g) => (g.gpu.name().into(), g.parts().map(|p| p.gpu.device()).collect::>().join(" + "), engine.ctx, g.slots()), Runner::Own(_) => { let d = rusting_strata::deepseek::mat::dev_stats(); (d.as_ref().map_or("cpu", |d| d.0).into(), d.map(|d| d.1).unwrap_or_default(), rusting_strata::ctx_limit(st.ctx_train.unwrap_or(0) as usize), 1) } _ => ("cpu".into(), String::new(), engine.ctx, 1), }; + st.own = matches!(r, Runner::Own(_)); gpu_stats(&r, &mut st); } let mut l = Loaded { r, tok: &tok, tpl: if _own.is_some() { Template::Xml } else { template(&g) }, name: name.clone(), path: model.to_path_buf() }; + // The Raon GGUF's steering levels, with the default RaonConfig uses when it names none (src/raon/mod.rs:115). + let raon_names: Option> = (arch == rusting_strata::raon::ARCH && g.meta.contains_key("raon1.reasoning_effort.alpha")).then(|| { + g.meta.get("raon1.reasoning_effort.names") + .and_then(|v| v.as_arr()) + .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect::>()) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| ["low".to_string(), "medium".to_string(), "high".to_string()].to_vec()) + }); + s.stats.lock().unwrap().efforts = effort_levels(arch, l.tpl, raon_names.as_deref()); say!("loaded {}", l.name); if let Some(mut w) = w.take() { let b = json!({"loaded": l.name}).to_string(); - let _ = write!(w, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()); + let _ = write!(w, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n{b}", b.len(), cors = serve::cors(&w)); } let next = s.serve(Some(&mut l), &engine); - s.stats.lock().unwrap().unload(None); + let own_drafts = { + let mut st = s.stats.lock().unwrap(); + let d = matches!(l.r, Runner::Own(_)).then(|| st.draft_kind.zip(st.drafts)).flatten(); + st.unload(None); + d + }; + if let Some((kind, (proposed, accepted))) = own_drafts && proposed > 0 { + say!("{kind} drafts accepted {accepted}/{proposed} ({:.1}%)", 100.0 * accepted as f64 / proposed as f64); + } // A failed profile save must not stop the server between two models. if let Err(e) = l.r.finish() { say!("{e:#}"); } Ok(next) @@ -2938,13 +4657,17 @@ fn gpu_stats(r: &Runner, s: &mut serve::Stats) { struct OwnState(Vec<(&'static str, Option)>); impl OwnState { - fn new() -> OwnState { + /// Called before a model of its own forward opens the GPUs: `margin` is the Inkling 2 `--vram-margin` (None for + /// the other architectures, which keep the budget their fraction of free VRAM gives). + fn new(margin: Option<&[usize]>) -> OwnState { + if let Some(mb) = margin { rusting_strata::deepseek::mat::dev_set_margin_mb(mb) } OwnState(["STRATA_DS_GPU", "STRATA_DS_GPU_FRACTION", "STRATA_DS_GPU_EXPERTS", "STRATA_DS_NOEVICT", "STRATA_GLM_PREFETCH"].map(|k| (k, std::env::var_os(k))).into()) } } impl Drop for OwnState { fn drop(&mut self) { + // `dev_free` clears the margin too. rusting_strata::deepseek::mat::dev_free(); for (k, v) in &self.0 { unsafe { match v { Some(v) => std::env::set_var(k, v), None => std::env::remove_var(k) } } @@ -2953,12 +4676,16 @@ impl Drop for OwnState { } fn gpu_model_stats(g: &GpuModel, s: &mut serve::Stats) { - s.vram = g.gpu.mem_info().ok().map(|(f, t)| ((t - f) as u64, t as u64)); - s.experts = g.cache.as_ref().map(|_| (g.hits as u64, g.misses as u64)); + // Over every device of a layer split (issue #205). + s.vram = g.parts().try_fold((0, 0), |a, p| p.gpu.mem_info().ok().map(|(f, t)| (a.0 + (t - f) as u64, a.1 + t as u64))); + s.experts = g.parts().any(|p| p.cache.is_some()).then(|| g.parts().fold((0, 0), |a, p| (a.0 + p.hits as u64, a.1 + p.misses as u64))); s.drafts = (g.drafts.0 > 0).then_some((g.drafts.0 as u64, g.drafts.1 as u64)); } /// Default models folder: `$XDG_DATA_HOME`, `%LOCALAPPDATA%` on Windows, else `~/.local/share`. +/// The totals behind `rustingstrata stats`, next to the default models folder. +fn usage_file() -> PathBuf { models_dir_default().with_file_name("usage.json") } + fn models_dir_default() -> PathBuf { std::env::var_os("XDG_DATA_HOME").or_else(|| std::env::var_os("LOCALAPPDATA")).map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".local/share")) @@ -2978,31 +4705,86 @@ fn open_browser(url: &str) { /// One Messages API stream event. fn sse(w: &mut impl Write, v: serde_json::Value) -> anyhow::Result<()> { Ok(write!(w, "event: {}\ndata: {v}\n\n", v["type"].as_str().unwrap_or_default())?) } -/// Streamed reply text as a Messages API text block (index 0), started by the first piece. -fn text_delta(w: &mut impl Write, opened: &mut bool, t: &str) -> anyhow::Result<()> { - if !std::mem::replace(opened, true) { sse(w, json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}))?; } - sse(w, json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": t}})) +/// A whole reply split into (reasoning, answer) at ``, as a streamed reply is split piece by piece. +fn split_think(open: bool, text: &str) -> (String, String) { + let mut th = Think::new(open); + let (mut r, mut a) = th.feed(text); + let (r2, a2) = th.finish(); + r += &r2; + a += &a2; + (r, a) +} + +/// The content of a whole Messages API reply: the reasoning as a `thinking` block (its signature empty: a local model +/// has none to give), then the answer as a `text` block, then the tool calls. +fn anthropic_content(reasoning: &str, text: &str, uses: Vec) -> Vec { + let thinking = (!reasoning.is_empty()).then(|| json!({"type": "thinking", "thinking": reasoning, "signature": ""})); + let text = (!text.is_empty()).then(|| json!({"type": "text", "text": text})); + thinking.into_iter().chain(text).chain(uses).collect() +} + +/// A streamed Messages API reply: the reasoning as a `thinking` block, then the answer as a `text` block. Each block +/// starts with its first piece and stops before the next one starts; `next` is the index the next block (a tool +/// call) takes. A thinking block gets an empty `signature_delta` before it stops, as the API requires. +struct AnthStream { think: Think, open: Option, next: usize } + +impl AnthStream { + fn new(think_open: bool) -> AnthStream { AnthStream { think: Think::new(think_open), open: None, next: 0 } } + /// Sends what is safe to send of `t` (a `` split over two pieces waits for the second). + fn feed(&mut self, w: &mut impl Write, t: &str) -> anyhow::Result<()> { + let p = self.think.feed(t); + self.send(w, p) + } + /// Sends `rest` and what the splitter still holds, then stops the open block. + fn finish(&mut self, w: &mut impl Write, rest: &str) -> anyhow::Result<()> { + self.feed(w, rest)?; + let p = self.think.finish(); + self.send(w, p)?; + self.close(w) + } + fn send(&mut self, w: &mut impl Write, (r, a): (String, String)) -> anyhow::Result<()> { + self.piece(w, true, &r)?; + self.piece(w, false, &a) + } + fn piece(&mut self, w: &mut impl Write, thinking: bool, t: &str) -> anyhow::Result<()> { + if t.is_empty() { return Ok(()); } + if self.open != Some(thinking) { + self.close(w)?; + // The same shape as a whole reply's block; the (empty) signature also comes as a `signature_delta` at the end. + let block = if thinking { json!({"type": "thinking", "thinking": "", "signature": ""}) } else { json!({"type": "text", "text": ""}) }; + sse(w, json!({"type": "content_block_start", "index": self.next, "content_block": block}))?; + self.open = Some(thinking); + } + let delta = if thinking { json!({"type": "thinking_delta", "thinking": t}) } else { json!({"type": "text_delta", "text": t}) }; + sse(w, json!({"type": "content_block_delta", "index": self.next, "delta": delta})) + } + fn close(&mut self, w: &mut impl Write) -> anyhow::Result<()> { + let Some(thinking) = self.open.take() else { return Ok(()) }; + if thinking { + sse(w, json!({"type": "content_block_delta", "index": self.next, "delta": {"type": "signature_delta", "signature": ""}}))?; + } + sse(w, json!({"type": "content_block_stop", "index": self.next}))?; + self.next += 1; + Ok(()) + } +} + +fn format_done_line(key_name: &str, last: &serve::Last, experts: &str, drafts: &str) -> String { + let decode_s = last.decode_ms / 1e3; + let prefill_s = last.prefill_ms / 1e3; + // Cached prompt tokens were not prefilled again, so they do not count toward the prefill speed. + let new_prompt = last.prompt_tokens.saturating_sub(last.cached_tokens); + let decode_tps = if decode_s > 0.0 { last.completion_tokens as f64 / decode_s } else { 0.0 }; + let prefill_tps = if prefill_s > 0.0 { new_prompt as f64 / prefill_s } else { 0.0 }; + format!( + "done: key={key_name} model={} prompt={} tok ({} cached) -> {} tok in {decode_s:.2} s, \ + decode {decode_tps:.1} tok/s, prefill {prefill_tps:.1} tok/s{experts}{drafts}, finish={}", + last.model, last.prompt_tokens, last.cached_tokens, last.completion_tokens, last.finish + ) } -/// The `timings` block llama-server puts in its responses. llama-swap and other -/// OpenAI-compatible clients read it for prefill/decode rates. `prompt_n` is the -/// uncached part of the prompt and `cache_n` the part served from cache, as in -/// llama-server. fn llama_timings(l: &serve::Last) -> serde_json::Value { - let prompt_n = l.prompt_tokens.saturating_sub(l.cached_tokens); - let per_token_ms = |ms: f64, n: usize| if n == 0 { 0.0 } else { ms / n as f64 }; - let per_second = |ms: f64, n: usize| if ms > 0.0 { n as f64 * 1e3 / ms } else { 0.0 }; - json!({ - "prompt_n": prompt_n, - "prompt_ms": l.prefill_ms, - "prompt_per_token_ms": per_token_ms(l.prefill_ms, prompt_n), - "prompt_per_second": per_second(l.prefill_ms, prompt_n), - "predicted_n": l.completion_tokens, - "predicted_ms": l.decode_ms, - "predicted_per_token_ms": per_token_ms(l.decode_ms, l.completion_tokens), - "predicted_per_second": per_second(l.decode_ms, l.completion_tokens), - "cache_n": l.cached_tokens, - }) + serve::timings(l.prompt_tokens, l.cached_tokens, l.completion_tokens, l.prefill_ms, l.decode_ms) } /// The chat page, served by the connection threads of `strata serve`. @@ -3017,9 +4799,13 @@ fn anthropic_refused(w: &mut TcpStream, r: &Runner) -> bool { fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Loaded>, e: &Engine, s: &Serving, i: usize, next: &mut Option<(PathBuf, TcpStream)>) -> anyhow::Result<()> { + // The response head of a streamed chat that waited in the queue may be out already: then a refusal is one + // error line of the stream. + let head_sent = q.as_ref().ok().and_then(|r| r.queued.as_ref()).is_some_and(|x| x.take()); let send = |w: &mut TcpStream, status: &str, v: serde_json::Value| -> anyhow::Result<()> { let b = v.to_string(); - Ok(write!(w, "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len())?) + if head_sent { return Ok(write!(w, "data: {b}\n\n")?) } + Ok(write!(w, "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n{b}", b.len(), cors = serve::cors(w))?) }; // A malformed request gets a 400 (best effort: the client may be gone) and is still logged. let serve::Request { method, path, host, auth, json, body, .. } = match q { @@ -3031,7 +4817,7 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo }; let created = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_secs(); // Browsers can reach a loopback server: the Host check stops DNS rebinding, and requiring a JSON content type - // makes a cross-site POST need a CORS preflight, which is never answered. + // makes a cross-site POST need a CORS preflight, which is answered only with `--cors-origin`. // With a key the check is not needed (a rebinding page has no key) and would refuse a reverse proxy's Host. let keys = s.keys.read().unwrap().clone(); if !keys.any() && !serve::host_ok(&host, &s.addr, &s.allowed_hosts) { return send(&mut w, "403 Forbidden", json!({"error": {"message": "bad Host header: name this host with --allowed-hosts, or set --api-key", "type": "forbidden"}})); } @@ -3040,26 +4826,32 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo // Claude Code adds `?beta=true`. let route = path.split('?').next().unwrap_or_default(); // Customer keys may not load models, download files or read the server's stats. - if !who.admin && !matches!(route, "/v1/chat/completions" | "/v1/messages" | "/v1/messages/count_tokens" | "/v1/models") { - return send(&mut w, "403 Forbidden", json!({"error": {"message": "this key may use only /v1/chat/completions, /v1/messages (and count_tokens) and /v1/models", "type": "permission_error"}})); + if !who.admin && !matches!(route, "/v1/chat/completions" | "/v1/messages" | "/v1/messages/count_tokens" | "/v1/models" | "/tokenize" | "/detokenize") { + return send(&mut w, "403 Forbidden", json!({"error": {"message": "this key may use only /v1/chat/completions, /v1/messages (and count_tokens), /v1/models, /tokenize and /detokenize", "type": "permission_error"}})); } match (method.as_str(), route) { ("GET", "/api/models") => { // The model `--auto-unload` freed counts as loaded: a chat loads it again. let asleep = s.asleep.lock().unwrap().clone(); - let models: Vec<_> = s.models().into_iter().map(|(id, p, n)| json!({"id": id, "bytes": n, "image": e.mmproj.is_some() || vision::find_sibling(&p).is_some(), "loaded": l.as_ref().is_some_and(|l| l.path == p) || asleep.as_ref() == Some(&p)})).collect(); + let efforts = s.stats.lock().unwrap().efforts.clone(); + let models: Vec<_> = s.models().into_iter().map(|(id, p, n)| json!({"id": id, "bytes": n, "image": e.mmproj_for(&p).is_some(), "loaded": l.as_ref().is_some_and(|l| l.path == p) || asleep.as_ref() == Some(&p)})).collect(); // The values in effect: with a model loaded, `chunk` and `mtp` include its calibration. let options = json!({"ctx": e.ctx, "kv": e.kv, "cache_ram": e.cache_ram, "vram_margin": e.vram_margin.join(","), "mtp": e.mtp, "chunk": e.chunk, + "parallel": e.parallel, "device": e.device.iter().map(|d| d.to_string()).collect::>().join(","), + "auto_unload": s.idle.lock().unwrap().map_or(0, |d| d.as_secs()), "gpu": e.gpu, "ctx_train": s.stats.lock().unwrap().ctx_train, // false: a GPU model with no calibration file (the page offers to calibrate it). "calibrated": l.as_ref().filter(|l| e.gpu && !matches!(l.r, Runner::Own(_))).map(|l| calibration_path(&l.path, &s.stats.lock().unwrap().backend, &e.device).exists())}); - send(&mut w, "200 OK", json!({"dir": s.dir, "models": models, "options": options})) + send(&mut w, "200 OK", json!({"dir": s.dir, "models": models, "options": options, "reasoning_effort": efforts})) } // Answered once the model has loaded (or failed to). ("POST", "/api/load") => { let v = serde_json::from_slice::(&body).unwrap_or_default(); let id = v["model"].as_str().unwrap_or_default(); if let Err(err) = e.with(&v["options"]) { return send(&mut w, "400 Bad Request", json!({"error": {"message": format!("{err:#}"), "type": "invalid_request_error"}})); } + // `--auto-unload` belongs to the server, not to a model: seconds, 0 for never. + let idle = &v["options"]["auto_unload"]; + if !idle.is_null() && idle.as_u64().is_none() { return send(&mut w, "400 Bad Request", json!({"error": {"message": "auto_unload must be a whole number of seconds (0: never)", "type": "invalid_request_error"}})); } // `path` names a file outside the models folder; it joins the list. let path = v["path"].as_str().map(PathBuf::from); if let Some(p) = &path && let Err(err) = s.add(p) { return send(&mut w, "400 Bad Request", json!({"error": {"message": format!("{err:#}"), "type": "invalid_request_error"}})); } @@ -3068,6 +4860,7 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo // `calibrate: true` measures the model first; it travels with the options to the load loop. let mut o = v["options"].clone(); if v["calibrate"] == true { if !o.is_object() { o = json!({}); } o["calibrate"] = true.into(); } + if let Some(n) = idle.as_u64() { *s.idle.lock().unwrap() = (n > 0).then(|| Duration::from_secs(n)); } *s.opts.lock().unwrap() = o; *next = Some((p, w)); Ok(()) } None => send(&mut w, "404 Not Found", json!({"error": {"message": format!("no model {id:?} in {}", s.dir.display()), "type": "not_found"}})), @@ -3080,6 +4873,50 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo Err(err) => send(&mut w, "502 Bad Gateway", json!({"error": {"message": format!("{err:#}"), "type": "server_error"}})), } } + // llama-server's slot files (`--slot-save-path`). + ("POST", r) if r.starts_with("/slots/") => { + let bad = |w: &mut TcpStream, m: String| send(w, "400 Bad Request", json!({"error": {"message": m, "type": "invalid_request_error"}})); + let Some(dir) = &s.slot_dir else { return send(&mut w, "501 Not Implemented", json!({"error": {"message": "slot save and restore need --slot-save-path", "type": "not_supported_error"}})) }; + let Some(l) = l else { return send(&mut w, "503 Service Unavailable", json!({"error": {"message": "no model loaded", "type": "server_error"}})) }; + let Ok(id) = r["/slots/".len()..].parse::() else { return bad(&mut w, format!("bad slot id in {r}")) }; + let action = path.split_once('?').and_then(|(_, q)| q.split('&').find_map(|kv| kv.strip_prefix("action="))).unwrap_or_default().to_string(); + let file = match action.as_str() { + "erase" => None, + "save" | "restore" => { + let v = serde_json::from_slice::(&body).unwrap_or_default(); + let f = v["filename"].as_str().unwrap_or_default(); + if !serve::plain_file_name(f) { return bad(&mut w, format!("bad filename {f:?}: a plain file name, no folders")); } + Some((f.to_string(), dir.join(f))) + } + a => return bad(&mut w, format!("action must be save, restore or erase, not {a:?}")), + }; + let res = match &mut l.r { + Runner::Gpu(g) => slot_action(g, id, &action, file, who.id), + Runner::Slot(c) => { + let (back, rx) = std::sync::mpsc::channel(); + c.tx.send(Job::Slot { slot: id, action, file, owner: who.id, back }).map_err(|_| anyhow::anyhow!("model gone")) + .and_then(|_| rx.recv().map_err(|_| anyhow::anyhow!("model gone"))?) + } + _ => return send(&mut w, "501 Not Implemented", json!({"error": {"message": "slot save and restore are not available for this model", "type": "not_supported_error"}})), + }; + match res { Ok(v) => send(&mut w, "200 OK", v), Err(err) => bad(&mut w, format!("{err:#}")) } + } + // Give expert-cache VRAM to another program, or take it back (`GpuModel::vram_reserve`). + ("POST", "/v1/vram") => { + let bad = |w: &mut TcpStream, m: String| send(w, "400 Bad Request", json!({"error": {"message": m, "type": "invalid_request_error"}})); + let reserve = match serve::vram_reserve_request(&body) { Ok(r) => r, Err(e) => return bad(&mut w, format!("{e:#}")) }; + let Some(l) = l else { return send(&mut w, "503 Service Unavailable", json!({"error": {"message": "no model loaded", "type": "server_error"}})) }; + let res = match &mut l.r { + Runner::Gpu(g) => g.vram_reserve(reserve), + Runner::Slot(c) => { + let (back, rx) = std::sync::mpsc::channel(); + c.tx.send(Job::Vram { reserve, back }).map_err(|_| anyhow::anyhow!("model gone")) + .and_then(|_| rx.recv().map_err(|_| anyhow::anyhow!("model gone"))?) + } + _ => return send(&mut w, "501 Not Implemented", json!({"error": {"message": "only the main engine's expert cache can be resized", "type": "not_supported_error"}})), + }; + match res { Ok(v) => send(&mut w, "200 OK", v), Err(err) => bad(&mut w, format!("{err:#}")) } + } ("GET", "/api/download") => send(&mut w, "200 OK", json!(*s.dl.lock().unwrap())), ("POST", "/api/download/cancel") => { s.dl.lock().unwrap().cancel = true; send(&mut w, "200 OK", json!(*s.dl.lock().unwrap())) } // Runs on its own thread so chats go on meanwhile; the page polls GET /api/download. @@ -3099,23 +4936,39 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo }); send(&mut w, "202 Accepted", json!(*s.dl.lock().unwrap())) } + // llama.cpp's tokenizer endpoints. + ("POST", p @ ("/tokenize" | "/detokenize")) => { + let Some(l) = l else { return send(&mut w, "503 Service Unavailable", json!({"error": {"message": "no model loaded", "type": "server_error"}})) }; + match if p == "/tokenize" { serve::tokenize(l.tok, &body) } else { serve::detokenize(l.tok, &body) } { + Ok(v) => send(&mut w, "200 OK", v), + Err(err) => send(&mut w, "400 Bad Request", json!({"error": {"message": format!("{err:#}"), "type": "invalid_request_error"}})), + } + } // The prompt's tokens as the model would see them, template and tools included. ("POST", "/v1/messages/count_tokens") => { let Some(l) = l else { return send(&mut w, "503 Service Unavailable", json!({"error": {"message": "no model loaded", "type": "server_error"}})) }; if anthropic_refused(&mut w, &l.r) { return Ok(()); } - match serve::messages_body(&body).and_then(|b| serve::chat_request(&b)) { - Ok(req) => { - let prompt = l.tpl.render(&req.messages, &req.tools, req.think.unwrap_or(e.think_default), req.preserve_thinking.unwrap_or(e.preserve_thinking), true); - let images: Vec = req.messages.iter().flat_map(|m| m.images.iter().cloned()).collect(); - let n = if images.is_empty() { l.tok.encode(&prompt)?.len() } else { - let mmproj = e.mmproj.clone().or_else(|| vision::find_sibling(&l.path)); - let mmproj = mmproj.as_deref().context("image input needs --mmproj")?; - let input = load_images(mmproj, &images)?; - build_image_prompt(l.tok, &input, &images, &prompt)?.ids.len() - }; - send(&mut w, "200 OK", json!({"input_tokens": n})) + // An image the server cannot use (no projector, a URL that is not an image) gets a 400 like a malformed body. + let n = serve::messages_body(&body).and_then(|b| serve::chat_request(&b)).and_then(|mut req| { + req.default_effort(e.reasoning_effort.as_deref()); + let (tpl, think) = l.tpl.with_effort(req.reasoning_effort.as_deref(), req.think); + let prompt = tpl.render(&req.messages, &req.tools, think.unwrap_or(e.think_default), req.preserve_thinking.unwrap_or(e.preserve_thinking), true); + let images: Vec = req.messages.iter().flat_map(|m| m.images.iter().cloned()).collect(); + Ok(if images.is_empty() { l.tok.encode(&prompt)?.len() } else { + let mmproj = e.mmproj_for(&l.path); + let mmproj = mmproj.as_deref().context("image input needs --mmproj")?; + let input = load_images(mmproj, &images)?; + build_image_prompt(l.tok, &input, &images, &prompt)?.ids.len() + }) + }); + match n { + Ok(n) => send(&mut w, "200 OK", json!({"input_tokens": n})), + Err(err) => { + let sent = send(&mut w, "400 Bad Request", json!({"error": {"message": format!("{err:#}"), "type": "invalid_request_error"}})); + // Encoding an image can run on the GPU: a lost device still ends the server, as in the serve loop. + serve::exit_if_gpu_dead(&err); + sent } - Err(err) => send(&mut w, "400 Bad Request", json!({"error": {"message": format!("{err:#}"), "type": "invalid_request_error"}})), } } // The Anthropic Messages API (Claude Code) is translated to a chat request, and the reply back. @@ -3123,33 +4976,35 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo let anth = p == "/v1/messages"; let Some(l) = l else { return send(&mut w, "503 Service Unavailable", json!({"error": {"message": "no model loaded", "type": "server_error"}})) }; if anth && anthropic_refused(&mut w, &l.r) { return Ok(()); } + let mut _live = term::Live::start(); let (r, tok, tpl, name) = (&mut l.r, &l.tok, l.tpl, l.name.as_str()); match r { Runner::Gpu(g) => g.owner = who.id, Runner::Slot(c) => (c.owner, c.conn) = (who.id, w.try_clone().ok()), _ => {} } let mut req = match if anth { serve::messages_body(&body) } else { Ok(body.clone()) }.and_then(|b| serve::chat_request(&b)) { Ok(q) => q, Err(err) => return send(&mut w, "400 Bad Request", json!({"error": {"message": format!("{err:#}"), "type": "invalid_request_error"}})), }; + req.default_effort(e.reasoning_effort.as_deref()); + // Qwen4 reads the effort level itself; "off" turns its thinking off. + let (tpl, think) = tpl.with_effort(req.reasoning_effort.as_deref(), req.think); + req.think = think; + if e.force_sampling { req.drop_sampling(); } let key_name = if who.name.is_empty() { "open" } else { who.name.as_str() }; // The `done:` line of a chat request, and its line in the usage log. - let log = |last: &serve::Last| { - let decode_s = last.decode_ms / 1e3; - let prefill_s = last.prefill_ms / 1e3; + let log = |last: &serve::Last, experts: &str, drafts: &str| { // Cached prompt tokens were not prefilled again, so they do not count toward the prefill speed. - let new_prompt = last.prompt_tokens.saturating_sub(last.cached_tokens); - let decode_tps = if decode_s > 0.0 { last.completion_tokens as f64 / decode_s } else { 0.0 }; - let prefill_tps = if prefill_s > 0.0 { new_prompt as f64 / prefill_s } else { 0.0 }; - say!("done: key={key_name} model={} prompt={} tok ({} cached) -> {} tok in {decode_s:.2} s, \ - decode {decode_tps:.1} tok/s, prefill {prefill_tps:.1} tok/s, finish={}", - last.model, last.prompt_tokens, last.cached_tokens, last.completion_tokens, last.finish); + term::server_sample(last.prompt_tokens.saturating_sub(last.cached_tokens), last.cached_tokens, last.prefill_ms / 1e3, last.completion_tokens, last.decode_ms / 1e3); + say!("{}", format_done_line(key_name, last, experts, drafts)); if let Some(f) = &s.usage { let mut v = json!(last); v["key"] = who.name.clone().into(); // A failed write must not fail the reply; it is reported. if let Err(err) = writeln!(f.lock().unwrap(), "{v}") { say!("usage log: {err}"); } } + if let Err(err) = serve::Usage::add(&usage_file(), key_name, last) { say!("stats: {err:#}"); } }; // A model outside the main engine answers the request itself (greedy; it fails before it writes). if let Runner::Own(chat) = r { + req.head_sent = head_sent; if s.max_tokens < usize::MAX { req.max_tokens = Some(req.max_tokens.unwrap_or(s.max_tokens).min(s.max_tokens)); } say!("request: {method} {p} key={key_name} model={name} messages={} stream={} tools={}", req.messages.len(), req.stream, req.tools.len()); s.stats.lock().unwrap().busy += 1; @@ -3161,9 +5016,13 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo gpu_stats(r, &mut st); return match res { Ok(d) => { + if let Some((kind, proposed, accepted)) = d.drafts { + st.add_drafts(kind, proposed as u64, accepted as u64); + } + let drafts = serve::format_drafts_suffix(d.drafts); let last = serve::Last { at: created, model: name.into(), system_tokens: 0, cached_tokens: d.cached, prompt_tokens: d.prompt, completion_tokens: d.completion, prefill_ms: d.prefill_s * 1e3, decode_ms: (total_ms - d.prefill_s * 1e3).max(0.0), finish: d.finish.into() }; - log(&last); + log(&last, "", &drafts); st.record(last); Ok(()) } @@ -3173,6 +5032,7 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo } }; } + if head_sent { return send(&mut w, "", json!({"error": {"message": "the model changed while this request waited; send it again", "type": "server_error"}})); } // Room is checked on the full prompt before any state changes. let preserve = req.preserve_thinking.unwrap_or(e.preserve_thinking); // An assistant message at the end is continued, not answered: the prompt stops inside it. @@ -3183,23 +5043,42 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo let n_sys = req.messages.iter().take_while(|m| m.role == "system").count(); let system = tpl.render(&req.messages[..n_sys], &req.tools, req.think.unwrap_or(e.think_default), preserve, false); let images: Vec = req.messages.iter().flat_map(|m| m.images.iter().cloned()).collect(); - let image_input = if images.is_empty() { None } else { - let mmproj = e.mmproj.clone().or_else(|| vision::find_sibling(&l.path)); - let mmproj = mmproj.as_deref().context("image input needs --mmproj")?; - Some(load_images(mmproj, &images)?) - }; - let vision_prompt = match &image_input { - Some(input) => Some(build_image_prompt(tok, input, &images, &prompt)?), - None => None, + // An image the server cannot use (no projector, a URL that is not an image) gets a 400, not a dropped connection. + let (image_input, vision_prompt, ids) = match (|| -> anyhow::Result<_> { + let image_input = if images.is_empty() { None } else { + let mmproj = e.mmproj_for(&l.path); + let mmproj = mmproj.as_deref().context("image input needs --mmproj")?; + Some(load_images(mmproj, &images)?) + }; + let vision_prompt = match &image_input { + Some(input) => Some(build_image_prompt(tok, input, &images, &prompt)?), + None => None, + }; + let ids = match &vision_prompt { Some(p) => p.ids.clone(), None => tok.encode(&prompt)? }; + Ok((image_input, vision_prompt, ids)) + })() { + Ok(x) => x, + Err(err) => { + let sent = send(&mut w, "400 Bad Request", json!({"error": {"message": format!("{err:#}"), "type": "invalid_request_error"}})); + // Encoding an image can run on the GPU: a lost device still ends the server, as in the serve loop. + serve::exit_if_gpu_dead(&err); + return sent; + } }; - let ids = match &vision_prompt { Some(p) => p.ids.clone(), None => tok.encode(&prompt)? }; // One line per chat request, and one when it finishes (see `log` above). say!("request: {method} {p} key={key_name} model={name} prompt={} tok stream={} tools={}", ids.len(), req.stream, req.tools.len()); + // The request's own expert hit rate, from the cache counters before and after it. + let hits = |r: &Runner| r.expert_summary().map(|s| (s.hits, s.misses)); + let h0 = hits(r); + // The request's own draft acceptance, from the counters before and after it. + let drafts_of = |r: &Runner| match r { Runner::Gpu(g) => Some((gpu_draft_kind(g), g.drafts)), _ => None }; + let d0 = drafts_of(r); let mut smp = e.sampler(); smp.temp = req.temperature.unwrap_or(smp.temp); smp.top_k = req.top_k.unwrap_or(smp.top_k); smp.top_p = req.top_p.unwrap_or(smp.top_p); + smp.min_p = req.min_p.unwrap_or(smp.min_p); smp.presence = req.presence_penalty.unwrap_or(smp.presence); smp.frequency = req.frequency_penalty.unwrap_or(smp.frequency); smp.repeat = req.repeat_penalty.unwrap_or(smp.repeat); @@ -3209,11 +5088,15 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo smp.dry_allowed = req.dry_allowed_length.unwrap_or(smp.dry_allowed); if smp.dry_mult > 0.0 { smp.dry_breakers = dry_breakers(tok, name); } smp.tool_tags = tok.token_id("").zip(tok.token_id("")).map(|(a, b)| (a as usize, b as usize)); - say!("sampling: temp={} top_k={} top_p={} presence={} frequency={} repeat={}/{} dry={}/{}/{}", smp.temp, smp.top_k, smp.top_p, + say!("sampling: temp={} top_k={} top_p={} min_p={} presence={} frequency={} repeat={}/{} dry={}/{}/{}", smp.temp, smp.top_k, smp.top_p, smp.min_p, smp.presence, smp.frequency, smp.repeat, smp.last_n, smp.dry_mult, smp.dry_base, smp.dry_allowed); if req.seed.is_some() { smp.rng = seed(req.seed); } + smp.limit = match rusting_strata::grammar::Constraint::new(&req, tok) { + Ok(c) => c, + Err(err) => return send(&mut w, "400 Bad Request", json!({"error": {"message": format!("{err:#}"), "type": "invalid_request_error"}})), + }; let n = room(e, ids.len(), req.max_tokens.unwrap_or(usize::MAX).min(s.max_tokens)); - if n == 0 { return send(&mut w, "400 Bad Request", json!({"error": {"message": format!("prompt of {} tokens fills the context", ids.len()), "type": "invalid_request_error"}})); } + if n == 0 { return send(&mut w, "400 Bad Request", json!({"error": {"message": serve::too_long(ids.len(), e.ctx), "type": "invalid_request_error"}})); } let id = format!("chatcmpl-{i}"); let chunk = |delta: serde_json::Value, finish: Option<&str>| json!({"id": id, "object": "chat.completion.chunk", "created": created, "model": name, "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}); @@ -3221,11 +5104,13 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo let tools = req.tool_calls && !req.tools.is_empty(); let mut cached = 0; let mut k = 0; // tokens decoded - let mut opened = false; // Messages API stream: the text block has started let mut hold = Hold::new(tools, req.stop); + let mut streamed = Vec::new(); // the tool-call arguments a stream has sent // A prompt that ends in an open think block makes the reply start with reasoning, up to ``. let think_open = prompt.trim_end().ends_with(""); + if think_open && let (Some(c), Some(close)) = (smp.limit.as_mut(), tok.token_id("")) { c.after_think(close); } let mut think = Think::new(think_open); + let mut blocks = AnthStream::new(think_open); // a Messages API stream's content blocks let n_system = tok.encode(&system)?.len(); let (mut t0, mut t1) = (Instant::now(), Instant::now()); // Under `--parallel` a request is busy (and its prefill timed) from when the model takes it, not while it @@ -3243,17 +5128,29 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo let res = (|| -> anyhow::Result<(Vec, bool)> { let logits; if serve::gone(&w) { anyhow::bail!("client closed the connection"); } - let (chat_ids, chat_logits, chat_cached) = match &vision_prompt { - Some(p) => (p.ids.clone(), r.chat_image(p, &image_input.as_ref().unwrap().embeddings)?, 0), - None => r.chat(tok, &prompt, &tpl.render(&req.messages[..n_hist], &req.tools, req.think.unwrap_or(e.think_default), preserve, false), &system)?, - }; + // The head goes out before the prompt runs, and comments follow it while the prompt runs (`serve::alive`). + if req.stream { write!(w, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: close\r\n{cors}\r\n", cors = serve::cors(&w))?; } + let (chat_ids, chat_logits, chat_cached) = serve::alive(&w, req.stream, || anyhow::Ok(match &vision_prompt { + Some(p) => { + // The history's rows are kept for the next turn, as `chat` keeps its tokens (#143). + let input = image_input.as_ref().unwrap(); + let history = tpl.render(&req.messages[..n_hist], &req.tools, req.think.unwrap_or(e.think_default), preserve, false); + let n_img: usize = req.messages[..n_hist].iter().map(|m| m.images.len()).sum(); + let first = ImageInput { grids: input.grids[..n_img].to_vec(), embeddings: vec![], hashes: vec![] }; + let keep = build_image_prompt(tok, &first, &images[..n_img], &history).ok() + .filter(|h| p.ids.starts_with(&h.ids)).map_or(0, |h| h.ids.len()); + let (logits, reused) = r.chat_image(p, &input.embeddings, &input.hashes, keep, &mut _live)?; + (p.ids.clone(), logits, reused) + } + None => r.chat(tok, &prompt, &tpl.render(&req.messages[..n_hist], &req.tools, req.think.unwrap_or(e.think_default), preserve, false), &system, &mut _live)?, + }))?; (_, logits, cached) = (chat_ids, chat_logits, chat_cached); + _live.prefill_cached(cached); if let Runner::Slot(c) = &*r && let Some(t) = c.started { t0 = t; start(&mut busy); } prefilled = true; t1 = Instant::now(); if serve::gone(&w) { anyhow::bail!("client closed the connection"); } if req.stream { - write!(w, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n")?; if anth { sse(&mut w, json!({"type": "message_start", "message": {"id": format!("msg_{i}"), "type": "message", "role": "assistant", "model": name, "content": [], "stop_reason": null, "stop_sequence": null, @@ -3272,21 +5169,37 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo let t = hold.push(t); if req.stream { if !t.is_empty() { - if !anth { send_split(&mut w, &chunk, think.feed(&t))?; } else { text_delta(&mut w, &mut opened, &t)?; } + if !anth { send_split(&mut w, &chunk, think.feed(&t))?; } else { blocks.feed(&mut w, &t)?; } last_stream_activity = Instant::now(); } else if last_stream_activity.elapsed() >= Duration::from_secs(15) { w.write_all(b": keep-alive\n\n")?; last_stream_activity = Instant::now(); } + if tools && !anth { + for d in call_deltas(&tpl.partial_calls(&hold.text, &req.tools), &mut streamed, i) { + write!(w, "data: {}\n\n", chunk(json!({"tool_calls": [d]}), None))?; + last_stream_activity = Instant::now(); + } + } } Ok(hold.stopped) }) })(); + let draft_counts = match r { Runner::Gpu(g) => Some(g.drafts), _ => None }; + term::server_quality(hits(r), draft_counts); { let mut st = s.stats.lock().unwrap(); if busy { st.busy -= 1; } gpu_stats(r, &mut st); } + let experts = match (h0, hits(r)) { + (Some((h0, m0)), Some((h1, m1))) if h1 + m1 > h0 + m0 => format!(", expert hit rate {:.1}%", 100.0 * (h1 - h0) as f64 / (h1 + m1 - h0 - m0) as f64), + _ => String::new(), + }; + let drafts = match (d0, drafts_of(r)) { + (Some((_, before)), Some((kind, after))) => serve::format_drafts_suffix(serve::draft_delta(kind, before, after)), + _ => String::new(), + }; let decoded = t1.elapsed(); let ms = |d: Duration| d.as_secs_f64() * 1e3; let mut last = serve::Last { at: created, model: name.into(), system_tokens: n_system, cached_tokens: cached, @@ -3300,7 +5213,7 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo last.finish = if gone { "cut" } else { "error" }.into(); // A request that failed before its prefill ended measured no prefill speed (t1 is still t0). if !prefilled { last.prefill_ms = 0.0; } - if prefilled || !gone { log(&last); } + if prefilled || !gone { log(&last, &experts, &drafts); } if !req.stream && !gone { let sent = send(&mut w, "500 Internal Server Error", json!({"error": {"message": format!("{err:#}"), "type": "server_error"}})); serve::exit_if_gpu_dead(&err); @@ -3309,12 +5222,17 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo return Err(err); } }; - // A malformed call goes out as plain text. - let calls = if tools { tpl.parse_calls(&hold.text, &req.tools) } else { None }; + // A malformed call goes out as plain text. A reply that broke off inside a later call (max_tokens, a stop + // string) or that went on past its calls keeps the calls that finished, which a stream already sent, and + // drops the rest. One cut by max_tokens still says "length". + let full = if tools { tpl.parse_calls(&hold.text, &req.tools) } else { None }; + let whole = full.is_some(); + let calls = full.or_else(|| tpl.finished_calls(&hold.text, &req.tools).filter(|_| tools)); + let called = calls.is_some() && (whole || stop); last.completion_tokens = out.len(); - last.finish = if calls.is_some() { "tool_calls" } else if stop { "stop" } else { "length" }.into(); + last.finish = if called { "tool_calls" } else if stop { "stop" } else { "length" }.into(); let timings = llama_timings(&last); - log(&last); + log(&last, &experts, &drafts); s.stats.lock().unwrap().record(last); let calls_json = |(content, calls): &(String, Vec<(String, String)>), stream: bool| { let c: Vec<_> = calls.iter().enumerate().map(|(k, (f, a))| { @@ -3322,24 +5240,32 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo if stream { c["index"] = k.into(); } c }).collect(); - if stream { json!({"tool_calls": c}) } - else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } + if stream { + // A stream sent the reasoning already, as `reasoning_content` deltas before the calls. + json!({"tool_calls": c}) + } else { + // The text before the calls opens with the reasoning when the prompt ended in an open think block. + let (r, a) = split_think(think_open, content); + let mut m = json!({"role": "assistant", "content": if a.is_empty() { None } else { Some(a) }, "tool_calls": c}); + if !r.is_empty() { m["reasoning_content"] = r.into(); } + m + } }; if anth { - let reason = if calls.is_some() { "tool_use" } else if stop { "end_turn" } else { "max_tokens" }; + let reason = if called { "tool_use" } else if stop { "end_turn" } else { "max_tokens" }; let usage = json!({"input_tokens": ids.len() - cached, "cache_read_input_tokens": cached, "cache_creation_input_tokens": 0, "output_tokens": out.len()}); let uses: Vec<_> = calls.iter().flat_map(|c| &c.1).enumerate().map(|(k, (f, a))| json!({"type": "tool_use", "id": format!("toolu_{i}_{k}"), "name": f, "input": serde_json::from_str::(a).unwrap_or(json!({}))})).collect(); if !req.stream { - let text = calls.as_ref().map_or(&hold.text, |c| &c.0); - let content: Vec<_> = (!text.is_empty()).then(|| json!({"type": "text", "text": text})).into_iter().chain(uses).collect(); + let (reasoning, text) = split_think(think_open, calls.as_ref().map_or(&hold.text, |c| &c.0)); + let content = anthropic_content(&reasoning, &text, uses); return send(&mut w, "200 OK", json!({"id": format!("msg_{i}"), "type": "message", "role": "assistant", "model": name, "content": content, "stop_reason": reason, "stop_sequence": null, "usage": usage, "timings": timings})); } - if calls.is_none() && !hold.rest().is_empty() { text_delta(&mut w, &mut opened, hold.rest())?; } - if opened { sse(&mut w, json!({"type": "content_block_stop", "index": 0}))?; } + // A parsed call's text stays held back: only the text before it (already sent) goes out. + blocks.finish(&mut w, if calls.is_none() { hold.rest() } else { "" })?; for (k, u) in uses.iter().enumerate() { - let (index, input) = (k + opened as usize, u["input"].to_string()); + let (index, input) = (blocks.next + k, u["input"].to_string()); let mut start = u.clone(); start["input"] = json!({}); sse(&mut w, json!({"type": "content_block_start", "index": index, "content_block": start}))?; @@ -3349,12 +5275,13 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo sse(&mut w, json!({"type": "message_delta", "delta": {"stop_reason": reason, "stop_sequence": null}, "usage": {"output_tokens": out.len()}, "timings": timings}))?; return sse(&mut w, json!({"type": "message_stop"})); } - let finish = if calls.is_some() { "tool_calls" } else if stop { "stop" } else { "length" }; + let finish = if called { "tool_calls" } else if stop { "stop" } else { "length" }; let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), "prompt_tokens_details": {"cached_tokens": cached}}); if req.stream { match &calls { - Some(c) => write!(w, "data: {}\n\n", chunk(calls_json(c, true), None))?, + Some(c) => for d in call_deltas(&c.1, &mut streamed, i) { write!(w, "data: {}\n\n", chunk(json!({"tool_calls": [d]}), None))?; }, + // ponytail: a call that streamed and then fails to parse also goes out as text; the client saw part of a call. None => { let (r, a) = think.feed(hold.rest()); send_split(&mut w, &chunk, (r, a))?; @@ -3367,10 +5294,7 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo Ok(write!(w, "data: {last}\n\ndata: [DONE]\n\n")?) } else { let message = match &calls { Some(c) => calls_json(c, false), None => { - let mut th = Think::new(think_open); - let (mut r, mut a) = th.feed(&hold.text); - let (r2, a2) = th.finish(); - r += &r2; a += &a2; + let (r, a) = split_think(think_open, &hold.text); if r.is_empty() { json!({"role": "assistant", "content": a}) } else { json!({"role": "assistant", "content": a, "reasoning_content": r}) } } }; send(&mut w, "200 OK", json!({"id": id, "object": "chat.completion", "created": created, "model": name, @@ -3381,6 +5305,70 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo } } +#[cfg(test)] +mod messages_api_tests { + use super::*; + + /// The events a Messages API stream wrote, one line each. + fn events(out: &[u8]) -> Vec { + String::from_utf8_lossy(out).split("\n\n").filter_map(|e| e.lines().find_map(|l| l.strip_prefix("data: "))).map(|d| { + let e: serde_json::Value = serde_json::from_str(d).unwrap(); + let (i, d) = (&e["index"], &e["delta"]); + match e["type"].as_str().unwrap() { + "content_block_start" => format!("start {i} {}", e["content_block"]["type"].as_str().unwrap()), + "content_block_stop" => format!("stop {i}"), + _ => match d["type"].as_str().unwrap() { + "thinking_delta" => format!("{i} thinking {:?}", d["thinking"].as_str().unwrap()), + "text_delta" => format!("{i} text {:?}", d["text"].as_str().unwrap()), + t => format!("{i} {t} {:?}", d["signature"].as_str().unwrap_or("")), + }, + } + }).collect() + } + + #[test] + fn streamed_reasoning_is_a_thinking_block_before_the_text() { + let (mut out, mut b) = (Vec::new(), AnthStream::new(true)); + for p in ["Let me", " think.\n\n\nThe answer", " is 4."] { b.feed(&mut out, p).unwrap(); } + b.finish(&mut out, "").unwrap(); + assert_eq!(events(&out), ["start 0 thinking", r#"0 thinking "Let me""#, r#"0 thinking " think.\n""#, r#"0 signature_delta """#, + "stop 0", "start 1 text", r#"1 text "The answer""#, r#"1 text " is 4.""#, "stop 1"]); + assert_eq!(b.next, 2); // a tool call would be block 2 + // The thinking block starts with the same fields as a whole reply's: an empty signature included. + let start: serde_json::Value = serde_json::from_str(String::from_utf8_lossy(&out).lines() + .find_map(|l| l.strip_prefix("data: ")).unwrap()).unwrap(); + assert_eq!(start["content_block"], json!({"type": "thinking", "thinking": "", "signature": ""})); + } + + #[test] + fn streamed_reply_without_think_block_is_one_text_block() { + let (mut out, mut b) = (Vec::new(), AnthStream::new(false)); + b.feed(&mut out, "Hi").unwrap(); + b.finish(&mut out, " there").unwrap(); + assert_eq!(events(&out), ["start 0 text", r#"0 text "Hi""#, r#"0 text " there""#, "stop 0"]); + assert_eq!(b.next, 1); + } + + #[test] + fn reasoning_cut_off_by_max_tokens_still_stops_its_block() { + let (mut out, mut b) = (Vec::new(), AnthStream::new(true)); + b.feed(&mut out, "still thinking").unwrap(); + b.finish(&mut out, "").unwrap(); + assert_eq!(events(&out), ["start 0 thinking", r#"0 thinking "still thinking""#, r#"0 signature_delta """#, "stop 0"]); + } + + #[test] + fn whole_reply_puts_reasoning_in_a_thinking_block() { + let (r, a) = split_think(true, "Reasoning.\n\n\n391"); + assert_eq!((r.as_str(), a.as_str()), ("Reasoning.", "391")); + assert_eq!(split_think(false, "no think block"), (String::new(), "no think block".to_string())); + let types = |c: Vec| c.iter().map(|b| b["type"].as_str().unwrap().to_string()).collect::>(); + assert_eq!(types(anthropic_content(&r, &a, vec![json!({"type": "tool_use"})])), ["thinking", "text", "tool_use"]); + assert_eq!(types(anthropic_content("", "391", vec![])), ["text"]); + assert_eq!(anthropic_content(&r, &a, vec![])[0], json!({"type": "thinking", "thinking": "Reasoning.", "signature": ""})); + } +} + #[cfg(test)] mod interface_tests { #[test] @@ -3388,18 +5376,78 @@ mod interface_tests { let models = vec![("a.gguf".to_string(), "/m/a.gguf".into(), 1), ("b.gguf".to_string(), "/m/b.gguf".into(), 2)]; // Model 9 does not exist, row 3 asks for a path and /no/such is not one, and mode 7 does not exist: each is // asked again. Then model 2, API server, GPU, 8192, default address. - let args = super::interface_args(&mut &b"9\n3\n/no/such\n2\n7\n3\n\nmany\n8192\n\n"[..], models.clone()).unwrap(); + // GPUs "x" are asked again; the default takes the one GPU. + let args = super::interface_args(&mut &b"9\n3\n/no/such\n2\n7\n3\n\nx\n\nmany\n8192\n\n"[..], models.clone(), 1).unwrap(); assert_eq!(args, ["serve", "--model", "/m/b.gguf", "--gpu", "--ctx", "8192", "--addr", "127.0.0.1:8080"]); + // Two GPUs: both by default, or the one asked for. + let args = super::interface_args(&mut &b"1\n4\n\n\n\n"[..], models.clone(), 2).unwrap(); + assert_eq!(args, ["bench", "--model", "/m/a.gguf", "--gpu", "--device", "0,1"]); + let args = super::interface_args(&mut &b"1\n4\n\n1\n\n"[..], models.clone(), 2).unwrap(); + assert_eq!(args, ["bench", "--model", "/m/a.gguf", "--gpu", "--device", "1"]); // Every default, on the CPU: chat with the first model. - let args = super::interface_args(&mut &b"\n\nn\n\n"[..], models.clone()).unwrap(); + let args = super::interface_args(&mut &b"\n\nn\n\n"[..], models.clone(), 2).unwrap(); assert_eq!(args, ["chat", "--model", "/m/a.gguf"]); - assert!(super::interface_args(&mut &b"1\n"[..], models).is_err(), "the input ended before the last answer"); + assert!(super::interface_args(&mut &b"1\n"[..], models, 1).is_err(), "the input ended before the last answer"); + } +} + +#[cfg(test)] +mod name_tests { + #[test] + fn a_split_model_is_named_without_its_shard() { + let n = |f| super::stem(std::path::Path::new(f)); + assert_eq!(n("/m/Big-Q4_K_M-00001-of-00002.gguf"), "Big-Q4_K_M"); + assert_eq!(n("/m/small.Q4.gguf"), "small.Q4"); + } +} + +#[cfg(test)] +mod preset_tests { + #[test] + fn parses_values() { + let v = super::parse_preset("# x\nctx = 4096\nkv = \"q8\" # note\nmodel = 'C:\\m.gguf'\ndevice = [0, 1]\nx_y = true\n").unwrap(); + let v: Vec<_> = v.into_iter().map(|(_, k, v)| (k, v)).collect(); + assert_eq!(v, [("ctx", vec!["4096"]), ("kv", vec!["q8"]), ("model", vec!["C:\\m.gguf"]), ("device", vec!["0", "1"]), ("x_y", vec!["true"])] + .map(|(k, v)| (k.to_string(), v.into_iter().map(String::from).collect::>()))); + assert_eq!(super::preset_values(r#""a\"b""#).unwrap(), ["a\"b"]); + for bad in ["ctx", "= 1", "ctx = ", "ctx = 1 2", "ctx = \"x", "d = [1, 2", "a b = 1"] { assert!(super::parse_preset(bad).is_err(), "{bad}"); } + } + #[test] + fn command_line_wins_and_other_commands_keys_are_skipped() { + let p = std::env::temp_dir().join(format!("strata-preset-{}.toml", std::process::id())); + std::fs::write(&p, "ctx = 4096\nkv = \"q8\"\nfixed_experts = true\nllama_numerics = false\napi_key = \"x\"\n").unwrap(); + let args = ["rustingstrata", "chat", "--model", "m.gguf", "--preset", p.to_str().unwrap(), "--ctx", "8192"].map(std::ffi::OsString::from).to_vec(); + let out = super::expand_preset(args).unwrap(); + let out: Vec<_> = out.iter().map(|a| a.to_str().unwrap()).collect(); + assert_eq!(out, ["rustingstrata", "chat", "--kv=q8", "--fixed-experts", "--model", "m.gguf", "--preset", p.to_str().unwrap(), "--ctx", "8192"]); + let m = super::cli_command().try_get_matches_from(&out).unwrap(); + let Some(super::Cmd::Chat { engine, .. }) = ::from_arg_matches(&m).unwrap().cmd else { panic!() }; + assert_eq!((engine.ctx, engine.kv.as_str(), engine.fixed_experts), (8192, "q8", true)); + std::fs::write(&p, "ctxx = 1\n").unwrap(); + let err = super::expand_preset(["rustingstrata", "chat", "--preset", p.to_str().unwrap()].map(std::ffi::OsString::from).to_vec()).unwrap_err(); + assert!(format!("{err:#}").contains("`ctxx` is not a flag"), "{err:#}"); + let _ = std::fs::remove_file(&p); + } + #[test] + fn calibration_replaces_keys_in_place() { + let t = "# mine\nmodel = \"m.gguf\"\nchunk = 512 # old\n#mtp = 9\n"; + assert_eq!(super::set_preset_keys(t, &[("chunk", "2048".into()), ("mtp", "2".into())]), + "# mine\nmodel = \"m.gguf\"\nchunk = 2048\n#mtp = 9\nmtp = 2\n"); } } #[cfg(test)] mod flag_tests { - use super::{calibrated_split, resolve_flags, split_moves, vram_margins}; + use super::{calibrated_split, resolve_flags, vram_margins}; + use clap::Parser; + + #[test] + fn reasoning_effort_flag_takes_levels_and_inkling_numbers() { + for ok in ["none", "off", "low", "high", "xhigh", "max", "0", "0.5", "0.99"] { assert_eq!(super::parse_effort(ok).as_deref(), Ok(ok)); } + for bad in ["hgih", "", "1", "-0.1", "medium-ish"] { assert!(super::parse_effort(bad).is_err(), "{bad}"); } + assert!(super::Cli::try_parse_from(["rustingstrata", "serve", "--reasoning-effort", "hgih"]).is_err()); + assert!(super::Cli::try_parse_from(["rustingstrata", "serve", "--reasoning-effort", "xhigh"]).is_ok()); + } #[test] fn calibrated_split_needs_the_same_devices_in_the_same_order() { @@ -3412,14 +5460,6 @@ mod flag_tests { assert_eq!(calibrated_split(&serde_json::json!({"chunk": 4096}), &[0, 1], &names(&["A", "B"])), None); } - #[test] - fn split_moves_shift_layers_between_neighbours() { - assert_eq!(split_moves(&[20, 20], 6), [vec![14, 26], vec![26, 14]]); - assert_eq!(split_moves(&[4, 36], 6), [vec![10, 30]]); - assert_eq!(split_moves(&[15, 15, 10], 6), [vec![9, 21, 10], vec![21, 9, 10], vec![15, 9, 16], vec![15, 21, 4]]); - assert!(split_moves(&[40], 6).is_empty()); - } - #[test] fn calibration_from_another_gpu_is_refused() { let v = serde_json::json!({"chunk": 4096, "gpu": "NVIDIA GeForce RTX 5080"}); @@ -3458,7 +5498,14 @@ mod flag_tests { assert_eq!(e.with(&serde_json::json!({"kv": "q4"})).unwrap().kv, "q4"); assert_eq!(e.with(&serde_json::json!({"kv": "q2"})).unwrap().kv, "q2"); assert_eq!(e.with(&serde_json::Value::Null).unwrap().ctx, e.ctx); - for bad in [serde_json::json!({"ctx": 8}), serde_json::json!({"ctx": "big"}), serde_json::json!({"kv": "q1"}), serde_json::json!({"mtp": -1})] { + let n = e.with(&serde_json::json!({"parallel": 3, "device": "1, 0"})).unwrap(); + assert_eq!((n.parallel, &n.device[..]), (3, &[1, 0][..])); + let mut slots = n.clone(); + slots.mtp = Some(0); + assert_eq!(slots.with(&serde_json::json!({"parallel": 1})).unwrap().mtp, None); + assert_eq!(slots.with(&serde_json::json!({"parallel": 1, "mtp": 2})).unwrap().mtp, Some(2)); + for bad in [serde_json::json!({"ctx": 8}), serde_json::json!({"ctx": "big"}), serde_json::json!({"kv": "q1"}), serde_json::json!({"mtp": -1}), + serde_json::json!({"parallel": 0}), serde_json::json!({"device": ""}), serde_json::json!({"device": "0,x"}), serde_json::json!({"device": 1})] { assert!(e.with(&bad).is_err(), "{bad}"); } } @@ -3566,6 +5613,29 @@ mod bench_tests { use serde_json::Value; use std::path::Path; + #[test] + fn cpu_inference_loader_selects_requested_numerics() { + use super::{Cmd, Gguf, Model, State, ops}; + let Some(path) = std::env::var_os("STRATA_CPU_PARITY_MODEL") else { return }; + let g = Gguf::open(Path::new(&path)).unwrap(); + let reference = Model::load(&g).unwrap(); + let Some(Cmd::Bench { mut engine, .. }) = Cli::parse_from(["rustingstrata", "bench", "--model", "fixture"]).cmd else { unreachable!() }; + let model = engine.load_inference_model(&g, None).unwrap(); + let mut a = State::new(&reference.cfg); + let mut b = State::new(&model.cfg); + let mut token = 42; + for _ in 0..4 { + let want = reference.step(&mut a, token); + let got = model.step(&mut b, token); + assert_eq!(got, want, "CPU generation logits changed at step {}", b.pos); + token = ops::argmax(&want) as u32; + } + engine.fast_cpu = true; + let fast = engine.load_inference_model(&g, None).unwrap(); + let expected = Model::load_with_matvec(&g, None, &[], true).unwrap(); + assert_eq!(fast.step(&mut State::new(&fast.cfg), token), expected.step(&mut State::new(&expected.cfg), token)); + } + fn meta() -> BenchMeta<'static> { BenchMeta { backend: "cpu", @@ -3675,7 +5745,7 @@ mod bench_tests { fn own_state_restores_the_environment() { // Safety: no other test reads this variable. unsafe { std::env::remove_var("STRATA_GLM_PREFETCH") }; - let st = super::OwnState::new(); + let st = super::OwnState::new(None); unsafe { std::env::set_var("STRATA_GLM_PREFETCH", "2") }; drop(st); assert!(std::env::var_os("STRATA_GLM_PREFETCH").is_none()); @@ -3688,3 +5758,435 @@ mod bench_tests { assert!(Cli::try_parse_from(["rustingstrata", "bench", "--model", "m.gguf", "--json-out", "/tmp/x.json"]).is_ok()); } } + +#[cfg(test)] +mod calibrate_cli_tests { + use super::*; + + #[test] + fn a_failing_baseline_does_not_abort_the_search_setup() { + let (ms, ok) = baseline_samples(Ok(vec![Measurement { prefill_tok_s: 10.0, decode_tok_s: 5.0, ..Default::default() }])); + assert!(ok); + assert_eq!(ms.len(), 1); + let (ms, ok) = baseline_samples(Err::, _>(anyhow::anyhow!("out of memory"))); + assert!(!ok); + assert!(ms.is_empty()); + } + + #[test] + fn spec_defaults_are_added_when_the_lists_omit_them() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.spec_types = vec!["ngram-simple".into()]; + s.draft_max = vec![4, 8]; + s.ngram_n = vec![3, 6]; + s.mtp_values = vec![2, 0]; + ensure_spec_defaults(&mut s); + assert!(s.spec_types.contains(&"none".to_string())); + assert!(s.draft_max.contains(&16)); + assert!(s.ngram_n.contains(&12)); + let b = spec_baseline(&s); + // The mtp knob is an index: index 1 is the value 0, not the value 1. + assert_eq!(b.i("mtp"), Some(1)); + assert_eq!(s.mtp_values[b.i("mtp").unwrap()], 0); + } + + #[test] + fn the_calibration_file_is_named_like_the_reader_looks_for_it() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + let measured = RefCell::new(String::new()); + assert_eq!(calib_backend_name(&s, &measured), "cuda"); + // CUDA requested but Vulkan really opened: runs look for the Vulkan file, so that is where we write. + *measured.borrow_mut() = "vulkan".into(); + assert_eq!(calib_backend_name(&s, &measured), "vulkan"); + s.backend = Some("cuda".into()); + assert_eq!(calib_backend_name(&s, &measured), "vulkan"); + } + + #[test] + fn gemma_bench_reports_the_chunk_it_actually_used() { + assert_eq!(gemma_bench_chunk(Some("512")), 512); + assert_eq!(gemma_bench_chunk(Some("nonsense")), 256); + assert_eq!(gemma_bench_chunk(None), 256); + } + + #[test] + fn a_new_calibration_clears_the_stale_v1_split() { + let mut v = serde_json::json!({"chunk": 4096, "split": {"devices": [0, 1], "layers": [12, 28]}, "gpu": "RTX"}); + drop_split(&mut v); + assert!(v.get("split").is_none()); + assert_eq!(v["chunk"], 4096); + assert_eq!(v["gpu"], "RTX"); + } + + #[test] + fn explicit_chunk_environment_variables_are_not_overwritten() { + let all = chunk_env_updates(512, |_| false); + assert_eq!(all.iter().map(|(k, _)| *k).collect::>(), + vec!["STRATA_DS_CHUNK", "STRATA_GLM_CHUNK", "STRATA_G4_CHUNK"]); + assert!(all.iter().all(|(_, v)| v == "512")); + let kept = chunk_env_updates(512, |k| k == "STRATA_DS_CHUNK"); + assert_eq!(kept.iter().map(|(k, _)| *k).collect::>(), + vec!["STRATA_GLM_CHUNK", "STRATA_G4_CHUNK"]); + assert!(chunk_env_updates(512, |_| true).is_empty()); + } + + #[test] + fn calibration_chunk_environment_is_restored_for_the_next_model() { + const KEY: &str = "STRATA_TEST_CALIB_RESTORE"; + let original = std::env::var_os(KEY); + unsafe { std::env::remove_var(KEY) } + CALIB_ENV.lock().unwrap().push((KEY, original.clone())); + unsafe { std::env::set_var(KEY, "256") } + assert_eq!(std::env::var_os(KEY).as_deref(), Some(std::ffi::OsStr::new("256"))); + restore_calib_env(); + assert_eq!(std::env::var_os(KEY), original, "the next model must not inherit this chunk"); + } + + #[test] + fn workloads_must_fit_the_context_being_measured() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.ctx = 2048; s.pp = vec![128, 4096]; s.tg = 16; + let e = check_workload_ctx(&s).unwrap_err(); + assert!(e.to_string().contains("exceeds --ctx 2048"), "{e}"); + s.pp = vec![128, 512]; + assert!(check_workload_ctx(&s).is_ok()); + } + + #[test] + fn cli_parses_the_v2_calibration_flags() { + let cli = Cli::try_parse_from([ + "rustingstrata", "calibrate", "--model", "m.gguf", "--samples", "7", "--reps", "2", + "--pp", "128,512", "--tg", "16", "--chunk-values", "1024,2048", "--task", "user:prompts.txt", + "--seed", "9", "--dry-run", + ]).unwrap(); + match cli.cmd.unwrap() { + Cmd::Calibrate { samples, reps, pp, tg, chunk_values, task, seed, dry_run, sub, .. } => { + assert_eq!((samples, reps, tg, seed), (7, 2, 16, 9)); + assert_eq!(pp, vec![128, 512]); + assert_eq!(chunk_values, Some(vec![1024, 2048])); + assert_eq!(task, vec!["user:prompts.txt"]); + assert!(dry_run); + assert!(sub.is_none()); + } + _other => panic!("wrong command"), + } + } + + #[test] + fn calibrate_takes_the_setup_flags_of_the_runs_and_hands_them_to_bench() { + let cli = Cli::try_parse_from([ + "rustingstrata", "calibrate", "--model", "m.gguf", "--kv", "turbo4-3", "--k", "q8", "--v", "f16", "--ple", "t.gguf", + "--threads", "6", "--cache-ram", "0", "--arena", "--host-share", "4", + ]).unwrap(); + let Some(Cmd::Calibrate { kv, setup, .. }) = cli.cmd else { panic!("wrong command") }; + assert_eq!(kv, "turbo4-3"); + assert_eq!(setup.ple, Some(PathBuf::from("t.gguf"))); + let args = setup.args(); + assert_eq!(args, ["--k", "q8", "--v", "f16", "--threads", "6", "--cache-ram", "0", "--host-share", "4", "--arena"]); + // `bench` must take every one of them, with the flags calibrate always passes. + let bench = ["rustingstrata", "bench", "--model", "m.gguf", "--kv", "turbo4-3"].into_iter().chain(args.iter().map(String::as_str)); + assert!(matches!(Cli::try_parse_from(bench).unwrap().cmd, Some(Cmd::Bench { .. }))); + let spec = Cli::try_parse_from(["rustingstrata", "calibrate", "spec", "--model", "m.gguf", "--v", "q4", "--ple", "t.gguf"]).unwrap(); + let Some(Cmd::Calibrate { sub: Some(CalibrateSub::Spec { setup, .. }), .. }) = spec.cmd else { panic!("wrong command") }; + assert_eq!(setup.args(), ["--v", "q4"]); + } + + #[test] + fn cli_parses_the_spec_subcommand() { + let cli = Cli::try_parse_from([ + "rustingstrata", "calibrate", "spec", "--model", "m.gguf", "--tasks", "prose,coding", + "--spec-types", "none,ngram-simple,ngram-mod", "--draft-max", "4,8", "--ngram-n", "3,6", + "--samples", "5", "--dry-run", + ]).unwrap(); + match cli.cmd.unwrap() { + Cmd::Calibrate { sub: Some(CalibrateSub::Spec { model, tasks, spec_types, draft_max, ngram_n, samples, dry_run, .. }), .. } => { + assert_eq!(model, PathBuf::from("m.gguf")); + assert_eq!(tasks, vec!["prose", "coding"]); + assert_eq!(spec_types, vec!["none", "ngram-simple", "ngram-mod"]); + assert_eq!((draft_max, ngram_n, samples), (vec![4, 8], vec![3, 6], 5)); + assert!(dry_run); + } + _other => panic!("wrong command"), + } + } + + #[test] + fn draft_counts_are_read_from_both_json_and_stdout() { + let v = serde_json::json!({"drafts": {"made": 300, "accepted": 285}}); + assert_eq!(parse_drafts(&v, ""), (300, 285)); + // The arch-specific benchners print "accepted /". + assert_eq!(parse_drafts(&serde_json::Value::Null, "speculative drafts accepted 285/300 (95.0%)"), (300, 285)); + assert_eq!(parse_drafts(&serde_json::Value::Null, "no drafts here"), (0, 0)); + } + + #[test] + fn workload_groups_keep_task_and_depth_order() { + let ws = vec![ + Workload::new(128, 16, "prose"), Workload::new(512, 16, "coding"), + Workload::new(2048, 16, "prose"), Workload::new(96, 16, "coding"), + ]; + let g = workload_groups(&ws); + assert_eq!(g.iter().map(|x| x.0.as_str()).collect::>(), vec!["prose", "coding"]); + assert_eq!(g[0].1.iter().map(|(_, w)| w.pp).collect::>(), vec![128, 2048]); + assert_eq!(g[1].1.iter().map(|(_, w)| w.pp).collect::>(), vec![512, 96]); + assert_eq!(g[0].1[0].0, 0); + assert_eq!(g[0].1[1].0, 2); + } + + #[test] + fn spec_space_stores_indices_not_actual_values() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.spec_types = vec!["none".into(), "ngram-simple".into(), "ngram-mod".into(), "ngram-cache".into()]; + s.draft_max = vec![4, 8, 16]; + s.ngram_n = vec![3, 6, 12]; + s.mtp_values = vec![0, 2]; + let space = spec_space(&s); + assert_eq!(space[0].values, vec![0.0, 1.0, 2.0, 3.0]); + assert_eq!(space[1].values, vec![0.0, 1.0, 2.0]); + assert_eq!(space[2].values, vec![0.0, 1.0, 2.0]); + assert_eq!(space[3].values, vec![0.0, 1.0]); + } + + #[test] + fn a_spec_sweep_preserves_the_engine_calibration() { + let old = serde_json::json!({"chunk": 2048, "mtp": 2, "ctx": 8192, "short": 32, "threads": 6, + "measured": {"prefill_tok_s": 100}, "best": {"chunk": 2048}}); + let spec = serde_json::json!({"prose": {"spec_type": "ngram-mod"}}); + let v = merge_spec_calibration(old, &spec, "inkling2_loop", "RTX", 1234); + assert_eq!(v["chunk"], 2048); + assert_eq!(v["mtp"], 2); + assert_eq!(v["ctx"], 8192); + assert_eq!(v["measured"]["prefill_tok_s"], 100); + assert_eq!(v["spec"]["prose"]["spec_type"], "ngram-mod"); + assert_eq!(v["gpu"], "RTX"); + assert_eq!(v["bytes"], 1234); + } + + #[test] + fn knob_space_is_only_chunk_mtp_and_short() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let main = build_space("qwen35moe", &s, true); + let names: Vec<_> = main.iter().map(|k| k.name.as_str()).collect(); + assert_eq!(names, vec!["chunk", "mtp", "short"]); + let base = baseline_knobs(&main, "qwen35moe"); + assert_eq!((base.i("chunk"), base.i("mtp"), base.i("short")), (Some(4096), Some(0), Some(32))); + + // No MTP head: don't spend samples on drafts that the engine cannot use. + let no_head = build_space("qwen35moe", &s, false); + assert_eq!(no_head[1].values, vec![0.0]); + + // Own-arch models have only the chunk knob. + let own = build_space("inkling2_loop", &s, false); + assert_eq!(own.iter().map(|k| k.name.as_str()).collect::>(), vec!["chunk"]); + } + + #[test] + fn chunks_larger_than_the_context_are_dropped() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.ctx = 2048; + let space = build_space("qwen35moe", &s, true); + let chunks = &space[0].values; + assert!(chunks.iter().all(|&c| c <= 2048.0), "{chunks:?}"); + assert!(!chunks.contains(&4096.0)); + assert!(!chunks.is_empty()); + s.ctx = 4096; + assert!(build_space("qwen35moe", &s, true)[0].values.contains(&4096.0)); + } + + #[test] + fn chunks_that_tie_the_default_on_every_workload_are_not_searched() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + (s.pp, s.ctx) = (vec![512], 8192); + assert_eq!(build_space("qwen35moe", &s, true)[0].values, [4096.0], "pp512 cannot tell a chunk from the default 4096"); + (s.pp, s.chunk_values) = (vec![128, 4096], vec![1024, 2048, 4096, 8192]); + assert_eq!(build_space("qwen35moe", &s, true)[0].values, [1024.0, 2048.0, 4096.0], "8192 splits no workload differently"); + s.pp = vec![6000]; + assert_eq!(build_space("qwen35moe", &s, true)[0].values, [1024.0, 2048.0, 4096.0, 8192.0]); + } + + #[test] + fn the_baseline_chunk_is_each_engines_own_default() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + for (arch, want) in [("gemma4", 256), ("glm5-next", 512), ("hy_v4_flash", 1024), ("kolibri1", 1024), ("gigachat4", 1024), + ("inkling2_loop", 256), ("inkling2", 256), ("qwen35moe", 4096)] { + let space = build_space(arch, &s, true); + let base = baseline_knobs(&space, arch); + assert_eq!(base.i("chunk"), Some(want), "{arch}"); + assert!(space[0].values.contains(&(want as f64)), "{arch} baseline must be searchable"); + } + // DeepSeek prefills one token at a time: there is no chunk to search or write. + assert!(build_space("deepseek41", &s, true).is_empty()); + assert_eq!(arch_default_chunk("deepseek41"), None); + } + + #[test] + fn inkling_chunks_larger_than_its_gpu_cap_are_not_searched() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let space = build_space("inkling2_loop", &s, false); + assert!(space[0].values.iter().all(|&c| c <= 256.0), "{:?}", space[0].values); + } + + /// Sampling flags take the ranges `serve` checks per request: out of them every reply would end in NaN logits. + #[test] + fn sampling_flags_are_range_checked() { + use clap::Parser; + let ok = |a: &str| Cli::try_parse_from(["rs", "generate", "--model", "m.gguf", "--prompt", "hi", a]).is_ok(); + assert!(ok("--repeat-penalty=1.1") && ok("--min-p=0.05") && ok("--presence-penalty=-1.5") && ok("--temp=0")); + assert!(!ok("--repeat-penalty=0") && !ok("--min-p=5") && !ok("--top-p=0") && !ok("--temp=-1") && !ok("--temp=inf")); + } + + #[test] + fn short_candidates_cross_the_workload_depths() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let space = build_space("qwen35moe", &s, true); + let short = &space.last().unwrap().values; + assert_eq!(short, &vec![32.0, 129.0, 513.0, 2049.0]); + // Every threshold above its depth makes that workload take the short path; none is inert. + for &pp in &s.pp { assert!(short.iter().any(|&t| t > pp as f64 && t <= (pp + 1) as f64)); } + let mut deep = CalibSettings::new(PathBuf::from("m.gguf")); + deep.pp = vec![512, 4096, 16384]; + assert_eq!(build_space("qwen35moe", &deep, true).last().unwrap().values, vec![32.0, 513.0, 4097.0]); + } + + #[test] + fn spec_baseline_uses_current_defaults_not_first_list_values() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.spec_types = vec!["ngram-simple".into(), "none".into()]; + s.draft_max = vec![4, 8, 16]; + s.ngram_n = vec![3, 6, 12]; + let b = spec_baseline(&s); + assert_eq!((b.i("spec_type"), b.i("draft_max"), b.i("ngram_n"), b.i("mtp")), + (Some(1), Some(2), Some(2), Some(0))); + } + + #[test] + fn done_line_includes_per_request_draft_acceptance() { + let last = serve::Last { + at: 0, + model: "Inkling-2-Mini".into(), + system_tokens: 0, + cached_tokens: 0, + prompt_tokens: 185, + completion_tokens: 318, + prefill_ms: 204.06, + decode_ms: 3750.0, + finish: "stop".into(), + }; + let plain = format_done_line("open", &last, "", ""); + assert!(!plain.contains("drafts accepted"), "{plain}"); + assert!(plain.ends_with(", finish=stop"), "{plain}"); + + let suffix = serve::format_drafts_suffix(serve::draft_delta("speculative ngram", (10, 4), (130, 88))); + let with_drafts = format_done_line("open", &last, "", &suffix); + assert!(with_drafts.contains(", speculative ngram drafts accepted 84/120 (70.0%), finish=stop"), "{with_drafts}"); + assert_eq!(parse_drafts(&serde_json::Value::Null, &with_drafts), (120, 84)); + + let mtp_suffix = serve::format_drafts_suffix(serve::draft_delta("MTP", (0, 0), (300, 210))); + let with_both = format_done_line("open", &last, ", expert hit rate 92.5%", &mtp_suffix); + assert!(with_both.contains(", expert hit rate 92.5%, MTP drafts accepted 210/300 (70.0%), finish=stop"), "{with_both}"); + assert_eq!(parse_drafts(&serde_json::Value::Null, &with_both), (300, 210)); + } +} + +#[cfg(test)] +mod kv_type_tests { + use super::effective_kv; + + fn pair(kv: &str, k: Option<&str>, v: Option<&str>) -> (String, String) { + effective_kv(kv, k, v).unwrap() + } + + #[test] + fn symmetric_flag_and_overrides() { + assert_eq!(pair("f16", None, None), ("f16".into(), "f16".into())); + assert_eq!(pair("turbo4", None, None), ("turbo4".into(), "turbo4".into())); + assert_eq!(pair("f16", Some("turbo4"), None), ("turbo4".into(), "f16".into())); + assert_eq!(pair("f16", None, Some("q8")), ("f16".into(), "q8".into())); + } + + #[test] + fn turbo_aliases_expand_to_independent_types() { + assert_eq!(pair("turbo4-3", None, None), ("turbo4".into(), "turbo3".into())); + assert_eq!(pair("turbo4-2", None, None), ("turbo4".into(), "turbo2".into())); + assert_eq!(pair("turbo3-2", None, None), ("turbo3".into(), "turbo2".into())); + } + + #[test] + fn arbitrary_kv_pairs_are_allowed() { + assert_eq!(pair("f16", Some("f16"), Some("q4")), ("f16".into(), "q4".into())); + assert_eq!(pair("f16", Some("q8"), Some("turbo4")), ("q8".into(), "turbo4".into())); + assert_eq!(pair("f16", Some("turbo3"), Some("turbo2")), ("turbo3".into(), "turbo2".into())); + assert_eq!(pair("f16", Some("turbo4"), Some("turbo3")), ("turbo4".into(), "turbo3".into())); + } + + #[test] + fn invalid_types_are_rejected() { + assert!(effective_kv("f16", Some("bogus"), None).is_err()); + assert!(effective_kv("f16", None, Some("turbo9")).is_err()); + } +} + +#[cfg(test)] +mod pretty_cli_tests { + use super::{Cli, Cmd}; + use clap::Parser; + + #[test] + fn serve_defaults_to_timestamped_logs_and_pretty_is_opt_in() { + let cli = Cli::try_parse_from(["rustingstrata", "serve"]).unwrap(); + let Some(Cmd::Serve { engine, .. }) = cli.cmd else { panic!("expected serve") }; + assert!(!engine.pretty); + assert!(!engine.graph); + + assert!(Cli::try_parse_from(["rustingstrata", "serve", "--graph"]).is_err()); + assert!(Cli::try_parse_from(["rustingstrata", "serve", "--status-graph"]).is_err()); + assert!(Cli::try_parse_from(["rustingstrata", "serve", "--ugly"]).is_err()); + + let cli = Cli::try_parse_from(["rustingstrata", "serve", "--pretty", "--graph"]).unwrap(); + let Some(Cmd::Serve { engine, .. }) = cli.cmd else { panic!("expected serve") }; + assert!(engine.pretty); + assert!(engine.graph); + } + + #[test] + fn calibrate_defaults_to_timestamped_logs_and_pretty_is_opt_in() { + let cli = Cli::try_parse_from(["rustingstrata", "calibrate", "--model", "m.gguf"]).unwrap(); + let Some(Cmd::Calibrate { pretty, graph, .. }) = cli.cmd else { panic!("expected calibrate") }; + assert!(!pretty); + assert!(!graph); + + assert!(Cli::try_parse_from(["rustingstrata", "calibrate", "--model", "m.gguf", "--graph"]).is_err()); + assert!(Cli::try_parse_from(["rustingstrata", "calibrate", "--model", "m.gguf", "--status-graph"]).is_err()); + assert!(Cli::try_parse_from(["rustingstrata", "calibrate", "--model", "m.gguf", "--ugly"]).is_err()); + + let cli = Cli::try_parse_from([ + "rustingstrata", "calibrate", "--model", "m.gguf", "--pretty", "--graph", + ]).unwrap(); + let Some(Cmd::Calibrate { pretty, graph, .. }) = cli.cmd else { panic!("expected calibrate") }; + assert!(pretty); + assert!(graph); + } +} + +#[cfg(test)] +mod effort_levels_tests { + use super::*; + + #[test] + fn levels_by_family() { + let e = |arch: &str, tpl: Template, names: Option>| effort_levels(arch, tpl, names.as_deref()); + let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(e("qwen4", Template::Qwen4 { effort: None }, None), ["off", "low", "high", "xhigh"]); + assert_eq!(e("qwen3", Template::Json { reasoning: false, hybrid: true }, None), ["none", "high"]); + for arch in ["gemma4", "glm5-next", "deepseek41", "hy_v4_flash", "gigachat4"] { + assert_eq!(e(arch, Template::Xml, None), ["none", "high"], "{}", arch); + } + for arch in ["inkling2_loop", "inkling2"] { + assert_eq!(e(arch, Template::Xml, None), ["none", "minimal", "low", "medium", "high", "xhigh"], "{}", arch); + } + assert_eq!(e("kolibri1", Template::Xml, None), ["none", "low", "medium", "high"]); + assert_eq!(e("raon1", Template::Xml, Some(names(&["low", "medium", "high"]))), ["none", "low", "medium", "high"]); + assert_eq!(e("raon1", Template::Xml, Some(names(&["none", "brief", "none"]))), ["none", "brief"]); + assert_eq!(e("raon1", Template::Xml, None), ["none", "high"]); + } +} diff --git a/src/mcp.rs b/src/mcp.rs index 9e882e6f..f6bf8ee1 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -10,6 +10,9 @@ use std::sync::mpsc::{Receiver, RecvTimeoutError}; use std::time::Duration; const VERSION: &str = "2025-06-18"; +const SUPPORTED_VERSIONS: &[&str] = &[VERSION, "2025-03-26", "2024-11-05"]; +const MAX_TOOLS: usize = 1000; +const MAX_TOOL_PAGES: usize = 100; #[derive(Clone, Debug, PartialEq)] pub enum Spec { @@ -47,7 +50,30 @@ fn timeout() -> Duration { enum Conn { /// `rx` carries the child's stdout lines from a reader thread, so a read can time out. Stdio { child: std::process::Child, stdin: std::process::ChildStdin, rx: Receiver }, - Http { agent: ureq::Agent, url: String, headers: Vec<(String, String)>, session: Option }, + Http { agent: ureq::Agent, url: String, headers: Vec<(String, String)>, session: Option, protocol: String }, +} + +enum RpcErr { + Remote(String), + Transport(anyhow::Error), +} + +impl From for anyhow::Error { + fn from(e: RpcErr) -> Self { + match e { + RpcErr::Remote(m) => anyhow!("{m}"), + RpcErr::Transport(e) => e, + } + } +} + +fn pick_response(v: Value, id: u64) -> Option { + let matches = |m: &Value| m.is_object() && m["id"] == id && m.get("method").is_none(); + match v { + Value::Array(items) => items.into_iter().find(matches), + other if matches(&other) => Some(other), + _ => None, + } } impl Drop for Conn { @@ -74,10 +100,16 @@ impl Conn { Spec::Http { url, headers } => { let t = Some(timeout()); let agent = ureq::Agent::config_builder().timeout_connect(Some(Duration::from_secs(30))).timeout_global(t).http_status_as_error(false).build().into(); - Conn::Http { agent, url: url.clone(), headers: headers.clone(), session: None } + Conn::Http { agent, url: url.clone(), headers: headers.clone(), session: None, protocol: VERSION.into() } } }; - c.rpc(1, "initialize", json!({"protocolVersion": VERSION, "capabilities": {}, "clientInfo": {"name": "rustingstrata", "version": env!("CARGO_PKG_VERSION")}}))?; + let init = c.rpc(1, "initialize", json!({"protocolVersion": VERSION, "capabilities": {}, "clientInfo": {"name": "rustingstrata", "version": env!("CARGO_PKG_VERSION")}}))?; + if let Some(v) = init.get("protocolVersion").filter(|v| !v.is_null()) { + let Some(v) = v.as_str().filter(|s| SUPPORTED_VERSIONS.contains(s)) else { + bail!("unsupported MCP protocolVersion {v}"); + }; + if let Conn::Http { protocol, .. } = &mut c { *protocol = v.to_string(); } + } c.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"}), None)?; Ok(c) } @@ -86,16 +118,19 @@ impl Conn { fn send(&mut self, m: &Value, id: Option) -> anyhow::Result> { match self { Conn::Stdio { stdin, .. } => { writeln!(stdin, "{m}")?; stdin.flush()?; Ok(None) } - Conn::Http { agent, url, headers, session } => { + Conn::Http { agent, url, headers, session, protocol } => { let mut r = agent.post(url.as_str()).header("Content-Type", "application/json").header("Accept", "application/json, text/event-stream") - .header("MCP-Protocol-Version", VERSION); + .header("MCP-Protocol-Version", protocol.as_str()); for (k, v) in headers.iter() { r = r.header(k.as_str(), v.as_str()); } if let Some(s) = session.as_deref() { r = r.header("Mcp-Session-Id", s); } let resp = r.send(m.to_string()).with_context(|| format!("POST {url}"))?; let status = resp.status().as_u16(); - if let Some(s) = resp.headers().get("mcp-session-id").and_then(|s| s.to_str().ok()) { *session = Some(s.to_string()); } - let stream = resp.headers().get("content-type").and_then(|c| c.to_str().ok()).is_some_and(|c| c.starts_with("text/event-stream")); if status >= 400 { bail!("{url} answered HTTP {status}"); } + if let Some(s) = resp.headers().get("mcp-session-id").and_then(|s| s.to_str().ok()).filter(|s| !s.is_empty()) { + *session = Some(s.to_string()); + } + let stream = resp.headers().get("content-type").and_then(|c| c.to_str().ok()) + .is_some_and(|c| c.split(';').next().is_some_and(|t| t.trim().eq_ignore_ascii_case("text/event-stream"))); let Some(id) = id else { return Ok(None) }; // ponytail: a 16 MB cap on one answer (JSON or event stream), so a remote server cannot fill the // memory; raise it when a tool legitimately returns more. @@ -103,21 +138,35 @@ impl Conn { if !stream { let mut b = String::new(); { body }.read_to_string(&mut b)?; - return Ok(Some(serde_json::from_str(&b).context("MCP answer is not JSON")?)); + let v: Value = serde_json::from_str(&b).context("MCP answer is not JSON")?; + return pick_response(v, id).map(Some).ok_or_else(|| anyhow!("{url}: answer did not match request {id}")); } + let mut data = Vec::::new(); + let flush = |data: &mut Vec| -> Option { + if data.is_empty() { return None; } + let payload = data.join("\n"); + data.clear(); + serde_json::from_str::(&payload).ok().and_then(|v| pick_response(v, id)) + }; for l in BufReader::new(body).lines() { let l = l?; - let Some(d) = l.strip_prefix("data:") else { continue }; - if let Ok(v) = serde_json::from_str::(d.trim()) && v["id"] == id && v.get("method").is_none() { return Ok(Some(v)); } + if l.is_empty() { + if let Some(v) = flush(&mut data) { return Ok(Some(v)); } + } else if let Some(d) = l.strip_prefix("data:") { + data.push(d.strip_prefix(' ').unwrap_or(d).to_string()); + } else if l == "data" { + data.push(String::new()); + } } + if let Some(v) = flush(&mut data) { return Ok(Some(v)); } bail!("{url}: the stream ended without an answer") } } } /// One request and its result. Server requests that arrive meanwhile are answered (`ping`) or refused. - fn rpc(&mut self, id: u64, method: &str, params: Value) -> anyhow::Result { - let direct = self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}), Some(id))?; + fn rpc_inner(&mut self, id: u64, method: &str, params: Value) -> Result { + let direct = self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}), Some(id)).map_err(RpcErr::Transport)?; let end = std::time::Instant::now() + timeout(); let v = match direct { Some(v) => v, @@ -125,8 +174,8 @@ impl Conn { let Conn::Stdio { rx, .. } = self else { unreachable!() }; let l = match rx.recv_timeout(end.saturating_duration_since(std::time::Instant::now())) { Ok(l) => l, - Err(RecvTimeoutError::Timeout) => bail!("no answer to {method} in {} s", timeout().as_secs()), - Err(RecvTimeoutError::Disconnected) => bail!("the server exited during {method}"), + Err(RecvTimeoutError::Timeout) => return Err(RpcErr::Transport(anyhow!("no answer to {method} in {} s", timeout().as_secs()))), + Err(RecvTimeoutError::Disconnected) => return Err(RpcErr::Transport(anyhow!("the server exited during {method}"))), }; // Servers may print other lines on stdout; anything that is not a JSON object is skipped. let Ok(v) = serde_json::from_str::(&l) else { continue }; @@ -134,16 +183,23 @@ impl Conn { if !v["id"].is_null() { let a = if v["method"] == "ping" { json!({"jsonrpc": "2.0", "id": v["id"], "result": {}}) } else { json!({"jsonrpc": "2.0", "id": v["id"], "error": {"code": -32601, "message": "not supported"}}) }; - self.send(&a, None)?; + self.send(&a, None).map_err(RpcErr::Transport)?; } continue; } - if v["id"] == id { break v; } + if let Some(v) = pick_response(v, id) { break v; } }, }; - if let Some(e) = v.get("error") { bail!("{}", e["message"].as_str().unwrap_or("MCP error")); } + if let Some(e) = v.get("error").filter(|e| !e.is_null()) { + let msg = e.get("message").and_then(Value::as_str).or_else(|| e.as_str()).unwrap_or("MCP error"); + return Err(RpcErr::Remote(msg.to_string())); + } Ok(v["result"].clone()) } + + fn rpc(&mut self, id: u64, method: &str, params: Value) -> anyhow::Result { + self.rpc_inner(id, method, params).map_err(Into::into) + } } struct Server { spec: Spec, conn: Option, next: u64, tools: Vec, error: Option } @@ -153,14 +209,30 @@ impl Server { fn up(&mut self) -> anyhow::Result<()> { if self.conn.is_some() { return Ok(()); } let mut c = Conn::open(&self.spec)?; - let (mut tools, mut cursor) = (Vec::new(), None::); + let (mut tools, mut cursor, mut seen) = (Vec::new(), None::, std::collections::HashSet::new()); + // ponytail: caps retained tools (1000) and pagination depth (100 pages) accumulated across `tools/list` + // responses (per-response HTTP bytes are capped separately in `Conn::send`); exceeding either limit or + // repeating a cursor fails loudly instead of silently returning a partial list. + let mut pages = 0; loop { + pages += 1; self.next += 1; - let r = c.rpc(self.next, "tools/list", cursor.map_or(json!({}), |c| json!({"cursor": c})))?; - tools.extend(r["tools"].as_array().into_iter().flatten().map(|t| json!({"name": t["name"], "description": t["description"], "inputSchema": t["inputSchema"]}))); - cursor = r["nextCursor"].as_str().map(String::from); - // ponytail: at most 1000 tools per server, so a server that always returns a cursor cannot loop forever. - if cursor.is_none() || tools.len() >= 1000 { break; } + let params = cursor.as_deref().map_or(json!({}), |c| json!({"cursor": c})); + let r = c.rpc(self.next, "tools/list", params)?; + let page = r["tools"].as_array().map(Vec::as_slice).unwrap_or(&[]); + if tools.len().saturating_add(page.len()) > MAX_TOOLS { + bail!("tools/list exceeded {MAX_TOOLS} tools"); + } + tools.extend(page.iter().map(|t| json!({"name": t["name"], "description": t["description"], "inputSchema": t["inputSchema"]}))); + let Some(next) = r["nextCursor"].as_str().filter(|s| !s.is_empty()) else { break; }; + let next = next.to_string(); + if !seen.insert(next.clone()) { + bail!("tools/list repeated pagination cursor {next:?}"); + } + if pages >= MAX_TOOL_PAGES { + bail!("tools/list exceeded {MAX_TOOL_PAGES} pages"); + } + cursor = Some(next); } (self.conn, self.tools) = (Some(c), tools); Ok(()) @@ -207,13 +279,12 @@ impl Hub { s.up()?; s.next += 1; let id = s.next; - let r = s.conn.as_mut().unwrap().rpc(id, "tools/call", json!({"name": tool, "arguments": args})); - let r = match r { + let r = match s.conn.as_mut().unwrap().rpc_inner(id, "tools/call", json!({"name": tool, "arguments": args})) { Ok(r) => r, - Err(e) => { - // "unknown tool" and the like leave the connection usable; a timeout or an exit does not. - let m = format!("{e:#}"); - if m.starts_with("no answer") || m.contains("exited") || m.contains("POST ") { s.conn = None; } + // "unknown tool" and the like leave the connection usable; transport or protocol failures do not. + Err(RpcErr::Remote(m)) => bail!("{m}"), + Err(RpcErr::Transport(e)) => { + s.conn = None; return Err(e); } }; diff --git a/src/memory.rs b/src/memory.rs index b01066de..5053fdb8 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -3,14 +3,15 @@ //! The cap bounds memory the process owns outright (baked tensors, LoRA factors, parked conversation states). The //! mmapped GGUF is page cache the OS can evict, so a model larger than RAM still loads and streams. -/// Total physical RAM in bytes, or `None` if undetectable. +/// Total physical RAM in bytes, or `None` if undetectable. On Linux the memory limit of the process's cgroup when it +/// is lower: a container sees the host's MemTotal (issue #132), and its page cache counts toward the limit. pub fn total_ram() -> Option { #[cfg(target_os = "linux")] { let m = std::fs::read_to_string("/proc/meminfo").unwrap_or_default(); let kb = m.lines().find_map(|l| l.strip_prefix("MemTotal:")?.trim().strip_suffix("kB")?.trim().parse::().ok()); if let Some(k) = kb { - return Some(k << 10); + return Some(cgroup_limit().map_or(k << 10, |c| c.min(k << 10))); } } #[cfg(windows)] @@ -35,6 +36,52 @@ pub fn total_ram() -> Option { None } +/// RAM that programs can still take (Linux MemAvailable or Windows ullAvailPhys), or `None`. +pub fn available_ram() -> Option { + #[cfg(target_os = "linux")] + { + let m = std::fs::read_to_string("/proc/meminfo").ok()?; + return m.lines().find_map(|l| l.strip_prefix("MemAvailable:")?.trim().strip_suffix("kB")?.trim().parse::().ok()).map(|k| k << 10); + } + #[cfg(windows)] + { + #[repr(C)] + struct MemStatus { + len: u32, + load: u32, + total: u64, + avail: u64, + rest: [u64; 5], + } + #[link(name = "kernel32")] + unsafe extern "system" { + fn GlobalMemoryStatusEx(m: *mut MemStatus) -> i32; + } + let mut m = MemStatus { len: size_of::() as u32, load: 0, total: 0, avail: 0, rest: [0; 5] }; + if unsafe { GlobalMemoryStatusEx(&mut m) } != 0 && m.avail > 0 { + return Some(m.avail); + } + } + #[allow(unreachable_code)] + None +} + +/// The memory limit of this process's cgroup: v2 `memory.max` of its own cgroup or one above it (a container sees +/// its own as the root), else v1 `memory.limit_in_bytes`. `None` without a limit. +#[cfg(target_os = "linux")] +fn cgroup_limit() -> Option { + let own = std::fs::read_to_string("/proc/self/cgroup").ok() + .and_then(|c| c.lines().find_map(|l| l.strip_prefix("0::").map(str::to_owned))).unwrap_or_default(); + let mut dir = std::path::PathBuf::from(format!("/sys/fs/cgroup{}", own.trim_end_matches('/'))); + let read = |p: std::path::PathBuf| std::fs::read_to_string(p).ok()?.trim().parse::().ok(); + let mut lim: Option = None; + loop { + if let Some(v) = read(dir.join("memory.max")) { lim = Some(lim.map_or(v, |l| l.min(v))); } + if !dir.pop() || !dir.starts_with("/sys/fs/cgroup") { break; } + } + lim.or_else(|| read("/sys/fs/cgroup/memory/memory.limit_in_bytes".into())) +} + /// Usable cap in bytes: `max_ram` if nonzero, else `total - margin`. `None` means unlimited (RAM undetectable). pub fn ram_cap(margin: u64, max_ram: u64) -> Option { if max_ram > 0 { @@ -52,6 +99,12 @@ mod tests { assert_eq!(ram_cap(512 << 20, 8 << 30), Some(8 << 30)); } + #[cfg(target_os = "linux")] + #[test] + fn cgroup_limit_caps_total() { + if let (Some(t), Some(c)) = (total_ram(), cgroup_limit()) { assert!(t <= c); } + } + #[test] fn margin_is_subtracted() { if let Some(t) = total_ram() { diff --git a/src/model.rs b/src/model.rs index 88aaa55f..b07822bb 100644 --- a/src/model.rs +++ b/src/model.rs @@ -4,6 +4,9 @@ use crate::config::{DFlashConfig, Eagle3Config, LayerKind, ModelConfig}; use crate::gguf::Gguf; use crate::ops; +use crate::cpu_moe::{self, Q8K}; +use std::cell::OnceCell; +use rayon::prelude::*; use crate::weights::{Tensor, Weights}; use anyhow::Context; use std::collections::HashMap; @@ -32,8 +35,14 @@ pub struct Model<'a> { pub loras: Vec, pub draft_model: Option>>, ple: Option, + fast_matvec: bool, + /// Fast CPU path: LoRA deltas added at run time instead of baked, keyed by the base tensor's data address. + lora_rt: HashMap>, } +/// One adapter on one matrix: y += mult * B (A x), with A `rank` x `in` and B `out` x `rank` (row-major). +struct RtLora { mult: f32, rank: usize, a: Vec, b: Vec } + impl Model<'_> { /// Host memory this process owns outright: baked/synthesized tensors and LoRA factors. The mmapped GGUF is /// evictable page cache and is not counted, so models larger than RAM still load. @@ -45,7 +54,7 @@ impl Model<'_> { } /// qwen4exp per-layer embedding (PLE): n-gram hash constants from the GGUF. -struct Ple { mult: Vec, off: Vec, vocab: Vec, eos: i64, heads_per_ngram: usize } +struct Ple { mult: Vec, off: Vec, vocab: Vec, eos: i64, heads_per_ngram: usize, direct: Option } // PLE geometry, checked against the GGUF at load: n-grams up to 3 tokens, `heads_per_ngram` hash heads per n-gram order, // a 4-tap causal conv dilated by the n-gram size, so it reads rows t-9, t-6, t-3, t. @@ -97,18 +106,233 @@ impl Default for Mtp { fn default() -> Mtp { Mtp { kv: LayerState::Attn { k: Vec::new(), v: Vec::new(), ik: Vec::new() }, pos: 0 } } } -fn mv(t: &Tensor, x: &[f32]) -> Vec { - let mut y = vec![0f32; t.rows]; - t.matvec(x, &mut y); - y -} - impl<'a> Model<'a> { + fn integer_kernel(&self, t: &Tensor) -> Option f32> { + let block = cpu_moe::affine_block_elems(t.ty).unwrap_or(256); + if self.fast_matvec && t.cols % block == 0 { cpu_moe::int_dot(t.ty) } else { None } + } + + fn mv(&self, t: &Tensor, x: &[f32]) -> Vec { + self.mv_cached(t, x, &OnceCell::new()) + } + + fn mv_cached(&self, t: &Tensor, x: &[f32], activation: &OnceCell>) -> Vec { + assert_eq!(t.cols, x.len()); + let mut y = vec![0.0; t.rows]; + if let Some(dot) = self.integer_kernel(t) { + cpu_moe::matvec_q8k(t, activation.get_or_init(|| cpu_moe::quantize_q8k(x)), &mut y, dot); + } else if self.fast_matvec { + t.matmul(x, 1, &mut y); + } else { + t.matvec(x, &mut y); + } + self.lora_add(t, x, &mut y); + y + } + + /// `mv` of each row of `xs`, with its bits; matrices on the same input share `xq`, its quantization. + fn mm(&self, t: &Tensor, xs: &[Vec], xq: &OnceCell>>) -> Vec> { + if !self.fast_matvec || xs.len() <= 1 { + return xs.iter().map(|x| self.mv(t, x)).collect(); + } + let mut ys = if let Some(dot) = self.integer_kernel(t) { + cpu_moe::matmul_q8k(t, xq.get_or_init(|| xs.par_iter().map(|x| cpu_moe::quantize_q8k(x)).collect()), dot) + } else { + // Any format with a row decoder can batch here. Decode each row only once. + let input: Vec = xs.iter().flatten().copied().collect(); + let mut out = vec![0.0; xs.len() * t.rows]; + t.matmul(&input, xs.len(), &mut out); + out.chunks_exact(t.rows).map(<[f32]>::to_vec).collect() + }; + for (x, y) in xs.iter().zip(&mut ys) { self.lora_add(t, x, y); } + ys + } + + /// Multiple PLE layers update one history ring in token order. Keep those models and mHC on the step path. + fn batched_prefill(&self) -> bool { + self.cfg.mhc_streams == 0 && (self.ple.is_none() || + (0..self.cfg.n_layer).filter(|&il| self.w.layer(il, "ple_key.weight").is_ok()).nth(1).is_none()) + } + + /// Feed `tokens` as `step` would one at a time and return the logits after the last one, with the same bits and + /// the same state. Where `batched_prefill` holds, each layer runs a chunk of tokens at once: every matrix reads + /// its rows once for the chunk, and only the recurrence and the attention over the cache go token by token. + /// `done(n)` after every n tokens fed. + pub fn prefill(&self, st: &mut State, tokens: &[u32], done: &mut dyn FnMut(usize)) -> Vec { + if tokens.len() < 2 || !self.batched_prefill() { + return tokens.iter().map(|&t| { let l = self.step(st, t); done(1); l }).last().unwrap_or_default(); + } + let chunk = std::env::var("STRATA_CPU_PREFILL_CHUNK").ok().and_then(|v| v.parse().ok()).filter(|&n: &usize| n > 0).unwrap_or(32); + if self.cfg.hc_n > 0 { return self.prefill_hc(st, tokens, chunk, done); } + let mut last = Vec::new(); + for ts in tokens.chunks(chunk) { + let mut xs: Vec> = ts.iter().map(|&t| self.embed(t)).collect(); + let rope: Vec<[i32; 4]> = (0..ts.len() as i32).map(|i| if i == 0 { st.rope_pos } else { [st.rope_pos[0] + i; 4] }).collect(); + for il in 0..self.cfg.n_layer { self.block_batch(il, &mut xs, &mut st.layers[il], st.pos, &rope); } + st.pos += ts.len(); + st.rope_pos = [rope[ts.len() - 1][0] + 1; 4]; + last = xs.pop().unwrap(); + done(ts.len()); + } + self.head(&last, &self.w.get("output_norm.weight").unwrap().to_f32()) + } + + /// `block` of the tokens `xs` at positions `pos`, `pos + 1`, ... (RoPE positions `rope`). + fn block_batch(&self, il: usize, xs: &mut [Vec], ls: &mut LayerState, pos: usize, rope: &[[i32; 4]]) { + let c = &self.cfg; + let norm = |w: &str, xs: &[Vec]| { + let w = self.f(il, w); + xs.iter().map(|x| { let mut h = vec![0f32; c.n_embd]; ops::rms_norm(x, &w, c.eps, &mut h); h }).collect::>() + }; + let hs = norm("attn_norm.weight", xs); + let mix = self.mixer_batch(il, &hs, ls, pos, rope); + for (x, m) in xs.iter_mut().zip(&mix) { for (a, b) in x.iter_mut().zip(m) { *a += b; } } + let hs = norm("post_attention_norm.weight", xs); + let ffn = self.ffn_layer_batch(il, &hs); + for (x, f) in xs.iter_mut().zip(&ffn) { for (a, b) in x.iter_mut().zip(f) { *a += b; } } + } + + /// `deltanet` or `attention` of the normed inputs `hs` at positions `pos`, `pos + 1`, ...: the matrices once for + /// the chunk, the recurrence, the QSA selection and the attention over the cache token by token. + fn mixer_batch(&self, il: usize, hs: &[Vec], ls: &mut LayerState, pos: usize, rope: &[[i32; 4]]) -> Vec> { + let rot = |xs: &[Vec]| xs.iter().map(|x| self.dense_rot(x).into_owned()).collect::>(); + let hr = rot(hs); + let (qh, qr) = (OnceCell::new(), OnceCell::new()); + match ls { + LayerState::Recurrent { conv, s } => { + let qkv = self.mm(&self.t(il, "attn_qkv.weight"), &hr, &qr); + let z = self.mm(&self.t(il, "attn_gate.weight"), &hr, &qr); + let beta = self.mm(&self.t(il, "ssm_beta.weight"), hs, &qh); + let alpha = self.mm(&self.t(il, "ssm_alpha.weight"), hs, &qh); + let out: Vec<_> = (0..hs.len()).map(|t| self.deltanet_mix(il, &qkv[t], &z[t], &beta[t], &alpha[t], conv, s)).collect(); + self.mm(&self.t(il, "ssm_out.weight"), &out, &OnceCell::new()) + } + LayerState::Attn { k, v, ik } => { + let sel = self.qsa_batch(il, hs, ik, pos, rope, &qh); + let qg = self.mm(&self.t(il, "attn_q.weight"), &hr, &qr); + let kraw = self.mm(&self.t(il, "attn_k.weight"), &hr, &qr); + let vv = self.mm(&self.t(il, "attn_v.weight"), &hr, &qr); + let out: Vec<_> = sel.into_iter().enumerate().map(|(t, cells)| { + let cells = cells.unwrap_or_else(|| self.cells(il, pos + t)); + self.attn_mix(il, &qg[t], &kraw[t], &vv[t], k, v, &cells, pos + t, rope[t]) + }).collect(); + self.mm(&self.t(il, "attn_output.weight"), &rot(&out), &OnceCell::new()) + } + } + } + + /// The FFN half of a layer (`moe` or `dense_ffn`) for each of `hs`. + fn ffn_layer_batch(&self, il: usize, hs: &[Vec]) -> Vec> { + if self.cfg.is_moe_layer(il) { return self.moe_batch(il, hs); } + self.ffn_batch(il, &self.t(il, "ffn_gate.weight"), &self.t(il, "ffn_up.weight"), &self.t(il, "ffn_down.weight"), "ffn_down.weight", None, hs) + } + + /// `ffn` of each of `hs`, every matrix read once for all of them. + fn ffn_batch(&self, il: usize, gate: &Tensor, up: &Tensor, down: &Tensor, down_name: &str, expert: Option, hs: &[Vec]) -> Vec> { + let rot = self.cfg.hadamard.as_ref().filter(|r| r.dense || down_name == "ffn_down_exps.weight"); + let hr: Vec>; + let hin = match rot { Some(r) => { hr = hs.iter().map(|h| r.rotated(h)).collect(); &hr[..] } None => hs }; + let q = OnceCell::new(); + let mut a = self.mm(gate, hin, &q); + for (at, ut) in a.iter_mut().zip(self.mm(up, hin, &q)) { + for (x, u) in at.iter_mut().zip(ut) { *x = ops::silu(*x) * u; } + } + let mut y = match rot { + Some(r) => self.mm(down, &a.iter().map(|x| r.rotated(x)).collect::>(), &OnceCell::new()), + None => self.mm(down, &a, &OnceCell::new()), + }; + if !self.loras.is_empty() && down_name == "ffn_down_exps.weight" { + let name = format!("blk.{il}.{down_name}"); + for (at, yt) in a.iter().zip(&mut y) { self.lora_delta(&name, at, yt, expert); } + } + y + } + + /// `moe` of each of `hs`. The tokens are grouped by expert, so an expert's rows are read once for every token of + /// the chunk that routes to it; each token's sum keeps its route's order, so the bits are those of `moe`. + fn moe_batch(&self, il: usize, hs: &[Vec]) -> Vec> { + if !self.fast_matvec || hs.len() <= 1 { return hs.iter().map(|h| self.moe(il, h)).collect(); } + let c = &self.cfg; + let q = OnceCell::new(); + let routes: Vec> = self.mm(&self.t(il, "ffn_gate_inp.weight"), hs, &q).into_iter().map(|p| self.route_logits(p)).collect(); + let n = c.n_expert; + let mut by_expert = vec![Vec::new(); n]; + // Record each token's row in its experts' batches, in the order used by the scalar reduction. + let routes: Vec> = routes.into_iter().enumerate().map(|(t, route)| { + route.into_iter().map(|(e, weight)| { + let row = by_expert[e].len(); + by_expert[e].push(t); + (e, row, weight) + }).collect() + }).collect(); + let (gate, up, down) = (self.t(il, "ffn_gate_exps.weight"), self.t(il, "ffn_up_exps.weight"), self.t(il, "ffn_down_exps.weight")); + let routed = || by_expert.par_iter().enumerate().map(|(e, ts)| { + if ts.is_empty() { return Vec::new(); } + let xs: Vec> = ts.iter().map(|&t| hs[t].clone()).collect(); + self.ffn_batch(il, &gate.expert(e, n), &up.expert(e, n), &down.expert(e, n), "ffn_down_exps.weight", Some(e), &xs) + }).collect::>(); + let shared = || self.w.layer(il, "ffn_up_shexp.weight").ok().map(|_| { + let s: Vec = match self.w.layer(il, "ffn_gate_inp_shexp.weight") { + Ok(sg) => self.mm(&sg, hs, &OnceCell::new()).into_iter().map(|v| ops::sigmoid(v[0])).collect(), + Err(_) => vec![1.0; hs.len()], + }; + (s, self.ffn_batch(il, &self.t(il, "ffn_gate_shexp.weight"), &self.t(il, "ffn_up_shexp.weight"), &self.t(il, "ffn_down_shexp.weight"), "ffn_down_shexp.weight", Some(0), hs)) + }); + let (outs, sh) = rayon::join(routed, shared); + let mut ys: Vec> = routes.into_iter().map(|route| { + let mut y = vec![0f32; c.n_embd]; + for (e, row, weight) in route { + for (a, b) in y.iter_mut().zip(&outs[e][row]) { *a += weight * b; } + } + y + }).collect(); + if let Some((s, o)) = sh { + for ((y, s), o) in ys.iter_mut().zip(s).zip(o) { for (a, b) in y.iter_mut().zip(o) { *a += s * b; } } + } + ys + } + + /// qwen4exp `prefill`: `step_embed_hc` a chunk of tokens at a time. The PLE n-gram rows, the hyper-connection + /// reads and writes, the recurrence and the attention go token by token; every matrix reads its rows once a chunk. + fn prefill_hc(&self, st: &mut State, tokens: &[u32], chunk: usize, done: &mut dyn FnMut(usize)) -> Vec { + let c = &self.cfg; + let mut last = Vec::new(); + for ts in tokens.chunks(chunk) { + let rope: Vec<[i32; 4]> = (0..ts.len() as i32).map(|i| if i == 0 { st.rope_pos } else { [st.rope_pos[0] + i; 4] }).collect(); + let mut rs: Vec> = ts.iter().map(|&t| self.embed(t).repeat(c.hc_n)).collect(); + let embs: Vec> = ts.iter().map(|&t| self.ple_embed(&mut st.ple_prev, t)).collect(); + for il in 0..c.n_layer { + if self.w.layer(il, "ple_key.weight").is_ok() { + let q = OnceCell::new(); + let keys = self.mm(&self.t(il, "ple_key.weight"), &embs, &q); + let values = self.mm(&self.t(il, "ple_value.weight"), &embs, &q); + for ((r, k), v) in rs.iter_mut().zip(&keys).zip(&values) { self.ple_mix(il, r, k, v, &mut st.ple_hist); } + } + let (h, inj) = self.hc_read_batch(&rs, &format!("blk.{il}.hc_attn_")); + let mix = self.mixer_batch(il, &h, &mut st.layers[il], st.pos, &rope); + for ((r, m), j) in rs.iter_mut().zip(&mix).zip(&inj) { Self::hc_write(r, m, j); } + let (h, inj) = self.hc_read_batch(&rs, &format!("blk.{il}.hc_ffn_")); + let ffn = self.ffn_layer_batch(il, &h); + for ((r, f), j) in rs.iter_mut().zip(&ffn).zip(&inj) { Self::hc_write(r, f, j); } + } + st.pos += ts.len(); + st.rope_pos = [rope[ts.len() - 1][0] + 1; 4]; + last = rs.pop().unwrap(); + done(ts.len()); + } + let (h, _) = self.hc_read(&last, "output_hc_"); + self.mv(&self.w.get("output.weight").unwrap(), &h) + } + pub fn load(g: &'a Gguf) -> anyhow::Result> { Self::load_with_lora(g, &[]) } pub fn load_with_lora(g: &'a Gguf, loras: &[(String, f32)]) -> anyhow::Result> { Self::load_with_aux(g, None, loras) } pub fn load_with_aux(g: &'a Gguf, aux: Option<&'a Gguf>, loras: &[(String, f32)]) -> anyhow::Result> { + Self::load_with_matvec(g, aux, loras, false) + } + + pub fn load_with_matvec(g: &'a Gguf, aux: Option<&'a Gguf>, loras: &[(String, f32)], fast_matvec: bool) -> anyhow::Result> { let mut cfg = ModelConfig::from_gguf(g)?; // A DFlash draft given on the command line replaces the target's own MTP head; without this the draft was // ignored without a word for a target GGUF that carries one. @@ -123,11 +347,20 @@ impl<'a> Model<'a> { && ag.tensors.contains_key("token_embd.weight") && ModelConfig::from_gguf(ag).is_ok() }); - let w = Weights::new_with_aux(g, if is_standalone_draft { None } else { aux })?; + let mut w = Weights::new_with_aux(g, if is_standalone_draft { None } else { aux })?; + // PTQ1_0 rows are copied to the 2-bit PTQ1_0R layout, whose AVX2 tiles decode Ternary Bonsai 27B at 1.7 tok/s + // instead of 0.7 on an i5-8365U. The copy takes 34/28 of the file's bytes in RAM; STRATA_PTQ1_REPACK=0 keeps + // the file's layout. + if fast_matvec && cfg!(target_feature = "avx2") && std::env::var_os("STRATA_SCALAR").is_none() + && std::env::var("STRATA_PTQ1_REPACK").as_deref() != Ok("0") { + let t0 = std::time::Instant::now(); + let n = w.repack_ptq1_0(); + if n > 0 { crate::say!("ptq1_0: repacked {} MB for the CPU kernels in {:.1} s", n >> 20, t0.elapsed().as_secs_f32()); } + } let mut draft_model = None; if is_standalone_draft { let ag = aux.unwrap(); - let dm = Model::load(ag)?; + let dm = Self::load_with_matvec(ag, None, &[], fast_matvec)?; anyhow::ensure!( dm.cfg.n_vocab == cfg.n_vocab, "standalone draft model vocab ({}) != target vocab ({})", @@ -140,7 +373,11 @@ impl<'a> Model<'a> { ); draft_model = Some(Box::new(dm)); } else if cfg.n_nextn == 0 { - if let Some(ag) = aux.filter(|_| w.layer(cfg.n_layer, "eagle3.fc.weight").is_ok()) { + let is_dflash_gguf = aux.is_some_and(|ag| { + ag.tensors.contains_key("dflash.fc.weight") + || ag.meta.get("general.architecture").and_then(|v| v.as_str()) == Some("dflash") + }); + if let Some(ag) = aux.filter(|_| !is_dflash_gguf && w.layer(cfg.n_layer, "eagle3.fc.weight").is_ok()) { let il = cfg.n_layer; let wq = w.layer(il, "attn_q.weight")?; let wk = w.layer(il, "attn_k.weight")?; @@ -189,13 +426,16 @@ impl<'a> Model<'a> { crate::say!( "note: loaded standalone EAGLE3 draft head (extract_layers={extract_layers:?}, heads={n_head}x{head_dim}, kv={n_head_kv}, ff={n_ff}, draft_vocab={draft_vocab})" ); - } else if aux.is_some_and(|ag| ag.tensors.contains_key("dflash.fc.weight")) { + } else if is_dflash_gguf { let ag = aux.unwrap(); + let is_llamacpp_dflash = !ag.tensors.contains_key("dflash.fc.weight"); let u = |k: &str| ag.meta.get(k).and_then(|v| v.as_u64()).map(|v| v as usize); let f = |k: &str| ag.meta.get(k).and_then(|v| v.as_f32()); let n_layer = u("dflash.block_count").context("dflash.block_count")?; let block_size = u("dflash.block_size").unwrap_or(16).max(2); - let mask_token_id = u("dflash.mask_token_id").context("dflash.mask_token_id")? as u32; + let mask_token_id = u("dflash.mask_token_id") + .or_else(|| u("tokenizer.ggml.mask_token_id")) + .context("dflash.mask_token_id")? as u32; let n_embd = u("dflash.embedding_length").unwrap_or(cfg.n_embd); let n_ff = u("dflash.feed_forward_length").context("dflash.feed_forward_length")?; let n_head = u("dflash.attention.head_count").unwrap_or(cfg.n_head); @@ -206,14 +446,18 @@ impl<'a> Model<'a> { let eps = f("dflash.attention.layer_norm_rms_epsilon").unwrap_or(cfg.eps); let sliding_window = u("dflash.attention.sliding_window").unwrap_or(0); let input_embedding_scale = f("dflash.input_embedding_scale").unwrap_or(1.0); - let output_multiplier = f("dflash.output_multiplier").unwrap_or(1.0); + // llama.cpp's converter writes the same value as `dflash.logit_scale`. + let output_multiplier = f("dflash.output_multiplier").or_else(|| f("dflash.logit_scale")).unwrap_or(1.0); let conv_kernel_size = u("dflash.conv_kernel_size").unwrap_or(0); let conv_group_size = u("dflash.conv_group_size").unwrap_or(0); let selector_rank = u("dflash.selector_rank").unwrap_or(0); let selector_top_k = u("dflash.selector_top_k").unwrap_or(0); let target_layer_ids = ag.meta.get("dflash.target_layers").and_then(|v| v.as_arr()) .context("dflash.target_layers")? - .iter().map(|v| v.as_u64().map(|x| x as usize).context("bad dflash target layer")).collect::>>()?; + .iter().map(|v| { + let x = v.as_u64().context("bad dflash target layer")? as usize; + Ok(if is_llamacpp_dflash { x.checked_sub(1).context("1-indexed dflash target layer 0")? } else { x }) + }).collect::>>()?; anyhow::ensure!(target_layer_ids.iter().all(|&id| id < cfg.n_layer), "dflash target_layer_ids out of range for {} layers: {target_layer_ids:?}", cfg.n_layer); let layer_swa = ag.meta.get("dflash.attention.sliding_window_pattern").and_then(|v| v.as_arr()) .filter(|a| a.len() >= n_layer) @@ -270,17 +514,25 @@ impl<'a> Model<'a> { let heads_per_ngram = int("heads_per_ngram")? as usize; anyhow::ensure!(int("ngram_size")? == PLE_NGRAM as u64 && heads_per_ngram > 0 && int("conv_kernel")? == PLE_KERNEL as u64, "unsupported PLE geometry"); - let ple = Ple { mult: arr("layer_multipliers")?, off: arr("head_offsets")?, vocab: arr("head_vocab_sizes")?, eos: int("eos_token_id")? as i64, heads_per_ngram }; + let t = w.get("per_layer_token_embd.weight")?; + let direct = g.tensors.get("per_layer_token_embd.weight").and_then(|i| { + let (f, at) = g.file_of(i); + crate::weights::DirectRows::open(f, at, t.row_bytes()) + }); + let ple = Ple { mult: arr("layer_multipliers")?, off: arr("head_offsets")?, vocab: arr("head_vocab_sizes")?, eos: int("eos_token_id")? as i64, heads_per_ngram, direct }; let heads = (PLE_NGRAM - 1) * heads_per_ngram; anyhow::ensure!(ple.mult.len() == PLE_NGRAM && ple.off.len() == heads && ple.vocab.len() == heads && ple.vocab.iter().all(|&v| v > 0) && heads * cfg.n_embd_ple == cfg.n_embd, "bad PLE metadata"); - w.get("per_layer_token_embd.weight")?; + // A table from `--ple` can be made for another model: every row a token can ask for must be in it. + let need = ple.off.iter().zip(&ple.vocab).map(|(o, v)| o.saturating_add(*v)).max().unwrap_or(0); + anyhow::ensure!(t.cols == cfg.n_embd_ple && t.rows as u64 >= need, + "the n-gram table is {} x {}, this model needs {} x {need} (wrong --ple file?)", t.cols, t.rows, cfg.n_embd_ple); Some(ple) } else { w.get("output_norm.weight")?; None }; - let mut m = Model { cfg, w, loras: Vec::new(), draft_model, ple }; + let mut m = Model { cfg, w, loras: Vec::new(), draft_model, ple, fast_matvec, lora_rt: HashMap::new() }; m.apply_lora(loras)?; Ok(m) } @@ -297,11 +549,41 @@ impl<'a> Model<'a> { "lora: target {name} is {}x{} with {ne} experts, adapter is {}x{} with {}", base.rows / ne, base.cols, e.out_dim, e.in_dim, e.n_expert); } self.w.clear_baked(); + self.lora_rt.clear(); self.loras = loras; - self.w.bake_lora(&self.loras); + // Baking makes each target an F32 copy, which the fast CPU path then reads through the float kernel (Ternary + // Bonsai with a 48-site rank-1 adapter: about 2 GB a token, 1 tok/s). There the delta is added at run time + // to the quantized product instead; the reference path and the GPU upload keep the baked tensors. + if !self.fast_matvec { return self.w.bake_lora(&self.loras); } + for lora in &self.loras { + for (name, e) in &lora.entries { + if name.ends_with("ffn_down_exps.weight") { continue; } + let Ok(base) = self.w.get(name) else { crate::say!("lora: target {name} not found, skipping"); continue }; + if e.n_expert != 1 || base.cols != e.in_dim || base.rows != e.out_dim { + crate::say!("lora: target {name} is {}x{}, adapter is {}x{} with {} experts; skipping", base.rows, base.cols, e.out_dim, e.in_dim, e.n_expert); + continue; + } + let mult = if lora.alpha > 0.0 { lora.scale * lora.alpha / e.rank as f32 } else { lora.scale }; + self.lora_rt.entry(base.data.as_ptr() as usize).or_default() + .push(RtLora { mult, rank: e.rank, a: e.a[0].clone(), b: e.b[0].clone() }); + } + } + if !self.lora_rt.is_empty() { crate::say!("lora: {} tensors take their deltas at run time", self.lora_rt.len()); } Ok(()) } + /// Adds the run-time LoRA deltas of `t` (`lora_rt`) for input `x` (the input `t` reads) to `y`. The same sums as + /// the baked weights, W + mult B A, in another order. + fn lora_add(&self, t: &Tensor, x: &[f32], y: &mut [f32]) { + let Some(ls) = self.lora_rt.get(&(t.data.as_ptr() as usize)) else { return }; + for l in ls { + for r in 0..l.rank { + let s = l.mult * l.a[r * x.len()..(r + 1) * x.len()].iter().zip(x).map(|(a, b)| a * b).sum::(); + for (o, yv) in y.iter_mut().enumerate() { *yv += s * l.b[o * l.rank + r]; } + } + } + } + pub fn lora_delta(&self, name: &str, x: &[f32], y: &mut [f32], expert: Option) { for lora in &self.loras { if let Some(e) = lora.entries.get(name) { @@ -329,12 +611,19 @@ impl<'a> Model<'a> { fn t(&self, il: usize, suffix: &str) -> Tensor<'a> { self.w.layer(il, suffix).unwrap_or_else(|e| panic!("{e:#}")) } - fn f(&self, il: usize, suffix: &str) -> Vec { self.t(il, suffix).to_f32() } + /// The tensor as floats: an F32 tensor in place (the mapped file aligns tensor data), others dequantized. Called + /// per token and layer, so the in-place read matters (a copy of `ssm_conv1d` per token was 10% of a CPU prefill). + fn f(&self, il: usize, suffix: &str) -> std::borrow::Cow<'a, [f32]> { + let t = self.t(il, suffix); + if let Some(values) = t.as_f32() { return values.into(); } + t.to_f32().into() + } pub fn embed(&self, token: u32) -> Vec { let mut x = vec![0f32; self.cfg.n_embd]; let idx = (token as usize).min(self.cfg.n_vocab.saturating_sub(1)); self.w.get("token_embd.weight").unwrap().row(idx, &mut x); + if let Some(r) = self.cfg.hadamard.as_ref().filter(|r| r.dense) { r.unrotate(&mut x); } x } @@ -413,8 +702,8 @@ impl<'a> Model<'a> { let norm: Vec = r.iter().map(|&v| v * scale).collect(); let w = self.t(il, &format!("{prefix}.weight")); let b = self.f(il, &format!("{prefix}.bias")); - let mut logits = mv(&w, &norm); - for (l, &bi) in logits.iter_mut().zip(&b) { *l += bi; } + let mut logits = self.mv(&w, &norm); + for (l, &bi) in logits.iter_mut().zip(b.iter()) { *l += bi; } let pre: Vec = logits[..streams].iter().map(|&v| ops::sigmoid(v)).collect(); let post: Vec = logits[streams..2 * streams].iter().map(|&v| 2.0 * ops::sigmoid(v)).collect(); let mix = if logits.len() <= 2 * streams { @@ -483,12 +772,13 @@ impl<'a> Model<'a> { }; Self::hc_write(&mut r, &mix, &inj); let (h, inj) = self.hc_read(&r, &format!("blk.{il}.hc_ffn_")); - Self::hc_write(&mut r, &self.moe(il, &h), &inj); + let ffn = if c.is_moe_layer(il) { self.moe(il, &h) } else { self.dense_ffn(il, &h) }; + Self::hc_write(&mut r, &ffn, &inj); } st.pos += 1; st.rope_pos = [rope_pos[0] + 1; 4]; let (h, _) = self.hc_read(&r, "output_hc_"); - (mv(&self.w.get("output.weight").unwrap(), &h), r) + (self.mv(&self.w.get("output.weight").unwrap(), &h), r) } /// Hyper-connection read (`build_hc_mix`) of the stack `r` with the tensors `{p}norm/down/up/inject.weight`: @@ -499,10 +789,28 @@ impl<'a> Model<'a> { let t = |s: &str| self.w.get(&format!("{p}{s}.weight")); let mut xn = vec![0f32; r.len()]; self.gnorm(r, &t("norm").unwrap().to_f32(), &mut xn); - let lo: Vec = mv(&t("down").unwrap(), &xn).into_iter().map(|v| ops::silu(v / hc)).collect(); + let lo: Vec = self.mv(&t("down").unwrap(), &xn).into_iter().map(|v| ops::silu(v / hc)).collect(); let mut mixed = vec![0f32; n]; - for (i, g) in mv(&t("up").unwrap(), &lo).into_iter().enumerate() { mixed[i % n] += xn[i] * ops::sigmoid(g) / hc; } - (mixed, t("inject").map(|w| mv(&w, &xn)).unwrap_or_default()) + for (i, g) in self.mv(&t("up").unwrap(), &lo).into_iter().enumerate() { mixed[i % n] += xn[i] * ops::sigmoid(g) / hc; } + (mixed, t("inject").map(|w| self.mv(&w, &xn)).unwrap_or_default()) + } + + /// `hc_read` of each stack of `rs`, every matrix read once for all of them. + fn hc_read_batch(&self, rs: &[Vec], p: &str) -> (Vec>, Vec>) { + let (n, hc) = (self.cfg.n_embd, self.cfg.hc_n as f32); + let t = |s: &str| self.w.get(&format!("{p}{s}.weight")); + let norm = t("norm").unwrap().to_f32(); + let xns: Vec> = rs.iter().map(|r| { let mut xn = vec![0f32; r.len()]; self.gnorm(r, &norm, &mut xn); xn }).collect(); + let q = OnceCell::new(); + let lo: Vec> = self.mm(&t("down").unwrap(), &xns, &q).into_iter() + .map(|l| l.into_iter().map(|v| ops::silu(v / hc)).collect()).collect(); + let mixed = self.mm(&t("up").unwrap(), &lo, &OnceCell::new()).into_iter().zip(&xns).map(|(g, xn)| { + let mut mixed = vec![0f32; n]; + for (i, g) in g.into_iter().enumerate() { mixed[i % n] += xn[i] * ops::sigmoid(g) / hc; } + mixed + }).collect(); + let inj = match t("inject") { Ok(w) => self.mm(&w, &xns, &q), Err(_) => vec![Vec::new(); rs.len()] }; + (mixed, inj) } /// Hyper-connection write (`build_hc_combine`): stream c += out * 2 sigmoid(inject[c] / hc). @@ -551,25 +859,39 @@ impl<'a> Model<'a> { if rows.is_empty() { return Vec::new() } let (table, d) = (self.w.get("per_layer_token_embd.weight").unwrap(), self.cfg.n_embd_ple); let mut emb = vec![0f32; self.cfg.n_embd]; - for (r, e) in rows.into_iter().zip(emb.chunks_exact_mut(d)) { table.row(r as usize, e); } + let direct = self.ple.as_ref().and_then(|p| p.direct.as_ref()); + // ponytail: no row cache; each token reads its 16 rows from the drive. Cache hot rows if a drive is too slow. + let mut buf = Vec::new(); + for (r, e) in rows.into_iter().zip(emb.chunks_exact_mut(d)) { + match direct.map(|f| f.read(r as usize, &mut buf)) { + Some(Ok(b)) => table.row_of(b, e), + Some(Err(err)) => { crate::say!("PLE row {r}: {err}; read through the map"); table.row(r as usize, e) } + None => table.row(r as usize, e), + } + } emb } /// The PLE block (`build_ple`) on the stack `r`: a per-stream gate from key·query scales the value, and the /// normalized gated rows feed a causal conv dilated by the n-gram size. r += gated + silu(conv). fn ple(&self, il: usize, r: &mut [f32], emb: &[f32], hist: &mut [f32]) { + let (key, value) = (self.mv(&self.t(il, "ple_key.weight"), emb), self.mv(&self.t(il, "ple_value.weight"), emb)); + self.ple_mix(il, r, &key, &value, hist); + } + + /// `ple` after its two projections of the embedding: `key_raw` = ple_key · emb, `value` = ple_value · emb. + fn ple_mix(&self, il: usize, r: &mut [f32], key_raw: &[f32], value: &[f32], hist: &mut [f32]) { let (n, d) = (self.cfg.n_embd, r.len()); let mut key = vec![0f32; d]; - self.gnorm(&mv(&self.t(il, "ple_key.weight"), emb), &self.f(il, "ple_norm_key.weight"), &mut key); + self.gnorm(key_raw, &self.f(il, "ple_norm_key.weight"), &mut key); let mut query = vec![0f32; d]; self.gnorm(r, &self.f(il, "ple_norm_query.weight"), &mut query); - let value = mv(&self.t(il, "ple_value.weight"), emb); let mut gated = vec![0f32; d]; for (c, gc) in gated.chunks_exact_mut(n).enumerate() { let s = key[c * n..(c + 1) * n].iter().zip(&query[c * n..(c + 1) * n]).map(|(a, b)| a * b).sum::() / (n as f32).sqrt(); let sign = if s > 0.0 { 1.0 } else if s < 0.0 { -1.0 } else { 0.0 }; let gate = ops::sigmoid(sign * s.abs().max(1e-6).sqrt()); - for (o, v) in gc.iter_mut().zip(&value) { *o = v * gate; } + for (o, v) in gc.iter_mut().zip(value) { *o = v * gate; } } let mut norm = vec![0f32; d]; self.gnorm(&gated, &self.f(il, "ple_norm_conv.weight"), &mut norm); @@ -603,7 +925,12 @@ impl<'a> Model<'a> { let mut h = vec![0f32; self.cfg.n_embd]; ops::rms_norm(x, norm, self.cfg.eps, &mut h); let head = self.w.get("output.weight").or_else(|_| self.w.get("token_embd.weight")).unwrap(); - mv(&head, &h) + self.mv(&head, &self.dense_rot(&h)) + } + + /// The input of a matrix of a rotated dense file (`config::Hadamard::dense`) as that matrix reads it. + fn dense_rot<'x>(&self, x: &'x [f32]) -> std::borrow::Cow<'x, [f32]> { + match self.cfg.hadamard.as_ref().filter(|r| r.dense) { Some(r) => r.rotated(x).into(), None => x.into() } } /// MTP draft (`nextn` block, stored as layer n_layer): logits for the token after `token`, from `hid`, the main @@ -615,13 +942,38 @@ impl<'a> Model<'a> { let mut eh = vec![0f32; 2 * n]; ops::rms_norm(&self.embed(token), &self.f(il, "nextn.enorm.weight"), c.eps, &mut eh[..n]); ops::rms_norm(hid, &self.f(il, "nextn.hnorm.weight"), c.eps, &mut eh[n..]); - let mut x = mv(&self.t(il, "nextn.eh_proj.weight"), &eh); + let mut x = self.mv(&self.t(il, "nextn.eh_proj.weight"), &eh); let rope_pos = [ms.pos as i32; 4]; self.block(il, &mut x, &mut ms.kv, ms.pos, rope_pos); ms.pos += 1; (self.head(&x, &self.f(il, "nextn.shared_head_norm.weight")), x) } + fn project_streams(&self, proj: &Tensor, e: &[f32], hn: &[f32]) -> Vec { + let n = e.len(); + assert_eq!(proj.cols, 2 * n); + let mut out = vec![0.0; hn.len() / n * proj.rows]; + let kernel = self.integer_kernel(proj); + // Only whole Q8_K blocks are independent of the following stream's values. + let shared = if kernel.is_some() { n / 256 * 256 } else { 0 }; + let mut blocks = cpu_moe::quantize_q8k(&e[..shared]); + let mut tail = vec![0.0; proj.cols - shared]; + tail[..n - shared].copy_from_slice(&e[shared..]); + for (h, y) in hn.chunks_exact(n).zip(out.chunks_exact_mut(proj.rows)) { + tail[n - shared..].copy_from_slice(h); + if let Some(dot) = kernel { + blocks.truncate(shared / 256); + blocks.extend(cpu_moe::quantize_q8k(&tail)); + cpu_moe::matvec_q8k(proj, &blocks, y, dot); + } else if self.fast_matvec { + proj.matmul(&tail, 1, y); + } else { + proj.matvec(&tail, y); + } + } + out + } + /// qwen4exp draft step (llama.cpp `graph_mtp`): `hid` is the hc_n x n_embd stack. Every stream is projected /// on its own from [enorm(embed), hnorm(stream)], then the nextn block runs as a hyper-connection layer with /// plain attention (no PLE, no QSA). Returns the logits and the new stack, which is `hid` of the next draft. @@ -633,7 +985,7 @@ impl<'a> Model<'a> { let mut hn = vec![0f32; hid.len()]; self.gnorm(hid, &self.f(il, "nextn.hnorm.weight"), &mut hn); let proj = self.t(il, "nextn.eh_proj.weight"); - let mut r: Vec = hn.chunks_exact(n).flat_map(|h| mv(&proj, &[&e, h].concat())).collect(); + let mut r = self.project_streams(&proj, &e, &hn); let (h, inj) = self.hc_read(&r, &format!("blk.{il}.hc_attn_")); let LayerState::Attn { k, v, ik } = &mut ms.kv else { unreachable!("the nextn block is an attention layer") }; Self::hc_write(&mut r, &self.attention(il, &h, k, v, ik, ms.pos, [ms.pos as i32; 4]), &inj); @@ -641,21 +993,31 @@ impl<'a> Model<'a> { Self::hc_write(&mut r, &self.moe(il, &h), &inj); ms.pos += 1; let (h, _) = self.hc_read(&r, &format!("blk.{il}.nextn.hc_head_")); - (mv(&self.w.get("output.weight").unwrap(), &h), r) + (self.mv(&self.w.get("output.weight").unwrap(), &h), r) } fn deltanet(&self, il: usize, h: &[f32], conv: &mut [f32], s: &mut [f32]) -> Vec { + let hr = self.dense_rot(h); + let qkv = self.mv(&self.t(il, "attn_qkv.weight"), &hr); + let z = self.mv(&self.t(il, "attn_gate.weight"), &hr); + let beta = self.mv(&self.t(il, "ssm_beta.weight"), h); + let alpha = self.mv(&self.t(il, "ssm_alpha.weight"), h); + let out = self.deltanet_mix(il, &qkv, &z, &beta, &alpha, conv, s); + self.mv(&self.t(il, "ssm_out.weight"), &out) + } + + /// The token's part of `deltanet` between its projections (`beta` and `alpha` raw) and `ssm_out`: the conv, the + /// recurrence, the norm and the gate, advancing `conv` and `s`. Returns the input of `ssm_out`. + fn deltanet_mix(&self, il: usize, qkv: &[f32], z: &[f32], beta: &[f32], alpha: &[f32], conv: &mut [f32], s: &mut [f32]) -> Vec { let c = &self.cfg; let (dk, nk, nv) = (c.ssm_d_state, c.ssm_n_group, c.ssm_dt_rank); let dv = c.ssm_dv(); let channels = c.ssm_d_inner + 2 * nk * dk; let kw = c.ssm_conv; - let qkv = mv(&self.t(il, "attn_qkv.weight"), h); - let z = mv(&self.t(il, "attn_gate.weight"), h); - let beta: Vec = mv(&self.t(il, "ssm_beta.weight"), h).into_iter().map(ops::sigmoid).collect(); + let beta: Vec = beta.iter().map(|&b| ops::sigmoid(b)).collect(); let (dt_bias, a) = (self.f(il, "ssm_dt.bias"), self.f(il, "ssm_a")); - let g: Vec = mv(&self.t(il, "ssm_alpha.weight"), h).iter().enumerate() + let g: Vec = alpha.iter().enumerate() .map(|(i, &al)| ops::softplus(al + dt_bias[i]) * a[i]).collect(); // Causal depthwise conv over [state..., current], then SiLU. @@ -668,7 +1030,7 @@ impl<'a> Model<'a> { y[ch] = ops::silu(acc); } conv.copy_within(channels.., 0); - conv[(kw - 2) * channels..].copy_from_slice(&qkv); + conv[(kw - 2) * channels..].copy_from_slice(qkv); let (q, rest) = y.split_at_mut(nk * dk); let (k, v) = rest.split_at_mut(nk * dk); @@ -677,13 +1039,17 @@ impl<'a> Model<'a> { let norm_w = self.f(il, "ssm_norm.weight"); let scale = 1.0 / (dk as f32).sqrt(); let mut out = vec![0f32; nv * dv]; - let mut o = vec![0f32; dv]; - for vh in 0..nv { + // qwen4exp gates with sigmoid(z), the others with silu(z) + let gate = if c.arch == "qwen4exp" { ops::sigmoid } else { ops::silu }; + let (q, k, v) = (&*q, &*k, &*v); + // The heads are independent (each its own state rows and output), so they run in parallel with the same bits. + out.par_chunks_mut(dv).zip(s.par_chunks_mut(dv * dk)).enumerate().for_each(|(vh, (oh, sm))| { let kh = if c.k_interleave { vh / (nv / nk) } else { vh % nk }; let (qh, khv, vv) = (&q[kh * dk..(kh + 1) * dk], &k[kh * dk..(kh + 1) * dk], &v[vh * dv..(vh + 1) * dv]); - let sm = &mut s[vh * dv * dk..(vh + 1) * dv * dk]; // row j (value dim) x col i (key dim) + // sm: row j (value dim) x col i (key dim) let decay = g[vh].exp(); for x in sm.iter_mut() { *x *= decay; } + let mut o = vec![0f32; dv]; for j in 0..dv { let row = &mut sm[j * dk..(j + 1) * dk]; let sk: f32 = row.iter().zip(khv).map(|(a, b)| a * b).sum(); @@ -691,13 +1057,11 @@ impl<'a> Model<'a> { for (r, kk) in row.iter_mut().zip(khv) { *r += d * kk; } o[j] = row.iter().zip(qh.iter()).map(|(a, b)| a * b).sum::() * scale; } - let oh = &mut out[vh * dv..(vh + 1) * dv]; ops::rms_norm(&o, &norm_w, c.eps, oh); - // qwen4exp gates with sigmoid(z), the others with silu(z) - let gate = if c.arch == "qwen4exp" { ops::sigmoid } else { ops::silu }; for (x, zz) in oh.iter_mut().zip(&z[vh * dv..(vh + 1) * dv]) { *x *= gate(*zz); } - } - mv(&self.t(il, "ssm_out.weight"), &out) + }); + if let Some(r) = self.cfg.hadamard.as_ref().filter(|r| r.dense) { r.rotate_ssm_out(&mut out, nk, nv); } + out } /// RoPE for one head: 1-D when the model has no M-RoPE sections, otherwise `[t, y, x, z]`. @@ -715,13 +1079,32 @@ impl<'a> Model<'a> { /// there are no more complete blocks than that. Mirrors llama.cpp qwen4exp.cpp `build_qsa_sel`. fn qsa(&self, il: usize, h: &[f32], ik: &mut Vec, pos: usize, rope_pos: [i32; 4]) -> Option> { let c = &self.cfg; - let (nh, d) = (c.idx_n_head, c.idx_head_dim); if c.idx_top_k == 0 || il >= c.n_layer || self.w.layer(il, "indexer.k_proj.weight").is_err() { return None; } - ik.extend_from_slice(&mv(&self.t(il, "indexer.k_proj.weight"), h)); + ik.extend_from_slice(&self.mv(&self.t(il, "indexer.k_proj.weight"), h)); + if (pos + 1) / QSA_POOL <= c.idx_top_k / QSA_POOL { return None; } + Some(self.qsa_select(il, &self.mv(&self.t(il, "indexer.q_proj.weight"), h), ik, pos, rope_pos)) + } + + /// `qsa` of each of `hs` at positions `pos`, `pos + 1`, ...: the indexer projections once for the chunk, each + /// token's key appended before its own selection. `q` holds the quantized `hs`. + fn qsa_batch(&self, il: usize, hs: &[Vec], ik: &mut Vec, pos: usize, rope: &[[i32; 4]], q: &OnceCell>>) -> Vec>> { + let c = &self.cfg; + if c.idx_top_k == 0 || il >= c.n_layer || self.w.layer(il, "indexer.k_proj.weight").is_err() { return vec![None; hs.len()]; } + let kp = self.mm(&self.t(il, "indexer.k_proj.weight"), hs, q); + let top = c.idx_top_k / QSA_POOL; + let qp = if (pos + hs.len()) / QSA_POOL > top { self.mm(&self.t(il, "indexer.q_proj.weight"), hs, q) } else { Vec::new() }; + kp.iter().enumerate().map(|(t, k)| { + ik.extend_from_slice(k); + ((pos + t + 1) / QSA_POOL > top).then(|| self.qsa_select(il, &qp[t], ik, pos + t, rope[t])) + }).collect() + } + + /// The QSA cells of row `pos` from its raw indexer query `qr`, once there are more complete blocks than the top. + fn qsa_select(&self, il: usize, qr: &[f32], ik: &[f32], pos: usize, rope_pos: [i32; 4]) -> Vec { + let c = &self.cfg; + let (nh, d) = (c.idx_n_head, c.idx_head_dim); let (nb, top) = ((pos + 1) / QSA_POOL, c.idx_top_k / QSA_POOL); - if nb <= top { return None; } let (qn, kn) = (self.f(il, "indexer.q_norm.weight"), self.f(il, "indexer.k_norm.weight")); - let qr = mv(&self.t(il, "indexer.q_proj.weight"), h); let mut q = vec![0f32; nh * d]; for i in 0..nh { ops::rms_norm(&qr[i * d..(i + 1) * d], &qn, c.eps, &mut q[i * d..(i + 1) * d]); @@ -741,24 +1124,34 @@ impl<'a> Model<'a> { } let mut blocks = ops::top_k(&score, top); blocks.sort_unstable(); - Some(blocks.iter().flat_map(|b| b * QSA_POOL..(b + 1) * QSA_POOL).chain(nb * QSA_POOL..pos + 1).collect()) + blocks.iter().flat_map(|b| b * QSA_POOL..(b + 1) * QSA_POOL).chain(nb * QSA_POOL..pos + 1).collect() } fn attention(&self, il: usize, h: &[f32], kc: &mut Vec, vc: &mut Vec, ik: &mut Vec, pos: usize, rope_pos: [i32; 4]) -> Vec { + let cells = self.qsa(il, h, ik, pos, rope_pos).unwrap_or_else(|| self.cells(il, pos)); + let h = &*self.dense_rot(h); + let qg = self.mv(&self.t(il, "attn_q.weight"), h); + let kraw = self.mv(&self.t(il, "attn_k.weight"), h); + let v = self.mv(&self.t(il, "attn_v.weight"), h); + let out = self.attn_mix(il, &qg, &kraw, &v, kc, vc, &cells, pos, rope_pos); + self.mv(&self.t(il, "attn_output.weight"), &self.dense_rot(&out)) + } + + /// The cache cells row `pos` attends to without QSA: all up to it, or the window of a sliding-window layer. + fn cells(&self, il: usize, pos: usize) -> Vec { + let c = &self.cfg; + if c.swa.get(il).copied().unwrap_or(false) { ((pos + 1).saturating_sub(c.n_swa)..=pos).collect() } else { (0..pos + 1).collect() } + } + + /// The token's part of `attention` between its projections and `attn_output`: q/k norms and RoPE, the cache + /// append, attention over `cells` and the output gate. Returns the input of `attn_output` before `dense_rot`. + fn attn_mix(&self, il: usize, qg: &[f32], kraw: &[f32], v: &[f32], kc: &mut Vec, vc: &mut Vec, cells: &[usize], pos: usize, rope_pos: [i32; 4]) -> Vec { let c = &self.cfg; - let cells = self.qsa(il, h, ik, pos, rope_pos).unwrap_or_else(|| { - if c.swa.get(il).copied().unwrap_or(false) { - ((pos + 1).saturating_sub(c.n_swa)..=pos).collect() - } else { - (0..pos + 1).collect() - } - }); let use_rope = c.rope_layer.get(il).copied().unwrap_or(true); - let sinks = if c.attn_sinks { self.f(il, "attn_sinks.weight") } else { Vec::new() }; + let sinks = if c.attn_sinks { self.f(il, "attn_sinks.weight") } else { Default::default() }; let (hd, nh, nkv) = (c.head_dim, c.n_head, c.n_head_kv); let qs = if c.q_gate { 2 * hd } else { hd }; // per-head row of attn_q: query, then the gate if any - let qg = mv(&self.t(il, "attn_q.weight"), h); let (qn, kn) = (self.f(il, "attn_q_norm.weight"), self.f(il, "attn_k_norm.weight")); let mut q = vec![0f32; nh * hd]; for i in 0..nh { @@ -766,8 +1159,6 @@ impl<'a> Model<'a> { ops::rms_norm(&qg[i * qs..i * qs + hd], &qn, c.eps, qh); if use_rope { self.rope(qh, pos, rope_pos); } } - let kraw = mv(&self.t(il, "attn_k.weight"), h); - let v = mv(&self.t(il, "attn_v.weight"), h); let mut k = vec![0f32; nkv * hd]; for i in 0..nkv { let kh = &mut k[i * hd..(i + 1) * hd]; @@ -775,7 +1166,7 @@ impl<'a> Model<'a> { if use_rope { self.rope(kh, pos, rope_pos); } } kc.extend_from_slice(&k); - vc.extend_from_slice(&v); + vc.extend_from_slice(v); let scale = 1.0 / (hd as f32).sqrt(); let mut out = vec![0f32; nh * hd]; let mut sc = vec![0f32; cells.len()]; @@ -797,19 +1188,20 @@ impl<'a> Model<'a> { for (o, gg) in oh.iter_mut().zip(gate) { *o *= ops::sigmoid(*gg); } } } - mv(&self.t(il, "attn_output.weight"), &out) + out } fn ffn(&self, il: usize, gate: &Tensor, up: &Tensor, down: &Tensor, down_name: &str, expert: Option, h: &[f32]) -> Vec { // A routed expert of a Gyro file reads rotated inputs (`config::Hadamard`); the LoRA delta reads the plain ones. // The shared expert (also called with an expert index) reads plain inputs. - let rot = self.cfg.hadamard.as_ref().filter(|_| down_name == "ffn_down_exps.weight"); + let rot = self.cfg.hadamard.as_ref().filter(|r| r.dense || down_name == "ffn_down_exps.weight"); let hr = rot.map(|r| r.rotated(h)); let h = hr.as_deref().unwrap_or(h); - let mut a = mv(gate, h); - for (x, u) in a.iter_mut().zip(mv(up, h)) { *x = ops::silu(*x) * u; } - let mut y = match rot { Some(r) => mv(down, &r.rotated(&a)), None => mv(down, &a) }; - if down_name == "ffn_down_exps.weight" { + let activation = OnceCell::new(); + let mut a = self.mv_cached(gate, h, &activation); + for (x, u) in a.iter_mut().zip(self.mv_cached(up, h, &activation)) { *x = ops::silu(*x) * u; } + let mut y = match rot { Some(r) => self.mv(down, &r.rotated(&a)), None => self.mv(down, &a) }; + if !self.loras.is_empty() && down_name == "ffn_down_exps.weight" { self.lora_delta(&format!("blk.{il}.{down_name}"), &a, &mut y, expert); } y @@ -820,23 +1212,29 @@ impl<'a> Model<'a> { } fn moe(&self, il: usize, h: &[f32]) -> Vec { - let mut y = self.routed_experts(il, h); - if self.w.layer(il, "ffn_up_shexp.weight").is_ok() { + if self.w.layer(il, "ffn_up_shexp.weight").is_err() { return self.routed_experts(il, h); } + let shared = || { // Flint's shared expert is always on; Qwen's has a sigmoid gate. let s = match self.w.layer(il, "ffn_gate_inp_shexp.weight") { - Ok(sg) => ops::sigmoid(mv(&sg, h)[0]), + Ok(sg) => ops::sigmoid(self.mv(&sg, h)[0]), Err(_) => 1.0, }; - let o = self.ffn(il, &self.t(il, "ffn_gate_shexp.weight"), &self.t(il, "ffn_up_shexp.weight"), &self.t(il, "ffn_down_shexp.weight"), "ffn_down_shexp.weight", Some(0), h); - for (a, b) in y.iter_mut().zip(o) { *a += s * b; } - } + (s, self.ffn(il, &self.t(il, "ffn_gate_shexp.weight"), &self.t(il, "ffn_up_shexp.weight"), &self.t(il, "ffn_down_shexp.weight"), "ffn_down_shexp.weight", Some(0), h)) + }; + // The shared expert runs beside the routed ones (it is as small as one of them). + let (mut y, (s, o)) = rayon::join(|| self.routed_experts(il, h), shared); + for (a, b) in y.iter_mut().zip(o) { *a += s * b; } y } /// Router scores, top-k and normalized weights: (expert, weight) pairs. pub fn route(&self, il: usize, h: &[f32]) -> Vec<(usize, f32)> { + self.route_logits(self.mv(&self.t(il, "ffn_gate_inp.weight"), h)) + } + + /// `route` from the router's output `p`. + fn route_logits(&self, mut p: Vec) -> Vec<(usize, f32)> { let c = &self.cfg; - let mut p = mv(&self.t(il, "ffn_gate_inp.weight"), h); if c.router_sigmoid { for v in &mut p { *v = ops::sigmoid(*v); } } else { @@ -854,8 +1252,12 @@ impl<'a> Model<'a> { let (gate, up, down) = (self.t(il, "ffn_gate_exps.weight"), self.t(il, "ffn_up_exps.weight"), self.t(il, "ffn_down_exps.weight")); let n = self.cfg.n_expert; let mut y = vec![0f32; self.cfg.n_embd]; - for (e, w) in self.route(il, h) { - let o = self.ffn(il, &gate.expert(e, n), &up.expert(e, n), &down.expert(e, n), "ffn_down_exps.weight", Some(e), h); + let route = self.route(il, h); + let expert = |&(e, _): &(usize, f32)| self.ffn(il, &gate.expert(e, n), &up.expert(e, n), &down.expert(e, n), "ffn_down_exps.weight", Some(e), h); + // One expert's matvecs are too small to keep every core busy (512 rows on Qwen4), so the experts run side by + // side. Each output is the same either way and the sum keeps the route's order: same bits. + let outs: Vec> = route.par_iter().map(expert).collect(); + for ((_, w), o) in route.iter().zip(outs) { for (a, b) in y.iter_mut().zip(o) { *a += w * b; } } y @@ -914,11 +1316,17 @@ pub fn load_lora(path: &str, scale: f32) -> anyhow::Result { #[cfg(test)] mod tests { use super::*; + use crate::testutil::make_qwen3; fn w_str(b: &mut Vec, s: &str) { b.extend((s.len() as u64).to_le_bytes()); b.extend(s.as_bytes()); } fn tiny_adapter(tag: &str) -> std::path::PathBuf { - let (in_dim, rank, out_dim) = (4u64, 2u64, 3u64); + let a: Vec = (0..8).map(|i| i as f32).collect(); + let w: Vec = (0..6).map(|i| 10.0 + i as f32).collect(); + adapter_file(tag, "blk.0.ffn_down_exps.weight", 4, 2, 3, &a, &w) + } + + fn adapter_file(tag: &str, target: &str, in_dim: u64, rank: u64, out_dim: u64, a: &[f32], w: &[f32]) -> std::path::PathBuf { let (mut b, mut off) = (Vec::new(), 0u64); b.extend(b"GGUF"); b.extend(3u32.to_le_bytes()); @@ -927,8 +1335,8 @@ mod tests { w_str(&mut b, "adapter.lora.alpha"); b.extend(6u32.to_le_bytes()); b.extend(2.0f32.to_le_bytes()); - for (name, dims) in [("blk.0.ffn_down_exps.weight.lora_a", [in_dim, rank, 1]), ("blk.0.ffn_down_exps.weight.lora_b", [rank, out_dim, 1])] { - w_str(&mut b, name); + for (name, dims) in [(format!("{target}.lora_a"), [in_dim, rank, 1]), (format!("{target}.lora_b"), [rank, out_dim, 1])] { + w_str(&mut b, &name); b.extend(3u32.to_le_bytes()); for d in dims { b.extend(d.to_le_bytes()); } b.extend(0u32.to_le_bytes()); // F32 @@ -936,15 +1344,42 @@ mod tests { off += (dims[0] * dims[1] * dims[2] * 4).next_multiple_of(32); } while b.len() % 32 != 0 { b.push(0); } - let a: Vec = (0..8).map(|i| i as f32).collect(); - let w: Vec = (0..6).map(|i| 10.0 + i as f32).collect(); - b.extend(a.iter().flat_map(|f| f.to_le_bytes())); - b.extend(w.iter().flat_map(|f| f.to_le_bytes())); + for t in [a, w] { + b.extend(t.iter().flat_map(|f| f.to_le_bytes())); + while b.len() % 32 != 0 { b.push(0); } + } let p = std::env::temp_dir().join(format!("strata-lora-{}-{tag}.gguf", std::process::id())); std::fs::write(&p, &b).unwrap(); p } + /// A dense target is baked as W + m * B * A (needs `STRATA_MODEL`). + #[test] + fn dense_lora_is_baked() { + let Some(m) = std::env::var_os("STRATA_MODEL").filter(|m| Path::new(m).exists()) else { return }; + let g = Gguf::open(Path::new(&m)).unwrap(); + // The first block that has it: the default model's blk.0 is DeltaNet, which has ssm_out instead. + let name = &(0..g.tensors.len()).map(|i| format!("blk.{i}.attn_output.weight")).find(|n| g.tensors.contains_key(n)).unwrap(); + let (base, out_dim, in_dim) = { let m0 = Model::load(&g).unwrap(); let t = m0.w.get(name).unwrap(); (t.to_f32(), t.rows, t.cols) }; + let rank = 3; + let a: Vec = (0..rank * in_dim).map(|i| ((i * 7 % 13) as f32 - 6.0) * 1e-3).collect(); + let b: Vec = (0..out_dim * rank).map(|i| ((i * 5 % 11) as f32 - 5.0) * 1e-2).collect(); + let p = adapter_file("dense", name, in_dim as u64, rank as u64, out_dim as u64, &a, &b); + let lm = Model::load_with_lora(&g, &[(p.to_str().unwrap().to_string(), 0.5)]); + std::fs::remove_file(&p).ok(); + let lm = lm.unwrap(); + let got = lm.w.get(name).unwrap().to_f32(); + // alpha 2, scale 0.5, rank 3 + let mult = 0.5 * 2.0 / rank as f32; + for o in (0..out_dim).step_by(97) { + for i in (0..in_dim).step_by(31) { + let d: f32 = (0..rank).map(|r| b[o * rank + r] * a[r * in_dim + i]).sum(); + let want = base[o * in_dim + i] + mult * d; + assert!((got[o * in_dim + i] - want).abs() <= 1e-5 * want.abs().max(1.0), "{o},{i}: {} vs {want}", got[o * in_dim + i]); + } + } + } + #[test] fn load_lora_adapter() { let p = tiny_adapter("parse"); @@ -1301,6 +1736,134 @@ mod tests { } } + #[test] + fn load_llamacpp_dflash2_aux_gguf() { + let dir = std::env::temp_dir().join(format!("rusting_strata_llamacpp_dflash_{}", std::process::id())); + std::fs::remove_dir_all(&dir).ok(); + std::fs::create_dir_all(&dir).unwrap(); + + let w_str = |b: &mut Vec, s: &str| { + b.extend((s.len() as u64).to_le_bytes()); + b.extend(s.as_bytes()); + }; + let add_str = |b: &mut Vec, k: &str, v: &str| { + w_str(b, k); + b.extend(8u32.to_le_bytes()); // STRING + w_str(b, v); + }; + let add_u32 = |b: &mut Vec, k: &str, v: u32| { + w_str(b, k); + b.extend(4u32.to_le_bytes()); // UINT32 + b.extend(v.to_le_bytes()); + }; + let add_f32 = |b: &mut Vec, k: &str, v: f32| { + w_str(b, k); + b.extend(6u32.to_le_bytes()); // FLOAT32 + b.extend(v.to_le_bytes()); + }; + + let pack_gguf = |kvs: Vec, nkv: u64, tensors: &[(&str, &[u64])]| -> Vec { + let mut hdr = Vec::new(); + let mut body = Vec::new(); + for (name, dims) in tensors { + let nb = 4 * dims.iter().product::() as usize; + hdr.extend((name.len() as u64).to_le_bytes()); + hdr.extend(name.as_bytes()); + hdr.extend((dims.len() as u32).to_le_bytes()); + for d in *dims { hdr.extend(d.to_le_bytes()); } + hdr.extend(0u32.to_le_bytes()); // F32 + hdr.extend((body.len() as u64).to_le_bytes()); + body.resize(body.len() + nb, 0); + while body.len() % 32 != 0 { body.push(0); } + } + let mut out = Vec::new(); + out.extend(b"GGUF"); + out.extend(3u32.to_le_bytes()); + out.extend((tensors.len() as u64).to_le_bytes()); + out.extend(nkv.to_le_bytes()); + out.extend(kvs); + out.extend(hdr); + while out.len() % 32 != 0 { out.push(0); } + out.extend(body); + out + }; + + let mut tkvs = Vec::new(); + add_str(&mut tkvs, "general.architecture", "qwen3"); + add_u32(&mut tkvs, "qwen3.block_count", 2); + add_u32(&mut tkvs, "qwen3.embedding_length", 32); + add_u32(&mut tkvs, "qwen3.feed_forward_length", 32); + add_u32(&mut tkvs, "qwen3.attention.head_count", 2); + add_u32(&mut tkvs, "qwen3.attention.head_count_kv", 1); + add_u32(&mut tkvs, "qwen3.attention.key_length", 16); + add_f32(&mut tkvs, "qwen3.attention.layer_norm_rms_epsilon", 1e-6); + let pt = dir.join("target.gguf"); + std::fs::write(&pt, pack_gguf(tkvs, 8, &[ + ("token_embd.weight", &[32, 64]), + ("output_norm.weight", &[32]), + ("output.weight", &[32, 64]), + ])).unwrap(); + + let mut akvs = Vec::new(); + add_str(&mut akvs, "general.architecture", "dflash"); + add_u32(&mut akvs, "dflash.block_count", 1); + add_u32(&mut akvs, "dflash.block_size", 8); + add_u32(&mut akvs, "dflash.embedding_length", 32); + add_u32(&mut akvs, "dflash.feed_forward_length", 32); + add_u32(&mut akvs, "dflash.attention.head_count", 2); + add_u32(&mut akvs, "dflash.attention.head_count_kv", 1); + add_u32(&mut akvs, "dflash.attention.key_length", 16); + add_u32(&mut akvs, "dflash.attention.sliding_window", 2048); + add_u32(&mut akvs, "dflash.conv_kernel_size", 2); + add_u32(&mut akvs, "dflash.conv_group_size", 4); + add_u32(&mut akvs, "dflash.selector_rank", 8); + add_u32(&mut akvs, "dflash.selector_top_k", 4); + add_u32(&mut akvs, "tokenizer.ggml.mask_token_id", 42); + w_str(&mut akvs, "dflash.target_layers"); + akvs.extend(9u32.to_le_bytes()); // ARRAY + akvs.extend(4u32.to_le_bytes()); // UINT32 + akvs.extend(2u64.to_le_bytes()); + akvs.extend(1u32.to_le_bytes()); + akvs.extend(2u32.to_le_bytes()); + + let aux_gguf = dir.join("dflash2-llamacpp.gguf"); + std::fs::write(&aux_gguf, pack_gguf(akvs, 15, &[ + ("fc.weight", &[64, 32]), + ("enc.output_norm.weight", &[32]), + ("output_norm.weight", &[32]), + ("selector_hidden.weight", &[32, 8]), + ("selector_predecessor.weight", &[8, 64]), + ("selector_successor.weight", &[8, 64]), + ("blk.0.attn_conv_base", &[32, 2, 2]), + ("blk.0.attn_conv_proj.weight", &[32, 32]), + ("blk.0.ffn_conv_base", &[32, 2, 2]), + ("blk.0.ffn_conv_proj.weight", &[32, 32]), + ("blk.0.attn_norm.weight", &[32]), + ("blk.0.ffn_norm.weight", &[32]), + ("blk.0.attn_q_norm.weight", &[16]), + ("blk.0.attn_k_norm.weight", &[16]), + ("blk.0.attn_q.weight", &[32, 32]), + ("blk.0.attn_k.weight", &[32, 16]), + ("blk.0.attn_v.weight", &[32, 16]), + ("blk.0.attn_output.weight", &[32, 32]), + ("blk.0.ffn_gate.weight", &[32, 32]), + ("blk.0.ffn_up.weight", &[32, 32]), + ("blk.0.ffn_down.weight", &[32, 32]), + ])).unwrap(); + + let gt = Gguf::open(&pt).unwrap(); + let ga = Gguf::open(&aux_gguf).unwrap(); + let m = Model::load_with_aux(>, Some(&ga), &[]).unwrap(); + std::fs::remove_dir_all(&dir).ok(); + + assert!(m.cfg.eagle3.is_none()); + assert_eq!(m.cfg.n_nextn, 0); + let df = m.cfg.dflash.as_ref().expect("llamacpp dflash2 config loaded"); + assert_eq!(df.mask_token_id, 42); + assert_eq!(df.target_layer_ids, vec![0, 1]); + crate::gpu_model::dflash_check(&m, df).unwrap(); + } + #[test] fn sensenova_loop_mhc_cpu_matches_gpu() { let dir = std::env::temp_dir().join(format!("strata_snloop_test_{}", std::process::id())); @@ -1422,68 +1985,96 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + /// The fast CPU path adds a LoRA's delta at run time (`lora_add`), once per product in `mv` and in `mm`, as + /// the baked weights would: W x + mult B (A x). + #[test] + fn runtime_lora_adds_the_baked_delta() { + let path = std::env::temp_dir().join(format!("strata_runtime_lora_{}.gguf", std::process::id())); + make_qwen3(&path, 0); + let g = Gguf::open(&path).unwrap(); + let (a, b): (Vec, Vec) = ((0..128).map(|i| ((i * 7 % 13) as f32 - 6.0) * 0.05).collect(), (0..128).map(|i| ((i * 5 % 11) as f32 - 5.0) * 0.03).collect()); + let adapter = adapter_file("runtime_lora", "blk.0.ffn_down.weight", 64, 2, 64, &a, &b); + let spec = [(adapter.display().to_string(), 1.0)]; + let (rt, plain) = (Model::load_with_matvec(&g, None, &spec, true).unwrap(), Model::load_with_matvec(&g, None, &[], true).unwrap()); + assert!(rt.w.lora_baked.is_empty() && rt.lora_rt.len() == 1, "the fast path must not bake"); + let mut baked = Model::load_with_matvec(&g, None, &spec, false).unwrap(); + assert!(baked.lora_rt.is_empty() && !baked.w.lora_baked.is_empty()); + baked.fast_matvec = true; + let x: Vec = (0..64).map(|i| ((i * 37 % 101) as f32 - 50.0) * 0.01).collect(); + let (t, tp, tb) = (rt.t(0, "ffn_down.weight"), plain.t(0, "ffn_down.weight"), baked.t(0, "ffn_down.weight")); + let want: Vec = baked.mv(&tb, &x).iter().zip(plain.mv(&tp, &x)).map(|(b, p)| b - p).collect(); + let xs = vec![x.clone(), x.clone()]; + for got in [rt.mv(&t, &x), rt.mm(&t, &xs, &OnceCell::new()).remove(1)] { + let got: Vec = got.iter().zip(plain.mv(&tp, &x)).map(|(r, p)| r - p).collect(); + let d = got.iter().zip(&want).map(|(g, w)| (g - w).abs()).fold(0f32, f32::max); + assert!(want.iter().any(|w| w.abs() > 1e-3) && d < 1e-4, "delta off by {d}: {got:?} vs {want:?}"); + } + std::fs::remove_file(&path).ok(); + } + + #[test] + fn cpu_projection_modes() { + use crate::quant::GgmlType::{F16, F32, Q8_0}; + let path = std::env::temp_dir().join(format!("strata_cpu_projection_{}.gguf", std::process::id())); + make_qwen3(&path, 0); + let g = Gguf::open(&path).unwrap(); + let adapter = tiny_adapter("cpu_projection"); + let model = Model::load_with_matvec(&g, Some(&g), &[(adapter.display().to_string(), 1.0)], true).unwrap(); + assert!(model.fast_matvec && model.draft_model.as_ref().unwrap().fast_matvec); + assert_eq!(model.loras.len(), 1); + assert!(!Model::load(&g).unwrap().fast_matvec); + for (ty, cols) in [(F32, 256), (F16, 30), (Q8_0, 96), (Q8_0, 256), (Q8_0, 512), (Q8_0, 768)] { + let rows = 8; + let mut data = vec![0; rows * ty.row_bytes(cols as u64)]; + match ty { + Q8_0 => for (i, b) in data.chunks_exact_mut(34).enumerate() { + b[..2].copy_from_slice(&half::f16::from_f32(0.025).to_le_bytes()); + for (j, q) in b[2..].iter_mut().enumerate() { *q = ((i * 19 + j * 13) % 89) as u8; } + }, + F16 => for b in data.chunks_exact_mut(2) { b.copy_from_slice(&half::f16::ONE.to_le_bytes()); }, + F32 => for b in data.chunks_exact_mut(4) { b.copy_from_slice(&1f32.to_le_bytes()); }, + _ => unreachable!(), + } + let t = Tensor { ty, cols, rows, data: &data, scale: 0.75 }; + let x: Vec = (0..cols).map(|i| ((i * 31 % 193) as f32 - 90.0) / 97.0).collect(); + let cache = OnceCell::new(); + let got = model.mv_cached(&t, &x, &cache); + let mut reference = vec![0.0; rows]; + t.matvec(&x, &mut reference); + if ty == Q8_0 && cols % 256 == 0 { + assert!(cache.get().is_some()); + let up = Tensor { scale: 1.25, ..t }; + assert_eq!(model.mv_cached(&up, &x, &cache), model.mv(&up, &x)); + let peak = reference.iter().copied().map(f32::abs).fold(0.0, f32::max); + for (a, b) in got.iter().zip(&reference) { assert!((a - b).abs() < 0.01 * peak); } + } else { + assert!(cache.get().is_none()); + for (a, b) in got.iter().zip(&reference) { + assert!((a - b).abs() <= 1e-5 * b.abs().max(1.0), "{ty:?}: {a} vs {b}"); + } + let xs = vec![x.clone(), x.iter().rev().copied().collect()]; + let quantized = OnceCell::new(); + let batched = model.mm(&t, &xs, &quantized); + assert!(quantized.get().is_none()); + for (y, x) in batched.iter().zip(&xs) { + assert_eq!(*y, model.mv(&t, x)); + } + } + let (e, h) = x.split_at(cols / 2); + let streams = [h, e].concat(); + let expected = [model.mv(&t, &x), model.mv(&t, &[e, e].concat())].concat(); + assert_eq!(model.project_streams(&t, e, &streams), expected); + } + std::fs::remove_file(adapter).unwrap(); + std::fs::remove_file(path).unwrap(); + } + #[test] fn standalone_external_draft_model_spec_step_matches_greedy() { let dir = std::env::temp_dir().join(format!("strata_extdraft_test_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - let make_qwen3 = |path: &std::path::Path, seed_off: usize| { - let mut kvs = Vec::new(); - let w_s = |b: &mut Vec, s: &str| { b.extend((s.len() as u64).to_le_bytes()); b.extend(s.as_bytes()); }; - let w_kv = |b: &mut Vec, k: &str, t: u32, p: &[u8]| { w_s(b, k); b.extend(t.to_le_bytes()); b.extend(p); }; - let s = |b: &mut Vec, k: &str, v: &str| { let mut p = Vec::new(); w_s(&mut p, v); w_kv(b, k, 8, &p); }; - s(&mut kvs, "general.architecture", "qwen3"); - w_kv(&mut kvs, "qwen3.block_count", 4, &1u32.to_le_bytes()); - w_kv(&mut kvs, "qwen3.embedding_length", 4, &64u32.to_le_bytes()); - w_kv(&mut kvs, "qwen3.feed_forward_length", 4, &64u32.to_le_bytes()); - w_kv(&mut kvs, "qwen3.attention.head_count", 4, &1u32.to_le_bytes()); - w_kv(&mut kvs, "qwen3.attention.head_count_kv", 4, &1u32.to_le_bytes()); - w_kv(&mut kvs, "qwen3.attention.key_length", 4, &64u32.to_le_bytes()); - w_kv(&mut kvs, "qwen3.attention.layer_norm_rms_epsilon", 6, &1e-6f32.to_le_bytes()); - - let mut hdr = Vec::new(); - let mut body = Vec::new(); - let mut seed = 1 + seed_off; - let mut add_t = |name: &str, dims: &[u64], scale: f32| { - w_s(&mut hdr, name); - hdr.extend((dims.len() as u32).to_le_bytes()); - for &d in dims { hdr.extend(d.to_le_bytes()); } - hdr.extend(0u32.to_le_bytes()); - hdr.extend((body.len() as u64).to_le_bytes()); - let n: usize = dims.iter().product::() as usize; - for i in 0..n { - let v = if scale == 0.0 { 1.0f32 } else { (((seed * 29 + i * 13 + 3) % 89) as f32 - 44.0) * scale }; - body.extend_from_slice(&v.to_le_bytes()); - } - seed += 1; - while body.len() % 32 != 0 { body.push(0); } - }; - add_t("token_embd.weight", &[64, 8], 0.02); - add_t("output_norm.weight", &[64], 0.0); - add_t("output.weight", &[64, 8], 0.02); - add_t("blk.0.attn_norm.weight", &[64], 0.0); - add_t("blk.0.ffn_norm.weight", &[64], 0.0); - add_t("blk.0.attn_q_norm.weight", &[64], 0.0); - add_t("blk.0.attn_k_norm.weight", &[64], 0.0); - add_t("blk.0.attn_q.weight", &[64, 64], 0.01); - add_t("blk.0.attn_k.weight", &[64, 64], 0.01); - add_t("blk.0.attn_v.weight", &[64, 64], 0.01); - add_t("blk.0.attn_output.weight", &[64, 64], 0.01); - add_t("blk.0.ffn_gate.weight", &[64, 64], 0.01); - add_t("blk.0.ffn_up.weight", &[64, 64], 0.01); - add_t("blk.0.ffn_down.weight", &[64, 64], 0.01); - let mut gg = Vec::new(); - gg.extend(b"GGUF"); - gg.extend(3u32.to_le_bytes()); - gg.extend(14u64.to_le_bytes()); - gg.extend(8u64.to_le_bytes()); - gg.extend(kvs); - gg.extend(hdr); - while gg.len() % 32 != 0 { gg.push(0); } - gg.extend(body); - std::fs::write(path, &gg).unwrap(); - }; let pt = dir.join("target.gguf"); let pd = dir.join("draft.gguf"); make_qwen3(&pt, 0); @@ -1525,8 +2116,9 @@ mod tests { assert_eq!(base_toks, spec_toks); // Now test when external draft model has different weights (forces rejections and state rollbacks). - make_qwen3(&pd, 42); - let gd2 = Gguf::open(&pd).unwrap(); + let rejection_draft = dir.join("draft-rejection.gguf"); + make_qwen3(&rejection_draft, 42); + let gd2 = Gguf::open(&rejection_draft).unwrap(); let m2 = Model::load_with_aux(>, Some(&gd2), &[]).unwrap(); if let Ok(bk3) = crate::backend::open(None, 0) { let mut gm_diff = crate::gpu_model::GpuModel::load(&m2, bk3, 64, 0, 0, 3).unwrap(); diff --git a/src/ops.rs b/src/ops.rs index 817ab42e..d50af38b 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -114,25 +114,28 @@ pub fn argmax(x: &[f32]) -> usize { const NON_FINITE: &str = "the forward pass produced NaN or infinite logits"; /// Token choice after the logits: greedy when `temp` is 0, else softmax(logits / temp) cut to the `top_k` most likely -/// tokens (0 = no cut) and then to the smallest set whose probability reaches `top_p`. +/// tokens (0 = no cut), then to the smallest set whose probability reaches `top_p`, then to the tokens whose +/// probability before the temperature is at least `min_p` times the best one's (llama.cpp's order and min-p). #[derive(Clone, Debug)] pub struct Sampler { pub temp: f32, pub top_k: usize, pub top_p: f32, + /// 0 is off. + pub min_p: f32, /// xorshift64 state; must not be 0. pub rng: u64, - /// OpenAI `presence_penalty`: subtracted once from the logit of every token this sampler already returned. + /// OpenAI `presence_penalty`: subtracted once from the logit of every token among the last `last_n` returned ones. pub presence: f32, - /// OpenAI `frequency_penalty`: subtracted from a returned token's logit once per time it was returned. + /// OpenAI `frequency_penalty`: subtracted from a token's logit once per time it is among the last `last_n` returned. pub frequency: f32, /// llama.cpp `repeat_penalty`: the logit of a token among the last `last_n` returned ones is divided by it when /// positive, multiplied when not. 1 is off. pub repeat: f32, - /// llama.cpp `penalty_last_n`, for `repeat` only: 0 turns it off, a negative value takes the whole reply. + /// llama.cpp `penalty_last_n`, the window of `repeat`, `presence` and `frequency` (as llama.cpp): 0 turns them + /// off, a negative value takes the whole reply. Counted over the whole reply, a frequency penalty of 0.2 took + /// 10 logits from a comma used 50 times: a long reply lost its common tokens and broke apart (#175). pub last_n: i32, - /// How often each token was returned, for the penalties (only the reply, not the prompt). - pub seen: std::collections::HashMap, /// DRY ("don't repeat yourself") multiplier; 0 is off. A token that would extend a sequence of `n >= /// dry_allowed` tokens that already appeared in the reply loses `dry_mult * dry_base^(n - dry_allowed)` of logit. pub dry_mult: f32, @@ -146,6 +149,8 @@ pub struct Sampler { /// The returned tokens in order (outside tool calls), for DRY. pub hist: Vec, pub in_tool: bool, + /// The request's `logit_bias` and grammar, applied after the penalties. + pub limit: Option, } /// DRY looks back this many reply tokens, and matches at most this long. @@ -154,30 +159,27 @@ const DRY_MAX_MATCH: usize = 64; impl Sampler { pub fn greedy() -> Self { - Sampler { temp: 0.0, top_k: 0, top_p: 1.0, rng: 1, presence: 0.0, frequency: 0.0, repeat: 1.0, last_n: 64, - seen: Default::default(), + Sampler { temp: 0.0, top_k: 0, top_p: 1.0, min_p: 0.0, rng: 1, presence: 0.0, frequency: 0.0, repeat: 1.0, last_n: 64, dry_mult: 0.0, dry_base: 1.75, dry_allowed: 2, dry_breakers: Default::default(), tool_tags: None, - hist: Vec::new(), in_tool: false } + hist: Vec::new(), in_tool: false, limit: None } } /// The logits with the repeat, presence, frequency and DRY penalties applied, or None when there is nothing to change. /// Without them a quantized model that samples greedily (or nearly) falls into loops it never leaves. fn penalized(&self, logits: &[f32]) -> Option> { if self.in_tool { return None; } - let rep = !self.seen.is_empty() && (self.presence != 0.0 || self.frequency != 0.0); let dry = self.dry_penalties(); - let n = if self.repeat == 1.0 { 0 } else { usize::try_from(self.last_n).unwrap_or(usize::MAX) }; - let mut last = self.hist[self.hist.len().saturating_sub(n)..].to_vec(); - if !rep && dry.is_empty() && last.is_empty() { return None; } + let n = usize::try_from(self.last_n).unwrap_or(usize::MAX); + let rep = self.repeat != 1.0; + let pf = self.presence != 0.0 || self.frequency != 0.0; + let mut last = if rep || pf { self.hist[self.hist.len().saturating_sub(n)..].to_vec() } else { vec![] }; + if dry.is_empty() && last.is_empty() { return None; } let mut l = logits.to_vec(); - (last.sort_unstable(), last.dedup()); - for t in last { - if let Some(x) = l.get_mut(t) { *x = if *x > 0.0 { *x / self.repeat } else { *x * self.repeat }; } - } - if rep { - for (&t, &n) in &self.seen { - if let Some(x) = l.get_mut(t) { *x -= self.presence + self.frequency * n as f32; } - } + last.sort_unstable(); + for c in last.chunk_by(|a, b| a == b) { + let Some(x) = l.get_mut(c[0]) else { continue }; + if rep { *x = if *x > 0.0 { *x / self.repeat } else { *x * self.repeat }; } + if pf { *x -= self.presence + self.frequency * c.len() as f32; } } for (t, p) in dry { if let Some(x) = l.get_mut(t) { *x -= p; } @@ -185,6 +187,13 @@ impl Sampler { Some(l) } + /// `penalized`, then the bias and grammar of `limit`. + fn adjusted(&self, logits: &[f32]) -> Option> { + let mut l = self.penalized(logits); + if let Some(c) = &self.limit { c.apply(l.get_or_insert_with(|| logits.to_vec()), self.temp <= 0.0); } + l + } + /// DRY penalties for the next token: for every earlier place where the reply's last tokens already appeared, /// the token that followed them there, with the longest such match (as llama.cpp's DRY sampler). pub fn dry_penalties(&self) -> Vec<(usize, f32)> { @@ -208,24 +217,37 @@ impl Sampler { /// Records a token the reply now has (done by `pick` and `accept` for the tokens they return). pub fn note(&mut self, t: usize) { + if let Some(c) = &mut self.limit { c.accept(t as u32); } if let Some((open, close)) = self.tool_tags { if t == open { self.in_tool = true; return; } if t == close { self.in_tool = false; return; } } if self.in_tool { return; } - *self.seen.entry(t).or_insert(0) += 1; self.hist.push(t); } pub fn pick(&mut self, logits: &[f32]) -> anyhow::Result { - let pen = self.penalized(logits); - let logits = pen.as_deref().unwrap_or(logits); let i = if self.temp <= 0.0 { + let pen = self.adjusted(logits); + let logits = pen.as_deref().unwrap_or(logits); let i = argmax(logits); anyhow::ensure!(logits[i].is_finite(), NON_FINITE); i + } else if let Some(c) = self.limit.take() { + // As llama.cpp: draw without the grammar, and mask the whole vocabulary and draw again only when the + // grammar refuses that token. The mask walks every token, so doing it each step costs ~100 ms (#162). + let mut l = self.penalized(logits).unwrap_or_else(|| logits.to_vec()); + c.add_bias(&mut l); + let mut i = self.draw(&self.cands(&l)); + if !matches!(i, Ok(t) if c.allows(t as u32)) { + c.mask(&mut l); + i = self.draw(&self.cands(&l)); + } + self.limit = Some(c); + i? } else { - let c = self.cands(logits); + let pen = self.penalized(logits); + let c = self.cands(pen.as_deref().unwrap_or(logits)); self.draw(&c)? }; self.note(i); @@ -235,7 +257,7 @@ impl Sampler { /// Speculative sampling with a fixed draft `d`: keeps `d` (None) with its probability under this sampler, else /// returns a token drawn from the others, renormalized. The result has the distribution of `pick`. `temp` > 0. pub fn accept(&mut self, logits: &[f32], d: usize) -> anyhow::Result> { - let pen = self.penalized(logits); + let pen = self.adjusted(logits); let c = self.cands(pen.as_deref().unwrap_or(logits)); anyhow::ensure!(!c.is_empty(), NON_FINITE); let q = c.iter().find(|x| x.0 == d).map_or(0.0, |x| x.1); @@ -258,7 +280,7 @@ impl Sampler { /// Leviathan lossless speculative rejection sampling using draft distribution `q` and target `logits` (`temp > 0`). /// Keeps `d` (`None`) with probability `min(1, p(d)/q(d))`, otherwise samples from normalized `max(0, p - q)`. pub fn accept_dist(&mut self, logits: &[f32], d: usize, q: &[(usize, f32)]) -> anyhow::Result> { - let pen = self.penalized(logits); + let pen = self.adjusted(logits); let c = self.cands(pen.as_deref().unwrap_or(logits)); let total: f32 = c.iter().map(|x| x.1).sum(); anyhow::ensure!(!c.is_empty() && total > 0.0, NON_FINITE); @@ -298,6 +320,12 @@ impl Sampler { if acc >= self.top_p * total { n = j + 1; break; } } c.truncate(n); + // llama.cpp cuts at logit >= max + ln(min_p), before the temperature; a weight here is that difference + // divided by `temp`, exponentiated. The best token (weight 1) always stays. + if self.min_p > 0.0 { + let w = self.min_p.powf(1.0 / self.temp); + c.retain(|x| x.1 >= w); + } c } @@ -326,6 +354,23 @@ impl Sampler { mod tests { use super::*; + #[test] + fn min_p_drops_the_unlikely_tokens() { + let l = [4.0f32.ln(), 2.0f32.ln(), 1.0f32.ln(), 0.5f32.ln()]; // probabilities relative to the best: 1, 1/2, 1/4, 1/8 + let kept = |temp: f32, min_p: f32| Sampler { temp, min_p, ..Sampler::greedy() }.cands(&l).iter().map(|x| x.0).collect::>(); + assert_eq!(kept(1.0, 0.0), [0, 1, 2, 3]); + assert_eq!(kept(1.0, 0.3), [0, 1]); + assert_eq!(kept(1.0, 0.2), [0, 1, 2]); + // As llama.cpp: the cut is on the probabilities before the temperature. + assert_eq!(kept(2.0, 0.3), [0, 1]); + assert_eq!(kept(0.5, 0.2), [0, 1, 2]); + assert_eq!(kept(1.0, 1.0), [0]); + // After top_k. + assert_eq!(Sampler { temp: 1.0, top_k: 1, min_p: 0.01, ..Sampler::greedy() }.cands(&l).len(), 1); + let mut s = Sampler { temp: 1.0, min_p: 0.3, rng: 7, ..Sampler::greedy() }; + assert!((0..200).all(|_| s.pick(&l).unwrap() < 2)); + } + #[test] fn mrope_matches_neox_for_text_positions() { let (n_rot, base, sections) = (64, 1e7f32, [11, 11, 10, 0]); diff --git a/src/quant/mod.rs b/src/quant/mod.rs index c3ea1b49..45f789a4 100644 --- a/src/quant/mod.rs +++ b/src/quant/mod.rs @@ -8,47 +8,47 @@ use half::{bf16, f16}; use tables::*; #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum GgmlType { F32, F16, BF16, F8E4M3, Q2_0, TQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, NVFP4 } +pub enum GgmlType { F32, F16, BF16, F8E4M3, Q1_0, Q2_0, PQ2_0, TQ1_0, TQ2_0, PTQ1_0, PTQ1R, TQ2T, TQK6, TQK7, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q8_1, Q8K, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, MXFP4, NVFP4 } use GgmlType::*; impl GgmlType { pub fn from_u32(id: u32) -> anyhow::Result { Ok(match id { - 0 => F32, 1 => F16, 30 => BF16, 43 => F8E4M3, 42 => Q2_0, 34 => TQ1_0, 35 => TQ2_0, 144 => TQ2T, 145 => TQK6, 146 => TQK7, 2 => Q4_0, 3 => Q4_1, 6 => Q5_0, 7 => Q5_1, 8 => Q8_0, 10 => Q2K, 11 => Q3K, 12 => Q4K, 13 => Q5K, 14 => Q6K, - 16 => IQ2XXS, 17 => IQ2XS, 19 => IQ1S, 29 => IQ1M, 18 => IQ3XXS, 21 => IQ3S, 22 => IQ2S, 23 => IQ4XS, 20 => IQ4NL, 40 => NVFP4, + 0 => F32, 1 => F16, 30 => BF16, 43 => F8E4M3, 41 => Q1_0, 42 => Q2_0, 142 => PQ2_0, 34 => TQ1_0, 35 => TQ2_0, 143 => PTQ1_0, 144 => TQ2T, 145 => TQK6, 146 => TQK7, 2 => Q4_0, 3 => Q4_1, 6 => Q5_0, 7 => Q5_1, 8 => Q8_0, 9 => Q8_1, 10 => Q2K, 11 => Q3K, 12 => Q4K, 13 => Q5K, 14 => Q6K, 15 => Q8K, + 16 => IQ2XXS, 17 => IQ2XS, 19 => IQ1S, 29 => IQ1M, 18 => IQ3XXS, 21 => IQ3S, 22 => IQ2S, 23 => IQ4XS, 20 => IQ4NL, 39 => MXFP4, 40 => NVFP4, _ => { const NAMES: [&str; 44] = ["F32", "F16", "Q4_0", "Q4_1", "", "", "Q5_0", "Q5_1", "Q8_0", "Q8_1", "Q2_K", "Q3_K", "Q4_K", "Q5_K", "Q6_K", "Q8_K", "IQ2_XXS", "IQ2_XS", "IQ3_XXS", "IQ1_S", "IQ4_NL", "IQ3_S", "IQ2_S", "IQ4_XS", "I8", "I16", "I32", "I64", "F64", "IQ1_M", "BF16", "", "", "", "TQ1_0", "TQ2_0", "", "", "", "MXFP4", "NVFP4", "Q1_0", "Q2_0", "F8_E4M3"]; // agentionai's llama.cpp fork: the Gyro-L file holds the pair trellis types, which are not ported. - const GYRO: [(u32, &str); 4] = [(143, "PTQ1_0"), (147, "TQP5"), (148, "TQP6"), (149, "TQP7")]; + const GYRO: [(u32, &str); 3] = [(147, "TQP5"), (148, "TQP6"), (149, "TQP7")]; if let Some((_, name)) = GYRO.iter().find(|g| g.0 == id) { anyhow::bail!("unsupported quant type {name} (ggml type id {id}): of the trellis types of agentionai's llama.cpp fork only TQ2_T, TQK6 and TQK7 (the Gyro-S and Gyro-M files) are supported, not the pair trellis of Gyro-L"); } let name = NAMES.get(id as usize).filter(|n| !n.is_empty()).unwrap_or(&"unknown"); - anyhow::bail!("unsupported quant type {name} (ggml type id {id}); supported: F32 F16 BF16 F8_E4M3 Q2_0 TQ1_0 TQ2_0 TQ2_T TQK6 TQK7 Q4_0 Q4_1 Q5_0 Q5_1 Q8_0 Q2_K-Q6_K IQ1_S IQ1_M IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_NL IQ4_XS NVFP4") + anyhow::bail!("unsupported quant type {name} (ggml type id {id}); supported: F32 F16 BF16 F8_E4M3 Q1_0 Q2_0 PQ2_0 TQ1_0 TQ2_0 PTQ1_0 TQ2_T TQK6 TQK7 Q4_0 Q4_1 Q5_0 Q5_1 Q8_0 Q8_1 Q8_K Q2_K-Q6_K IQ1_S IQ1_M IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_NL IQ4_XS MXFP4 NVFP4") } }) } /// A GPU matvec of this type reads its input as floats, not as int8: the float types (F16 is uploaded as F32) /// and the trellis types, whose codebook is not on an int8 grid (as int8 its values are 0.8% off). pub fn float_x(self) -> bool { matches!(self, F32 | BF16 | F8E4M3 | TQ2T | TQK6 | TQK7) } - pub fn block_elems(self) -> usize { match self { F32 | F16 | BF16 | F8E4M3 => 1, Q4_0 | Q4_1 | Q5_0 | Q5_1 | Q8_0 | IQ4NL => 32, Q2_0 | NVFP4 => 64, TQ2T | TQK6 | TQK7 => 128, _ => 256 } } - pub fn block_bytes(self) -> usize { + pub const fn block_elems(self) -> usize { match self { F32 | F16 | BF16 | F8E4M3 => 1, Q4_0 | Q4_1 | Q5_0 | Q5_1 | Q8_0 | Q8_1 | IQ4NL | MXFP4 => 32, Q2_0 | NVFP4 => 64, Q1_0 | PQ2_0 | PTQ1_0 | PTQ1R | TQ2T | TQK6 | TQK7 => 128, _ => 256 } } + pub const fn block_bytes(self) -> usize { match self { - F32 => 4, F16 => 2, BF16 => 2, F8E4M3 => 1, Q2_0 => 18, TQ1_0 => 54, TQ2_0 => 66, TQ2T => 34, TQK6 => 26, TQK7 => 30, Q4_0 => 18, Q4_1 => 20, Q5_0 => 22, Q5_1 => 24, Q8_0 => 34, Q2K => 84, Q3K => 110, Q4K => 144, Q5K => 176, Q6K => 210, - IQ1S => 50, IQ1M => 56, IQ2XXS => 66, IQ2XS => 74, IQ2S => 82, IQ3XXS => 98, IQ3S => 110, IQ4XS => 136, IQ4NL => 18, NVFP4 => 36, + F32 => 4, F16 => 2, BF16 => 2, F8E4M3 => 1, Q1_0 | Q2_0 => 18, PQ2_0 => 34, TQ1_0 => 54, TQ2_0 => 66, PTQ1_0 => 28, PTQ1R => 34, TQ2T => 34, TQK6 => 26, TQK7 => 30, Q4_0 => 18, Q4_1 => 20, Q5_0 => 22, Q5_1 => 24, Q8_0 => 34, Q8_1 => 36, Q8K => 292, Q2K => 84, Q3K => 110, Q4K => 144, Q5K => 176, Q6K => 210, + IQ1S => 50, IQ1M => 56, IQ2XXS => 66, IQ2XS => 74, IQ2S => 82, IQ3XXS => 98, IQ3S => 110, IQ4XS => 136, IQ4NL => 18, MXFP4 => 17, NVFP4 => 36, } } /// Backend `backend` ("cuda" or "vulkan") has kernels for this type. F16 has none: `Backend::upload` converts it to /// F32, which holds its values exactly. - pub fn gpu(self, _backend: &str) -> bool { self != F16 } + pub fn gpu(self, _backend: &str) -> bool { !matches!(self, F16 | Q1_0 | PQ2_0 | PTQ1R | Q8_1 | Q8K | MXFP4) } pub fn row_bytes(self, n: u64) -> usize { n as usize / self.block_elems() * self.block_bytes() } pub fn name(self) -> &'static str { match self { - F32 => "F32", F16 => "F16", BF16 => "BF16", F8E4M3 => "F8_E4M3", Q2_0 => "Q2_0", TQ1_0 => "TQ1_0", TQ2_0 => "TQ2_0", TQ2T => "TQ2_T", TQK6 => "TQK6", TQK7 => "TQK7", Q4_0 => "Q4_0", Q4_1 => "Q4_1", Q5_0 => "Q5_0", Q5_1 => "Q5_1", Q8_0 => "Q8_0", Q2K => "Q2_K", Q3K => "Q3_K", Q4K => "Q4_K", - Q5K => "Q5_K", Q6K => "Q6_K", IQ1S => "IQ1_S", IQ1M => "IQ1_M", IQ2XXS => "IQ2_XXS", IQ2XS => "IQ2_XS", IQ2S => "IQ2_S", IQ3XXS => "IQ3_XXS", IQ3S => "IQ3_S", IQ4XS => "IQ4_XS", IQ4NL => "IQ4_NL", NVFP4 => "NVFP4", + F32 => "F32", F16 => "F16", BF16 => "BF16", F8E4M3 => "F8_E4M3", Q1_0 => "Q1_0", PQ2_0 => "PQ2_0", Q2_0 => "Q2_0", TQ1_0 => "TQ1_0", TQ2_0 => "TQ2_0", PTQ1_0 => "PTQ1_0", PTQ1R => "PTQ1_0R", TQ2T => "TQ2_T", TQK6 => "TQK6", TQK7 => "TQK7", Q4_0 => "Q4_0", Q4_1 => "Q4_1", Q5_0 => "Q5_0", Q5_1 => "Q5_1", Q8_0 => "Q8_0", Q8_1 => "Q8_1", Q8K => "Q8_K", Q2K => "Q2_K", Q3K => "Q3_K", Q4K => "Q4_K", + Q5K => "Q5_K", Q6K => "Q6_K", IQ1S => "IQ1_S", IQ1M => "IQ1_M", IQ2XXS => "IQ2_XXS", IQ2XS => "IQ2_XS", IQ2S => "IQ2_S", IQ3XXS => "IQ3_XXS", IQ3S => "IQ3_S", IQ4XS => "IQ4_XS", IQ4NL => "IQ4_NL", MXFP4 => "MXFP4", NVFP4 => "NVFP4", } } } @@ -90,26 +90,34 @@ pub(crate) fn scale_min_k4(j: usize, q: &[u8]) -> (u8, u8) { pub fn dequant_row(ty: GgmlType, src: &[u8], dst: &mut [f32]) { let (be, bb) = (ty.block_elems(), ty.block_bytes()); debug_assert_eq!(src.len(), ty.row_bytes(dst.len() as u64)); + // F32 rows (the small Qwen3.5 projections and norms, read on every token) without a match per value. + if ty == F32 { + for (y, b) in dst.iter_mut().zip(src.chunks_exact(4)) { *y = f32::from_le_bytes(b.try_into().unwrap()); } + return; + } + // BF16 likewise (Qwen4's PLE key and value, the QSA indexer): keep the conversion in a vectorizable row loop. + if ty == BF16 { + for (y, b) in dst.iter_mut().zip(src.chunks_exact(2)) { *y = bf16::from_le_bytes([b[0], b[1]]).to_f32(); } + return; + } for (blk, y) in src.chunks_exact(bb).zip(dst.chunks_exact_mut(be)) { match ty { - F32 => y[0] = f32::from_le_bytes(blk.try_into().unwrap()), + F32 | BF16 => unreachable!("decoded above"), F16 => y[0] = h(blk, 0), - BF16 => y[0] = bf16::from_le_bytes([blk[0], blk[1]]).to_f32(), F8E4M3 => y[0] = f8_e4m3_to_f32(blk[0]), - // Q2_0 (Strata/ggml type 42): f16 d, then 2-bit codes, value = (code - 1) * d. - Q2_0 => { let d = h(blk, 0); for j in 0..64 { y[j] = (((blk[2 + j / 4] >> (2 * (j % 4))) & 3) as f32 - 1.0) * d; } } - TQ1_0 => tq1_0(blk, y), TQ2_0 => tq2_0(blk, y), + Q1_0 => unpack_q1_0(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + PQ2_0 => unpack_q2_0(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + Q2_0 => unpack_q2_0(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + TQ1_0 => tq1_0(blk, y), TQ2_0 => tq2_0(blk, y), PTQ1_0 => ptq1_0(blk, y), PTQ1R => ptq1r(blk, y), TQ2T | TQK6 | TQK7 => tq(blk, y), - Q4_0 | Q5_0 => { let (d, q) = (h(blk, 0), q5_codes(ty, blk)); for j in 0..32 { y[j] = q[j] as f32 * d; } } - // Q4_1 / Q5_1: f16 d, f16 m, (Q5_1: u32 high bits,) nibbles as in Q4_0; value = d * code + m. - Q4_1 | Q5_1 => { - let (d, m, qh, qs) = if ty == Q5_1 { (h(blk, 0), h(blk, 2), u32::from_le_bytes(blk[4..8].try_into().unwrap()), &blk[8..24]) } else { (h(blk, 0), h(blk, 2), 0, &blk[4..20]) }; - for j in 0..16 { - y[j] = d * ((qs[j] & 0xF) as u32 | ((qh >> j) & 1) << 4) as f32 + m; - y[j + 16] = d * ((qs[j] >> 4) as u32 | ((qh >> (j + 16)) & 1) << 4) as f32 + m; - } - } - Q8_0 => { let d = h(blk, 0); for j in 0..32 { y[j] = blk[2 + j] as i8 as f32 * d; } } + Q4_0 => unpack_q4_0(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + Q4_1 => unpack_q4_1(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + Q5_0 => unpack_q5_0(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + Q5_1 => unpack_q5_1(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + Q8_0 => unpack_q8_0(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + Q8_1 => unpack_q8_1(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + Q8K => unpack_q8k(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), + MXFP4 => unpack_mxfp4(blk, |i, q, d, m| y[i] = affine_value(q, d, m)), Q2K => q2k(blk, y), Q3K => q3k(blk, y), Q4K => q4k(blk, y), Q5K => q5k(blk, y), Q6K => q6k(blk, y), IQ1S => iq1s(blk, y), IQ1M => iq1m(blk, y), IQ2XXS => iq2xxs(blk, y), IQ2XS => iq2xs(blk, y), IQ2S => iq2s(blk, y), IQ3XXS => iq3xxs(blk, y), IQ3S => iq3s(blk, y), IQ4XS => iq4xs(blk, y), IQ4NL => iq4nl(blk, y), NVFP4 => nvfp4(blk, y), } @@ -128,20 +136,94 @@ fn tq1_trit(v: u8, n: usize) -> f32 { /// bytes (trit n of byte m is element 32 n + m), 160..240 from the next 16 (element 160 + 16 n + m), 240..256 from qh /// (element 240 + 4 n + j). fn tq1_0(b: &[u8], y: &mut [f32]) { + unpack_tq1_0(b, |i, q, d, m| y[i] = affine_value(q, d, m)); +} + +pub(crate) fn unpack_tq1_0(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 52); + let mut i = 0; + for (base, width, count) in [(0, 32, 5), (32, 16, 5), (48, 4, 4)] { + for trit in 0..count { + for j in 0..width { + emit(i, tq1_trit(b[base + j], trit) as i16, d, 0.0); + i += 1; + } + } + } +} + +/// PTQ1_0 of PrismML's llama.cpp fork (Ternary Bonsai; 28 bytes a block of 128): 24 bytes of five trits, 2 bytes of +/// four, then f16 d. Values 0..80 come from bytes 0..16 (trit n of byte m is element 16 n + m), 80..120 from bytes +/// 16..24 (element 80 + 8 n + m), 120..128 from qh (element 120 + 2 n + j). +fn ptq1_0(b: &[u8], y: &mut [f32]) { + // The direct loop, not `unpack_ptq1_0`: going through the code array made the reference decode 23% slower. + let d = h(b, 26); let mut o = 0; - for n in 0..5 { for m in 0..32 { y[o] = d * tq1_trit(b[m], n); o += 1; } } - for n in 0..5 { for m in 0..16 { y[o] = d * tq1_trit(b[32 + m], n); o += 1; } } - for n in 0..4 { for j in 0..4 { y[o] = d * tq1_trit(b[48 + j], n); o += 1; } } + for n in 0..5 { for m in 0..16 { y[o] = d * tq1_trit(b[m], n); o += 1; } } + for n in 0..5 { for m in 0..8 { y[o] = d * tq1_trit(b[16 + m], n); o += 1; } } + for n in 0..4 { for j in 0..2 { y[o] = d * tq1_trit(b[24 + j], n); o += 1; } } +} + +/// Integer codes and affine coefficients used by both the reference decoder and CPU dot. +pub(crate) fn unpack_ptq1_0(b: &[u8], codes: &mut [u8; 128]) -> (f32, f32) { + for (start, width, count, offset) in [(0, 16, 5, 0), (16, 8, 5, 80), (24, 2, 4, 120)] { + for j in 0..width { + let mut packed = b[start + j]; + for trit in 0..count { + codes[offset + trit * width + j] = ((3 * packed as u16) >> 8) as u8; + packed = packed.wrapping_mul(3); + } + } + } + let scale = h(b, 26); + (scale, -scale) +} + +/// PTQ1_0R: PTQ1_0 repacked in memory for the CPU kernels (never in a file; 34 bytes a block of 128). Element +/// 32 l + m is bits 2 l of byte m, a code 0..3 for value (code - 1) d, then the same f16 d. A 2-bit code costs a shift +/// and a mask to unpack instead of PTQ1_0's base-3 arithmetic, for 6 more bytes a block. +fn ptq1r(b: &[u8], y: &mut [f32]) { + let mut codes = [0; 128]; + let (scale, _) = unpack_ptq1r(b, &mut codes); + for (v, code) in y.iter_mut().zip(codes) { *v = scale * (code as f32 - 1.0); } +} + +pub(crate) fn unpack_ptq1r(b: &[u8], codes: &mut [u8; 128]) -> (f32, f32) { + for (i, c) in codes.iter_mut().enumerate() { *c = (b[i % 32] >> (2 * (i / 32))) & 3; } + let scale = h(b, 32); + (scale, -scale) +} + +/// PTQ1_0 bytes (whole blocks) as PTQ1_0R, block for block: the same codes and scale bits, so the same values. +pub fn repack_ptq1_0(src: &[u8], dst: &mut [u8]) { + for (s, d) in src.chunks_exact(28).zip(dst.chunks_exact_mut(34)) { + let mut codes = [0; 128]; + unpack_ptq1_0(s, &mut codes); + for m in 0..32 { d[m] = codes[m] | codes[32 + m] << 2 | codes[64 + m] << 4 | codes[96 + m] << 6; } + d[32..34].copy_from_slice(&s[26..28]); + } } /// TQ2_0 (66 bytes): 64 bytes of 2-bit codes, then f16 d. Element 128 j + 32 l + m is codes byte 32 j + m bits 2 l, /// value (code - 1) d. fn tq2_0(b: &[u8], y: &mut [f32]) { - let d = h(b, 64); - for j in 0..2 { for l in 0..4 { for m in 0..32 { - y[32 * (4 * j + l) + m] = d * (((b[32 * j + m] >> (2 * l)) & 3) as f32 - 1.0); - } } } + let mut codes = [0; 256]; + let (scale, _) = unpack_tq2_0(b, &mut codes); + for (v, code) in y.iter_mut().zip(codes) { *v = scale * (code as f32 - 1.0); } +} + +pub(crate) fn unpack_tq2_0(b: &[u8], codes: &mut [u8; 256]) -> (f32, f32) { + for j in 0..2 { + let packed = &b[32 * j..32 * (j + 1)]; + for l in 0..4 { + let offset = 128 * j + 32 * l; + for (dst, &src) in codes[offset..offset + 32].iter_mut().zip(packed) { + *dst = (src >> (2 * l)) & 3; + } + } + } + let scale = h(b, 64); + (scale, -scale) } /// The 2048 codebook points of the trellis types (TQ2_T, TQK6, TQK7 of agentionai's llama.cpp fork), two values each. @@ -157,7 +239,11 @@ pub static TQ_LUT: [[f32; 2]; 2048] = { /// from bit `(31 - t) K` on, least significant first, circular over the 32 K bits. The points are two 11-bit fields /// of the state times 0x9e3779b1. #[inline] -pub fn tq_points(qs: &[u8], t: usize) -> (usize, usize) { +pub fn tq_points(qs: &[u8], t: usize) -> (usize, usize) { state_points(tq_state(qs, t)) } + +/// The 15-bit state of trellis step `t` (see `tq_points`). +#[inline] +pub fn tq_state(qs: &[u8], t: usize) -> usize { let n = qs.len(); let s = if n == 32 { (qs[(t + 31) & 31] as u32) << 8 | qs[t] as u32 } else { let off = (31 - t) * (n / 4); @@ -165,10 +251,46 @@ pub fn tq_points(qs: &[u8], t: usize) -> (usize, usize) { let w = |i: usize| qs[if i < n { i } else { i - n }] as u32; // i < 2 n; a division here costs a third of a dot (qs[b] as u32 | w(b + 1) << 8 | w(b + 2) << 16) >> (off & 7) }; - let x = (s & 0x7fff).wrapping_mul(0x9e3779b1); + (s & 0x7fff) as usize +} + +/// A TQK stream with its first 4 bytes repeated after it, so `tq_state_in` reads a state with one 4-byte load. +#[inline(always)] +pub fn tq_stream(qs: &[u8]) -> [u8; 36] { + let (n, mut b) = (qs.len(), [0u8; 36]); + if n < 32 { + b[..n].copy_from_slice(qs); + b[n..n + 4].copy_from_slice(&qs[..4]); + } + b +} + +/// `tq_state(qs, t)`, with `buf = tq_stream(qs)`. +#[inline(always)] +pub fn tq_state_in(buf: &[u8; 36], qs: &[u8], t: usize) -> usize { + let n = qs.len(); + if n == 32 { return tq_state(qs, t) } + let off = (31 - t) * (n / 4); + (u32::from_le_bytes(buf[off >> 3..][..4].try_into().unwrap()) >> (off & 7) & 0x7fff) as usize +} + +#[inline] +fn state_points(s: usize) -> (usize, usize) { + let x = (s as u32).wrapping_mul(0x9e3779b1); ((x >> 21) as usize, ((x >> 10) & 2047) as usize) } +/// The four values of each trellis state (its two codebook points), 512 KB: a step is one load instead of the hash +/// and two loads, and the values are the same f32s. +pub static TQ_STATES: std::sync::LazyLock> = std::sync::LazyLock::new(|| (0..1 << 15).map(|s| { + let (a, b) = state_points(s); + [TQ_LUT[a][0], TQ_LUT[a][1], TQ_LUT[b][0], TQ_LUT[b][1]] +}).collect()); + +/// `TQ_STATES` times 8192, rounded to int16 (|values| < 4), for the integer CPU kernel. +pub static TQ_STATES_I16: std::sync::LazyLock> = + std::sync::LazyLock::new(|| TQ_STATES.iter().map(|v| v.map(|x| (x * 8192.0).round() as i16)).collect()); + /// TQ2_T (34 bytes), TQK7 (30), TQK6 (26): f16 d, then 32 trellis steps; step t gives values 4 t .. 4 t + 4, the two /// codebook points of `tq_points` times d. fn tq(b: &[u8], y: &mut [f32]) { @@ -179,7 +301,17 @@ fn tq(b: &[u8], y: &mut [f32]) { } } +#[inline] +fn affine_value(code: i16, scale: f32, offset: f32) -> f32 { + let v = scale * code as f32; + if offset == 0.0 { v } else { v + offset } +} + fn q2k(b: &[u8], y: &mut [f32]) { + unpack_q2k(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_q2k(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let (sc, d, min) = (&b[0..16], h(b, 80), h(b, 82)); let (mut q, mut is, mut o) = (16, 0, 0); for _ in 0..2 { @@ -188,7 +320,7 @@ fn q2k(b: &[u8], y: &mut [f32]) { let s = sc[is]; is += 1; let (dl, ml) = (d * (s & 0xF) as f32, min * (s >> 4) as f32); - for l in 0..16 { y[o] = dl * ((b[q + l + 16 * half] >> shift) & 3) as f32 - ml; o += 1; } + for l in 0..16 { emit(o, ((b[q + l + 16 * half] >> shift) & 3) as i16, dl, -ml); o += 1; } } } q += 32; @@ -212,6 +344,10 @@ pub(crate) fn q3k_scales(b: &[u8]) -> [i8; 16] { } fn q3k(b: &[u8], y: &mut [f32]) { + unpack_q3k(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_q3k(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let (hm, d_all, scales) = (&b[0..32], h(b, 108), q3k_scales(b)); let (mut q, mut is, mut o, mut m) = (32usize, 0, 0, 1u8); for _ in 0..2 { @@ -222,7 +358,7 @@ fn q3k(b: &[u8], y: &mut [f32]) { for l in 0..16 { let i = l + 16 * half; let v = ((b[q + i] >> shift) & 3) as i32 - if hm[i] & m != 0 { 0 } else { 4 }; - y[o] = dl * v as f32; + emit(o, v as i16, dl, 0.0); o += 1; } } @@ -233,28 +369,36 @@ fn q3k(b: &[u8], y: &mut [f32]) { } fn q4k(b: &[u8], y: &mut [f32]) { + unpack_q4k(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_q4k(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let (d, min, sc) = (h(b, 0), h(b, 2), &b[4..16]); let (mut q, mut o) = (16, 0); for j in 0..4 { let (s1, m1) = scale_min_k4(2 * j, sc); let (s2, m2) = scale_min_k4(2 * j + 1, sc); let (d1, m1, d2, m2) = (d * s1 as f32, min * m1 as f32, d * s2 as f32, min * m2 as f32); - for l in 0..32 { y[o + l] = d1 * (b[q + l] & 0xF) as f32 - m1; } - for l in 0..32 { y[o + 32 + l] = d2 * (b[q + l] >> 4) as f32 - m2; } + for l in 0..32 { emit(o + l, (b[q + l] & 0xF) as i16, d1, -m1); } + for l in 0..32 { emit(o + 32 + l, (b[q + l] >> 4) as i16, d2, -m2); } q += 32; o += 64; } } fn q5k(b: &[u8], y: &mut [f32]) { + unpack_q5k(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_q5k(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let (d, min, sc, qh) = (h(b, 0), h(b, 2), &b[4..16], &b[16..48]); let (mut q, mut o, mut u1, mut u2) = (48, 0, 1u8, 2u8); for j in 0..4 { let (s1, m1) = scale_min_k4(2 * j, sc); let (s2, m2) = scale_min_k4(2 * j + 1, sc); let (d1, m1, d2, m2) = (d * s1 as f32, min * m1 as f32, d * s2 as f32, min * m2 as f32); - for l in 0..32 { y[o + l] = d1 * ((b[q + l] & 0xF) as f32 + if qh[l] & u1 != 0 { 16.0 } else { 0.0 }) - m1; } - for l in 0..32 { y[o + 32 + l] = d2 * ((b[q + l] >> 4) as f32 + if qh[l] & u2 != 0 { 16.0 } else { 0.0 }) - m2; } + for l in 0..32 { emit(o + l, ((b[q + l] & 0xF) | (u8::from(qh[l] & u1 != 0) << 4)) as i16, d1, -m1); } + for l in 0..32 { emit(o + 32 + l, ((b[q + l] >> 4) | (u8::from(qh[l] & u2 != 0) << 4)) as i16, d2, -m2); } q += 32; o += 64; u1 <<= 2; @@ -263,6 +407,10 @@ fn q5k(b: &[u8], y: &mut [f32]) { } fn q6k(b: &[u8], y: &mut [f32]) { + unpack_q6k(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_q6k(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 208); for n in 0..2 { let (ql, qh, sc) = (&b[64 * n..], &b[128 + 32 * n..], &b[192 + 8 * n..]); @@ -273,30 +421,38 @@ fn q6k(b: &[u8], y: &mut [f32]) { let q2 = ((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) as i32 - 32; let q3 = ((ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4)) as i32 - 32; let q4 = ((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) as i32 - 32; - y[yo + l] = d * sc[is] as i8 as f32 * q1 as f32; - y[yo + l + 32] = d * sc[is + 2] as i8 as f32 * q2 as f32; - y[yo + l + 64] = d * sc[is + 4] as i8 as f32 * q3 as f32; - y[yo + l + 96] = d * sc[is + 6] as i8 as f32 * q4 as f32; + emit(yo + l, q1 as i16, d * sc[is] as i8 as f32, 0.0); + emit(yo + l + 32, q2 as i16, d * sc[is + 2] as i8 as f32, 0.0); + emit(yo + l + 64, q3 as i16, d * sc[is + 4] as i8 as f32, 0.0); + emit(yo + l + 96, q4 as i16, d * sc[is + 6] as i8 as f32, 0.0); } } } -fn sign(signs: u8, j: usize) -> f32 { if signs & KMASK_IQ2XS[j] != 0 { -1.0 } else { 1.0 } } +fn sign(signs: u8, j: usize) -> i16 { if signs & KMASK_IQ2XS[j] != 0 { -1 } else { 1 } } fn iq1s(b: &[u8], y: &mut [f32]) { + unpack_iq1s(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_iq1s(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 0); for ib in 0..8 { let qh = u16::from_le_bytes([b[34 + 2 * ib], b[35 + 2 * ib]]) as usize; let dl = d * (2 * ((qh >> 12) & 7) + 1) as f32; - let delta = if qh & 0x8000 != 0 { -0.125 } else { 0.125 }; + let delta = if qh & 0x8000 != 0 { -1 } else { 1 }; for l in 0..4 { let grid = IQ1S_GRID[b[2 + 4 * ib + l] as usize | (((qh >> (3 * l)) & 7) << 8)].to_le_bytes(); - for j in 0..8 { y[32 * ib + 8 * l + j] = dl * (grid[j] as i8 as f32 + delta); } + for j in 0..8 { emit(32 * ib + 8 * l + j, 8 * grid[j] as i8 as i16 + delta, dl * 0.125, 0.0); } } } } fn iq1m(b: &[u8], y: &mut [f32]) { + unpack_iq1m(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_iq1m(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let sc: [usize; 4] = std::array::from_fn(|i| u16::from_le_bytes([b[48 + 2 * i], b[49 + 2 * i]]) as usize); let d = f16::from_bits(((sc[0] >> 12) | ((sc[1] >> 8) & 0xF0) | ((sc[2] >> 4) & 0xF00) | (sc[3] & 0xF000)) as u16).to_f32(); for ib in 0..8 { @@ -304,37 +460,49 @@ fn iq1m(b: &[u8], y: &mut [f32]) { let dl = d * (2 * ((sc[ib / 2] >> (6 * (ib % 2) + 3 * (l / 2))) & 7) + 1) as f32; let qh = b[32 + 2 * ib + l / 2] as usize >> (4 * (l % 2)); let grid = IQ1S_GRID[b[4 * ib + l] as usize | ((qh & 7) << 8)].to_le_bytes(); - let delta = if qh & 8 != 0 { -0.125 } else { 0.125 }; - for j in 0..8 { y[32 * ib + 8 * l + j] = dl * (grid[j] as i8 as f32 + delta); } + let delta = if qh & 8 != 0 { -1 } else { 1 }; + for j in 0..8 { emit(32 * ib + 8 * l + j, 8 * grid[j] as i8 as i16 + delta, dl * 0.125, 0.0); } } } } fn iq2xxs(b: &[u8], y: &mut [f32]) { + unpack_iq2xxs(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_iq2xxs(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 0); for ib in 0..8 { let (qs, aux) = (&b[2 + 8 * ib..6 + 8 * ib], u32::from_le_bytes(b[6 + 8 * ib..10 + 8 * ib].try_into().unwrap())); let db = d * (0.5 + (aux >> 28) as f32) * 0.25; for l in 0..4 { let (grid, signs) = (IQ2XXS_GRID[qs[l] as usize].to_le_bytes(), KSIGNS_IQ2XS[((aux >> (7 * l)) & 127) as usize]); - for j in 0..8 { y[32 * ib + 8 * l + j] = db * grid[j] as f32 * sign(signs, j); } + for j in 0..8 { emit(32 * ib + 8 * l + j, grid[j] as i16 * sign(signs, j), db, 0.0); } } } } fn iq2s(b: &[u8], y: &mut [f32]) { + unpack_iq2s(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_iq2s(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 0); let (qs, signs, qh, scales) = (&b[2..34], &b[34..66], &b[66..74], &b[74..82]); for ib in 0..8 { let db = [d * (0.5 + (scales[ib] & 0xF) as f32) * 0.25, d * (0.5 + (scales[ib] >> 4) as f32) * 0.25]; for l in 0..4 { let grid = IQ2S_GRID[qs[4 * ib + l] as usize | ((qh[ib] as usize) << (8 - 2 * l) & 0x300)].to_le_bytes(); - for j in 0..8 { y[32 * ib + 8 * l + j] = db[l / 2] * grid[j] as f32 * sign(signs[4 * ib + l], j); } + for j in 0..8 { emit(32 * ib + 8 * l + j, grid[j] as i16 * sign(signs[4 * ib + l], j), db[l / 2], 0.0); } } } } fn iq2xs(b: &[u8], y: &mut [f32]) { + unpack_iq2xs(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_iq2xs(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 0); let scales = &b[66..74]; for ib in 0..8 { @@ -344,12 +512,16 @@ fn iq2xs(b: &[u8], y: &mut [f32]) { let q = u16::from_le_bytes([b[o], b[o + 1]]); let grid = IQ2XS_GRID[(q & 511) as usize].to_le_bytes(); let signs = KSIGNS_IQ2XS[(q >> 9) as usize]; - for j in 0..8 { y[32 * ib + 8 * l + j] = db[l / 2] * grid[j] as f32 * sign(signs, j); } + for j in 0..8 { emit(32 * ib + 8 * l + j, grid[j] as i16 * sign(signs, j), db[l / 2], 0.0); } } } } fn iq3xxs(b: &[u8], y: &mut [f32]) { + unpack_iq3xxs(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_iq3xxs(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 0); let (qs, ss) = (&b[2..66], &b[66..98]); for ib in 0..8 { @@ -361,14 +533,18 @@ fn iq3xxs(b: &[u8], y: &mut [f32]) { let g2 = IQ3XXS_GRID[qs[8 * ib + 2 * l + 1] as usize].to_le_bytes(); let o = 32 * ib + 8 * l; for j in 0..4 { - y[o + j] = db * g1[j] as f32 * sign(signs, j); - y[o + j + 4] = db * g2[j] as f32 * sign(signs, j + 4); + emit(o + j, g1[j] as i16 * sign(signs, j), db, 0.0); + emit(o + j + 4, g2[j] as i16 * sign(signs, j + 4), db, 0.0); } } } } fn iq3s(b: &[u8], y: &mut [f32]) { + unpack_iq3s(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_iq3s(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 0); let (qs, qh, signs, sc) = (&b[2..66], &b[66..74], &b[74..106], &b[106..110]); for ib in 0..8 { @@ -379,14 +555,18 @@ fn iq3s(b: &[u8], y: &mut [f32]) { let g2 = IQ3S_GRID[qs[8 * ib + 2 * l + 1] as usize | ((hb << (7 - 2 * l)) & 256)].to_le_bytes(); let (sg, o) = (signs[4 * ib + l], 32 * ib + 8 * l); for j in 0..4 { - y[o + j] = db * g1[j] as f32 * sign(sg, j); - y[o + j + 4] = db * g2[j] as f32 * sign(sg, j + 4); + emit(o + j, g1[j] as i16 * sign(sg, j), db, 0.0); + emit(o + j + 4, g2[j] as i16 * sign(sg, j + 4), db, 0.0); } } } } fn iq4xs(b: &[u8], y: &mut [f32]) { + unpack_iq4xs(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_iq4xs(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 0); let sh = u16::from_le_bytes([b[2], b[3]]); let (sl, qs) = (&b[4..8], &b[8..136]); @@ -395,30 +575,87 @@ fn iq4xs(b: &[u8], y: &mut [f32]) { let dl = d * (ls - 32) as f32; for j in 0..16 { let q = qs[16 * ib + j]; - y[32 * ib + j] = dl * KVALUES_IQ4NL[(q & 0xF) as usize] as f32; - y[32 * ib + j + 16] = dl * KVALUES_IQ4NL[(q >> 4) as usize] as f32; + emit(32 * ib + j, KVALUES_IQ4NL[(q & 0xF) as usize] as i16, dl, 0.0); + emit(32 * ib + j + 16, KVALUES_IQ4NL[(q >> 4) as usize] as i16, dl, 0.0); } } } -/// Signed codes of a Q4_0 block (f16 d, 16 bytes of nibbles; value = (q - 8) d) or a Q5_0 block (f16 d, 32 high bits, -/// 16 bytes of nibbles; value = (q - 16) d). Element j < 16 is the low nibble of byte j, j + 16 its high nibble. -fn q5_codes(ty: GgmlType, b: &[u8]) -> [i8; 32] { - let mut q = [0i8; 32]; - let (qh, qs) = if ty == Q5_0 { (u32::from_le_bytes(b[2..6].try_into().unwrap()), &b[6..22]) } else { (0, &b[2..18]) }; - let off = if ty == Q5_0 { 16 } else { 8 }; - for j in 0..16 { - q[j] = ((qs[j] & 0xF) as i32 | (((qh >> j) & 1) << 4) as i32) as i8 - off; - q[j + 16] = ((qs[j] >> 4) as i32 | (((qh >> (j + 16)) & 1) << 4) as i32) as i8 - off; +pub(crate) fn unpack_q1_0(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { + let d = h(b, 0); + for j in 0..128 { + let bit = (b[2 + j / 8] >> (j % 8)) & 1; + emit(j, 2 * bit as i16 - 1, d, 0.0); } - q +} + +pub(crate) fn unpack_q2_0(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { + let d = h(b, 0); + for j in 0..(b.len() - 2) * 4 { + let q = (b[2 + j / 4] >> (2 * (j % 4))) & 3; + emit(j, q as i16 - 1, d, 0.0); + } +} + +fn unpack_q4( + b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32), +) { + let start = if OFFSET { 4 } else { 2 }; + let (qh, qs) = if HIGH { + (u32::from_le_bytes(b[start..start + 4].try_into().unwrap()), &b[start + 4..]) + } else { (0, &b[start..]) }; + let d = h(b, 0); + let offset = if OFFSET { h(b, 2) } else { 0.0 }; + let zero = if OFFSET { 0 } else if HIGH { 16 } else { 8 }; + for (j, &q) in qs.iter().take(16).enumerate() { + let lo = (q & 15) as i16 | (((qh >> j) & 1) as i16 * 16); + let hi = (q >> 4) as i16 | (((qh >> (j + 16)) & 1) as i16 * 16); + emit(j, lo - zero, d, offset); + emit(j + 16, hi - zero, d, offset); + } +} + +pub(crate) fn unpack_q4_0(b: &[u8], emit: impl FnMut(usize, i16, f32, f32)) { + unpack_q4::(b, emit); +} + +pub(crate) fn unpack_q4_1(b: &[u8], emit: impl FnMut(usize, i16, f32, f32)) { + unpack_q4::(b, emit); +} + +pub(crate) fn unpack_q5_0(b: &[u8], emit: impl FnMut(usize, i16, f32, f32)) { + unpack_q4::(b, emit); +} + +pub(crate) fn unpack_q5_1(b: &[u8], emit: impl FnMut(usize, i16, f32, f32)) { + unpack_q4::(b, emit); +} + +pub(crate) fn unpack_q8_0(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { + let d = h(b, 0); + for (j, &q) in b[2..34].iter().enumerate() { emit(j, q as i8 as i16, d, 0.0); } +} + +pub(crate) fn unpack_q8_1(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { + let d = h(b, 0); + // The second half is the stored activation sum. It is not a weight offset. + for (j, &q) in b[4..36].iter().enumerate() { emit(j, q as i8 as i16, d, 0.0); } +} + +pub(crate) fn unpack_q8k(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { + let d = f32::from_le_bytes(b[..4].try_into().unwrap()); + for (j, &q) in b[4..260].iter().enumerate() { emit(j, q as i8 as i16, d, 0.0); } } fn iq4nl(b: &[u8], y: &mut [f32]) { + unpack_iq4nl(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_iq4nl(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { let d = h(b, 0); for j in 0..16 { - y[j] = d * KVALUES_IQ4NL[(b[2 + j] & 0xF) as usize] as f32; - y[j + 16] = d * KVALUES_IQ4NL[(b[2 + j] >> 4) as usize] as f32; + emit(j, KVALUES_IQ4NL[(b[2 + j] & 0xF) as usize] as i16, d, 0.0); + emit(j + 16, KVALUES_IQ4NL[(b[2 + j] >> 4) as usize] as i16, d, 0.0); } } @@ -448,22 +685,76 @@ static UE4M3_LUT: [f32; 256] = { #[inline] pub fn ue4m3(x: u8) -> f32 { UE4M3_LUT[x as usize] } +pub(crate) fn unpack_mxfp4(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { + // The E2M1 table is doubled, so halve the shared E8M0 scale. + let exponent = u32::from(b[0]); + let d = f32::from_bits(if exponent < 2 { 0x0020_0000 << exponent } else { (exponent - 1) << 23 }); + for (j, &q) in b[1..17].iter().enumerate() { + emit(j, KVALUES_FP4[(q & 15) as usize] as i16, d, 0.0); + emit(j + 16, KVALUES_FP4[(q >> 4) as usize] as i16, d, 0.0); + } +} + /// NVFP4: 64 values as four sub-blocks of 16, each with a UE4M3 scale `d[s]`, then 32 bytes of E2M1 codes. fn nvfp4(b: &[u8], y: &mut [f32]) { + unpack_nvfp4(b, |i, code, scale, offset| y[i] = affine_value(code, scale, offset)); +} + +pub(crate) fn unpack_nvfp4(b: &[u8], mut emit: impl FnMut(usize, i16, f32, f32)) { for s in 0..4 { let d = ue4m3(b[s]); for j in 0..8 { let q = b[4 + 8 * s + j]; - y[16 * s + j] = d * KVALUES_FP4[(q & 0xF) as usize] as f32; - y[16 * s + j + 8] = d * KVALUES_FP4[(q >> 4) as usize] as f32; + emit(16 * s + j, KVALUES_FP4[(q & 0xF) as usize] as i16, d, 0.0); + emit(16 * s + j + 8, KVALUES_FP4[(q >> 4) as usize] as i16, d, 0.0); } } } #[cfg(test)] mod tests { + #[test] + fn tq_state_in_matches() { + let mut r = 0x12345678u32; + for n in [24, 28, 32] { + for _ in 0..200 { + let qs: Vec = (0..n).map(|_| { r ^= r << 13; r ^= r >> 17; r ^= r << 5; r as u8 }).collect(); + let buf = super::tq_stream(&qs); + for t in 0..32 { assert_eq!(super::tq_state_in(&buf, &qs, t), super::tq_state(&qs, t)); } + } + } + } + use super::*; + #[test] + fn affine_ternary_layouts_match_reference() { + let scale = -0.75; + let mut ptq = [0; 28]; + for (i, b) in ptq[..26].iter_mut().enumerate() { *b = (19 * i + 83) as u8; } + ptq[26..].copy_from_slice(&f16::from_f32(scale).to_le_bytes()); + let mut out = [0.0; 128]; + dequant_row(PTQ1_0, &ptq, &mut out); + for (i, &v) in out.iter().enumerate() { + let (byte, trit) = match i { + 0..80 => (i % 16, i / 16), + 80..120 => (16 + (i - 80) % 8, (i - 80) / 8), + _ => (24 + (i - 120) % 2, (i - 120) / 2), + }; + assert_eq!(v.to_bits(), (scale * tq1_trit(ptq[byte], trit)).to_bits()); + } + + let mut tq = [0; 66]; + for (i, b) in tq[..64].iter_mut().enumerate() { *b = (31 * i + 45) as u8; } + tq[64..].copy_from_slice(&f16::from_f32(scale).to_le_bytes()); + let mut out = [0.0; 256]; + dequant_row(TQ2_0, &tq, &mut out); + for (i, &v) in out.iter().enumerate() { + let code = (tq[i / 128 * 32 + i % 32] >> (2 * (i / 32 % 4))) & 3; + assert_eq!(v.to_bits(), (scale * (code as f32 - 1.0)).to_bits()); + } + } + #[test] fn nvfp4_dequant() { // Scale bytes: 0x38 = e 7, m 0 (1.0, halved 0.5); 0x01 = subnormal 2^-9 (halved 2^-10); 0x7F = NaN (0); 0x41 = e 8, m 1 (2.25, halved 1.125). diff --git a/src/raon/chat.rs b/src/raon/chat.rs new file mode 100644 index 00000000..ae36d87c --- /dev/null +++ b/src/raon/chat.rs @@ -0,0 +1,376 @@ +//! `rustingstrata generate|chat|serve` for KRAFTON Raon-1 mini (`raon1`). +use super::{dflash::RaonDFlash, forward::RaonModel}; +use crate::{chat::{Json, Msg}, gguf::Gguf, tokenizer::Tokenizer}; +use std::io::{BufRead, Write}; +use std::path::Path; + +const IM_START: &str = "<|im_start|>"; +const IM_END: &str = "<|im_end|>"; +const THINK_OPEN: &str = "\n"; +const THINK_EMPTY: &str = "\n\n"; +const THINK_END: &str = ""; +const CALL_TAG: &str = ""; + +pub use crate::deepseek::chat::gpu_defaults; + +/// Render messages + optional tools using KRAFTON Raon-1 mini's ChatML SFT template. +pub fn render(msgs: &[Msg], tools: &[Json], think: bool, preserve: Option) -> String { + let truncate_history = preserve.map(|p| !p).unwrap_or(false); + let mut s = String::new(); + let has_tools = !tools.is_empty(); + let first_sys = msgs.first().is_some_and(|m| m.role == "system"); + + if has_tools { + s += &format!("{IM_START}system\n# Tools\n\nYou have access to the following functions:\n\n"); + for t in tools { + s += "\n"; + s += &t.dump(); + } + s += "\n\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\ + \n\n\nvalue_1\n\n\ + \nThis is the value for the second parameter\nthat can span\nmultiple lines\n\ + \n\n\n\n\nReminder:\n\ + - Function calls MUST follow the specified format: an inner block must be nested within XML tags\n\ + - Required parameters MUST be specified\n\ + - You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n\ + - If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n\ + "; + if first_sys { + let c = msgs[0].content.trim(); + if !c.is_empty() { + s += "\n\n"; + s += c; + } + } + s += &format!("{IM_END}\n"); + } else if first_sys { + s += &format!("{IM_START}system\n{}{IM_END}\n", msgs[0].content.trim()); + } + + let mut last_query_idx = msgs.len().saturating_sub(1); + for (i, m) in msgs.iter().enumerate().rev() { + if m.role == "user" { + let c = m.content.trim(); + if !(c.starts_with("") && c.ends_with("")) { + last_query_idx = i; + break; + } + } + } + + for (i, m) in msgs.iter().enumerate() { + let content = m.content.trim(); + match m.role.as_str() { + "system" => { + if i > 0 { + s += &format!("{IM_START}system\n{content}{IM_END}\n"); + } + } + "user" => { + s += &format!("{IM_START}user\n{content}{IM_END}\n"); + } + "assistant" => { + let (reasoning, body) = if let Some(r) = &m.reasoning { + (r.as_str(), content) + } else if content.starts_with("") && content.contains(THINK_END) { + let (a, b) = content.split_once(THINK_END).unwrap(); + (a[7..].trim_matches('\n'), b.trim_start_matches('\n')) + } else { + ("", content) + }; + s += &format!("{IM_START}assistant\n"); + let keep_r = !truncate_history || i > last_query_idx; + if keep_r && !reasoning.trim().is_empty() { + s += &format!("\n{}\n\n\n", reasoning.trim()); + } else { + s += THINK_EMPTY; + } + s += body; + for (ci, c) in m.calls.iter().enumerate() { + if ci == 0 { + if !body.trim().is_empty() { s += "\n\n"; } + } else { + s += "\n"; + } + s += &format!("\n\n", c.name); + if let Json::Obj(args) = &c.args { + for (k, v) in args { + let val = v.as_str().map_or_else(|| v.dump(), str::to_string); + s += &format!("\n{val}\n\n"); + } + } + s += "\n"; + } + s += &format!("{IM_END}\n"); + } + "tool" => { + let prev_tool = i > 0 && msgs[i - 1].role == "tool"; + let next_tool = msgs.get(i + 1).is_some_and(|x| x.role == "tool"); + if !prev_tool { s += &format!("{IM_START}user"); } + s += &format!("\n\n{content}\n"); + if !next_tool { s += &format!("{IM_END}\n"); } + } + _ => {} + } + } + + s += &format!("{IM_START}assistant\n"); + s += if think { THINK_OPEN } else { THINK_EMPTY }; + s +} + +/// Parse `v` blocks. +pub fn parse_calls(text: &str) -> Option<(String, Vec<(String, String)>)> { + let from = text.rfind(THINK_END).map_or(0, |p| p + THINK_END.len()); + let start = from + text[from..].find(CALL_TAG)?; + let mut calls = Vec::new(); + for block in text[start..].split(CALL_TAG).skip(1) { + let Some(inner) = block.split("").next() else { continue; }; + let Some((_, after_fn)) = inner.split_once("') else { continue; }; + let Some(body) = rest.split("").next() else { continue; }; + let mut args = serde_json::Map::new(); + for part in body.split("') else { continue; }; + let Some(val) = vrest.split("").next() else { continue; }; + let val = val.trim(); + args.insert(k.trim().to_string(), serde_json::from_str(val).unwrap_or_else(|_| val.into())); + } + calls.push((name.trim().to_string(), serde_json::Value::Object(args).to_string())); + } + (!calls.is_empty()).then(|| (text[from..start].trim().to_string(), calls)) +} + +fn decode( + m: &mut RaonModel, + mut df: Option<&mut RaonDFlash>, + tok: &Tokenizer, + lim: &mut Option, + mut logits: Vec, + n: usize, + drafts: &mut (usize, usize), + mut piece: impl FnMut(&str) -> bool, +) -> (Vec, bool) { + let eos = tok.eos_ids(); + // A grammar or bias checks each token, so the drafts are off then. + let spec_on = lim.is_none() && std::env::var("STRATA_RAON_SPEC").ok().as_deref() != Some("0"); + if lim.is_some() { df = None; } + let (mut out, mut shown) = (Vec::new(), 0); + let mut emit = |out: &[u32], shown: &mut usize| -> bool { + let s = tok.decode(out).unwrap_or_default(); + if !s.ends_with('\u{FFFD}') && s.len() > *shown && s.is_char_boundary(*shown) { + if !piece(&s[*shown..]) { return false; } + *shown = s.len(); + } + true + }; + while out.len() < n { + let next = if lim.is_some() { crate::grammar::greedy(lim, &mut logits) } else { crate::ops::argmax(&logits) as u32 }; + if eos.contains(&next) { return (out, true); } + out.push(next); + if !emit(&out, &mut shown) { break; } + if out.len() >= n { break; } + let rem = n - out.len(); + if let Some(dflash) = df.as_deref_mut() && rem >= 2 { + let t0 = std::time::Instant::now(); + let feats = m.take_pending_feats(); + dflash.commit_ctx(&feats); + let t1 = std::time::Instant::now(); + let blk = std::env::var("STRATA_DFLASH_BLOCK") + .ok() + .and_then(|v| v.parse::().ok()) + .unwrap_or(4) + .clamp(2, dflash.block_size.max(2)); + let k_eff = rem.min(blk - 1); + let draft = dflash.draft_block(next, m, k_eff); + let t2 = std::time::Instant::now(); + if !draft.is_empty() { + let (accepted, next_logits) = m.verify_greedy(next, &draft, &eos); + drafts.0 += draft.len(); + drafts.1 += accepted.len(); + if std::env::var_os("STRATA_RAON_PROF").is_some() { + eprintln!( + "dflash: acc={}/{} commit={:.1}ms draft={:.1}ms verify={:.1}ms", + accepted.len(), + draft.len(), + t1.duration_since(t0).as_secs_f64() * 1e3, + t2.duration_since(t1).as_secs_f64() * 1e3, + t2.elapsed().as_secs_f64() * 1e3, + ); + } + logits = next_logits; + for t in accepted { + out.push(t); + if !emit(&out, &mut shown) { return (out, false); } + if out.len() >= n { return (out, false); } + } + continue; + } + } else if spec_on && rem >= 2 { + let max_d = rem.min(3); + let (draft, order) = crate::ngram::suffix_draft_with_order(&m.toks, next, max_d, &eos); + if draft.len() >= 2 && order >= 3 { + let (accepted, next_logits) = m.verify_greedy(next, &draft, &eos); + drafts.0 += draft.len(); + drafts.1 += accepted.len(); + logits = next_logits; + for t in accepted { + out.push(t); + if !emit(&out, &mut shown) { return (out, false); } + if out.len() >= n { return (out, false); } + } + continue; + } + } + logits = m.step(next); + } + (out, false) +} + +fn show(s: &str) -> bool { + print!("{s}"); + std::io::stdout().flush().is_ok() +} + +pub fn generate(g: &Gguf, prompt: &str, n: usize, draft_model: Option<&Path>) -> anyhow::Result<()> { + gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = RaonModel::new(g)?; + let df_gguf = draft_model.map(Gguf::open).transpose()?; + let mut df = df_gguf.as_ref().map(RaonDFlash::load).transpose()?; + if let Some(d) = &df { + m.set_capture_layers(d.target_layers.clone()); + } + let max_ctx = m.cfg.n_ctx; + let ids = tok.encode(prompt)?; + anyhow::ensure!(!ids.is_empty() && ids.len() < max_ctx, "{}", crate::serve::too_long(ids.len(), max_ctx)); + let logits = m.prefill(&ids); + let mut drafts = (0, 0); + decode(&mut m, df.as_mut(), &tok, &mut None, logits, n.min(max_ctx - ids.len()), &mut drafts, show); + println!(); + Ok(()) +} + +pub fn chat(g: &Gguf, system: Option, n: usize, think: bool, draft_model: Option<&Path>) -> anyhow::Result<()> { + gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = RaonModel::new(g)?; + let df_gguf = draft_model.map(Gguf::open).transpose()?; + let mut df = df_gguf.as_ref().map(RaonDFlash::load).transpose()?; + if let Some(d) = &df { + m.set_capture_layers(d.target_layers.clone()); + } + m.set_effort(None, think); + let max_ctx = m.cfg.n_ctx; + let stdin = std::io::stdin(); + let mut history: Vec = system.into_iter().map(|s| Msg::new("system", &s)).collect(); + loop { + print!("{}", crate::term::prompt()); + std::io::stdout().flush()?; + let mut line = String::new(); + if stdin.lock().read_line(&mut line)? == 0 { break; } + let line = line.trim_end(); + if line.is_empty() { continue; } + history.push(Msg::new("user", line)); + let text = render(&history, &[], think, None); + let ids = tok.encode(&text)?; + if ids.len() >= max_ctx { + println!("context is full ({max_ctx} tokens); restart the chat"); + break; + } + let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { + m.toks.len() + } else { + m.reset(); + if let Some(d) = df.as_mut() { d.reset(); } + 0 + }; + let logits = m.prefill(&ids[keep..]); + let mut drafts = (0, 0); + let (out, _) = decode(&mut m, df.as_mut(), &tok, &mut None, logits, n.min(max_ctx - ids.len()), &mut drafts, show); + println!(); + let reply = tok.decode(&out).unwrap_or_default(); + let stored = if think { format!("{THINK_OPEN}{reply}") } else { reply }; + history.push(Msg::new("assistant", &stored)); + } + Ok(()) +} + +pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Result> { + use anyhow::Context; + use serde_json::json; + gpu_defaults(); + let mut m = RaonModel::new(g)?; + crate::serve::warm_up(tok, |ids| { m.prefill(ids); m.reset(); })?; + let max_ctx = m.cfg.n_ctx; + Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| { + let think = q.think.unwrap_or(false); + m.set_effort(q.reasoning_effort.as_deref(), think); + let ids = tok.encode(&render(&q.messages, &q.tools, think, q.preserve_thinking)) + .ok().filter(|i| !i.is_empty()).context("cannot encode prompt")?; + anyhow::ensure!(ids.len() < max_ctx, "{}", crate::serve::too_long(ids.len(), max_ctx)); + let mut lim = crate::grammar::Constraint::new(q, tok)?; + let t = std::time::Instant::now(); + let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; + if q.stream && !q.head_sent { let _ = write!(c, "{}", crate::serve::sse_head(c)); } + let logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); + let prefill_s = t.elapsed().as_secs_f64(); + let n = q.max_tokens.unwrap_or(usize::MAX).min(max_ctx - ids.len()); + let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); + let tools = q.tool_calls && !q.tools.is_empty(); + let mut hold = crate::chat::Hold::new(tools, q.stop.clone()).tagged(CALL_TAG); + let mut alive = std::time::Instant::now(); + let mut drafts = (0, 0); + let (out, stopped) = decode(&mut m, None, &tok, &mut lim, logits, n, &mut drafts, |p| { + let t = hold.push(p); + (!q.stream || if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() }) && !hold.stopped + }); + let calls = if tools { parse_calls(&hold.text) } else { None }; + let done = if calls.is_some() { "tool_calls" } else if stopped || hold.stopped { "stop" } else { "length" }; + let calls_json = |(content, calls): &(String, Vec<(String, String)>), stream: bool| { + let c: Vec<_> = calls.iter().enumerate().map(|(k, (f, a))| { + let mut c = json!({"id": format!("call_{k}"), "type": "function", "function": {"name": f, "arguments": a}}); + if stream { c["index"] = k.into(); } + c + }).collect(); + if stream { json!({"tool_calls": c}) } else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } + }; + let drafts = crate::serve::draft_delta(crate::serve::draft_kind(crate::serve::DraftModel::None, true), (0, 0), drafts); + let d = crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done, drafts }; + let timings = d.timings(t); + let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), "prompt_tokens_details": {"cached_tokens": keep}}); + if q.stream { + match &calls { + Some(x) => { let _ = write!(c, "data: {}\n\n", chunk(calls_json(x, true), None)); } + None if !hold.rest().is_empty() => { let _ = write!(c, "data: {}\n\n", chunk(json!({"content": hold.rest()}), None)); } + None => {} + } + let mut last = chunk(json!({}), Some(done)); + last["usage"] = usage; + last["timings"] = timings; + let _ = write!(c, "data: {last}\n\ndata: [DONE]\n\n"); + } else { + let message = match &calls { Some(x) => calls_json(x, false), None => json!({"role": "assistant", "content": hold.text}) }; + let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": message, "finish_reason": done}], + "usage": usage, "timings": timings}); + crate::serve::send(c, "200 OK", "application/json", &b.to_string()); + } + Ok(d) + })) +} + +#[test] +fn template_and_calls() { + let user = [Msg::new("user", "hi")]; + assert_eq!(render(&user, &[], false, None), "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n\n"); + assert_eq!(render(&user, &[], true, None), "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n"); + let reply = "\nplan\n\n\nok\n\n\n\n\nSeoul\n\n\n3\n\n\n"; + assert_eq!(parse_calls(reply), Some(("ok".into(), vec![("get".into(), r#"{"city":"Seoul","n":3}"#.into())]))); + // One malformed tool_call block must not discard valid sibling blocks. + let mixed = "malformed\n\n\n\n"; + assert_eq!(parse_calls(mixed), Some(("".into(), vec![("ping".into(), "{}".into())]))); + // Multi-turn history with think=true preserves reasoning block properly. + let hist = [Msg::new("user", "hi"), Msg::new("assistant", "\nplan\n\n\nhello"), Msg::new("user", "next")]; + let rendered = render(&hist, &[], true, Some(false)); + assert!(rendered.contains("<|im_start|>assistant\n\n\nhello<|im_end|>\n")); +} diff --git a/src/raon/dflash.rs b/src/raon/dflash.rs new file mode 100644 index 00000000..9b6bc024 --- /dev/null +++ b/src/raon/dflash.rs @@ -0,0 +1,442 @@ +//! DFlash2 parallel block-diffusion drafter for KRAFTON Raon-1 mini (`dflash-raon-1-mini-Q8_0.gguf`). +//! Uses `GroupedDynamicCausalConv` (prepare/finish), sliding-window bidirectional block attention with +//! QK-RMSNorm + NeoX RoPE, SwiGLU FFN, and low-rank `CandidateSelector` (`top_k = 16`). +use super::forward::RaonModel; +use crate::deepseek::mat::{Mat, matvec_rows, vec_f32}; +use crate::deepseek::ops::rms_norm_w; +use crate::gguf::Gguf; +use crate::weights::dot; +use anyhow::{Context, Result}; +use rayon::prelude::*; + +struct DfConv<'a> { + base: Vec, // [2, K, H] + proj: Mat<'a>, // [H, 2*K*G] +} + +struct DfLayer<'a> { + attn_norm: Vec, + attn_conv: Option>, + wq: Mat<'a>, + wk: Mat<'a>, + wv: Mat<'a>, + q_norm: Vec, + k_norm: Vec, + wo: Mat<'a>, + ffn_norm: Vec, + ffn_conv: Option>, + gate: Mat<'a>, + up: Mat<'a>, + down: Mat<'a>, +} + +struct Selector<'a> { + hidden: Mat<'a>, // [H, rank] + pred: Mat<'a>, // [rank, vocab] + succ: Mat<'a>, // [rank, vocab] + rank: usize, + top_k: usize, +} + +pub struct RaonDFlash<'a> { + pub block_size: usize, + pub mask_token_id: u32, + pub target_layers: Vec, // 0-indexed Raon layer outputs to capture + n_embd: usize, + n_head: usize, + n_head_kv: usize, + head_dim: usize, + eps: f32, + rope_base: f32, + conv_k: usize, + conv_gs: usize, + swa_window: usize, + fc: Mat<'a>, + enc_norm: Vec, + out_norm: Vec, + layers: Vec>, + selector: Option>, + // Per-layer cached context K/V: [pos * n_head_kv * head_dim] + k_cache: Vec>, + v_cache: Vec>, + ctx_len: usize, +} + +#[inline] +fn silu(x: f32) -> f32 { + x / (1.0 + (-x).exp()) +} + +/// NeoX-style rotary embedding in-place on `n_heads` heads of dimension `hd` at position `pos`. +fn rope_neox_inplace(v: &mut [f32], n_heads: usize, hd: usize, pos: usize, base: f32) { + let half = hd / 2; + let p = pos as f32; + for h in 0..n_heads { + let s = &mut v[h * hd..(h + 1) * hd]; + for i in 0..half { + let inv_freq = base.powf(-2.0 * i as f32 / hd as f32); + let ang = p * inv_freq; + let (si, co) = ang.sin_cos(); + let (a, b) = (s[i], s[i + half]); + s[i] = a * co - b * si; + s[i + half] = a * si + b * co; + } + } +} + +/// DFlash2 `GroupedDynamicCausalConv` (matches `src/vulkan/shaders/dflash2_conv.comp`). +/// `x`: `[T, H]`, `dyn_w`: `[T, 2, K, G]`, `base`: `[2, K, H]`, `part`: 0 (prepare) or 1 (finish). +fn dflash2_conv(x: &[f32], dyn_w: &[f32], base: &[f32], h: usize, gs: usize, k: usize, t_len: usize, part: usize) -> Vec { + let g_cnt = h / gs; + let mut out = vec![0.0f32; t_len * h]; + for t in 0..t_len { + let dst = &mut out[t * h..(t + 1) * h]; + for off in 0..k { + if t >= off { + let src = &x[(t - off) * h..(t - off + 1) * h]; + let b_row = &base[(part * k + off) * h..(part * k + off + 1) * h]; + let d_row = &dyn_w[((t * 2 + part) * k + off) * g_cnt..((t * 2 + part) * k + off + 1) * g_cnt]; + for i in 0..h { + dst[i] += (b_row[i] + d_row[i / gs]) * src[i]; + } + } + } + } + out +} + +impl<'a> RaonDFlash<'a> { + pub fn load(g: &'a Gguf) -> Result { + let u = |k: &str, def: usize| -> usize { g.get(k).ok().and_then(|v| v.as_u64()).map_or(def, |v| v as usize) }; + let f = |k: &str, def: f32| -> f32 { g.get(k).ok().and_then(|v| v.as_f32()).unwrap_or(def) }; + + let n_layer = u("dflash.block_count", 5); + let n_embd = u("dflash.embedding_length", 2560); + let n_head = u("dflash.attention.head_count", 20); + let n_head_kv = u("dflash.attention.head_count_kv", 5); + let head_dim = u("dflash.attention.key_length", 128); + let eps = f("dflash.attention.layer_norm_rms_epsilon", 1e-5); + let rope_base = f("dflash.rope.freq_base", 10_000_000.0); + let block_size = u("dflash.block_size", 8); + let conv_k = u("dflash.conv_kernel_size", 0); + let conv_gs = u("dflash.conv_group_size", 16); + let swa_window = u("dflash.attention.sliding_window", 2048); + let mask_token_id = u("tokenizer.ggml.mask_token_id", 259_839) as u32; + + // `dflash.target_layers` in GGUF stores 1-indexed hidden-state IDs (e.g. [2, 7, 12, 17, 22]), + // corresponding to 0-indexed Raon layer outputs [1, 6, 11, 16, 21]. + let target_layers: Vec = g.get("dflash.target_layers") + .ok() + .and_then(|v| v.as_arr()) + .map(|a| a.iter().filter_map(|x| x.as_u64()).map(|id| (id as usize).saturating_sub(1)).collect()) + .filter(|v: &Vec| !v.is_empty()) + .unwrap_or_else(|| vec![1, 6, 11, 16, 21]); + + let hm = |name: &str| Mat::load_host(g, name); + let fc = hm("fc.weight")?; + let enc_norm = vec_f32(g, "enc.output_norm.weight")?; + let out_norm = vec_f32(g, "output_norm.weight")?; + + let mut layers = Vec::with_capacity(n_layer); + for il in 0..n_layer { + let attn_conv = if conv_k > 0 && g.tensors.contains_key(&format!("blk.{il}.attn_conv_base")) { + Some(DfConv { + base: vec_f32(g, &format!("blk.{il}.attn_conv_base"))?, + proj: hm(&format!("blk.{il}.attn_conv_proj.weight"))?, + }) + } else { + None + }; + let ffn_conv = if conv_k > 0 && g.tensors.contains_key(&format!("blk.{il}.ffn_conv_base")) { + Some(DfConv { + base: vec_f32(g, &format!("blk.{il}.ffn_conv_base"))?, + proj: hm(&format!("blk.{il}.ffn_conv_proj.weight"))?, + }) + } else { + None + }; + layers.push(DfLayer { + attn_norm: vec_f32(g, &format!("blk.{il}.attn_norm.weight"))?, + attn_conv, + wq: hm(&format!("blk.{il}.attn_q.weight"))?, + wk: hm(&format!("blk.{il}.attn_k.weight"))?, + wv: hm(&format!("blk.{il}.attn_v.weight"))?, + q_norm: vec_f32(g, &format!("blk.{il}.attn_q_norm.weight"))?, + k_norm: vec_f32(g, &format!("blk.{il}.attn_k_norm.weight"))?, + wo: hm(&format!("blk.{il}.attn_output.weight"))?, + ffn_norm: vec_f32(g, &format!("blk.{il}.ffn_norm.weight"))?, + ffn_conv, + gate: hm(&format!("blk.{il}.ffn_gate.weight"))?, + up: hm(&format!("blk.{il}.ffn_up.weight"))?, + down: hm(&format!("blk.{il}.ffn_down.weight"))?, + }); + } + + let selector_rank = u("dflash.selector_rank", 0); + let selector_top_k = u("dflash.selector_top_k", 16); + let selector = if selector_rank > 0 && g.tensors.contains_key("selector_hidden.weight") { + Some(Selector { + hidden: hm("selector_hidden.weight").context("selector_hidden.weight")?, + pred: hm("selector_predecessor.weight").context("selector_predecessor.weight")?, + succ: hm("selector_successor.weight").context("selector_successor.weight")?, + rank: selector_rank, + top_k: selector_top_k, + }) + } else { + None + }; + + Ok(Self { + block_size, + mask_token_id, + target_layers, + n_embd, + n_head, + n_head_kv, + head_dim, + eps, + rope_base, + conv_k, + conv_gs, + swa_window, + fc, + enc_norm, + out_norm, + k_cache: vec![Vec::new(); n_layer], + v_cache: vec![Vec::new(); n_layer], + layers, + selector, + ctx_len: 0, + }) + } + + pub fn reset(&mut self) { + for k in &mut self.k_cache { k.clear(); } + for v in &mut self.v_cache { v.clear(); } + self.ctx_len = 0; + } + + /// Project newly accepted target hidden features into each drafter layer's K/V context cache. + pub fn commit_ctx(&mut self, feats: &[Vec]) { + if feats.is_empty() { return; } + let nt = feats.len(); + let frefs: Vec<&[f32]> = feats.iter().map(Vec::as_slice).collect(); + let fc_out = matvec_rows(&self.fc, &frefs); + let mut h = vec![0.0f32; nt * self.n_embd]; + for t in 0..nt { + rms_norm_w( + &fc_out[t * self.n_embd..(t + 1) * self.n_embd], + &self.enc_norm, + self.eps, + &mut h[t * self.n_embd..(t + 1) * self.n_embd], + ); + } + let hrefs: Vec<&[f32]> = h.chunks_exact(self.n_embd).collect(); + let kv_dim = self.n_head_kv * self.head_dim; + let hd = self.head_dim; + for (il, dl) in self.layers.iter().enumerate() { + let mut ks = matvec_rows(&dl.wk, &hrefs); + let vs = matvec_rows(&dl.wv, &hrefs); + let mut kn = vec![0.0f32; hd]; + for t in 0..nt { + let row = &mut ks[t * kv_dim..(t + 1) * kv_dim]; + for kh in 0..self.n_head_kv { + let s = &mut row[kh * hd..(kh + 1) * hd]; + rms_norm_w(s, &dl.k_norm, self.eps, &mut kn); + s.copy_from_slice(&kn); + } + rope_neox_inplace(row, self.n_head_kv, hd, self.ctx_len + t, self.rope_base); + } + self.k_cache[il].extend_from_slice(&ks); + self.v_cache[il].extend_from_slice(&vs); + } + self.ctx_len += nt; + } + + /// Draft `k_eff` (`<= block_size - 1`) speculative tokens following `anchor`. + pub fn draft_block(&mut self, anchor: u32, target: &RaonModel, k_eff: usize) -> Vec { + let k_eff = k_eff.min(self.block_size.saturating_sub(1)); + if k_eff == 0 { return Vec::new(); } + let b_len = k_eff + 1; + let (ne, nh, nkv, hd, eps) = (self.n_embd, self.n_head, self.n_head_kv, self.head_dim, self.eps); + let kv_dim = nkv * hd; + let gqa = nh / nkv; + let scale = 1.0 / (hd as f32).sqrt(); + let start = self.ctx_len; + + // Input block embeddings: [anchor, mask, mask, ...] + let mut x = vec![0.0f32; b_len * ne]; + target.embed_tok(anchor, &mut x[..ne]); + let mut mask_emb = vec![0.0f32; ne]; + target.embed_tok(self.mask_token_id, &mut mask_emb); + for t in 1..b_len { + x[t * ne..(t + 1) * ne].copy_from_slice(&mask_emb); + } + + let mut h = vec![0.0f32; b_len * ne]; + for (il, dl) in self.layers.iter().enumerate() { + // 1. Attention norm + optional DFlash2 conv prepare + for t in 0..b_len { + rms_norm_w(&x[t * ne..(t + 1) * ne], &dl.attn_norm, eps, &mut h[t * ne..(t + 1) * ne]); + } + let (q_in, attn_dyn) = if let Some(cv) = &dl.attn_conv { + let hrefs: Vec<&[f32]> = h.chunks_exact(ne).collect(); + let dyn_w = matvec_rows(&cv.proj, &hrefs); + let pre = dflash2_conv(&h, &dyn_w, &cv.base, ne, self.conv_gs, self.conv_k, b_len, 0); + (pre, Some(dyn_w)) + } else { + (h.clone(), None) + }; + + let qrefs: Vec<&[f32]> = q_in.chunks_exact(ne).collect(); + let mut qs = matvec_rows(&dl.wq, &qrefs); + let mut ks_blk = matvec_rows(&dl.wk, &qrefs); + let vs_blk = matvec_rows(&dl.wv, &qrefs); + + let mut tmp = vec![0.0f32; hd]; + for t in 0..b_len { + let qrow = &mut qs[t * nh * hd..(t + 1) * nh * hd]; + for qh in 0..nh { + let s = &mut qrow[qh * hd..(qh + 1) * hd]; + rms_norm_w(s, &dl.q_norm, eps, &mut tmp); + s.copy_from_slice(&tmp); + } + rope_neox_inplace(qrow, nh, hd, start + t, self.rope_base); + + let krow = &mut ks_blk[t * kv_dim..(t + 1) * kv_dim]; + for kh in 0..nkv { + let s = &mut krow[kh * hd..(kh + 1) * hd]; + rms_norm_w(s, &dl.k_norm, eps, &mut tmp); + s.copy_from_slice(&tmp); + } + rope_neox_inplace(krow, nkv, hd, start + t, self.rope_base); + } + + // Bidirectional block attention over [ctx_start..start] + [0..b_len] + let ctx_start = start.saturating_sub(self.swa_window); + let n_ctx = start - ctx_start; + let total_kv = n_ctx + b_len; + let k_ctx = &self.k_cache[il]; + let v_ctx = &self.v_cache[il]; + + let mut att = vec![0.0f32; b_len * nh * hd]; + att.par_chunks_mut(hd).enumerate().for_each(|(idx, oh)| { + let (t, qh) = (idx / nh, idx % nh); + let kh = qh / gqa; + let qv = &qs[(t * nh + qh) * hd..(t * nh + qh + 1) * hd]; + let mut scores = Vec::with_capacity(total_kv); + let mut mx = f32::NEG_INFINITY; + for p in ctx_start..start { + let kv = &k_ctx[p * kv_dim + kh * hd..p * kv_dim + (kh + 1) * hd]; + let s = dot(qv, kv) * scale; + if s > mx { mx = s; } + scores.push(s); + } + for p in 0..b_len { + let kv = &ks_blk[p * kv_dim + kh * hd..p * kv_dim + (kh + 1) * hd]; + let s = dot(qv, kv) * scale; + if s > mx { mx = s; } + scores.push(s); + } + let mut sum = 0.0f32; + for s in &mut scores { *s = (*s - mx).exp(); sum += *s; } + let inv = 1.0 / sum; + for (si, &s) in scores[..n_ctx].iter().enumerate() { + let w = s * inv; + let p = ctx_start + si; + let vv = &v_ctx[p * kv_dim + kh * hd..p * kv_dim + (kh + 1) * hd]; + for j in 0..hd { oh[j] += w * vv[j]; } + } + for (p, &s) in scores[n_ctx..].iter().enumerate() { + let w = s * inv; + let vv = &vs_blk[p * kv_dim + kh * hd..p * kv_dim + (kh + 1) * hd]; + for j in 0..hd { oh[j] += w * vv[j]; } + } + }); + + let arefs: Vec<&[f32]> = att.chunks_exact(nh * hd).collect(); + let mut o = matvec_rows(&dl.wo, &arefs); + if let (Some(cv), Some(dyn_w)) = (&dl.attn_conv, &attn_dyn) { + o = dflash2_conv(&o, dyn_w, &cv.base, ne, self.conv_gs, self.conv_k, b_len, 1); + } + for (xv, &ov) in x.iter_mut().zip(&o) { *xv += ov; } + + // 2. FFN norm + optional DFlash2 conv prepare + SwiGLU + conv finish + for t in 0..b_len { + rms_norm_w(&x[t * ne..(t + 1) * ne], &dl.ffn_norm, eps, &mut h[t * ne..(t + 1) * ne]); + } + let (m_in, ffn_dyn) = if let Some(cv) = &dl.ffn_conv { + let hrefs: Vec<&[f32]> = h.chunks_exact(ne).collect(); + let dyn_w = matvec_rows(&cv.proj, &hrefs); + let pre = dflash2_conv(&h, &dyn_w, &cv.base, ne, self.conv_gs, self.conv_k, b_len, 0); + (pre, Some(dyn_w)) + } else { + (h.clone(), None) + }; + let mrefs: Vec<&[f32]> = m_in.chunks_exact(ne).collect(); + let mut gy = matvec_rows(&dl.gate, &mrefs); + let uy = matvec_rows(&dl.up, &mrefs); + for (g, u) in gy.iter_mut().zip(&uy) { *g = silu(*g) * *u; } + let nf = dl.gate.rows; + let grefs: Vec<&[f32]> = gy.chunks_exact(nf).collect(); + let mut fo = matvec_rows(&dl.down, &grefs); + if let (Some(cv), Some(dyn_w)) = (&dl.ffn_conv, &ffn_dyn) { + fo = dflash2_conv(&fo, dyn_w, &cv.base, ne, self.conv_gs, self.conv_k, b_len, 1); + } + for (xv, &ov) in x.iter_mut().zip(&fo) { *xv += ov; } + } + + // 3. Final norm + shared target lm_head on draft positions [1..b_len] + let mut h_draft = vec![0.0f32; k_eff * ne]; + for i in 0..k_eff { + rms_norm_w(&x[(i + 1) * ne..(i + 2) * ne], &self.out_norm, eps, &mut h_draft[i * ne..(i + 1) * ne]); + } + let drefs: Vec<&[f32]> = h_draft.chunks_exact(ne).collect(); + let logits = target.lm_head_rows(&drefs); + let n_voc = logits.len() / k_eff; + + if let Some(sel) = &self.selector { + let h_proj = matvec_rows(&sel.hidden, &drefs); + let k_top = sel.top_k.min(n_voc).max(1); + let rank = sel.rank; + let mut pred = anchor; + let mut out_toks = Vec::with_capacity(k_eff); + let mut pred_vec = vec![0.0f32; rank]; + let mut succ_vec = vec![0.0f32; rank]; + let mut q_vec = vec![0.0f32; rank]; + let mut cands: Vec<(usize, f32)> = Vec::with_capacity(n_voc); + for pos in 0..k_eff { + let row = &logits[pos * n_voc..(pos + 1) * n_voc]; + cands.clear(); + for (idx, &v) in row.iter().enumerate() { cands.push((idx, v)); } + if cands.len() > k_top { + cands.select_nth_unstable_by(k_top - 1, |a, b| b.1.total_cmp(&a.1)); + cands.truncate(k_top); + } + sel.pred.row_into(pred as usize, &mut pred_vec); + let hp = &h_proj[pos * rank..(pos + 1) * rank]; + for r in 0..rank { q_vec[r] = pred_vec[r] * hp[r]; } + let mut best_tok = cands[0].0 as u32; + let mut best_s = f32::NEG_INFINITY; + for &(idx, u) in &cands { + sel.succ.row_into(idx, &mut succ_vec); + let s = u + dot(&q_vec, &succ_vec); + if s > best_s { + best_s = s; + best_tok = idx as u32; + } + } + pred = best_tok; + out_toks.push(pred); + } + out_toks + } else { + (0..k_eff) + .map(|i| { + let row = &logits[i * n_voc..(i + 1) * n_voc]; + crate::ops::argmax(row) as u32 + }) + .collect() + } + } +} diff --git a/src/raon/forward.rs b/src/raon/forward.rs new file mode 100644 index 00000000..356bff51 --- /dev/null +++ b/src/raon/forward.rs @@ -0,0 +1,1519 @@ +//! KRAFTON Raon-1 mini forward pass: 4-stream Raon-mHC, 18 RDA (Raon Delta Attention) layers, 7 gated NoPE MLA +//! layers, SiTU-GLU dense/MoE FFN + shared expert, and reasoning effort steering. +//! Matvecs and routed experts reuse `crate::deepseek::mat` (CPU AVX2/AVX-512 + CUDA/Vulkan/HIP GPU). +use super::RaonConfig; +use crate::deepseek::mat::{Mat, matvec_many, matvec_many_cpu, matvec_many_cpu_shared, matvec_many_opt, matvec_rows, matvec_rows_many, matvec_rows_sets, situ_experts_split, vec_f32}; +use crate::deepseek::ops::rms_norm_w; +use crate::gguf::Gguf; +use crate::quant::GgmlType; +use crate::weights::dot; +use anyhow::{Context, Result}; +use rayon::prelude::*; + +struct Hcw<'a> { + f: Mat<'a>, + base: Vec, + scale: Vec, +} + +struct RdaWeights<'a> { + wq: Mat<'a>, + wk: Mat<'a>, + wv: Mat<'a>, + q_conv: Vec, + k_conv: Vec, + v_conv: Vec, + f_a: Mat<'a>, + f_b: Mat<'a>, + beta: Mat<'a>, + rda: Mat<'a>, + ssm_a: Vec, + dt_b: Vec, + g: Mat<'a>, + o_norm: Vec, + wo: Mat<'a>, +} + +struct MlaWeights<'a> { + q_a: Mat<'a>, + q_a_norm: Vec, + q_b: Mat<'a>, + kv_a: Mat<'a>, + kv_a_norm: Vec, + k_groups: Vec>, + v_groups: Vec>, + gate: Mat<'a>, + wo: Mat<'a>, +} + +enum Attn<'a> { + Rda(RdaWeights<'a>), + Mla(MlaWeights<'a>), +} + +enum Ffn<'a> { + Dense { gate: Mat<'a>, up: Mat<'a>, down: Mat<'a> }, + Moe { + gate_inp: Mat<'a>, + bias: Vec, + gexps: Mat<'a>, + uexps: Mat<'a>, + dexps: Mat<'a>, + shared: Option<(Mat<'a>, Mat<'a>, Mat<'a>)>, + effort_steer: Option>, + }, +} + +struct Layer<'a> { + hc_attn: Hcw<'a>, + hc_ffn: Hcw<'a>, + attn_norm: Vec, + attn: Attn<'a>, + ffn_norm: Vec, + ffn: Ffn<'a>, +} + +/// Recurrent state for one RDA layer: rolling 3-token Q/K/V conv windows + `[n_head][head_dim][head_dim]` V-first state. +#[derive(Clone)] +struct RdaState { + q_hist: Vec, + k_hist: Vec, + v_hist: Vec, + state: Vec, +} + +impl RdaState { + fn new(n_head: usize, hd: usize, d_conv: usize) -> Self { + let d_inner = n_head * hd; + let hlen = (d_conv - 1) * d_inner; + Self { + q_hist: vec![0.0; hlen], + k_hist: vec![0.0; hlen], + v_hist: vec![0.0; hlen], + state: vec![0.0; n_head * hd * hd], + } + } + + fn clear(&mut self) { + self.q_hist.fill(0.0); + self.k_hist.fill(0.0); + self.v_hist.fill(0.0); + self.state.fill(0.0); + } +} + +pub struct RaonModel<'a> { + pub cfg: RaonConfig, + tok_embd: Mat<'a>, + out_norm: Vec, + out_w: Mat<'a>, + layers: Vec>, + helmert: Vec, + chart_base: Vec, + /// One `RdaState` per layer (`Some` for RDA layers, `None` for MLA layers). + rda_states: Vec>, + /// One KV cache per layer (`[pos][kv_lora_rank + qk_rope_hd]` for MLA layers, empty for RDA layers). + mla_keys: Vec>, + /// Active reasoning effort steering alpha (`0.0` disables steering). + pub effort_alpha: f32, + pub toks: Vec, + capture_layers: Vec, + pending_feats: Vec>, + /// Pre-allocated per-token RDA snapshots reused across `verify_greedy` calls (zero malloc/page-fault churn). + rda_snap_pool: Vec>>, + pub trace: bool, +} + +fn host_mat<'a>(g: &'a Gguf, name: &str) -> Result> { + let t = g.tensors.get(name).with_context(|| format!("missing tensor {name}"))?; + Ok(Mat { data: g.bytes(t), ty: GgmlType::from_u32(t.ty)?, rows: t.dims[1] as usize, cols: t.dims[0] as usize, cpu: false, gpu: None, scale: 1.0 }) +} + +#[inline] +fn sigmoid(x: f32) -> f32 { 1.0 / (1.0 + (-x).exp()) } + +#[inline] +fn silu(x: f32) -> f32 { x * sigmoid(x) } + +#[inline] +fn softplus(x: f32) -> f32 { + if x > 20.0 { x } else if x < -20.0 { x.exp() } else { (1.0 + x.exp()).ln() } +} + +/// SiTU-GLU: `(gate_beta * tanh(g / gate_beta) * sigmoid(g)) * (value_beta * tanh(v / value_beta))`. +#[inline] +pub fn situ_glu(g: f32, v: f32, gate_beta: f32, value_beta: f32) -> f32 { + (gate_beta * (g / gate_beta).tanh() * sigmoid(g)) * (value_beta * (v / value_beta).tanh()) +} + +/// Orthonormal Helmert basis `Q` in `R^{n x (n-1)}` (row-major `[n][n-1]`). +pub fn helmert_basis(n: usize) -> Vec { + let nm = n - 1; + let mut q = vec![0.0f32; n * nm]; + for k in 1..n { + let inv = 1.0 / ((k * (k + 1)) as f32).sqrt(); + for i in 0..k { + q[i * nm + (k - 1)] = inv; + } + q[k * nm + (k - 1)] = -(k as f32) * inv; + } + q +} + +/// Chart base `B = 0.5 * (I + 11^T / n)` (row-major `[n][n]`). +fn chart_base_mat(n: usize) -> Vec { + let mut b = vec![0.5 / n as f32; n * n]; + for i in 0..n { + b[i * n + i] += 0.5; + } + b +} + +/// Compute Raon-mHC `(h_pre [hc], h_post [hc], h_res [hc*hc])` from `mixes = (fn @ flat) / rms`. +pub fn raon_mhc_coeffs( + mixes: &[f32], base: &[f32], scale: &[f32], hc: usize, hc_mag: f32, helmert: &[f32], chart_base: &[f32], +) -> (Vec, Vec, Vec) { + let nm = hc - 1; + let mut pre = vec![0.0f32; hc]; + let mut post = vec![0.0f32; hc]; + for i in 0..hc { + pre[i] = sigmoid(mixes[i] * scale[0] + base[i]); + post[i] = hc_mag * sigmoid(mixes[hc + i] * scale[1] + base[hc + i]); + } + let mut z = vec![0.0f32; nm * nm]; + for i in 0..nm * nm { + z[i] = mixes[2 * hc + i] * scale[2] + base[2 * hc + i]; + } + // tmp = Q @ Z ([hc, nm]), e = tmp @ Q^T ([hc, hc]) + let mut tmp = vec![0.0f32; hc * nm]; + for i in 0..hc { + for j in 0..nm { + let mut s = 0.0f32; + for m in 0..nm { s += helmert[i * nm + m] * z[m * nm + j]; } + tmp[i * nm + j] = s; + } + } + let mut e = vec![0.0f32; hc * hc]; + let mut max_ratio = 0.0f32; + for i in 0..hc { + for j in 0..hc { + let mut s = 0.0f32; + for m in 0..nm { s += tmp[i * nm + m] * helmert[j * nm + m]; } + e[i * hc + j] = s; + let r = -s / chart_base[i * hc + j]; + if r > max_ratio { max_ratio = r; } + } + } + let inv_rho = 1.0 / (1.0 + max_ratio); + let gamma = sigmoid(scale[3]); + let mut h_res = vec![0.0f32; hc * hc]; + for i in 0..hc { + for j in 0..hc { + let phi = chart_base[i * hc + j] + e[i * hc + j] * inv_rho; + let eye = if i == j { 1.0 } else { 0.0 }; + h_res[i * hc + j] = eye + gamma * (phi - eye); + } + } + (pre, post, h_res) +} + +/// Depthwise causal conv1d (kernel 4) + SiLU for one token, advancing the 3-token rolling history `[3, d_inner]`. +/// `w` is stored channel-major `[d_inner, 4]` (GGUF `{4, 1, d_inner, 1}`). +fn conv1d_step_silu(x: &[f32], hist: &mut [f32], w: &[f32], d_inner: usize) -> Vec { + let mut out = vec![0.0f32; d_inner]; + for c in 0..d_inner { + let wc = &w[c * 4..c * 4 + 4]; + let h0 = hist[c]; + let h1 = hist[d_inner + c]; + let h2 = hist[2 * d_inner + c]; + let x0 = x[c]; + let y = h0 * wc[0] + h1 * wc[1] + h2 * wc[2] + x0 * wc[3]; + hist[c] = h1; + hist[d_inner + c] = h2; + hist[2 * d_inner + c] = x0; + out[c] = silu(y); + } + out +} + +/// Single-token V-first RDA recurrence across all heads (`state`: `[n_head][hd][hd]`, row-major `[v][k]`). +pub fn rda_recurrent_step( + q: &[f32], k: &[f32], v: &[f32], log_alpha: &[f32], beta: &[f32], + state: &mut [f32], n_head: usize, hd: usize, +) -> Vec { + let mut out = vec![0.0f32; n_head * hd]; + out.par_chunks_mut(hd) + .zip(state.par_chunks_mut(hd * hd)) + .enumerate() + .for_each(|(h, (oh, sh))| { + let qh = &q[h * hd..(h + 1) * hd]; + let kh = &k[h * hd..(h + 1) * hd]; + let vh = &v[h * hd..(h + 1) * hd]; + let lh = &log_alpha[h * hd..(h + 1) * hd]; + let bh = beta[h]; + let mut dec = [0.0f32; 128]; + for j in 0..hd { dec[j] = lh[j].exp(); } + for vi in 0..hd { + let row = &mut sh[vi * hd..(vi + 1) * hd]; + let mut pred = 0.0f32; + for ki in 0..hd { + let s = row[ki] * dec[ki]; + row[ki] = s; + pred += s * kh[ki]; + } + let err = bh * (vh[vi] - pred); + let mut o = 0.0f32; + for ki in 0..hd { + let s = row[ki] + err * kh[ki]; + row[ki] = s; + o += s * qh[ki]; + } + oh[vi] = o; + } + }); + out +} + +/// Sigmoid router with selection-only bias and optional renormalization. +pub fn route(logits: &[f32], bias: &[f32], top_k: usize, renorm: bool, scale: f32) -> Vec<(usize, f32)> { + let probs: Vec = logits.iter().map(|&v| sigmoid(v)).collect(); + let mut sel: Vec = (0..probs.len()).collect(); + sel.sort_by(|&a, &b| (probs[b] + bias[b]).total_cmp(&(probs[a] + bias[a]))); + sel.truncate(top_k); + let mut out: Vec<(usize, f32)> = sel.into_iter().map(|e| (e, probs[e])).collect(); + if renorm { + let sum: f32 = out.iter().map(|(_, w)| *w).sum::() + 1e-20; + for (_, w) in &mut out { *w /= sum; } + } + if scale != 1.0 && scale != 0.0 { + for (_, w) in &mut out { *w *= scale; } + } + out +} + +fn run_experts_gpu(list: &[(Mat, Mat, Mat, f32)], x: &[f32], gate_beta: f32, value_beta: f32, n: usize) -> Vec { + let mut mix = vec![0.0f32; n]; + let Some(first) = list.first() else { return mix }; + let (k, nf) = (list.len(), first.0.rows); + let gs: Vec = list.iter().map(|e| e.0).collect(); + let us: Vec = list.iter().map(|e| e.1).collect(); + let ds: Vec = list.iter().map(|e| e.2).collect(); + let dy = situ_experts_split(&gs, &us, &ds, x, gate_beta, value_beta).or_else(|| { + let gu: Vec = gs.into_iter().chain(us).collect(); + let y = matvec_many_opt(&gu, x, 0)?; + let a: Vec = (0..k * nf).map(|i| situ_glu(y[i], y[k * nf + i], gate_beta, value_beta)).collect(); + matvec_many_opt(&ds, &a, nf) + }); + if let Some(dy) = dy { + for (i, e) in list.iter().enumerate() { + for j in 0..n { mix[j] += e.3 * dy[i * n + j]; } + } + } else { + return run_experts_cpu(list, x, gate_beta, value_beta, n); + } + mix +} + +fn run_experts_cpu(list: &[(Mat, Mat, Mat, f32)], x: &[f32], gate_beta: f32, value_beta: f32, n: usize) -> Vec { + let mut mix = vec![0.0f32; n]; + let Some(first) = list.first() else { return mix }; + let (k, nf) = (list.len(), first.0.rows); + let gu: Vec = list.iter().map(|e| e.0).chain(list.iter().map(|e| e.1)).collect(); + let ds: Vec = list.iter().map(|e| e.2).collect(); + if let Some(y) = matvec_many_cpu_shared(&gu, x) { + let a: Vec = (0..k * nf).map(|i| situ_glu(y[i], y[k * nf + i], gate_beta, value_beta)).collect(); + let xs: Vec<&[f32]> = a.chunks_exact(nf).collect(); + if let Some(dy) = matvec_many_cpu(&ds, &xs) { + for (i, e) in list.iter().enumerate() { + for j in 0..n { mix[j] += e.3 * dy[i * n + j]; } + } + return mix; + } + } + let (mut gy, mut uy, mut dy) = (vec![0.0f32; nf], vec![0.0f32; nf], vec![0.0f32; n]); + for (g, u, d, w) in list { + g.matvec(x, &mut gy); + u.matvec(x, &mut uy); + for (gv, uv) in gy.iter_mut().zip(&uy) { *gv = situ_glu(*gv, *uv, gate_beta, value_beta); } + d.matvec(&gy, &mut dy); + for j in 0..n { mix[j] += w * dy[j]; } + } + mix +} + +fn run_experts(list: &[(Mat, Mat, Mat, f32)], x: &[f32], gate_beta: f32, value_beta: f32, n: usize) -> Vec { + let (mut gpu_list, mut cpu_list) = (Vec::with_capacity(list.len()), Vec::new()); + for &e in list { + if e.0.gpu.is_some() && e.1.gpu.is_some() && e.2.gpu.is_some() { + gpu_list.push(e); + } else { + cpu_list.push(e); + } + } + match (gpu_list.is_empty(), cpu_list.is_empty()) { + (true, true) => vec![0.0f32; n], + (false, true) => run_experts_gpu(&gpu_list, x, gate_beta, value_beta, n), + (true, false) => run_experts_cpu(&cpu_list, x, gate_beta, value_beta, n), + (false, false) => { + let (mut g, c) = rayon::join( + || run_experts_gpu(&gpu_list, x, gate_beta, value_beta, n), + || run_experts_cpu(&cpu_list, x, gate_beta, value_beta, n), + ); + for j in 0..n { g[j] += c[j]; } + g + } + } +} + +impl<'a> RaonModel<'a> { + pub fn new(g: &'a Gguf) -> Result { + let cfg = RaonConfig::from_gguf(g)?; + let hcw = |p: &str| -> Result> { + Ok(Hcw { + // Tiny [10240, 17] BF16 hyper-connection projections: faster on CPU (0.07 ms, zero GPU syncs). + f: Mat::load_host(g, &format!("{p}_fn.weight"))?, + base: vec_f32(g, &format!("{p}_base.weight"))?, + scale: vec_f32(g, &format!("{p}_scale.weight"))?, + }) + }; + let mut layers = Vec::with_capacity(cfg.n_layer); + for il in 0..cfg.n_layer { + let m = |s: &str| Mat::load(g, &format!("blk.{il}.{s}.weight")); + let hm = |s: &str| Mat::load_host(g, &format!("blk.{il}.{s}.weight")); + let v = |s: &str| vec_f32(g, &format!("blk.{il}.{s}.weight")); + let attn = if cfg.is_rda[il] { + Attn::Rda(RdaWeights { + wq: m("attn_q")?, + wk: m("attn_k")?, + wv: m("attn_v")?, + q_conv: v("ssm_conv1d_q")?, + k_conv: v("ssm_conv1d_k")?, + v_conv: v("ssm_conv1d_v")?, + // Tiny BF16 scalar/low-rank gating projections: run on CPU concurrently with GPU Q/K/V/G. + f_a: hm("ssm_f_a")?, + f_b: hm("ssm_f_b")?, + beta: hm("ssm_beta")?, + rda: hm("ssm_rda")?, + ssm_a: vec_f32(g, &format!("blk.{il}.ssm_a"))?, + dt_b: vec_f32(g, &format!("blk.{il}.ssm_dt.bias"))?, + g: m("ssm_g")?, + o_norm: v("ssm_norm")?, + wo: m("attn_output")?, + }) + } else { + let k_b = Mat::load_groups(g, &format!("blk.{il}.attn_k_b.weight"), cfg.n_head)?; + let v_b = Mat::load_groups(g, &format!("blk.{il}.attn_v_b.weight"), cfg.n_head)?; + let k_groups = (0..cfg.n_head).map(|h| k_b.group(h, cfg.n_head)).collect(); + let v_groups = (0..cfg.n_head).map(|h| v_b.group(h, cfg.n_head)).collect(); + Attn::Mla(MlaWeights { + q_a: m("attn_q_a")?, + q_a_norm: v("attn_q_a_norm")?, + q_b: m("attn_q_b")?, + kv_a: m("attn_kv_a_mqa")?, + kv_a_norm: v("attn_kv_a_norm")?, + k_groups, + v_groups, + gate: m("attn_gate")?, + wo: m("attn_output")?, + }) + }; + let ffn = if il < cfg.n_dense { + Ffn::Dense { gate: m("ffn_gate")?, up: m("ffn_up")?, down: m("ffn_down")? } + } else { + let shared = if cfg.n_shared > 0 { + Some((m("ffn_gate_shexp")?, m("ffn_up_shexp")?, m("ffn_down_shexp")?)) + } else { + None + }; + let effort_steer = if cfg.effort_layers[il] { + Some(v("ffn_effort_steer")?) + } else { + None + }; + Ffn::Moe { + // Tiny [2560, 128] F32 router: 0.04 ms on CPU, avoids 24 GPU round-trips/token. + gate_inp: hm("ffn_gate_inp")?, + bias: vec_f32(g, &format!("blk.{il}.exp_probs_b.bias"))?, + gexps: m("ffn_gate_exps")?, + uexps: m("ffn_up_exps")?, + dexps: m("ffn_down_exps")?, + shared, + effort_steer, + } + }; + layers.push(Layer { + hc_attn: hcw(&format!("blk.{il}.hc_attn"))?, + hc_ffn: hcw(&format!("blk.{il}.hc_ffn"))?, + attn_norm: v("attn_norm")?, + attn, + ffn_norm: v("ffn_norm")?, + ffn, + }); + } + let rda_states = (0..cfg.n_layer) + .map(|il| cfg.is_rda[il].then(|| RdaState::new(cfg.n_head, cfg.rda_hd, cfg.d_conv))) + .collect(); + let effort_alpha = cfg.effort_alpha_for(None, true); + let (helmert, chart_base) = (helmert_basis(cfg.hc), chart_base_mat(cfg.hc)); + Ok(RaonModel { + tok_embd: host_mat(g, "token_embd.weight")?, + out_norm: vec_f32(g, "output_norm.weight")?, + out_w: Mat::load(g, "output.weight")?, + mla_keys: vec![Vec::new(); cfg.n_layer], + rda_states, + layers, + helmert, + chart_base, + effort_alpha, + toks: Vec::new(), + capture_layers: Vec::new(), + pending_feats: Vec::new(), + rda_snap_pool: Vec::new(), + trace: std::env::var_os("STRATA_DS_TRACE").is_some(), + cfg, + }) + } + + pub fn set_capture_layers(&mut self, layers: Vec) { + self.capture_layers = layers; + self.pending_feats.clear(); + } + + pub fn take_pending_feats(&mut self) -> Vec> { + std::mem::take(&mut self.pending_feats) + } + + pub fn embed_tok(&self, tok: u32, out: &mut [f32]) { + self.tok_embd.row_into(tok as usize, out); + } + + pub fn lm_head_rows(&self, xs: &[&[f32]]) -> Vec { + matvec_rows(&self.out_w, xs) + } + + pub fn reset(&mut self) { + for s in self.rda_states.iter_mut().flatten() { s.clear(); } + for k in &mut self.mla_keys { k.clear(); } + self.toks.clear(); + self.pending_feats.clear(); + } + + pub fn set_effort(&mut self, effort: Option<&str>, think: bool) { + let next = self.cfg.effort_alpha_for(effort, think); + if (next - self.effort_alpha).abs() > 1e-6 && !self.toks.is_empty() { + // Prefix KV/RDA states were built under a different steering alpha; invalidate cache. + self.reset(); + } + self.effort_alpha = next; + } + + fn hc_pre(&self, flat: &[f32], hc_w: &Hcw) -> (Vec, Vec, Vec) { + let (hc, n) = (self.cfg.hc, self.cfg.n_embd); + let inv = 1.0 / (flat.iter().map(|&v| v * v).sum::() / flat.len() as f32 + self.cfg.hc_eps).sqrt(); + let mut mixes = vec![0.0f32; hc_w.f.rows]; + hc_w.f.matvec(flat, &mut mixes); + for v in &mut mixes { *v *= inv; } + let (pre, post, h_res) = raon_mhc_coeffs(&mixes, &hc_w.base, &hc_w.scale, hc, self.cfg.hc_mag, &self.helmert, &self.chart_base); + let mut cur = vec![0.0f32; n]; + for s in 0..hc { + let w = pre[s]; + for j in 0..n { cur[j] += w * flat[s * n + j]; } + } + (cur, post, h_res) + } + + fn hc_post(&self, flat: &mut [f32], branch: &[f32], post: &[f32], h_res: &[f32]) { + let (hc, n) = (self.cfg.hc, self.cfg.n_embd); + if hc <= 8 { + let mut col = [0.0f32; 8]; + for j in 0..n { + for src in 0..hc { col[src] = flat[src * n + j]; } + let bj = branch[j]; + for dst in 0..hc { + let mut s = post[dst] * bj; + let row = &h_res[dst * hc..(dst + 1) * hc]; + for src in 0..hc { s += row[src] * col[src]; } + flat[dst * n + j] = s; + } + } + } else { + let old = flat.to_vec(); + for dst in 0..hc { + let out = &mut flat[dst * n..(dst + 1) * n]; + let p = post[dst]; + for j in 0..n { + let mut s = p * branch[j]; + for src in 0..hc { s += h_res[dst * hc + src] * old[src * n + j]; } + out[j] = s; + } + } + } + } + + fn rda_step(&mut self, il: usize, cur: &[f32]) -> Vec { + let Attn::Rda(r) = &self.layers[il].attn else { unreachable!() }; + let (nh, hd) = (self.cfg.n_head, self.cfg.rda_hd); + let d_inner = nh * hd; + // Run heavy Q/K/V/G on GPU (or 1-shot CPU) while tiny BF16 beta/rda/f_a/f_b overlap on CPU. + let (qkvg, (beta_raw, rda_delta, mut decay)) = rayon::join( + || matvec_many(&[r.wq, r.wk, r.wv, r.g], cur, 0), + || { + let mut br = vec![0.0f32; r.beta.rows]; + let mut dr = vec![0.0f32; r.rda.rows]; + let mut fa = vec![0.0f32; r.f_a.rows]; + let mut fb = vec![0.0f32; r.f_b.rows]; + r.beta.matvec(cur, &mut br); + r.rda.matvec(cur, &mut dr); + r.f_a.matvec(cur, &mut fa); + r.f_b.matvec(&fa, &mut fb); + (br, dr, fb) + }, + ); + let (o1, o2, o3) = (d_inner, 2 * d_inner, 3 * d_inner); + let (q_proj, k_proj, v_proj, gate) = (&qkvg[..o1], &qkvg[o1..o2], &qkvg[o2..o3], &qkvg[o3..]); + for (d, &b) in decay.iter_mut().zip(&r.dt_b) { *d += b; } + + let st = self.rda_states[il].as_mut().unwrap(); + let q_scale = 1.0 / (hd as f32).sqrt(); + let glb = self.cfg.gate_lower_bound; + let eps = self.cfg.eps; + let mut gated = vec![0.0f32; d_inner]; + // Fused per-head parallel pass: depthwise conv1d+SiLU, L2-norm, decay/ratio, V-first delta-rule recurrence, + // RMSNorm + output sigmoid gate — keeps each head's vectors hot in L1 with zero intermediate Vec allocations. + let (qh0, qh12) = st.q_hist.split_at_mut(d_inner); + let (qh1, qh2) = qh12.split_at_mut(d_inner); + let (kh0, kh12) = st.k_hist.split_at_mut(d_inner); + let (kh1, kh2) = kh12.split_at_mut(d_inner); + let (vh0, vh12) = st.v_hist.split_at_mut(d_inner); + let (vh1, vh2) = vh12.split_at_mut(d_inner); + gated.par_chunks_mut(hd) + .zip(st.state.par_chunks_mut(hd * hd)) + .zip(qh0.par_chunks_mut(hd).zip(qh1.par_chunks_mut(hd)).zip(qh2.par_chunks_mut(hd))) + .zip(kh0.par_chunks_mut(hd).zip(kh1.par_chunks_mut(hd)).zip(kh2.par_chunks_mut(hd))) + .zip(vh0.par_chunks_mut(hd).zip(vh1.par_chunks_mut(hd)).zip(vh2.par_chunks_mut(hd))) + .enumerate() + .for_each(|(h, ((((gh, sh), ((q0, q1), q2)), ((k0, k1), k2)), ((v0, v1), v2)))| { + let off = h * hd; + let mut q = [0.0f32; 128]; + let mut k = [0.0f32; 128]; + let mut v = [0.0f32; 128]; + let mut dec = [0.0f32; 128]; + let mut qn2 = 0.0f32; + let mut kn2 = 0.0f32; + let exp_a = -r.ssm_a[h]; + let br = beta_raw[h]; + let dr = rda_delta[h]; + let ratio = (softplus(-br) - softplus(-(br + dr))).exp(); + let bh = sigmoid(br); + for j in 0..hd { + let c = off + j; + let wq = &r.q_conv[c * 4..c * 4 + 4]; + let qx = q_proj[c]; + let qv = silu(q0[j] * wq[0] + q1[j] * wq[1] + q2[j] * wq[2] + qx * wq[3]); + q0[j] = q1[j]; q1[j] = q2[j]; q2[j] = qx; + q[j] = qv; qn2 += qv * qv; + + let wk = &r.k_conv[c * 4..c * 4 + 4]; + let kx = k_proj[c]; + let kv = silu(k0[j] * wk[0] + k1[j] * wk[1] + k2[j] * wk[2] + kx * wk[3]); + k0[j] = k1[j]; k1[j] = k2[j]; k2[j] = kx; + k[j] = kv; kn2 += kv * kv; + + let wv = &r.v_conv[c * 4..c * 4 + 4]; + let vx = v_proj[c]; + let vv = silu(v0[j] * wv[0] + v1[j] * wv[1] + v2[j] * wv[2] + vx * wv[3]); + v0[j] = v1[j]; v1[j] = v2[j]; v2[j] = vx; + v[j] = vv * ratio; + + let scaled = exp_a * decay[c]; + let la = match glb { + Some(lb) => lb * sigmoid(scaled), + None => -softplus(scaled), + }; + dec[j] = la.exp(); + } + let qf = q_scale / qn2.sqrt().max(1e-6); + let kf = 1.0 / kn2.sqrt().max(1e-6); + for j in 0..hd { q[j] *= qf; k[j] *= kf; } + + let mut out_h = [0.0f32; 128]; + let mut ss = 0.0f32; + for vi in 0..hd { + let row = &mut sh[vi * hd..(vi + 1) * hd]; + let mut pred = 0.0f32; + for ki in 0..hd { + let s = row[ki] * dec[ki]; + row[ki] = s; + pred += s * k[ki]; + } + let err = bh * (v[vi] - pred); + let mut o = 0.0f32; + for ki in 0..hd { + let s = row[ki] + err * k[ki]; + row[ki] = s; + o += s * q[ki]; + } + out_h[vi] = o; + ss += o * o; + } + let inv = 1.0 / (ss / hd as f32 + eps).sqrt(); + for j in 0..hd { + gh[j] = out_h[j] * inv * r.o_norm[j] * sigmoid(gate[off + j]); + } + }); + let mut y = vec![0.0f32; self.cfg.n_embd]; + r.wo.matvec(&gated, &mut y); + y + } + + fn mla_step(&mut self, il: usize, cur: &[f32]) -> Vec { + let Attn::Mla(a) = &self.layers[il].attn else { unreachable!() }; + let (nh, kr, nr, kl) = (self.cfg.n_head, self.cfg.kv_lora_rank, self.cfg.qk_rope_hd, self.cfg.mla_key_len); + let nope = kl - nr; + let kw = kr + nr; + + let proj = matvec_many(&[a.q_a, a.kv_a, a.gate], cur, 0); + let q_rank = self.cfg.q_lora_rank; + let (qr_raw, kv, g) = (&proj[..q_rank], &proj[q_rank..q_rank + kw], &proj[q_rank + kw..]); + let mut qr = vec![0.0f32; q_rank]; + rms_norm_w(qr_raw, &a.q_a_norm, self.cfg.latent_eps, &mut qr); + let mut q = vec![0.0f32; nh * kl]; + a.q_b.matvec(&qr, &mut q); + + let mut krow = vec![0.0f32; kw]; + rms_norm_w(&kv[..kr], &a.kv_a_norm, self.cfg.latent_eps, &mut krow[..kr]); + krow[kr..].copy_from_slice(&kv[kr..]); + self.mla_keys[il].extend_from_slice(&krow); + + let qn = matvec_many(&a.k_groups, &q, kl); + let scale = 1.0 / (kl as f32).sqrt(); + let all_k = &self.mla_keys[il]; + let n_pos = all_k.len() / kw; + + let mut att = vec![0.0f32; nh * kr]; + att.par_chunks_mut(kr).enumerate().for_each(|(h, oh)| { + let qnh = &qn[h * kr..(h + 1) * kr]; + let qeh = &q[h * kl + nope..(h + 1) * kl]; + let mut scores = Vec::with_capacity(n_pos); + let mut mx = f32::NEG_INFINITY; + for p in 0..n_pos { + let row = &all_k[p * kw..(p + 1) * kw]; + let s = (dot(qnh, &row[..kr]) + dot(qeh, &row[kr..])) * scale; + if s > mx { mx = s; } + scores.push(s); + } + let mut sum = 0.0f32; + for s in &mut scores { *s = (*s - mx).exp(); sum += *s; } + let inv = 1.0 / sum; + for (p, &s) in scores.iter().enumerate() { + let w = s * inv; + let lat = &all_k[p * kw..p * kw + kr]; + for j in 0..kr { oh[j] += w * lat[j]; } + } + }); + + let mut out = matvec_many(&a.v_groups, &att, kr); + for (o, &gv) in out.iter_mut().zip(g) { *o *= sigmoid(gv); } + let mut y = vec![0.0f32; self.cfg.n_embd]; + a.wo.matvec(&out, &mut y); + y + } + + fn ffn_step(&self, il: usize, cur: &[f32]) -> Vec { + let (n, gb, vb) = (self.cfg.n_embd, self.cfg.situ_beta, self.cfg.situ_linear_beta); + match &self.layers[il].ffn { + Ffn::Dense { gate, up, down } => { + if let Some(y) = situ_experts_split(&[*gate], &[*up], &[*down], cur, gb, vb) { + return y; + } + let nf = gate.rows; + let gu = matvec_many(&[*gate, *up], cur, 0); + let mut gy = vec![0.0f32; nf]; + for i in 0..nf { gy[i] = situ_glu(gu[i], gu[nf + i], gb, vb); } + let mut y = vec![0.0f32; n]; + down.matvec(&gy, &mut y); + y + } + Ffn::Moe { gate_inp, bias, gexps, uexps, dexps, shared, effort_steer } => { + let exp_nf = gexps.rows / self.cfg.n_expert; + let fold_shared = shared.is_some_and(|(sg, _, _)| sg.rows == exp_nf); + let (logits, shared_gu) = if !fold_shared && let Some((sg, su, _)) = shared { + let all = matvec_many(&[*gate_inp, *sg, *su], cur, 0); + let r = gate_inp.rows; + (all[..r].to_vec(), Some(all[r..].to_vec())) + } else { + let mut logits = vec![0.0f32; gate_inp.rows]; + gate_inp.matvec(cur, &mut logits); + (logits, None) + }; + let sel = route(&logits, bias, self.cfg.n_used, self.cfg.exp_norm, self.cfg.exp_scale); + let evict = std::env::var_os("STRATA_RAON_EVICT").is_some(); + let mut list: Vec<(Mat, Mat, Mat, f32)> = sel.into_iter() + .map(|(e, w)| ( + gexps.expert_opt(e, self.cfg.n_expert, evict), + uexps.expert_opt(e, self.cfg.n_expert, evict), + dexps.expert_opt(e, self.cfg.n_expert, evict), + w, + )) + .collect(); + if fold_shared && let Some((sg, su, sd)) = shared { + list.push((*sg, *su, *sd, 1.0)); + } + let mut y = run_experts(&list, cur, gb, vb, n); + if !fold_shared && let Some((sg, _, sd)) = shared { + let nf = sg.rows; + let gu = shared_gu.unwrap(); + let mut gy = vec![0.0f32; nf]; + for i in 0..nf { gy[i] = situ_glu(gu[i], gu[nf + i], gb, vb); } + let mut sy = vec![0.0f32; n]; + sd.matvec(&gy, &mut sy); + for j in 0..n { y[j] += sy[j]; } + } + if self.effort_alpha != 0.0 + && let Some(steer) = effort_steer + { + let a = self.effort_alpha; + for j in 0..n { y[j] += a * steer[j]; } + } + y + } + } + } + + fn step_opt(&mut self, tok: u32, want_logits: bool) -> Vec { + let (n, hc) = (self.cfg.n_embd, self.cfg.hc); + self.toks.push(tok); + let mut emb = vec![0.0f32; n]; + self.tok_embd.row_into(tok as usize, &mut emb); + let mut flat = emb.repeat(hc); + let mut normed = vec![0.0f32; n]; + + let prof = std::env::var_os("STRATA_RAON_PROF").is_some(); + let (mut t_hc, mut t_rda, mut t_mla, mut t_ffn) = (0.0f64, 0.0f64, 0.0f64, 0.0f64); + let mut feat = if self.capture_layers.is_empty() { + Vec::new() + } else { + Vec::with_capacity(self.capture_layers.len() * flat.len()) + }; + for il in 0..self.cfg.n_layer { + let t0 = std::time::Instant::now(); + let (cur, post, h_res) = self.hc_pre(&flat, &self.layers[il].hc_attn); + rms_norm_w(&cur, &self.layers[il].attn_norm, self.cfg.eps, &mut normed); + let t1 = std::time::Instant::now(); + let attn_out = if self.cfg.is_rda[il] { + let y = self.rda_step(il, &normed); + t_rda += t1.elapsed().as_secs_f64() * 1e3; + y + } else { + let y = self.mla_step(il, &normed); + t_mla += t1.elapsed().as_secs_f64() * 1e3; + y + }; + let t2 = std::time::Instant::now(); + self.hc_post(&mut flat, &attn_out, &post, &h_res); + + let (cur, post, h_res) = self.hc_pre(&flat, &self.layers[il].hc_ffn); + rms_norm_w(&cur, &self.layers[il].ffn_norm, self.cfg.eps, &mut normed); + let t3 = std::time::Instant::now(); + let ffn_out = self.ffn_step(il, &normed); + t_ffn += t3.elapsed().as_secs_f64() * 1e3; + let t4 = std::time::Instant::now(); + self.hc_post(&mut flat, &ffn_out, &post, &h_res); + if self.capture_layers.contains(&il) { + feat.extend_from_slice(&flat); + } + t_hc += (t1.duration_since(t0) + t3.duration_since(t2) + t4.elapsed()).as_secs_f64() * 1e3; + } + if !self.capture_layers.is_empty() { + self.pending_feats.push(feat); + } + + if !want_logits { + return Vec::new(); + } + let t_out0 = std::time::Instant::now(); + let inv_hc = 1.0 / hc as f32; + let mut cur = vec![0.0f32; n]; + for s in 0..hc { + for j in 0..n { cur[j] += flat[s * n + j] * inv_hc; } + } + rms_norm_w(&cur, &self.out_norm, self.cfg.eps, &mut normed); + let mut logits = vec![0.0f32; self.out_w.rows]; + self.out_w.matvec(&normed, &mut logits); + if prof { + let t_out = t_out0.elapsed().as_secs_f64() * 1e3; + eprintln!("raon prof (ms): hc={t_hc:.1} rda={t_rda:.1} mla={t_mla:.1} ffn={t_ffn:.1} out={t_out:.1} total={:.1}", t_hc + t_rda + t_mla + t_ffn + t_out); + } + logits + } + + pub fn step(&mut self, tok: u32) -> Vec { + self.step_opt(tok, true) + } + + fn prefill_chunk(&mut self, toks: &[u32]) { + self.prefill_chunk_opt(toks, false); + } + + fn prefill_chunk_opt(&mut self, toks: &[u32], capture_snaps: bool) -> Option>> { + let (nt, n, hc) = (toks.len(), self.cfg.n_embd, self.cfg.hc); + if nt == 0 { return None; } + let p0 = self.toks.len(); + self.toks.extend_from_slice(toks); + if capture_snaps && self.rda_snap_pool.len() < nt { + let nl = self.cfg.n_layer; + while self.rda_snap_pool.len() < nt { + let row = (0..nl) + .map(|il| self.cfg.is_rda[il].then(|| RdaState::new(self.cfg.n_head, self.cfg.rda_hd, self.cfg.d_conv))) + .collect(); + self.rda_snap_pool.push(row); + } + } + let mut chunk_feats: Vec> = if self.capture_layers.is_empty() { + Vec::new() + } else { + (0..nt).map(|_| Vec::with_capacity(self.capture_layers.len() * hc * n)).collect() + }; + + let mut flats: Vec> = toks.iter().map(|&t| { + let mut emb = vec![0.0f32; n]; + self.tok_embd.row_into(t as usize, &mut emb); + emb.repeat(hc) + }).collect(); + + let grouped = |gs: &[Mat<'a>], x: &[f32], nh: usize, w: usize| -> Vec { + if nt < nh { + return x.chunks_exact(nh * w).flat_map(|xt| matvec_many(gs, xt, w)).collect(); + } + let r = gs[0].rows; + let mut y = vec![0.0f32; nt * nh * r]; + for (h, g) in gs.iter().enumerate() { + let rows_h: Vec<&[f32]> = x.chunks_exact(nh * w).map(|xt| &xt[h * w..][..g.cols]).collect(); + let yh = matvec_rows(g, &rows_h); + for (t, yt) in yh.chunks_exact(r).enumerate() { + y[(t * nh + h) * r..][..r].copy_from_slice(yt); + } + } + y + }; + + for il in 0..self.cfg.n_layer { + // 1. Batched hc_attn pre + attn_norm + let flat_refs: Vec<&[f32]> = flats.iter().map(Vec::as_slice).collect(); + let hc_mix_all = matvec_rows(&self.layers[il].hc_attn.f, &flat_refs); + let mix_w = self.layers[il].hc_attn.f.rows; + let mut posts = Vec::with_capacity(nt); + let mut h_ress = Vec::with_capacity(nt); + let mut normed_flat = vec![0.0f32; nt * n]; + for t in 0..nt { + let flat = &flats[t]; + let inv = 1.0 / (flat.iter().map(|&v| v * v).sum::() / flat.len() as f32 + self.cfg.hc_eps).sqrt(); + let mixes: Vec = hc_mix_all[t * mix_w..(t + 1) * mix_w].iter().map(|&v| v * inv).collect(); + let (pre, post, h_res) = raon_mhc_coeffs( + &mixes, &self.layers[il].hc_attn.base, &self.layers[il].hc_attn.scale, + hc, self.cfg.hc_mag, &self.helmert, &self.chart_base, + ); + let mut cur = vec![0.0f32; n]; + for s in 0..hc { + let w = pre[s]; + for j in 0..n { cur[j] += w * flat[s * n + j]; } + } + rms_norm_w(&cur, &self.layers[il].attn_norm, self.cfg.eps, &mut normed_flat[t * n..(t + 1) * n]); + posts.push(post); + h_ress.push(h_res); + } + + // 2. Attention (batched RDA or batched MLA) + let attn_out_all = match &self.layers[il].attn { + Attn::Rda(r) => { + let (nh, hd) = (self.cfg.n_head, self.cfg.rda_hd); + let d_inner = nh * hd; + let nrefs: Vec<&[f32]> = normed_flat.chunks_exact(n).collect(); + let (qkvg, (b_all, d_all, fb_all)) = rayon::join( + || matvec_rows_sets(&[(r.wq, 0), (r.wk, 0), (r.wv, 0), (r.g, 0)], &normed_flat, nt), + || { + let b_all = matvec_rows(&r.beta, &nrefs); + let d_all = matvec_rows(&r.rda, &nrefs); + let fa_all = matvec_rows(&r.f_a, &nrefs); + let fa_refs: Vec<&[f32]> = fa_all.chunks_exact(r.f_a.rows).collect(); + let fb_all = matvec_rows(&r.f_b, &fa_refs); + (b_all, d_all, fb_all) + }, + ); + let (l1, l2, l3) = (nt * d_inner, 2 * nt * d_inner, 3 * nt * d_inner); + let (q_all, k_all, v_all, g_all) = (&qkvg[..l1], &qkvg[l1..l2], &qkvg[l2..l3], &qkvg[l3..]); + + let q_scale = 1.0 / (hd as f32).sqrt(); + let mut gated_all = vec![0.0f32; nt * d_inner]; + let st = self.rda_states[il].as_mut().unwrap(); + for t in 0..nt { + let mut q = conv1d_step_silu(&q_all[t * d_inner..(t + 1) * d_inner], &mut st.q_hist, &r.q_conv, d_inner); + let mut k = conv1d_step_silu(&k_all[t * d_inner..(t + 1) * d_inner], &mut st.k_hist, &r.k_conv, d_inner); + let mut v = conv1d_step_silu(&v_all[t * d_inner..(t + 1) * d_inner], &mut st.v_hist, &r.v_conv, d_inner); + let decay_t = &fb_all[t * d_inner..(t + 1) * d_inner]; + let br_t = &b_all[t * nh..(t + 1) * nh]; + let dr_t = &d_all[t * nh..(t + 1) * nh]; + let mut log_alpha = vec![0.0f32; d_inner]; + let mut beta = vec![0.0f32; nh]; + for h in 0..nh { + let qs = &mut q[h * hd..(h + 1) * hd]; + let qf = q_scale / dot(qs, qs).sqrt().max(1e-6); + for x in qs.iter_mut() { *x *= qf; } + let ks = &mut k[h * hd..(h + 1) * hd]; + let kf = 1.0 / dot(ks, ks).sqrt().max(1e-6); + for x in ks.iter_mut() { *x *= kf; } + let exp_a = -r.ssm_a[h]; + for j in 0..hd { + let scaled = exp_a * (decay_t[h * hd + j] + r.dt_b[h * hd + j]); + log_alpha[h * hd + j] = match self.cfg.gate_lower_bound { + Some(lb) => lb * sigmoid(scaled), + None => -softplus(scaled), + }; + } + let (br, dr) = (br_t[h], dr_t[h]); + let ratio = (softplus(-br) - softplus(-(br + dr))).exp(); + for x in &mut v[h * hd..(h + 1) * hd] { *x *= ratio; } + beta[h] = sigmoid(br); + } + let out = rda_recurrent_step(&q, &k, &v, &log_alpha, &beta, &mut st.state, nh, hd); + if capture_snaps + && let Some(dst_st) = self.rda_snap_pool[t][il].as_mut() + { + dst_st.q_hist.copy_from_slice(&st.q_hist); + dst_st.k_hist.copy_from_slice(&st.k_hist); + dst_st.v_hist.copy_from_slice(&st.v_hist); + dst_st.state.copy_from_slice(&st.state); + } + let gt = &g_all[t * d_inner..(t + 1) * d_inner]; + let dst = &mut gated_all[t * d_inner..(t + 1) * d_inner]; + for h in 0..nh { + let s = h * hd..(h + 1) * hd; + rms_norm_w(&out[s.clone()], &r.o_norm, self.cfg.eps, &mut dst[s.clone()]); + for j in s { dst[j] *= sigmoid(gt[j]); } + } + } + let grefs: Vec<&[f32]> = gated_all.chunks_exact(d_inner).collect(); + matvec_rows(&r.wo, &grefs) + } + Attn::Mla(a) => { + let (nh, kr, nr, kl, vl) = (self.cfg.n_head, self.cfg.kv_lora_rank, self.cfg.qk_rope_hd, self.cfg.mla_key_len, self.cfg.mla_val_len); + let (nope, kw) = (kl - nr, kr + nr); + let proj = matvec_rows_sets(&[(a.q_a, 0), (a.kv_a, 0), (a.gate, 0)], &normed_flat, nt); + let (l_q, l_kv) = (nt * self.cfg.q_lora_rank, nt * kw); + let (qr_raw, kv_all, g_all) = (&proj[..l_q], &proj[l_q..l_q + l_kv], &proj[l_q + l_kv..]); + let mut qr = vec![0.0f32; qr_raw.len()]; + for (src, dst) in qr_raw.chunks_exact(self.cfg.q_lora_rank).zip(qr.chunks_exact_mut(self.cfg.q_lora_rank)) { + rms_norm_w(src, &a.q_a_norm, self.cfg.latent_eps, dst); + } + let q_refs: Vec<&[f32]> = qr.chunks_exact(self.cfg.q_lora_rank).collect(); + let q = matvec_rows(&a.q_b, &q_refs); + + for kv in kv_all.chunks_exact(kw) { + let mut krow = vec![0.0f32; kw]; + rms_norm_w(&kv[..kr], &a.kv_a_norm, self.cfg.latent_eps, &mut krow[..kr]); + krow[kr..].copy_from_slice(&kv[kr..]); + self.mla_keys[il].extend_from_slice(&krow); + } + + let qn = grouped(&a.k_groups, &q, nh, kl); + let scale = 1.0 / (kl as f32).sqrt(); + let all_k = &self.mla_keys[il]; + let mut att = vec![0.0f32; nt * nh * kr]; + att.par_chunks_mut(kr).enumerate().for_each(|(idx, oh)| { + let t = idx / nh; + let n_pos = p0 + t + 1; + let qnh = &qn[idx * kr..(idx + 1) * kr]; + let qeh = &q[idx * kl + nope..(idx + 1) * kl]; + let mut scores = Vec::with_capacity(n_pos); + let mut mx = f32::NEG_INFINITY; + for p in 0..n_pos { + let row = &all_k[p * kw..(p + 1) * kw]; + let s = (dot(qnh, &row[..kr]) + dot(qeh, &row[kr..])) * scale; + if s > mx { mx = s; } + scores.push(s); + } + let mut sum = 0.0f32; + for s in &mut scores { *s = (*s - mx).exp(); sum += *s; } + let inv = 1.0 / sum; + for (p, &s) in scores.iter().enumerate() { + let w = s * inv; + let lat = &all_k[p * kw..p * kw + kr]; + for j in 0..kr { oh[j] += w * lat[j]; } + } + }); + + let mut out = grouped(&a.v_groups, &att, nh, kr); + for (o, &gv) in out.iter_mut().zip(g_all) { *o *= sigmoid(gv); } + let orefs: Vec<&[f32]> = out.chunks_exact(nh * vl).collect(); + matvec_rows(&a.wo, &orefs) + } + }; + + for t in 0..nt { + self.hc_post(&mut flats[t], &attn_out_all[t * n..(t + 1) * n], &posts[t], &h_ress[t]); + } + + // 3. Batched hc_ffn pre + ffn_norm + let flat_refs: Vec<&[f32]> = flats.iter().map(Vec::as_slice).collect(); + let hc_mix_all = matvec_rows(&self.layers[il].hc_ffn.f, &flat_refs); + let mix_w = self.layers[il].hc_ffn.f.rows; + posts.clear(); + h_ress.clear(); + for t in 0..nt { + let flat = &flats[t]; + let inv = 1.0 / (flat.iter().map(|&v| v * v).sum::() / flat.len() as f32 + self.cfg.hc_eps).sqrt(); + let mixes: Vec = hc_mix_all[t * mix_w..(t + 1) * mix_w].iter().map(|&v| v * inv).collect(); + let (pre, post, h_res) = raon_mhc_coeffs( + &mixes, &self.layers[il].hc_ffn.base, &self.layers[il].hc_ffn.scale, + hc, self.cfg.hc_mag, &self.helmert, &self.chart_base, + ); + let mut cur = vec![0.0f32; n]; + for s in 0..hc { + let w = pre[s]; + for j in 0..n { cur[j] += w * flat[s * n + j]; } + } + rms_norm_w(&cur, &self.layers[il].ffn_norm, self.cfg.eps, &mut normed_flat[t * n..(t + 1) * n]); + posts.push(post); + h_ress.push(h_res); + } + + // 4. Batched FFN (dense or expert-deduplicated MoE + shared + effort steering) + let (gb, vb) = (self.cfg.situ_beta, self.cfg.situ_linear_beta); + let ffn_out_all = match &self.layers[il].ffn { + Ffn::Dense { gate, up, down } => { + let gu = matvec_rows_sets(&[(*gate, 0), (*up, 0)], &normed_flat, nt); + let half = nt * gate.rows; + let gy: Vec = (0..half).map(|i| situ_glu(gu[i], gu[half + i], gb, vb)).collect(); + let grefs: Vec<&[f32]> = gy.chunks_exact(gate.rows).collect(); + matvec_rows(down, &grefs) + } + Ffn::Moe { gate_inp, bias, gexps, uexps, dexps, shared, effort_steer } => { + let nrefs: Vec<&[f32]> = normed_flat.chunks_exact(n).collect(); + let (logits_all, shared_gu) = if let Some((sg, su, _)) = shared { + let (lg, sgu) = rayon::join( + || matvec_rows(gate_inp, &nrefs), + || matvec_rows_sets(&[(*sg, 0), (*su, 0)], &normed_flat, nt), + ); + (lg, Some(sgu)) + } else { + (matvec_rows(gate_inp, &nrefs), None) + }; + let mut by_e: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for t in 0..nt { + let lg = &logits_all[t * gate_inp.rows..(t + 1) * gate_inp.rows]; + for (e, w) in route(lg, bias, self.cfg.n_used, self.cfg.exp_norm, self.cfg.exp_scale) { + by_e.entry(e).or_default().push((t, w)); + } + } + let mut y_all = vec![0.0f32; nt * n]; + if !by_e.is_empty() { + let evict = std::env::var_os("STRATA_RAON_EVICT").is_some(); + let exp_nf = gexps.rows / self.cfg.n_expert; + let mut gpu_grp = Vec::new(); + let mut cpu_grp = Vec::new(); + for (e, picks) in by_e { + let ge = gexps.expert_opt(e, self.cfg.n_expert, evict); + let ue = uexps.expert_opt(e, self.cfg.n_expert, evict); + let de = dexps.expert_opt(e, self.cfg.n_expert, evict); + if ge.gpu.is_some() && ue.gpu.is_some() && de.gpu.is_some() { + gpu_grp.push((ge, ue, de, picks)); + } else { + cpu_grp.push((ge, ue, de, picks)); + } + } + let run_cpu_grp = |grp: &[(Mat, Mat, Mat, Vec<(usize, f32)>)]| -> Vec { + let mut out = vec![0.0f32; nt * n]; + if grp.is_empty() { return out; } + let can_int = std::env::var_os("STRATA_CPU_REF").is_none() + && grp.iter().all(|(ge, ue, de, _)| { + ge.cols % ge.ty.block_elems() == 0 + && ue.cols % ue.ty.block_elems() == 0 + && de.cols % de.ty.block_elems() == 0 + && crate::cpu_moe::int_dot(ge.ty).is_some() + && crate::cpu_moe::int_dot(ue.ty).is_some() + && crate::cpu_moe::int_dot(de.ty).is_some() + }); + if can_int && grp.len() >= 4 { + // Quantize each token's activation once, then run all active experts in parallel + // (1 Rayon pass total, zero inter-expert barriers, L1/L2 cache-local per expert). + let xq_all: Vec<_> = (0..nt) + .into_par_iter() + .map(|t| crate::cpu_moe::quantize_q8k(&normed_flat[t * n..(t + 1) * n])) + .collect(); + let partials: Vec<(Vec<(usize, f32)>, Vec)> = grp + .par_iter() + .map(|(ge, ue, de, picks)| { + let np = picks.len(); + let g_dot = crate::cpu_moe::int_dot(ge.ty).unwrap(); + let g_dot4 = crate::cpu_moe::int_dot4(ge.ty); + let u_dot = crate::cpu_moe::int_dot(ue.ty).unwrap(); + let u_dot4 = crate::cpu_moe::int_dot4(ue.ty); + let d_dot = crate::cpu_moe::int_dot(de.ty).unwrap(); + let d_dot4 = crate::cpu_moe::int_dot4(de.ty); + let grb = ge.ty.row_bytes(ge.cols as u64); + let urb = ue.ty.row_bytes(ue.cols as u64); + let drb = de.ty.row_bytes(de.cols as u64); + let mut act = vec![0.0f32; np * exp_nf]; + for r in 0..exp_nf { + let gw = &ge.data[r * grb..(r + 1) * grb]; + let uw = &ue.data[r * urb..(r + 1) * urb]; + let mut p = 0; + if let (Some(gd4), Some(ud4)) = (g_dot4, u_dot4) { + while p + 4 <= np { + let qs = [ + xq_all[picks[p].0].as_slice(), + xq_all[picks[p + 1].0].as_slice(), + xq_all[picks[p + 2].0].as_slice(), + xq_all[picks[p + 3].0].as_slice(), + ]; + let gv = gd4(gw, qs); + let uv = ud4(uw, qs); + for j in 0..4 { + act[(p + j) * exp_nf + r] = situ_glu(gv[j] * ge.scale, uv[j] * ue.scale, gb, vb); + } + p += 4; + } + } + while p < np { + let q = xq_all[picks[p].0].as_slice(); + let gv = g_dot(gw, q) * ge.scale; + let uv = u_dot(uw, q) * ue.scale; + act[p * exp_nf + r] = situ_glu(gv, uv, gb, vb); + p += 1; + } + } + let aq: Vec<_> = act + .chunks_exact(exp_nf) + .map(crate::cpu_moe::quantize_q8k) + .collect(); + let mut dy = vec![0.0f32; np * n]; + for r in 0..n { + let dw = &de.data[r * drb..(r + 1) * drb]; + let mut p = 0; + if let Some(dd4) = d_dot4 { + while p + 4 <= np { + let dv = dd4(dw, [ + aq[p].as_slice(), + aq[p + 1].as_slice(), + aq[p + 2].as_slice(), + aq[p + 3].as_slice(), + ]); + for j in 0..4 { dy[(p + j) * n + r] = dv[j] * de.scale; } + p += 4; + } + } + while p < np { + dy[p * n + r] = d_dot(dw, aq[p].as_slice()) * de.scale; + p += 1; + } + } + (picks.clone(), dy) + }) + .collect(); + for (picks, dy) in partials { + for (pi, &(t, w)) in picks.iter().enumerate() { + let dst = &mut out[t * n..(t + 1) * n]; + let src = &dy[pi * n..(pi + 1) * n]; + for j in 0..n { dst[j] += w * src[j]; } + } + } + return out; + } + let mut gu_jobs: Vec<(Mat, usize)> = Vec::with_capacity(grp.len() * 2); + let mut gu_x: Vec = Vec::new(); + let mut d_jobs: Vec<(Mat, usize)> = Vec::with_capacity(grp.len()); + for (ge, ue, de, picks) in grp { + gu_jobs.push((*ge, picks.len())); + for &(t, _) in picks { gu_x.extend_from_slice(&normed_flat[t * n..(t + 1) * n]); } + gu_jobs.push((*ue, picks.len())); + for &(t, _) in picks { gu_x.extend_from_slice(&normed_flat[t * n..(t + 1) * n]); } + d_jobs.push((*de, picks.len())); + } + let gu_out = matvec_rows_many(&gu_jobs, &gu_x); + let mut act_x = Vec::with_capacity(gu_out.len() / 2); + let mut off = 0; + for (_, _, _, picks) in grp { + let m = picks.len() * exp_nf; + let g_slice = &gu_out[off..off + m]; + let u_slice = &gu_out[off + m..off + 2 * m]; + for i in 0..m { act_x.push(situ_glu(g_slice[i], u_slice[i], gb, vb)); } + off += 2 * m; + } + let d_out = matvec_rows_many(&d_jobs, &act_x); + let mut doff = 0; + for (_, _, _, picks) in grp { + for &(t, w) in picks { + let dst = &mut out[t * n..(t + 1) * n]; + let src = &d_out[doff..doff + n]; + for j in 0..n { dst[j] += w * src[j]; } + doff += n; + } + } + out + }; + let run_gpu_grp = |grp: &[(Mat, Mat, Mat, Vec<(usize, f32)>)]| -> Vec { + let mut out = vec![0.0f32; nt * n]; + if grp.is_empty() { return out; } + let mut gu_jobs: Vec<(Mat, usize)> = Vec::with_capacity(grp.len() * 2); + let mut gu_x: Vec = Vec::new(); + let mut d_jobs: Vec<(Mat, usize)> = Vec::with_capacity(grp.len()); + for (ge, ue, de, picks) in grp { + gu_jobs.push((*ge, picks.len())); + for &(t, _) in picks { gu_x.extend_from_slice(&normed_flat[t * n..(t + 1) * n]); } + gu_jobs.push((*ue, picks.len())); + for &(t, _) in picks { gu_x.extend_from_slice(&normed_flat[t * n..(t + 1) * n]); } + d_jobs.push((*de, picks.len())); + } + let gu_out = matvec_rows_many(&gu_jobs, &gu_x); + let mut act_x = Vec::with_capacity(gu_out.len() / 2); + let mut off = 0; + for (_, _, _, picks) in grp { + let m = picks.len() * exp_nf; + let g_slice = &gu_out[off..off + m]; + let u_slice = &gu_out[off + m..off + 2 * m]; + for i in 0..m { act_x.push(situ_glu(g_slice[i], u_slice[i], gb, vb)); } + off += 2 * m; + } + let d_out = matvec_rows_many(&d_jobs, &act_x); + let mut doff = 0; + for (_, _, _, picks) in grp { + for &(t, w) in picks { + let dst = &mut out[t * n..(t + 1) * n]; + let src = &d_out[doff..doff + n]; + for j in 0..n { dst[j] += w * src[j]; } + doff += n; + } + } + out + }; + match (gpu_grp.is_empty(), cpu_grp.is_empty()) { + (false, true) => y_all = run_gpu_grp(&gpu_grp), + (true, false) => y_all = run_cpu_grp(&cpu_grp), + (false, false) => { + let (mut gy, cy) = rayon::join(|| run_gpu_grp(&gpu_grp), || run_cpu_grp(&cpu_grp)); + for (a, b) in gy.iter_mut().zip(&cy) { *a += b; } + y_all = gy; + } + (true, true) => {} + } + } + if let Some((sg, _, sd)) = shared { + let gu = shared_gu.unwrap(); + let half = nt * sg.rows; + let gy: Vec = (0..half).map(|i| situ_glu(gu[i], gu[half + i], gb, vb)).collect(); + let grefs: Vec<&[f32]> = gy.chunks_exact(sg.rows).collect(); + let sy = matvec_rows(sd, &grefs); + for (a, b) in y_all.iter_mut().zip(&sy) { *a += b; } + } + if self.effort_alpha != 0.0 + && let Some(steer) = effort_steer + { + let a = self.effort_alpha; + for row in y_all.chunks_exact_mut(n) { + for j in 0..n { row[j] += a * steer[j]; } + } + } + y_all + } + }; + + for t in 0..nt { + self.hc_post(&mut flats[t], &ffn_out_all[t * n..(t + 1) * n], &posts[t], &h_ress[t]); + if self.capture_layers.contains(&il) { + chunk_feats[t].extend_from_slice(&flats[t]); + } + } + } + if !self.capture_layers.is_empty() { + self.pending_feats.extend(chunk_feats); + } + if !capture_snaps { + return None; + } + let inv_hc = 1.0 / hc as f32; + let mut normed_all = vec![0.0f32; nt * n]; + let mut cur = vec![0.0f32; n]; + for t in 0..nt { + cur.fill(0.0); + for s in 0..hc { + for j in 0..n { cur[j] += flats[t][s * n + j] * inv_hc; } + } + rms_norm_w(&cur, &self.out_norm, self.cfg.eps, &mut normed_all[t * n..(t + 1) * n]); + } + let nrefs: Vec<&[f32]> = normed_all.chunks_exact(n).collect(); + let all_logits = matvec_rows(&self.out_w, &nrefs); + let logits_per_tok: Vec> = all_logits.chunks_exact(self.out_w.rows).map(|s| s.to_vec()).collect(); + Some(logits_per_tok) + } + + /// Verify `draft` tokens following `anchor` in one batched pass (`int_dot4` on CPU / batched GEMM on GPU). + /// Returns `(accepted_draft_tokens, next_logits)` and rolls back RDA + MLA states on any mismatch, + /// guaranteeing bit-identical greedy output to calling `step` one token at a time. + pub fn verify_greedy(&mut self, anchor: u32, draft: &[u32], eos: &[u32]) -> (Vec, Vec) { + if draft.is_empty() { + return (Vec::new(), self.step(anchor)); + } + let p0 = self.toks.len(); + let pf0 = self.pending_feats.len(); + let mut seq = Vec::with_capacity(1 + draft.len()); + seq.push(anchor); + seq.extend_from_slice(draft); + let logits = self.prefill_chunk_opt(&seq, true).unwrap(); + let kw = self.cfg.kv_lora_rank + self.cfg.qk_rope_hd; + let (accepted, next_idx) = greedy_accepted_prefix(draft, &logits, eos); + if next_idx < draft.len() { + let keep_len = p0 + next_idx + 1; + self.toks.truncate(keep_len); + if !self.capture_layers.is_empty() { + self.pending_feats.truncate(pf0 + next_idx + 1); + } + for il in 0..self.cfg.n_layer { + if !self.cfg.is_rda[il] { + self.mla_keys[il].truncate(keep_len * kw); + } else if let (Some(dst), Some(src)) = (self.rda_states[il].as_mut(), self.rda_snap_pool[next_idx][il].as_ref()) { + dst.q_hist.copy_from_slice(&src.q_hist); + dst.k_hist.copy_from_slice(&src.k_hist); + dst.v_hist.copy_from_slice(&src.v_hist); + dst.state.copy_from_slice(&src.state); + } + } + return (accepted, logits[next_idx].clone()); + } + (accepted, logits[draft.len()].clone()) + } + + pub fn prefill(&mut self, toks: &[u32]) -> Vec { + let Some((&last, head)) = toks.split_last() else { return Vec::new() }; + let chunk: usize = std::env::var("STRATA_DS_CHUNK").ok().and_then(|v| v.parse().ok()).unwrap_or(256); + if chunk > 1 && !self.trace { + for c in head.chunks(chunk) { + self.prefill_chunk(c); + } + } else { + for &t in head { + self.step_opt(t, false); + } + } + self.step_opt(last, true) + } +} + +/// Matches `draft` tokens against greedy argmax predictions in `logits[0..draft.len()]`, stopping at the +/// first mismatch or EOS token. Returns `(accepted_draft_prefix, next_logits_index)`: neither the corrected +/// token (`logits[j]`) nor the bonus token (`logits[draft.len()]`) is placed into `accepted_draft_prefix`. +fn greedy_accepted_prefix(draft: &[u32], logits: &[Vec], eos: &[u32]) -> (Vec, usize) { + let mut accepted = Vec::with_capacity(draft.len()); + for (j, &d) in draft.iter().enumerate() { + let pred = crate::ops::argmax(&logits[j]) as u32; + if pred == d && !eos.contains(&pred) { + accepted.push(d); + } else { + return (accepted, j); + } + } + (accepted, draft.len()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn situ_glu_matches_definition() { + let y = situ_glu(1.5, -2.0, 4.0, 25.0); + let want = (4.0 * (1.5f32 / 4.0).tanh() * sigmoid(1.5)) * (25.0 * (-2.0f32 / 25.0).tanh()); + assert!((y - want).abs() < 1e-6); + assert!(situ_glu(0.0, 10.0, 4.0, 25.0).abs() < 1e-7); + } + + #[test] + fn raon_mhc_is_doubly_stochastic() { + let hc = 4; + let h = helmert_basis(hc); + let b = chart_base_mat(hc); + let mixes: Vec = (0..2 * hc + (hc - 1) * (hc - 1)).map(|i| (i as f32 * 0.7).sin() * 2.0).collect(); + let base = vec![0.1f32; mixes.len()]; + let scale = vec![0.5, 0.5, 1.2, 0.3]; + let (pre, post, h_res) = raon_mhc_coeffs(&mixes, &base, &scale, hc, 2.0, &h, &b); + assert!(pre.iter().all(|&v| v > 0.0 && v < 1.0)); + assert!(post.iter().all(|&v| v > 0.0 && v < 2.0)); + for i in 0..hc { + let rsum: f32 = (0..hc).map(|j| h_res[i * hc + j]).sum(); + let csum: f32 = (0..hc).map(|j| h_res[j * hc + i]).sum(); + assert!((rsum - 1.0).abs() < 1e-5, "row {i} sum {rsum}"); + assert!((csum - 1.0).abs() < 1e-5, "col {i} sum {csum}"); + for j in 0..hc { + assert!(h_res[i * hc + j] >= -1e-6, "negative entry ({i},{j})={}", h_res[i * hc + j]); + } + } + } + + #[test] + fn rda_recurrent_matches_scalar_reference() { + let (nh, hd) = (2, 4); + let q: Vec = (0..nh * hd).map(|i| (i as f32 * 0.3 + 0.1).sin()).collect(); + let k: Vec = (0..nh * hd).map(|i| (i as f32 * 0.5 + 0.2).cos()).collect(); + let v: Vec = (0..nh * hd).map(|i| (i as f32 * 0.2 - 0.4).sin()).collect(); + let la: Vec = (0..nh * hd).map(|i| -0.1 * (i as f32 + 1.0)).collect(); + let beta = [0.6f32, 0.8f32]; + let mut st = vec![0.0f32; nh * hd * hd]; + let out = rda_recurrent_step(&q, &k, &v, &la, &beta, &mut st, nh, hd); + // Step 0 from zero state: S = beta * v * k^T, out = beta * (k . q) * v + for h in 0..nh { + let kq = dot(&k[h * hd..(h + 1) * hd], &q[h * hd..(h + 1) * hd]); + for vi in 0..hd { + let want = beta[h] * kq * v[h * hd + vi]; + assert!((out[h * hd + vi] - want).abs() < 1e-6); + } + } + } + + #[test] + fn router_uses_bias_for_selection_only() { + let logits = [0.0f32, 2.0, -2.0, 0.1]; + let bias = [5.0f32, 0.0, 0.0, 0.0]; + let sel = route(&logits, &bias, 2, true, 1.0); + assert_eq!(sel[0].0, 0); + assert_eq!(sel[1].0, 1); + let s0 = sigmoid(0.0); + let s1 = sigmoid(2.0); + assert!((sel[0].1 - s0 / (s0 + s1)).abs() < 1e-6); + assert!((sel[1].1 - s1 / (s0 + s1)).abs() < 1e-6); + } + + #[test] + fn verify_greedy_prefix_excludes_corrected_and_bonus_tokens() { + let one_hot = |tok: u32| -> Vec { + let mut v = vec![0.0f32; 10]; + v[tok as usize] = 1.0; + v + }; + let draft = [1, 2, 3]; + let eos = [9]; + + // Zero acceptance: mismatch at index 0 leaves corrected token (4) in logits[0], not accepted. + let logits_zero = [one_hot(4), one_hot(2), one_hot(3), one_hot(5)]; + let (acc, next_idx) = greedy_accepted_prefix(&draft, &logits_zero, &eos); + assert_eq!((acc, next_idx), (vec![], 0)); + assert_eq!(crate::ops::argmax(&logits_zero[next_idx]) as u32, 4); + + // Partial acceptance: draft[0] accepted, mismatch at index 1 leaves corrected token (4) in logits[1]. + let logits_partial = [one_hot(1), one_hot(4), one_hot(3), one_hot(5)]; + let (acc, next_idx) = greedy_accepted_prefix(&draft, &logits_partial, &eos); + assert_eq!((acc, next_idx), (vec![1], 1)); + assert_eq!(crate::ops::argmax(&logits_partial[next_idx]) as u32, 4); + + // Full acceptance: all 3 drafts accepted (len == draft.len()); bonus token (5) stays in logits[3]. + let logits_full = [one_hot(1), one_hot(2), one_hot(3), one_hot(5)]; + let (acc, next_idx) = greedy_accepted_prefix(&draft, &logits_full, &eos); + assert_eq!((acc, next_idx), (vec![1, 2, 3], 3)); + assert_eq!(crate::ops::argmax(&logits_full[next_idx]) as u32, 5); + + // EOS match on draft[1]: stops before EOS so accepted only counts draft[0] and logits[1] yields EOS. + let draft_eos = [1, 9, 3]; + let logits_eos = [one_hot(1), one_hot(9), one_hot(3), one_hot(5)]; + let (acc, next_idx) = greedy_accepted_prefix(&draft_eos, &logits_eos, &eos); + assert_eq!((acc, next_idx), (vec![1], 1)); + assert_eq!(crate::ops::argmax(&logits_eos[next_idx]) as u32, 9); + } +} diff --git a/src/raon/mod.rs b/src/raon/mod.rs new file mode 100644 index 00000000..52b65a19 --- /dev/null +++ b/src/raon/mod.rs @@ -0,0 +1,188 @@ +//! KRAFTON Raon-1 mini (`raon1`): 4-stream Raon-mHC, hybrid RDA (Raon Delta Attention) + gated NoPE MLA, +//! SiTU-GLU dense/MoE FFN, and per-layer reasoning effort steering. +//! Mirrors `krafton-ai/llama.cpp` `src/models/raon1.cpp` and `KRAFTON/Raon-1-mini` `modeling_raon1_mini.py`. +pub mod chat; +pub mod dflash; +pub mod forward; + +use crate::gguf::{Gguf, Value}; +use anyhow::{Context, ensure}; + +pub const ARCH: &str = "raon1"; + +#[derive(Debug, Clone)] +pub struct RaonConfig { + pub n_layer: usize, + pub n_ctx: usize, + pub n_embd: usize, + pub n_vocab: usize, + pub n_head: usize, + /// `true` for RDA (linear delta attention) layers (`head_count_kv == 0`), `false` for MLA layers (`head_count_kv == 1`). + pub is_rda: Vec, + pub d_conv: usize, + pub dt_rank: usize, + pub rda_hd: usize, + pub gate_lower_bound: Option, + pub q_lora_rank: usize, + pub kv_lora_rank: usize, + pub qk_rope_hd: usize, + pub mla_key_len: usize, + pub mla_val_len: usize, + pub eps: f32, + pub latent_eps: f32, + pub hc: usize, + pub hc_eps: f32, + pub hc_mag: f32, + pub situ_beta: f32, + pub situ_linear_beta: f32, + pub n_dense: usize, + pub n_ff: usize, + pub n_ff_exp: usize, + pub n_expert: usize, + pub n_used: usize, + pub n_shared: usize, + pub exp_scale: f32, + pub exp_norm: bool, + pub effort_names: Vec, + pub effort_alpha: Vec, + pub effort_default: Option, + pub effort_layers: Vec, +} + +impl RaonConfig { + pub fn from_gguf(g: &Gguf) -> anyhow::Result { + let k = |s: &str| format!("{ARCH}.{s}"); + let u = |s: &str| -> anyhow::Result { Ok(g.get(&k(s))?.as_u64().with_context(|| k(s))? as usize) }; + let f = |s: &str| -> anyhow::Result { g.get(&k(s))?.as_f32().with_context(|| k(s)) }; + let arr_u = |s: &str| -> anyhow::Result> { + g.get(&k(s))?.as_arr().with_context(|| k(s))?.iter().map(|v| v.as_u64().with_context(|| k(s))).collect() + }; + + let n_layer = u("block_count")?; + let n_embd = u("embedding_length")?; + let n_head = u("attention.head_count")?; + let head_count_kv = arr_u("attention.head_count_kv")?; + ensure!(head_count_kv.len() == n_layer, "raon1.attention.head_count_kv len {} != {n_layer}", head_count_kv.len()); + let mut is_rda = Vec::with_capacity(n_layer); + let mut n_rda = 0usize; + for (i, &kv) in head_count_kv.iter().enumerate() { + ensure!(kv == 0 || kv == 1, "raon1 layer {i} head_count_kv must be 0 (RDA) or 1 (MLA), got {kv}"); + is_rda.push(kv == 0); + if kv == 0 { n_rda += 1; } + } + ensure!(n_rda > 0 && n_rda < n_layer, "raon1 requires both RDA and MLA layers (got {n_rda}/{n_layer} RDA)"); + + let d_conv = u("ssm.conv_kernel")?; + ensure!(d_conv == 4, "raon1 ssm.conv_kernel must be 4, got {d_conv}"); + let dt_rank = u("ssm.time_step_rank")?; + let rda_hd = u("kda.head_dim")?; + ensure!(matches!(rda_hd, 16 | 32 | 64 | 128), "unsupported raon1 kda.head_dim {rda_hd}"); + let gate_lower_bound = g.meta.get(&k("kda.gate_lower_bound")).and_then(Value::as_f32).filter(|v| v.is_finite()); + + let q_lora_rank = u("attention.q_lora_rank")?; + let kv_lora_rank = u("attention.kv_lora_rank")?; + let qk_rope_hd = u("rope.dimension_count")?; + let mla_key_len = u("attention.key_length_mla")?; + let mla_val_len = u("attention.value_length_mla")?; + ensure!(mla_key_len > qk_rope_hd, "raon1 MLA key_len {mla_key_len} <= rope dim {qk_rope_hd}"); + + let hc = u("hyper_connection.count")?; + ensure!((2..=8).contains(&hc), "raon1 hyper_connection.count {hc} not in 2..=8"); + let n_dense = u("leading_dense_block_count")?; + ensure!(n_dense <= n_layer, "raon1 leading_dense_block_count {n_dense} > {n_layer}"); + let exp_norm = match g.get(&k("expert_weights_norm"))? { + Value::Bool(b) => *b, + v => v.as_u64().with_context(|| k("expert_weights_norm"))? != 0, + }; + let n_ff_exp = match g.get(&k("expert_feed_forward_length"))? { + Value::Arr(a) => a.first().and_then(Value::as_u64).context("empty expert_feed_forward_length")? as usize, + v => v.as_u64().with_context(|| k("expert_feed_forward_length"))? as usize, + }; + + let mut effort_names = Vec::new(); + let mut effort_alpha = Vec::new(); + let mut effort_default = None; + let mut effort_layers = vec![false; n_layer]; + if let Some(alpha_v) = g.meta.get(&k("reasoning_effort.alpha")) { + effort_alpha = alpha_v.as_arr().context("reasoning_effort.alpha")?.iter() + .map(|v| v.as_f32().context("reasoning_effort.alpha entry")) + .collect::>()?; + effort_names = if let Some(nv) = g.meta.get(&k("reasoning_effort.names")) { + nv.as_arr().context("reasoning_effort.names")?.iter() + .map(|v| v.as_str().map(str::to_string).context("reasoning_effort.names entry")) + .collect::>()? + } else { + vec!["low".into(), "medium".into(), "high".into()] + }; + ensure!(effort_names.len() == effort_alpha.len() && !effort_alpha.is_empty(), "raon1 reasoning_effort mismatch"); + if let Some(dv) = g.meta.get(&k("reasoning_effort.default")).and_then(Value::as_str) { + effort_default = effort_names.iter().position(|s| s == dv); + } + for il in arr_u("reasoning_effort.layers")? { + let il = il as usize; + ensure!(il >= n_dense && il < n_layer, "raon1 reasoning_effort layer {il} out of MoE range"); + effort_layers[il] = true; + } + } + + let (n_expert, n_used) = (u("expert_count")?, u("expert_used_count")?); + ensure!(n_embd > 0 && n_head > 0 && dt_rank > 0 && q_lora_rank > 0 && kv_lora_rank > 0, "raon1 has a zero dimension"); + ensure!(n_dense == n_layer || (1..=n_expert).contains(&n_used), "raon1 expert_used_count {n_used} not in 1..={n_expert}"); + let n_vocab = g.tensors.get("token_embd.weight").context("missing token_embd.weight")?.dims[1] as usize; + Ok(RaonConfig { + n_layer, + n_ctx: crate::ctx_limit(g.meta.get(&k("context_length")).and_then(Value::as_u64).map_or(32768, |v| v as usize)), + n_embd, + n_vocab, + n_head, + is_rda, + d_conv, + dt_rank, + rda_hd, + gate_lower_bound, + q_lora_rank, + kv_lora_rank, + qk_rope_hd, + mla_key_len, + mla_val_len, + eps: f("attention.layer_norm_rms_epsilon")?, + latent_eps: f("attention.latent_norm_rms_epsilon")?, + hc, + hc_eps: f("hyper_connection.epsilon")?, + hc_mag: f("hyper_connection.magnitude")?, + situ_beta: f("activation.situ_beta")?, + situ_linear_beta: f("activation.situ_linear_beta")?, + n_dense, + n_ff: u("feed_forward_length")?, + n_ff_exp, + n_expert, + n_used, + n_shared: u("expert_shared_count")?, + exp_scale: f("expert_weights_scale")?, + exp_norm, + effort_names, + effort_alpha, + effort_default, + effort_layers, + }) + } + + /// Resolve an effort name (`none|low|medium|high|xhigh|max`) to its steering alpha (0.0 when disabled). + pub fn effort_alpha_for(&self, effort: Option<&str>, think: bool) -> f32 { + if self.effort_alpha.is_empty() { + return 0.0; + } + if let Some(name) = effort.map(str::trim).filter(|s| !s.is_empty()) { + if let Some(idx) = self.effort_names.iter().position(|n| n == name) { + return self.effort_alpha[idx]; + } + } + if !think { + if let Some(idx) = self.effort_names.iter().position(|n| n == "none") { + return self.effort_alpha[idx]; + } + return 0.0; + } + self.effort_default.map_or(0.0, |i| self.effort_alpha[i]) + } +} diff --git a/src/serve.rs b/src/serve.rs index 313330c9..32ddef4c 100644 --- a/src/serve.rs +++ b/src/serve.rs @@ -15,7 +15,12 @@ pub struct Request { /// A reverse proxy's header is present (`Forwarded`, `X-Forwarded-*`, `X-Real-IP`): the peer address is the /// proxy's, not the client's. pub proxied: bool, + /// `Origin` and `Access-Control-Request-Headers`, for `--cors-origin`. + pub origin: String, + pub cors_headers: String, pub body: Vec, + /// Set by the accept loop for a streamed chat that waits in the queue (`Queued`). + pub queued: Option>, } /// Reads one request, with a `Content-Length` or a chunked body (`Transfer-Encoding: chunked`, which wins when both @@ -27,6 +32,7 @@ pub fn read_request(r: &mut impl BufRead) -> anyhow::Result { let mut it = line.split_whitespace(); let (method, path) = (it.next().context("empty request")?.to_string(), it.next().context("no path")?.to_string()); let (mut len, mut host, mut auth, mut json, mut proxied, mut chunked) = (0, String::new(), String::new(), false, false, false); + let (mut origin, mut cors_headers) = (String::new(), String::new()); loop { line.clear(); if h.read_line(&mut line)? == 0 { bail!("headers cut off or too long"); } @@ -43,11 +49,15 @@ pub fn read_request(r: &mut impl BufRead) -> anyhow::Result { "x-api-key" if auth.is_empty() => auth = format!("Bearer {v}"), "content-type" => json = v.starts_with("application/json"), "forwarded" | "x-real-ip" => proxied = true, + "origin" => origin = v.to_string(), + "access-control-request-headers" => cors_headers = v.to_string(), _ if k.starts_with("x-forwarded-") => proxied = true, _ => {} } } const MAX: usize = 8 << 20; + // Never sized up front: memory follows the bytes that arrive, not the size the client claims. A short body is + // still io's UnexpectedEof, the error `read_exact` gave. let mut body = Vec::new(); if chunked { // Each chunk: a hex size (extensions after ';' are ignored), CRLF, the bytes, CRLF. Size 0 ends the body; @@ -59,8 +69,8 @@ pub fn read_request(r: &mut impl BufRead) -> anyhow::Result { if n == 0 { break; } if n > MAX - body.len() { bail!("body too large"); } let at = body.len(); - body.resize(at + n, 0); - r.read_exact(&mut body[at..])?; + r.by_ref().take(n as u64).read_to_end(&mut body)?; + if body.len() != at + n { return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "chunked body cut off").into()); } line.clear(); r.by_ref().take(1 << 10).read_line(&mut line)?; if !line.trim_end().is_empty() { bail!("bad chunk end"); } @@ -72,10 +82,53 @@ pub fn read_request(r: &mut impl BufRead) -> anyhow::Result { } } else { if len > MAX { bail!("body too large"); } - body.resize(len, 0); - r.read_exact(&mut body)?; + r.by_ref().take(len as u64).read_to_end(&mut body)?; + if body.len() != len { return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "body cut off").into()); } } - Ok(Request { method, path, host, auth, json, proxied, body }) + Ok(Request { method, path, host, auth, json, proxied, origin, cors_headers, body, queued: None }) +} + +/// How long a whole request (headers and body) may take to arrive: an 8 MiB body still gets through at about 70 KB/s. +pub const REQUEST_TIME: std::time::Duration = std::time::Duration::from_secs(120); + +/// A connection read until `end`, which the accept loop sets `REQUEST_TIME` ahead (the error names that limit). Each +/// read still waits at most 30 s for the next byte, but that alone let a client that sends a byte every 29 s hold its +/// connection, and a place in `--max-waiting`, for as long as it liked. +pub struct Deadline<'a> { c: &'a std::net::TcpStream, end: std::time::Instant } + +impl<'a> Deadline<'a> { + pub fn new(c: &'a std::net::TcpStream, end: std::time::Instant) -> Self { Deadline { c, end } } +} + +impl Read for Deadline<'_> { + fn read(&mut self, b: &mut [u8]) -> std::io::Result { + use std::io::{Error, ErrorKind}; + let late = || Error::new(ErrorKind::TimedOut, format!("the request did not arrive within {} s", REQUEST_TIME.as_secs())); + let left = self.end.saturating_duration_since(std::time::Instant::now()); + // `set_read_timeout` refuses a zero duration. + if left.is_zero() { return Err(late()); } + let wait = left.min(std::time::Duration::from_secs(30)); + self.c.set_read_timeout(Some(wait))?; + // A read that waited for all the time left ran into `end` (Unix reports WouldBlock, Windows TimedOut). + self.c.read(b).map_err(|e| if wait == left && matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) { late() } else { e }) + } +} + +/// `POST /v1/vram`'s body, `{"reserve_mib": N}`: the VRAM to keep free in bytes, or `None` for `null` or no key (the +/// `--vram-margin` each device loaded with). A number past what fits saturates, which shrinks the cache to its floor. +pub fn vram_reserve_request(body: &[u8]) -> anyhow::Result> { + let v: Value = serde_json::from_slice(body).context("the body must be JSON, as {\"reserve_mib\": 4096}")?; + match &v["reserve_mib"] { + Value::Null => Ok(None), + r => r.as_u64().map(|n| Some(usize::try_from(n).unwrap_or(usize::MAX).saturating_mul(1 << 20))) + .context("reserve_mib: a whole number of MiB, 0 or more, or null"), + } +} + +/// A slot file name (`POST /slots/{id}`): letters, digits, `-`, `_` and `.`, not starting with `.`, so it stays +/// inside `--slot-save-path`. +pub fn plain_file_name(f: &str) -> bool { + !f.is_empty() && f.len() <= 255 && !f.starts_with('.') && f.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)) } /// Host header check against DNS rebinding: a loopback name, the host the server was bound to, or a name the user @@ -97,16 +150,257 @@ pub fn gone(c: &std::net::TcpStream) -> bool { match r { Ok(n) => n == 0, Err(e) => e.kind() != std::io::ErrorKind::WouldBlock } } +/// The longest time a stream sends nothing. +const KEEP: std::time::Duration = std::time::Duration::from_secs(15); + +/// The error text for a prompt longer than the context. Clients that compact a conversation when it overflows (Pi, and +/// others with the same patterns) look for these words: "prompt is too long" (Anthropic) and "exceeds the available +/// context size" (llama.cpp server) (issue #130). +pub fn too_long(prompt: usize, limit: usize) -> String { + format!("prompt is too long: {prompt} tokens, the limit is {limit} (the request exceeds the available context size; raise --ctx)") +} + +/// One untimed 512-token prefill at load (`STRATA_WARMUP=0` skips it); `prefill` feeds the tokens and resets the +/// model. A MoE model larger than free RAM otherwise reads its CPU experts off the drive one page fault at a time +/// during the first request (GigaChat 4: 33 tok/s instead of ~400); this fills the VRAM expert cache and the page +/// cache before a request waits on them. +pub fn warm_up(tok: &crate::tokenizer::Tokenizer, prefill: impl FnOnce(&[u32])) -> anyhow::Result<()> { + if std::env::var("STRATA_WARMUP").as_deref() == Ok("0") { return Ok(()); } + let t = std::time::Instant::now(); + let text = "The river town woke before dawn. Fishermen checked their nets, bakers lit ovens, and a clockmaker argued with his apprentice about gears, tides and the price of brass. "; + let ids: Vec = tok.encode(&text.repeat(16))?.into_iter().take(512).collect(); + prefill(&ids); + crate::say!("warm-up: {} tokens in {:.1} s", ids.len(), t.elapsed().as_secs_f32()); + Ok(()) +} + +/// Runs `f`, the prefill of a request. For a stream, whose response head is written before the call, an SSE comment +/// goes out every 15 s until `f` returns, so a client that waits a limited time for the next byte keeps waiting +/// through a long prompt (`f` must not write to `c`). +pub fn alive(c: &std::net::TcpStream, stream: bool, f: impl FnOnce() -> T) -> T { alive_every(c, stream.then_some(KEEP), f) } + +/// A streamed chat in the queue of a model that answers one request at a time (a model outside the main engine, +/// such as Inkling 2). After `QUEUE_HEAD` in the queue its response head goes out, then `: keep-alive` every 15 s, +/// so a client with a time limit for the head (OpenCode) waits for its turn instead of giving up. `take` ends that +/// when the model picks the request; the thread also ends when the request is dropped. +pub struct Queued { picked: std::sync::Mutex, cv: std::sync::Condvar, head: std::sync::atomic::AtomicBool } + +pub const QUEUE_HEAD: std::time::Duration = std::time::Duration::from_secs(10); + +impl Queued { + pub fn start(c: &std::net::TcpStream) -> std::io::Result> { + use std::io::Write; + let q = std::sync::Arc::new(Queued { picked: Default::default(), cv: Default::default(), head: Default::default() }); + let (w, mut c) = (std::sync::Arc::downgrade(&q), c.try_clone()?); + std::thread::spawn(move || { + let mut wait = QUEUE_HEAD; + while let Some(q) = w.upgrade() { + let (g, _) = q.cv.wait_timeout_while(q.picked.lock().unwrap(), wait, |p| !*p).unwrap(); + // A dropped request leaves only this thread's reference: write nothing for it. + if *g || std::sync::Arc::strong_count(&q) == 1 { return; } + // Written under the lock, so `take` returns after a write in progress. + let out = if q.head.swap(true, std::sync::atomic::Ordering::Relaxed) { c.write_all(b": keep-alive\n\n") } else { c.write_all(sse_head(&c).as_bytes()) }; + if out.is_err() { return; } + wait = KEEP; + } + }); + Ok(q) + } + /// The model picked the request: stops the thread. True when the response head is already out. + pub fn take(&self) -> bool { + *self.picked.lock().unwrap() = true; + self.cv.notify_all(); + self.head.load(std::sync::atomic::Ordering::Relaxed) + } +} + +/// The response head of a streamed chat. +pub fn sse_head(c: &std::net::TcpStream) -> String { + format!("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n{}\r\n", cors(c)) +} + +/// `--cors-origin`: the origins whose pages may call the server (`*` for any). Not set: no CORS headers. +pub static CORS_ORIGINS: std::sync::OnceLock> = std::sync::OnceLock::new(); + +/// The CORS header lines (each ending in CRLF) for a request from `origin`; empty when `--cors-origin` is not set or +/// does not name it. `requested` is the preflight's `Access-Control-Request-Headers`, allowed besides the key headers. +pub fn cors_lines(origin: &str, requested: &str) -> String { + CORS_ORIGINS.get().map_or_else(String::new, |a| cors_lines_for(a, origin, requested)) +} + +fn cors_lines_for(allowed: &[String], origin: &str, requested: &str) -> String { + let o = if allowed.iter().any(|a| a == "*") { "*" } else if !origin.is_empty() && allowed.iter().any(|a| a == origin) { origin } else { return String::new() }; + let extra = if requested.is_empty() { String::new() } else { format!(", {requested}") }; + format!("Access-Control-Allow-Origin: {o}\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\n\ + Access-Control-Allow-Headers: Authorization, Content-Type, x-api-key{extra}\r\nAccess-Control-Max-Age: 600\r\nVary: Origin\r\n") +} + +/// The CORS lines of each open connection's request, by peer address: the response heads are written in many +/// places, each takes its connection's lines (`cors`) once, as every connection carries one response. +static CORS_CONNS: std::sync::Mutex>> = std::sync::Mutex::new(None); + +/// Keeps `r`'s CORS lines for the response head of connection `c` (nothing when `--cors-origin` is not set). +pub fn cors_keep(c: &std::net::TcpStream, r: &Request) { + let lines = cors_lines(&r.origin, ""); + if lines.is_empty() { return } + let Ok(p) = c.peer_addr() else { return }; + let mut m = CORS_CONNS.lock().unwrap(); + let m = m.get_or_insert_default(); + // ponytail: a connection whose head was never written leaves its entry; the cap bounds that. + if m.len() > 4096 { m.clear(); } + m.insert(p, lines); +} + +/// The CORS lines kept for connection `c` (`cors_keep`), taken for its response head; empty without them. +pub fn cors(c: &std::net::TcpStream) -> String { + if CORS_ORIGINS.get().is_none() { return String::new() } + c.peer_addr().ok().and_then(|p| CORS_CONNS.lock().unwrap().as_mut()?.remove(&p)).unwrap_or_default() +} + +/// `alive` with the time between two comments (`None`: no stream, nothing is written). +pub fn alive_every(c: &std::net::TcpStream, every: Option, f: impl FnOnce() -> T) -> T { + use std::io::Write; + let Some(every) = every else { return f() }; + let (tx, rx) = std::sync::mpsc::channel::<()>(); + std::thread::scope(|s| { + // The end of `f` drops `tx`, which ends the wait at once. + s.spawn(move || { let mut c = c; while rx.recv_timeout(every) == Err(std::sync::mpsc::RecvTimeoutError::Timeout) && c.write_all(b": keep-alive\n\n").is_ok() {} }); + let r = f(); + drop(tx); + r + }) +} + +/// What a stream writes while its text is held back (the body of a tool call): an SSE comment when `last` is 15 s +/// old, so a client that gives up after some minutes without a byte (undici: 300 s) keeps reading. False when the +/// client is gone. +pub fn held(c: &mut impl std::io::Write, last: &mut std::time::Instant) -> bool { + if last.elapsed() < KEEP { return true; } + *last = std::time::Instant::now(); + c.write_all(b": keep-alive\n\n").is_ok() +} + /// `Authorization` header check for `--api-key`, without an early exit on the first differing byte. /// The chat page of `serve`. pub const PAGE: &str = include_str!("web/index.html"); +/// The KaTeX files the chat page needs to show math in replies, by the path they are served at. Embedded like the +/// page itself, so the server stays one file that works without the network. +pub const KATEX: &[(&str, &str, &[u8])] = &[ + ("katex.min.js", "application/javascript; charset=utf-8", include_bytes!("web/katex/katex.min.js")), + ("katex.min.css", "text/css; charset=utf-8", include_bytes!("web/katex/katex.min.css")), + ("fonts/KaTeX_AMS-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_AMS-Regular.woff2")), + ("fonts/KaTeX_Caligraphic-Bold.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Caligraphic-Bold.woff2")), + ("fonts/KaTeX_Caligraphic-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Caligraphic-Regular.woff2")), + ("fonts/KaTeX_Fraktur-Bold.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Fraktur-Bold.woff2")), + ("fonts/KaTeX_Fraktur-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Fraktur-Regular.woff2")), + ("fonts/KaTeX_Main-Bold.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Main-Bold.woff2")), + ("fonts/KaTeX_Main-BoldItalic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Main-BoldItalic.woff2")), + ("fonts/KaTeX_Main-Italic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Main-Italic.woff2")), + ("fonts/KaTeX_Main-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Main-Regular.woff2")), + ("fonts/KaTeX_Math-BoldItalic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Math-BoldItalic.woff2")), + ("fonts/KaTeX_Math-Italic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Math-Italic.woff2")), + ("fonts/KaTeX_SansSerif-Bold.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_SansSerif-Bold.woff2")), + ("fonts/KaTeX_SansSerif-Italic.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_SansSerif-Italic.woff2")), + ("fonts/KaTeX_SansSerif-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_SansSerif-Regular.woff2")), + ("fonts/KaTeX_Script-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Script-Regular.woff2")), + ("fonts/KaTeX_Size1-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Size1-Regular.woff2")), + ("fonts/KaTeX_Size2-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Size2-Regular.woff2")), + ("fonts/KaTeX_Size3-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Size3-Regular.woff2")), + ("fonts/KaTeX_Size4-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Size4-Regular.woff2")), + ("fonts/KaTeX_Typewriter-Regular.woff2", "font/woff2", include_bytes!("web/katex/fonts/KaTeX_Typewriter-Regular.woff2")), +]; + /// What a chat of a model outside the main engine did, for the server's log and statistics. -pub struct Done { pub prompt: usize, pub cached: usize, pub completion: usize, pub prefill_s: f64, pub finish: &'static str } +pub struct Done { + pub prompt: usize, + pub cached: usize, + pub completion: usize, + pub prefill_s: f64, + pub finish: &'static str, + /// Speculative drafts `(kind, proposed, accepted)` for this request, when any were proposed. + pub drafts: Option<(&'static str, usize, usize)>, +} + +impl Done { + /// The llama-server `timings` block of this reply; `t` is when its prefill started. + pub fn timings(&self, t: std::time::Instant) -> Value { + let decode_ms = (t.elapsed().as_secs_f64() - self.prefill_s).max(0.0) * 1e3; + timings(self.prompt, self.cached, self.completion, self.prefill_s * 1e3, decode_ms) + } +} + +/// Primary model-based speculative drafter attached to a runner, paired with optional n-gram/suffix drafting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DraftModel { + None, + Mtp, + DFlash, + External, + Dspark, +} + +/// Whether an optional `NgramDrafter` is actively enabled. +pub fn ngram_enabled(ng: Option<&crate::ngram::NgramDrafter>) -> bool { + ng.is_some_and(|n| n.cfg.is_enabled()) +} + +/// Label for speculative draft acceptance logs across both the main GPU engine and `Runner::Own` architectures. +pub fn draft_kind(model: DraftModel, ngram: bool) -> &'static str { + match (model, ngram) { + (DraftModel::DFlash, true) => "FlashCascade (DFlash + suffix/ngram)", + (DraftModel::DFlash, false) => "DFlash", + (DraftModel::External, true) => "FlashCascade (external draft + suffix/ngram)", + (DraftModel::External, false) => "external draft", + (DraftModel::Dspark, true) => "DSpark + speculative ngram", + (DraftModel::Dspark, false) => "DSpark", + (DraftModel::Mtp | DraftModel::None, true) => "speculative ngram", + (DraftModel::Mtp, false) => "MTP", + (DraftModel::None, false) => "speculative", + } +} + +/// Per-request speculative draft counts `(kind, proposed, accepted)` from cumulative `(proposed, accepted)` +/// counters before and after one request, or `None` when no drafts were proposed. +pub fn draft_delta(kind: &'static str, before: (usize, usize), after: (usize, usize)) -> Option<(&'static str, usize, usize)> { + let proposed = after.0.saturating_sub(before.0); + (proposed > 0).then(|| (kind, proposed, after.1.saturating_sub(before.1).min(proposed))) +} + +/// Suffix appended to `serve`'s `done:` log line when speculative drafts were proposed. +pub fn format_drafts_suffix(drafts: Option<(&str, usize, usize)>) -> String { + match drafts { + Some((kind, proposed, accepted)) if proposed > 0 => { + format!(", {kind} drafts accepted {accepted}/{proposed} ({:.1}%)", 100.0 * accepted as f64 / proposed as f64) + } + _ => String::new(), + } +} + +/// The `timings` block llama-server puts in its responses. llama-swap and other OpenAI-compatible clients read it for +/// prefill/decode rates. `prompt_n` is the uncached part of the prompt and `cache_n` the part served from cache, as in +/// llama-server. +pub fn timings(prompt: usize, cached: usize, completion: usize, prefill_ms: f64, decode_ms: f64) -> Value { + let prompt_n = prompt.saturating_sub(cached); + let per_token_ms = |ms: f64, n: usize| if n == 0 { 0.0 } else { ms / n as f64 }; + let per_second = |ms: f64, n: usize| if ms > 0.0 { n as f64 * 1e3 / ms } else { 0.0 }; + serde_json::json!({ + "prompt_n": prompt_n, + "prompt_ms": prefill_ms, + "prompt_per_token_ms": per_token_ms(prefill_ms, prompt_n), + "prompt_per_second": per_second(prefill_ms, prompt_n), + "predicted_n": completion, + "predicted_ms": decode_ms, + "predicted_per_token_ms": per_token_ms(decode_ms, completion), + "predicted_per_second": per_second(decode_ms, completion), + "cache_n": cached, + }) +} /// Writes one response with a body. -pub fn send(c: &mut impl std::io::Write, status: &str, ty: &str, b: &str) { - let _ = write!(c, "HTTP/1.1 {status}\r\nContent-Type: {ty}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()); +pub fn send(c: &mut std::net::TcpStream, status: &str, ty: &str, b: &str) { + use std::io::Write; + let _ = write!(c, "HTTP/1.1 {status}\r\nContent-Type: {ty}\r\nContent-Length: {}\r\nConnection: close\r\n{}\r\n{b}", b.len(), cors(c)); } /// The chat of a model outside the main engine (Gemma 4, GLM, DeepSeek, Hy4, Inkling 2), which owns the model: it @@ -202,11 +496,20 @@ pub fn list_models(dir: &Path) -> Vec<(String, PathBuf, u64)> { files.push((id, std::fs::metadata(&p).map_or(0, |m| m.len()))); } } - let mut out: Vec<_> = models(&files).into_iter().map(|(id, n)| (id.clone(), dir.join(id), n)).collect(); + let mut out: Vec<_> = models(&files).into_iter().map(|(id, n)| (id.clone(), dir.join(id), n)).filter(|m| loads(&m.1)).collect(); out.sort(); out } +/// Whether the GGUF at `p` is a model to load, not a file that only `--lora` (`general.type` "adapter") or +/// `--draft-model` (a DFlash drafter) takes: the list leaves those out (issue #211). A file whose header does not +/// read stays listed, so loading it says why. +fn loads(p: &Path) -> bool { + let Ok(g) = crate::gguf::Gguf::head(p) else { return true }; + let s = |k| g.meta.get(k).and_then(|v| v.as_str()); + s("general.type") != Some("adapter") && s("general.architecture") != Some("dflash") +} + /// GGUF models that the Hugging Face hub cache (`hf download`, `huggingface_hub`, llama.cpp `-hf`) and llama.cpp's /// own cache already hold, so the page offers them without a second download. Hub repos appear as /// `hf///` from the snapshot that `refs/main` names (else the newest one); llama.cpp's cache as @@ -325,6 +628,7 @@ pub struct ChatRequest { pub temperature: Option, pub top_k: Option, pub top_p: Option, + pub min_p: Option, pub presence_penalty: Option, pub frequency_penalty: Option, /// llama.cpp server names: the repeat penalty and how many of the reply's last tokens it looks at. @@ -337,6 +641,11 @@ pub struct ChatRequest { pub seed: Option, /// The reply ends before the first of these strings (`stop`). pub stop: Vec, + /// `logit_bias`, and a GBNF `grammar` the reply must follow (see `crate::grammar`). + pub logit_bias: Vec<(crate::grammar::BiasKey, f32)>, + pub grammar: Option>, + /// The response head went out while the request waited in the queue (`Queued`): the handler must not write it. + pub head_sent: bool, } pub fn chat_request(body: &[u8]) -> anyhow::Result { @@ -376,7 +685,24 @@ pub fn chat_request(body: &[u8]) -> anyhow::Result { }.context("stop must be a string or an array of strings")?.into_iter().filter(|s| !s.is_empty()).collect::>(); // Hold checks every prefix of every stop string at each token, so both are bounded. if stop.len() > 16 || stop.iter().any(|s| s.len() > 256) { bail!("stop takes at most 16 strings of at most 256 bytes"); } - let think = v["chat_template_kwargs"]["enable_thinking"].as_bool(); + let grammar = match &v["grammar"] { + Value::Null => None, + Value::String(s) if s.trim().is_empty() => None, + Value::String(s) => Some(std::sync::Arc::new(crate::grammar::Grammar::parse(s)?)), + _ => bail!("grammar must be a string"), + }; + let grammar = match crate::grammar::response_format(&{ + #[derive(serde::Deserialize)] + struct R { #[serde(default)] response_format: Option } + serde_json::from_slice::(body)?.response_format.unwrap_or(crate::grammar::Json::Leaf(Value::Null)) + })? { + Some(g) if grammar.is_none() => Some(std::sync::Arc::new(g)), + Some(_) => bail!("grammar and response_format do not go together"), + None => grammar, + }; + // A grammar is for the answer: thinking is off unless the request turns it on, and then the grammar holds from + // `` on (`Constraint::after_think`). + let think = v["chat_template_kwargs"]["enable_thinking"].as_bool().or(grammar.as_ref().map(|_| false)); let include_usage = v["stream_options"]["include_usage"].as_bool().unwrap_or(false); let raw_effort = if !v["reasoning_effort"].is_null() { &v["reasoning_effort"] @@ -385,13 +711,16 @@ pub fn chat_request(body: &[u8]) -> anyhow::Result { }; let reasoning_effort = match raw_effort { Value::Null => None, - Value::String(s) => Some(s.trim().to_string()), + // "off" is Qwen4's name for "none"; the other families know only "none". + Value::String(s) => Some(match s.trim() { "off" => "none", t => t }.to_string()), Value::Number(n) => { let f = n.as_f64().context("reasoning_effort must be a finite number")?; Some(if f == 0.0 { "0".into() } else { format!("{f}") }) } _ => bail!("reasoning_effort must be a string or a number"), }; + // `reasoning_effort: "none"` turns thinking off for every family, not only those whose template reads it. + let think = think.or((reasoning_effort.as_deref() == Some("none")).then_some(false)); let thinking_budget = match int("thinking_budget", 0)? { Some(n) => Some(n as usize), None => match &v["chat_template_kwargs"]["thinking_budget"] { @@ -403,6 +732,7 @@ pub fn chat_request(body: &[u8]) -> anyhow::Result { preserve_thinking: v["chat_template_kwargs"]["preserve_thinking"].as_bool(), temperature: num("temperature", |f| f >= 0.0, "a number >= 0")?, top_k: int("top_k", 0)?.map(|n| n as usize), top_p: num("top_p", |f| f > 0.0 && f <= 1.0, "a number in (0, 1]")?, + min_p: num("min_p", |f| (0.0..=1.0).contains(&f), "a number in [0, 1]")?, presence_penalty: num("presence_penalty", |f| (-2.0..=2.0).contains(&f), "a number in [-2, 2]")?, frequency_penalty: num("frequency_penalty", |f| (-2.0..=2.0).contains(&f), "a number in [-2, 2]")?, repeat_penalty: num("repeat_penalty", |f| f > 0.0 && f <= 5.0, "a number in (0, 5]")?, @@ -412,7 +742,30 @@ pub fn chat_request(body: &[u8]) -> anyhow::Result { }, dry_multiplier: num("dry_multiplier", |f| (0.0..=5.0).contains(&f), "a number in [0, 5]")?, dry_base: num("dry_base", |f| f > 1.0 && f <= 4.0, "a number in (1, 4]")?, - dry_allowed_length: int("dry_allowed_length", 1)?.map(|n| n as usize), seed: int("seed", 0)?, stop }) + dry_allowed_length: int("dry_allowed_length", 1)?.map(|n| n as usize), seed: int("seed", 0)?, stop, + logit_bias: crate::grammar::parse_bias(&v["logit_bias"])?, grammar, head_sent: false }) +} + +impl ChatRequest { + /// `serve --reasoning-effort`: the effort of a request that names none; skipped when the request turned thinking + /// off (`enable_thinking: false`, Anthropic `thinking.type: "disabled"`, or a grammar), and a default of "none", + /// "off", or 0 does not turn off a request that explicitly asked for thinking. + pub fn default_effort(&mut self, effort: Option<&str>) { + if self.reasoning_effort.is_some() || self.think == Some(false) { return; } + let Some(e) = effort else { return }; + let e = if e == "off" { "none" } else { e }; + let off = e == "none" || e.parse::().is_ok_and(|n| n == 0.0); + if off && self.think == Some(true) { return; } + self.reasoning_effort = Some(e.to_string()); + if e == "none" { self.think = Some(false); } + } + + /// `serve --force-sampling`: forget the request's sampling fields, so the server's flags hold for clients (many + /// agent apps) that send their own temperature or top_p and cannot be told not to. + pub fn drop_sampling(&mut self) { + (self.temperature, self.top_k, self.top_p, self.min_p, self.presence_penalty, self.frequency_penalty, self.repeat_penalty, + self.penalty_last_n, self.dry_multiplier, self.dry_base, self.dry_allowed_length) = Default::default(); + } } /// What the chat page's side panel shows about the server, kept by the request loop and answered by the reader @@ -435,13 +788,23 @@ pub struct Stats { pub ctx_train: Option, /// Requests decoded at once (`--parallel`). pub slots: usize, + /// The loaded model answers one request at a time outside the main engine (`Queued` applies). + #[serde(skip)] + pub own: bool, + /// The `reasoning_effort` levels the loaded model honours, for `/v1/models`' meta and the page's think dropdown; + /// empty while a model loads or none is loaded. + #[serde(skip)] + pub efforts: Vec, /// Device memory in use and in total, measured after the load and after each request. pub vram: Option<(u64, u64)>, /// Host RAM cap in bytes (`total - --ram-margin`, or `--max-ram`); `None` if undetectable. pub ram_cap: Option, - /// MoE expert cache hits and misses, and MTP drafts tried and accepted, since the model loaded. + /// MoE expert cache hits and misses, and speculative drafts tried and accepted, since the model loaded. pub experts: Option<(u64, u64)>, pub drafts: Option<(u64, u64)>, + /// Label for `drafts` (used for the unload summary of `Runner::Own` models). + #[serde(skip)] + pub draft_kind: Option<&'static str>, /// Replies being generated, and their tokens so far. pub busy: usize, pub live_tokens: usize, @@ -471,6 +834,159 @@ pub struct Last { pub finish: String, } +/// Totals of answered chat requests for one model or one API key, kept across server runs (`rustingstrata stats`). +#[derive(Clone, Default, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct Totals { + pub requests: u64, + pub prompt_tokens: u64, + pub cached_tokens: u64, + pub completion_tokens: u64, + pub prefill_ms: f64, + pub decode_ms: f64, + /// Unix seconds of the first and the latest request. + pub first: u64, + pub last: u64, +} + +/// The file behind `rustingstrata stats`: totals by model and by key name ("open" without `--api-keys`). +#[derive(Default, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct Usage { + pub models: std::collections::BTreeMap, + pub keys: std::collections::BTreeMap, +} + +impl Totals { + fn add(&mut self, l: &Last) { + if self.requests == 0 { self.first = l.at; } + self.requests += 1; + self.prompt_tokens += l.prompt_tokens as u64; + self.cached_tokens += l.cached_tokens as u64; + self.completion_tokens += l.completion_tokens as u64; + self.prefill_ms += l.prefill_ms; + self.decode_ms += l.decode_ms; + self.last = l.at; + } +} + +impl Usage { + pub fn load(path: &Path) -> anyhow::Result { + match std::fs::read(path) { + Ok(b) => serde_json::from_slice(&b).with_context(|| format!("{}", path.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Usage::default()), + Err(e) => Err(e).with_context(|| format!("{}", path.display())), + } + } + + /// Adds one request to `path` (written to a temporary file and renamed, so a crash leaves the old totals). + // ponytail: read-modify-write per request under a process lock; two servers sharing the file can lose counts. + pub fn add(path: &Path, key: &str, l: &Last) -> anyhow::Result<()> { + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let mut u = Usage::load(path)?; + u.models.entry(l.model.clone()).or_default().add(l); + u.keys.entry(key.to_string()).or_default().add(l); + if let Some(d) = path.parent() { std::fs::create_dir_all(d)?; } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, serde_json::to_vec_pretty(&u)?)?; + Ok(std::fs::rename(&tmp, path)?) + } + + /// The table `rustingstrata stats` prints. + pub fn table(&self) -> String { + let n = |v: u64| match v { + v if v >= 1_000_000_000 => format!("{:.2}B", v as f64 / 1e9), + v if v >= 1_000_000 => format!("{:.2}M", v as f64 / 1e6), + v if v >= 10_000 => format!("{:.1}k", v as f64 / 1e3), + v => v.to_string(), + }; + let rate = |t: u64, ms: f64| if ms > 0.0 { format!("{:.1}", t as f64 * 1e3 / ms) } else { "-".into() }; + let mut s = String::new(); + for (title, m) in [("model", &self.models), ("key", &self.keys)] { + let w = m.keys().map(|k| k.chars().count()).max().unwrap_or(0).max(title.len()); + s += &format!("{title:8} {:>8} {:>8} {:>8} {:>8} {:>13} {:>12} {:<10} {:<10}\n", + "requests", "prompt", "cached", "output", "total", "prefill tok/s", "decode tok/s", "first", "last"); + let mut all = Totals::default(); + for (k, t) in m { + s += &format!("{k:8} {:>8} {:>8} {:>8} {:>8} {:>13} {:>12} {:<10} {:<10}\n", + t.requests, n(t.prompt_tokens), n(t.cached_tokens), n(t.completion_tokens), n(t.prompt_tokens + t.completion_tokens), + rate(t.prompt_tokens - t.cached_tokens.min(t.prompt_tokens), t.prefill_ms), rate(t.completion_tokens, t.decode_ms), + date(t.first), date(t.last)); + all.requests += t.requests; + all.prompt_tokens += t.prompt_tokens; + all.cached_tokens += t.cached_tokens; + all.completion_tokens += t.completion_tokens; + } + if m.len() > 1 { + s += &format!("{:8} {:>8} {:>8} {:>8} {:>8}\n", "all", all.requests, n(all.prompt_tokens), + n(all.cached_tokens), n(all.completion_tokens), n(all.prompt_tokens + all.completion_tokens)); + } + s += "\n"; + } + s + } +} + +/// `YYYY-MM-DD` (UTC) of Unix seconds. +fn date(secs: u64) -> String { + // Days to civil date (Howard Hinnant's algorithm). + let z = (secs / 86400) as i64 + 719468; + let era = z.div_euclid(146097); + let doe = z - era * 146097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + format!("{:04}-{m:02}-{d:02}", yoe + era * 400 + (m <= 2) as i64) +} + +#[cfg(test)] +mod usage_tests { + /// `--cors-origin`: a listed origin is echoed, `*` allows any, another origin gets no CORS lines. + #[test] + fn cors_origins() { + let list = ["http://a.example".to_string(), "http://b.example".into()]; + let l = super::cors_lines_for(&list, "http://b.example", "x-stainless-os"); + assert!(l.starts_with("Access-Control-Allow-Origin: http://b.example\r\n") && l.contains("x-api-key, x-stainless-os\r\n") && l.contains("Vary: Origin")); + assert!(super::cors_lines_for(&list, "http://evil.example", "").is_empty()); + assert!(super::cors_lines_for(&list, "", "").is_empty()); + assert!(super::cors_lines_for(&["*".into()], "", "").starts_with("Access-Control-Allow-Origin: *\r\n")); + } + + #[test] + fn slot_file_names_stay_in_the_folder() { + for f in ["a.bin", "slot_0-save.bin", "x"] { assert!(super::plain_file_name(f), "{f}"); } + for f in ["", ".", "..", "../x", "a/b", "a\\b", ".hidden", "c:x", "a b", "\u{e9}"] { assert!(!super::plain_file_name(f), "{f}"); } + } + + use super::{Last, Usage, date}; + + #[test] + fn usage_adds_and_persists() { + assert_eq!(date(0), "1970-01-01"); + assert_eq!(date(1795728053), "2026-11-26"); + assert_eq!(date(951782400), "2000-02-29"); + let p = std::env::temp_dir().join(format!("strata-usage-{}.json", std::process::id())); + let _ = std::fs::remove_file(&p); + let l = |at, model: &str| Last { at, model: model.into(), prompt_tokens: 100, cached_tokens: 40, completion_tokens: 20, + prefill_ms: 60.0, decode_ms: 400.0, ..Default::default() }; + Usage::add(&p, "open", &l(10, "a")).unwrap(); + Usage::add(&p, "open", &l(20, "a")).unwrap(); + Usage::add(&p, "bob", &l(30, "b")).unwrap(); + let u = Usage::load(&p).unwrap(); + std::fs::remove_file(&p).unwrap(); + let a = &u.models["a"]; + assert_eq!((a.requests, a.prompt_tokens, a.cached_tokens, a.completion_tokens, a.first, a.last), (2, 200, 80, 40, 10, 20)); + assert_eq!((u.keys["open"].requests, u.keys["bob"].requests, u.models["b"].first), (2, 1, 30)); + let t = u.table(); + // 120 new prompt tokens in 120 ms, 40 reply tokens in 800 ms. + assert!(t.lines().any(|r| r.starts_with("a ") && r.contains(" 1000.0 ") && r.contains(" 50.0 ")), "{t}"); + assert!(t.lines().any(|r| r.starts_with("all ")), "{t}"); + } +} + impl Stats { pub fn record(&mut self, l: Last) { self.requests += 1; @@ -481,6 +997,15 @@ impl Stats { self.recent.push_back(l); } + /// Adds one request's speculative draft counts to the loaded model's cumulative `drafts`. + pub fn add_drafts(&mut self, kind: &'static str, proposed: u64, accepted: u64) { + if proposed == 0 { return; } + let accepted = accepted.min(proposed); + let (p, a) = self.drafts.unwrap_or((0, 0)); + self.drafts = Some((p.saturating_add(proposed), a.saturating_add(accepted))); + self.draft_kind = Some(kind); + } + /// The stats in Prometheus text format, with `waiting` requests open besides the scrape. pub fn prometheus(&self, waiting: usize, uptime_s: u64) -> String { let mut s = String::new(); @@ -570,9 +1095,38 @@ pub fn system() -> Value { v } +/// llama.cpp's `POST /tokenize`: `{"content", "add_special", "with_pieces"}` to `{"tokens": [id, ...]}`, or with +/// pieces `{"tokens": [{"id", "piece"}, ...]}`, a piece being a string, or its bytes when it is not whole UTF-8. +pub fn tokenize(tok: &crate::tokenizer::Tokenizer, body: &[u8]) -> anyhow::Result { + let v: Value = serde_json::from_slice(body)?; + let content = v["content"].as_str().context("content: a string is required")?; + let flag = |k: &str| -> anyhow::Result { Ok(match &v[k] { Value::Null => false, x => x.as_bool().with_context(|| format!("{k}: not a boolean"))? }) }; + let ids = tok.encode_special(content, flag("add_special")?)?; + if !flag("with_pieces")? { return Ok(serde_json::json!({"tokens": ids})); } + let tokens: Vec = ids.iter().map(|&id| { + let b = tok.token_bytes(id); + let piece = match std::str::from_utf8(b) { Ok(s) => Value::from(s), Err(_) => Value::from(b.to_vec()) }; + serde_json::json!({"id": id, "piece": piece}) + }).collect(); + Ok(serde_json::json!({"tokens": tokens})) +} + +/// llama.cpp's `POST /detokenize`: `{"tokens": [id, ...]}` to `{"content": text}`. +pub fn detokenize(tok: &crate::tokenizer::Tokenizer, body: &[u8]) -> anyhow::Result { + let v: Value = serde_json::from_slice(body)?; + let ids = match &v["tokens"] { + Value::Null => vec![], + Value::Array(a) => a.iter().map(|t| t.as_u64().filter(|&t| (t as usize) < tok.vocab_size()).map(|t| t as u32) + .with_context(|| format!("tokens: {t} is not a token id"))).collect::>>()?, + _ => bail!("tokens: an array of ids is required"), + }; + Ok(serde_json::json!({"content": tok.decode(&ids)?})) +} + /// An Anthropic Messages API request (`POST /v1/messages`, what Claude Code sends) as the OpenAI chat request /// `chat_request` reads: the system blocks become a system message, `tool_use` blocks tool calls, `tool_result` -/// blocks tool messages, and `thinking: {"type": "enabled"}` turns thinking on. Images and server tools are dropped. +/// blocks tool messages, and `thinking: {"type": "enabled"}` / `{"type": "disabled"}` turns thinking on / off. +/// Images and server tools are dropped. pub fn messages_body(body: &[u8]) -> anyhow::Result> { let j: Json = serde_json::from_slice(body)?; let s = |x: &str| Json::Str(x.into()); @@ -640,14 +1194,124 @@ pub fn messages_body(body: &[u8]) -> anyhow::Result> { Some("tool") => out.push(("tool_choice", obj(vec![("type", s("function")), ("function", obj(vec![("name", j.get("tool_choice").get("name").clone())]))]))), _ => {} } - for (from, to) in [("max_tokens", "max_tokens"), ("temperature", "temperature"), ("top_p", "top_p"), ("top_k", "top_k"), ("stop_sequences", "stop"), ("stream", "stream")] { + for (from, to) in [("max_tokens", "max_tokens"), ("temperature", "temperature"), ("top_p", "top_p"), ("min_p", "min_p"), ("top_k", "top_k"), ("stop_sequences", "stop"), ("stream", "stream")] { if !matches!(j.get(from), Json::Null) { out.push((to, j.get(from).clone())); } } - if j.get("thinking").get("type").as_str() == Some("enabled") { - out.push(("chat_template_kwargs", obj(vec![("enable_thinking", Json::Bool(true))]))); - if !matches!(j.get("thinking").get("budget_tokens"), Json::Null) { - out.push(("thinking_budget", j.get("thinking").get("budget_tokens").clone())); + match j.get("thinking").get("type").as_str() { + Some("enabled") => { + out.push(("chat_template_kwargs", obj(vec![("enable_thinking", Json::Bool(true))]))); + if !matches!(j.get("thinking").get("budget_tokens"), Json::Null) { + out.push(("thinking_budget", j.get("thinking").get("budget_tokens").clone())); + } } + // Without this the server default (`--think`) applies, and a client could not turn thinking off. + Some("disabled") => out.push(("chat_template_kwargs", obj(vec![("enable_thinking", Json::Bool(false))]))), + _ => {} } Ok(obj(out).dump().into_bytes()) } + +#[cfg(test)] +mod messages_tests { + use super::messages_body; + + /// `serve --reasoning-effort` fills only a request that names no effort; "none" also turns thinking off. + #[test] + fn server_default_effort() { + let req = |b: &str| super::chat_request(b.as_bytes()).unwrap(); + let mut q = req(r#"{"messages":[{"role":"user","content":"hi"}]}"#); + q.default_effort(Some("xhigh")); + assert_eq!((q.reasoning_effort.as_deref(), q.think), (Some("xhigh"), None)); + let mut q = req(r#"{"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"low"}"#); + q.default_effort(Some("xhigh")); + assert_eq!(q.reasoning_effort.as_deref(), Some("low")); + let mut q = req(r#"{"messages":[{"role":"user","content":"hi"}]}"#); + q.default_effort(Some("none")); + assert_eq!(q.think, Some(false)); + // "off" is "none", from the flag and from a request (Inkling 2 and Kolibri know only "none"). + let mut q = req(r#"{"messages":[{"role":"user","content":"hi"}]}"#); + q.default_effort(Some("off")); + assert_eq!((q.reasoning_effort.as_deref(), q.think), (Some("none"), Some(false))); + let q = req(r#"{"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"off"}"#); + assert_eq!((q.reasoning_effort.as_deref(), q.think), (Some("none"), Some(false))); + let mut q = req(r#"{"messages":[{"role":"user","content":"hi"}]}"#); + q.default_effort(None); + assert_eq!((q.reasoning_effort, q.think), (None, None)); + } + + /// `--reasoning-effort` must not re-enable thinking on requests that disabled it (`enable_thinking: false`, + /// Anthropic `thinking.type: "disabled"`, or `response_format`/`grammar`), and `--reasoning-effort none|off|0` + /// must not override an explicit `enable_thinking: true` or Anthropic `thinking.type: "enabled"`. + #[test] + fn server_default_effort_respects_request_thinking_switch() { + let req = |b: &str| super::chat_request(b.as_bytes()).unwrap(); + let anth = |b: &str| super::chat_request(&messages_body(b.as_bytes()).unwrap()).unwrap(); + + // Request explicitly turns thinking off (or uses response_format without enable_thinking: true). + for mut q in [ + req(r#"{"messages":[{"role":"user","content":"hi"}],"chat_template_kwargs":{"enable_thinking":false}}"#), + req(r#"{"messages":[{"role":"user","content":"hi"}],"response_format":{"type":"json_object"}}"#), + anth(r#"{"model":"m","max_tokens":8,"messages":[{"role":"user","content":"hi"}],"thinking":{"type":"disabled"}}"#), + ] { + q.default_effort(Some("high")); + assert_eq!((q.reasoning_effort.as_deref(), q.think), (None, Some(false))); + assert_eq!(crate::inkling2::chat::parse_effort(q.reasoning_effort.as_deref(), q.think, true).unwrap(), "0"); + assert_eq!(crate::kolibri::chat::effort(q.think, q.reasoning_effort.as_deref()), "none"); + } + + // Request explicitly turns thinking on: server default none/off/0 must not force thinking back off. + for srv in ["none", "off", "0", "0.0"] { + for mut q in [ + req(r#"{"messages":[{"role":"user","content":"hi"}],"chat_template_kwargs":{"enable_thinking":true}}"#), + anth(r#"{"model":"m","max_tokens":8,"messages":[{"role":"user","content":"hi"}],"thinking":{"type":"enabled","budget_tokens":256}}"#), + ] { + q.default_effort(Some(srv)); + assert_eq!((q.reasoning_effort.as_deref(), q.think), (None, Some(true)), "server default {srv}"); + let (_, q4_think) = crate::chat::Template::Qwen4 { effort: None }.with_effort(q.reasoning_effort.as_deref(), q.think); + assert_eq!(q4_think, Some(true), "Qwen4 with server default {srv}"); + assert_eq!(crate::inkling2::chat::parse_effort(q.reasoning_effort.as_deref(), q.think, false).unwrap(), "0.9", "Inkling 2 with server default {srv}"); + assert_eq!(crate::kolibri::chat::effort(q.think, q.reasoning_effort.as_deref()), "high", "Kolibri with server default {srv}"); + } + } + + // A non-zero server default still supplies the effort level when the request enables thinking. + let mut q = req(r#"{"messages":[{"role":"user","content":"hi"}],"chat_template_kwargs":{"enable_thinking":true}}"#); + q.default_effort(Some("low")); + assert_eq!((q.reasoning_effort.as_deref(), q.think), (Some("low"), Some(true))); + } + + /// `thinking` maps to the template's `enable_thinking`, both ways, and its budget to `thinking_budget`. + #[test] + fn thinking_turns_thinking_on_and_off() { + let mapped = |thinking: &str| { + let body = format!(r#"{{"model":"m","max_tokens":8,"messages":[{{"role":"user","content":"hi"}}]{thinking}}}"#); + let v: serde_json::Value = serde_json::from_slice(&messages_body(body.as_bytes()).unwrap()).unwrap(); + (v["chat_template_kwargs"]["enable_thinking"].clone(), v["thinking_budget"].clone()) + }; + assert_eq!(mapped(r#","thinking":{"type":"enabled","budget_tokens":512}"#), (serde_json::json!(true), serde_json::json!(512))); + assert_eq!(mapped(r#","thinking":{"type":"disabled"}"#), (serde_json::json!(false), serde_json::Value::Null)); + assert_eq!(mapped(""), (serde_json::Value::Null, serde_json::Value::Null)); // the server default + } +} + +#[cfg(test)] +mod stats_tests { + use super::Stats; + + /// `efforts` starts empty and stays out of the `GET /api/stats` JSON, so the page's panel is unchanged. + #[test] + fn efforts_stay_out_of_the_stats_json() { + let s = Stats::default(); + assert!(s.efforts.is_empty()); + assert!(serde_json::to_value(&s).unwrap().get("efforts").is_none()); + } + + /// `unload` rebuilds the stats from defaults: a freed model takes its `reasoning_effort` levels with it. + #[test] + fn unload_clears_efforts() { + let mut s = Stats::default(); + s.efforts = vec!["none".into(), "low".into()]; + s.unload(None); + assert!(s.efforts.is_empty()); + } +} diff --git a/src/term.rs b/src/term.rs index d155bbdb..531a472e 100644 --- a/src/term.rs +++ b/src/term.rs @@ -19,10 +19,14 @@ fn vt(handle: u32) -> bool { } } #[cfg(not(windows))] -fn vt(_: u32) -> bool { true } +fn vt(_: u32) -> bool { + true +} fn wanted(tty: bool, handle: u32) -> bool { - tty && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty()) && std::env::var_os("TERM").is_none_or(|v| v != "dumb") && vt(handle) + tty && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty()) + && std::env::var_os("TERM").is_none_or(|v| v != "dumb") + && vt(handle) } /// Styling of stderr, where the status lines go. @@ -31,6 +35,13 @@ pub fn err() -> bool { *ON.get_or_init(|| wanted(std::io::stderr().is_terminal(), -12i32 as u32)) } +/// Whether stderr can safely receive an in-place progress row, independent of the color preference. +fn progress_enabled() -> bool { + std::io::stderr().is_terminal() + && std::env::var_os("TERM").is_none_or(|v| v != "dumb") + && vt(-12i32 as u32) +} + /// Styling of stdout, where the model's text and the prompts go. pub fn out() -> bool { static ON: OnceLock = OnceLock::new(); @@ -39,33 +50,1500 @@ pub fn out() -> bool { /// `s` in the SGR style `code` (`1` bold, `2` dim, `36` cyan) when `on`, else `s`. pub fn paint(on: bool, code: &str, s: &str) -> String { - if on { format!("\x1b[{code}m{s}\x1b[0m") } else { s.to_string() } + if on { + format!("\x1b[{code}m{s}\x1b[0m") + } else { + s.to_string() + } } /// One status line for stderr: a leading `warning` or `error` in colour, any other line dim, so the model's text /// stands out from the engine's notes. -pub fn status(s: &str) -> String { status_on(err(), s) } +pub fn status(s: &str) -> String { + // Leading blank lines stay before the time. + let t = s.trim_start_matches('\n'); + format!( + "{}{} {}", + &s[..s.len() - t.len()], + paint(err(), "2", &clock()), + status_on(err(), t) + ) +} + +/// The local wall-clock time as `[HH:MM:SS]`, which starts each status line. +pub fn clock() -> String { + let (h, m, s) = local_hms(); + format!("[{h:02}:{m:02}:{s:02}]") +} + +#[cfg(unix)] +fn local_hms() -> (i32, i32, i32) { + // `struct tm` starts with tm_sec, tm_min, tm_hour (ints) on every Unix; the buffer is larger than any `struct tm`. + unsafe extern "C" { + fn localtime_r(t: *const i64, tm: *mut [i32; 16]) -> *mut [i32; 16]; + } + let t = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64); + let mut tm = [0i32; 16]; + if unsafe { localtime_r(&t, &mut tm) }.is_null() { + return ( + (t / 3600 % 24) as i32, + (t / 60 % 60) as i32, + (t % 60) as i32, + ); + } + (tm[2], tm[1], tm[0]) +} + +#[cfg(windows)] +fn local_hms() -> (i32, i32, i32) { + // SYSTEMTIME: year, month, day of week, day, hour, minute, second, milliseconds. + unsafe extern "system" { + fn GetLocalTime(t: *mut [u16; 8]); + } + let mut t = [0u16; 8]; + unsafe { GetLocalTime(&mut t) }; + (t[4] as i32, t[5] as i32, t[6] as i32) +} + +#[cfg(not(any(unix, windows)))] +fn local_hms() -> (i32, i32, i32) { + let t = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + ( + (t / 3600 % 24) as i32, + (t / 60 % 60) as i32, + (t % 60) as i32, + ) +} + +use console::Term; +use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle}; +use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; +use std::sync::{Condvar, Mutex}; +use std::time::{Duration, Instant}; + +/// Prompt and reply tokens run so far, for the speed line (`live`). +static PREFILLED: AtomicUsize = AtomicUsize::new(0); +static DECODED: AtomicUsize = AtomicUsize::new(0); +static HIDE_DECODE_AT: AtomicUsize = AtomicUsize::new(usize::MAX); +#[derive(Clone)] +struct Rows { + multi: MultiProgress, + header: ProgressBar, + phase: ProgressBar, + prefill_progress: ProgressBar, + summary: ProgressBar, + details: ProgressBar, + quality: ProgressBar, + graph: Option>, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Mode { + Inference, + Calibration, +} + +#[derive(Clone, Default)] +struct Quality { + drafts: Option<(usize, usize)>, + experts: Option<(usize, usize)>, +} + +#[derive(Clone, Default)] +struct CalibrationStatus { + completed: usize, + total: usize, + sample: String, + sample_started: Option, + started: Option, + result: String, +} + +#[derive(Clone)] +struct Run { + started: Instant, + p0: usize, + d0: usize, + active: usize, + persistent: bool, + dirty: bool, + decode: bool, + graph_enabled: bool, + interval: Duration, + pretty: bool, + hidden_decode: bool, + expected_prefill: usize, + cached_prefill: usize, + quality: Quality, + prefill_tokens: usize, + prefill_seconds: f64, + decode_tokens: usize, + decode_seconds: f64, + requests: usize, + last_prefill_tokens: usize, + last_cached_tokens: usize, + last_prefill_seconds: f64, + last_decode_tokens: usize, + last_decode_seconds: f64, + mode: Mode, + calibration: CalibrationStatus, + rows: Option, +} +static RUN: OnceLock<(Mutex>, Condvar)> = OnceLock::new(); +fn run() -> &'static (Mutex>, Condvar) { + RUN.get_or_init(|| (Mutex::new(None), Condvar::new())) +} +static SETTINGS: OnceLock> = OnceLock::new(); +fn settings() -> &'static Mutex<(bool, Duration, bool, bool)> { + SETTINGS.get_or_init(|| Mutex::new((false, Duration::from_millis(500), false, false))) +} + +/// Counts `n` prompt tokens that ran through the model. +pub fn prefilled(n: usize) { + PREFILLED.fetch_add(n, Relaxed); +} + +/// Counts `n` reply tokens. +pub fn decoded(n: usize) { + let before = DECODED.fetch_add(n, Relaxed); + if n > 0 && before == HIDE_DECODE_AT.load(Relaxed) && before != usize::MAX { + HIDE_DECODE_AT.store(usize::MAX, Relaxed); + let mut guard = run().0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(r) = guard.as_mut().filter(|r| !r.decode) { + r.hidden_decode = true; + if let Some(rows) = r.rows.take() { + clear_rows(rows); + } + } + } +} + +fn make_rows(graph: bool) -> Rows { + let multi = MultiProgress::with_draw_target(ProgressDrawTarget::stderr_with_hz(10)); + let header = multi.add(ProgressBar::no_length()); + let graph = graph.then(|| { + (0..GRAPH_ROWS) + .map(|_| multi.add(ProgressBar::no_length())) + .collect::>() + }); + let phase = multi.add(ProgressBar::no_length()); + let prefill_progress = multi.add(ProgressBar::no_length()); + let summary = multi.add(ProgressBar::no_length()); + let details = multi.add(ProgressBar::no_length()); + let quality = multi.add(ProgressBar::no_length()); + let plain = ProgressStyle::with_template("{wide_msg:!}").unwrap(); + + header.set_style( + ProgressStyle::with_template(if err() { + "{spinner:.cyan.bold} {wide_msg:!}" + } else { + "{spinner} {wide_msg:!}" + }) + .unwrap() + .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ "), + ); + phase.set_style(plain.clone()); + prefill_progress.set_style(ProgressStyle::with_template("{msg}").unwrap()); + summary.set_style(plain.clone()); + details.set_style(plain.clone()); + quality.set_style(plain.clone()); + if let Some(graph) = &graph { + for row in graph { + row.set_style(plain.clone()); + } + } + + Rows { + multi, + header, + phase, + prefill_progress, + summary, + details, + quality, + graph, + } +} + +fn clear_rows(rows: Rows) { + for bar in [ + &rows.header, + &rows.phase, + &rows.prefill_progress, + &rows.summary, + &rows.details, + &rows.quality, + ] { + bar.finish_and_clear(); + } + if let Some(graph) = rows.graph { + for row in graph { + row.finish_and_clear(); + } + } + let _ = rows.multi.clear(); +} + +/// Configure the shared terminal renderer. Chat and generate suppress decode updates while text streams to stdout. +pub fn live(decode: bool, interval: Duration, pretty: bool, graph: bool) { + *settings().lock().unwrap_or_else(|e| e.into_inner()) = (decode, interval, pretty, graph); + let (lock, wake) = run(); + if let Some(r) = lock.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + r.decode = decode; + r.interval = interval; + r.pretty = pretty; + r.graph_enabled = graph; + } + wake.notify_all(); + if !pretty || progress_enabled() { + static WORKER: OnceLock<()> = OnceLock::new(); + WORKER.get_or_init(|| { + std::thread::Builder::new() + .name("strata-status".into()) + .spawn(status_worker) + .expect("status worker"); + }); + } +} + +const MAX_GRAPH_COLUMNS: usize = 50; +const MAX_GRAPH_SAMPLES: usize = MAX_GRAPH_COLUMNS * 2; +const MAX_PREFILL_COLUMN_WIDTH: usize = 30; + +/// Width available to each side of a paired status line. +fn paired_column_width(width: usize) -> usize { + width.saturating_sub(3) / 2 +} + +fn graph_column_width(width: usize) -> usize { + // Each graph gets up to 50 columns, while narrow terminals scale down to + // half the available width so both graphs and their separator still fit. + paired_column_width(width).min(MAX_GRAPH_COLUMNS) +} + +fn fit_column(value: &str, width: usize) -> String { + let mut chars = value.chars(); + let mut out: String = chars.by_ref().take(width).collect(); + if chars.next().is_some() && width > 0 { + out.pop(); + out.push('…'); + } + let used = out.chars().count(); + out.push_str(&" ".repeat(width.saturating_sub(used))); + out +} + +fn paired_text(left: &str, right: &str, width: usize) -> String { + // Status text should use all available terminal width, not the graph's cap. + let column_width = paired_column_width(width); + format!( + "{} │ {}", + fit_column(left, column_width), + fit_column(right, column_width) + ) +} + +/// Four terminal rows, with each Braille cell encoding two adjacent time samples. +const GRAPH_ROWS: usize = 4; +const BRAILLE_DOTS_PER_COLUMN: [u32; 4] = [0x40, 0x04, 0x02, 0x01]; +const BRAILLE_DOTS_PER_RIGHT_COLUMN: [u32; 4] = [0x80, 0x20, 0x10, 0x08]; + +/// Convert a rate into a 0..=16 vertical height. A terminal row contains four +/// Braille dot rows, so the four stacked terminal rows form one 16-dot bar. +fn graph_height(rate: f64, max_rate: f64) -> usize { + if !rate.is_finite() || rate <= 0.0 || !max_rate.is_finite() || max_rate <= 0.0 { + 0 + } else { + (rate / max_rate * (GRAPH_ROWS * 4) as f64) + .ceil() + .clamp(1.0, (GRAPH_ROWS * 4) as f64) as usize + } +} + +/// Return the dots for one quarter of a vertically stacked bar. Rows are +/// ordered top-to-bottom, while Braille dot indices are filled bottom-to-top. +fn braille_row_bits(height: usize, dots: &[u32; 4], row: usize) -> u32 { + let levels_below = (GRAPH_ROWS - 1 - row) * 4; + let filled_here = height.saturating_sub(levels_below).min(4); + dots.iter() + .take(filled_here) + .copied() + .fold(0, |bits, dot| bits | dot) +} + +/// Four terminal rows form a vertical graph. Each Braille cell carries two +/// adjacent time samples: the left dot column is the older sample and the +/// right dot column is the newer sample. The stacked rows extend bar height, +/// not the time axis. +fn braille_graph(values: &[f64], width: usize) -> Vec { + let width = width.min(MAX_GRAPH_COLUMNS); + if width == 0 { + return vec![String::new(); GRAPH_ROWS]; + } + + let sample_count = values.len().min(width * 2); + let recent = &values[values.len().saturating_sub(sample_count)..]; + let max_rate = recent + .iter() + .copied() + .filter(|rate| rate.is_finite() && *rate > 0.0) + .fold(0.0_f64, f64::max); + let mut rows = vec![String::new(); GRAPH_ROWS]; + + for pair in recent.chunks(2) { + let left = graph_height(pair[0], max_rate); + let right = pair.get(1).map_or(0, |rate| graph_height(*rate, max_rate)); + for (row, output) in rows.iter_mut().enumerate() { + let bits = braille_row_bits(left, &BRAILLE_DOTS_PER_COLUMN, row) + | braille_row_bits(right, &BRAILLE_DOTS_PER_RIGHT_COLUMN, row); + output.push(char::from_u32(0x2800 + bits).unwrap_or('⠀')); + } + } + + for row in &mut rows { + let rendered = row.chars().count(); + row.push_str(&"⠀".repeat(width.saturating_sub(rendered))); + } + rows +} + +fn set_graph_rows( + rows: &Rows, + prefill: &[f64], + decode: &[f64], + show_prefill: bool, + show_decode: bool, + width: usize, +) { + let Some(graph) = &rows.graph else { + return; + }; + if width < 3 { + clear_graph(rows); + return; + } + let column_width = graph_column_width(width); + let blank = vec!["⠀".repeat(column_width); GRAPH_ROWS]; + let p = if show_prefill { + braille_graph(prefill, column_width) + } else { + blank.clone() + }; + let d = if show_decode { + braille_graph(decode, column_width) + } else { + blank + }; + for row in 0..GRAPH_ROWS { + graph[row].set_message(format!("{} │ {}", p[row], d[row])); + } +} + +fn terminal_width() -> usize { + Term::stderr() + .size_checked() + .map_or(80, |(_, columns)| usize::from(columns).max(1)) +} + +fn prefill_bar_style() -> ProgressStyle { + ProgressStyle::with_template(if err() { + "{prefix:.green.bold} {bar:12.green/green} {wide_msg:!}" + } else { + "{prefix} {bar:12} {wide_msg:!}" + }) + .unwrap() + .progress_chars("─╸ ") +} + +fn prefill_progress_style(bar_width: usize) -> ProgressStyle { + ProgressStyle::with_template(&format!("{{bar:{bar_width}.green/green}} {{msg}}")) + .unwrap() + .progress_chars("─╸ ") +} + +fn format_progress_count(n: usize) -> String { + if n >= 10_000 { + format!("{}k", n / 1_000) + } else { + format_count(n) + } +} + +/// Draw the prompt progress bar in the left column and reserve the right column +/// for the decode graph. Keeping both columns the same width prevents wrapping. +fn draw_prefill_progress(rows: &Rows, r: &Run, state: &Sample, width: usize) { + let idle = r.persistent && r.active == 0; + let total = if idle { + r.last_prefill_tokens + } else { + r.expected_prefill + }; + + if total == 0 { + rows.prefill_progress + .set_style(ProgressStyle::with_template("{msg}").unwrap()); + rows.prefill_progress.set_message(String::new()); + return; + } + + let completed = if idle { + total + } else { + state.prefill.min(total) + }; + // Keep the prefill progress layout unchanged; only the graph and paired + // status text use the wider terminal-aware columns. + let column_width = graph_column_width(width).min(MAX_PREFILL_COLUMN_WIDTH); + let bar_width = column_width.saturating_sub(3).min(8).max(1); + let message_width = column_width.saturating_sub(bar_width + 1); + let eta = if completed >= total { + "complete".to_string() + } else if state.prefill_rate.is_finite() && state.prefill_rate > 0.0 { + let remaining = total.saturating_sub(completed); + let seconds = remaining as f64 / state.prefill_rate; + let eta_duration = if !seconds.is_finite() || seconds >= u64::MAX as f64 { + Duration::MAX + } else { + Duration::from_secs_f64(seconds.max(0.0)) + }; + format!("ETA {}", format_eta(eta_duration)) + } else { + "ETA —".to_string() + }; + let label = format!( + "{}/{} {eta}", + format_progress_count(completed), + format_progress_count(total) + ); + + rows.prefill_progress + .set_style(prefill_progress_style(bar_width)); + rows.prefill_progress.set_length(total.max(1) as u64); + rows.prefill_progress + .set_position(completed.min(total) as u64); + rows.prefill_progress.set_message(format!( + "{} │ {}", + fit_column(&label, message_width), + " ".repeat(column_width) + )); +} + +fn push_graph_sample(history: &mut std::collections::VecDeque, rate: f64) { + if history.len() == MAX_GRAPH_SAMPLES { + let _ = history.pop_front(); + } + history.push_back(rate); +} + +fn calibration_progress(completed: usize, total: usize, elapsed: Duration) -> String { + let percent = if total == 0 { + 100 + } else { + (100.0 * completed.min(total) as f64 / total as f64).round() as usize + }; + let remaining = total.saturating_sub(completed); + let eta = if completed > 0 { + format!( + "ETA {}", + format_eta(Duration::from_secs_f64( + elapsed.as_secs_f64() * remaining as f64 / completed as f64 + )) + ) + } else { + "ETA —".to_string() + }; + format!("{percent}% · {eta} · {remaining} left") +} + +fn format_eta(d: Duration) -> String { + let seconds = d.as_secs_f64(); + if seconds >= 3600.0 { + format!("{:.0}h", seconds / 3600.0) + } else if seconds >= 60.0 { + format!("{}m{:02}s", d.as_secs() / 60, d.as_secs() % 60) + } else if seconds >= 10.0 { + format!("{:.0}s", seconds) + } else { + format!("{seconds:.1}s") + } +} + +fn weighted_rate(tokens: usize, seconds: f64) -> Option { + (seconds.is_finite() && seconds > 0.0).then(|| tokens as f64 / seconds) +} + +#[cfg(test)] +fn average_status(phase: &str, tokens: usize, seconds: f64) -> String { + weighted_rate(tokens, seconds).map_or_else(String::new, |rate| { + format!( + "AVG {phase} · {rate:.1} tok/s · {} tokens · {} elapsed", + format_count(tokens), + format_duration(Duration::from_secs_f64(seconds)) + ) + }) +} + +#[cfg(test)] +fn server_average_status(requests: usize, phase: &str, tokens: usize, seconds: f64) -> String { + if requests == 0 { + String::new() + } else { + average_status(phase, tokens, seconds) + } +} + +#[cfg(test)] +fn server_last_status(phase: &str, tokens: usize, seconds: f64) -> String { + let mut s = format!("LAST {} tokens", format_count(tokens)); + if let Some(rate) = weighted_rate(tokens, seconds) { + s.push_str(&format!( + " · {} tok/s · {}", + format_rate(rate), + format_duration(Duration::from_secs_f64(seconds)) + )); + } + format!("{phase} {s}") +} + +fn calibration_result( + prefill: Option, + decode: Option, + drafts: Option<(usize, usize)>, +) -> String { + let mut result = Vec::new(); + if let Some(rate) = prefill { + result.push(format!("PREFILL {:.0} tok/s", rate)); + } + if let Some(rate) = decode { + result.push(format!("DECODE {:.1} tok/s", rate)); + } + if let Some((offered, accepted)) = drafts.filter(|(offered, _)| *offered > 0) { + result.push(format!( + "DRAFT {:.1}%", + accepted as f64 * 100.0 / offered as f64 + )); + } + result.join(" · ") +} + +fn draw_rows(rows: &Rows, r: &Run, state: Sample) { + let elapsed = format_duration(state.elapsed); + let active = if r.active > 1 { + format!(" · {} active requests (aggregate)", r.active) + } else { + String::new() + }; + let title = if r.mode == Mode::Calibration { + "CALIBRATION" + } else if r.persistent { + "SERVER" + } else { + "INFERENCE" + }; + rows.header + .set_message(format!("{title} · {elapsed}{active}")); + + if r.mode == Mode::Calibration { + rows.phase.set_message(format!( + "SAMPLE {}/{}", + r.calibration.completed, r.calibration.total + )); + rows.prefill_progress.set_style(prefill_bar_style()); + rows.prefill_progress + .set_length(r.calibration.total.max(1) as u64); + rows.prefill_progress + .set_position(r.calibration.completed.min(r.calibration.total) as u64); + rows.prefill_progress.set_prefix("CAL"); + let calibration_elapsed = r + .calibration + .started + .map_or(Duration::ZERO, |t| t.elapsed()); + rows.prefill_progress.set_message(calibration_progress( + r.calibration.completed, + r.calibration.total, + calibration_elapsed, + )); + rows.summary.set_message(r.calibration.result.clone()); + rows.details.set_message(String::new()); + rows.quality.set_message(String::new()); + clear_graph(rows); + return; + } + + let width = terminal_width(); + if r.persistent && r.active == 0 { + rows.header.set_message(if r.requests == 0 { + "SERVER · waiting for requests".into() + } else { + format!("SERVER · idle · {} requests", r.requests) + }); + + let p_avg = weighted_rate(r.prefill_tokens, r.prefill_seconds).map_or_else( + || "—".to_string(), + |rate| format!("{} tok/s", format_compact_rate(rate)), + ); + let d_avg = weighted_rate(r.decode_tokens, r.decode_seconds).map_or_else( + || "—".to_string(), + |rate| format!("{} tok/s", format_compact_rate(rate)), + ); + let p_last_rate = weighted_rate(r.last_prefill_tokens, r.last_prefill_seconds) + .map_or_else(String::new, |rate| { + format!(" · {} tok/s", format_compact_rate(rate)) + }); + let d_last_rate = weighted_rate(r.last_decode_tokens, r.last_decode_seconds) + .map_or_else(String::new, |rate| { + format!(" · {} tok/s", format_compact_rate(rate)) + }); + let p_last = if r.requests == 0 { + "LAST —".to_string() + } else { + let cached = if r.last_cached_tokens > 0 { + format!(" +{}c", format_progress_count(r.last_cached_tokens)) + } else { + String::new() + }; + format!( + "LAST {} new{cached}{p_last_rate}", + format_compact_count(r.last_prefill_tokens) + ) + }; + let d_last = if r.requests == 0 { + "LAST —".to_string() + } else { + format!( + "LAST {}{d_last_rate}", + format_compact_count(r.last_decode_tokens) + ) + }; + + rows.phase.set_message(paired_text( + &format!("PREFILL AVG {p_avg}"), + &format!("DECODE AVG {d_avg}"), + width, + )); + draw_prefill_progress(rows, r, &state, width); + rows.summary + .set_style(ProgressStyle::with_template("{wide_msg:!}").unwrap()); + rows.summary.set_prefix(""); + rows.summary + .set_message(paired_text(&p_last, &d_last, width)); + rows.details.set_message(String::new()); + rows.quality.set_message(styled_quality_status(&r.quality)); + set_graph_rows( + rows, + &state.prefill_history, + &state.decode_history, + !state.prefill_history.is_empty(), + !state.decode_history.is_empty(), + width, + ); + return; + } + + let prefill_pending = r.expected_prefill > state.prefill; + let (mut prefill_visible, mut decode_visible) = visible_phases( + state.prefill_delta, + state.decode_delta, + prefill_pending, + r.decode, + state.prefill, + state.decode, + ); + prefill_visible |= !state.prefill_history.is_empty(); + decode_visible |= r.decode && !state.decode_history.is_empty(); + + let p_rate = if state.prefill_rate > 0.0 { + format!("{} tok/s", format_compact_rate(state.prefill_rate)) + } else { + "— tok/s".to_string() + }; + let d_rate = if state.decode_rate > 0.0 { + format!("{} tok/s", format_compact_rate(state.decode_rate)) + } else { + "— tok/s".to_string() + }; + let p_phase = if prefill_visible { + format!("PREFILL {} · {p_rate}", format_compact_count(state.prefill)) + } else { + "PREFILL —".to_string() + }; + let d_phase = if decode_visible { + format!("DECODE {} · {d_rate}", format_compact_count(state.decode)) + } else { + "DECODE —".to_string() + }; + rows.phase + .set_message(paired_text(&p_phase, &d_phase, width)); + draw_prefill_progress(rows, r, &state, width); + + if r.persistent { + let p_avg = weighted_rate(r.prefill_tokens, r.prefill_seconds).map_or_else( + || "—".to_string(), + |rate| format!("{} tok/s", format_compact_rate(rate)), + ); + let d_avg = weighted_rate(r.decode_tokens, r.decode_seconds).map_or_else( + || "—".to_string(), + |rate| format!("{} tok/s", format_compact_rate(rate)), + ); + let p_last_rate = weighted_rate(r.last_prefill_tokens, r.last_prefill_seconds) + .map_or_else(String::new, |rate| { + format!(" · {} tok/s", format_compact_rate(rate)) + }); + let d_last_rate = weighted_rate(r.last_decode_tokens, r.last_decode_seconds) + .map_or_else(String::new, |rate| { + format!(" · {} tok/s", format_compact_rate(rate)) + }); + let p_last = if r.requests == 0 { + "LAST —".to_string() + } else { + let cached = if r.last_cached_tokens > 0 { + format!(" +{}c", format_progress_count(r.last_cached_tokens)) + } else { + String::new() + }; + format!( + "LAST {} new{cached}{p_last_rate}", + format_compact_count(r.last_prefill_tokens) + ) + }; + let d_last = if r.requests == 0 { + "LAST —".to_string() + } else { + format!( + "LAST {}{d_last_rate}", + format_compact_count(r.last_decode_tokens) + ) + }; + rows.summary + .set_style(ProgressStyle::with_template("{wide_msg:!}").unwrap()); + rows.summary.set_prefix(""); + rows.summary.set_message(paired_text( + &format!("AVG {p_avg} · {p_last}"), + &format!("AVG {d_avg} · {d_last}"), + width, + )); + } else { + rows.summary + .set_style(ProgressStyle::with_template("{wide_msg:!}").unwrap()); + rows.summary.set_prefix(""); + rows.summary.set_message(String::new()); + } + + set_graph_rows( + rows, + &state.prefill_history, + &state.decode_history, + prefill_visible, + decode_visible, + width, + ); + rows.details.set_message(format!( + "ELAPSED {} · {} active request{}", + elapsed, + r.active, + if r.active == 1 { "" } else { "s" } + )); + rows.quality.set_message(styled_quality_status(&r.quality)); +} + +fn clear_graph(rows: &Rows) { + if let Some(graph) = &rows.graph { + for row in graph { + row.set_message(String::new()); + } + } +} + +fn draft_status(value: Option<(usize, usize)>) -> String { + value.map_or_else( + || "DRAFT acceptance —".to_string(), + |(made, accepted)| { + if made == 0 { + "DRAFT acceptance —".into() + } else { + format!( + "DRAFT acceptance {:.1}% · {}/{} · cumulative", + accepted as f64 * 100.0 / made as f64, + format_count(accepted), + format_count(made) + ) + } + }, + ) +} + +fn expert_status(value: Option<(usize, usize)>) -> String { + value.map_or_else( + || "EXPERT hit rate —".to_string(), + |(hits, misses)| { + let total = hits + misses; + if total == 0 { + "EXPERT hit rate —".into() + } else { + format!( + "EXPERT hit rate {:.1}% · {} hits / {} misses · cumulative", + hits as f64 * 100.0 / total as f64, + format_count(hits), + format_count(misses) + ) + } + }, + ) +} + +fn quality_status(quality: &Quality) -> String { + [ + quality.drafts.map(|v| draft_status(Some(v))), + quality.experts.map(|v| expert_status(Some(v))), + ] + .into_iter() + .flatten() + .filter(|s| !s.ends_with('—')) + .collect::>() + .join(" · ") +} + +fn styled_quality_status(quality: &Quality) -> String { + quality_status(quality) + .replace( + "DRAFT acceptance", + &paint(err(), "1;33", "DRAFT acceptance"), + ) + .replace("EXPERT hit rate", &paint(err(), "1;36", "EXPERT hit rate")) +} + +fn visible_phases( + prefill_delta: usize, + decode_delta: usize, + prefill_pending: bool, + decode_enabled: bool, + prefilled: usize, + decoded: usize, +) -> (bool, bool) { + let prefill = prefill_delta > 0 || prefill_pending || prefilled > 0; + let decode = decode_enabled && (decode_delta > 0 || decoded > 0); + (prefill, decode) +} + +fn status_worker() { + let (lock, wake) = run(); + let (mut last_p, mut last_d, mut at) = (0usize, 0usize, Instant::now()); + let (mut p_rate, mut d_rate) = (0.0f64, 0.0f64); + let (mut p_history, mut d_history) = ( + std::collections::VecDeque::new(), + std::collections::VecDeque::new(), + ); + let mut session = None; + let mut drawn_width = terminal_width(); + let mut last_draw = Instant::now(); + loop { + let mut guard = lock.lock().unwrap_or_else(|e| e.into_inner()); + let (r, idle) = loop { + while guard.is_none() { + guard = wake.wait(guard).unwrap_or_else(|e| e.into_inner()); + } + let current = guard.as_ref().unwrap(); + if current.active == 0 { + if current.persistent { + if current.dirty { + let snapshot = current.clone(); + guard.as_mut().unwrap().dirty = false; + break (snapshot, true); + } + let idle_interval = current.interval.min(Duration::from_millis(250)); + let (next, timed) = wake + .wait_timeout(guard, idle_interval) + .unwrap_or_else(|e| e.into_inner()); + guard = next; + if timed.timed_out() && terminal_width() != drawn_width { + if let Some(snapshot) = guard.as_ref().cloned() { + break (snapshot, true); + } + } + continue; + } + guard = wake.wait(guard).unwrap_or_else(|e| e.into_inner()); + continue; + } + let interval = current.interval; + let probe = interval.min(Duration::from_millis(100)); + let (next, timed) = wake + .wait_timeout(guard, probe) + .unwrap_or_else(|e| e.into_inner()); + guard = next; + if timed.timed_out() + && (last_draw.elapsed() >= interval || terminal_width() != drawn_width) + && let Some(snapshot) = guard.as_ref().cloned() + { + break (snapshot, false); + } + }; + if idle { + if r.persistent { + if session != Some(r.started) { + last_p = r.p0; + last_d = r.d0; + at = r.started; + p_rate = 0.0; + d_rate = 0.0; + } + let now = Instant::now(); + let (p, d) = (PREFILLED.load(Relaxed), DECODED.load(Relaxed)); + let (dp, dd) = (p.saturating_sub(last_p), d.saturating_sub(last_d)); + let secs = now.duration_since(at).as_secs_f64().max(1e-9); + if dp > 0 { + p_rate = sample_rate(dp, secs); + push_graph_sample(&mut p_history, p_rate); + } + if dd > 0 { + d_rate = sample_rate(dd, secs); + push_graph_sample(&mut d_history, d_rate); + } + (last_p, last_d, at) = (p, d, now); + } + let prefill_history = p_history.iter().copied().collect(); + let decode_history = d_history.iter().copied().collect(); + drop(guard); + if let Some(rows) = &r.rows { + draw_rows( + rows, + &r, + Sample { + elapsed: r.started.elapsed(), + prefill: 0, + decode: 0, + prefill_delta: 0, + decode_delta: 0, + prefill_rate: p_rate, + decode_rate: d_rate, + prefill_history, + decode_history, + }, + ); + drawn_width = terminal_width(); + last_draw = Instant::now(); + } + session = Some(r.started); + continue; + } + drop(guard); + if session != Some(r.started) { + session = Some(r.started); + if !r.persistent { + p_history.clear(); + d_history.clear(); + } + if r.persistent { + last_p = r.p0; + last_d = r.d0; + at = r.started; + } else { + last_p = r.p0; + last_d = r.d0; + at = r.started; + } + p_rate = 0.0; + d_rate = 0.0; + } + let now = Instant::now(); + let (p, d) = (PREFILLED.load(Relaxed), DECODED.load(Relaxed)); + let (p_total, d_total) = (p.saturating_sub(r.p0), d.saturating_sub(r.d0)); + let (dp, dd) = (p.saturating_sub(last_p), d.saturating_sub(last_d)); + let secs = now.duration_since(at).as_secs_f64().max(1e-9); + if dp > 0 { + p_rate = sample_rate(dp, secs); + } + if dd > 0 { + d_rate = sample_rate(dd, secs); + } + // Prefill may still be in flight after another parallel slot starts decoding. + if dp > 0 { + push_graph_sample(&mut p_history, p_rate); + } + if dd > 0 { + push_graph_sample(&mut d_history, d_rate); + } + if !r.pretty { + if r.mode == Mode::Inference { + if let Some(line) = speed_line( + p_total, + d_total, + dp, + dd, + now.duration_since(r.started).as_secs_f64(), + secs, + r.decode, + ) { + crate::say!("{line}"); + } + } + last_draw = Instant::now(); + drawn_width = terminal_width(); + } else if let Some(rows) = &r.rows { + let guard = lock.lock().unwrap_or_else(|e| e.into_inner()); + if guard.as_ref().is_some_and(|current| { + current.started == r.started && current.active > 0 && !current.hidden_decode + }) { + draw_rows( + rows, + &r, + Sample { + elapsed: now.duration_since(r.started), + prefill: p_total, + decode: d_total, + prefill_delta: dp, + decode_delta: dd, + prefill_rate: p_rate, + decode_rate: d_rate, + prefill_history: p_history.iter().copied().collect(), + decode_history: d_history.iter().copied().collect(), + }, + ); + rows.header.tick(); + drawn_width = terminal_width(); + last_draw = Instant::now(); + } + } + (last_p, last_d, at) = (p, d, now); + } +} + +struct Sample { + elapsed: Duration, + prefill: usize, + decode: usize, + prefill_delta: usize, + decode_delta: usize, + prefill_rate: f64, + decode_rate: f64, + prefill_history: Vec, + decode_history: Vec, +} + +fn sample_rate(delta: usize, elapsed_s: f64) -> f64 { + if delta == 0 || !elapsed_s.is_finite() || elapsed_s <= 0.0 { + 0.0 + } else { + delta as f64 / elapsed_s + } +} + +fn format_compact_count(n: usize) -> String { + if n >= 1_000_000 { + format!("{:.1}M", n as f64 / 1_000_000.0) + } else if n >= 10_000 { + format!("{:.1}k", n as f64 / 1_000.0) + } else { + format_count(n) + } +} + +fn format_compact_rate(n: f64) -> String { + if n >= 100.0 { + format_count(n.round() as usize) + } else { + format!("{n:.1}") + } +} + +#[cfg(test)] +fn format_rate(n: f64) -> String { + if n >= 1_000_000.0 { + format!("{:.1}M", n / 1_000_000.0) + } else if n >= 10_000.0 { + format!("{:.1}k", n / 1000.0) + } else if n >= 100.0 { + format_count(n.round() as usize) + } else { + format!("{n:.1}") + } +} +fn format_count(n: usize) -> String { + let s = n.to_string(); + let mut out = String::with_capacity(s.len() + s.len() / 3); + for (i, c) in s.chars().enumerate() { + if i > 0 && (s.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + out +} +fn format_duration(d: Duration) -> String { + format!("{:.2}s", d.as_secs_f64()) +} + +/// The speed line from the tokens of this run (`dp`, `dd`), those since the last line (`np`, `nd`), the seconds the +/// prompt tokens took and the seconds since the last line. None when nothing ran. +fn speed_line( + dp: usize, + dd: usize, + np: usize, + nd: usize, + prefill_s: f64, + window_s: f64, + decode: bool, +) -> Option { + if dd > 0 { + return (decode && nd > 0).then(|| { + format!( + "decode: {:.1} tok/s, {dd} tok", + nd as f64 / window_s.max(1e-9) + ) + }); + } + (np > 0).then(|| { + format!( + "prefill: {:.1} tok/s, {dp} tok", + dp as f64 / prefill_s.max(1e-9) + ) + }) +} + +/// A request or chat turn that generates; the speed line (`live`) covers it until it is dropped. Requests that run +/// at once (`serve --parallel`) share one line. +pub struct Live { + prefill_goal: usize, + cached_goal: usize, +} + +impl Live { + pub fn start() -> Live { + let (lock, wake) = run(); + let mut guard = lock.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(r) = guard.as_mut() { + if r.persistent && r.active == 0 { + r.started = Instant::now(); + r.p0 = PREFILLED.load(Relaxed); + r.d0 = DECODED.load(Relaxed); + r.expected_prefill = 0; + r.cached_prefill = 0; + r.quality = Quality::default(); + r.hidden_decode = false; + r.mode = Mode::Inference; + r.calibration = CalibrationStatus::default(); + } + r.active += 1; + } else { + let (decode, interval, pretty, graph_enabled) = + *settings().lock().unwrap_or_else(|e| e.into_inner()); + let rows = (pretty && progress_enabled()).then(|| make_rows(graph_enabled)); + let d0 = DECODED.load(Relaxed); + if !decode { + HIDE_DECODE_AT.store(d0, Relaxed); + } + *guard = Some(Run { + started: Instant::now(), + p0: PREFILLED.load(Relaxed), + d0, + active: 1, + persistent: false, + dirty: false, + decode, + graph_enabled, + interval, + pretty, + hidden_decode: false, + expected_prefill: 0, + cached_prefill: 0, + quality: Quality::default(), + prefill_tokens: 0, + prefill_seconds: 0.0, + decode_tokens: 0, + decode_seconds: 0.0, + requests: 0, + last_prefill_tokens: 0, + last_cached_tokens: 0, + last_prefill_seconds: 0.0, + last_decode_tokens: 0, + last_decode_seconds: 0.0, + mode: Mode::Inference, + calibration: CalibrationStatus::default(), + rows, + }); + } + wake.notify_all(); + Live { + prefill_goal: 0, + cached_goal: 0, + } + } + + /// Set a known number of model-processed prompt tokens for ETA estimation. + pub fn prefill_total(&mut self, total: usize) { + let add = total.saturating_sub(self.prefill_goal); + self.prefill_goal = total; + if let Some(r) = run().0.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + r.expected_prefill = r.expected_prefill.saturating_add(add); + } + } + /// Count reusable prompt tokens separately from work that actually reaches the model. + pub fn prefill_cached(&mut self, cached: usize) { + let (add, remove) = ( + cached.saturating_sub(self.cached_goal), + self.cached_goal.saturating_sub(cached), + ); + self.cached_goal = cached; + if let Some(r) = run().0.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + r.cached_prefill = r.cached_prefill.saturating_add(add).saturating_sub(remove); + } + } + /// Attach completed request counters for the experts and speculative drafter rows. + pub fn quality(&mut self, experts: Option<(usize, usize)>, drafts: Option<(usize, usize)>) { + if let Some(r) = run().0.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + if experts.is_some() { + r.quality.experts = experts; + } + if drafts.is_some() { + r.quality.drafts = drafts; + } + } + } +} + +impl Drop for Live { + fn drop(&mut self) { + let (lock, wake) = run(); + let mut guard = lock.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(r) = guard.as_mut() { + r.active = r.active.saturating_sub(1); + if r.active == 0 { + if r.persistent { + r.dirty = true; + } else { + if let Some(rows) = r.rows.take() { + clear_rows(rows); + } + *guard = None; + } + wake.notify_all(); + } + } + } +} + +/// A calibration run uses the same bottom-anchored rows as inference and clears them on every exit path. +pub struct CalibrationLive { + _live: Live, +} + +pub fn calibration_start(total: usize) -> CalibrationLive { + let live = Live::start(); + if let Some(r) = run().0.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + r.mode = Mode::Calibration; + r.calibration = CalibrationStatus { + total, + started: Some(Instant::now()), + ..CalibrationStatus::default() + }; + } + CalibrationLive { _live: live } +} + +pub fn calibration_sample_start(label: &str) { + if let Some(r) = run().0.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + r.calibration.sample = label.to_string(); + r.calibration.sample_started = Some(Instant::now()); + r.calibration.result.clear(); + } +} + +pub fn calibration_sample_done( + label: &str, + prefill: Option, + decode: Option, + drafts: Option<(usize, usize)>, +) { + if let Some(r) = run().0.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + r.calibration.completed = r.calibration.completed.saturating_add(1); + r.calibration.sample = label.to_string(); + r.calibration.sample_started = None; + r.calibration.result = calibration_result(prefill, decode, drafts); + } +} + +/// Publish cumulative draft and expert counters for the active inference request(s). +pub fn quality(experts: Option<(usize, usize)>, drafts: Option<(usize, usize)>) { + if let Some(r) = run().0.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + if experts.is_some() { + r.quality.experts = experts; + } + if drafts.is_some() { + r.quality.drafts = drafts; + } + } +} + +/// Replace server quality summaries after a request, clearing metrics that the current model cannot report. +pub fn server_quality(experts: Option<(usize, usize)>, drafts: Option<(usize, usize)>) { + if let Some(r) = run() + .0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_mut() + .filter(|r| r.persistent) + { + r.quality = Quality { experts, drafts }; + r.dirty = true; + } +} + +/// Keep one aggregate server panel mounted between requests and until the server exits. +pub struct ServerStatus; + +pub fn server_status(interval: Duration, pretty: bool, graph: bool) -> ServerStatus { + live(true, interval, pretty, graph); + let (lock, wake) = run(); + let mut guard = lock.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(r) = guard.as_mut() { + r.persistent = true; + r.dirty = true; + } else { + let (decode, interval, pretty, graph_enabled) = + *settings().lock().unwrap_or_else(|e| e.into_inner()); + let rows = (pretty && progress_enabled()).then(|| make_rows(graph_enabled)); + *guard = Some(Run { + started: Instant::now(), + p0: PREFILLED.load(Relaxed), + d0: DECODED.load(Relaxed), + active: 0, + persistent: true, + dirty: true, + decode, + graph_enabled, + interval, + pretty, + hidden_decode: false, + expected_prefill: 0, + cached_prefill: 0, + quality: Quality::default(), + prefill_tokens: 0, + prefill_seconds: 0.0, + decode_tokens: 0, + decode_seconds: 0.0, + requests: 0, + last_prefill_tokens: 0, + last_cached_tokens: 0, + last_prefill_seconds: 0.0, + last_decode_tokens: 0, + last_decode_seconds: 0.0, + mode: Mode::Inference, + calibration: CalibrationStatus::default(), + rows, + }); + } + wake.notify_all(); + ServerStatus +} + +/// Update the weighted server averages from one completed (or partially completed) request. +pub fn server_sample( + prefill_tokens: usize, + cached_tokens: usize, + prefill_seconds: f64, + decode_tokens: usize, + decode_seconds: f64, +) { + let (lock, wake) = run(); + if let Some(r) = lock + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_mut() + .filter(|r| r.persistent) + { + r.prefill_tokens = r.prefill_tokens.saturating_add(prefill_tokens); + r.prefill_seconds += prefill_seconds.max(0.0); + r.decode_tokens = r.decode_tokens.saturating_add(decode_tokens); + r.decode_seconds += decode_seconds.max(0.0); + r.last_prefill_tokens = prefill_tokens; + r.last_cached_tokens = cached_tokens; + r.last_prefill_seconds = prefill_seconds.max(0.0); + r.last_decode_tokens = decode_tokens; + r.last_decode_seconds = decode_seconds.max(0.0); + r.requests = r.requests.saturating_add(1); + r.dirty = true; + wake.notify_all(); + } +} + +impl Drop for ServerStatus { + fn drop(&mut self) { + let (lock, wake) = run(); + let mut guard = lock.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(r) = guard.as_mut().filter(|r| r.persistent) { + if let Some(rows) = r.rows.take() { + clear_rows(rows); + } + *guard = None; + } + wake.notify_all(); + } +} fn status_on(on: bool, s: &str) -> String { - if !on { return s.to_string(); } + if !on { + return s.to_string(); + } for (label, code) in [("warning", "1;33"), ("error", "1;31")] { - if let Some(rest) = s.strip_prefix(label) { return format!("\x1b[{code}m{label}\x1b[0m{rest}"); } + if let Some(rest) = s.strip_prefix(label) { + return format!("\x1b[{code}m{label}\x1b[0m{rest}"); + } } + let s = s + .replace("expert hit rate", "\x1b[1;36mexpert hit rate\x1b[0m") + .replace("draft acceptance", "\x1b[1;33mdraft acceptance\x1b[0m"); format!("\x1b[2m{s}\x1b[0m") } /// A part of a dim status line that the user acts on (an address), in bold. pub fn hl(s: &str) -> String { - if err() { format!("\x1b[0;1m{s}\x1b[0;2m") } else { s.to_string() } + if err() { + format!("\x1b[0;1m{s}\x1b[0;2m") + } else { + s.to_string() + } +} + +/// Print an ordinary timestamped status line while keeping an active inline bar intact. +pub fn say(s: &str) { + let line = status(s); + let multi = run() + .0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|r| r.rows.as_ref().map(|rows| rows.multi.clone())); + if let Some(multi) = multi { + multi.suspend(|| eprintln!("{line}")); + } else { + eprintln!("{line}"); + } } /// The input prompt of the terminal chats. -pub fn prompt() -> String { paint(out(), "1;36", "> ") } +pub fn prompt() -> String { + paint(out(), "1;36", "> ") +} /// `eprintln!` for a status line, styled by [`term::status`](crate::term::status). #[macro_export] macro_rules! say { - ($($t:tt)*) => { eprintln!("{}", $crate::term::status(&format!($($t)*))) }; + ($($t:tt)*) => { $crate::term::say(&format!($($t)*)) }; +} + +/// `STRATA_VERBOSE` is set: the run also prints the lines for developers and bug reports ([`detail!`](crate::detail)). +pub fn verbose() -> bool { + std::env::var_os("STRATA_VERBOSE").is_some() +} + +/// A [`say!`](crate::say) line that only a developer reads: printed with `STRATA_VERBOSE=1`. +#[macro_export] +macro_rules! detail { + ($($t:tt)*) => { if $crate::term::verbose() { $crate::say!($($t)*) } }; } #[cfg(test)] @@ -78,6 +1556,208 @@ mod tests { assert_eq!(status_on(true, "warning: x"), "\x1b[1;33mwarning\x1b[0m: x"); assert_eq!(status_on(true, "error: x"), "\x1b[1;31merror\x1b[0m: x"); assert_eq!(status_on(true, "loaded m"), "\x1b[2mloaded m\x1b[0m"); + assert!(!status_on(true, "attn_decode_gqa*").contains("\x1b[1;33mdecode\x1b[0m")); + assert!(!status_on(true, "attn_prefill_*").contains("\x1b[1;32mprefill\x1b[0m")); assert_eq!(paint(false, "1", "a"), "a"); } + + #[test] + fn paired_metrics_use_available_terminal_width_without_changing_graph_caps() { + assert_eq!(format_compact_count(512), "512"); + assert_eq!(format_compact_count(12_345), "12.3k"); + assert_eq!(format_compact_rate(32.6), "32.6"); + assert_eq!(format_compact_rate(1_284.0), "1,284"); + + assert_eq!(paired_column_width(2), 0); + assert_eq!(paired_column_width(120), 58); + assert_eq!(graph_column_width(2), 0); + assert_eq!(graph_column_width(3), 0); + assert_eq!(graph_column_width(80), 38); + assert_eq!(graph_column_width(120), 50); + assert_eq!(graph_column_width(300), 50); + assert_eq!(MAX_GRAPH_SAMPLES, 100); + + let width = 120; + let left = "AVG 90.2 tok/s · LAST 57 new"; + let right = "AVG 25.8 tok/s · LAST 511 · 3.0s"; + let paired = paired_text(left, right, width); + assert_eq!(paired.chars().count(), paired_column_width(width) * 2 + 3); + let divider = paired.find('│').unwrap(); + assert!(paired[..divider].trim_end().ends_with(left)); + assert!( + paired[divider + '│'.len_utf8()..] + .trim_start() + .starts_with(right) + ); + assert!(!paired.contains('…')); + assert!(!paired.contains('\n')); + + // Narrow terminals still trim safely rather than wrapping the row. + let narrow = paired_text(left, right, 24); + assert_eq!(narrow.chars().count(), paired_column_width(24) * 2 + 3); + assert!(narrow.contains('…')); + } + + #[test] + fn prefill_progress_helpers_are_present_and_handle_large_counts() { + assert_eq!(format_progress_count(0), "0"); + assert_eq!(format_progress_count(9_999), "9,999"); + assert_eq!(format_progress_count(10_000), "10k"); + assert_eq!(format_progress_count(15_999), "15k"); + + // Constructing these styles validates their indicatif templates. + let _ = prefill_bar_style(); + let _ = prefill_progress_style(1); + let _ = prefill_progress_style(8); + assert!(terminal_width() >= 1); + } + + #[test] + fn clock_and_speed_lines() { + let c = clock(); + assert!( + c.len() == 10 && c.starts_with('[') && c.ends_with(']') && c.as_bytes()[3] == b':', + "{c}" + ); + assert_eq!(speed_line(0, 0, 0, 0, 0.0, 2.0, true), None); + assert_eq!( + speed_line(1000, 0, 500, 0, 4.0, 2.0, true).as_deref(), + Some("prefill: 250.0 tok/s, 1000 tok") + ); + // A prompt chunk still running: no new prompt tokens, no line. + assert_eq!(speed_line(1000, 0, 0, 0, 4.0, 2.0, true), None); + assert_eq!( + speed_line(1000, 40, 0, 30, 4.0, 2.0, true).as_deref(), + Some("decode: 15.0 tok/s, 40 tok") + ); + assert_eq!(speed_line(1000, 40, 0, 30, 4.0, 2.0, false), None); + assert_eq!(server_average_status(0, "PREFILL", 0, 0.0), ""); + assert!(server_average_status(1, "PREFILL", 24, 2.0).contains("AVG PREFILL · 12.0 tok/s")); + assert!(server_last_status("DECODE", 8, 2.0).contains("LAST 8 tokens · 4.0 tok/s · 2.00s")); + } + + #[test] + fn phase_switching_only_shows_active_work_and_eta_is_prefill_only() { + assert_eq!(visible_phases(0, 10, false, true, 4096, 10), (true, true)); + assert_eq!(visible_phases(10, 0, true, true, 100, 0), (true, false)); + assert_eq!(visible_phases(10, 4, true, true, 100, 4), (true, true)); + assert_eq!(visible_phases(0, 0, false, true, 4096, 128), (true, true)); + assert_eq!(visible_phases(0, 0, false, true, 0, 0), (false, false)); + assert_eq!(format_count(4096), "4,096"); + assert_eq!(format_compact_count(15_000), "15.0k"); + assert_eq!(format_compact_rate(500.0), "500"); + assert_eq!(format_compact_rate(5_000.0), "5,000"); + assert_eq!(format_compact_rate(32.6), "32.6"); + assert_eq!(sample_rate(500, 1.0), 500.0); + assert_eq!(sample_rate(2_500, 0.5), 5_000.0); + assert_eq!(sample_rate(0, 1.0), 0.0); + + assert_eq!(graph_height(1.0, 16.0), 1); + assert_eq!(graph_height(4.0, 16.0), 4); + assert_eq!(graph_height(8.0, 16.0), 8); + assert_eq!(graph_height(16.0, 16.0), 16); + assert_eq!(graph_height(f64::NAN, 16.0), 0); + assert_eq!(graph_height(f64::INFINITY, 16.0), 0); + + // One cell has two temporal samples, left-to-right. Four terminal + // rows extend each bar vertically to 16 Braille dot levels. + let graph = braille_graph(&[16.0, 1.0], 1); + assert_eq!(graph.len(), GRAPH_ROWS); + assert!(graph.iter().all(|row| row.chars().count() == 1)); + let codes: Vec = graph + .iter() + .map(|row| row.chars().next().unwrap() as u32 - 0x2800) + .collect(); + assert_eq!(codes, vec![0x47, 0x47, 0x47, 0xC7]); + + // A newer/right-hand sample alone fills only the right Braille column. + let right_only = braille_graph(&[0.0, 16.0], 1); + let right_codes: Vec = right_only + .iter() + .map(|row| row.chars().next().unwrap() as u32 - 0x2800) + .collect(); + assert_eq!(right_codes, vec![0xB8; GRAPH_ROWS]); + + // Each pair occupies one glyph; samples beyond the visible window are + // cropped from the left, preserving the most recent rates. + let graph = braille_graph(&[1.0, 2.0, 3.0], 2); + assert_eq!(graph.len(), GRAPH_ROWS); + assert!(graph.iter().all(|row| row.chars().count() == 2)); + let narrow = graph_column_width(2); + assert_eq!(narrow, 0); + assert_eq!(graph_column_width(3), 0); + assert_eq!(graph_column_width(80), 38); + assert_eq!(graph_column_width(120), 50); + assert_eq!(graph_column_width(300), 50); + + let mut history = std::collections::VecDeque::new(); + for n in 1..=MAX_GRAPH_SAMPLES { + push_graph_sample(&mut history, n as f64); + } + assert_eq!(history.len(), MAX_GRAPH_SAMPLES); + assert_eq!(history.front(), Some(&1.0)); + assert_eq!(history.back(), Some(&(MAX_GRAPH_SAMPLES as f64))); + push_graph_sample(&mut history, (MAX_GRAPH_SAMPLES + 1) as f64); + assert_eq!(history.len(), MAX_GRAPH_SAMPLES); + assert_eq!(history.front(), Some(&2.0)); + assert_eq!(history.back(), Some(&((MAX_GRAPH_SAMPLES + 1) as f64))); + + let p = format!( + "PREFILL {}/{} uncached · {} cached · {} tok/s · ETA {}", + format_count(4096), + format_count(8192), + format_count(512), + format_compact_rate(1284.0), + format_duration(Duration::from_millis(3190)) + ); + let d = format!( + "DECODE {} generated · {} tok/s", + format_count(128), + format_compact_rate(32.6) + ); + assert!( + p.contains("4,096/8,192 uncached") + && p.contains("512 cached") + && p.contains("ETA 3.19s") + ); + assert!(d.contains("128 generated") && d.contains("32.6 tok/s") && !d.contains("ETA")); + assert_eq!(format_eta(Duration::from_millis(3190)), "3.2s"); + assert_eq!(format_progress_count(15_000), "15k"); + assert!(ProgressStyle::with_template("{bar:8.green/green} {msg}").is_ok()); + assert!(draft_status(Some((100, 75))).contains("75.0% · 75/100")); + assert!(expert_status(Some((80, 20))).contains("80.0% · 80 hits / 20 misses")); + assert_eq!(draft_status(Some((0, 0))), "DRAFT acceptance —"); + assert_eq!(expert_status(None), "EXPERT hit rate —"); + assert_eq!(quality_status(&Quality::default()), ""); + let quality = styled_quality_status(&Quality { + drafts: Some((100, 75)), + experts: Some((80, 20)), + }); + assert!(quality.contains("DRAFT acceptance") && quality.contains("75.0%")); + assert!(quality.contains("EXPERT hit rate") && quality.contains("80.0%")); + assert_eq!( + calibration_progress(1, 4, Duration::from_secs(8)), + "25% · ETA 24s · 3 left" + ); + assert_eq!( + calibration_result(Some(1284.0), Some(32.6), Some((100, 75))), + "PREFILL 1284 tok/s · DECODE 32.6 tok/s · DRAFT 75.0%" + ); + assert_eq!(weighted_rate(120, 2.0), Some(60.0)); + assert_eq!(weighted_rate(0, 2.0), Some(0.0)); + assert_eq!(weighted_rate(20, 0.0), None); + assert!(average_status("PREFILL", 120, 2.0).contains("60.0 tok/s")); + assert_eq!(average_status("DECODE", 0, 0.0), ""); + } + + #[test] + fn measured_rate_uses_the_actual_elapsed_window() { + assert_eq!(sample_rate(500, 1.0), 500.0); + assert_eq!(sample_rate(250, 0.5), 500.0); + assert_eq!(sample_rate(2_500, 0.5), 5_000.0); + assert_eq!(sample_rate(0, 0.5), 0.0); + assert_eq!(sample_rate(100, 0.0), 0.0); + assert_eq!(format_compact_rate(500.0), "500"); + assert_eq!(format_compact_rate(5_000.0), "5,000"); + } } diff --git a/src/testutil.rs b/src/testutil.rs new file mode 100644 index 00000000..50624f59 --- /dev/null +++ b/src/testutil.rs @@ -0,0 +1,63 @@ +//! Fixtures shared by the unit tests: a tiny GGUF that both the CPU reference and a GPU forward can run, so tests +//! that need a whole model build one in a temp file instead of needing `STRATA_MODEL`. + +use std::path::Path; + +/// Write a tiny dense qwen3 (1 block, 64 wide, 1 head, vocab 8) to `path`: the smallest model that loads through +/// `Model::load` and runs on a GPU backend. `seed_off` varies the weights, so two such files differ. +pub(crate) fn make_qwen3(path: &Path, seed_off: usize) { + let mut kvs = Vec::new(); + let w_s = |b: &mut Vec, s: &str| { b.extend((s.len() as u64).to_le_bytes()); b.extend(s.as_bytes()); }; + let w_kv = |b: &mut Vec, k: &str, t: u32, p: &[u8]| { w_s(b, k); b.extend(t.to_le_bytes()); b.extend(p); }; + let s = |b: &mut Vec, k: &str, v: &str| { let mut p = Vec::new(); w_s(&mut p, v); w_kv(b, k, 8, &p); }; + s(&mut kvs, "general.architecture", "qwen3"); + w_kv(&mut kvs, "qwen3.block_count", 4, &1u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.embedding_length", 4, &64u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.feed_forward_length", 4, &64u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.attention.head_count", 4, &1u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.attention.head_count_kv", 4, &1u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.attention.key_length", 4, &64u32.to_le_bytes()); + w_kv(&mut kvs, "qwen3.attention.layer_norm_rms_epsilon", 6, &1e-6f32.to_le_bytes()); + + let mut hdr = Vec::new(); + let mut body = Vec::new(); + let mut seed = 1 + seed_off; + let mut add_t = |name: &str, dims: &[u64], scale: f32| { + w_s(&mut hdr, name); + hdr.extend((dims.len() as u32).to_le_bytes()); + for &d in dims { hdr.extend(d.to_le_bytes()); } + hdr.extend(0u32.to_le_bytes()); + hdr.extend((body.len() as u64).to_le_bytes()); + let n: usize = dims.iter().product::() as usize; + for i in 0..n { + let v = if scale == 0.0 { 1.0f32 } else { (((seed * 29 + i * 13 + 3) % 89) as f32 - 44.0) * scale }; + body.extend_from_slice(&v.to_le_bytes()); + } + seed += 1; + while body.len() % 32 != 0 { body.push(0); } + }; + add_t("token_embd.weight", &[64, 8], 0.02); + add_t("output_norm.weight", &[64], 0.0); + add_t("output.weight", &[64, 8], 0.02); + add_t("blk.0.attn_norm.weight", &[64], 0.0); + add_t("blk.0.ffn_norm.weight", &[64], 0.0); + add_t("blk.0.attn_q_norm.weight", &[64], 0.0); + add_t("blk.0.attn_k_norm.weight", &[64], 0.0); + add_t("blk.0.attn_q.weight", &[64, 64], 0.01); + add_t("blk.0.attn_k.weight", &[64, 64], 0.01); + add_t("blk.0.attn_v.weight", &[64, 64], 0.01); + add_t("blk.0.attn_output.weight", &[64, 64], 0.01); + add_t("blk.0.ffn_gate.weight", &[64, 64], 0.01); + add_t("blk.0.ffn_up.weight", &[64, 64], 0.01); + add_t("blk.0.ffn_down.weight", &[64, 64], 0.01); + let mut gg = Vec::new(); + gg.extend(b"GGUF"); + gg.extend(3u32.to_le_bytes()); + gg.extend(14u64.to_le_bytes()); + gg.extend(8u64.to_le_bytes()); + gg.extend(kvs); + gg.extend(hdr); + while gg.len() % 32 != 0 { gg.push(0); } + gg.extend(body); + std::fs::write(path, &gg).unwrap(); +} diff --git a/src/tokenizer.rs b/src/tokenizer.rs index b0b3b4cf..e320af89 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -36,9 +36,35 @@ const FLINT_RE: [&str; 3] = [ r"[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?| ?[\p{P}\p{S}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+", ]; +/// llama.cpp `LLAMA_VOCAB_PRE_TYPE_RAON` (KRAFTON Raon-1 mini): CJK runs, space-joined words, 3-digit groups, NFC normalized. +const RAON_RE: &str = " ?[\u{4e00}-\u{9fa5}\u{3040}-\u{309f}\u{30a0}-\u{30ff}]+| ?(?:(?:(?![\u{4e00}-\u{9fa5}\u{3040}-\u{309f}\u{30a0}-\u{30ff}])\\p{L})\\p{M}*)+(?: (?:(?:(?![\u{4e00}-\u{9fa5}\u{3040}-\u{309f}\u{30a0}-\u{30ff}])\\p{L})\\p{M}*)+)*|\\p{N}{1,3}(?=(?:\\p{N}{3})*(?!\\p{N}))| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"; + pub struct Tokenizer { inner: tokenizers::Tokenizer, eos: Vec, + /// The BOS id when the GGUF asks for one at the start (`tokenizer.ggml.add_bos_token`). + bos: Option, + /// Control and user-defined tokens (types 3 and 4). + special: Vec, + /// Gemma 4 vocabulary: U+2581 for a space, `<0xXX>` for a byte. + spm: bool, + bytes: std::sync::OnceLock>>, + gbytes: std::sync::OnceLock>>>, +} + +/// The BOS id when the GGUF asks for one at the start of a prompt. +fn add_bos(g: &Gguf) -> Option { + let on = g.meta.get("tokenizer.ggml.add_bos_token").and_then(|v| v.as_u64()) == Some(1); + on.then(|| g.meta.get("tokenizer.ggml.bos_token_id").and_then(|v| v.as_u64()).map(|v| v as u32)).flatten() +} + +/// GPT-2 byte-level BPE writes byte `b` as one printable char: itself for the printable ones, 256 + n for the n-th +/// other byte. This is its inverse. +fn gpt2_byte(c: char) -> Option { + let printable = |b: u32| (33..=126).contains(&b) || (161..=172).contains(&b) || (174..=255).contains(&b); + let c = c as u32; + if printable(c) { return Some(c as u8); } + (0..256u32).filter(|&b| !printable(b)).nth(c.checked_sub(256)? as usize).map(|b| b as u8) } impl Tokenizer { @@ -48,10 +74,11 @@ impl Tokenizer { if model != "gpt2" { bail!("unsupported tokenizer model '{model}'"); } let pre = g.get("tokenizer.ggml.pre")?.as_str().unwrap_or(""); let res: &[&str] = match pre { - "qwen35" => &[QWEN35_RE], "qwen2" => &[QWEN2_RE], "joyai-llm" | "hy_v4" => &JOYAI_RE, + "qwen35" | "qwen4" => &[QWEN35_RE], "qwen2" => &[QWEN2_RE], "joyai-llm" | "hy_v4" => &JOYAI_RE, "flint" => &FLINT_RE, "glm4" | "glm5" | "chatglm-bpe" => &[GLM4_RE], - "inkling2" => &[GPT4O_RE], + "inkling2" | "gigachat4" => &[GPT4O_RE], + "raon" => &[RAON_RE], _ => bail!("unsupported pre-tokenizer '{pre}'"), }; let strs = |k: &str| -> anyhow::Result> { @@ -64,9 +91,13 @@ impl Tokenizer { .map(|m| m.split_once(' ').map(|(a, b)| (a.to_string(), b.to_string())).context("bad merge")) .collect::>>()?; let vocab: HashMap = tokens.iter().enumerate().map(|(i, t)| (t.clone(), i as u32)).collect(); - let bpe = BPE::builder().vocab_and_merges(vocab, merges).build().map_err(|e| anyhow!("{e}"))?; + // llama.cpp `qwen4`: the QWEN35 split, and a piece already in the vocabulary is one token (`ignore_merges`). + let bpe = BPE::builder().vocab_and_merges(vocab, merges).ignore_merges(pre == "qwen4").build().map_err(|e| anyhow!("{e}"))?; let mut inner = tokenizers::Tokenizer::new(bpe); + if pre == "raon" { + inner.with_normalizer(Some(tokenizers::normalizers::unicode::NFC)); + } let mut pre_tok = Vec::new(); for re in res { let split = Split::new(SplitPattern::Regex((*re).into()), SplitDelimiterBehavior::Isolated, false) @@ -83,6 +114,7 @@ impl Tokenizer { .map(|(i, _)| AddedToken::from(tokens[i].clone(), true)) .collect(); inner.add_special_tokens(&special); + let special = types.iter().map(|t| matches!(t.as_u64(), Some(3 | 4))).collect(); let mut eos: Vec = g.meta.get("tokenizer.ggml.eos_token_id").and_then(|v| v.as_u64()).map(|v| v as u32).into_iter().collect(); if let Some(a) = g.meta.get("tokenizer.ggml.eog_token_ids").and_then(|v| v.as_arr()) { @@ -92,13 +124,15 @@ impl Tokenizer { if let Some(id) = inner.token_to_id(t) && !eos.contains(&id) { eos.push(id); } } if pre == "inkling2" && let Some(id) = inner.token_to_id("<|content_model_end_sampling|>") && !eos.contains(&id) { eos.push(id); } + // A GigaChat 4 reply ends with the turn separator. + if pre == "gigachat4" && let Some(id) = inner.token_to_id("<|message_sep|>") && !eos.contains(&id) { eos.push(id); } if pre == "flint" { // llama.cpp treats these turn markers as end of generation for Flint. for t in ["<|user|>", "<|observation|>"] { if let Some(id) = inner.token_to_id(t) && !eos.contains(&id) { eos.push(id); } } } - Ok(Tokenizer { inner, eos }) + Ok(Tokenizer { inner, eos, bos: add_bos(g), special, spm: false, bytes: Default::default(), gbytes: Default::default() }) } /// Gemma 4: SPM-style BPE. Spaces become U+2581, merges run over each newline-free run of raw UTF-8, unknown bytes fall back to <0xXX>. @@ -127,11 +161,12 @@ impl Tokenizer { .map(|(i, _)| AddedToken::from(tokens[i].clone(), true)) .collect(); inner.add_special_tokens(&special); + let special = types.iter().map(|t| matches!(t.as_u64(), Some(3 | 4))).collect(); let mut eos: Vec = g.meta.get("tokenizer.ggml.eos_token_id").and_then(|v| v.as_u64()).map(|v| v as u32).into_iter().collect(); for t in ["", ""] { if let Some(id) = inner.token_to_id(t) && !eos.contains(&id) { eos.push(id); } } - Ok(Tokenizer { inner, eos }) + Ok(Tokenizer { inner, eos, bos: add_bos(g), special, spm: true, bytes: Default::default(), gbytes: Default::default() }) } pub fn token_id(&self, t: &str) -> Option { self.inner.token_to_id(t) } @@ -140,6 +175,44 @@ impl Tokenizer { Ok(self.inner.encode(text, false).map_err(|e| anyhow!("{e}"))?.get_ids().to_vec()) } + /// `encode` with the BOS token in front when `add_special` and the model asks for one (llama.cpp `/tokenize`). + pub fn encode_special(&self, text: &str, add_special: bool) -> anyhow::Result> { + let mut ids = self.encode(text)?; + if add_special && let Some(b) = self.bos { ids.insert(0, b); } + Ok(ids) + } + + /// Whether `id` is a control or user-defined token (`<|im_end|>`, ``). + pub fn is_special(&self, id: u32) -> bool { self.special.get(id as usize).copied().unwrap_or(false) } + + /// The bytes token `id` stands for: its text for a special token, nothing for an id outside the vocabulary. + /// A token may hold part of a UTF-8 character. + pub fn token_bytes(&self, id: u32) -> &[u8] { + let all = self.bytes.get_or_init(|| (0..self.vocab_size() as u32).map(|i| self.bytes_of(i)).collect()); + all.get(id as usize).map_or(&[], |b| b.as_slice()) + } + + /// The bytes of each token for a grammar: none for a special token, which a grammar never takes. + pub fn grammar_bytes(&self) -> std::sync::Arc>> { + self.gbytes.get_or_init(|| std::sync::Arc::new((0..self.vocab_size() as u32) + .map(|i| if self.is_special(i) { vec![] } else { self.token_bytes(i).to_vec() }).collect())).clone() + } + + fn bytes_of(&self, id: u32) -> Vec { + let Some(t) = self.inner.id_to_token(id) else { return vec![] }; + if self.is_special(id) { return t.into_bytes(); } + if self.spm { + if let Some(h) = t.strip_prefix("<0x").and_then(|h| h.strip_suffix('>')) && let Ok(b) = u8::from_str_radix(h, 16) { return vec![b]; } + return t.replace('\u{2581}', " ").into_bytes(); + } + // A char outside the byte map (an added non-special token) stands for itself. + let mut out = vec![]; + for c in t.chars() { + match gpt2_byte(c) { Some(b) => out.push(b), None => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()) } + } + out + } + pub fn decode(&self, ids: &[u32]) -> anyhow::Result { self.inner.decode(ids, false).map_err(|e| anyhow!("{e}")) } @@ -148,3 +221,16 @@ impl Tokenizer { pub fn vocab_size(&self) -> usize { self.inner.get_vocab_size(true) } } + +#[cfg(test)] +mod tests { + #[test] + fn gpt2_byte_map_is_the_inverse() { + assert_eq!(super::gpt2_byte('a'), Some(b'a')); + assert_eq!(super::gpt2_byte('\u{120}'), Some(b' ')); // Ġ + assert_eq!(super::gpt2_byte('\u{10a}'), Some(b'\n')); // Ċ + assert_eq!(super::gpt2_byte('\u{100}'), Some(0)); + assert_eq!(super::gpt2_byte('\u{143}'), Some(173)); // the last of the 68 remapped bytes + assert_eq!(super::gpt2_byte('\u{144}'), None); + } +} diff --git a/src/update.rs b/src/update.rs new file mode 100644 index 00000000..331bb8ab --- /dev/null +++ b/src/update.rs @@ -0,0 +1,145 @@ +//! `rustingstrata update`: replaces the running binary with the newest GitHub release, and the one-line notice +//! `serve` prints at start when a newer release is out. `STRATA_NO_UPDATE_CHECK=1` turns the notice off. + +use anyhow::{Context, bail, ensure}; +use std::io::{Read, Write}; +use std::time::Duration; + +const LATEST: &str = "https://api.github.com/repos/RustingStudio/RustingStrata/releases/latest"; + +/// The release asset for this platform, as the release workflow names it. +const ASSET: Option<&str> = if cfg!(all(target_os = "linux", target_arch = "x86_64")) { + Some("rustingstrata-linux-x86_64") +} else if cfg!(all(target_os = "windows", target_arch = "x86_64")) { + Some("rustingstrata-windows-x86_64.exe") +} else { + None +}; + +fn agent(whole: Duration) -> ureq::Agent { + let s = Some(Duration::from_secs(60)); + ureq::Agent::config_builder().timeout_connect(Some(Duration::from_secs(15))).timeout_recv_response(s) + .timeout_per_read(s).timeout_global(Some(whole)).user_agent("rustingstrata-update").build().into() +} + +/// "v1.2.10" or "1.2.10" as numbers, so 1.2.10 is newer than 1.2.9. +fn version(s: &str) -> Option> { s.trim_start_matches('v').split('.').map(|p| p.parse().ok()).collect() } + +fn newer(tag: &str, have: &str) -> bool { matches!((version(tag), version(have)), (Some(a), Some(b)) if a > b) } + +/// The latest release's tag, with the download URL and size of this platform's binary if it has one. +fn latest(whole: Duration) -> anyhow::Result<(String, Option<(String, u64)>)> { + let mut r = agent(whole).get(LATEST).header("Accept", "application/vnd.github+json").call() + .context("ask GitHub for the latest release")?; + let v: serde_json::Value = serde_json::from_str(&r.body_mut().read_to_string()?)?; + let tag = v["tag_name"].as_str().context("the release has no tag")?.to_string(); + let asset = v["assets"].as_array().into_iter().flatten().find(|a| Some(a["name"].as_str().unwrap_or("")) == ASSET) + .and_then(|a| Some((a["browser_download_url"].as_str()?.to_string(), a["size"].as_u64()?))); + Ok((tag, asset)) +} + +/// A binary a package manager put in place (the AUR's rustingstrata-bin in /usr/bin, winget's portable folder) is +/// updated by that package manager, so `update` leaves it alone. +fn managed(exe: &std::path::Path) -> bool { + let p = exe.to_string_lossy().replace('\\', "/").to_ascii_lowercase(); + p.starts_with("/usr/") || p.starts_with("/opt/") || p.contains("/winget/packages/") || p.contains("/scoop/apps/") +} + +fn exe() -> anyhow::Result { + let e = std::env::current_exe().context("find the running binary")?; + Ok(e.canonicalize().unwrap_or(e)) +} + +/// The line that says a newer release is out, and how to get it. +fn out_line(tag: &str) -> String { + let how = if exe().is_ok_and(|e| managed(&e)) { "update it with your package manager" } else { "run `rustingstrata update` to install it" }; + format!("RustingStrata {tag} is out (this is {}): {how}", env!("CARGO_PKG_VERSION")) +} + +/// Prints one line if a newer release is out. It runs on its own thread and gives up after 5 s, so a machine +/// without internet starts as before. +pub fn notice() { + if std::env::var("STRATA_NO_UPDATE_CHECK").is_ok_and(|v| v == "1") || ASSET.is_none() { return; } + std::thread::spawn(|| { + if let Ok((tag, Some(_))) = latest(Duration::from_secs(5)) && newer(&tag, env!("CARGO_PKG_VERSION")) { + crate::say!("{}", out_line(&tag)); + } + }); +} + +/// Downloads the newest release next to the running binary and swaps it in. The old binary is kept as `.old` +/// until the next update: Windows cannot delete a running exe, but it can rename it. +pub fn run(check: bool) -> anyhow::Result<()> { + let have = env!("CARGO_PKG_VERSION"); + let (tag, asset) = latest(Duration::from_secs(60))?; + if !newer(&tag, have) { + crate::say!("RustingStrata {have} is the newest release"); + return Ok(()); + } + if check { + crate::say!("{}", out_line(&tag)); + return Ok(()); + } + let exe = exe()?; + if managed(&exe) { + bail!("{} was installed by a package manager (on Arch: the AUR package rustingstrata-bin); update it with that, \ + so the package manager knows the new version", exe.display()); + } + let Some((url, size)) = asset else { + bail!("release {tag} has no binary for this platform; build it from source or see \ + https://github.com/RustingStudio/RustingStrata/releases"); + }; + let (new, old) = (exe.with_extension("new"), exe.with_extension("old")); + let _ = std::fs::remove_file(&old); + crate::say!("downloading RustingStrata {tag} ({:.1} MB)", size as f64 / 1e6); + let r = agent(Duration::from_secs(1800)).get(&url).call().with_context(|| format!("download {url}"))?; + let mut out = std::fs::File::create(&new).with_context(|| format!("write {} (is the folder writable?)", new.display()))?; + let (mut rd, mut buf, mut got) = (r.into_body().into_reader(), vec![0; 1 << 20], 0u64); + loop { + let n = rd.read(&mut buf).context("download")?; + if n == 0 { break; } + out.write_all(&buf[..n])?; + got += n as u64; + } + drop(out); + if got != size { + let _ = std::fs::remove_file(&new); + bail!("received {got} of {size} bytes; nothing was changed"); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&new, std::fs::Permissions::from_mode(0o755))?; + } + std::fs::rename(&exe, &old).with_context(|| format!("move {} aside", exe.display()))?; + if let Err(e) = std::fs::rename(&new, &exe) { + let _ = std::fs::rename(&old, &exe); + return Err(e).with_context(|| format!("put the new binary at {}", exe.display())); + } + ensure!(exe.exists(), "{} is missing after the update", exe.display()); + crate::say!("updated {have} -> {tag}: {}", exe.display()); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn versions_compare_as_numbers() { + assert!(newer("v1.3.10", "1.3.9")); + assert!(newer("v1.4.0", "1.3.4")); + assert!(!newer("v1.3.4", "1.3.4")); + assert!(!newer("v1.3.3", "1.3.4")); + assert!(!newer("nightly", "1.3.4")); + } + + #[test] + fn package_manager_installs_are_left_alone() { + use std::path::Path; + assert!(managed(Path::new("/usr/bin/rustingstrata"))); + assert!(managed(Path::new(r"C:\Users\a\AppData\Local\Microsoft\WinGet\Packages\x\rustingstrata.exe"))); + assert!(!managed(Path::new("/home/a/.local/bin/rustingstrata"))); + assert!(!managed(Path::new(r"C:\Users\a\AppData\Local\Programs\RustingStrata\rustingstrata.exe"))); + } +} diff --git a/src/vision/image.rs b/src/vision/image.rs index d956ef36..68e0d047 100644 --- a/src/vision/image.rs +++ b/src/vision/image.rs @@ -5,6 +5,8 @@ use base64::Engine as _; use image::{DynamicImage, RgbImage}; use std::path::Path; use std::time::Duration; +use ureq::unversioned::resolver::{DefaultResolver, ResolvedSocketAddrs, Resolver}; +use ureq::unversioned::transport::{DefaultConnector, NextTimeout}; /// A decoded RGB image with rows top-to-bottom and interleaved channels (`R G B R G B ...`). pub type Rgb = RgbImage; @@ -70,16 +72,43 @@ fn decode_data_url(rest: &str) -> anyhow::Result> { fn fetch_url(url: &str) -> anyhow::Result> { check_public_url(url)?; - let agent: ureq::Agent = ureq::Agent::config_builder() - .timeout_connect(Some(Duration::from_secs(10))) - .timeout_global(Some(Duration::from_secs(30))) - .build() - .into(); - let mut r = agent.get(url).call().with_context(|| format!("fetch {url}"))?; + // Without a proxy, the agent's lookups go through the same rule, so a changed DNS answer or a redirect cannot reach a private address. + let mut r = agent().get(url).call().with_context(|| format!("fetch {url}"))?; + // A 3xx comes back only through a proxy (see `agent_with`): say so, rather than fail to decode its body. + anyhow::ensure!(!r.status().is_redirection(), "image URL {url} redirects ({}); redirects are not followed through a proxy, give the address it redirects to", r.status()); let body = r.body_mut().read_to_vec().context("read image body")?; Ok(body) } +/// A new agent per image download, as before: downloads are rare next to inference, and the proxy variables are read +/// each time (a cached agent would keep the first ones for the whole process). +fn agent() -> ureq::Agent { agent_with(ureq::Proxy::try_from_env()) } + +fn agent_with(proxy: Option) -> ureq::Agent { + let config = ureq::Agent::config_builder() + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_global(Some(Duration::from_secs(30))) + // A proxy resolves the hosts it connects to, so the connect-time check cannot see a redirect target through it. + .max_redirects(if proxy.is_some() { 0 } else { 10 }) + .proxy(proxy) + .build(); + ureq::Agent::with_parts(config, DefaultConnector::new(), PublicResolver::default()) +} + +/// ureq's resolver, refusing a host with any address `check_public_url` would refuse; it runs for every connection. +#[derive(Debug, Default)] +struct PublicResolver(DefaultResolver); + +impl Resolver for PublicResolver { + fn resolve(&self, uri: &ureq::http::Uri, config: &ureq::config::Config, timeout: NextTimeout) -> Result { + let addrs = self.0.resolve(uri, config, timeout)?; + // The configured proxy is the operator's choice, so its own address is let through. + let is_proxy = config.proxy().is_some_and(|p| uri.host() == Some(p.host())); + if is_proxy || std::env::var("STRATA_ALLOW_PRIVATE_IMAGE_URLS").is_ok_and(|v| v == "1") || addrs.iter().all(|a| is_public_ip(a.ip().to_canonical())) { return Ok(addrs); } + Err(std::io::Error::other(format!("{} resolves to a private or loopback address", uri.host().unwrap_or_default())).into()) + } +} + /// Reject URLs whose host resolves to a loopback, private, link-local or otherwise non-global address. /// `STRATA_ALLOW_PRIVATE_IMAGE_URLS=1` disables the check for tests and trusted local setups. pub fn check_public_url(url: &str) -> anyhow::Result<()> { @@ -89,7 +118,8 @@ pub fn check_public_url(url: &str) -> anyhow::Result<()> { let addrs: Vec<_> = (host.as_str(), 0).to_socket_addrs().with_context(|| format!("resolve {host}"))?.collect(); anyhow::ensure!(!addrs.is_empty(), "{host} did not resolve"); for a in addrs { - if !is_public_ip(a.ip()) { bail!("image URL {url} resolves to a private or loopback address"); } + // `::ffff:a.b.c.d` connects to the IPv4 host, so it is judged as that host. + if !is_public_ip(a.ip().to_canonical()) { bail!("image URL {url} resolves to a private or loopback address"); } } Ok(()) } @@ -104,8 +134,16 @@ fn url_host(url: &str) -> Option { fn is_public_ip(ip: std::net::IpAddr) -> bool { match ip { - std::net::IpAddr::V4(v4) => !(v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_broadcast() || v4.is_unspecified() || v4.is_multicast()), - std::net::IpAddr::V6(v6) => !(v6.is_loopback() || v6.is_unspecified() || v6.is_multicast() || v6.is_unicast_link_local() || v6.is_unique_local()), + // 100.64.0.0/10 is shared address space (carrier-grade NAT, Tailscale); `Ipv4Addr::is_shared` is unstable. + // 0.0.0.0/8 is "this network" (a connection to it can reach the local host), 192.0.0.0/24 holds IETF protocol + // assignments and 240.0.0.0/4 is reserved. + // 198.18.0.0/15 stays allowed: fake-IP DNS proxies (Clash, Surge, sing-box in TUN mode) answer every name with one. + std::net::IpAddr::V4(v4) => !(v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_broadcast() || v4.is_unspecified() || v4.is_multicast() || matches!(v4.octets(), [0, ..] | [100, 64..=127, ..] | [192, 0, 0, _] | [240..=255, ..])), + std::net::IpAddr::V6(v6) => match v6.octets() { + // NAT64 (64:ff9b::/96) and 6to4 (2002::/16) reach the IPv4 host they carry, so they are judged as that host. + [0, 0x64, 0xff, 0x9b, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] | [0x20, 0x02, a, b, c, d, ..] => is_public_ip([a, b, c, d].into()), + _ => !(v6.is_loopback() || v6.is_unspecified() || v6.is_multicast() || v6.is_unicast_link_local() || v6.is_unique_local()), + }, } } @@ -271,4 +309,51 @@ mod tests { let same = resize_bilinear(&img, 2, 2); assert_eq!(same.as_raw(), img.as_raw()); } + + #[test] + fn guard_refuses_non_public_hosts() { + // IP literals resolve without DNS, so no network is used. + let allowed: Vec<_> = ["http://127.0.0.1/a.png", "http://[::1]/a.png", "http://[::ffff:127.0.0.1]/a.png", "http://[::ffff:169.254.169.254]/latest/", "http://100.100.100.100/a.png", + "http://240.0.0.1/a.png", "http://192.0.0.1/a.png", "http://[64:ff9b::a9fe:a9fe]/", "http://[64:ff9b::7f00:1]/a.png", "http://[2002:7f00:1::]/a.png", "http://0.1.2.3/a.png"] + .into_iter().filter(|u| check_public_url(u).is_ok()).collect(); + assert!(allowed.is_empty(), "allowed {allowed:?}"); + // 198.18.0.1 on purpose: fake-IP DNS proxies answer every name with an address in 198.18.0.0/15. + for u in ["http://8.8.8.8/a.png", "http://[64:ff9b::808:808]/a.png", "http://198.18.0.1/a.png"] { check_public_url(u).unwrap(); } + } + + #[test] + fn agent_checks_the_address_when_it_connects() { + // No `check_public_url` here: the agent's own lookup refuses 127.0.0.1, as it does for every connection and redirect hop. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let e = agent_with(None).get(format!("http://{}/a.png", listener.local_addr().unwrap())).call().expect_err("the agent fetched from 127.0.0.1"); + assert!(e.to_string().contains("private or loopback"), "{e}"); + assert_eq!(listener.accept().expect_err("the agent connected").kind(), std::io::ErrorKind::WouldBlock); + } + + #[test] + fn a_proxy_is_used_and_its_redirect_is_not_followed() { + use std::io::{BufRead, Write}; + let proxy = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let second = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + second.set_nonblocking(true).unwrap(); + let (addr, target) = (proxy.local_addr().unwrap(), second.local_addr().unwrap()); + // A fake CONNECT proxy that answers the tunneled request itself, so nothing leaves the machine. + let proxied = std::thread::spawn(move || { + let (s, _) = proxy.accept().unwrap(); + let (mut lines, mut w) = (std::io::BufReader::new(&s).lines(), &s); + let connect = lines.next().unwrap().unwrap(); + // Read each whole head: closing with unread bytes sends a reset that could hide the reply. + for l in lines.by_ref() { if l.unwrap().is_empty() { break; } } + write!(w, "HTTP/1.1 200 Connection established\r\n\r\n").unwrap(); + for l in lines.by_ref() { if l.unwrap().is_empty() { break; } } + write!(w, "HTTP/1.1 302 Found\r\nLocation: http://{target}/x.png\r\nContent-Length: 0\r\n\r\n").unwrap(); + connect + }); + let r = agent_with(Some(ureq::Proxy::new(&format!("http://{addr}")).unwrap())).get("http://8.8.8.8/a.png").call().unwrap(); + // The proxy's own loopback address was let through, and it was asked for 8.8.8.8, which it never contacts. + assert_eq!(proxied.join().unwrap(), "CONNECT 8.8.8.8:80 HTTP/1.1"); + assert_eq!(r.status(), 302); + assert_eq!(second.accept().expect_err("the redirect was followed").kind(), std::io::ErrorKind::WouldBlock); + } } diff --git a/src/vision/mmproj.rs b/src/vision/mmproj.rs index 3cf67ecc..81fa11f4 100644 --- a/src/vision/mmproj.rs +++ b/src/vision/mmproj.rs @@ -174,12 +174,19 @@ pub struct ClipModel { } impl ClipModel { - pub fn open(path: &Path) -> anyhow::Result { - let g = Gguf::open(path)?; + pub fn open(path: &Path) -> anyhow::Result { Self::of(Gguf::open(path)?, path) } + + /// `open` of an opened file; `find_sibling` gives it `Gguf::head`, which asks what the file is without reading it. + fn of(g: Gguf, path: &Path) -> anyhow::Result { + // A model GGUF with the vision tower embedded (clip.vision.* keys and v.* tensors next to the text + // model's) opens as its own projector; a separate file must say it is one. + if !has_embedded_vision(&g) { + let arch = g.meta.get("general.architecture").and_then(Value::as_str).unwrap_or_default(); + anyhow::ensure!(arch == "clip", "{}: not a CLIP projector (architecture {arch})", path.display()); + anyhow::ensure!(g.meta.get("general.type").and_then(Value::as_str) == Some("mmproj"), + "{}: general.type is not mmproj", path.display()); + } let cfg = ClipConfig::from_gguf(&g)?; - anyhow::ensure!(cfg.arch == "clip", "{}: not a CLIP projector (architecture {})", path.display(), cfg.arch); - anyhow::ensure!(g.meta.get("general.type").and_then(Value::as_str) == Some("mmproj"), - "{}: general.type is not mmproj", path.display()); Ok(ClipModel { g, cfg }) } @@ -217,18 +224,31 @@ pub fn is_mmproj(path: &Path) -> bool { name.starts_with("mmproj") || name.contains("-mmproj") || name.contains("mmproj-") } -/// Find `mmproj*.gguf` next to a text model. +/// Find `mmproj*.gguf` next to a text model: the first one (by name) that opens as a projector this build +/// knows. A file that does not (another model's projector, such as a `pixtral` one) is skipped with a +/// warning, so a text-only run is not stopped by it; `--mmproj` still names a file explicitly. pub fn find_sibling(model: &Path) -> Option { let dir = model.parent()?; - let mut found = None; - for e in std::fs::read_dir(dir).ok()? { - let p = e.ok()?.path(); - if p.extension().is_some_and(|x| x.eq_ignore_ascii_case("gguf")) && is_mmproj(&p) { - found = Some(p); - break; - } - } - found + let mut found: Vec<_> = std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("gguf")) && is_mmproj(p)) + .collect(); + found.sort(); + found.into_iter().find(|p| match Gguf::head(p).and_then(|g| ClipModel::of(g, p)) { + Ok(_) => true, + Err(e) => { crate::say!("note: skipping {}: {e:#}", p.display()); false } + }) +} + +/// A text model GGUF that also carries a vision tower: `clip.vision.*` metadata under a non-clip architecture. +fn has_embedded_vision(g: &Gguf) -> bool { + g.meta.get("general.architecture").and_then(Value::as_str).is_some_and(|a| a != "clip") + && g.meta.contains_key("clip.vision.embedding_length") +} + +/// `model` itself when it embeds a vision tower (see `has_embedded_vision`), so no `--mmproj` is needed. +pub fn embedded(model: &Path) -> Option { + let g = Gguf::head(model).ok()?; + has_embedded_vision(&g).then(|| model.to_path_buf()) } /// Validate that the projector's output width matches the text model's embedding width. diff --git a/src/vision/mod.rs b/src/vision/mod.rs index f7a664e5..55a7ec32 100644 --- a/src/vision/mod.rs +++ b/src/vision/mod.rs @@ -7,6 +7,6 @@ pub mod projector; pub mod prompt; pub use image::{PreprocessedImage, Rgb, decode_bytes, decode_path, load_image, smart_resize}; -pub use mmproj::{ClipConfig, ClipModel, FfnKind, MergeKind, ProjectorKind, find_sibling, is_mmproj, validate_projection}; -pub use projector::{VisionProjector, encode_image}; +pub use mmproj::{ClipConfig, ClipModel, FfnKind, MergeKind, ProjectorKind, embedded, find_sibling, is_mmproj, validate_projection}; +pub use projector::{VisionProjector, encode_image, use_gpu}; pub use prompt::{ImageSpan, Prompt, expand_image, expand_images, feed_prompt, next_text_position}; diff --git a/src/vision/projector.rs b/src/vision/projector.rs index 0ea3b6bc..4ae3e35c 100644 --- a/src/vision/projector.rs +++ b/src/vision/projector.rs @@ -7,10 +7,14 @@ use crate::ops; use crate::vision::image::{PreprocessedImage, Rgb, resize_bilinear, resize_bilinear_antialias_f32, resize_bilinear_f32, smart_resize}; use crate::vision::mmproj::{ClipConfig, ClipModel, FfnKind, ProjectorKind}; +use crate::backend::{Backend, GpuTensor}; +use crate::quant::GgmlType; use crate::weights::Tensor; use anyhow::{Context, bail}; use rayon::prelude::*; use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock}; fn dbg() -> bool { std::env::var_os("STRATA_VISION_DEBUG").is_some() } @@ -121,8 +125,8 @@ fn encode_qwen3vl(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul let patch_area = c.patch_size * c.patch_size * 3; // 1. patch convolution. `v.patch_embd.weight` is [kx, ky, c, out]; flatten it to [out][kx,ky,c]. - let w0 = p.model.tensor_as("v.patch_embd.weight", Some(patch_area))?; - let w1 = p.model.tensor_as("v.patch_embd.weight.1", Some(patch_area))?; + let w0 = rows_f32(&p.model.tensor_as("v.patch_embd.weight", Some(patch_area))?); + let w1 = rows_f32(&p.model.tensor_as("v.patch_embd.weight.1", Some(patch_area))?); let bias = p.model.tensor("v.patch_embd.bias")?; let mut patch_bias = vec![0f32; n_embd]; bias.row(0, &mut patch_bias); @@ -139,12 +143,9 @@ fn encode_qwen3vl(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul } } } - let mut buf = vec![0f32; patch_area]; - for o in 0..n_embd { - w0.row(o, &mut buf); - let mut v = buf.iter().zip(&patch).map(|(a, b)| a * b).sum::(); - w1.row(o, &mut buf); - v += buf.iter().zip(&patch).map(|(a, b)| a * b).sum::(); + for (o, (r0, r1)) in w0.chunks_exact(patch_area).zip(w1.chunks_exact(patch_area)).enumerate() { + let mut v = r0.iter().zip(&patch).map(|(a, b)| a * b).sum::(); + v += r1.iter().zip(&patch).map(|(a, b)| a * b).sum::(); xs[o] = v + patch_bias[o]; } }); @@ -187,7 +188,9 @@ fn encode_qwen3vl(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul // 4. transformer blocks. let base = 10000.0f32; let scale = 1.0 / (c.d_head as f32).sqrt(); - for il in 0..c.n_layer { + static BLOCKS_OFF: AtomicBool = AtomicBool::new(false); + let on = on_gpu(&BLOCKS_OFF, |b| qwen3vl_blocks_gpu(b, p, &mut x, n_patches, mx)).is_some(); + for il in (0..c.n_layer).filter(|_| !on) { let ln1w = p.model.to_f32(&format!("v.blk.{il}.ln1.weight"))?; let ln1b = p.model.to_f32(&format!("v.blk.{il}.ln1.bias"))?; let ln2w = p.model.to_f32(&format!("v.blk.{il}.ln2.weight"))?; @@ -197,7 +200,7 @@ fn encode_qwen3vl(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul let qkv_w = p.model.tensor(&format!("v.blk.{il}.attn_qkv.weight"))?; let qkv_b = p.model.tensor(&format!("v.blk.{il}.attn_qkv.bias"))?; let mut qkv = vec![0f32; n_patches * 3 * n_embd]; - qkv_w.matmul(&h, n_patches, &mut qkv); + matmul(&qkv_w, &h, n_patches, &mut qkv); add_bias_rows(&mut qkv, &qkv_b, 3 * n_embd); let mut q = vec![0f32; n_patches * n_embd]; @@ -230,7 +233,7 @@ fn encode_qwen3vl(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul let wo_w = p.model.tensor(&format!("v.blk.{il}.attn_out.weight"))?; let wo_b = p.model.tensor(&format!("v.blk.{il}.attn_out.bias"))?; let mut attn_out = vec![0f32; n_patches * n_embd]; - wo_w.matmul(&attn, n_patches, &mut attn_out); + matmul(&wo_w, &attn, n_patches, &mut attn_out); add_bias_rows(&mut attn_out, &wo_b, n_embd); for (a, b) in x.iter_mut().zip(&attn_out) { *a += *b; } @@ -238,13 +241,13 @@ fn encode_qwen3vl(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul let up_w = p.model.tensor(&format!("v.blk.{il}.ffn_up.weight"))?; let up_b = p.model.tensor(&format!("v.blk.{il}.ffn_up.bias"))?; let mut up = vec![0f32; n_patches * c.n_ff]; - up_w.matmul(&h, n_patches, &mut up); + matmul(&up_w, &h, n_patches, &mut up); add_bias_rows(&mut up, &up_b, c.n_ff); up.par_iter_mut().for_each(|v| *v = activate(c.ffn, *v)); let down_w = p.model.tensor(&format!("v.blk.{il}.ffn_down.weight"))?; let down_b = p.model.tensor(&format!("v.blk.{il}.ffn_down.bias"))?; let mut down = vec![0f32; n_patches * n_embd]; - down_w.matmul(&up, n_patches, &mut down); + matmul(&down_w, &up, n_patches, &mut down); add_bias_rows(&mut down, &down_b, n_embd); for (a, b) in x.iter_mut().zip(&down) { *a += *b; } } @@ -263,13 +266,13 @@ fn encode_qwen3vl(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul let mm0 = p.model.tensor("mm.0.weight")?; let mm0_b = p.model.tensor("mm.0.bias")?; let mut proj = vec![0f32; n_merged * feat]; - mm0.matmul(&x, n_merged, &mut proj); + matmul(&mm0, &x, n_merged, &mut proj); add_bias_rows(&mut proj, &mm0_b, feat); proj.par_iter_mut().for_each(|v| *v = activate(c.ffn, *v)); let mm2 = p.model.tensor("mm.2.weight")?; let mm2_b = p.model.tensor("mm.2.bias")?; let mut out = vec![0f32; n_merged * c.projection_dim]; - mm2.matmul(&proj, n_merged, &mut out); + matmul(&mm2, &proj, n_merged, &mut out); add_bias_rows(&mut out, &mm2_b, c.projection_dim); rows(out, n_merged, c.projection_dim) @@ -283,7 +286,7 @@ fn encode_gemma4v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul let n_patches = nx * ny; let n_embd = c.n_embd; let patch_area = c.patch_size * c.patch_size * 3; - let w = p.model.tensor_as("v.patch_embd.weight", Some(patch_area))?; + let w = rows_f32(&p.model.tensor_as("v.patch_embd.weight", Some(patch_area))?); let mut x = vec![0f32; n_patches * n_embd]; x.par_chunks_mut(n_embd).enumerate().for_each(|(q, xs)| { let px = q % nx; @@ -297,10 +300,8 @@ fn encode_gemma4v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul } } } - let mut buf = vec![0f32; patch_area]; - for o in 0..n_embd { - w.row(o, &mut buf); - xs[o] = buf.iter().zip(&patch).map(|(a, b)| a * b).sum(); + for (o, r) in w.chunks_exact(patch_area).enumerate() { + xs[o] = r.iter().zip(&patch).map(|(a, b)| a * b).sum(); } }); @@ -326,9 +327,9 @@ fn encode_gemma4v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul let k_w = p.model.tensor(&format!("v.blk.{il}.attn_k.weight"))?; let v_w = p.model.tensor(&format!("v.blk.{il}.attn_v.weight"))?; let (mut q, mut k, mut v) = (vec![0f32; n_patches * n_embd], vec![0f32; n_patches * n_embd], vec![0f32; n_patches * n_embd]); - q_w.matmul(&h, n_patches, &mut q); - k_w.matmul(&h, n_patches, &mut k); - v_w.matmul(&h, n_patches, &mut v); + matmul(&q_w, &h, n_patches, &mut q); + matmul(&k_w, &h, n_patches, &mut k); + matmul(&v_w, &h, n_patches, &mut v); let q_norm = p.model.to_f32(&format!("v.blk.{il}.attn_q_norm.weight"))?; let k_norm = p.model.to_f32(&format!("v.blk.{il}.attn_k_norm.weight"))?; @@ -357,7 +358,7 @@ fn encode_gemma4v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul let attn = attention(&q, &k, &v, n_patches, c.n_head, c.d_head, 1.0); let o_w = p.model.tensor(&format!("v.blk.{il}.attn_out.weight"))?; let mut attn_out = vec![0f32; n_patches * n_embd]; - o_w.matmul(&attn, n_patches, &mut attn_out); + matmul(&o_w, &attn, n_patches, &mut attn_out); let apn = p.model.to_f32(&format!("v.blk.{il}.attn_post_norm.weight"))?; let attn_out = rms_norm_all(&attn_out, n_embd, &apn, c.eps); if dbg() && il == 0 { eprintln!("g4 attn_post sum = {} row0 = {:?}", attn_out.iter().sum::(), &attn_out[..3]); } @@ -369,10 +370,10 @@ fn encode_gemma4v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul let up_w = p.model.tensor(&format!("v.blk.{il}.ffn_up.weight"))?; let down_w = p.model.tensor(&format!("v.blk.{il}.ffn_down.weight"))?; let (mut gate, mut up, mut down) = (vec![0f32; n_patches * c.n_ff], vec![0f32; n_patches * c.n_ff], vec![0f32; n_patches * n_embd]); - gate_w.matmul(&h, n_patches, &mut gate); - up_w.matmul(&h, n_patches, &mut up); + matmul(&gate_w, &h, n_patches, &mut gate); + matmul(&up_w, &h, n_patches, &mut up); for (u, g) in up.iter_mut().zip(&gate) { *u *= activate(c.ffn, *g); } - down_w.matmul(&up, n_patches, &mut down); + matmul(&down_w, &up, n_patches, &mut down); let fpn = p.model.to_f32(&format!("v.blk.{il}.ffn_post_norm.weight"))?; let down = rms_norm_all(&down, n_embd, &fpn, c.eps); for (a, b) in x.iter_mut().zip(&down) { *a += *b; } @@ -410,7 +411,7 @@ fn encode_gemma4v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resul if dbg() { eprintln!("g4 preproj sum = {} row0 = {:?}", y.iter().sum::(), &y[..3]); } let proj = p.model.tensor("mm.input_projection.weight")?; let mut out = vec![0f32; ox * oy * c.projection_dim]; - proj.matmul(&y, ox * oy, &mut out); + matmul(&proj, &y, ox * oy, &mut out); if dbg() { eprintln!("g4 proj sum = {} row0 = {:?}", out.iter().sum::(), &out[..3]); for t in 0..(ox * oy) { @@ -435,7 +436,7 @@ fn encode_gemma4uv(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resu let n2b = p.model.to_f32("v.patch_norm.2.bias")?; let n3w = p.model.to_f32("v.patch_norm.3.weight")?; let n3b = p.model.to_f32("v.patch_norm.3.bias")?; - let w = p.model.tensor_as("v.patch_embd.weight", Some(patch_area))?; + let w = rows_f32(&p.model.tensor_as("v.patch_embd.weight", Some(patch_area))?); let bias = p.model.tensor("v.patch_embd.bias")?; let mut patch_bias = vec![0f32; n_embd]; bias.row(0, &mut patch_bias); @@ -455,11 +456,9 @@ fn encode_gemma4uv(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resu } let mut normed = vec![0f32; patch_area]; ops::layer_norm(&patch, &n1w, &n1b, eps, &mut normed); - let mut buf = vec![0f32; patch_area]; let mut emb = vec![0f32; n_embd]; - for o in 0..n_embd { - w.row(o, &mut buf); - emb[o] = buf.iter().zip(&normed).map(|(a, b)| a * b).sum::() + patch_bias[o]; + for (o, r) in w.chunks_exact(patch_area).enumerate() { + emb[o] = r.iter().zip(&normed).map(|(a, b)| a * b).sum::() + patch_bias[o]; } ops::layer_norm(&emb, &n2w, &n2b, eps, xs); }); @@ -478,7 +477,7 @@ fn encode_gemma4uv(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Resu let x = rms_norm_nw_all(&x, n_embd, c.eps); let proj = p.model.tensor("mm.input_projection.weight")?; let mut out = vec![0f32; n_patches * c.projection_dim]; - proj.matmul(&x, n_patches, &mut out); + matmul(&proj, &x, n_patches, &mut out); rows(out, n_patches, c.projection_dim) } @@ -498,7 +497,7 @@ fn encode_inkling2v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Res let patch_area = c.patch_size * c.patch_size * 3; // 1. Patch convolution (`v.patch_embd.weight`, optional `v.patch_embd.bias`). - let w0 = p.model.tensor_as("v.patch_embd.weight", Some(patch_area))?; + let w0 = rows_f32(&p.model.tensor_as("v.patch_embd.weight", Some(patch_area))?); let patch_bias = if p.model.has("v.patch_embd.bias") { p.model.to_f32("v.patch_embd.bias")? } else { @@ -517,10 +516,8 @@ fn encode_inkling2v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Res } } } - let mut buf = vec![0f32; patch_area]; - for o in 0..n_embd { - w0.row(o, &mut buf); - xs[o] = buf.iter().zip(&patch).map(|(a, b)| a * b).sum::() + patch_bias[o]; + for (o, r) in w0.chunks_exact(patch_area).enumerate() { + xs[o] = r.iter().zip(&patch).map(|(a, b)| a * b).sum::() + patch_bias[o]; } }); @@ -581,7 +578,7 @@ fn encode_inkling2v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Res if p.model.has(&format!("v.blk.{il}.attn_qkv.weight")) { let qkv_w = p.model.tensor(&format!("v.blk.{il}.attn_qkv.weight"))?; let mut qkv = vec![0f32; n_pos * 3 * n_embd]; - qkv_w.matmul(&h, n_pos, &mut qkv); + matmul(&qkv_w, &h, n_pos, &mut qkv); if p.model.has(&format!("v.blk.{il}.attn_qkv.bias")) { let qkv_b = p.model.tensor(&format!("v.blk.{il}.attn_qkv.bias"))?; add_bias_rows(&mut qkv, &qkv_b, 3 * n_embd); @@ -596,9 +593,9 @@ fn encode_inkling2v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Res let q_w = p.model.tensor(&format!("v.blk.{il}.attn_q.weight"))?; let k_w = p.model.tensor(&format!("v.blk.{il}.attn_k.weight"))?; let v_w = p.model.tensor(&format!("v.blk.{il}.attn_v.weight"))?; - q_w.matmul(&h, n_pos, &mut q); - k_w.matmul(&h, n_pos, &mut k); - v_w.matmul(&h, n_pos, &mut v); + matmul(&q_w, &h, n_pos, &mut q); + matmul(&k_w, &h, n_pos, &mut k); + matmul(&v_w, &h, n_pos, &mut v); if p.model.has(&format!("v.blk.{il}.attn_q.bias")) { add_bias_rows(&mut q, &p.model.tensor(&format!("v.blk.{il}.attn_q.bias"))?, n_embd); } @@ -616,7 +613,7 @@ fn encode_inkling2v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Res let attn = attention(&q, &k, &v, n_pos, c.n_head, c.d_head, scale); let wo_w = p.model.tensor(&format!("v.blk.{il}.attn_out.weight"))?; let mut attn_out = vec![0f32; n_pos * n_embd]; - wo_w.matmul(&attn, n_pos, &mut attn_out); + matmul(&wo_w, &attn, n_pos, &mut attn_out); if p.model.has(&format!("v.blk.{il}.attn_out.bias")) { add_bias_rows(&mut attn_out, &p.model.tensor(&format!("v.blk.{il}.attn_out.bias"))?, n_embd); } @@ -633,14 +630,14 @@ fn encode_inkling2v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Res let h = layer_norm_all(&x, n_embd, &ln2w, &ln2b, c.eps); let up_w = p.model.tensor(&format!("v.blk.{il}.ffn_up.weight"))?; let mut up = vec![0f32; n_pos * c.n_ff]; - up_w.matmul(&h, n_pos, &mut up); + matmul(&up_w, &h, n_pos, &mut up); if p.model.has(&format!("v.blk.{il}.ffn_up.bias")) { add_bias_rows(&mut up, &p.model.tensor(&format!("v.blk.{il}.ffn_up.bias"))?, c.n_ff); } up.par_iter_mut().for_each(|v| *v = activate(c.ffn, *v)); let down_w = p.model.tensor(&format!("v.blk.{il}.ffn_down.weight"))?; let mut down = vec![0f32; n_pos * n_embd]; - down_w.matmul(&up, n_pos, &mut down); + matmul(&down_w, &up, n_pos, &mut down); if p.model.has(&format!("v.blk.{il}.ffn_down.bias")) { add_bias_rows(&mut down, &p.model.tensor(&format!("v.blk.{il}.ffn_down.bias"))?, n_embd); } @@ -673,14 +670,14 @@ fn encode_inkling2v(p: &VisionProjector, img: &PreprocessedImage) -> anyhow::Res // 7. Projector MLP: `mm.1` -> `GeluErf` -> `mm.2`. let mm1 = p.model.tensor("mm.1.weight")?; let mut proj = vec![0f32; n_merged * mm1.rows]; - mm1.matmul(&merged, n_merged, &mut proj); + matmul(&mm1, &merged, n_merged, &mut proj); if p.model.has("mm.1.bias") { add_bias_rows(&mut proj, &p.model.tensor("mm.1.bias")?, mm1.rows); } proj.par_iter_mut().for_each(|v| *v = activate(FfnKind::GeluErf, *v)); let mm2 = p.model.tensor("mm.2.weight")?; let mut out = vec![0f32; n_merged * c.projection_dim]; - mm2.matmul(&proj, n_merged, &mut out); + matmul(&mm2, &proj, n_merged, &mut out); if p.model.has("mm.2.bias") { add_bias_rows(&mut out, &p.model.tensor("mm.2.bias")?, c.projection_dim); } @@ -749,8 +746,173 @@ fn add_bias_rows(out: &mut [f32], bias: &Tensor, cols: usize) { }); } +/// The GPU the encoders run their matmuls and attention on (`--gpu`): backend kind and device. Unset: the CPU. +static GPU_AT: OnceLock<(Option, usize)> = OnceLock::new(); +/// The backend, opened at the first image (`Some(None)`: it did not open). Encodes take turns on it. +static GPU: Mutex>>> = Mutex::new(None); + +/// Run the encoders on GPU `device` of backend `kind` (`None`: CUDA, else Vulkan). `STRATA_VISION_CPU` keeps the CPU. +pub fn use_gpu(kind: Option, device: usize) { + if std::env::var_os("STRATA_VISION_CPU").is_none() { let _ = GPU_AT.set((kind, device)); } +} + +/// `f` on the encoder's GPU; `None` without one, or when `f` fails, so the caller runs the CPU code. A failure is +/// said and sets `off`: that operation stays on the CPU from then on. +// ponytail: one failure (out of VRAM too) keeps the operation on the CPU for the rest of the run. +fn on_gpu(off: &AtomicBool, f: impl FnOnce(&dyn Backend) -> anyhow::Result) -> Option { + let (kind, device) = GPU_AT.get()?; + if off.load(Relaxed) { return None; } + let mut g = GPU.lock().unwrap_or_else(|e| e.into_inner()); + let b = g.get_or_insert_with(|| crate::backend::open(kind.as_deref(), *device) + .inspect_err(|e| crate::say!("vision: no GPU ({e:#}), images encode on the CPU")).ok()); + f(b.as_deref()?).inspect_err(|e| { + off.store(true, Relaxed); + crate::say!("vision: {e:#}; that part runs on the CPU"); + }).ok() +} + +/// The rows of `w` as f32, one after another. +fn rows_f32(w: &Tensor) -> Vec { + let mut f = vec![0f32; w.rows * w.cols]; + f.par_chunks_mut(w.cols).enumerate().for_each(|(r, row)| w.row(r, row)); + f +} + +fn f32_bytes(x: &[f32]) -> &[u8] { + // SAFETY: any f32 is 4 plain bytes; u8 has no alignment. + unsafe { std::slice::from_raw_parts(x.as_ptr().cast(), 4 * x.len()) } +} + +fn put(b: &dyn Backend, x: &[f32]) -> anyhow::Result { + let buf = b.alloc(4 * x.len())?; + b.htod(f32_bytes(x), &buf, 0)?; + Ok(buf) +} + +fn get(b: &dyn Backend, buf: &crate::backend::Buf, out: &mut [f32]) -> anyhow::Result<()> { + // SAFETY: as in f32_bytes; every byte pattern is a valid f32. + b.dtoh(buf, 0, unsafe { std::slice::from_raw_parts_mut(out.as_mut_ptr().cast(), 4 * out.len()) }) +} + +/// `w` on the GPU and the column count it has there. The GEMM takes columns in steps of 64; a weight with other widths +/// (Qwen3-VL's ffn_down: 4304) goes up with zero columns added (BF16 and F32 as they are, other types as F32), and x +/// needs them too. +fn upload_weight(b: &dyn Backend, w: &Tensor) -> anyhow::Result<(GpuTensor, usize)> { + let cols = w.cols.next_multiple_of(64); + Ok(if w.cols % 64 == 0 { (b.upload(w)?, w.cols) } else if matches!(w.ty, GgmlType::BF16 | GgmlType::F32) { + let (rb, pb) = (w.data.len() / w.rows, w.data.len() / w.rows / w.cols * cols); + let mut raw = vec![0u8; w.rows * pb]; + for (d, s) in raw.chunks_exact_mut(pb).zip(w.data.chunks_exact(rb)) { d[..rb].copy_from_slice(s); } + let buf = b.alloc(raw.len())?; + b.htod(&raw, &buf, 0)?; + (GpuTensor::new(w.ty, w.rows, cols, buf).with_scale(w.scale), cols) + } else { + let mut f = vec![0f32; w.rows * cols]; + for (r, row) in f.chunks_exact_mut(cols).enumerate() { w.row(r, &mut row[..w.cols]); } + (GpuTensor::new(GgmlType::F32, w.rows, cols, put(b, &f)?), cols) + }) +} + +/// Qwen3-VL transformer blocks on the GPU, as the CPU loop in `encode_qwen3vl` does them. x goes up once and comes +/// back once: with each matmul and the attention on their own, the host copies took most of the time (#149). +fn qwen3vl_blocks_gpu(b: &dyn Backend, p: &VisionProjector, x: &mut [f32], n: usize, mx: usize) -> anyhow::Result<()> { + let c = &p.model.cfg; + let e = c.n_embd; + anyhow::ensure!(n <= 65535 && x.len() == n * e && c.n_head * c.d_head == e, "vision: {n} patches or the head shape do not fit the GPU blocks"); + let act = match c.ffn { FfnKind::Gelu => 1, FfnKind::GeluErf => 2, FfnKind::GeluQuick => 3, FfnKind::Silu => 4 }; + // Five [n][e] buffers; the FFN runs `R` rows at a time, so its wide middle stays small (the text model has most of + // the VRAM). h holds the norms and the attention output, q the projections back to e. + const R: usize = 2048; + let ff = c.n_ff.next_multiple_of(64); + let xb = put(b, x)?; + let [h, q, k, v] = [(); 4].map(|_| b.alloc(4 * n * e)); + let (h, q, k, v) = (h?, q?, k?, v?); + let up = b.alloc(4 * R.min(n) * ff)?; + b.memset(&up)?; // the padding columns stay 0 + let vec = |name: String| p.model.to_f32(&name).and_then(|f| put(b, &f)); + let f = |buf: &crate::backend::Buf, row: usize, width: usize| buf.addr() + (4 * row * width) as u64; + // y = act(W src + bias) for rows r..r + m; src rows `xs` floats apart, y rows `ys`. + let linear = |gw: &GpuTensor, bias: u64, m: usize, src: u64, xs: usize, y: u64, ys: usize, act: i32| -> anyhow::Result<()> { + b.gemm_dense(gw, m, src, xs, y, ys, 0)?; + b.vit_bias(y, ys, bias, m, gw.rows, act) + }; + let scale = 1.0 / (c.d_head as f32).sqrt(); + for il in 0..c.n_layer { + let name = |s: &str| format!("v.blk.{il}.{s}"); + let w = |s: &str| p.model.tensor(&name(s)).and_then(|t| upload_weight(b, &t)).map(|(g, _)| g); + b.vit_norm(xb.addr(), h.addr(), vec(name("ln1.weight"))?.addr(), vec(name("ln1.bias"))?.addr(), n, e, c.eps)?; + // The kernels do not bound-check: a mmproj with other shapes must stop here (the CPU path then runs). + let shape = |s: &str, cols: usize, rows: usize| -> anyhow::Result<()> { + let t = p.model.tensor(&name(s))?; + anyhow::ensure!(t.cols == cols && t.rows == rows, "vision: {s} is {}x{}, not {cols}x{rows}", t.cols, t.rows); + Ok(()) + }; + for (s, cols, rows) in [("attn_qkv.weight", e, 3 * e), ("attn_out.weight", e, e), ("ffn_up.weight", e, c.n_ff), ("ffn_down.weight", c.n_ff, e)] { + shape(s, cols, rows)?; + } + for (s, len) in [("ln1.weight", e), ("ln1.bias", e), ("ln2.weight", e), ("ln2.bias", e), ("attn_qkv.bias", 3 * e), ("attn_out.bias", e), ("ffn_up.bias", c.n_ff), ("ffn_down.bias", e)] { + anyhow::ensure!(p.model.to_f32(&name(s))?.len() == len, "vision: {s} is not {len} long"); + } + let qkv = p.model.tensor(&name("attn_qkv.weight"))?; + let qkv_b = vec(name("attn_qkv.bias"))?; + let rb = qkv.data.len() / qkv.rows; + let mut keep = Vec::new(); + for (j, dst) in [&q, &k, &v].into_iter().enumerate() { + let wj = Tensor { ty: qkv.ty, cols: qkv.cols, rows: e, data: &qkv.data[j * e * rb..(j + 1) * e * rb], scale: qkv.scale }; + keep.push(upload_weight(b, &wj)?.0); + linear(&keep[j], qkv_b.addr() + (4 * j * e) as u64, n, h.addr(), e, dst.addr(), e, 0)?; + } + b.vit_rope(q.addr(), n, c.n_head, c.d_head, c.n_merge, mx, 10000.0)?; + b.vit_rope(k.addr(), n, c.n_head, c.d_head, c.n_merge, mx, 10000.0)?; + b.vit_attn(q.addr(), k.addr(), v.addr(), h.addr(), n, c.n_head, c.d_head, scale)?; + let (wo, ob) = (w("attn_out.weight")?, vec(name("attn_out.bias"))?); + linear(&wo, ob.addr(), n, h.addr(), e, q.addr(), e, 0)?; + b.add(xb.addr(), q.addr(), n * e)?; + b.vit_norm(xb.addr(), h.addr(), vec(name("ln2.weight"))?.addr(), vec(name("ln2.bias"))?.addr(), n, e, c.eps)?; + let (wu, ub, wd, db) = (w("ffn_up.weight")?, vec(name("ffn_up.bias"))?, w("ffn_down.weight")?, vec(name("ffn_down.bias"))?); + for r in (0..n).step_by(R) { + let m = R.min(n - r); + linear(&wu, ub.addr(), m, f(&h, r, e), e, up.addr(), ff, act)?; + linear(&wd, db.addr(), m, up.addr(), ff, f(&q, r, e), e, 0)?; + } + b.add(xb.addr(), q.addr(), n * e)?; + // This layer's weights are freed at the end of the iteration: its kernels must be done by then. + b.sync()?; + } + get(b, &xb, x) +} + +/// `out = w x` for `n` rows of x: on the GPU when there is one (the weight is uploaded for this call: each is used +/// once an image), else `Tensor::matmul`. +fn matmul(w: &Tensor, x: &[f32], n: usize, out: &mut [f32]) { + // The GPU path does not bound-check like the CPU slices do: a mmproj with mismatched shapes must stop here. + assert!(x.len() == n * w.cols && out.len() == n * w.rows, "vision matmul: shape mismatch"); + static OFF: AtomicBool = AtomicBool::new(false); + let done = on_gpu(&OFF, |b| { + let (gw, cols) = upload_weight(b, w)?; + let xb = if cols == w.cols { put(b, x)? } else { + let mut p = vec![0f32; n * cols]; + p.par_chunks_mut(cols).zip(x.par_chunks_exact(w.cols)).for_each(|(d, s)| d[..w.cols].copy_from_slice(s)); + put(b, &p)? + }; + let y = b.alloc(4 * out.len())?; + b.gemm_dense(&gw, n, xb.addr(), cols, y.addr(), w.rows, 0)?; + get(b, &y, out) + }); + if done.is_none() { w.matmul(x, n, out); } +} + +/// Unmasked attention over `n` rows of `n_head` heads (`[n][n_head][d_head]`): on the GPU when there is one. fn attention(q: &[f32], k: &[f32], v: &[f32], n: usize, n_head: usize, d_head: usize, scale: f32) -> Vec { let mut out = vec![0f32; n * n_head * d_head]; + assert!(q.len() == out.len() && k.len() == out.len() && v.len() == out.len(), "vision attention: shape mismatch"); + static OFF: AtomicBool = AtomicBool::new(false); + let done = on_gpu(&OFF, |b| { + let (qb, kb, vb, ob) = (put(b, q)?, put(b, k)?, put(b, v)?, b.alloc(4 * out.len())?); + b.vit_attn(qb.addr(), kb.addr(), vb.addr(), ob.addr(), n, n_head, d_head, scale)?; + get(b, &ob, &mut out) + }); + if done.is_some() { return out; } out.par_chunks_mut(n_head * d_head).enumerate().for_each(|(t, o)| { let mut scores = vec![0f32; n]; for h in 0..n_head { @@ -779,3 +941,4 @@ pub fn encode_image(projector: &VisionProjector, img: &Rgb) -> anyhow::Result<(V anyhow::ensure!(feats.len() == nx * ny, "encoder returned {} tokens, expected {}x{}", feats.len(), nx, ny); Ok((feats, nx, ny)) } + diff --git a/src/vision/prompt.rs b/src/vision/prompt.rs index 0902d99f..96a9d4fa 100644 --- a/src/vision/prompt.rs +++ b/src/vision/prompt.rs @@ -20,6 +20,17 @@ impl ImageSpan { pub fn n_tokens(&self) -> usize { self.width * self.height } } +impl Prompt { + /// The ids a prefix cache compares: each image's first row carries its source's hash (`hashes`, one per image, + /// in prompt order) with the top bit set, which no vocabulary id has. A cached prefix then reaches past an + /// image only when the same image starts there. + pub fn cache_keys(&self, hashes: &[u64]) -> Vec { + let mut k = self.ids.clone(); + for (s, &h) in self.images.iter().zip(hashes) { k[s.start] = 1 << 31 | (h ^ h >> 32) as u32; } + k + } +} + #[derive(Clone, Debug, Default)] pub struct Prompt { pub ids: Vec, @@ -122,6 +133,16 @@ mod tests { assert_eq!(p.images, [ImageSpan { start: 2, width: 2, height: 2 }]); } + #[test] + fn cache_keys_tell_images_apart() { + let p = expand_image(&[1, 10, 20, 30, 2], 10, 30, 20, 2, 2).unwrap(); + let (a, b) = (p.cache_keys(&[7]), p.cache_keys(&[8])); + assert_eq!(a[..2], p.ids[..2], "text before the image is plain ids"); + assert!(a[2] >= 1 << 31 && a[2] != b[2], "the image's first row names its source"); + assert_eq!(a[3..], p.ids[3..]); + assert_eq!(a, p.cache_keys(&[7])); + } + #[test] fn text_resumes_after_wider_side() { let ids = [10, 20, 30]; diff --git a/src/vulkan/mod.rs b/src/vulkan/mod.rs index 158b5080..ad99615b 100644 --- a/src/vulkan/mod.rs +++ b/src/vulkan/mod.rs @@ -3,7 +3,7 @@ //! command buffer, which a host copy or `sync` submits and waits for. Every op ends with a full compute and transfer //! barrier, which also orders it before the work of later submissions. -use crate::backend::{ATT_SPLITS, ATT_SPLITS_1, Backend, Buf, GpuTensor, SAME_X}; +use crate::backend::{BATCHED, ATT_SPLITS, ATT_SPLITS_1, Backend, Buf, GpuTensor, SAME_X}; use crate::quant::GgmlType; use anyhow::{Context, anyhow, ensure}; use ash::vk; @@ -44,7 +44,10 @@ const SPV: &[(&str, &[u8])] = &[ ("gemmi_16", include_bytes!("spv/gemmi_16.spv")), ("gemmi_dp", include_bytes!("spv/gemmi_dp.spv")), ("gemmi_s", include_bytes!("spv/gemmi_s.spv")), + ("gemm_red", include_bytes!("spv/gemm_red.spv")), ("gemmi_s_16", include_bytes!("spv/gemmi_s_16.spv")), + ("gemmi_s2", include_bytes!("spv/gemmi_s2.spv")), + ("gemmi_s2_16", include_bytes!("spv/gemmi_s2_16.spv")), ("gemv_f", include_bytes!("spv/gemv_f.spv")), ("gemv_q", include_bytes!("spv/gemv_q.spv")), ("hadamard", include_bytes!("spv/hadamard.spv")), @@ -54,6 +57,12 @@ const SPV: &[(&str, &[u8])] = &[ ("ink_attn", include_bytes!("spv/ink_attn.spv")), ("ink_attn_merge", include_bytes!("spv/ink_attn_merge.spv")), ("ink_attn_prefill", include_bytes!("spv/ink_attn_prefill.spv")), + ("attn_sel", include_bytes!("spv/attn_sel.spv")), + ("vit_attn", include_bytes!("spv/vit_attn.spv")), + ("vit_attn_cm", include_bytes!("spv/vit_attn_cm.spv")), + ("vit_norm", include_bytes!("spv/vit_norm.spv")), + ("vit_bias", include_bytes!("spv/vit_bias.spv")), + ("vit_rope", include_bytes!("spv/vit_rope.spv")), ("ink_clip", include_bytes!("spv/ink_clip.spv")), ("ink_conv", include_bytes!("spv/ink_conv.spv")), ("ink_conv_batch", include_bytes!("spv/ink_conv_batch.spv")), @@ -86,13 +95,20 @@ const SPV: &[(&str, &[u8])] = &[ ("situ_q", include_bytes!("spv/situ_q.spv")), ("softcap", include_bytes!("spv/softcap.spv")), ("swiglu", include_bytes!("spv/swiglu.spv")), + ("swiglu_clamp", include_bytes!("spv/swiglu_clamp.spv")), // quant_xq under another name, so that it gets no barrier inside a batch: its output is read after the batch. ("swiglu_q", include_bytes!("spv/quant_xq.spv")), ]; /// The device, a scratch buffer of XQ bytes for x quantized by `quant_xq` when an op does that itself, the IQ lookup -/// tables (`iq_tables`), the growable q8 rows for `gemmi` prefill, and a fixed q8 buffer for `<= TMAX` graphed forwards. -pub struct Vk(Arc, Buf, Buf, Mutex<(Buf, Option<[u64; 4]>)>, Mutex<(Buf, Option<[u64; 4]>)>); +/// tables (`iq_tables`), the growable q8 rows for `gemmi` prefill, a fixed q8 buffer for `<= TMAX` graphed forwards, +/// and the split-K slices of batched-decode GEMMs (`SPLIT_SCR` bytes, made at first use). +pub struct Vk(Arc, Buf, Buf, Mutex<(Buf, Option<[u64; 4]>)>, Mutex<(Buf, Option<[u64; 4]>)>, std::sync::OnceLock); + +/// Split-K scratch of a batched GEMM: ks * nd * rows floats, ks chosen so ks * workgroups <= SPLIT_WG (so it fits: +/// rows <= 64 g0 and nd <= 64 g1). 224, 448 and 896 measured alike at 16 rows; 448 was best at 64. +const SPLIT_WG: usize = 448; +const SPLIT_SCR: usize = SPLIT_WG * 64 * 64 * 4; /// The IQ lookup tables in one buffer, and the `tables.glsl` that names each at its offset from the buffer's address /// (spec constants 3 and 4). As GLSL const arrays the tables went to per-thread local memory on NVIDIA, which made @@ -139,6 +155,8 @@ const BAR: &[vk::MemoryPropertyFlags] = &[vk::MemoryPropertyFlags::from_raw(7), const BAR_AMD: &[vk::MemoryPropertyFlags] = &[vk::MemoryPropertyFlags::from_raw(0xc7), vk::MemoryPropertyFlags::from_raw(0xc6), vk::MemoryPropertyFlags::from_raw(7), vk::MemoryPropertyFlags::from_raw(0xe), vk::MemoryPropertyFlags::from_raw(6)]; +/// How long a waiting submit polls its fence before it sleeps in the driver. +const SPIN: std::time::Duration = std::time::Duration::from_micros(300); /// How long the host waits for a submission before it tells MoE combines still waiting for the CPU worker to give up /// (err[2], see `Inner::submit`). const GIVE_UP: std::time::Duration = std::time::Duration::from_secs(1); @@ -176,6 +194,9 @@ struct Inner { dp_tile: bool, /// Int8 cooperative matrix K-dimension (`32` for NVIDIA `16x16x32`, `16` for AMD RDNA3/3.5 `16x16x16`, `0` = off). coop_i8: u32, + /// Without int8 cooperative matrices, GEMMs of quantized weights run as gemmi_dp (int8 dot products), else as + /// gemm_f_dp (`gemm_raw`): false without hardware int8 dot products, except on RADV. + dp4: bool, /// VK_AMD_device_coherent_memory is enabled (the mailbox uses `BAR_AMD`). amd_coherent: bool, /// An AMD GPU without it: the CPU expert mailbox cannot work (the GPU caches it), so a timeout names the fix. @@ -185,8 +206,10 @@ struct Inner { cr: Option, /// Specialization constant 0 of kernels that quantize x: llama.cpp q8_K numerics (`--llama-numerics`). llama: u32, - /// Specialization constant 15 of every kernel: KV cache mode (0 = f16, 1 = q8, 2 = q4). - kv_mode: u32, + /// Specialization constants 15 and 16 of every kernel: independent K and V cache modes + /// (0 = f16, 1 = q8, 2 = q4, 3 = q2, 4 = turbo4, 5 = turbo3, 6 = turbo2). + kv_k_mode: u32, + kv_v_mode: u32, /// `maxComputeSharedMemorySize` of the device (or STRATA_VK_SMEM_LIMIT, a test hook): no pipeline may need more /// `Workgroup` bytes than this (`Vk::pipeline`), or the driver accepts it and faults at dispatch (Xid 13 on Volta). smem_limit: u32, @@ -363,7 +386,12 @@ fn features<'a>(f11: &'a mut vk::PhysicalDeviceVulkan11Features<'static>, f12: & impl Vk { /// The usable GPU with index `device` (`backend::device_order`). Fails with "Vulkan init" (and the reasons) when there is none. pub fn new(device: usize) -> anyhow::Result { - ensure!(!(crate::cuda::kv_mode() > 0 && crate::cuda::llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)"); + let (kv_k_mode, kv_v_mode) = (crate::cuda::kv_k_mode(), crate::cuda::kv_v_mode()); + // ponytail: Vulkan turbo gave wrong text on Qwen3-4B (RTX 3060) and its hd 128 prefill needs 64000 B of shared + // memory; refused until fixed, `STRATA_VK_TURBO=1` opens it for tests. + ensure!((kv_k_mode < 4 && kv_v_mode < 4) || std::env::var_os("STRATA_VK_TURBO").is_some(), + "--kv turbo* is not ready on Vulkan yet; use the CUDA backend or --kv q8/q4"); + ensure!(!(crate::cuda::kv_mode() > 0 && crate::cuda::llama_numerics()), "--kv q8/q4/turbo* does not combine with --llama-numerics (its attention reads f16 KV)"); // RADV hides VK_AMD_device_coherent_memory on RDNA4 (RX 9000) unless this driconf option is set, and without // it the GPU caches the CPU expert mailbox: MoE combines miss the worker's answer and wait until they give up. // Mesa reads the option from the environment when the device is created; other drivers ignore it. @@ -395,7 +423,7 @@ impl Vk { unsafe { instance.destroy_instance(None) }; return Err(anyhow!("no usable Vulkan device {device} ({} usable; {})", usable.len(), why.join("; "))).context("Vulkan init"); }; - eprintln!("vulkan device {device}: {name}"); + crate::say!("vulkan device {device}: {name}"); // ponytail: the instance leaks if device setup below fails; it is a one-time startup error. let mut sg = vk::PhysicalDeviceSubgroupSizeControlProperties::default(); unsafe { instance.get_physical_device_properties2(pd, &mut vk::PhysicalDeviceProperties2::default().push_next(&mut sg)) }; @@ -420,6 +448,20 @@ impl Vk { else if shape(32, vk::ComponentTypeKHR::SINT8, vk::ComponentTypeKHR::SINT32) { 32 } else if shape(16, vk::ComponentTypeKHR::SINT8, vk::ComponentTypeKHR::SINT32) { 16 } else { 0 }; + // Without int8 cooperative matrices the int8 GEMM (gemmi_dp) sums with dotPacked4x8EXT. A device without a + // 4 x int8 dot instruction (Vega 10 / gfx900: it came with gfx906) has the driver emulate it. The AMD + // proprietary driver does that so slowly that its float GEMM is 11x faster there (issue #133: prefill 30 vs + // 340 tok/s on a Vega 56), so gemm_raw takes gemm_f_dp, as llama.cpp does. RADV keeps gemmi_dp there, as before + // 1.4.2: since gemm_f_dp became the default, a Vega 64 hangs in long agentic runs (issue #148). STRATA_VK_DP4=0 + // or 1 overrides the choice. + let mut idp = vk::PhysicalDeviceShaderIntegerDotProductProperties::default(); + let mut drv = vk::PhysicalDeviceDriverProperties::default(); + unsafe { instance.get_physical_device_properties2(pd, &mut vk::PhysicalDeviceProperties2::default().push_next(&mut idp).push_next(&mut drv)) }; + let dp4 = match std::env::var("STRATA_VK_DP4").ok().as_deref() { + Some("0") => false, + Some(_) => true, + None => idp.integer_dot_product4x8_bit_packed_signed_accelerated != 0 || drv.driver_id == vk::DriverId::MESA_RADV, + }; // The tiled fallback needs a 1024-thread workgroup and 32 KB of shared memory (see attn_prefill_tile.comp). let dev_props = unsafe { instance.get_physical_device_properties(pd) }; let limits = dev_props.limits; @@ -438,7 +480,7 @@ impl Vk { }; if amd_coherent { exts.push(ash::amd::device_coherent_memory::NAME.as_ptr()) } let amd_plain = !amd_coherent && unsafe { instance.get_physical_device_properties(pd) }.vendor_id == 0x1002; - if amd_plain { eprintln!("warning: this AMD GPU has no VK_AMD_device_coherent_memory; experts on the CPU will make decode slow (the GPU \ + if amd_plain { crate::say!("warning: this AMD GPU has no VK_AMD_device_coherent_memory; experts on the CPU will make decode slow (the GPU \ does not see the CPU worker's answers in time)"); } let mut fcr = vk::PhysicalDeviceConditionalRenderingFeaturesEXT::default(); let cond = has(ash::ext::conditional_rendering::NAME) && std::env::var_os("STRATA_VK_NO_COND").is_none() && { @@ -483,11 +525,12 @@ impl Vk { // device with Xid 13). STRATA_VK_SMEM_LIMIT pretends the device reports another value, so a test can exercise // the refusal without a doctored shader. let mut smem_limit = unsafe { instance.get_physical_device_properties(pd) }.limits.max_compute_shared_memory_size; - // The AMD proprietary driver on Windows reports 32768 on RDNA3/4 cards (cooperative matrices), which really have - // 64 KB (issue #20; vulkaninfo agrees with the driver, Linux RADV reports 65536). No kernel needs more than 49152. + // The AMD proprietary driver on Windows reports 32768 on RDNA3/4 cards (cooperative matrices) and on GCN (Vega, + // issue #133), which really have 64 KB (issue #20; vulkaninfo agrees with the driver, Linux RADV reports 65536). + // No kernel needs more than 49152. let mut drv = vk::PhysicalDeviceDriverProperties::default(); unsafe { instance.get_physical_device_properties2(pd, &mut vk::PhysicalDeviceProperties2::default().push_next(&mut drv)) }; - if drv.driver_id == vk::DriverId::AMD_PROPRIETARY && coop && smem_limit == 32768 { smem_limit = 49152; } + if drv.driver_id == vk::DriverId::AMD_PROPRIETARY && smem_limit == 32768 { smem_limit = 49152; } if let Ok(v) = std::env::var("STRATA_VK_SMEM_LIMIT") { smem_limit = v.parse().context("STRATA_VK_SMEM_LIMIT")?; } let pool_info = vk::CommandPoolCreateInfo::default().queue_family_index(qf); let pool = unsafe { dev.create_command_pool(&pool_info, None) }?; @@ -502,7 +545,7 @@ impl Vk { let cr = cond.then(|| ash::ext::conditional_rendering::Device::new(&instance, &dev)); let ts_period = limits.timestamp_period; let rcp_d = dev_props.vendor_id == 0x1002; - let inner = Inner { _entry: entry, instance, pd, dev, queue, tq, qfs: [qf, tf.unwrap_or(qf)], csem, tsem, mem, budget, igpu, gfx11, wave64, rcp_d, coop, dp_tile, coop_i8, amd_coherent, amd_plain, cr, llama: crate::cuda::llama_numerics() as u32, kv_mode: crate::cuda::kv_mode(), smem_limit, ts_period, stats, layout, st: Mutex::new(st) }; + let inner = Inner { _entry: entry, instance, pd, dev, queue, tq, qfs: [qf, tf.unwrap_or(qf)], csem, tsem, mem, budget, igpu, gfx11, wave64, rcp_d, coop, dp_tile, coop_i8, dp4, amd_coherent, amd_plain, cr, llama: crate::cuda::llama_numerics() as u32, kv_k_mode, kv_v_mode, smem_limit, ts_period, stats, layout, st: Mutex::new(st) }; let staging = inner.buffer(STAGING, HOST)?; let map = unsafe { inner.dev.map_memory(staging.1, 0, vk::WHOLE_SIZE, vk::MemoryMapFlags::empty()) }; let mut st = inner.st(); @@ -520,6 +563,7 @@ impl Vk { Buf::new(0, 0, ()), Mutex::new((Buf::new(0, 0, ()), None)), Mutex::new((Buf::new(0, 0, ()), None)), + Default::default(), ); v.1 = v.buf(XQ, DEVICE)?.0; v.4.lock().unwrap().0 = v.alloc(1 << 20)?; @@ -528,7 +572,7 @@ impl Vk { v.htod(&t, &v.2, 0)?; if v.0.cr.is_some() && !v.cond_test()? { v.0.st().no_cond = true; - eprintln!("note: Vulkan conditional rendering failed its self-test; a CPU expert worker that is slow on \ + crate::say!("note: Vulkan conditional rendering failed its self-test; a CPU expert worker that is slow on \ a layer will be an error"); } // One line with what the device has, so a pasted bug report shows it. @@ -538,9 +582,10 @@ impl Vk { let yn = |b: bool| if b { "yes" } else { "no" }; let amd = if v.0.amd_plain || v.0.amd_coherent { format!(", device-coherent memory {}", yn(v.0.amd_coherent)) } else { String::new() }; let i8_s = match v.0.coop_i8 { 32 => "yes (16x16x32)", 16 => "yes (16x16x16)", _ => "no" }; - eprintln!("vulkan: {name} ({} {}){amd}, cooperative matrix f16 {} int8 {i8_s}, conditional rendering {}, maxComputeSharedMemorySize {}", - s(&drv.driver_name), s(&drv.driver_info), yn(v.0.coop), yn(v.0.cr.is_some() && !v.0.st().no_cond), v.0.smem_limit); - if !v.0.coop { eprintln!("vulkan: prefill attention: {} (no cooperative matrices)", if v.0.dp_tile { "tiled" } else { "per-query" }); } + let igpu_s = if v.0.igpu { ", iGPU unified" } else { "" }; + crate::detail!("vulkan: {name} ({} {}){amd}{igpu_s}, cooperative matrix f16 {} int8 {i8_s}, int8 dot product {}, conditional rendering {}, maxComputeSharedMemorySize {}", + s(&drv.driver_name), s(&drv.driver_info), yn(v.0.coop), yn(v.0.dp4), yn(v.0.cr.is_some() && !v.0.st().no_cond), v.0.smem_limit); + if !v.0.coop { crate::detail!("vulkan: prefill attention: {} (no cooperative matrices)", if v.0.dp_tile { "tiled" } else { "per-query" }); } Ok(v) } @@ -705,6 +750,8 @@ impl Inner { let e = st.err.2 as *mut u32; let give_up = if self.cr.is_some() && !st.no_cond { GIVE_UP } else { 8 * GIVE_UP }; let t0 = std::time::Instant::now(); + // A short round trip (a matvec of one token) ends before a sleeping thread would wake: poll first. + while t0.elapsed() < SPIN && !unsafe { self.dev.get_fence_status(st.fence) }? { std::hint::spin_loop(); } loop { match unsafe { self.dev.wait_for_fences(&[st.fence], true, 20_000_000) } { Err(vk::Result::TIMEOUT) => if t0.elapsed() >= give_up && !e.is_null() { unsafe { e.add(2).write_volatile(1) } }, @@ -810,15 +857,16 @@ impl Inner { if let Some(&p) = st.pipes.get(&(name, spec.to_vec())) { return Ok(p); } let code = SPV.iter().find(|s| s.0 == name).with_context(|| format!("no Vulkan kernel {name}"))?.1; // One choke point for Workgroup shared memory: the driver creates such a pipeline and faults at dispatch. - spv_smem::check_shared_memory(name, spec, self.kv_mode, self.smem_limit)?; + spv_smem::check_shared_memory(name, spec, self.kv_k_mode, self.kv_v_mode, self.smem_limit)?; let words = ash::util::read_spv(&mut std::io::Cursor::new(code))?; let m = unsafe { self.dev.create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&words), None) }?; let n = spec.len() as u32; let entries: Vec<_> = (0..n).map(|i| vk::SpecializationMapEntry::default().constant_id(i).offset(4 * i).size(4)) .chain([vk::SpecializationMapEntry::default().constant_id(15).offset(4 * n).size(4), - vk::SpecializationMapEntry::default().constant_id(14).offset(4 * n + 4).size(4), - vk::SpecializationMapEntry::default().constant_id(13).offset(4 * n + 8).size(4)]).collect(); - let data: Vec = spec.iter().chain([&self.kv_mode, &(self.wave64 as u32), &(self.rcp_d as u32)]).flat_map(|v| v.to_le_bytes()).collect(); + vk::SpecializationMapEntry::default().constant_id(16).offset(4 * n + 4).size(4), + vk::SpecializationMapEntry::default().constant_id(14).offset(4 * n + 8).size(4), + vk::SpecializationMapEntry::default().constant_id(13).offset(4 * n + 12).size(4)]).collect(); + let data: Vec = spec.iter().chain([&self.kv_k_mode, &self.kv_v_mode, &(self.wave64 as u32), &(self.rcp_d as u32)]).flat_map(|v| v.to_le_bytes()).collect(); let si = vk::SpecializationInfo::default().map_entries(&entries).data(&data); let mut sub = vk::PipelineShaderStageRequiredSubgroupSizeCreateInfo::default().required_subgroup_size(32); let stage = vk::PipelineShaderStageCreateInfo::default().stage(vk::ShaderStageFlags::COMPUTE).module(m).name(c"main").specialization_info(&si); @@ -867,20 +915,29 @@ impl Arg for f32 { fn put(&self, v: &mut Vec) { v.extend(self.to_le_bytes()) impl Vk { /// As the CUDA one: both kernels run, the step decides which one works, then attn_merge combines the splits (and /// writes out quantized into xq when not null). - fn attn(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize) -> anyhow::Result<()> { + fn attn(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize, kvt: u64, splits: usize) -> anyhow::Result<()> { ensure!([64, 128, 256, 512].contains(&hd), "attention head_dim {hd} unsupported (64, 128, 256 or 512)"); - let (per, pz) = ((hd / 32) as u32, (nh * ATT_SPLITS * (hd + 2)) as u32); + let (per, pz) = ((hd / 32) as u32, (nh * splits * (hd + 2)) as u32); // splits: of attn_decode_gqa if self.0.llama != 0 { // one head per workgroup, merged as the attn_decode splits (empty ones weigh 0) self.run("attn_decode_llama", &[0, hd as u32], [nh * nt, ATT_SPLITS_1, 1], &[&q, &kc, &vc, &part, &step, &sel, &(sst as u32), &(nh as u32), &(nkv as u32), &scale, &pz, &(nt as u32), &(win as i32)])?; return self.run("attn_merge", &[], [nh, 1, nt], &[&part, &qg, &out, &step, &(hd as u32), &(ATT_SPLITS as u32), &(ATT_SPLITS_1 as u32), &i32::MAX, &0u64, &sink]); } let g = [8, 4, 2, 1].into_iter().find(|&g| (nh / nkv) % g == 0 && g * hd <= 2048).unwrap(); - let args: [&dyn Arg; 14] = [&q, &kc, &vc, &part, &step, &sel, &(sst as u32), &(nh as u32), &(nkv as u32), &scale, &gq_min, &pz, &(nt as u32), &(win as i32)]; + let args: [&dyn Arg; 15] = [&q, &kc, &vc, &part, &step, &sel, &(sst as u32), &(nh as u32), &(nkv as u32), &scale, &gq_min, &pz, &(nt as u32), &(win as i32), &kvt]; // gq_min i32::MAX or 0 fixes the regime, so the dispatch that would exit at once is skipped. let wide = (nt >= 2) as u32; if gq_min != 0 { self.run("attn_decode", &[0, per, 1, 0, wide], [nh * nt, ATT_SPLITS_1, 1], &args)?; } - if gq_min != i32::MAX { self.run("attn_decode", &[0, per, g as u32, 1, wide], [nh / g * nt, ATT_SPLITS, 1], &args)?; } - self.run("attn_merge", &[], [nh, 1, nt], &[&part, &qg, &out, &step, &(hd as u32), &(ATT_SPLITS as u32), &(ATT_SPLITS_1 as u32), &gq_min, &xq, &sink]) + if gq_min != i32::MAX { self.run("attn_decode", &[0, per, g as u32, 1, wide], [nh / g * nt, splits, 1], &args)?; } + self.run("attn_merge", &[], [nh, 1, nt], &[&part, &qg, &out, &step, &(hd as u32), &(splits as u32), &(ATT_SPLITS_1 as u32), &gq_min, &xq, &sink]) + } + /// rms_norm with rope and (kc, or kvt with v) the K/V store; see rms_norm.comp. + fn rope_rows(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, step: u64, base: f32, v: u64, kc: u64, vc: u64, kvt: u64) -> anyhow::Result<()> { + if kc != 0 || (kvt != 0 && v != 0) { + let turbo = self.0.kv_k_mode >= 4 || self.0.kv_v_mode >= 4; + ensure!(!turbo || n % 128 == 0, "turbo KV cache: head_dim {n} is not a multiple of 128"); + } + let ts = (base as f64).powf(-2.0 / n_rot as f64); + self.run("rms_norm", &[self.0.llama], [rows, 1, 1], &[&x, &w, &out, &0u64, &(x_stride as u32), &(n as u32), &(n as u32), &eps, &step, &ts, &(per as u32), &(n_rot as u32), &0u64, &v, &kc, &vc, &kvt]) } /// Record kernel `name` over `groups` workgroups with push constants `args`. fn run(&self, name: &'static str, spec: &[u32], groups: [usize; 3], args: &[&dyn Arg]) -> anyhow::Result<()> { @@ -988,14 +1045,14 @@ impl Vk { ensure!(cols % 64 == 0, "{} matrix with {cols} columns: GEMM needs a multiple of 64", ty.name()); if n_tiles == 0 { return Ok(()); } let (spec, grid, nk) = (self.wspec(ty), [rows.div_ceil(64), n_tiles, 1], (cols / 64) as u32); - let (same, act) = (act & SAME_X != 0, act & !SAME_X); + let (same, batched, act) = (act & SAME_X != 0, act & BATCHED != 0, act & 3); let mut q8 = self.q8_mutex(n_x, cols).lock().unwrap(); let key = Some([x, x_stride as u64, n_x as u64, cols as u64]); // as on CUDA let reuse = same && q8.1 == key; // A gemm inside a batch cannot quantize x (the quantize and the gemm would not be ordered): when the cached // q8 rows are not x's (or, without SAME_X, may not be), use the f16 kernel (as on CUDA). let int8 = crate::cuda::Gpu::mmq(ty) && cols.is_multiple_of(128); - let f = !int8 || (!reuse && self.0.st().batch); + let f = !int8 || (!reuse && self.0.st().batch) || (self.0.coop_i8 == 0 && !self.0.dp4); // A dense GEMM of few workgroups runs as gemm_fs/gemmi_s (cooperative matrices only), 32 positions a // workgroup (as on CUDA). let sm = tiles == 0 && grid[0] * grid[1] < 112 && if f { self.0.coop } else { self.0.coop_i8 != 0 }; @@ -1013,6 +1070,23 @@ impl Vk { // Only SAME_X promises that x still holds what was quantized (as on CUDA). if !same { q8.1 = None; } let xq = self.q8_x(&mut q8, ty, cols, n_x, x, x_stride)?.expect("int8 GEMM without a quantized x"); + // A step of a batch of requests (at most 64 rows of x): gemmi_s, K split over ks workgroups so that the few + // weight-row tiles fill the device, each slice into the scratch, then gemm_red sums them (as gemmd on CUDA). + if batched && tiles == 0 && xrow == 0 && nd <= 64 && self.0.coop_i8 != 0 && !self.0.st().batch { + // More than 32 positions: gemmi_s2, one tile of 64, so each weight is decoded once. + let s2 = nd > 32; + let g = [rows.div_ceil(64), nd.div_ceil(if s2 { 64 } else { 32 }), 1]; + let ks = (SPLIT_WG / (g[0] * g[1])).clamp(1, 8).min(nk as usize / 4).max(1); + let (sk, scr) = if ks > 1 { (ks, self.5.get_or_init(|| self.alloc(SPLIT_SCR).expect("split-K scratch")).addr()) } else { (1, y) }; + let (ys, a) = if ks > 1 { (rows, 0) } else { (y_stride, act) }; + let args: [&dyn Arg; 11] = [&tiles, &wd, &xq, &xrow, &scr, &(nd as u32), &(ys as u32), tail[0], tail[1], &a, tail[3]]; + self.run(match (s2, self.0.coop_i8 == 32) { (false, true) => "gemmi_s", (false, false) => "gemmi_s_16", (true, true) => "gemmi_s2", (true, false) => "gemmi_s2_16" }, &spec, [g[0], g[1], sk], &args)?; + if ks > 1 { + self.run("gemm_red", &[], [(rows * nd).div_ceil(256), 1, 1], + &[&scr, &y, &(rows as u32), &(nd as u32), &(y_stride as u32), &(ks as u32), &act])?; + } + return Ok(()); + } let args: [&dyn Arg; 11] = [&tiles, &wd, &xq, &xrow, &y, &(nd as u32), &(y_stride as u32), tail[0], tail[1], tail[2], tail[3]]; let (gk, gks) = match self.0.coop_i8 { 32 => ("gemmi", "gemmi_s"), 16 => ("gemmi_16", "gemmi_s_16"), _ => ("gemmi_dp", "gemmi_dp") }; self.run(if self.0.coop_i8 == 0 { "gemmi_dp" } else if sm { gks } else { gk }, &spec, grid, &args)?; @@ -1032,6 +1106,8 @@ fn gemv_cols(llama: u32, ty: GgmlType, cols: usize) -> anyhow::Result { #[allow(unused_variables)] impl Backend for Vk { fn name(&self) -> &'static str { "vulkan" } + // The int8 GEMM runs only with int8 cooperative matrices or dot products (`gemm_raw`); tests pick the reference by it. + fn mmq(&self, ty: GgmlType) -> bool { (self.0.coop_i8 != 0 || self.0.dp4) && crate::cuda::Gpu::mmq(ty) } fn device(&self) -> String { let p = unsafe { self.0.instance.get_physical_device_properties(self.0.pd) }; p.device_name_as_c_str().map_or(String::new(), |s| s.to_string_lossy().into_owned()) @@ -1043,6 +1119,7 @@ impl Backend for Vk { self.2.clone(), Mutex::new((Buf::new(0, 0, ()), None)), Mutex::new((Buf::new(0, 0, ()), None)), + Default::default(), ); v.4.lock().unwrap().0 = v.alloc(1 << 20)?; Ok(Box::new(v)) @@ -1147,17 +1224,35 @@ impl Backend for Vk { } /// Free from `VK_EXT_memory_budget` when the driver has it, else the heap size less this backend's buffers. + /// On an iGPU (e.g. AMD Radeon 890M), `Inner::buffer` falls back from the small BIOS DEVICE_LOCAL carveout to the + /// unified HOST (GTT) heap, so sum all unique DEVICE+HOST heaps and cap `free` by available host RAM to avoid OOM. fn mem_info(&self) -> anyhow::Result<(usize, usize)> { let m = &self.0.mem; - let h = (0..m.memory_heap_count as usize).find(|&h| m.memory_heaps[h].flags.contains(vk::MemoryHeapFlags::DEVICE_LOCAL)) - .context("no device-local heap")?; - let total = m.memory_heaps[h].size as usize; - if !self.0.budget { return Ok((total.saturating_sub(self.0.st().bufs.values().map(|b| b.1).sum()), total)); } - let mut b = vk::PhysicalDeviceMemoryBudgetPropertiesEXT::default(); - let mut p = vk::PhysicalDeviceMemoryProperties2::default().push_next(&mut b); - unsafe { self.0.instance.get_physical_device_memory_properties2(self.0.pd, &mut p) }; - let _ = p; - Ok((b.heap_budget[h].saturating_sub(b.heap_usage[h]) as usize, total)) + let heaps = if self.0.igpu { + igpu_heaps(m) + } else { + let h = (0..m.memory_heap_count as usize).find(|&h| m.memory_heaps[h].flags.contains(vk::MemoryHeapFlags::DEVICE_LOCAL)) + .context("no device-local heap")?; + vec![h] + }; + anyhow::ensure!(!heaps.is_empty(), "no device-local heap"); + let total: usize = heaps.iter().map(|&h| m.memory_heaps[h].size as usize).fold(0usize, usize::saturating_add); + let free = if !self.0.budget { + total.saturating_sub(self.0.st().bufs.values().map(|b| b.1).sum()) + } else { + let mut b = vk::PhysicalDeviceMemoryBudgetPropertiesEXT::default(); + let mut p = vk::PhysicalDeviceMemoryProperties2::default().push_next(&mut b); + unsafe { self.0.instance.get_physical_device_memory_properties2(self.0.pd, &mut p) }; + let _ = p; + heaps.iter().map(|&h| b.heap_budget[h].saturating_sub(b.heap_usage[h]) as usize).fold(0usize, usize::saturating_add) + }; + let free = if self.0.igpu { + let capped = crate::memory::available_ram().map_or(free, |avail| free.min(avail as usize)); + capped.min(total) + } else { + free.min(total) + }; + Ok((free, total)) } fn sync(&self) -> anyhow::Result<()> { self.0.flush(&mut self.0.st()) } @@ -1234,6 +1329,14 @@ impl Backend for Vk { unsafe { self.0.dev.free_command_buffers(st.gpool, &[c]) }; Ok(()) } + fn graph_clear(&self) -> anyhow::Result<()> { + let mut st = self.0.st(); + if st.graphs.is_empty() { return Ok(()) } + self.0.flush(&mut st)?; + let cs: Vec<_> = st.graphs.drain().map(|(_, c)| c).collect(); + unsafe { self.0.dev.free_command_buffers(st.gpool, &cs) }; + Ok(()) + } fn moe_mailbox_optional(&self) -> bool { true } fn verify_rows(&self) -> usize { crate::cpu_worker::TMAX } @@ -1245,7 +1348,10 @@ impl Backend for Vk { } fn preflight(&self, types: &[GgmlType], verbose: bool) -> anyhow::Result<()> { Vk::preflight(self, types, verbose) } fn kv_words(&self, n: usize) -> usize { - match self.0.kv_mode { 0 => n, 1 => n * 17 / 32, 2 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } + match self.0.kv_k_mode { 0 => n, 1 => n * 17 / 32, 2 | 4..=6 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } + } + fn kv_words_v(&self, n: usize) -> usize { + match self.0.kv_v_mode { 0 => n, 1 => n * 17 / 32, 2 | 4..=6 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } } fn gemm(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { @@ -1329,14 +1435,22 @@ impl Backend for Vk { self.rms_norm_q(x, x_stride, w, out, out_stride, n, rows, eps, 0, 0) } fn rms_norm_q(&self, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, n: usize, rows: usize, eps: f32, xq: u64, res: u64) -> anyhow::Result<()> { - self.run("rms_norm", &[self.0.llama], [rows, 1, 1], &[&x, &w, &out, &xq, &(x_stride as u32), &(out_stride as u32), &(n as u32), &eps, &0u64, &0f64, &0u32, &0u32, &res, &0u64, &0u64, &0u64]) + self.run("rms_norm", &[self.0.llama], [rows, 1, 1], &[&x, &w, &out, &xq, &(x_stride as u32), &(out_stride as u32), &(n as u32), &eps, &0u64, &0f64, &0u32, &0u32, &res, &0u64, &0u64, &0u64, &0u64]) } fn rms_norm_rope(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { self.rms_norm_rope_kv(x, x_stride, w, out, n, rows, eps, per, n_rot, step, base, 0, 0, 0) } fn rms_norm_rope_kv(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { - let ts = (base as f64).powf(-2.0 / n_rot as f64); - self.run("rms_norm", &[self.0.llama], [rows, 1, 1], &[&x, &w, &out, &0u64, &(x_stride as u32), &(n as u32), &(n as u32), &eps, &step, &ts, &(per as u32), &(n_rot as u32), &0u64, &v, &kc, &vc]) + self.rope_rows(x, x_stride, w, out, n, rows, eps, per, n_rot, step, base, v, kc, vc, 0) + } + fn kv_rows(&self) -> bool { self.0.llama == 0 } // attn_decode_llama has no kvt + fn rms_norm_rope_qk_rows(&self, q: u64, q_stride: usize, qw: u64, qo: u64, nh: usize, k: u64, kw: u64, ko: u64, nkv: usize, hd: usize, eps: f32, n_rot: usize, + step: u64, base: f32, v: u64, kvt: u64, nt: usize) -> anyhow::Result<()> { + self.rope_rows(q, q_stride, qw, qo, hd, nt * nh, eps, nh, n_rot, step, base, 0, 0, 0, kvt)?; + self.rope_rows(k, hd, kw, ko, hd, nt * nkv, eps, nkv, n_rot, step, base, v, 0, 0, kvt) + } + fn attn_rows(&self, q: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, nt: usize, sink: u64, win: usize, kvt: u64, splits: usize) -> anyhow::Result<()> { + self.attn(q, 0, 0, qg, out, part, step, nh, nkv, hd, scale, 0, nt, 0, 0, 0, sink, win, kvt, splits) } fn argmax_rows(&self, x: u64, n: usize, rows: usize, out: u64) -> anyhow::Result<()> { // One workgroup per row reads 1 MB (a 248320-token vocabulary) in ~25 us; 64 per row share it. The partials go @@ -1355,6 +1469,7 @@ impl Backend for Vk { } fn add(&self, x: u64, y: u64, n: usize) -> anyhow::Result<()> { self.run("add", &[], [n.div_ceil(256), 1, 1], &[&x, &y, &(n as u32)]) } fn swiglu(&self, g: u64, u: u64, n: usize) -> anyhow::Result<()> { self.run("swiglu", &[], [n.div_ceil(256), 1, 1], &[&g, &u, &(n as u32)]) } + fn swiglu_clamp(&self, g: u64, u: u64, n: usize, lim: f32) -> anyhow::Result<()> { self.run("swiglu_clamp", &[], [n.div_ceil(256), 1, 1], &[&g, &u, &(n as u32), &lim]) } fn situ(&self, y: u64, n: usize, rows: usize, scale: u64, beta: f32, lb: f32) -> anyhow::Result<()> { self.run("situ", &[], [(n * rows).div_ceil(256), 1, 1], &[&y, &scale, &(n as u32), &(rows as u32), &beta, &lb]) } @@ -1388,12 +1503,13 @@ impl Backend for Vk { pos0: usize, log_alpha: f32, log_floor: f32, ) -> anyhow::Result<()> { ensure!(w <= 128, "ink_clip_n: w={w} > 128"); - ensure!(self.0.kv_mode == 0 || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); + let quant = |m: u32| m > 0; + ensure!(!(quant(self.0.kv_k_mode) || quant(self.0.kv_v_mode)) || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; self.run("ink_clip", &[], [rows, nt, 1], &[ &x, &scale, &dst, &0u64, &(w as u32), &thr, &eps, &mul, - &(dst_at0 as u32), &(ring as u32), &(pos0 as u32), &log_alpha, &fl, + &(dst_at0 as u32), &(ring as u32), &(pos0 as u32), &log_alpha, &fl, &0u32, ]) } fn ink_clip_pos( @@ -1403,12 +1519,44 @@ impl Backend for Vk { pos_ptr: u64, log_alpha: f32, log_floor: f32, ) -> anyhow::Result<()> { ensure!(w <= 128, "ink_clip_pos: w={w} > 128"); - ensure!(self.0.kv_mode == 0 || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); + ensure!(!(self.0.kv_k_mode > 0 || self.0.kv_v_mode > 0) || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; self.run("ink_clip", &[], [rows, nt, 1], &[ &x, &scale, &dst, &pos_ptr, &(w as u32), &thr, &eps, &mul, - &0u32, &(ring as u32), &0u32, &log_alpha, &fl, + &0u32, &(ring as u32), &0u32, &log_alpha, &fl, &0u32, + ]) + } + fn ink_clip_n_v( + &self, x: u64, scale: u64, w: usize, rows: usize, nt: usize, + thr: f32, eps: f32, mul: f32, + dst: u64, dst_at0: usize, dst_ring: usize, + pos0: usize, log_alpha: f32, log_floor: f32, + ) -> anyhow::Result<()> { + ensure!(w <= 128, "ink_clip_n: w={w} > 128"); + let quant = self.0.kv_k_mode > 0 || self.0.kv_v_mode > 0; + ensure!(!quant || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); + let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; + let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; + self.run("ink_clip", &[], [rows, nt, 1], &[ + &x, &scale, &dst, &0u64, &(w as u32), &thr, &eps, &mul, + &(dst_at0 as u32), &(ring as u32), &(pos0 as u32), &log_alpha, &fl, &1u32, + ]) + } + fn ink_clip_pos_v( + &self, x: u64, scale: u64, w: usize, rows: usize, nt: usize, + thr: f32, eps: f32, mul: f32, + dst: u64, dst_ring: usize, + pos_ptr: u64, log_alpha: f32, log_floor: f32, + ) -> anyhow::Result<()> { + ensure!(w <= 128, "ink_clip_pos: w={w} > 128"); + let quant = self.0.kv_k_mode > 0 || self.0.kv_v_mode > 0; + ensure!(!quant || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); + let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; + let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; + self.run("ink_clip", &[], [rows, nt, 1], &[ + &x, &scale, &dst, &pos_ptr, &(w as u32), &thr, &eps, &mul, + &0u32, &(ring as u32), &0u32, &log_alpha, &fl, &1u32, ]) } fn ink_attn(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, rows: usize, at: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { @@ -1431,6 +1579,29 @@ impl Backend for Vk { &(pos as u32), &(nt as u32), &(nh as u32), &(nkv as u32), &(nr as u32), &(ext as u32), &(ring.max(1) as u32), &(win as u32), ]) } + fn attn_sel(&self, q: u64, kc: u64, vc: u64, idx: u64, cnt: u64, out: u64, nt: usize, nh: usize, nkv: usize, hd: usize, ns: usize, scale: f32) -> anyhow::Result<()> { + let per = nh / nkv.max(1); + ensure!(hd % 32 == 0 && hd <= 256 && nkv > 0 && nh % nkv == 0 && (1..=8).contains(&per), "attn_sel: unsupported shape nh={nh} nkv={nkv} hd={hd}"); + self.run("attn_sel", &[0, hd as u32, per as u32, (32 * per) as u32], [nt, nkv, 1], &[&q, &kc, &vc, &idx, &cnt, &out, &(nh as u32), &(nkv as u32), &(ns as u32), &scale]) + } + fn vit_norm(&self, x: u64, out: u64, w: u64, b: u64, rows: usize, n: usize, eps: f32) -> anyhow::Result<()> { + self.run("vit_norm", &[], [rows, 1, 1], &[&x, &out, &w, &b, &(n as u32), &eps]) + } + fn vit_bias(&self, y: u64, stride: usize, bias: u64, rows: usize, cols: usize, act: i32) -> anyhow::Result<()> { + self.run("vit_bias", &[], [cols.div_ceil(256), rows, 1], &[&y, &bias, &(stride as u32), &(cols as u32), &act]) + } + fn vit_rope(&self, x: u64, n: usize, nh: usize, hd: usize, m: usize, mx: usize, base: f32) -> anyhow::Result<()> { + let ts = base.powf(-2.0 / (hd / 2) as f32); + self.run("vit_rope", &[], [n, 1, 1], &[&x, &(nh as u32), &(hd as u32), &(m as u32), &(mx as u32), &ts]) + } + fn vit_attn(&self, q: u64, k: u64, v: u64, out: u64, n: usize, nh: usize, hd: usize, scale: f32) -> anyhow::Result<()> { + ensure!(hd > 0 && hd <= 128, "vit_attn: head dim {hd} not supported"); + // Cooperative matrices: the head padded to 80 (STRATA_VIT_SCALAR=1 keeps the scalar kernel). + if self.0.coop && hd <= 80 && hd % 8 == 0 && std::env::var_os("STRATA_VIT_SCALAR").is_none() { + return self.run("vit_attn_cm", &[], [n.div_ceil(64), nh, 1], &[&q, &k, &v, &out, &(n as u32), &(nh as u32), &(hd as u32), &scale]); + } + self.run("vit_attn", &[0, hd as u32], [n.div_ceil(32), nh, 1], &[&q, &k, &v, &out, &(n as u32), &(nh as u32), &scale]) + } fn ink_ffn_sum_n(&self, acc: u64, d: u64, wts: u64, ne: usize, n: usize, nt: usize, cpu: u64) -> anyhow::Result<()> { self.run("ink_ffn_sum", &[], [n.div_ceil(256), nt, 1], &[&acc, &d, &wts, &cpu, &(ne as u32), &(n as u32)]) } @@ -1438,17 +1609,25 @@ impl Backend for Vk { ensure!(n_expert <= 512 && k <= 32, "ink_route: n_expert={n_expert} k={k}"); self.run("ink_route", &[], [rows, 1, 1], &[&logits, &bias, &ids, &wts, &gu_sc, &dn_sc, &gsc_out, &(n_expert as u32), &(k as u32), &exp_scale]) } - fn hadamard(&self, x: u64, u: u64, s: u64, out: u64, n: usize, block: usize, rows: usize) -> anyhow::Result<()> { - // ponytail: a block is one workgroup, and 128 invocations is what every Vulkan device takes; a larger block - // needs maxComputeWorkGroupInvocations checked. - ensure!(block <= 128, "prism.hadamard.block_size {block}: at most 128 on Vulkan"); - self.run("hadamard", &[self.0.llama, block as u32], [n / block, rows, 1], &[&x, &u, &s, &out, &(n as u32), &(1.0 / (block as f32).sqrt())]) + fn hadamard(&self, x: u64, u: u64, s: u64, perm: u64, out: u64, n: usize, block: usize, rows: usize) -> anyhow::Result<()> { + // A block is one workgroup of at most 128 invocations (what every Vulkan device takes) and 16 KB of shared floats. + ensure!((2..=4096).contains(&block), "prism.hadamard.block_size {block}: 2 to 4096 on Vulkan"); + self.run("hadamard", &[self.0.llama, block as u32, block.min(128) as u32], [n / block, rows, 1], &[&x, &u, &s, &perm, &out, &(n as u32), &(1.0 / (block as f32).sqrt())]) } fn ssm_gates(&self, beta: u64, g: u64, dt_bias: u64, a: u64, n: usize, nv: usize) -> anyhow::Result<()> { self.run("ssm_gates", &[], [n.div_ceil(256), 1, 1], &[&beta, &g, &dt_bias, &a, &(n as u32), &(nv as u32)]) } fn conv_silu(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, nn: usize, eps: f32) -> anyhow::Result<()> { - self.run("conv_silu", &[], [ch.div_ceil(128), 1, 1], &[&qkv, &state, &w, &y, &(ch as u32), &(kw as u32), &(nn as u32), &eps]) + self.run("conv_silu", &[], [ch.div_ceil(128), 1, 1], &[&qkv, &state, &w, &y, &(ch as u32), &(kw as u32), &(nn as u32), &eps, &0u64]) + } + fn conv_silu_rows(&self, qkv: u64, tab: u64, states: &[u64], w: u64, y: u64, ch: usize, kw: usize, eps: f32) -> anyhow::Result<()> { + self.run("conv_silu", &[], [ch.div_ceil(128), states.len(), 1], &[&qkv, &0u64, &w, &y, &(ch as u32), &(kw as u32), &0u32, &eps, &tab]) + } + fn deltanet_rows(&self, y: u64, tab: u64, states: &[u64], beta: u64, g: u64, o: u64, nk: usize, nv: usize, interleave: bool, dk: usize, dv: usize, scale: f32, ych: usize) -> anyhow::Result<()> { + let rows = 512 / dk.max(1); + ensure!(matches!(dk, 32 | 64 | 128 | 256) && dv % rows == 0, "deltanet: head dims {dk}/{dv} unsupported"); + self.run("deltanet", &[], [nv, dv.div_ceil(8 * rows), states.len()], &[&y, &0u64, &beta, &g, &o, &0u64, &0u64, &0u64, &tab, &(nk as u32), &(nv as u32), + &(interleave as u32), &(dk as u32), &(dv as u32), &scale, &1u32, &(ych as u32), &0u32]) } fn deltanet(&self, y: u64, s: u64, beta: u64, g: u64, dt_bias: u64, a: u64, o: u64, nk: usize, nv: usize, interleave: bool, dk: usize, dv: usize, scale: f32, t: usize, ych: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { self.deltanet_strided(y, s, beta, g, dt_bias, a, o, nk, nv, interleave, dk, dv, scale, t, ych, snap, nsnap, 1) @@ -1458,7 +1637,7 @@ impl Backend for Vk { let rows = 512 / dk.max(1); // state rows per subgroup ensure!(matches!(dk, 32 | 64 | 128 | 256) && dv % rows == 0, "deltanet: head dims {dk}/{dv} unsupported"); let spec: &[u32] = if snap_stride > 1 { &[0, snap_stride as u32] } else { &[] }; - self.run("deltanet", spec, [nv, dv.div_ceil(8 * rows), 1], &[&y, &s, &beta, &g, &o, &snap, &dt_bias, &a, &(nk as u32), &(nv as u32), + self.run("deltanet", spec, [nv, dv.div_ceil(8 * rows), 1], &[&y, &s, &beta, &g, &o, &snap, &dt_bias, &a, &0u64, &(nk as u32), &(nv as u32), &(interleave as u32), &(dk as u32), &(dv as u32), &scale, &(t as u32), &(ych as u32), &(nsnap as u32)]) } fn conv_seq(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, t: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { @@ -1551,15 +1730,17 @@ impl Backend for Vk { } fn kv_store(&self, k: u64, v: u64, kc: u64, vc: u64, n: usize, t: usize, step: u64, hd: usize) -> anyhow::Result<()> { // q8/q4: each subgroup quantizes one 32-value block of one row. - ensure!(self.0.kv_mode == 0 || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32"); + ensure!((self.0.kv_k_mode == 0 && self.0.kv_v_mode == 0) || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32"); + let turbo = self.0.kv_k_mode >= 4 || self.0.kv_v_mode >= 4; + ensure!(!turbo || hd % 128 == 0, "turbo KV cache: head_dim {hd} is not a multiple of 128"); self.run("kv_store", &[], [(n * t).div_ceil(256), 1, 1], &[&k, &v, &kc, &vc, &step, &(n as u32), &((n * t) as u32), &(hd as u32)]) } fn attn_decode_gq(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, gq_min: i32, nt: usize, sink: u64, win: usize) -> anyhow::Result<()> { - self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, 0, 0, 0, sink, win) + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, 0, 0, 0, sink, win, 0, ATT_SPLITS) } fn attn_decode_q(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize) -> anyhow::Result { let xq = if self.0.llama != 0 { 0 } else { xq }; - self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, xq, sel, sst, sink, win)?; + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, xq, sel, sst, sink, win, 0, ATT_SPLITS)?; Ok(xq) } fn qsa_pool(&self, ik: u64, ring: u64, pool: u64, w: u64, step: u64, t: usize, n_rot: usize, base: f32, eps: f32) -> anyhow::Result<()> { @@ -1574,7 +1755,8 @@ impl Backend for Vk { ensure!(n <= 512 && k <= 32, "router_topk: {n} experts, top {k}"); self.run("router_topk", &[], [t, 1, 1], &[&p, &ids, &wts, &(n as u32), &(k as u32), &extra_scale, &(sigmoid as u32)]) } - fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool) -> anyhow::Result<()> { + fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool, hid: u64, hmin: i32) -> anyhow::Result<()> { + let _ = (hid, hmin); debug_assert_eq!(pid, 0, "the Vulkan backend has no next-layer prefetch"); ensure!(n <= 512 && k <= 32, "moe_route: {n} experts, top {k}"); self.run("moe_route", &[], [1, 1, 1], &[&p, &table, &ids, &wts, &slots, &wh, &h, &mb, &step, &(n as u32), &(k as u32), &extra_scale, &(nh as u32), &(h_off as u32), &(t as u32), &(sigmoid as u32)]) @@ -1629,3 +1811,60 @@ impl Vk { &(rows as u32), &nc, &(xg as u32), &(ntok as u32), &(rpw as u32)]) } } + +/// Unique Vulkan heap indices usable by `DEVICE` or `HOST` allocations on an integrated GPU (excluding AMD uncached +/// flags 0xc0). Matches `Inner::buffer`'s fallback from `DEVICE` to `HOST` on APUs with a small BIOS VRAM carveout. +fn igpu_heaps(m: &vk::PhysicalDeviceMemoryProperties) -> Vec { + let ok = |f: vk::MemoryPropertyFlags, want| f.contains(want) && (f & vk::MemoryPropertyFlags::from_raw(0xc0) & !want).is_empty(); + let mut heaps = Vec::new(); + for i in 0..m.memory_type_count as usize { + let mt = m.memory_types[i]; + let h = mt.heap_index as usize; + if h < m.memory_heap_count as usize + && DEVICE.iter().chain(HOST.iter()).any(|&w| ok(mt.property_flags, w)) + && !heaps.contains(&h) + { + heaps.push(h); + } + } + heaps +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn igpu_heaps_combines_vram_and_gtt_without_duplicates_or_uncached() { + let mut m = vk::PhysicalDeviceMemoryProperties::default(); + m.memory_heap_count = 3; + m.memory_heaps[0] = vk::MemoryHeap { size: 512 << 20, flags: vk::MemoryHeapFlags::DEVICE_LOCAL }; + m.memory_heaps[1] = vk::MemoryHeap { size: 16 << 30, flags: vk::MemoryHeapFlags::empty() }; + m.memory_heaps[2] = vk::MemoryHeap { size: 256 << 20, flags: vk::MemoryHeapFlags::empty() }; + m.memory_type_count = 5; + // Heap 0: DEVICE_LOCAL (512 MB BIOS carveout on Radeon 890M) + m.memory_types[0] = vk::MemoryType { property_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL, heap_index: 0 }; + // Heap 0 duplicate: DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT + m.memory_types[1] = vk::MemoryType { + property_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL | vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, + heap_index: 0, + }; + // Heap 1: GTT HOST_VISIBLE | HOST_COHERENT | HOST_CACHED (16 GB unified LPDDR) + m.memory_types[2] = vk::MemoryType { + property_flags: vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT | vk::MemoryPropertyFlags::HOST_CACHED, + heap_index: 1, + }; + // Heap 2: AMD device-coherent / uncached only (flags 0xc0) — must be excluded + m.memory_types[3] = vk::MemoryType { + property_flags: vk::MemoryPropertyFlags::from_raw(0xc6), + heap_index: 2, + }; + // Heap 1 duplicate: HOST_VISIBLE | HOST_COHERENT + m.memory_types[4] = vk::MemoryType { + property_flags: vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, + heap_index: 1, + }; + assert_eq!(igpu_heaps(&m), vec![0, 1]); + } +} + diff --git a/src/vulkan/preflight.rs b/src/vulkan/preflight.rs index 9961e758..3ae27e01 100644 --- a/src/vulkan/preflight.rs +++ b/src/vulkan/preflight.rs @@ -14,7 +14,7 @@ use std::time::Instant; impl Vk { /// The `Workgroup` bytes of kernel `name` with `spec` and this device's KV cache mode. pub fn shared_bytes(&self, name: &str, spec: &[u32]) -> Result { - spv_smem::shared_bytes(name, spec, self.0.kv_mode) + spv_smem::shared_bytes_split(name, spec, self.0.kv_k_mode, self.0.kv_v_mode) } /// Check the (kernel, specialization) pairs the weight types `types` reach (see `gpu_model::gpu_weight_types`) @@ -30,13 +30,13 @@ impl Vk { let (mut n, mut worst) = (0usize, (0u32, "", Vec::new())); for (name, spec) in self.shared_memory_pairs(types) { if !checked.insert((name, spec.clone())) { continue; } - let bytes = spv_smem::check_shared_memory(name, &spec, self.0.kv_mode, self.0.smem_limit)?; + let bytes = spv_smem::check_shared_memory(name, &spec, self.0.kv_k_mode, self.0.kv_v_mode, self.0.smem_limit)?; n += 1; if verbose { crate::say!("vulkan: preflight {name} {spec:?}: {bytes} bytes"); } if bytes > worst.0 { worst = (bytes, name, spec); } } - crate::say!("vulkan: shared-memory preflight: {n} (kernel, specialization) pairs checked, largest {} bytes \ - ({}) of {} allowed, {:.1} ms", worst.0, worst.1, self.0.smem_limit, t0.elapsed().as_secs_f64() * 1e3); + if verbose || crate::term::verbose() { crate::say!("vulkan: shared-memory preflight: {n} (kernel, specialization) pairs checked, largest {} bytes \ + ({}) of {} allowed, {:.1} ms", worst.0, worst.1, self.0.smem_limit, t0.elapsed().as_secs_f64() * 1e3); } if !verbose { let mut st = self.0.st(); for &ty in types { @@ -75,7 +75,7 @@ impl Vk { let mut max = 0; for (name, spec) in self.shared_memory_pairs(types) { if !checked.insert((name, spec.clone())) { continue; } - max = max.max(spv_smem::check_shared_memory(name, &spec, self.0.kv_mode, self.0.smem_limit)?); + max = max.max(spv_smem::check_shared_memory(name, &spec, self.0.kv_k_mode, self.0.kv_v_mode, self.0.smem_limit)?); } Ok(max) } @@ -89,14 +89,16 @@ impl Vk { let float = ty.float_x(); let mut push = |name: &'static str, spec: Vec| pairs.push((name, spec)); // gemm_raw: `f = !mmq(ty) || cols % 128 != 0`; the float kernel takes every type, the int8 one the rest. - if float || !crate::cuda::Gpu::mmq(ty) { + // Without int8 cooperative matrices or hardware int8 dot products every type takes the float kernel. + let no_i8 = self.0.coop_i8 == 0 && !self.0.dp4; + if float || !crate::cuda::Gpu::mmq(ty) || no_i8 { if self.0.coop { push("gemm_f", ws.clone()); push("gemm_fs", ws.clone()); } else { push("gemm_f_dp", ws.clone()); } } if !float { if self.0.coop_i8 == 32 { push("gemmi", ws.clone()); push("gemmi_s", ws.clone()); } else if self.0.coop_i8 == 16 { push("gemmi_16", ws.clone()); push("gemmi_s_16", ws.clone()); } - else { push("gemmi_dp", ws.clone()); } + else if !no_i8 { push("gemmi_dp", ws.clone()); } for nt in 1..=4 { push("gemv_q", [&ws[..], &[nt]].concat()); } for nm in [1u32, 4, 8, 17] { push("moe_gemv_q", [&ws[..], &[nm]].concat()); } push("dequant", ws.clone()); diff --git a/src/vulkan/shaders/attn_decode.comp b/src/vulkan/shaders/attn_decode.comp index ea4c9c3b..a9b91cde 100644 --- a/src/vulkan/shaders/attn_decode.comp +++ b/src/vulkan/shaders/attn_decode.comp @@ -11,10 +11,12 @@ layout(constant_id = 3) const bool GQA = false; // 0 ..= step (see qsa_select). // WIDE (nt >= 2): f16 rows in uvec4 loads. They cut two-token (MTP) calls by up to 18% at 32K but cost one-token calls // 4-11% at 16K+, so one token keeps the word loads. +// kvt (not null): token t is a row of its own sequence, with its caches at kvt[2t] and kvt[2t + 1] (step_batch). layout(constant_id = 4) const bool WIDE = false; const uint HD = PER * 32, C = 32, J = 4, NW = 8; // positions per chunk, per subgroup; subgroups +layout(buffer_reference, std430, buffer_reference_align = 8) buffer U64 { uint64_t v[]; }; layout(push_constant) uniform P { F32 q; U32 kc; U32 vc; F32 part; I32 step; I32 sel; uint sst; uint nh; uint nkv; float scale; int gq_min; - uint pz; uint nt; int win; } p; + uint pz; uint nt; int win; U64 kvt; } p; layout(buffer_reference, std430, buffer_reference_align = 16) buffer UV4 { uvec4 v[]; }; shared float sq[PER * 256]; // G * HD query values, then NW * HD subgroup partials shared float ss[G * C], sc[G], sm[G], sl[G]; @@ -39,31 +41,47 @@ void main() { return; } uint g = h0 / (p.nh / p.nkv); + bool rows = uint64_t(p.kvt) != 0; + U32 kc = rows ? U32(p.kvt.v[2 * t]) : p.kc, vc = rows ? U32(p.kvt.v[2 * t + 1]) : p.vc; for (uint i = tid; i < G * HD; i += 256) sq[i] = p.q.v[qo + h0 * HD + i]; precise float acc[G * PER], l = 0.0; // l, m: running sum and max of head w (subgroups w < G) float m = ninf; [[unroll]] for (uint i = 0; i < G * PER; i++) acc[i] = 0.0; #define cell(i) (sp ? uint(p.sel.v[so + 1 + (i)]) : (base + (i))) barrier(); + if (TQ_K) { + // Rotate each query head's 128-value groups into the KV domain (4 dims per lane). + for (uint i = 0u; i < G; i++) + for (uint gg = 0u; gg < HD / 128u; gg++) { + uint lane = tid & 31u; + if ((tid >> 5u) == (i * (HD / 128u) + gg) % 8u) { + uint base = i * HD + gg * 128u + 4u * lane; + vec4 qv = vec4(sq[base], sq[base + 1u], sq[base + 2u], sq[base + 3u]); + qv = tq_wht4(qv, lane, false); + sq[base] = qv.x; sq[base + 1u] = qv.y; sq[base + 2u] = qv.z; sq[base + 3u] = qv.w; + } + } + barrier(); + } for (uint c0 = p0; c0 < p1; c0 += C) { float s_part[J * G]; [[unroll]] for (uint j = 0; j < J; j++) { uint kr[PER / 2]; uint tt = c0 + w * J + j, r = ((cell(min(tt, p1 - 1)) * p.nkv + g) * HD + lane * PER) / 2; - if (KV_MODE > 0u && PER % 4 == 0) { + if (K_MODE > 0u && PER % 4 == 0) { [[unroll]] for (uint d = 0; d < PER / 2; d += 2) { - uvec2 k = ldkv4(U16(uint64_t(p.kc)), 2 * (r + d), HD); + uvec2 k = ldkv4_k(U16(uint64_t(kc)), 2 * (r + d), HD); if (tt >= p1) k = uvec2(0); kr[d] = k.x; kr[d + 1] = k.y; } - } else if (KV_MODE == 0u && WIDE && PER % 8 == 0) { + } else if (K_MODE == 0u && WIDE && PER % 8 == 0) { [[unroll]] for (uint d = 0; d < PER / 2; d += 4) { - uvec4 k = UV4(uint64_t(p.kc)).v[(r + d) / 4]; + uvec4 k = UV4(uint64_t(kc)).v[(r + d) / 4]; [[unroll]] for (uint e = 0; e < 4; e++) kr[d + e] = tt >= p1 ? 0 : k[e]; } } else { [[unroll]] for (uint d = 0; d < PER / 2; d++) { - uint k = KV_MODE > 0u ? ldkv2(U16(uint64_t(p.kc)), 2 * (r + d), HD) : p.kc.v[r + d]; + uint k = K_MODE > 0u ? ldkv2_k(U16(uint64_t(kc)), 2 * (r + d), HD) : kc.v[r + d]; kr[d] = tt >= p1 ? 0 : k; } } @@ -100,20 +118,20 @@ void main() { [[unroll]] for (uint j = 0; j < J; j++) { uint vr[PER / 2]; uint tt = c0 + w * J + j, r = ((cell(min(tt, p1 - 1)) * p.nkv + g) * HD + lane * PER) / 2; - if (KV_MODE > 0u && PER % 4 == 0) { + if (V_MODE > 0u && PER % 4 == 0) { [[unroll]] for (uint d = 0; d < PER / 2; d += 2) { - uvec2 v = ldkv4(U16(uint64_t(p.vc)), 2 * (r + d), HD); + uvec2 v = ldkv4_v(U16(uint64_t(vc)), 2 * (r + d), HD); if (tt >= p1) v = uvec2(0); vr[d] = v.x; vr[d + 1] = v.y; } - } else if (KV_MODE == 0u && WIDE && PER % 8 == 0) { + } else if (V_MODE == 0u && WIDE && PER % 8 == 0) { [[unroll]] for (uint d = 0; d < PER / 2; d += 4) { - uvec4 v = UV4(uint64_t(p.vc)).v[(r + d) / 4]; + uvec4 v = UV4(uint64_t(vc)).v[(r + d) / 4]; [[unroll]] for (uint e = 0; e < 4; e++) vr[d + e] = tt >= p1 ? 0 : v[e]; } } else { [[unroll]] for (uint d = 0; d < PER / 2; d++) { - uint v = KV_MODE > 0u ? ldkv2(U16(uint64_t(p.vc)), 2 * (r + d), HD) : p.vc.v[r + d]; + uint v = V_MODE > 0u ? ldkv2_v(U16(uint64_t(vc)), 2 * (r + d), HD) : vc.v[r + d]; vr[d] = tt >= p1 ? 0 : v; } } diff --git a/src/vulkan/shaders/attn_merge.comp b/src/vulkan/shaders/attn_merge.comp index f40baa46..dc3eea45 100644 --- a/src/vulkan/shaders/attn_merge.comp +++ b/src/vulkan/shaders/attn_merge.comp @@ -6,6 +6,7 @@ layout(local_size_x = 256) in; // quant_xq does (hd is a multiple of 32: a subgroup holds one scale's 32 values). layout(push_constant) uniform P { F32 part; F32 qg; F32 out_; I32 step; uint hd; uint ns; uint ns1; int gq_min; U8 xq; F32 sink; } p; shared float ws[256]; // split max, then split weight +shared float ro[512]; // ungated output in the rotated domain void main() { uint h = gl_WorkGroupID.x, nh = gl_NumWorkGroups.x, z = gl_WorkGroupID.z, tid = gl_LocalInvocationID.x, hd = p.hd; uint ns = p.step.v[2 * z] + 1 < p.gq_min ? p.ns1 : p.ns; // attn_decode ran, not attn_decode_gqa @@ -25,8 +26,23 @@ void main() { for (uint d = tid; d < hd; d += 256) { precise float o = 0.0; for (uint s = 0; s < ns; s++) o = fma(p.part.v[pp + s * (hd + 2) + d], ws[s], o); + ro[d] = fdiv(o, L); + } + barrier(); + if (TQ_V) { + for (uint g = 0u; g < hd / 128u; g++) { + if (tid < 32u) { + uint base = g * 128u + 4u * tid; + vec4 v = vec4(ro[base], ro[base + 1u], ro[base + 2u], ro[base + 3u]); + v = tq_wht4(v, tid, true); + ro[base] = v.x; ro[base + 1u] = v.y; ro[base + 2u] = v.z; ro[base + 3u] = v.w; + } + } + barrier(); + } + for (uint d = tid; d < hd; d += 256) { float gate = uint64_t(p.qg) != 0 ? sigmoid(p.qg.v[(z * nh + h) * 2 * hd + hd + d]) : 1.0; - float v = fdiv(o, L) * gate; + float v = ro[d] * gate; p.out_.v[(z * nh + h) * hd + d] = v; if (uint64_t(p.xq) != 0) { float mx = warp_max(abs(v)), id = mx > 0.0 ? rcp_d(127.0, mx) : 0.0; diff --git a/src/vulkan/shaders/attn_prefill.glsl b/src/vulkan/shaders/attn_prefill.glsl index f9ad724e..fc0416b1 100644 --- a/src/vulkan/shaders/attn_prefill.glsl +++ b/src/vulkan/shaders/attn_prefill.glsl @@ -22,6 +22,22 @@ shared float ss[4 * 16 * BK]; // scores of each subgroup; at the start the shared float16_t ps[4 * 16 * PP]; // softmax weights of each subgroup shared float rs[4 * 16]; // per row: the rescale factor, at the end the sum l shared float rm[4 * 16]; // per row: the final max +// Q staging, reused for the inverse WHT output (warp, row, dim); one column without a turbo cache, so the 48 KB of +// shared memory NVIDIA's Vulkan driver allows still hold the other tiles. +const uint TQ_D = (TQ_K || TQ_V) ? HD : 1u; +shared float16_t tq_q[4][16][TQ_D]; +float tq_kget(uint row, uint col) { + uvec4 u = kvs[row * PQ + col / 8u]; + return unpackFloat2x16(u[(col % 8u) / 2u])[col % 2u]; +} +void tq_kset(uint row, uint col, float x) { + uint a = row * PQ + col / 8u, w = (col % 8u) / 2u; + uvec4 u = kvs[a]; + vec2 h = unpackFloat2x16(u[w]); + h[col % 2u] = x; + u[w] = packFloat2x16(f16vec2(h)); + kvs[a] = u; +} void main() { uint pos0 = uint(p.step.v[0]), q0 = (gl_NumWorkGroups.x - 1 - gl_WorkGroupID.x) * BQ, h = gl_WorkGroupID.y, kvh = h / (p.nh / p.nkv), kvd = p.nkv * HD; @@ -42,6 +58,37 @@ void main() { ps[i] = float16_t(i / 16); ps[256 + i] = float16_t(i % 16); } barrier(); + if (TQ_K) { + // Unpack Q into per-dim staging first: several lanes share a uvec4 word, so writing it in place races. + uint w0 = WARP; + for (uint i = tid; i < 4u * 16u * (HD / 8u); i += 128u) { + uint w = i / (16u * (HD / 8u)), r = (i / (HD / 8u)) % 16u, c = i % (HD / 8u); + uvec4 u = kvs[(w * 16u + r) * PQ + c]; + [[unroll]] for (uint h = 0u; h < 8u; h++) + tq_q[w][r][c * 8u + h] = unpackFloat2x16(u[h / 2u])[h % 2u]; + } + barrier(); + uint lane = LANE; + for (uint r = 0u; r < 16u; r++) + for (uint gg = 0u; gg < HD / 128u; gg++) { + uint base = gg * 128u + 4u * lane; + vec4 v = vec4(float(tq_q[w0][r][base]), float(tq_q[w0][r][base + 1u]), + float(tq_q[w0][r][base + 2u]), float(tq_q[w0][r][base + 3u])); + v = tq_wht4(v, lane, false); + tq_q[w0][r][base] = float16_t(v.x); tq_q[w0][r][base + 1u] = float16_t(v.y); + tq_q[w0][r][base + 2u] = float16_t(v.z); tq_q[w0][r][base + 3u] = float16_t(v.w); + } + barrier(); + for (uint i = tid; i < 4u * 16u * (HD / 8u); i += 128u) { + uint w = i / (16u * (HD / 8u)), r = (i / (HD / 8u)) % 16u, c = i % (HD / 8u); + uvec4 u; + [[unroll]] for (uint h = 0u; h < 8u; h += 2u) { + u[h / 2u] = packFloat2x16(f16vec2(tq_q[w][r][c * 8u + h], tq_q[w][r][c * 8u + h + 1u])); + } + kvs[(w * 16u + r) * PQ + c] = u; + } + barrier(); + } // Pack the 8 (row, col) indices in 0..15 of this lane's accumulator elements into 2 uint VGPRs instead of keeping 16 float VGPRs live. uint r_pack = 0u, c_pack = 0u; bool nv; @@ -88,8 +135,8 @@ void main() { for (uint n = 0; n < N; n++) { uint i = tid + n * 128, r = i / (HD / 8), c = i % (HD / 8), off = (min(k0 + r, last) * kvd + kvh * HD) / 8 + c, o = off * 8; bool in_ = k0 + r <= last; - uvec4 kl = KV_MODE > 0u ? uvec4(ldkv4(p.kc, o, HD), ldkv4(p.kc, o + 4, HD)) : UV4(uint64_t(p.kc)).v[off]; - uvec4 vl = KV_MODE > 0u ? uvec4(ldkv4(p.vc, o, HD), ldkv4(p.vc, o + 4, HD)) : UV4(uint64_t(p.vc)).v[off]; + uvec4 kl = K_MODE > 0u ? uvec4(ldkv4_k(p.kc, o, HD), ldkv4_k(p.kc, o + 4, HD)) : UV4(uint64_t(p.kc)).v[off]; + uvec4 vl = V_MODE > 0u ? uvec4(ldkv4_v(p.vc, o, HD), ldkv4_v(p.vc, o + 4, HD)) : UV4(uint64_t(p.vc)).v[off]; kvs[r * PQ + c] = in_ ? kl : uvec4(0); kvs[(BK + r) * PQ + c] = in_ ? vl : uvec4(0); } @@ -97,8 +144,8 @@ void main() { uvec4 kl[N], vl[N]; [[unroll]] for (uint n = 0; n < N; n++) { uint i = tid + n * 128, r = i / (HD / 8), c = i % (HD / 8), off = (min(k0 + r, last) * kvd + kvh * HD) / 8 + c, o = off * 8; - kl[n] = KV_MODE > 0u ? uvec4(ldkv4(p.kc, o, HD), ldkv4(p.kc, o + 4, HD)) : UV4(uint64_t(p.kc)).v[off]; - vl[n] = KV_MODE > 0u ? uvec4(ldkv4(p.vc, o, HD), ldkv4(p.vc, o + 4, HD)) : UV4(uint64_t(p.vc)).v[off]; + kl[n] = K_MODE > 0u ? uvec4(ldkv4_k(p.kc, o, HD), ldkv4_k(p.kc, o + 4, HD)) : UV4(uint64_t(p.kc)).v[off]; + vl[n] = V_MODE > 0u ? uvec4(ldkv4_v(p.vc, o, HD), ldkv4_v(p.vc, o + 4, HD)) : UV4(uint64_t(p.vc)).v[off]; } [[unroll]] for (uint n = 0; n < N; n++) { uint i = tid + n * 128, r = i / (HD / 8), c = i % (HD / 8); @@ -190,6 +237,30 @@ void main() { subgroupMemoryBarrierShared(); subgroupBarrier(); float sk = uint64_t(p.sink) != 0 ? p.sink.v[h] : ninf; + if (TQ_V) { + for (uint i = 0u; i < acc[0].length(); i++) { + uint row = (r_pack >> (4u * i)) & 15u; + float mx = rm[rb + row]; + float M = max(mx, sk), sc = mx == ninf ? 0.0 : expf_(mx - M); + float den = rs[rb + row] * sc + (sk == ninf ? 0.0 : expf_(sk - M)); + float inv = den > 0.0 ? fdiv(sc, den) : 0.0; + [[unroll]] for (uint d = 0u; d < HD / 16u; d++) { + uint col = d * 16u + ((c_pack >> (4u * i)) & 15u); + tq_q[w][row][col] = float16_t(acc[d][i] * inv); + } + } + barrier(); + for (uint r = 0u; r < 16u; r++) + for (uint gg = 0u; gg < HD / 128u; gg++) { + uint lane = LANE, base = gg * 128u + 4u * lane; + vec4 v = vec4(float(tq_q[w][r][base]), float(tq_q[w][r][base + 1u]), + float(tq_q[w][r][base + 2u]), float(tq_q[w][r][base + 3u])); + v = tq_wht4(v, lane, true); + tq_q[w][r][base] = float16_t(v.x); tq_q[w][r][base + 1u] = float16_t(v.y); + tq_q[w][r][base + 2u] = float16_t(v.z); tq_q[w][r][base + 3u] = float16_t(v.w); + } + barrier(); + } [[unroll]] for (uint d = 0; d < HD / 16; d++) [[unroll]] for (uint i = 0; i < acc[d].length(); i++) { uint row = (r_pack >> (4u * i)) & 15u, col = d * 16 + ((c_pack >> (4u * i)) & 15u), t = q0 + w * 16 + row; @@ -199,6 +270,6 @@ void main() { float den = rs[rb + row] * sc + (sk == ninf ? 0.0 : expf_(sk - M)); float inv = den > 0.0 ? fdiv(sc, den) : 0.0; float gate = uint64_t(p.qg) != 0 ? sigmoid(p.qg.v[t * p.nh * 2 * HD + h * 2 * HD + HD + col]) : 1.0; - p.o.v[t * p.nh * HD + h * HD + col] = acc[d][i] * inv * gate; + p.o.v[t * p.nh * HD + h * HD + col] = (TQ_V ? float(tq_q[w][row][col]) : acc[d][i] * inv) * gate; } } diff --git a/src/vulkan/shaders/attn_prefill_dp.comp b/src/vulkan/shaders/attn_prefill_dp.comp index d776c165..e8da85ac 100644 --- a/src/vulkan/shaders/attn_prefill_dp.comp +++ b/src/vulkan/shaders/attn_prefill_dp.comp @@ -7,7 +7,26 @@ layout(local_size_x = 128) in; layout(push_constant) uniform P { F32 q; U16 kc; U16 vc; F32 qg; F32 o; I32 step; uint t; uint nh; uint nkv; float scale; U32 qm; uint mw; uint q_off; F32 sink; int win; } p; layout(constant_id = 1) const uint PER = 4; // head_dim / 32 const uint HD = 32 * PER; - +uint tq_idx(uint j, uint lane, uint mode) { + if (mode >= 4u) return PER == 2u ? 2u * lane + (j & 1u) : (j >> 2u) * 128u + 4u * lane + (j & 3u); + return lane + 32u * j; +} +void rotate_q(inout float q[PER], uint lane) { + for (uint g = 0u; g < PER / 4u; g++) { + vec4 v = vec4(q[4u * g], q[4u * g + 1u], q[4u * g + 2u], q[4u * g + 3u]); + v = tq_wht4(v, lane, false); + q[4u * g] = v.x; q[4u * g + 1u] = v.y; q[4u * g + 2u] = v.z; q[4u * g + 3u] = v.w; + } + if (PER == 2u) { vec2 v = vec2(q[0], q[1]); v = tq_wht2(v, lane, false); q[0] = v.x; q[1] = v.y; } +} +void rotate_v(inout float v[PER], uint lane) { + for (uint g = 0u; g < PER / 4u; g++) { + vec4 a = vec4(v[4u * g], v[4u * g + 1u], v[4u * g + 2u], v[4u * g + 3u]); + a = tq_wht4(a, lane, true); + v[4u * g] = a.x; v[4u * g + 1u] = a.y; v[4u * g + 2u] = a.z; v[4u * g + 3u] = a.w; + } + if (PER == 2u) { vec2 a = vec2(v[0], v[1]); a = tq_wht2(a, lane, true); v[0] = a.x; v[1] = a.y; } +} void main() { uint t = gl_WorkGroupID.x * 4 + WARP, h = gl_WorkGroupID.y, lane = LANE; if (t >= p.t) return; @@ -15,29 +34,33 @@ void main() { uint kvo = h / (p.nh / p.nkv) * HD + lane, kvd = p.nkv * HD, last = uint(p.step.v[0]) + row; float q[PER], acc[PER], m = 0.0, l = 0.0; [[unroll]] for (uint j = 0; j < PER; j++) { - q[j] = p.q.v[(t * p.nh + h) * HD + lane + 32 * j] * p.scale; + q[j] = p.q.v[(t * p.nh + h) * HD + tq_idx(j, lane, KV_MODE)] * p.scale; acc[j] = 0.0; } + if (TQ_K) rotate_q(q, lane); bool first = true; for (uint k = 0; k <= last; k++) { if (p.win > 0 && k + uint(p.win) <= last) continue; if (uint64_t(p.qm) != 0 && !qsa_bit(p.qm, p.mw, row, k)) continue; float s = 0.0; - [[unroll]] for (uint j = 0; j < PER; j++) s += q[j] * ldkv(p.kc, k * kvd + kvo + 32 * j, HD); + [[unroll]] for (uint j = 0; j < PER; j++) s += q[j] * ldkv_k(p.kc, k * kvd + h / (p.nh / p.nkv) * HD + tq_idx(j, lane, KV_MODE), HD); s = W64 ? warp_sum(s) : subgroupAdd(s); float mn = first ? s : max(m, s), c = first ? 0.0 : expf_(m - mn), e = expf_(s - mn); l = first ? e : fma(l, c, e); first = false; - [[unroll]] for (uint j = 0; j < PER; j++) acc[j] = fma(e, ldkv(p.vc, k * kvd + kvo + 32 * j, HD), acc[j] * c); + [[unroll]] for (uint j = 0; j < PER; j++) acc[j] = fma(e, ldkv_v(p.vc, k * kvd + h / (p.nh / p.nkv) * HD + tq_idx(j, lane, VKV_MODE), HD), acc[j] * c); m = mn; } float sk = uint64_t(p.sink) != 0 ? p.sink.v[h] : uintBitsToFloat(0xff800000u); float M = max(m, sk), sc = m == uintBitsToFloat(0xff800000u) ? 0.0 : expf_(m - M); float den = l * sc + (uint64_t(p.sink) == 0 ? 0.0 : expf_(sk - M)); float inv = den > 0.0 ? fdiv(sc, den) : 0.0; + float ov[PER]; + [[unroll]] for (uint j = 0; j < PER; j++) ov[j] = acc[j] * inv; + if (TQ_V) rotate_v(ov, lane); [[unroll]] for (uint j = 0; j < PER; j++) { - uint col = lane + 32 * j; + uint col = tq_idx(j, lane, VKV_MODE); float gate = uint64_t(p.qg) != 0 ? sigmoid(p.qg.v[t * p.nh * 2 * HD + h * 2 * HD + HD + col]) : 1.0; - p.o.v[t * p.nh * HD + h * HD + col] = acc[j] * inv * gate; + p.o.v[t * p.nh * HD + h * HD + col] = ov[j] * gate; } } diff --git a/src/vulkan/shaders/attn_prefill_tile.comp b/src/vulkan/shaders/attn_prefill_tile.comp index a9899936..a571f4cc 100644 --- a/src/vulkan/shaders/attn_prefill_tile.comp +++ b/src/vulkan/shaders/attn_prefill_tile.comp @@ -12,7 +12,26 @@ const uint BK = 8192 / HD; // keys per tile: 32, 64 or 128; 3 layout(push_constant) uniform P { F32 q; U16 kc; U16 vc; F32 qg; F32 o; I32 step; uint t; uint nh; uint nkv; float scale; U32 qm; uint mw; uint bq; uint hper; uint hgroups; uint q_off; F32 sink; int win; } p; // K and V rows of the current key tile, all f16 (also with KV_Q8: ldkv rounds to f16, so this is exact). shared float16_t sk[8192], sv[8192]; - +uint tq_idx(uint j, uint lane, uint mode) { + if (mode >= 4u) return PER == 2u ? 2u * lane + (j & 1u) : (j >> 2u) * 128u + 4u * lane + (j & 3u); + return lane + 32u * j; +} +void rotate_q(inout float q[8], uint lane) { + for (uint g = 0u; g < PER / 4u; g++) { + vec4 v = vec4(q[4u * g], q[4u * g + 1u], q[4u * g + 2u], q[4u * g + 3u]); + v = tq_wht4(v, lane, false); + q[4u * g] = v.x; q[4u * g + 1u] = v.y; q[4u * g + 2u] = v.z; q[4u * g + 3u] = v.w; + } + if (PER == 2u) { vec2 v = vec2(q[0], q[1]); v = tq_wht2(v, lane, false); q[0] = v.x; q[1] = v.y; } +} +void rotate_v(inout float v[8], uint lane) { + for (uint g = 0u; g < PER / 4u; g++) { + vec4 a = vec4(v[4u * g], v[4u * g + 1u], v[4u * g + 2u], v[4u * g + 3u]); + a = tq_wht4(a, lane, true); + v[4u * g] = a.x; v[4u * g + 1u] = a.y; v[4u * g + 2u] = a.z; v[4u * g + 3u] = a.w; + } + if (PER == 2u) { vec2 a = vec2(v[0], v[1]); a = tq_wht2(a, lane, true); v[0] = a.x; v[1] = a.y; } +} void main() { uint tid = gl_LocalInvocationID.x, task = WARP, lane = LANE; uint g = p.nh / p.nkv; // query heads per KV head @@ -25,12 +44,13 @@ void main() { uint qr = min(q, p.t - 1), hr = min(h, p.nh - 1); // inactive tasks still form a safe address below uint pos0 = uint(p.step.v[0]), last_max = pos0 + p.q_off + min(q0 + p.bq, p.t) - 1, last_q = pos0 + p.q_off + q; uint kvd = p.nkv * HD, kvo = kvh * HD; - float qv[PER], acc[PER], m = 0.0, l = 0.0; + float qv[8], acc[8], m = 0.0, l = 0.0; bool first = true; [[unroll]] for (uint j = 0; j < PER; j++) { - qv[j] = live ? p.q.v[(qr * p.nh + hr) * HD + lane + 32 * j] * p.scale : 0.0; + qv[j] = live ? p.q.v[(qr * p.nh + hr) * HD + tq_idx(j, lane, KV_MODE)] * p.scale : 0.0; acc[j] = 0.0; } + if (TQ_K) rotate_q(qv, lane); for (uint k0 = 0; k0 <= last_max; k0 += BK) { barrier(); // All threads load the tile (inactive tasks too, they still reach the barrier). Rows past the last key are @@ -39,20 +59,20 @@ void main() { uint r = i / HD, c = i % HD, k = k0 + r; bool ok = k <= last_max; uint off = ok ? k * kvd + kvo + c : 0; - sk[i] = ok ? float16_t(ldkv(p.kc, off, HD)) : float16_t(0.0); - sv[i] = ok ? float16_t(ldkv(p.vc, off, HD)) : float16_t(0.0); + sk[i] = ok ? float16_t(ldkv_k(p.kc, off, HD)) : float16_t(0.0); + sv[i] = ok ? float16_t(ldkv_v(p.vc, off, HD)) : float16_t(0.0); } barrier(); if (live) for (uint r = 0; r < BK; r++) { uint k = k0 + r; if (k > last_q || (p.win > 0 && k + uint(p.win) <= last_q) || (uint64_t(p.qm) != 0 && !qsa_bit(p.qm, p.mw, p.q_off + q, k))) continue; float s = 0.0; - [[unroll]] for (uint j = 0; j < PER; j++) s += qv[j] * float(sk[r * HD + lane + 32 * j]); + [[unroll]] for (uint j = 0; j < PER; j++) s += qv[j] * float(sk[r * HD + tq_idx(j, lane, KV_MODE)]); s = W64 ? warp_sum(s) : subgroupAdd(s); float mn = first ? s : max(m, s), c = first ? 0.0 : expf_(m - mn), e = expf_(s - mn); l = first ? e : fma(l, c, e); first = false; - [[unroll]] for (uint j = 0; j < PER; j++) acc[j] = fma(e, float(sv[r * HD + lane + 32 * j]), acc[j] * c); + [[unroll]] for (uint j = 0; j < PER; j++) acc[j] = fma(e, float(sv[r * HD + tq_idx(j, lane, VKV_MODE)]), acc[j] * c); m = mn; } } @@ -61,9 +81,12 @@ void main() { float M = max(m, sk), sc = m == uintBitsToFloat(0xff800000u) ? 0.0 : expf_(m - M); float den = l * sc + (uint64_t(p.sink) == 0 ? 0.0 : expf_(sk - M)); float inv = den > 0.0 ? fdiv(sc, den) : 0.0; + float ov[8]; + [[unroll]] for (uint j = 0; j < PER; j++) ov[j] = acc[j] * inv; + if (TQ_V) rotate_v(ov, lane); [[unroll]] for (uint j = 0; j < PER; j++) { - uint col = lane + 32 * j; + uint col = tq_idx(j, lane, VKV_MODE); float gate = uint64_t(p.qg) != 0 ? sigmoid(p.qg.v[q * p.nh * 2 * HD + h * 2 * HD + HD + col]) : 1.0; - p.o.v[q * p.nh * HD + h * HD + col] = acc[j] * inv * gate; + p.o.v[q * p.nh * HD + h * HD + col] = ov[j] * gate; } } diff --git a/src/vulkan/shaders/attn_sel.comp b/src/vulkan/shaders/attn_sel.comp new file mode 100644 index 00000000..f6259e03 --- /dev/null +++ b/src/vulkan/shaders/attn_sel.comp @@ -0,0 +1,87 @@ +#version 460 +layout(constant_id = 1) const uint HD = 128; // head_dim +layout(constant_id = 2) const uint PERH = 4; // query heads of one K/V head +layout(local_size_x_id = 3) in; // 32 * PERH +#include "common.glsl" +layout(push_constant) uniform P { F32 q; U16 kc; U16 vc; U32 idx; I32 cnt; F32 outp; uint nh; uint nkv; uint ns; float scale; } p; + +// Attention of each query over its own list of keys (attn_sel of kernels.cu): query t reads the cnt[t] rows +// idx[t * ns ..] of an f16 K/V cache. A workgroup is one query token and one K/V head, a warp one query head; +// 32 keys of K and V are loaded into shared memory at a time. +shared float qs[PERH * HD], kt[32 * HD], vt[32 * HD], ps[PERH * 32]; +shared float ro[PERH * HD]; +void main() { + uint t = gl_WorkGroupID.x, g = gl_WorkGroupID.y, h = WARP, c = LANE, tid = h * 32u + c, nthr = PERH * 32u; + uint n = uint(p.cnt.v[t]), qg = (t * p.nh + g * PERH) * HD; + for (uint i = tid; i < PERH * HD; i += nthr) qs[i] = p.q.v[qg + i]; + barrier(); + if (TQ_K) { + for (uint hh = 0u; hh < PERH; hh++) + for (uint gg = 0u; gg < HD / 128u; gg++) { + uint lane = c; + if (h == hh && lane < 32u) { + uint base = hh * HD + gg * 128u + 4u * lane; + vec4 v = vec4(qs[base], qs[base + 1u], qs[base + 2u], qs[base + 3u]); + v = tq_wht4(v, lane, false); + qs[base] = v.x; qs[base + 1u] = v.y; qs[base + 2u] = v.z; qs[base + 3u] = v.w; + } + } + barrier(); + } + float acc[8]; + for (uint r = 0; r < 8u; r++) acc[r] = 0.0; + float ninf = uintBitsToFloat(0xff800000u), m = ninf, l = 0.0; + for (uint j0 = 0; j0 < n; j0 += 32u) { + barrier(); + for (uint i = tid; i < 32u * HD; i += nthr) { + uint j = j0 + i / HD; + if (j < n) { + uint row = (p.idx.v[t * p.ns + j] * p.nkv + g) * HD + i % HD; + kt[i] = ldkv_k(p.kc, row, HD); + vt[i] = ldkv_v(p.vc, row, HD); + } else { + kt[i] = 0.0; + vt[i] = 0.0; + } + } + barrier(); + bool key = j0 + c < n; + float s = ninf; + if (key) { + float d = 0.0; + for (uint i = 0; i < HD; i++) d = fma(qs[h * HD + i], kt[c * HD + i], d); + s = d * p.scale; + } + float mn = max(m, warp_max(s)); + float a = m == ninf ? 0.0 : expf_(m - mn), e = key ? expf_(s - mn) : 0.0; + l = l * a + warp_sum(e); + m = mn; + ps[tid] = e; + barrier(); + for (uint r = 0; r < HD / 32u; r++) { + float v = 0.0; + for (uint k = 0; k < 32u; k++) v = fma(ps[h * 32u + k], vt[k * HD + c + 32u * r], v); + acc[r] = acc[r] * a + v; + } + } + uint o = (t * p.nh + g * PERH + h) * HD; + if (TQ_V) { + for (uint r = 0u; r < HD / 32u; r++) ro[h * HD + c + 32u * r] = fdiv(acc[r], l); + barrier(); + for (uint gg = 0u; gg < HD / 128u; gg++) { + if (h < PERH && c < 32u) { + uint base = h * HD + gg * 128u + 4u * c; + vec4 v = vec4(ro[base], ro[base + 1u], ro[base + 2u], ro[base + 3u]); + v = tq_wht4(v, c, true); + ro[base] = v.x; ro[base + 1u] = v.y; ro[base + 2u] = v.z; ro[base + 3u] = v.w; + } + } + barrier(); + for (uint gg = 0u; gg < HD / 128u; gg++) { + uint base = gg * 128u + 4u * c; + for (uint j = 0u; j < 4u; j++) p.outp.v[o + base + j] = ro[h * HD + base + j]; + } + } else { + for (uint r = 0; r < HD / 32u; r++) p.outp.v[o + c + 32u * r] = fdiv(acc[r], l); + } +} diff --git a/src/vulkan/shaders/common.glsl b/src/vulkan/shaders/common.glsl index ad02be10..9657c03a 100644 --- a/src/vulkan/shaders/common.glsl +++ b/src/vulkan/shaders/common.glsl @@ -121,11 +121,13 @@ layout(constant_id = 0) const bool LLAMA_Q8 = false; // KV cache rows (one per position and KV head) hold hd f16 values (KV_MODE 0), hd int8 values followed by hd / 32 f16 scales // (KV_MODE 1, `--kv q8`), hd/2 packed uint4 nibbles + hd/32 f16 scales (KV_MODE 2, `--kv q4`), or affine 2-bit codes // (hd/4 B) + hd/32 f16 scales + hd/32 f16 mins (KV_MODE 3, `--kv q2`). Offsets below count values. -layout(constant_id = 15) const uint KV_MODE = 0u; +layout(constant_id = 15) const uint KV_MODE = 0u; // K cache: 0 f16, 1 q8, 2 q4, 3 q2, 4 turbo4, 5 turbo3, 6 turbo2 +layout(constant_id = 16) const uint VKV_MODE = 0u; // V cache: same encoding +#include "tq.glsl" // Store x at value offset e; with quantized KV the 32 lanes of the subgroup hold one 32-value block. -void kv_put(U16 c, uint e, uint hd, float x) { - if (KV_MODE == 0u) { c.v[e] = uint16_t(f2h(x)); return; } - if (KV_MODE == 3u) { +void kv_put(U16 c, uint e, uint hd, float x, uint mode) { + if (mode == 0u) { c.v[e] = uint16_t(f2h(x)); return; } + if (mode == 3u) { uint16_t mnh = uint16_t(f2h(warp_min(x))); float mn = float(uint16BitsToHalf(mnh)), mx = warp_max(x); float d_raw = rcp_d(max(0.0, mx - mn), 3.0); @@ -145,7 +147,7 @@ void kv_put(U16 c, uint e, uint hd, float x) { } return; } - if (KV_MODE == 2u) { + if (mode == 2u) { float d = rcp_d(warp_max(abs(x)), 7.0), y = d == 0.0 ? 0.0 : rcp_d(x, d), qf = trunc(y); if (abs(y - qf) >= 0.5) qf += sign(y); // roundf: halves away from zero uint nib = uint(clamp(int(qf), -7, 7) + 8); @@ -162,16 +164,16 @@ void kv_put(U16 c, uint e, uint hd, float x) { if (w % 32 == 0) c.v[(r + hd) / 2 + w / 32] = uint16_t(f2h(d)); } // The cache value at offset off. q8/q4/q2: dequantized and rounded once to f16, as ldkv in kernels.cu. -float ldkv(U16 c, uint off, uint hd) { - if (KV_MODE == 0u) return float(uint16BitsToHalf(c.v[off])); - if (KV_MODE == 3u) { +float ldkv(U16 c, uint off, uint hd, uint mode) { + if (mode == 0u) return float(uint16BitsToHalf(c.v[off])); + if (mode == 3u) { uint w = off % hd, r = off / hd * (3u * hd / 8u), b = uint(U8(uint64_t(c)).v[r + w / 4u]); float d = unpackHalf2x16(uint(c.v[(r + hd / 4u) / 2u + w / 32u])).x; float mn = unpackHalf2x16(uint(c.v[(r + hd / 4u + hd / 16u) / 2u + w / 32u])).x; uint q = (b >> (2u * (w & 3u))) & 3u; return rh(fma(float(q), d, mn)); } - if (KV_MODE == 2u) { + if (mode == 2u) { uint w = off % hd, r = off / hd * (hd / 2 + hd / 16), b = uint(U8(uint64_t(c)).v[r + w / 2]); float d = unpackHalf2x16(uint(c.v[(r + hd / 2) / 2 + w / 32])).x; int q = int((w & 1u) == 0u ? (b & 15u) : (b >> 4)) - 8; @@ -182,15 +184,15 @@ float ldkv(U16 c, uint off, uint hd) { return rh(float(int(uint(U8(uint64_t(c)).v[r + w]) << 24) >> 24) * d); } // q8/q4/q2 values off and off + 1 (off even) as one f16 pair word, from one load and one scale(+min). -uint ldkv2(U16 c, uint off, uint hd) { - if (KV_MODE == 3u) { +uint ldkv2(U16 c, uint off, uint hd, uint mode) { + if (mode == 3u) { uint w = off % hd, r = off / hd * (3u * hd / 8u), b = uint(U8(uint64_t(c)).v[r + w / 4u]); uint s = (b >> (2u * (w & 2u))) & 15u; float d = unpackHalf2x16(uint(c.v[(r + hd / 4u) / 2u + w / 32u])).x; float mn = unpackHalf2x16(uint(c.v[(r + hd / 4u + hd / 16u) / 2u + w / 32u])).x; return packHalf2x16(vec2(rh(fma(float(s & 3u), d, mn)), rh(fma(float(s >> 2), d, mn)))); } - if (KV_MODE == 2u) { + if (mode == 2u) { uint w = off % hd, r = off / hd * (hd / 2 + hd / 16), b = uint(U8(uint64_t(c)).v[r + w / 2]); float d = unpackHalf2x16(uint(c.v[(r + hd / 2) / 2 + w / 32])).x; return packHalf2x16(vec2(rh(float(int(b & 15u) - 8) * d), rh(float(int(b >> 4) - 8) * d))); @@ -200,8 +202,8 @@ uint ldkv2(U16 c, uint off, uint hd) { return packHalf2x16(vec2(rh(float(int(b << 24) >> 24) * d), rh(float(int(b << 16) >> 24) * d))); } // q8/q4/q2 values off .. off + 3 (off % 4 == 0) as two f16 pair words using packed FP16 arithmetic. -uvec2 ldkv4(U16 c, uint off, uint hd) { - if (KV_MODE == 3u) { +uvec2 ldkv4(U16 c, uint off, uint hd, uint mode) { + if (mode == 3u) { uint w = off % hd, r = off / hd * (3u * hd / 8u), b = uint(U8(uint64_t(c)).v[r + w / 4u]); precise f16vec2 d2 = f16vec2(uint16BitsToHalf(c.v[(r + hd / 4u) / 2u + w / 32u])); precise f16vec2 mn2 = f16vec2(uint16BitsToHalf(c.v[(r + hd / 4u + hd / 16u) / 2u + w / 32u])); @@ -210,7 +212,7 @@ uvec2 ldkv4(U16 c, uint off, uint hd) { precise f16vec2 z = fma(unpackFloat2x16((((b >> 4) & 3u) | ((b & 0xc0u) << 10)) | 0x64006400u) - m, d2, mn2); return uvec2(packFloat2x16(a), packFloat2x16(z)); } - if (KV_MODE == 2u) { + if (mode == 2u) { uint w = off % hd, r = off / hd * (hd / 2 + hd / 16), b = uint(c.v[(r + w / 2) / 2]); float16_t d = uint16BitsToHalf(c.v[(r + hd / 2) / 2 + w / 32]); precise f16vec2 m = f16vec2(1032.0hf); @@ -218,7 +220,7 @@ uvec2 ldkv4(U16 c, uint off, uint hd) { precise f16vec2 z = (unpackFloat2x16((((b >> 8) & 0x000Fu) | ((b & 0xF000u) << 4)) | 0x64006400u) - m) * d; return uvec2(packFloat2x16(a), packFloat2x16(z)); } - if (hd % 64 != 0) return uvec2(ldkv2(c, off, hd), ldkv2(c, off + 2, hd)); + if (hd % 64 != 0) return uvec2(ldkv2(c, off, hd, mode), ldkv2(c, off + 2, hd, mode)); uint w = off % hd, r = off / hd * (hd + hd / 16), b = U32(uint64_t(c)).v[(r + w) / 4]; // q + 128 as the low mantissa bits of 1024 gives the f16 1152 + q, so q comes out exact without int -> float // converts. The f16 product q * d is rounded once, as rh(float(q) * d). @@ -278,3 +280,22 @@ void quant_x(F32 x, uint xo, uint n, F32 w, float sc, F32 u, U32 q, uint qo, F32 if ((gl_LocalInvocationID.x & 3) == 0) d.v[do_ + i / 32] = dd; } } + +// Mode-dispatched entry points. The *_k / *_v wrappers keep the non-turbo half bit-identical in mixed layouts. +void kv_put_ex(U16 c, uint e, uint hd, float x, float norm, bool valid, uint mode, uint bits) { + if (mode >= 4u) { tq_put(c, e, hd, x, norm, valid, bits, ((e / hd) & 7u) * 8u + ((e % hd) >> 7u)); return; } + if (!valid) return; + kv_put(c, e, hd, x, mode); +} +void kv_put_k(U16 c, uint e, uint hd, float x) { kv_put_ex(c, e, hd, x, 1.0f, true, KV_MODE, TQ_KBITS); } +void kv_put_v(U16 c, uint e, uint hd, float x) { kv_put_ex(c, e, hd, x, 1.0f, true, VKV_MODE, TQ_VBITS); } +void kv_put_tq_which(U16 c, uint e, uint hd, float x, float norm, bool valid, uint which) { + uint m = which == 0u ? KV_MODE : VKV_MODE, b = which == 0u ? TQ_KBITS : TQ_VBITS; + kv_put_ex(c, e, hd, x, norm, valid, m, b); +} +float ldkv_k(U16 c, uint off, uint hd) { return KV_MODE >= 4u ? tq_ldkv(c, off, hd, TQ_KBITS) : ldkv(c, off, hd, KV_MODE); } +float ldkv_v(U16 c, uint off, uint hd) { return VKV_MODE >= 4u ? tq_ldkv(c, off, hd, TQ_VBITS) : ldkv(c, off, hd, VKV_MODE); } +uint ldkv2_k(U16 c, uint off, uint hd) { return KV_MODE >= 4u ? tq_ldkv2(c, off, hd, TQ_KBITS) : ldkv2(c, off, hd, KV_MODE); } +uint ldkv2_v(U16 c, uint off, uint hd) { return VKV_MODE >= 4u ? tq_ldkv2(c, off, hd, TQ_VBITS) : ldkv2(c, off, hd, VKV_MODE); } +uvec2 ldkv4_k(U16 c, uint off, uint hd) { return KV_MODE >= 4u ? tq_ldkv4(c, off, hd, TQ_KBITS) : ldkv4(c, off, hd, KV_MODE); } +uvec2 ldkv4_v(U16 c, uint off, uint hd) { return VKV_MODE >= 4u ? tq_ldkv4(c, off, hd, TQ_VBITS) : ldkv4(c, off, hd, VKV_MODE); } diff --git a/src/vulkan/shaders/conv_silu.comp b/src/vulkan/shaders/conv_silu.comp index 11874cb4..fb0769b8 100644 --- a/src/vulkan/shaders/conv_silu.comp +++ b/src/vulkan/shaders/conv_silu.comp @@ -1,20 +1,27 @@ #version 460 layout(local_size_x = 128) in; #include "common.glsl" +layout(buffer_reference, std430, buffer_reference_align = 8) buffer U64 { uint64_t v[]; }; // Causal depthwise conv over [state..., current] then SiLU; state keeps the last kw-1 inputs, oldest first. // Workgroup = 128 channels; the first nn workgroups are then l2-normalized as l2_norm does (the decode q and k heads). -layout(push_constant) uniform P { F32 qkv; F32 state; F32 w; F32 y; uint ch; uint kw; uint nn; float eps; } p; +// tab (not null): workgroup y is row y, at qkv and y + y * ch, with its state at tab[2y] (step_batch). +layout(push_constant) uniform P { F32 qkv; F32 state; F32 w; F32 y; uint ch; uint kw; uint nn; float eps; U64 tab; } p; void main() { uint c = gl_GlobalInvocationID.x, kw = p.kw, ch = p.ch; + F32 qkv = p.qkv, state = p.state, y = p.y; + if (uint64_t(p.tab) != 0) { + uint r = gl_WorkGroupID.y; + state = F32(p.tab.v[2 * r]); qkv = F32(uint64_t(p.qkv) + 4ul * r * ch); y = F32(uint64_t(p.y) + 4ul * r * ch); + } float v = 0.0; if (c < ch) { float acc = 0.0; - for (uint k = 0; k < kw - 1; k++) acc += p.state.v[k * ch + c] * p.w.v[c * kw + k]; - acc += p.qkv.v[c] * p.w.v[c * kw + kw - 1]; + for (uint k = 0; k < kw - 1; k++) acc += state.v[k * ch + c] * p.w.v[c * kw + k]; + acc += qkv.v[c] * p.w.v[c * kw + kw - 1]; v = silu(acc); - for (uint k = 0; k + 2 < kw; k++) p.state.v[k * ch + c] = p.state.v[(k + 1) * ch + c]; - p.state.v[(kw - 2) * ch + c] = p.qkv.v[c]; + for (uint k = 0; k + 2 < kw; k++) state.v[k * ch + c] = state.v[(k + 1) * ch + c]; + state.v[(kw - 2) * ch + c] = qkv.v[c]; } if (gl_WorkGroupID.x < p.nn) v *= fdiv(1.0, max(sqrt_(block_sum(v * v)), p.eps)); - if (c < ch) p.y.v[c] = v; + if (c < ch) y.v[c] = v; } diff --git a/src/vulkan/shaders/deltanet.comp b/src/vulkan/shaders/deltanet.comp index cffe4756..ef908599 100644 --- a/src/vulkan/shaders/deltanet.comp +++ b/src/vulkan/shaders/deltanet.comp @@ -2,32 +2,42 @@ layout(local_size_x = 256) in; #include "common.glsl" layout(buffer_reference, std430, buffer_reference_align = 16) buffer FV4 { vec4 v[]; }; +layout(buffer_reference, std430, buffer_reference_align = 8) buffer U64 { uint64_t v[]; }; // Gated DeltaNet scan over T tokens, as deltanet_seq in kernels.cu (see there). Workgroup (value head, row block): // state row j (dk floats) is held by L = dk / 16 lanes, 16 floats each (4-float chunks s, s + L, ...), so a // subgroup holds R = 32 / L rows. The state after each of the first min(nsnap, T - 1) tokens goes to snap. +// tab (not null): workgroup z is row z of one token, at token z's place in y, beta, g and o, with its state at +// tab[2z + 1] (step_batch). // With dtb set, beta and g are raw and get ssm_gates' gates here (dtb, ga as its dt_bias, a). -layout(push_constant) uniform P { F32 y; F32 S; F32 beta; F32 g; F32 o; F32 snap; F32 dtb; F32 ga; uint nk; uint nv; uint ilv; uint dk; +layout(push_constant) uniform P { F32 y; F32 S; F32 beta; F32 g; F32 o; F32 snap; F32 dtb; F32 ga; U64 tab; uint nk; uint nv; uint ilv; uint dk; uint dv; float scale; uint T; uint ych; uint nsnap; } p; layout(constant_id = 1) const uint SNAP_STRIDE = 1; +F32 Y, SS, BT, GG, OO; // Token tok's k and q (this lane's 4-float chunks), g, beta and v. void ld(uint tok, uint kh, uint vh, uint j, uint s, out vec4 k4[4], out vec4 q4[4], out float g, out float b, out float v) { uint dk = p.dk, L = dk >> 4, yt = tok * p.ych; // 16-byte aligned: ych and dk are multiples of 4 - bool need_q = uint64_t(p.o) != 0; + bool need_q = uint64_t(OO) != 0; [[unroll]] for (uint i = 0; i < 4; i++) { - k4[i] = FV4(uint64_t(p.y)).v[(yt + p.nk * dk + kh * dk) / 4 + s + L * i]; - q4[i] = need_q ? FV4(uint64_t(p.y)).v[(yt + kh * dk) / 4 + s + L * i] : vec4(0.0); + k4[i] = FV4(uint64_t(Y)).v[(yt + p.nk * dk + kh * dk) / 4 + s + L * i]; + q4[i] = need_q ? FV4(uint64_t(Y)).v[(yt + kh * dk) / 4 + s + L * i] : vec4(0.0); } - g = p.g.v[tok * p.nv + vh]; b = p.beta.v[tok * p.nv + vh]; v = p.y.v[yt + 2 * p.nk * dk + vh * p.dv + j]; + g = GG.v[tok * p.nv + vh]; b = BT.v[tok * p.nv + vh]; v = Y.v[yt + 2 * p.nk * dk + vh * p.dv + j]; if (uint64_t(p.dtb) != 0) { g = softplus(g + p.dtb.v[vh]) * p.ga.v[vh]; b = sigmoid(b); } } void main() { + Y = p.y; SS = p.S; BT = p.beta; GG = p.g; OO = p.o; + if (uint64_t(p.tab) != 0) { + uint z = gl_WorkGroupID.z; + SS = F32(p.tab.v[2 * z + 1]); Y = F32(uint64_t(p.y) + 4ul * z * p.ych); + BT = F32(uint64_t(p.beta) + 4ul * z * p.nv); GG = F32(uint64_t(p.g) + 4ul * z * p.nv); OO = F32(uint64_t(p.o) + 4ul * z * p.nv * p.dv); + } uint dk = p.dk, L = dk >> 4, R = 32 / L, lane = LANE, s = lane % L, vh = gl_WorkGroupID.x; uint kh = p.ilv != 0 ? vh / (p.nv / p.nk) : vh % p.nk; uint j0 = (gl_WorkGroupID.y * 8 + WARP) * R, j = j0 + lane / L; if (j0 >= p.dv) return; // whole subgroup past the end (R divides dv) uint row = (vh * p.dv + j) * dk, ns = min(p.nsnap, p.T - 1); precise float r[16]; - [[unroll]] for (uint i = 0; i < 4; i++) { vec4 t = FV4(uint64_t(p.S)).v[row / 4 + s + L * i]; [[unroll]] for (uint e = 0; e < 4; e++) r[4 * i + e] = t[e]; } + [[unroll]] for (uint i = 0; i < 4; i++) { vec4 t = FV4(uint64_t(SS)).v[row / 4 + s + L * i]; [[unroll]] for (uint e = 0; e < 4; e++) r[4 * i + e] = t[e]; } // Token inputs do not depend on the state: token tok + 1's are loaded while token tok computes. vec4 nk4[4], nq4[4]; float ng, nb, nvv; @@ -40,15 +50,15 @@ void main() { [[unroll]] for (uint e = 0; e < 16; e++) { r[e] *= decay; sk = fma(r[e], kk[e], sk); } [[unroll]] for (uint off = L >> 1; off > 0; off >>= 1) sk += subgroupShuffleXor(sk, off); float d = bt * (vt - sk); - if (uint64_t(p.o) != 0) { + if (uint64_t(OO) != 0) { [[unroll]] for (uint e = 0; e < 16; e++) { r[e] = fma(d, kk[e], r[e]); oq = fma(r[e], qv[e], oq); } [[unroll]] for (uint off = L >> 1; off > 0; off >>= 1) oq += subgroupShuffleXor(oq, off); - if (s == 0) p.o.v[tok * p.nv * p.dv + vh * p.dv + j] = oq * p.scale; + if (s == 0) OO.v[tok * p.nv * p.dv + vh * p.dv + j] = oq * p.scale; } else { [[unroll]] for (uint e = 0; e < 16; e++) r[e] = fma(d, kk[e], r[e]); } if ((tok % SNAP_STRIDE) == 0u && tok + 1 < p.T && (tok / SNAP_STRIDE) < p.nsnap) [[unroll]] for (uint i = 0; i < 4; i++) FV4(uint64_t(p.snap)).v[((tok / SNAP_STRIDE) * p.nv * p.dv * dk + row) / 4 + s + L * i] = vec4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); } - [[unroll]] for (uint i = 0; i < 4; i++) FV4(uint64_t(p.S)).v[row / 4 + s + L * i] = vec4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + [[unroll]] for (uint i = 0; i < 4; i++) FV4(uint64_t(SS)).v[row / 4 + s + L * i] = vec4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); } diff --git a/src/vulkan/shaders/deq.glsl b/src/vulkan/shaders/deq.glsl index ff616a86..74116be7 100644 --- a/src/vulkan/shaders/deq.glsl +++ b/src/vulkan/shaders/deq.glsl @@ -54,9 +54,15 @@ float f8_e4m3_to_f32(uint x) { // Bytes of a row of `cols` values (a multiple of the type's block). uint rowb(uint cols) { return cols * SBB / 256; } int sb(uint x) { return int(x << 24) >> 24; } // the low byte, signed -const uint TQ_POW3[5] = uint[5](1u, 3u, 9u, 27u, 81u); +// 3^n, n < 5, with no table (an array indexed by a runtime n may go to local memory). +uint tq_pow3(uint n) { return n == 4u ? 81u : (0x1B090301u >> (8u * n)) & 255u; } // TQ1_0 trit n of byte v: v * 3^n in u8, then (3 q) >> 8, minus 1 (llama.cpp dequantize_row_tq1_0). -int tq1_trit(uint v, uint n) { uint q = (v * TQ_POW3[n]) & 255u; return int((q * 3u) >> 8) - 1; } +int tq1_trit(uint v, uint n) { uint q = (v * tq_pow3(n)) & 255u; return int((q * 3u) >> 8) - 1; } +// Trit n of each byte of w (p = 3^n) as a byte 0..2, two bytes at a time in 16-bit lanes. +uint trit4(uint w, uint p) { + uint a = ((w & 0x00ff00ffu) * p) & 0x00ff00ffu, c = (((w >> 8) & 0x00ff00ffu) * p) & 0x00ff00ffu; + return (((a * 3u) >> 8) & 0x00030003u) | ((((c * 3u) >> 8) & 0x00030003u) << 8); +} // IQ1_M (T 29) or IQ1_S (19) sub-block l of block ib: grid index, scale and the sign of the 1/8 offset. void iq1_sub(U8 w, uint b, uint ib, uint l, out uint idx, out float dl, out bool neg) { @@ -272,6 +278,16 @@ void qi8(U8 w, uint b, uint sub, out int q[8], out float d, out float m) { uint r = e - 240; [[unroll]] for (uint i = 0; i < 8; i++) { uint li = r + i; q[i] = tq1_trit(u8_(w, b + 48 + (li & 3)), li >> 2); } } + } else if (T == 143) { // PTQ1_0, 2 blocks of 28: qs[24] five trits a byte, qh[2] four, f16 d at 26 + uint p = b + 28 * (sub >> 4), e = (sub & 15) * 8; + d = ldh(w, p + 26); + if (e < 120) { + uint n = e < 80 ? e >> 4 : (e - 80) >> 3, o = p + (e < 80 ? (e & 15) : 16), pw = tq_pow3(n); + uint lo = trit4(ld32(w, o), pw), hi = trit4(ld32(w, o + 4), pw); + [[unroll]] for (uint i = 0; i < 8; i++) q[i] = int(((i < 4 ? lo : hi) >> (8 * (i & 3))) & 3u) - 1; + } else { + [[unroll]] for (uint i = 0; i < 8; i++) q[i] = tq1_trit(u8_(w, p + 24 + (i & 1)), i >> 1); + } } else if (T == 35) { // TQ2_0: 64 bytes of 2-bit codes, f16 d at 64; value (code - 1) d uint e = sub * 8, j = e >> 7, l = (e >> 5) & 3, m = e & 31; d = ldh(w, b + 64); diff --git a/src/vulkan/shaders/gemm_f.glsl b/src/vulkan/shaders/gemm_f.glsl index 181ae120..dcce1b58 100644 --- a/src/vulkan/shaders/gemm_f.glsl +++ b/src/vulkan/shaders/gemm_f.glsl @@ -92,6 +92,10 @@ void main() { [[unroll]] for (uint q = 0; q < XM / 16; q++) { uint r = (tid >> 4) + 16 * q; vec4 v = xb[q] != ~0u ? p.x.v[xb[q] + kb * BK / 4] : vec4(0.0); +#if !COOP + // gemm_f_dp: x past the f16 range is clamped, not made inf (inf * 0 in the products would be NaN). + v = clamp(v, vec4(-65504.0), vec4(65504.0)); +#endif xs[r * PW + xc / 2] = h2(v.x, v.y); xs[r * PW + xc / 2 + 1] = h2(v.z, v.w); } barrier(); diff --git a/src/vulkan/shaders/gemm_red.comp b/src/vulkan/shaders/gemm_red.comp new file mode 100644 index 00000000..720724dc --- /dev/null +++ b/src/vulkan/shaders/gemm_red.comp @@ -0,0 +1,15 @@ +#version 460 +layout(local_size_x = 256) in; +#include "common.glsl" +// The ks split-K slices of a batched gemmi (s: [ks][nd][rows], each already times the weight scale) summed in slice +// order into y (row stride ys), with act as gemm_f. +layout(push_constant) uniform P { F32 s; F32 y; uint rows; uint nd; uint ys; uint ks; uint act; } p; +void main() { + uint i = gl_GlobalInvocationID.x; + if (i >= p.rows * p.nd) return; + uint m = i / p.rows, n = i % p.rows; + float v = 0.0; + for (uint z = 0; z < p.ks; z++) v += p.s.v[(z * p.nd + m) * p.rows + n]; + uint o = m * p.ys + n; + p.y.v[o] = p.act == 0 ? v : p.act == 1 ? silu(p.y.v[o]) * v : p.y.v[o] + v; +} diff --git a/src/vulkan/shaders/gemmi.glsl b/src/vulkan/shaders/gemmi.glsl index db78f5d7..4ddac115 100644 --- a/src/vulkan/shaders/gemmi.glsl +++ b/src/vulkan/shaders/gemmi.glsl @@ -27,9 +27,10 @@ layout(push_constant) uniform P { U64 tiles; uint64_t wd; U32 x; I32 xrow; F32 y #ifndef COOP_K #define COOP_K 32 #endif -// SM 1 (gemmi_s): only the tiles of at most 32 positions, as gemm_fs; X holds XM positions. -const uint BM = 128, XM = SM != 0 ? 32 : BM; -const uint KS = T == 42 || T == 34 || T == 35 || T == 2 || T == 3 || T == 6 || T == 7 || T == 8 || T == 12 || T == 13 || T == 16 || T == 19 || T == 18 || T == 21 || T == 23 ? 32 : 16; +// SM 1 (gemmi_s): only the tiles of at most 32 positions, as gemm_fs; X holds XM positions. SM 2 (gemmi_s2, batched +// decode): 64 positions, each subgroup 16 positions by 32 rows, so a 64-row batch decodes each weight once. +const uint BM = 128, XM = SM == 1 ? 32 : SM == 2 ? 64 : BM; +const uint KS = T == 42 || T == 34 || T == 143 || T == 35 || T == 2 || T == 3 || T == 6 || T == 7 || T == 8 || T == 12 || T == 13 || T == 16 || T == 19 || T == 18 || T == 21 || T == 23 ? 32 : 16; // Rows in words. On NVIDIA (COOP_K 32), KS = 16 pads each 16 weights with 16 zeros (PW = 36). // On RDNA 3/3.5 (COOP_K 16), 16x16x16 coopmat consumes KS = 16 directly without padding (PW = 20). const uint PX = 20, PW = (COOP != 0 && COOP_K == 16) || KS == 32 ? 20 : 36; @@ -107,7 +108,7 @@ void main() { // most expert tiles) only the 16 x 16 at bm, bn, in acc[0][0], so the 8 output tiles are spread over all 8 // subgroups. Each output sums the same products in the same order either way. const bool sm = SM != 0; - uint bm = sm ? 16 * (w & 1) : (w >> 1) * 32, bn = sm ? 16 * (w >> 1) : (w & 1) * 32; + uint bm = SM == 2 ? 16 * (w & 3) : sm ? 16 * (w & 1) : (w >> 1) * 32, bn = SM == 2 ? 32 * (w >> 2) : sm ? 16 * (w >> 1) : (w & 1) * 32; // nv: the layout of mma.sync (element i at row g + 8 (i >> 2), column 2 t + (i & 1) + 8 ((i >> 1) & 1)), as on NVIDIA. uint g = LANE >> 2, t = LANE & 3; #if COOP @@ -128,19 +129,27 @@ void main() { // W: invocation decodes the 16 weights (subs 2 wi, 2 wi + 1 of the step) of row wr. uint wr = tid >> 2, wi = tid & 3; bool wok = n0 + wr < p.rows; + // Split K (gemmi_s in batched decode, z = segment): this workgroup sums K steps k0 .. k1 into its own y slice. + // Only SM: the same code in gemmi cost a third of its prefill speed. +#if SM + uint nkl = (p.nk + gl_NumWorkGroups.z - 1) / gl_NumWorkGroups.z, k0 = gl_WorkGroupID.z * nkl, k1 = min(p.nk, k0 + nkl), kz = gl_WorkGroupID.z; +#else + const uint k0 = 0, kz = 0; + uint k1 = p.nk; +#endif precise float acc[2][2][8]; [[unroll]] for (uint a = 0; a < 2; a++) for (uint b = 0; b < 2; b++) for (uint i = 0; i < 8; i++) acc[a][b][i] = 0.0; // W step kb is decoded into registers during step kb - 1's products and stored after them, as kernels.cu. uvec4 wv; float d, m; - ldw(wt, wr, wi, wok, n0, 0, wv, d, m); - if (xr < XM) ldx(xr, xh, xok, xo, cols, 0, 0); + ldw(wt, wr, wi, wok, n0, k0, wv, d, m); + if (xr < XM) ldx(xr, xh, xok, xo, cols, k0, 0); [[unroll]] for (uint j = 0; j < 4; j++) wq[wr * PW + wi * WS + j] = wv[j]; wsc[0][wr][wi] = d; wmn[0][wr][wi] = m; - for (uint kb = 0; kb < p.nk; kb++) { - uint xb = kb & 1; + for (uint kb = k0; kb < k1; kb++) { + uint xb = (kb - k0) & 1; barrier(); - if (kb + 1 < p.nk && xr < XM) ldx(xr, xh, xok, xo, cols, kb + 1, xb ^ 1); - if (kb + 1 < p.nk) ldw(wt, wr, wi, wok, n0, kb + 1, wv, d, m); + if (kb + 1 < k1 && xr < XM) ldx(xr, xh, xok, xo, cols, kb + 1, xb ^ 1); + if (kb + 1 < k1) ldw(wt, wr, wi, wok, n0, kb + 1, wv, d, m); // Expert tiles are often part full; a subgroup whose 32 positions are all past cnt has nothing to multiply. if (bm < cnt) [[unroll]] for (uint h = 0; h < 64 / KS; h++) { @@ -148,19 +157,19 @@ void main() { #if COOP_K == 16 coopmat a0[2], a1[2]; coopmat b0[2], b1[2]; - [[unroll]] for (uint i = 0; i < 2; i++) if (!sm || i == 0) { - coopMatLoad(a0[i], xq, (xb * XM + bm + 16 * i) * PX + h * (KS / 4), PX, gl_CooperativeMatrixLayoutRowMajor); + [[unroll]] for (uint i = 0; i < 2; i++) if (!sm || i == 0 || SM == 2) { + if (!sm || i == 0) coopMatLoad(a0[i], xq, (xb * XM + bm + 16 * i) * PX + h * (KS / 4), PX, gl_CooperativeMatrixLayoutRowMajor); coopMatLoad(b0[i], wq, (xb * 64 + bn + 16 * i) * PW + h * (KS / 4), PW, gl_CooperativeMatrixLayoutColumnMajor); if (KS == 32) { - coopMatLoad(a1[i], xq, (xb * XM + bm + 16 * i) * PX + h * 8 + 4, PX, gl_CooperativeMatrixLayoutRowMajor); + if (!sm || i == 0) coopMatLoad(a1[i], xq, (xb * XM + bm + 16 * i) * PX + h * 8 + 4, PX, gl_CooperativeMatrixLayoutRowMajor); coopMatLoad(b1[i], wq, (xb * 64 + bn + 16 * i) * PW + h * 8 + 4, PW, gl_CooperativeMatrixLayoutColumnMajor); } } #else coopmat a[2]; coopmat b[2]; - [[unroll]] for (uint i = 0; i < 2; i++) if (!sm || i == 0) { - coopMatLoad(a[i], xq, (xb * XM + bm + 16 * i) * PX + h * KS / 4, PX, gl_CooperativeMatrixLayoutRowMajor); + [[unroll]] for (uint i = 0; i < 2; i++) if (!sm || i == 0 || SM == 2) { + if (!sm || i == 0) coopMatLoad(a[i], xq, (xb * XM + bm + 16 * i) * PX + h * KS / 4, PX, gl_CooperativeMatrixLayoutRowMajor); coopMatLoad(b[i], wq, (xb * 64 + bn + 16 * i) * PW + h * 8, PW, gl_CooperativeMatrixLayoutColumnMajor); } #endif @@ -168,7 +177,7 @@ void main() { // NVIDIA layout: a lane's scales are those of 2 rows per mt and 4 columns per nt, loaded once per h. float da[2][2], sa[2][2], db[2][4], mb[2][4]; if (nv) { - [[unroll]] for (uint mt = 0; mt < 2; mt++) + [[unroll]] for (uint mt = 0; mt < 2; mt++) if (!sm || mt == 0) [[unroll]] for (uint e = 0; e < 2; e++) { uint r = bm + 16 * mt + g + 8 * e; da[mt][e] = xd[xb][r][h * KS / 32]; @@ -182,7 +191,7 @@ void main() { } } [[unroll]] for (uint mt = 0; mt < 2; mt++) - [[unroll]] for (uint nt = 0; nt < 2; nt++) if (!sm || mt + nt == 0) { + [[unroll]] for (uint nt = 0; nt < 2; nt++) if (!sm || mt == 0 && (nt == 0 || SM == 2)) { #if COOP #if COOP_K == 16 IACC c = coopMatMulAdd(a0[mt], b0[nt], IACC(I2F_BIAS)); @@ -218,17 +227,17 @@ void main() { #endif } } - if (kb + 1 < p.nk) { + if (kb + 1 < k1) { [[unroll]] for (uint j = 0; j < 4; j++) wq[((xb ^ 1) * 64 + wr) * PW + wi * WS + j] = wv[j]; wsc[xb ^ 1][wr][wi] = d; wmn[xb ^ 1][wr][wi] = m; } } [[unroll]] for (uint mt = 0; mt < 2; mt++) [[unroll]] for (uint nt = 0; nt < 2; nt++) - [[unroll]] for (uint i = 0; i < NE; i++) if (!sm || mt + nt == 0) { + [[unroll]] for (uint i = 0; i < NE; i++) if (!sm || mt == 0 && (nt == 0 || SM == 2)) { uint r = bm + 16 * mt + RI(i), n = n0 + bn + 16 * nt + CI(i); if (r >= cnt || n >= p.rows) continue; - uint o = (m0 + r) * p.ys + n; + uint o = (kz * p.nd + m0 + r) * p.ys + n; float v = acc[mt][nt][i] * p.sc; p.y.v[o] = p.act == 0 ? v : p.act == 1 ? silu(p.y.v[o]) * v : p.y.v[o] + v; } diff --git a/src/vulkan/shaders/gemmi_s2.comp b/src/vulkan/shaders/gemmi_s2.comp new file mode 100644 index 00000000..65dad72d --- /dev/null +++ b/src/vulkan/shaders/gemmi_s2.comp @@ -0,0 +1,4 @@ +#version 460 +#define COOP 1 +#define SM 2 +#include "gemmi.glsl" diff --git a/src/vulkan/shaders/gemmi_s2_16.comp b/src/vulkan/shaders/gemmi_s2_16.comp new file mode 100644 index 00000000..42ee99a9 --- /dev/null +++ b/src/vulkan/shaders/gemmi_s2_16.comp @@ -0,0 +1,5 @@ +#version 460 +#define COOP 1 +#define COOP_K 16 +#define SM 2 +#include "gemmi.glsl" diff --git a/src/vulkan/shaders/hadamard.comp b/src/vulkan/shaders/hadamard.comp index ae65ebc1..bf13f896 100644 --- a/src/vulkan/shaders/hadamard.comp +++ b/src/vulkan/shaders/hadamard.comp @@ -1,27 +1,33 @@ #version 460 -// Gyro files (config::Hadamard; CUDA hadamard): row gl_WorkGroupID.y of n floats at x (times silu(x) * u first when u -// is not null) becomes H (s x) / sqrt(BS) per BS values, written to o, which may be x. s: the n signs of a row as -// floats. One workgroup per block of BS values (specialization constant 1, a power of two). +// config::Hadamard (CUDA hadamard): row gl_WorkGroupID.y of n floats at x (times silu(x) * u first when u is not +// null) becomes H (s x) / sqrt(BS) per BS values, written to o. s: the n signs of a row as floats. With perm (n +// indices), value c of a row is x[perm[c]] of that row and o must not be x; otherwise o may be x. One workgroup of WG +// invocations per block of BS values (specialization constants 1 and 2; BS a power of two, at most 4096). layout(constant_id = 1) const uint BS = 128; -layout(local_size_x_id = 1) in; +layout(constant_id = 2) const uint WG = 128; +layout(local_size_x_id = 2) in; #include "common.glsl" -layout(push_constant) uniform P { F32 x; F32 u; F32 s; F32 o; uint n; float scale; } p; -shared float sh[2 * BS]; +layout(push_constant) uniform P { F32 x; F32 u; F32 s; U32 perm; F32 o; uint n; float scale; } p; +shared float sh[BS]; void main() { - uint j = gl_LocalInvocationID.x, c = gl_WorkGroupID.x * BS + j, i = gl_WorkGroupID.y * p.n + c; - float v = p.x.v[i]; - if (uint64_t(p.u) != 0) v = silu(v) * p.u.v[i]; - v *= p.s.v[c]; - // The fast Walsh-Hadamard transform in natural order; the two halves of sh alternate, so a step never reads - // what the same step writes. - uint b = 0; + uint r = gl_WorkGroupID.y * p.n, c0 = gl_WorkGroupID.x * BS; + for (uint j = gl_LocalInvocationID.x; j < BS; j += WG) { + uint c = c0 + j; + float v = p.x.v[r + (uint64_t(p.perm) != 0 ? p.perm.v[c] : c)]; + if (uint64_t(p.u) != 0) v = silu(v) * p.u.v[r + c]; + sh[j] = v * p.s.v[c]; + } + barrier(); + // The fast Walsh-Hadamard transform in natural order, in place: a stage's pairs are disjoint. for (uint len = 1; len < BS; len <<= 1) { - sh[b + j] = v; + for (uint q = gl_LocalInvocationID.x; q < BS / 2; q += WG) { + uint a = q / len * 2 * len + q % len; + float va = sh[a], vb = sh[a + len]; + sh[a] = va + vb; + sh[a + len] = va - vb; + } barrier(); - float w = sh[b + (j ^ len)]; - v = (j & len) != 0 ? w - v : v + w; - b ^= BS; } - p.o.v[i] = v * p.scale; + for (uint j = gl_LocalInvocationID.x; j < BS; j += WG) p.o.v[r + c0 + j] = sh[j] * p.scale; } diff --git a/src/vulkan/shaders/ink_attn.comp b/src/vulkan/shaders/ink_attn.comp index 9f66cf02..b31b39d2 100644 --- a/src/vulkan/shaders/ink_attn.comp +++ b/src/vulkan/shaders/ink_attn.comp @@ -9,6 +9,7 @@ layout(push_constant) uniform P { F32 q; F32 r; F32 sink; U16 k; U16 v; F32 bias shared float qs[128]; shared float ps[64]; shared float acc[128]; +shared float tro[128]; void main() { uint h = gl_WorkGroupID.x, kh = h / (p.nh / p.nkv), kw = p.nkv * p.hd, t = gl_LocalInvocationID.x; uint rows = p.rows, at = p.at; @@ -20,13 +21,29 @@ void main() { uint i0 = gl_WorkGroupID.y * 64, n = i0 < rows ? min(64u, rows - i0) : 0u; if (t < p.hd) qs[t] = p.q.v[h * p.hd + t]; barrier(); + if (TQ_K) { + for (uint g = 0u; g < p.hd / 128u; g++) { + if (t < 32u) { + uint base = g * 128u + 4u * t; + vec4 qv = vec4(qs[base], qs[base + 1u], qs[base + 2u], qs[base + 3u]); + qv = tq_wht4(qv, t, false); + qs[base] = qv.x; qs[base + 1u] = qv.y; qs[base + 2u] = qv.z; qs[base + 3u] = qv.w; + } + } + if (p.hd == 64u && t < 32u) { + vec2 qv = vec2(qs[2u * t], qs[2u * t + 1u]); + qv = tq_wht2(qv, t, false); + qs[2u * t] = qv.x; qs[2u * t + 1u] = qv.y; + } + barrier(); + } float scale = fdiv(1.0, sqrt_(float(p.hd))); for (uint j = WARP; j < 64; j += 4) { uint i = i0 + j, dist = at >= i ? at - i : at + rows - i; float d = 0.0; if (j < n) { uint ko = i * kw + kh * p.hd; - for (uint c = LANE; c < p.hd; c += 32) d += qs[c] * ldkv(p.k, ko + c, p.hd); + for (uint c = LANE; c < p.hd; c += 32) d += qs[c] * ldkv_k(p.k, ko + c, p.hd); d *= scale; if (dist < p.ext) for (uint c = LANE; c < p.nr; c += 32) d += p.r.v[h * p.nr + c] * p.bias.v[dist * p.nr + c]; } @@ -41,11 +58,31 @@ void main() { barrier(); uint c = t % p.hd, parts = 128 / p.hd; float a = 0.0; - for (uint j = t / p.hd; j < n; j += parts) a += ps[j] * ldkv(p.v, (i0 + j) * kw + kh * p.hd + c, p.hd); + for (uint j = t / p.hd; j < n; j += parts) a += ps[j] * ldkv_v(p.v, (i0 + j) * kw + kh * p.hd + c, p.hd); acc[t] = a; barrier(); uint o = (h * gl_NumWorkGroups.y + gl_WorkGroupID.y) * (p.hd + 2); - if (t < p.hd) { + if (TQ_V) { + float s = 0.0; + if (t < p.hd) for (uint j = 0; j < parts; j++) s += acc[j * p.hd + t]; + tro[t] = s; + barrier(); + for (uint g = 0u; g < p.hd / 128u; g++) { + if (t < 32u) { + uint base = g * 128u + 4u * t; + vec4 av = vec4(tro[base], tro[base + 1u], tro[base + 2u], tro[base + 3u]); + av = tq_wht4(av, t, true); + tro[base] = av.x; tro[base + 1u] = av.y; tro[base + 2u] = av.z; tro[base + 3u] = av.w; + } + } + if (p.hd == 64u && t < 32u) { + vec2 av = vec2(tro[2u * t], tro[2u * t + 1u]); + av = tq_wht2(av, t, true); + tro[2u * t] = av.x; tro[2u * t + 1u] = av.y; + } + barrier(); + if (t < p.hd) p.sc.v[o + 2 + t] = tro[t]; + } else if (t < p.hd) { float s = 0.0; for (uint j = 0; j < parts; j++) s += acc[j * p.hd + t]; p.sc.v[o + 2 + t] = s; diff --git a/src/vulkan/shaders/ink_attn_prefill.comp b/src/vulkan/shaders/ink_attn_prefill.comp index a212e3e3..b4ef36c1 100644 --- a/src/vulkan/shaders/ink_attn_prefill.comp +++ b/src/vulkan/shaders/ink_attn_prefill.comp @@ -10,6 +10,9 @@ layout(constant_id = 1) const uint PER = 4; // head_dim / 32 // Inkling 2 causal prefill attention with online softmax + virtual sink logit 0. // When kc_new != 0 and kp >= pos (SWA chunk prefill without overwriting history < pos), reads kp - pos from kc_new/vc_new. // One warp per query token (4 queries per workgroup x, head h = workgroup y). +// The legacy cache keeps main's lane + 32*j layout; a turbo half uses the contiguous WHT layout. +uint kidx(uint j, uint lane) { if (K_MODE >= 4u) return PER == 2u ? 2u * lane + (j & 1u) : (j >> 2u) * 128u + 4u * lane + (j & 3u); return lane + 32u * j; } +uint vidx(uint j, uint lane) { if (V_MODE >= 4u) return PER == 2u ? 2u * lane + (j & 1u) : (j >> 2u) * 128u + 4u * lane + (j & 3u); return lane + 32u * j; } void main() { uint t = gl_WorkGroupID.x * 4u + WARP, h = gl_WorkGroupID.y, lane = LANE; if (t >= p.nt) return; @@ -20,9 +23,17 @@ void main() { float scale = fdiv(1.0, sqrt_(float(HD))); float q[PER], acc[PER]; [[unroll]] for (uint j = 0; j < PER; j++) { - q[j] = p.q.v[(t * p.nh + h) * HD + lane + 32u * j] * scale; + q[j] = p.q.v[(t * p.nh + h) * HD + kidx(j, lane)] * scale; acc[j] = 0.0; } + if (TQ_K) { + for (uint g = 0u; g < PER / 4u; g++) { + vec4 qv = vec4(q[4u * g], q[4u * g + 1u], q[4u * g + 2u], q[4u * g + 3u]); + qv = tq_wht4(qv, lane, false); + q[4u * g] = qv.x; q[4u * g + 1u] = qv.y; q[4u * g + 2u] = qv.z; q[4u * g + 3u] = qv.w; + } + if (PER == 2u) { vec2 qv = vec2(q[0], q[1]); qv = tq_wht2(qv, lane, false); q[0] = qv.x; q[1] = qv.y; } + } float sink_val = p.sink.v[t * p.nh + h]; float r_reg = (p.nr <= 32u && lane < p.nr) ? p.r.v[(t * p.nh + h) * p.nr + lane] : 0.0; // Virtual sink has logit 0 and value 0 -> m = 0, l = 1. @@ -34,7 +45,7 @@ void main() { uint row = use_new ? (kp - p.pos) : (p.win > 0u ? (kp % p.ring) : kp); uint kbase = row * kw + kh * HD; float s = 0.0; - [[unroll]] for (uint j = 0; j < PER; j++) s += q[j] * ldkv(kbuf, kbase + lane + 32u * j, HD); + [[unroll]] for (uint j = 0; j < PER; j++) s += q[j] * ldkv_k(kbuf, kbase + kidx(j, lane), HD); s = W64 ? warp_sum(s) : subgroupAdd(s); uint dist = q_pos - kp; float b = 0.0; @@ -49,13 +60,23 @@ void main() { float logit = s + b - sink_val; float mn = max(m, logit), c = expf_(m - mn), e = expf_(logit - mn); l = fma(l, c, e); - [[unroll]] for (uint j = 0; j < PER; j++) acc[j] = fma(e, ldkv(vbuf, kbase + lane + 32u * j, HD), acc[j] * c); + [[unroll]] for (uint j = 0; j < PER; j++) acc[j] = fma(e, ldkv_v(vbuf, kbase + vidx(j, lane), HD), acc[j] * c); m = mn; } float inv = fdiv(1.0, l); + float ov[PER]; + [[unroll]] for (uint j = 0; j < PER; j++) ov[j] = acc[j] * inv; + if (TQ_V) { + for (uint g = 0u; g < PER / 4u; g++) { + vec4 vv = vec4(ov[4u * g], ov[4u * g + 1u], ov[4u * g + 2u], ov[4u * g + 3u]); + vv = tq_wht4(vv, lane, true); + ov[4u * g] = vv.x; ov[4u * g + 1u] = vv.y; ov[4u * g + 2u] = vv.z; ov[4u * g + 3u] = vv.w; + } + if (PER == 2u) { vec2 vv = vec2(ov[0], ov[1]); vv = tq_wht2(vv, lane, true); ov[0] = vv.x; ov[1] = vv.y; } + } [[unroll]] for (uint j = 0; j < PER; j++) { - uint col = lane + 32u * j; + uint col = vidx(j, lane); uint idx = (t * p.nh + h) * HD + col; - p.outp.v[idx] = acc[j] * inv * sigmoid(p.gate.v[idx]); + p.outp.v[idx] = ov[j] * sigmoid(p.gate.v[idx]); } } diff --git a/src/vulkan/shaders/ink_clip.comp b/src/vulkan/shaders/ink_clip.comp index 64d1657c..b87aa41e 100644 --- a/src/vulkan/shaders/ink_clip.comp +++ b/src/vulkan/shaders/ink_clip.comp @@ -5,12 +5,12 @@ layout(push_constant) uniform P { F32 x; F32 scale; U16 dst; I32 pos_ptr; uint w; float thr; float eps; float mul; uint dst_at0; uint dst_ring; - uint pos0; float log_alpha; float log_floor; + uint pos0; float log_alpha; float log_floor; uint which; } p; -// Workgroup (row, tok): rows of w values (w at most 128, multiple of 32 when KV_MODE > 0 and dst != 0). -// scale is shared across tokens: [gl_NumWorkGroups.x][w]. dst writes KV row (dst_at0 + tok) % dst_ring via kv_put. -// When pos_ptr != 0, pos0 = uint(pos_ptr.v[0]) and dst_at0 = pos0 % dst_ring. +// Workgroup (row, tok): rows of w values (w at most 128, multiple of 32 when a quantized KV half stores them). +// `which` selects the K (0) or V (1) cache format when dst writes KV row (dst_at0 + tok) % dst_ring. +shared float tq[128]; void main() { uint t = gl_LocalInvocationID.x; uint row = gl_WorkGroupID.x, tok = gl_WorkGroupID.y, rows = gl_NumWorkGroups.x; @@ -26,13 +26,26 @@ void main() { float mul = p.mul; if (p.log_alpha != 0.0) mul *= 1.0 + p.log_alpha * log(max(fdiv(float(pos0 + tok + 1u), p.log_floor), 1.0)); float f = (p.thr > 0.0 ? min(fdiv(p.thr, sqrt_(ss) + 1e-6), 1.0) : fdiv(1.0, sqrt_(fdiv(ss, float(p.w)) + p.eps))) * mul; - if (t < p.w) { - v *= f; - p.x.v[at] = v; - } - if (uint64_t(p.dst) != 0 && t < p.w) { + if (t < p.w) { v *= f; p.x.v[at] = v; } + if (uint64_t(p.dst) != 0) { + tq[t] = t < p.w ? v : 0.0; + barrier(); + uint mode = p.which == 0u ? KV_MODE : VKV_MODE; + if (mode >= 4u) { + if (p.w == 128u && t < 32u) { + vec4 a = vec4(tq[4u * t], tq[4u * t + 1u], tq[4u * t + 2u], tq[4u * t + 3u]); + a = tq_wht4(a, t, false); + tq[4u * t] = a.x; tq[4u * t + 1u] = a.y; tq[4u * t + 2u] = a.z; tq[4u * t + 3u] = a.w; + } else if (p.w == 64u && t < 32u) { + vec2 a = vec2(tq[2u * t], tq[2u * t + 1u]); + a = tq_wht2(a, t, false); + tq[2u * t] = a.x; tq[2u * t + 1u] = a.y; + } + barrier(); + } + // All 128 invocations call the store so every WHT group's reduction slots are written, even at w = 64. uint dst_pos = (dst_at0 + tok) % p.dst_ring; uint dat = (dst_pos * rows + row) * p.w + t; - kv_put(p.dst, dat, p.w, v); + kv_put_tq_which(p.dst, dat, p.w, mode >= 4u ? tq[t] : v, sqrt_(ss) * f, t < p.w, p.which); } } diff --git a/src/vulkan/shaders/kv_store.comp b/src/vulkan/shaders/kv_store.comp index 931e11d2..c592c2a6 100644 --- a/src/vulkan/shaders/kv_store.comp +++ b/src/vulkan/shaders/kv_store.comp @@ -3,7 +3,36 @@ layout(local_size_x = 256) in; #include "common.glsl" // Store `total` values (consecutive tokens of n each, heads of hd) of k and v into the caches from position step[0]. layout(push_constant) uniform P { F32 k; F32 v; U16 kc; U16 vc; I32 step; uint n; uint total; uint hd; } p; +shared float kq[128], vq[128]; +// A 128-value WHT group is gathered as 4*lane+j so all five butterfly stages stay inside one warp. +void rotate(inout float s[128], uint gbase, uint lane, bool inv) { + vec4 a = vec4(s[gbase + 4u * lane], s[gbase + 4u * lane + 1u], s[gbase + 4u * lane + 2u], s[gbase + 4u * lane + 3u]); + a = tq_wht4(a, lane, inv); + s[gbase + 4u * lane] = a.x; s[gbase + 4u * lane + 1u] = a.y; + s[gbase + 4u * lane + 2u] = a.z; s[gbase + 4u * lane + 3u] = a.w; +} void main() { - uint i = gl_GlobalInvocationID.x, e = uint(p.step.v[0]) * p.n + i; - if (i < p.total) { kv_put(p.kc, e, p.hd, p.k.v[i]); kv_put(p.vc, e, p.hd, p.v.v[i]); } + uint tid = gl_LocalInvocationID.x, i = gl_WorkGroupID.x * 256u + tid; + uint e = uint(p.step.v[0]) * p.n + i; + bool valid = i < p.total; + float kv = valid ? p.k.v[i] : 0.0, vv = valid ? p.v.v[i] : 0.0; + kq[tid] = kv; vq[tid] = vv; + barrier(); + if (TQ_K || TQ_V) { + uint lane = tid & 31u, gbase = (tid >> 7u) * 128u; + if ((tid & 127u) < 32u) { + if (TQ_K) rotate(kq, gbase, lane, false); + if (TQ_V) rotate(vq, gbase, lane, false); + } + barrier(); + } + uint slot = ((e / p.hd) & 7u) * 8u + ((e % p.hd) >> 7u); + float krot = TQ_K ? kq[tid] : kv, vrot = TQ_V ? vq[tid] : vv; + float sk = 1.0, sv = 1.0; + if (TQ_K) sk = sqrt_(tq_group_reduce(krot * krot, slot)); + if (TQ_V) sv = sqrt_(tq_group_reduce(vrot * vrot, slot)); + if (valid) { + kv_put_ex(p.kc, e, p.hd, krot, sk, true, KV_MODE, TQ_KBITS); + kv_put_ex(p.vc, e, p.hd, vrot, sv, true, VKV_MODE, TQ_VBITS); + } } diff --git a/src/vulkan/shaders/rms_norm.comp b/src/vulkan/shaders/rms_norm.comp index 9c98d5e0..e422e0c1 100644 --- a/src/vulkan/shaders/rms_norm.comp +++ b/src/vulkan/shaders/rms_norm.comp @@ -3,9 +3,19 @@ layout(local_size_x = 256) in; #include "common.glsl" // Workgroup = row. out[r] = rmsnorm(x[r]) * w; with q not null, out is also quantized as quant_xq does. With step not // null, out is then rotated as rope_neox does (row r = a head of token r / per). With res not null, x += res first. -// With kc not null, out and v (rows of n) are then stored as kv_store does. +// With kc not null, out and v (rows of n) are then stored as kv_store does. With kvt not null (step_batch), token +// r / per is a row of its own sequence at position step[2 (r / per)], and with v not null it stores into the caches +// at kvt[2 (r / per)] and kvt[2 (r / per) + 1]. +layout(buffer_reference, std430, buffer_reference_align = 8) buffer U64 { uint64_t v[]; }; layout(push_constant) uniform P { F32 x; F32 w; F32 o; U32 q; uint xs; uint os; uint n; float eps; I32 step; double ts; uint per; uint n_rot; F32 res; - F32 v; U16 kc; U16 vc; } p; + F32 v; U16 kc; U16 vc; U64 kvt; } p; +shared float tqk[512], tqv[512]; +void rotate(inout float s[512], uint base, uint lane, bool inv) { + vec4 a = vec4(s[base + 4u * lane], s[base + 4u * lane + 1u], s[base + 4u * lane + 2u], s[base + 4u * lane + 3u]); + a = tq_wht4(a, lane, inv); + s[base + 4u * lane] = a.x; s[base + 4u * lane + 1u] = a.y; + s[base + 4u * lane + 2u] = a.z; s[base + 4u * lane + 3u] = a.w; +} void main() { uint r = gl_WorkGroupID.x, xo = r * p.xs, oo = r * p.os, h = 0; float s = 0.0; @@ -30,7 +40,7 @@ void main() { float sc = fdiv(1.0, sqrt_(fdiv(block_sum(s), float(p.n)) + p.eps)); if (uint64_t(p.step) != 0) { h = p.n_rot / 2; - double pos = double(p.step.v[0] + int(r / p.per)); + double pos = double(uint64_t(p.kvt) != 0 ? p.step.v[2 * (r / p.per)] : p.step.v[0] + int(r / p.per)); for (uint i = gl_LocalInvocationID.x; i < h; i += 256) { float sn, cs, a = p.x.v[xo + i] * sc * p.w.v[i], b = p.x.v[xo + i + h] * sc * p.w.v[i + h]; rope_cs(pos, p.ts, i, sn, cs); @@ -50,13 +60,29 @@ void main() { } for (; i < p.n; i += 256) p.o.v[oo + i] = p.x.v[xo + i] * sc * p.w.v[i]; } - if (uint64_t(p.kc) != 0) { + bool rows = uint64_t(p.kvt) != 0; + if (uint64_t(p.kc) != 0 || (rows && uint64_t(p.v) != 0)) { memoryBarrierBuffer(); barrier(); - uint e = (uint(p.step.v[0]) * p.per + r) * p.n; + uint tok = r / p.per, e = rows ? (uint(p.step.v[2 * tok]) * p.per + r % p.per) * p.n : (uint(p.step.v[0]) * p.per + r) * p.n; + U16 kc = rows ? U16(p.kvt.v[2 * tok]) : p.kc, vc = rows ? U16(p.kvt.v[2 * tok + 1]) : p.vc; + for (i = gl_LocalInvocationID.x; i < p.n; i += 256) { tqk[i] = p.o.v[oo + i]; tqv[i] = p.v.v[r * p.n + i]; } + barrier(); + if (TQ_K || TQ_V) { + uint g = gl_LocalInvocationID.x >> 5u, lane = gl_LocalInvocationID.x & 31u; + if (g < p.n / 128u) { + if (TQ_K) rotate(tqk, g * 128u, lane, false); + if (TQ_V) rotate(tqv, g * 128u, lane, false); + } + barrier(); + } for (i = gl_LocalInvocationID.x; i < p.n; i += 256) { - kv_put(p.kc, e + i, p.n, p.o.v[oo + i]); - kv_put(p.vc, e + i, p.n, p.v.v[r * p.n + i]); + float ko = TQ_K ? tqk[i] : p.o.v[oo + i], vo = TQ_V ? tqv[i] : p.v.v[r * p.n + i]; + uint slot = (r & 7u) * 8u + ((i / p.n) >> 7u); + float sk = TQ_K ? sqrt_(tq_group_reduce(ko * ko, slot)) : 1.0; + float sv = TQ_V ? sqrt_(tq_group_reduce(vo * vo, slot)) : 1.0; + kv_put_ex(kc, e + i, p.n, ko, sk, true, KV_MODE, TQ_KBITS); + kv_put_ex(vc, e + i, p.n, vo, sv, true, VKV_MODE, TQ_VBITS); } - } +} } diff --git a/src/vulkan/shaders/swiglu_clamp.comp b/src/vulkan/shaders/swiglu_clamp.comp new file mode 100644 index 00000000..a4777fc8 --- /dev/null +++ b/src/vulkan/shaders/swiglu_clamp.comp @@ -0,0 +1,10 @@ +#version 460 +layout(local_size_x = 256) in; +#include "common.glsl" +layout(push_constant) uniform P { F32 g; F32 u; uint n; float lim; } p; + +// g = silu(min(g, lim)) * clamp(u, -lim, lim). +void main() { + uint i = gl_GlobalInvocationID.x; + if (i < p.n) p.g.v[i] = silu(min(p.g.v[i], p.lim)) * clamp(p.u.v[i], -p.lim, p.lim); +} diff --git a/src/vulkan/shaders/tq.glsl b/src/vulkan/shaders/tq.glsl new file mode 100644 index 00000000..ae8ab110 --- /dev/null +++ b/src/vulkan/shaders/tq.glsl @@ -0,0 +1,142 @@ +// TurboQuant KV helpers, mirroring src/cuda/kernels.cu (TheTom's llama-cpp-turboquant design). +// Included from common.glsl after the K/V mode constants. K/V stay WHT-rotated in the cache; Q is rotated in +// attention and only the attention output is inverse-rotated. +const uint K_MODE = KV_MODE; +const uint V_MODE = VKV_MODE; +const bool TQ_K = KV_MODE >= 4u; +const bool TQ_V = VKV_MODE >= 4u; +const uint TQ_KBITS = KV_MODE == 5u ? 3u : (KV_MODE == 6u ? 2u : 4u); +const uint TQ_VBITS = VKV_MODE == 5u ? 3u : (VKV_MODE == 6u ? 2u : 4u); + +float tq_flip(float x, uint b) { return uintBitsToFloat(floatBitsToUint(x) ^ (b << 31)); } + +uint tq_sw(uint lane, bool inv) { + uint i = lane >> 3u; + if (inv) return i == 0u ? 0x16ACEE90u : i == 1u ? 0x3F628FDCu : i == 2u ? 0xB7A5357Au : 0xBEA56562u; + return i == 0u ? 0xE46A0359u : i == 1u ? 0x42F85949u : i == 2u ? 0xA4C63BBBu : 0x49F250A9u; +} +uint tq_sw64(uint lane, bool inv) { + uint w = (2u * lane) & 31u; + uint i = lane >> 4u; + return inv ? (i == 0u ? 0x16ACEE90u : 0x3F628FDCu) : (i == 0u ? 0xE46A0359u : 0x42F85949u); +} + +// v.xyzw are dims 4 * lane .. 4 * lane + 3. All five butterfly stages are inside one logical 32-lane warp. +vec4 tq_wht4(vec4 vin, uint lane, bool inv) { + precise vec4 v = vin; + uint a = (tq_sw(lane, inv) >> (4u * (lane & 7u))) & 15u; + v.x = tq_flip(v.x, a & 1u); v.y = tq_flip(v.y, (a >> 1u) & 1u); + v.z = tq_flip(v.z, (a >> 2u) & 1u); v.w = tq_flip(v.w, (a >> 3u) & 1u); + { precise float x = v.x, y = v.y; v.x = x + y; v.y = x - y; + precise float z = v.z, w = v.w; v.z = z + w; v.w = z - w; } + { precise float x = v.x, z = v.z; v.x = x + z; v.z = x - z; + precise float y = v.y, w = v.w; v.y = y + w; v.w = y - w; } + [[unroll]] for (uint m = 1u; m <= 16u; m <<= 1u) { + precise vec4 p = vec4(subgroupShuffleXor(v.x, m), subgroupShuffleXor(v.y, m), + subgroupShuffleXor(v.z, m), subgroupShuffleXor(v.w, m)); + bool hi = (lane & m) != 0u; + v = hi ? p - v : v + p; + } + uint b = (tq_sw(lane, !inv) >> (4u * (lane & 7u))) & 15u; + v *= 0.08838834764831845; // 1 / sqrt(128) + v.x = tq_flip(v.x, b & 1u); v.y = tq_flip(v.y, (b >> 1u) & 1u); + v.z = tq_flip(v.z, (b >> 2u) & 1u); v.w = tq_flip(v.w, (b >> 3u) & 1u); + return v; +} + +// hd == 64 (Inkling only): v.xy are dims 2 * lane and 2 * lane + 1. +vec2 tq_wht2(vec2 vin, uint lane, bool inv) { + precise vec2 v = vin; + uint a = (tq_sw64(lane, inv) >> ((2u * lane) & 31u)) & 3u; + v.x = tq_flip(v.x, a & 1u); v.y = tq_flip(v.y, (a >> 1u) & 1u); + { precise float x = v.x, y = v.y; v.x = x + y; v.y = x - y; } + [[unroll]] for (uint m = 1u; m <= 16u; m <<= 1u) { + precise vec2 p = vec2(subgroupShuffleXor(v.x, m), subgroupShuffleXor(v.y, m)); + bool hi = (lane & m) != 0u; + v = hi ? p - v : v + p; + } + uint b = (tq_sw64(lane, !inv) >> ((2u * lane) & 31u)) & 3u; + v *= 0.125; // 1 / sqrt(64) + v.x = tq_flip(v.x, b & 1u); v.y = tq_flip(v.y, (b >> 1u) & 1u); + return v; +} + +// Lloyd-Max midpoints and centroids for N(0, 1 / 128); the comparisons are the same as CUDA tq_nearest. +int tq_q4(float v) { + int q = 0; + q += int(v >= -0.212203); q += int(v >= -0.162947); q += int(v >= -0.127026); + q += int(v >= -0.097164); q += int(v >= -0.070671); q += int(v >= -0.046174); + q += int(v >= -0.022824); q += int(v >= 0.0); + q += int(v >= 0.022824); q += int(v >= 0.046174); q += int(v >= 0.070671); + q += int(v >= 0.097164); q += int(v >= 0.127026); q += int(v >= 0.162947); + q += int(v >= 0.212203); + return q; +} +int tq_q3(float v) { + int q = 0; + q += int(v >= -0.154496); q += int(v >= -0.092804); q += int(v >= -0.044243); + q += int(v >= 0.0); q += int(v >= 0.044243); q += int(v >= 0.092804); q += int(v >= 0.154496); + return q; +} +int tq_q2(float v) { + int q = int(v >= -0.086728) + int(v >= 0.0) + int(v >= 0.086728); + return q; +} +float tq_mag4(uint k) { + return k == 0u ? 0.011349 : k == 1u ? 0.034299 : k == 2u ? 0.058050 : k == 3u ? 0.083292 : + k == 4u ? 0.111036 : k == 5u ? 0.143016 : k == 6u ? 0.182877 : 0.241529; +} +float tq_mag3(uint k) { + return k == 0u ? 0.021663 : k == 1u ? 0.066822 : k == 2u ? 0.118786 : 0.190207; +} +float tq_c4(int q) { bool p = q >= 8; float m = tq_mag4(p ? uint(q - 8) : uint(7 - q)); return p ? m : -m; } +float tq_c3(int q) { bool p = q >= 4; float m = tq_mag3(p ? uint(q - 4) : uint(3 - q)); return p ? m : -m; } +float tq_c2(int q) { bool p = q >= 2; float m = p ? 0.133462 : 0.039994; return p ? m : -m; } +int tq_nearest(uint bits, float v) { return bits == 3u ? tq_q3(v) : bits == 2u ? tq_q2(v) : tq_q4(v); } +float tq_centroid(uint bits, int q) { return bits == 3u ? tq_c3(q) : bits == 2u ? tq_c2(q) : tq_c4(q); } + +shared float tq_red[(TQ_K || TQ_V) ? 256u : 1u]; +// Per-128-group sum, in the same butterfly order as CUDA tq_group_sum. `slot` must be unique per (row, group) +// within the workgroup; every invocation of that group calls this with the same slot. +float tq_group_reduce(float cs, uint slot) { + float v = warp_sum(cs); + uint lane = LANE, w = (gl_LocalInvocationID.x & 127u) >> 5u; + if (lane < 4u) tq_red[4u * slot + lane] = 0.0; + barrier(); + if (lane == 0u) tq_red[4u * slot + w] = v; + barrier(); + float t = lane < 4u ? tq_red[4u * slot + lane] : 0.0; + barrier(); + return warp_sum(t); +} +// Store one rotated, quantized value. Active lanes join the reduction; inactive ones contribute no energy and write nothing. +void tq_put(U16 c, uint e, uint hd, float x, float norm, bool valid, uint bits, uint slot) { + int q = tq_nearest(bits, fdiv(x, norm)); + uint nib = uint(q), pair = nib | (subgroupShuffleXor(nib, 1u) << 4); + uint we = e % hd, g = we >> 7u, w = we & 127u; + uint r = e / hd * (hd / 2u + hd / 16u); + if (valid && (we & 1u) == 0u) U8(uint64_t(c)).v[r + we / 2u] = uint8_t(pair); + float cen = tq_centroid(bits, q); + float recon = sqrt_(tq_group_reduce(valid ? cen * cen : 0.0, slot)); + if (valid && w == 0u) + c.v[(r + hd / 2u) / 2u + g] = uint16_t(f2h(fdiv(norm, max(recon, 1e-6)))); +} +float tq_ldkv(U16 c, uint off, uint hd, uint bits) { + uint we = off % hd, r = off / hd * (hd / 2u + hd / 16u); + float norm = float(uint16BitsToHalf(c.v[(r + hd / 2u) / 2u + (we >> 7u)])); + uint b = uint(U8(uint64_t(c)).v[r + we / 2u]); + int q = int((we & 1u) == 0u ? b & 15u : b >> 4); + return rh(tq_centroid(bits, q) * norm); +} +uint tq_ldkv2(U16 c, uint off, uint hd, uint bits) { + uint a0 = off % hd, r = off / hd * (hd / 2u + hd / 16u); + float n0 = float(uint16BitsToHalf(c.v[(r + hd / 2u) / 2u + (a0 >> 7u)])); + uint b = uint(U8(uint64_t(c)).v[r + a0 / 2u]); + uint lo = f2h(tq_centroid(bits, int(b & 15u)) * n0); + uint a1 = (off + 1u) % hd; + float n1 = float(uint16BitsToHalf(c.v[(r + hd / 2u) / 2u + (a1 >> 7u)])); + return lo | (f2h(tq_centroid(bits, int(b >> 4)) * n1) << 16); +} +uvec2 tq_ldkv4(U16 c, uint off, uint hd, uint bits) { + return uvec2(tq_ldkv2(c, off, hd, bits), tq_ldkv2(c, off + 2u, hd, bits)); +} diff --git a/src/vulkan/shaders/vit_attn.comp b/src/vulkan/shaders/vit_attn.comp new file mode 100644 index 00000000..61b34c9d --- /dev/null +++ b/src/vulkan/shaders/vit_attn.comp @@ -0,0 +1,67 @@ +#version 460 +layout(constant_id = 1) const uint HD = 72; // head_dim, at most 128 +layout(local_size_x = 128) in; +#include "common.glsl" +layout(push_constant) uniform P { F32 q; F32 k; F32 v; F32 outp; uint n; uint nh; float scale; } p; + +// Attention of a vision encoder (vit_attn of kernels.cu): every query row sees all n keys, no mask; q, k, v and out +// are f32 [n][nh][HD]. A workgroup takes 32 query rows of head gl_WorkGroupID.y (8 a warp) and walks the keys 32 at +// a time through shared memory, one key a lane, with an online softmax. The 8 rows of a warp share each K and V load; +// each lane keeps its own part of the softmax sum until the end. A key row takes HD + 1 floats so the 32 lanes, each +// on its own key, hit 32 banks. +shared float qs[32 * HD], vs[32 * HD], ks[32 * (HD + 1)], ps[4 * 256]; +void main() { + uint h = gl_WorkGroupID.y, q0 = gl_WorkGroupID.x * 32u, lane = LANE, w = WARP, tid = gl_LocalInvocationID.x; + uint n = p.n, ld = p.nh * HD; + for (uint i = tid; i < 32u * HD; i += 128u) { + uint r = i / HD, d = i - r * HD; + qs[i] = q0 + r < n ? p.q.v[(q0 + r) * ld + h * HD + d] * p.scale : 0.0; + } + float ninf = uintBitsToFloat(0xff800000u); + float m[8], l[8], o[8][4]; + [[unroll]] for (uint r = 0u; r < 8u; r++) { + m[r] = ninf; l[r] = 0.0; + [[unroll]] for (uint c = 0u; c < 4u; c++) o[r][c] = 0.0; + } + for (uint k0 = 0u; k0 < n; k0 += 32u) { + barrier(); + for (uint i = tid; i < 32u * HD; i += 128u) { + uint r = i / HD, d = i - r * HD, g = (k0 + r) * ld + h * HD + d; + bool inr = k0 + r < n; + ks[r * (HD + 1u) + d] = inr ? p.k.v[g] : 0.0; + vs[i] = inr ? p.v.v[g] : 0.0; + } + barrier(); + bool valid = k0 + lane < n; + float s[8]; + [[unroll]] for (uint r = 0u; r < 8u; r++) s[r] = 0.0; + for (uint d = 0u; d < HD; d++) { + float kd = ks[lane * (HD + 1u) + d]; + [[unroll]] for (uint r = 0u; r < 8u; r++) s[r] = fma(qs[(w * 8u + r) * HD + d], kd, s[r]); + } + [[unroll]] for (uint r = 0u; r < 8u; r++) { + // The first tile always holds key 0, so mn is finite from then on and corr is 0 on the first tile. + float mn = max(m[r], warp_max(valid ? s[r] : ninf)); + float e = valid ? expf_(s[r] - mn) : 0.0; + float corr = m[r] == ninf ? 0.0 : expf_(m[r] - mn); + l[r] = l[r] * corr + e; + m[r] = mn; + [[unroll]] for (uint c = 0u; c < 4u; c++) o[r][c] *= corr; + ps[w * 256u + r * 32u + lane] = e; + } + barrier(); + for (uint j = 0u; j < 32u; j++) { + [[unroll]] for (uint c = 0u; c < 4u; c++) { + if (lane + 32u * c >= HD) continue; + float vv = vs[j * HD + lane + 32u * c]; + [[unroll]] for (uint r = 0u; r < 8u; r++) o[r][c] = fma(ps[w * 256u + r * 32u + j], vv, o[r][c]); + } + } + } + [[unroll]] for (uint r = 0u; r < 8u; r++) { + uint t = q0 + w * 8u + r; + float lt = warp_sum(l[r]); + if (t >= n) continue; + [[unroll]] for (uint c = 0u; c < 4u; c++) if (lane + 32u * c < HD) p.outp.v[t * ld + h * HD + lane + 32u * c] = fdiv(o[r][c], lt); + } +} diff --git a/src/vulkan/shaders/vit_attn_cm.comp b/src/vulkan/shaders/vit_attn_cm.comp new file mode 100644 index 00000000..15b36f82 --- /dev/null +++ b/src/vulkan/shaders/vit_attn_cm.comp @@ -0,0 +1,178 @@ +#version 460 +// vit_attn on cooperative matrices (vit_attn_tc of kernels.cu): flash attention over f16 copies of q, k and v with +// f32 scores, softmax and output, as attn_prefill.glsl but with no mask (only the keys past n) and the head padded +// to HP = 80 by zero columns. q, k, v and out are f32 [n][nh][hd], hd % 8 == 0 and hd <= HP. Workgroup (x, h): +// queries 64x .. 64x + 63 of head h; subgroup w owns queries 16w .. 16w + 15 and walks the keys 32 at a time. +#extension GL_KHR_cooperative_matrix : require +#extension GL_KHR_memory_scope_semantics : require +#extension GL_KHR_shader_subgroup_vote : require +#extension GL_EXT_control_flow_attributes : require +layout(local_size_x = 128) in; +#include "common.glsl" +layout(buffer_reference, std430, buffer_reference_align = 16) buffer FV4 { vec4 v[]; }; +layout(push_constant) uniform P { F32 q; F32 k; F32 v; F32 o; uint n; uint nh; uint hd; float scale; } p; +#define HP 80 +// PQ: tile rows in uvec4 (8 halves). +const uint BQ = 64, BK = 32, PQ = HP / 8 + 1, PP = BK + 8; +#define ACC coopmat +// The Q tile at the start, then the K and V tiles of each key block (BQ = 2 * BK rows either way). +shared uvec4 kvs[BQ * PQ]; +shared float ss[4 * 16 * BK]; // scores of each subgroup; at the start the row and column index matrices +shared float16_t ps[4 * 16 * PP]; // softmax weights of each subgroup +shared float rs[4 * 16]; // per row: the rescale factor, at the end the sum l + +// Rows r0 .. r0 + 63 of x (head h) as halves at kvs[base ..], times mul; zeros past n and past hd. +void load(F32 x, uint r0, uint base, float mul) { + uint tid = gl_LocalInvocationID.x; + for (uint i = tid; i < BQ * (HP / 8); i += 128) { + uint r = i / (HP / 8), c = i % (HP / 8), o = ((r0 + r) * p.nh * p.hd + gl_WorkGroupID.y * p.hd) / 4 + 2 * c; + uvec4 u = uvec4(0); + if (r0 + r < p.n && 8 * c < p.hd) { + [[unroll]] for (uint j = 0; j < 2; j++) { + vec4 v = FV4(uint64_t(x)).v[o + j] * mul; + u[2 * j] = packFloat2x16(f16vec2(v.xy)); + u[2 * j + 1] = packFloat2x16(f16vec2(v.zw)); + } + } + kvs[base + r * PQ + c] = u; + } +} + +void main() { + uint q0 = gl_WorkGroupID.x * BQ, h = gl_WorkGroupID.y, ld = p.nh * p.hd; + uint tid = gl_LocalInvocationID.x, w = WARP, lane = LANE, g = lane >> 2, t4 = lane & 3; + float ninf = uintBitsToFloat(0xff800000u); + load(p.q, q0, 0, p.scale); + for (uint i = tid; i < 256; i += 128) { + ss[i] = float(i / 16); ss[256 + i] = float(i % 16); + ps[i] = float16_t(i / 16); ps[256 + i] = float16_t(i % 16); + } + barrier(); + // The (row, col) of this lane's accumulator elements (see attn_prefill.glsl): nv when they are mma.sync's. + uint r_pack = 0u, c_pack = 0u; + bool nv; + { + ACC ri, ci; + coopMatLoad(ri, ss, 0, 16, gl_CooperativeMatrixLayoutRowMajor); + coopMatLoad(ci, ss, 256, 16, gl_CooperativeMatrixLayoutRowMajor); + nv = ri.length() == 8; + [[unroll]] for (uint i = 0; i < ri.length(); i++) { + uint rv = uint(ri[i]), cv = uint(ci[i]); + nv = nv && rv == g + 8 * (i >> 2) && cv == 2 * t4 + (i & 1) + 8 * ((i >> 1) & 1); + r_pack |= (rv & 15u) << (4u * i); + c_pack |= (cv & 15u) << (4u * i); + } + nv = subgroupAll(nv); + } + bool nva; + { + coopmat ra, ca; + coopMatLoad(ra, ps, 0, 16, gl_CooperativeMatrixLayoutRowMajor); + coopMatLoad(ca, ps, 256, 16, gl_CooperativeMatrixLayoutRowMajor); + nva = nv && ra.length() == 8; + [[unroll]] for (uint i = 0; i < ra.length(); i++) nva = nva && uint(ra[i]) == g + 8 * ((i >> 1) & 1) && uint(ca[i]) == 2 * t4 + (i & 1) + 8 * (i >> 2); + nva = subgroupAll(nva); + } + barrier(); // ps is rewritten below + coopmat qa[HP / 16]; + [[unroll]] for (uint kk = 0; kk < HP / 16; kk++) coopMatLoad(qa[kk], kvs, w * 16 * PQ + kk * 2, PQ, gl_CooperativeMatrixLayoutRowMajor); + ACC acc[HP / 16]; + [[unroll]] for (uint d = 0; d < HP / 16; d++) acc[d] = ACC(0.0); + float m[2] = {ninf, ninf}; + precise float l[2] = {0.0, 0.0}; + uint sb = w * 16 * BK, pb = w * 16 * PP, rb = w * 16; + for (uint k0 = 0; k0 < p.n; k0 += BK) { + barrier(); + // K rows k0 .. k0 + 31 at kvs[0 ..], the same V rows at kvs[BK * PQ ..]. + for (uint i = tid; i < 2 * BK * (HP / 8); i += 128) { + uint r = i / (HP / 8), c = i % (HP / 8), kr = k0 + r % BK; + uint o = (kr * ld + h * p.hd) / 4 + 2 * c; + F32 x = r < BK ? p.k : p.v; + uvec4 u = uvec4(0); + if (kr < p.n && 8 * c < p.hd) { + [[unroll]] for (uint j = 0; j < 2; j++) { + vec4 v = FV4(uint64_t(x)).v[o + j]; + u[2 * j] = packFloat2x16(f16vec2(v.xy)); + u[2 * j + 1] = packFloat2x16(f16vec2(v.zw)); + } + } + kvs[r * PQ + c] = u; + } + barrier(); + ACC s0 = ACC(0.0), s1 = ACC(0.0); + [[unroll]] for (uint kk = 0; kk < HP / 16; kk++) { + coopmat b0, b1; + coopMatLoad(b0, kvs, kk * 2, PQ, gl_CooperativeMatrixLayoutColumnMajor); + coopMatLoad(b1, kvs, 16 * PQ + kk * 2, PQ, gl_CooperativeMatrixLayoutColumnMajor); + s0 = coopMatMulAdd(qa[kk], b0, s0); + s1 = coopMatMulAdd(qa[kk], b1, s1); + } + // CUDA's lane holds s[nt][e]: row g + 8 (e >> 1), key nt * 8 + 2 t4 + (e & 1). + float s[4][4], mx[2] = {m[0], m[1]}, c[2]; + if (nv) { + [[unroll]] for (uint i = 0; i < 8; i++) { + uint nt = (i >> 1) & 1, e = (i & 1) + 2 * (i >> 2); + s[nt][e] = s0[i]; + s[nt + 2][e] = s1[i]; + } + } else { + coopMatStore(s0, ss, sb, BK, gl_CooperativeMatrixLayoutRowMajor); + coopMatStore(s1, ss, sb + 16, BK, gl_CooperativeMatrixLayoutRowMajor); + subgroupMemoryBarrierShared(); + subgroupBarrier(); + [[unroll]] for (uint nt = 0; nt < 4; nt++) + [[unroll]] for (uint e = 0; e < 4; e++) s[nt][e] = ss[sb + (g + 8 * (e >> 1)) * BK + nt * 8 + 2 * t4 + (e & 1)]; + } + [[unroll]] for (uint nt = 0; nt < 4; nt++) + [[unroll]] for (uint e = 0; e < 4; e++) { + if (k0 + nt * 8 + 2 * t4 + (e & 1) >= p.n) s[nt][e] = ninf; + mx[e >> 1] = max(mx[e >> 1], s[nt][e]); + } + [[unroll]] for (uint r = 0; r < 2; r++) { + // Key k0 < n is in every tile, so mx is finite; c is 0 on the first tile (m = -inf). + mx[r] = max(mx[r], subgroupShuffleXor(mx[r], 1)); + mx[r] = max(mx[r], subgroupShuffleXor(mx[r], 2)); + c[r] = expf_(m[r] - mx[r]); + m[r] = mx[r]; + } + [[unroll]] for (uint nt = 0; nt < 4; nt++) + [[unroll]] for (uint e = 0; e < 4; e++) { + uint r = e >> 1; + float pe = expf_(s[nt][e] - mx[r]); + l[r] = nt == 0 && (e & 1) == 0 ? fma(l[r], c[r], pe) : l[r] + pe; + s[nt][e] = pe; + if (!nva) ps[pb + (g + 8 * r) * PP + nt * 8 + 2 * t4 + (e & 1)] = float16_t(pe); + } + if (!nva) { + if (!nv && t4 == 0) { rs[rb + g] = c[0]; rs[rb + g + 8] = c[1]; } + subgroupMemoryBarrierShared(); + subgroupBarrier(); + } + [[unroll]] for (uint d = 0; d < HP / 16; d++) + [[unroll]] for (uint i = 0; i < acc[d].length(); i++) acc[d][i] *= nv ? c[i >> 2] : rs[rb + ((r_pack >> (4u * i)) & 15u)]; + [[unroll]] for (uint kb = 0; kb < BK / 16; kb++) { + coopmat pa; + if (nva) { + [[unroll]] for (uint i = 0; i < 8; i++) pa[i] = float16_t(s[2 * kb + (i >> 2)][i & 3]); + } else coopMatLoad(pa, ps, pb + kb * 16, PP, gl_CooperativeMatrixLayoutRowMajor); + [[unroll]] for (uint d = 0; d < HP / 16; d++) { + coopmat vb; + coopMatLoad(vb, kvs, (BK + kb * 16) * PQ + d * 2, PQ, gl_CooperativeMatrixLayoutRowMajor); + acc[d] = coopMatMulAdd(pa, vb, acc[d]); + } + } + } + [[unroll]] for (uint r = 0; r < 2; r++) { + l[r] += subgroupShuffleXor(l[r], 1); + l[r] += subgroupShuffleXor(l[r], 2); + } + subgroupBarrier(); + if (t4 == 0) { rs[rb + g] = l[0]; rs[rb + g + 8] = l[1]; } + subgroupMemoryBarrierShared(); + subgroupBarrier(); + [[unroll]] for (uint d = 0; d < HP / 16; d++) + [[unroll]] for (uint i = 0; i < acc[d].length(); i++) { + uint row = (r_pack >> (4u * i)) & 15u, col = d * 16 + ((c_pack >> (4u * i)) & 15u), t = q0 + w * 16 + row; + if (t < p.n && col < p.hd) p.o.v[t * ld + h * p.hd + col] = fdiv(acc[d][i], rs[rb + row]); + } +} diff --git a/src/vulkan/shaders/vit_bias.comp b/src/vulkan/shaders/vit_bias.comp new file mode 100644 index 00000000..b01b02b3 --- /dev/null +++ b/src/vulkan/shaders/vit_bias.comp @@ -0,0 +1,21 @@ +#version 460 +layout(local_size_x = 256) in; +#include "common.glsl" +layout(push_constant) uniform P { F32 y; F32 bias; uint stride; uint cols; int act; } p; + +// y[r][c] = act(y[r][c] + bias[c]) for row r = workgroup y. act: 0 none, 1 GELU (tanh), 2 GELU (erf, +// Abramowitz-Stegun 7.1.26 as the CPU encoder), 3 quick GELU, 4 SiLU. +void main() { + uint c = gl_GlobalInvocationID.x; + if (c >= p.cols) return; + uint i = gl_WorkGroupID.y * p.stride + c; + float x = p.y.v[i] + p.bias.v[c]; + if (p.act == 1) x = 0.5 * x * (1.0 + tanh(0.79788456 * x * (1.0 + 0.044715 * x * x))); + else if (p.act == 2) { + float z = x * 0.70710678, t = fdiv(1.0, 1.0 + 0.3275911 * abs(z)); + float e = 1.0 - (((((1.0614054 * t - 1.4531521) * t) + 1.4214138) * t - 0.28449672) * t + 0.2548296) * t * expf_(-z * z); + x = 0.5 * x * (1.0 + (z >= 0.0 ? e : -e)); + } else if (p.act == 3) x = fdiv(x, 1.0 + expf_(-1.702 * x)); + else if (p.act == 4) x = silu(x); + p.y.v[i] = x; +} diff --git a/src/vulkan/shaders/vit_norm.comp b/src/vulkan/shaders/vit_norm.comp new file mode 100644 index 00000000..5a2a6ad0 --- /dev/null +++ b/src/vulkan/shaders/vit_norm.comp @@ -0,0 +1,15 @@ +#version 460 +layout(local_size_x = 256) in; +#include "common.glsl" +layout(push_constant) uniform P { F32 x; F32 o; F32 w; F32 b; uint n; float eps; } p; + +// Vision encoder layer norm with bias, workgroup = row: o = (x - mean) / sqrt(var + eps) * w + b. +void main() { + uint xo = gl_WorkGroupID.x * p.n; + float s = 0.0; + for (uint i = gl_LocalInvocationID.x; i < p.n; i += 256) s += p.x.v[xo + i]; + float mean = fdiv(block_sum(s), float(p.n)), v = 0.0; + for (uint i = gl_LocalInvocationID.x; i < p.n; i += 256) { float d = p.x.v[xo + i] - mean; v += d * d; } + float inv = fdiv(1.0, sqrt_(fdiv(block_sum(v), float(p.n)) + p.eps)); + for (uint i = gl_LocalInvocationID.x; i < p.n; i += 256) p.o.v[xo + i] = (p.x.v[xo + i] - mean) * inv * p.w.v[i] + p.b.v[i]; +} diff --git a/src/vulkan/shaders/vit_rope.comp b/src/vulkan/shaders/vit_rope.comp new file mode 100644 index 00000000..bf4a107c --- /dev/null +++ b/src/vulkan/shaders/vit_rope.comp @@ -0,0 +1,23 @@ +#version 460 +layout(local_size_x = 256) in; +#include "common.glsl" +layout(push_constant) uniform P { F32 x; uint nh; uint hd; uint m; uint mx; float ts; } p; + +// Qwen3-VL vision RoPE (ops::rope_vision) of the heads of token t = workgroup, x [n][nh][hd], tokens in 2x2 merge-block +// order (token t is patch (w2 m + dx, h2 m + dy), mx blocks a row). Pairs (i, i + hd/2); the first hd/4 turn by the +// row, the rest by the column, each section with its own exponent. ts = base^(-2 / (hd / 2)) from the host. +void main() { + uint t = gl_WorkGroupID.x, half_ = p.hd / 2, sec = half_ / 2; + uint dx = t % p.m, dy = (t / p.m) % p.m, blk = t / (p.m * p.m); + uint px = (blk % p.mx) * p.m + dx, py = (blk / p.mx) * p.m + dy; + uint xo = t * p.nh * p.hd; + for (uint j = gl_LocalInvocationID.x; j < p.nh * half_; j += 256) { + uint h = j / half_, i = j % half_; + float sn, cs; + rope_cs(double(i < sec ? py : px), double(p.ts), i < sec ? i : i - sec, sn, cs); + uint r = xo + h * p.hd + i; + float a = p.x.v[r], b = p.x.v[r + half_]; + p.x.v[r] = a * cs - b * sn; + p.x.v[r + half_] = a * sn + b * cs; + } +} diff --git a/src/vulkan/spv/argmax_rows.spv b/src/vulkan/spv/argmax_rows.spv index e17cd6dd..787627bc 100644 Binary files a/src/vulkan/spv/argmax_rows.spv and b/src/vulkan/spv/argmax_rows.spv differ diff --git a/src/vulkan/spv/attn_decode.spv b/src/vulkan/spv/attn_decode.spv index 53f1f45a..f79047ef 100644 Binary files a/src/vulkan/spv/attn_decode.spv and b/src/vulkan/spv/attn_decode.spv differ diff --git a/src/vulkan/spv/attn_decode_llama.spv b/src/vulkan/spv/attn_decode_llama.spv index 3020de69..3d118fab 100644 Binary files a/src/vulkan/spv/attn_decode_llama.spv and b/src/vulkan/spv/attn_decode_llama.spv differ diff --git a/src/vulkan/spv/attn_merge.spv b/src/vulkan/spv/attn_merge.spv index bd78efc9..307d931b 100644 Binary files a/src/vulkan/spv/attn_merge.spv and b/src/vulkan/spv/attn_merge.spv differ diff --git a/src/vulkan/spv/attn_prefill_128.spv b/src/vulkan/spv/attn_prefill_128.spv index 15bc96fb..98cf20e5 100644 Binary files a/src/vulkan/spv/attn_prefill_128.spv and b/src/vulkan/spv/attn_prefill_128.spv differ diff --git a/src/vulkan/spv/attn_prefill_256.spv b/src/vulkan/spv/attn_prefill_256.spv index 039fff62..cef34255 100644 Binary files a/src/vulkan/spv/attn_prefill_256.spv and b/src/vulkan/spv/attn_prefill_256.spv differ diff --git a/src/vulkan/spv/attn_prefill_64.spv b/src/vulkan/spv/attn_prefill_64.spv index 399ed412..3c9b86ab 100644 Binary files a/src/vulkan/spv/attn_prefill_64.spv and b/src/vulkan/spv/attn_prefill_64.spv differ diff --git a/src/vulkan/spv/attn_prefill_dp.spv b/src/vulkan/spv/attn_prefill_dp.spv index 6f99d0a1..51eee38e 100644 Binary files a/src/vulkan/spv/attn_prefill_dp.spv and b/src/vulkan/spv/attn_prefill_dp.spv differ diff --git a/src/vulkan/spv/attn_prefill_llama.spv b/src/vulkan/spv/attn_prefill_llama.spv index a1fb9b6d..b15307f4 100644 Binary files a/src/vulkan/spv/attn_prefill_llama.spv and b/src/vulkan/spv/attn_prefill_llama.spv differ diff --git a/src/vulkan/spv/attn_prefill_tile.spv b/src/vulkan/spv/attn_prefill_tile.spv index dcc6efb1..d5bf8bdc 100644 Binary files a/src/vulkan/spv/attn_prefill_tile.spv and b/src/vulkan/spv/attn_prefill_tile.spv differ diff --git a/src/vulkan/spv/attn_sel.spv b/src/vulkan/spv/attn_sel.spv new file mode 100644 index 00000000..ce57e2fa Binary files /dev/null and b/src/vulkan/spv/attn_sel.spv differ diff --git a/src/vulkan/spv/conv_seq.spv b/src/vulkan/spv/conv_seq.spv index 692f646d..87b36333 100644 Binary files a/src/vulkan/spv/conv_seq.spv and b/src/vulkan/spv/conv_seq.spv differ diff --git a/src/vulkan/spv/conv_silu.spv b/src/vulkan/spv/conv_silu.spv index 0976bf9a..276c83da 100644 Binary files a/src/vulkan/spv/conv_silu.spv and b/src/vulkan/spv/conv_silu.spv differ diff --git a/src/vulkan/spv/conv_state.spv b/src/vulkan/spv/conv_state.spv index 75ea35f9..e617b1b5 100644 Binary files a/src/vulkan/spv/conv_state.spv and b/src/vulkan/spv/conv_state.spv differ diff --git a/src/vulkan/spv/deltanet.spv b/src/vulkan/spv/deltanet.spv index fc832a36..5c0e393e 100644 Binary files a/src/vulkan/spv/deltanet.spv and b/src/vulkan/spv/deltanet.spv differ diff --git a/src/vulkan/spv/dequant.spv b/src/vulkan/spv/dequant.spv index 2b0cbe09..dcbec9fe 100644 Binary files a/src/vulkan/spv/dequant.spv and b/src/vulkan/spv/dequant.spv differ diff --git a/src/vulkan/spv/dflash2_conv.spv b/src/vulkan/spv/dflash2_conv.spv index aba0c0d7..798067fe 100644 Binary files a/src/vulkan/spv/dflash2_conv.spv and b/src/vulkan/spv/dflash2_conv.spv differ diff --git a/src/vulkan/spv/gemm_f.spv b/src/vulkan/spv/gemm_f.spv index c5c0ca63..5b07f1cf 100644 Binary files a/src/vulkan/spv/gemm_f.spv and b/src/vulkan/spv/gemm_f.spv differ diff --git a/src/vulkan/spv/gemm_f_dp.spv b/src/vulkan/spv/gemm_f_dp.spv index 06f72f16..28a66c13 100644 Binary files a/src/vulkan/spv/gemm_f_dp.spv and b/src/vulkan/spv/gemm_f_dp.spv differ diff --git a/src/vulkan/spv/gemm_fs.spv b/src/vulkan/spv/gemm_fs.spv index 3ff3279c..7ded305c 100644 Binary files a/src/vulkan/spv/gemm_fs.spv and b/src/vulkan/spv/gemm_fs.spv differ diff --git a/src/vulkan/spv/gemm_red.spv b/src/vulkan/spv/gemm_red.spv new file mode 100644 index 00000000..3ca1e75b Binary files /dev/null and b/src/vulkan/spv/gemm_red.spv differ diff --git a/src/vulkan/spv/gemmi.spv b/src/vulkan/spv/gemmi.spv index 744fc86e..c8b3174f 100644 Binary files a/src/vulkan/spv/gemmi.spv and b/src/vulkan/spv/gemmi.spv differ diff --git a/src/vulkan/spv/gemmi_16.spv b/src/vulkan/spv/gemmi_16.spv index 698dc89d..8816357e 100644 Binary files a/src/vulkan/spv/gemmi_16.spv and b/src/vulkan/spv/gemmi_16.spv differ diff --git a/src/vulkan/spv/gemmi_dp.spv b/src/vulkan/spv/gemmi_dp.spv index 80a5e111..76fce5bf 100644 Binary files a/src/vulkan/spv/gemmi_dp.spv and b/src/vulkan/spv/gemmi_dp.spv differ diff --git a/src/vulkan/spv/gemmi_s.spv b/src/vulkan/spv/gemmi_s.spv index d9342d26..3ad6bf18 100644 Binary files a/src/vulkan/spv/gemmi_s.spv and b/src/vulkan/spv/gemmi_s.spv differ diff --git a/src/vulkan/spv/gemmi_s2.spv b/src/vulkan/spv/gemmi_s2.spv new file mode 100644 index 00000000..f6863bf6 Binary files /dev/null and b/src/vulkan/spv/gemmi_s2.spv differ diff --git a/src/vulkan/spv/gemmi_s2_16.spv b/src/vulkan/spv/gemmi_s2_16.spv new file mode 100644 index 00000000..68e0ec65 Binary files /dev/null and b/src/vulkan/spv/gemmi_s2_16.spv differ diff --git a/src/vulkan/spv/gemmi_s_16.spv b/src/vulkan/spv/gemmi_s_16.spv index 74d2f785..b1a9edfd 100644 Binary files a/src/vulkan/spv/gemmi_s_16.spv and b/src/vulkan/spv/gemmi_s_16.spv differ diff --git a/src/vulkan/spv/gemv_f.spv b/src/vulkan/spv/gemv_f.spv index 1b2328fd..4bcd94cd 100644 Binary files a/src/vulkan/spv/gemv_f.spv and b/src/vulkan/spv/gemv_f.spv differ diff --git a/src/vulkan/spv/gemv_q.spv b/src/vulkan/spv/gemv_q.spv index 65df9b41..3f30f97d 100644 Binary files a/src/vulkan/spv/gemv_q.spv and b/src/vulkan/spv/gemv_q.spv differ diff --git a/src/vulkan/spv/hadamard.spv b/src/vulkan/spv/hadamard.spv index c6acf809..4b700b2a 100644 Binary files a/src/vulkan/spv/hadamard.spv and b/src/vulkan/spv/hadamard.spv differ diff --git a/src/vulkan/spv/hc_mix.spv b/src/vulkan/spv/hc_mix.spv index 3960e8bd..187af483 100644 Binary files a/src/vulkan/spv/hc_mix.spv and b/src/vulkan/spv/hc_mix.spv differ diff --git a/src/vulkan/spv/hc_silu.spv b/src/vulkan/spv/hc_silu.spv index 437cbd70..edd110dc 100644 Binary files a/src/vulkan/spv/hc_silu.spv and b/src/vulkan/spv/hc_silu.spv differ diff --git a/src/vulkan/spv/hc_write.spv b/src/vulkan/spv/hc_write.spv index 1efcf675..32d1c8d6 100644 Binary files a/src/vulkan/spv/hc_write.spv and b/src/vulkan/spv/hc_write.spv differ diff --git a/src/vulkan/spv/ink_attn.spv b/src/vulkan/spv/ink_attn.spv index 087202f9..35a2face 100644 Binary files a/src/vulkan/spv/ink_attn.spv and b/src/vulkan/spv/ink_attn.spv differ diff --git a/src/vulkan/spv/ink_attn_merge.spv b/src/vulkan/spv/ink_attn_merge.spv index 3f9c2c6e..53da02a9 100644 Binary files a/src/vulkan/spv/ink_attn_merge.spv and b/src/vulkan/spv/ink_attn_merge.spv differ diff --git a/src/vulkan/spv/ink_attn_prefill.spv b/src/vulkan/spv/ink_attn_prefill.spv index 170f0a6c..43e55a99 100644 Binary files a/src/vulkan/spv/ink_attn_prefill.spv and b/src/vulkan/spv/ink_attn_prefill.spv differ diff --git a/src/vulkan/spv/ink_clip.spv b/src/vulkan/spv/ink_clip.spv index 56511640..854c8c86 100644 Binary files a/src/vulkan/spv/ink_clip.spv and b/src/vulkan/spv/ink_clip.spv differ diff --git a/src/vulkan/spv/ink_conv.spv b/src/vulkan/spv/ink_conv.spv index 48fc3d72..c99398d2 100644 Binary files a/src/vulkan/spv/ink_conv.spv and b/src/vulkan/spv/ink_conv.spv differ diff --git a/src/vulkan/spv/ink_conv_batch.spv b/src/vulkan/spv/ink_conv_batch.spv index ef88c953..a502d023 100644 Binary files a/src/vulkan/spv/ink_conv_batch.spv and b/src/vulkan/spv/ink_conv_batch.spv differ diff --git a/src/vulkan/spv/ink_ctrl_gate.spv b/src/vulkan/spv/ink_ctrl_gate.spv index 7b039b01..bcc197c8 100644 Binary files a/src/vulkan/spv/ink_ctrl_gate.spv and b/src/vulkan/spv/ink_ctrl_gate.spv differ diff --git a/src/vulkan/spv/ink_ctrl_out.spv b/src/vulkan/spv/ink_ctrl_out.spv index f89548ef..eb8f3261 100644 Binary files a/src/vulkan/spv/ink_ctrl_out.spv and b/src/vulkan/spv/ink_ctrl_out.spv differ diff --git a/src/vulkan/spv/ink_ffn_sum.spv b/src/vulkan/spv/ink_ffn_sum.spv index 15833e33..0586e9b3 100644 Binary files a/src/vulkan/spv/ink_ffn_sum.spv and b/src/vulkan/spv/ink_ffn_sum.spv differ diff --git a/src/vulkan/spv/ink_mix.spv b/src/vulkan/spv/ink_mix.spv index 07cda7da..e51df710 100644 Binary files a/src/vulkan/spv/ink_mix.spv and b/src/vulkan/spv/ink_mix.spv differ diff --git a/src/vulkan/spv/ink_route.spv b/src/vulkan/spv/ink_route.spv index 4a1082a6..ca428854 100644 Binary files a/src/vulkan/spv/ink_route.spv and b/src/vulkan/spv/ink_route.spv differ diff --git a/src/vulkan/spv/kv_store.spv b/src/vulkan/spv/kv_store.spv index e9b21cee..daf0de50 100644 Binary files a/src/vulkan/spv/kv_store.spv and b/src/vulkan/spv/kv_store.spv differ diff --git a/src/vulkan/spv/l2_norm.spv b/src/vulkan/spv/l2_norm.spv index d24fb723..2dcf3c2a 100644 Binary files a/src/vulkan/spv/l2_norm.spv and b/src/vulkan/spv/l2_norm.spv differ diff --git a/src/vulkan/spv/moe_combine.spv b/src/vulkan/spv/moe_combine.spv index a88b03a3..3f409aa8 100644 Binary files a/src/vulkan/spv/moe_combine.spv and b/src/vulkan/spv/moe_combine.spv differ diff --git a/src/vulkan/spv/moe_combine_seq.spv b/src/vulkan/spv/moe_combine_seq.spv index 5049671e..9f7f7d8f 100644 Binary files a/src/vulkan/spv/moe_combine_seq.spv and b/src/vulkan/spv/moe_combine_seq.spv differ diff --git a/src/vulkan/spv/moe_down_combine.spv b/src/vulkan/spv/moe_down_combine.spv index 2eebf930..2b8c0e6d 100644 Binary files a/src/vulkan/spv/moe_down_combine.spv and b/src/vulkan/spv/moe_down_combine.spv differ diff --git a/src/vulkan/spv/moe_gemv_f.spv b/src/vulkan/spv/moe_gemv_f.spv index 341a0aac..b86d7e88 100644 Binary files a/src/vulkan/spv/moe_gemv_f.spv and b/src/vulkan/spv/moe_gemv_f.spv differ diff --git a/src/vulkan/spv/moe_gemv_q.spv b/src/vulkan/spv/moe_gemv_q.spv index 03d30fc2..108963a3 100644 Binary files a/src/vulkan/spv/moe_gemv_q.spv and b/src/vulkan/spv/moe_gemv_q.spv differ diff --git a/src/vulkan/spv/moe_route.spv b/src/vulkan/spv/moe_route.spv index 904ebc70..c560cea6 100644 Binary files a/src/vulkan/spv/moe_route.spv and b/src/vulkan/spv/moe_route.spv differ diff --git a/src/vulkan/spv/norm_gate.spv b/src/vulkan/spv/norm_gate.spv index bdce6306..5c69fc9f 100644 Binary files a/src/vulkan/spv/norm_gate.spv and b/src/vulkan/spv/norm_gate.spv differ diff --git a/src/vulkan/spv/ple_conv.spv b/src/vulkan/spv/ple_conv.spv index b80ce58a..f870d4bb 100644 Binary files a/src/vulkan/spv/ple_conv.spv and b/src/vulkan/spv/ple_conv.spv differ diff --git a/src/vulkan/spv/ple_gate.spv b/src/vulkan/spv/ple_gate.spv index c7cb065d..991cf81c 100644 Binary files a/src/vulkan/spv/ple_gate.spv and b/src/vulkan/spv/ple_gate.spv differ diff --git a/src/vulkan/spv/qsa_pool.spv b/src/vulkan/spv/qsa_pool.spv index 227b6f7f..807caa99 100644 Binary files a/src/vulkan/spv/qsa_pool.spv and b/src/vulkan/spv/qsa_pool.spv differ diff --git a/src/vulkan/spv/qsa_score.spv b/src/vulkan/spv/qsa_score.spv index feb51284..bbc667ae 100644 Binary files a/src/vulkan/spv/qsa_score.spv and b/src/vulkan/spv/qsa_score.spv differ diff --git a/src/vulkan/spv/qsa_select.spv b/src/vulkan/spv/qsa_select.spv index 7b047745..13bafcea 100644 Binary files a/src/vulkan/spv/qsa_select.spv and b/src/vulkan/spv/qsa_select.spv differ diff --git a/src/vulkan/spv/quant_q8.spv b/src/vulkan/spv/quant_q8.spv index 76cc59b5..e1016811 100644 Binary files a/src/vulkan/spv/quant_q8.spv and b/src/vulkan/spv/quant_q8.spv differ diff --git a/src/vulkan/spv/quant_xq.spv b/src/vulkan/spv/quant_xq.spv index e9f9afec..f8947a66 100644 Binary files a/src/vulkan/spv/quant_xq.spv and b/src/vulkan/spv/quant_xq.spv differ diff --git a/src/vulkan/spv/rms_norm.spv b/src/vulkan/spv/rms_norm.spv index 5bbd45b9..1836ab51 100644 Binary files a/src/vulkan/spv/rms_norm.spv and b/src/vulkan/spv/rms_norm.spv differ diff --git a/src/vulkan/spv/rope_neox.spv b/src/vulkan/spv/rope_neox.spv index bde9d10c..9d839c85 100644 Binary files a/src/vulkan/spv/rope_neox.spv and b/src/vulkan/spv/rope_neox.spv differ diff --git a/src/vulkan/spv/router_topk.spv b/src/vulkan/spv/router_topk.spv index a000dbeb..0ca2dc10 100644 Binary files a/src/vulkan/spv/router_topk.spv and b/src/vulkan/spv/router_topk.spv differ diff --git a/src/vulkan/spv/situ.spv b/src/vulkan/spv/situ.spv index 95356f1f..61b0d2f5 100644 Binary files a/src/vulkan/spv/situ.spv and b/src/vulkan/spv/situ.spv differ diff --git a/src/vulkan/spv/situ_q.spv b/src/vulkan/spv/situ_q.spv index 67c959df..76104469 100644 Binary files a/src/vulkan/spv/situ_q.spv and b/src/vulkan/spv/situ_q.spv differ diff --git a/src/vulkan/spv/softcap.spv b/src/vulkan/spv/softcap.spv index bc4b35aa..21ad9e9d 100644 Binary files a/src/vulkan/spv/softcap.spv and b/src/vulkan/spv/softcap.spv differ diff --git a/src/vulkan/spv/ssm_gates.spv b/src/vulkan/spv/ssm_gates.spv index 4633a730..e9e94973 100644 Binary files a/src/vulkan/spv/ssm_gates.spv and b/src/vulkan/spv/ssm_gates.spv differ diff --git a/src/vulkan/spv/swiglu.spv b/src/vulkan/spv/swiglu.spv index 20b5de47..97a9949b 100644 Binary files a/src/vulkan/spv/swiglu.spv and b/src/vulkan/spv/swiglu.spv differ diff --git a/src/vulkan/spv/swiglu_clamp.spv b/src/vulkan/spv/swiglu_clamp.spv new file mode 100644 index 00000000..bd7eeaaf Binary files /dev/null and b/src/vulkan/spv/swiglu_clamp.spv differ diff --git a/src/vulkan/spv/vit_attn.spv b/src/vulkan/spv/vit_attn.spv new file mode 100644 index 00000000..fce978f8 Binary files /dev/null and b/src/vulkan/spv/vit_attn.spv differ diff --git a/src/vulkan/spv/vit_attn_cm.spv b/src/vulkan/spv/vit_attn_cm.spv new file mode 100644 index 00000000..560b0c17 Binary files /dev/null and b/src/vulkan/spv/vit_attn_cm.spv differ diff --git a/src/vulkan/spv/vit_bias.spv b/src/vulkan/spv/vit_bias.spv new file mode 100644 index 00000000..71633d6e Binary files /dev/null and b/src/vulkan/spv/vit_bias.spv differ diff --git a/src/vulkan/spv/vit_norm.spv b/src/vulkan/spv/vit_norm.spv new file mode 100644 index 00000000..1b3b23bf Binary files /dev/null and b/src/vulkan/spv/vit_norm.spv differ diff --git a/src/vulkan/spv/vit_rope.spv b/src/vulkan/spv/vit_rope.spv new file mode 100644 index 00000000..b9b9155d Binary files /dev/null and b/src/vulkan/spv/vit_rope.spv differ diff --git a/src/vulkan/spv_smem.rs b/src/vulkan/spv_smem.rs index fee5843f..8633b353 100644 --- a/src/vulkan/spv_smem.rs +++ b/src/vulkan/spv_smem.rs @@ -251,11 +251,12 @@ impl Module { } } - /// Workgroup bytes the module needs with the pipeline's `spec` (constant ids 0 .. n-1) and constant 15 = `kv_mode`. - fn shared_bytes(&self, kernel: &str, spec: &[u32], kv_mode: u32) -> Result { - let mut map = HashMap::with_capacity(spec.len() + 1); + /// Workgroup bytes the module needs with the pipeline's `spec` (ids 0 .. n-1) and the split K/V modes. + fn shared_bytes_modes(&self, kernel: &str, spec: &[u32], kv_k: u32, kv_v: u32) -> Result { + let mut map = HashMap::with_capacity(spec.len() + 2); for (i, &v) in spec.iter().enumerate() { map.insert(i as u32, v); } - map.insert(15, kv_mode); // as Vk::pipeline: KV_MODE, common.glsl + map.insert(15, kv_k); // as Vk::pipeline: KV_MODE and VKV_MODE, common.glsl + map.insert(16, kv_v); let mut total = 0u64; for &ty in &self.workgroup { let (size, align) = self.layout(ty, &map).with_context(|| format!("kernel {kernel}"))?; @@ -270,8 +271,13 @@ impl Module { fn round_up(v: u64, a: u64) -> u64 { v.div_ceil(a.max(1)) * a.max(1) } /// Bytes of `Workgroup` shared memory kernel `kernel` needs with specialization constants `spec` (ids 0 .. n-1, and -/// constant 15 = `kv_mode`), computed from the committed SPIR-V in `src/vulkan/spv/`. No GPU and no pipeline. +/// constant 15 = K mode and 16 = V mode), computed from the committed SPIR-V in `src/vulkan/spv/`. No GPU and no pipeline. pub fn shared_bytes(kernel: &str, spec: &[u32], kv_mode: u32) -> Result { + shared_bytes_split(kernel, spec, kv_mode, kv_mode) +} + +/// `shared_bytes` with independent K and V cache modes (specialization constants 15 and 16). +pub fn shared_bytes_split(kernel: &str, spec: &[u32], kv_k: u32, kv_v: u32) -> Result { let (name, code) = super::SPV.iter().find(|s| s.0 == kernel).map(|s| (s.0, s.1)) .with_context(|| format!("no Vulkan kernel {kernel}"))?; // Parsed modules are immutable and reused: pipelines are created once per specialization, but a preflight @@ -287,13 +293,13 @@ pub fn shared_bytes(kernel: &str, spec: &[u32], kv_mode: u32) -> Result { m } }; - m.shared_bytes(name, spec, kv_mode) + m.shared_bytes_modes(name, spec, kv_k, kv_v) } /// `shared_bytes`, refusing when it exceeds `limit`: the driver accepts such a pipeline and faults at dispatch /// (`Xid 13 SKEDCHECK18_L1_CONFIG_TOO_SMALL` on Volta). Returns the size when it fits. -pub fn check_shared_memory(kernel: &str, spec: &[u32], kv_mode: u32, limit: u32) -> Result { - let bytes = shared_bytes(kernel, spec, kv_mode)?; +pub fn check_shared_memory(kernel: &str, spec: &[u32], kv_k: u32, kv_v: u32, limit: u32) -> Result { + let bytes = shared_bytes_split(kernel, spec, kv_k, kv_v)?; ensure!(bytes <= limit, "vulkan: kernel {kernel} with specialization [[{}]] needs {bytes} bytes of shared memory; \ this device allows {limit} (maxComputeSharedMemorySize). If the card really has more (the AMD Windows driver reports 32768 on a 9070 XT), \ set STRATA_VK_SMEM_LIMIT=49152; no kernel needs more", spec.iter().map(u32::to_string).collect::>().join(", ")); @@ -317,11 +323,11 @@ mod tests { #[test] fn shared_memory_refusal_names_the_kernel_spec_and_both_sizes() { - let e = check_shared_memory("gemmi_dp", &[0, 10, 84, 0, 0], 0, 40960).unwrap_err().to_string(); + let e = check_shared_memory("gemmi_dp", &[0, 10, 84, 0, 0], 0, 0, 40960).unwrap_err().to_string(); for want in ["gemmi_dp", "[0, 10, 84, 0, 0]", "49152", "40960", "maxComputeSharedMemorySize"] { assert!(e.contains(want), "{e:?} does not contain {want:?}"); } - assert_eq!(check_shared_memory("gemmi_dp", &[0, 10, 84, 0, 0], 0, 49152).unwrap(), 49152); + assert_eq!(check_shared_memory("gemmi_dp", &[0, 10, 84, 0, 0], 0, 0, 49152).unwrap(), 49152); } /// Every weight kernel the preflight names has a computable Workgroup size for every GPU weight type: a shader or @@ -364,4 +370,15 @@ mod tests { assert!(worst_v100.0 <= 49152, "{} needs {} bytes of Workgroup memory with cooperative matrices off", worst_v100.1, worst_v100.0); } + + /// PR 120: without TurboQuant the prompt attention fits NVIDIA's 48 KB for every other KV type. + #[test] + fn attn_prefill_non_turbo_fits_48kb() { + for kernel in ["attn_prefill_64", "attn_prefill_128", "attn_prefill_256"] { + for mode in 0..=3u32 { + let bytes = shared_bytes_split(kernel, &[], mode, mode).unwrap(); + assert!(bytes <= 49152, "{kernel} with kv_mode={mode} needs {bytes} bytes (> 49152)"); + } + } + } } diff --git a/src/web/index.html b/src/web/index.html index aa836c79..8d0f340d 100644 --- a/src/web/index.html +++ b/src/web/index.html @@ -5,6 +5,8 @@ RustingStrata + +